momentic 2.10.1 → 2.10.2
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/bin/cli.js
CHANGED
|
@@ -38,7 +38,7 @@ ${JSON.stringify(t)}`);let r=[];if(!n.skipIntermediateEntries)for(let o=e.length
|
|
|
38
38
|
`)}catch(i){throw new Error(`Could not read test file ${t}: ${i}`)}let o;try{o=Wo.parse(r)}catch(i){throw new Error(`Could not parse test file ${t} as YAML: ${i}`)}return ut.parse(o)}function to(n,e,t){let r=t.project.rootDir,o;try{o=pn.readFileSync(n,"utf-8")}catch(a){throw e.error({err:a,projectRoot:r},a.message),new Error(a.message)}let i=Wo.parse(o);if(!i.steps||!Array.isArray(i.steps))throw new Error(`Test ${n} is missing steps`);return i}async function ga(n,e,t){let r=to(n,e,t),o;try{o=Xt.parse(r)}catch(a){throw new Error(`Test ${n} is missing metadata or has invalid metadata: ${a}`)}let{resolvedTest:i}=await uS({rawSteps:{steps:r.steps,beforeSteps:r.beforeSteps,afterSteps:r.afterSteps},metadata:o,logger:e,callbacks:{onFetchModule:async({id:a,logger:s})=>{let l=t.modules[a]?.fullFilePath;if(l)return Kn(l,s)}}});return i}import bI from"@dotenvx/dotenvx";import wI from"fs";import TS from"path";function xS(n,e){return(n.config.environments??[]).map(t=>fa(t.name,n,e))}function ES(n){return n.includes("${")?n.replace(/\$\{([^}]+)\}/g,(e,t)=>{let[r,o]=t.split(/:-|-/,2),i=process.env[r];return t.includes(":-")?i&&i!==""?i:o||"":t.includes("-")?i!==void 0?i:o||"":i||""}):n}function fa(n,e,t){let r=(e.config.environments??[]).find(a=>a.name===n);if(!r)throw new Error(`Environment ${n} not found in local project configuration file`);let o={[Qe]:ES(r.baseUrl)};if(r.envVariables){let a={};for(let[s,l]of Object.entries(r.envVariables))if(typeof l=="string"){let c=ES(l);c&&(a[s]=c)}else{let c=l.fromFile,d;try{d=wI.readFileSync(TS.resolve(e.rootDir,c),"utf-8")}catch(p){throw new Error(`Failed to read environment variable '${s}' from file '${c}': ${p}`)}if(l.json)try{a[s]=JSON.parse(d)}catch(p){throw new Error(`Failed to parse environment variable '${s}' from file '${c}' as JSON: ${p}`)}else a[s]=d}Object.keys(a).length>0&&y.debug(a,"Set environment variables with interpolation from project configuration"),Object.assign(o,a)}if(r.envFile){let a={},s=bI.config({path:TS.resolve(e.rootDir,r.envFile),processEnv:a,logLevel:"error",quiet:!0});if(s.error)throw new Error(`Failed to load .env file: ${s.error.message}`);t.debug(a,"Set environment variables from .env file"),Object.assign(o,a)}return r.inheritFromShell&&(t.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:n,variables:o,browser:r.browser}}import{existsSync as JP,readFileSync as QP,readdirSync as ZP,writeFileSync as eL}from"fs";var WS=xE(FS(),1);var ya=n=>{if(typeof n!="string")throw new TypeError("invalid pattern");if(n.length>65536)throw new TypeError("pattern is too long")};var II={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},ba=n=>n.replace(/[[\]\\-]/g,"\\$&"),PI=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),US=n=>n.join(""),BS=(n,e)=>{let t=e;if(n.charAt(t)!=="[")throw new Error("not in a brace expression");let r=[],o=[],i=t+1,a=!1,s=!1,l=!1,c=!1,d=t,p="";e:for(;i<n.length;){let g=n.charAt(i);if((g==="!"||g==="^")&&i===t+1){c=!0,i++;continue}if(g==="]"&&a&&!l){d=i+1;break}if(a=!0,g==="\\"&&!l){l=!0,i++;continue}if(g==="["&&!l){for(let[f,[S,b,w]]of Object.entries(II))if(n.startsWith(f,i)){if(p)return["$.",!1,n.length-t,!0];i+=f.length,w?o.push(S):r.push(S),s=s||b;continue e}}if(l=!1,p){g>p?r.push(ba(p)+"-"+ba(g)):g===p&&r.push(ba(g)),p="",i++;continue}if(n.startsWith("-]",i+1)){r.push(ba(g+"-")),i+=2;continue}if(n.startsWith("-",i+1)){p=g,i+=2;continue}r.push(ba(g)),i++}if(d<i)return["",!1,0,!1];if(!r.length&&!o.length)return["$.",!1,n.length-t,!0];if(o.length===0&&r.length===1&&/^\\?.$/.test(r[0])&&!c){let g=r[0].length===2?r[0].slice(-1):r[0];return[PI(g),!1,d-t,!1]}let u="["+(c?"^":"")+US(r)+"]",m="["+(c?"":"^")+US(o)+"]";return[r.length&&o.length?"("+u+"|"+m+")":r.length?u:m,s,d-t,!0]};var un=(n,{windowsPathsNoEscape:e=!1}={})=>e?n.replace(/\[([^\/\\])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var LI=new Set(["!","?","+","*","@"]),zS=n=>LI.has(n),OI="(?!(?:^|/)\\.\\.?(?:$|/))",dl="(?!\\.)",MI=new Set(["[","."]),NI=new Set(["..","."]),kI=new Set("().*{}+?[]^$\\!"),_I=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),tp="[^/]",HS=tp+"*?",jS=tp+"+?",Vo=class n{type;#e;#t;#i=!1;#r=[];#a;#w;#c;#p=!1;#s;#l;#o=!1;constructor(e,t,r={}){this.type=e,e&&(this.#t=!0),this.#a=t,this.#e=this.#a?this.#a.#e:this,this.#s=this.#e===this?r:this.#e.#s,this.#c=this.#e===this?[]:this.#e.#c,e==="!"&&!this.#e.#p&&this.#c.push(this),this.#w=this.#a?this.#a.#r.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#r)if(typeof e!="string"&&(e.type||e.hasMagic))return this.#t=!0;return this.#t}toString(){return this.#l!==void 0?this.#l:this.type?this.#l=this.type+"("+this.#r.map(e=>String(e)).join("|")+")":this.#l=this.#r.map(e=>String(e)).join("")}#f(){if(this!==this.#e)throw new Error("should only call on root");if(this.#p)return this;this.toString(),this.#p=!0;let e;for(;e=this.#c.pop();){if(e.type!=="!")continue;let t=e,r=t.#a;for(;r;){for(let o=t.#w+1;!r.type&&o<r.#r.length;o++)for(let i of e.#r){if(typeof i=="string")throw new Error("string part in extglob AST??");i.copyIn(r.#r[o])}t=r,r=t.#a}}return this}push(...e){for(let t of e)if(t!==""){if(typeof t!="string"&&!(t instanceof n&&t.#a===this))throw new Error("invalid part: "+t);this.#r.push(t)}}toJSON(){let e=this.type===null?this.#r.slice().map(t=>typeof t=="string"?t:t.toJSON()):[this.type,...this.#r.map(t=>t.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#p&&this.#a?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#a?.isStart())return!1;if(this.#w===0)return!0;let e=this.#a;for(let t=0;t<this.#w;t++){let r=e.#r[t];if(!(r instanceof n&&r.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#a?.type==="!")return!0;if(!this.#a?.isEnd())return!1;if(!this.type)return this.#a?.isEnd();let e=this.#a?this.#a.#r.length:0;return this.#w===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let t=new n(this.type,e);for(let r of this.#r)t.copyIn(r);return t}static#S(e,t,r,o){let i=!1,a=!1,s=-1,l=!1;if(t.type===null){let m=r,h="";for(;m<e.length;){let g=e.charAt(m++);if(i||g==="\\"){i=!i,h+=g;continue}if(a){m===s+1?(g==="^"||g==="!")&&(l=!0):g==="]"&&!(m===s+2&&l)&&(a=!1),h+=g;continue}else if(g==="["){a=!0,s=m,l=!1,h+=g;continue}if(!o.noext&&zS(g)&&e.charAt(m)==="("){t.push(h),h="";let f=new n(g,t);m=n.#S(e,f,m,o),t.push(f);continue}h+=g}return t.push(h),m}let c=r+1,d=new n(null,t),p=[],u="";for(;c<e.length;){let m=e.charAt(c++);if(i||m==="\\"){i=!i,u+=m;continue}if(a){c===s+1?(m==="^"||m==="!")&&(l=!0):m==="]"&&!(c===s+2&&l)&&(a=!1),u+=m;continue}else if(m==="["){a=!0,s=c,l=!1,u+=m;continue}if(zS(m)&&e.charAt(c)==="("){d.push(u),u="";let h=new n(m,d);d.push(h),c=n.#S(e,h,c,o);continue}if(m==="|"){d.push(u),u="",p.push(d),d=new n(null,t);continue}if(m===")")return u===""&&t.#r.length===0&&(t.#o=!0),d.push(u),u="",t.push(...p,d),c;u+=m}return t.type=null,t.#t=void 0,t.#r=[e.substring(r-1)],c}static fromGlob(e,t={}){let r=new n(null,void 0,t);return n.#S(e,r,0,t),r}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,r,o,i]=this.toRegExpSource();if(!(o||this.#t||this.#s.nocase&&!this.#s.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return r;let s=(this.#s.nocase?"i":"")+(i?"u":"");return Object.assign(new RegExp(`^${t}$`,s),{_src:t,_glob:e})}get options(){return this.#s}toRegExpSource(e){let t=e??!!this.#s.dot;if(this.#e===this&&this.#f(),!this.type){let l=this.isStart()&&this.isEnd(),c=this.#r.map(m=>{let[h,g,f,S]=typeof m=="string"?n.#u(m,this.#t,l):m.toRegExpSource(e);return this.#t=this.#t||f,this.#i=this.#i||S,h}).join(""),d="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&NI.has(this.#r[0]))){let h=MI,g=t&&h.has(c.charAt(0))||c.startsWith("\\.")&&h.has(c.charAt(2))||c.startsWith("\\.\\.")&&h.has(c.charAt(4)),f=!t&&!e&&h.has(c.charAt(0));d=g?OI:f?dl:""}let p="";return this.isEnd()&&this.#e.#p&&this.#a?.type==="!"&&(p="(?:$|\\/)"),[d+c+p,un(c),this.#t=!!this.#t,this.#i]}let r=this.type==="*"||this.type==="+",o=this.type==="!"?"(?:(?!(?:":"(?:",i=this.#m(t);if(this.isStart()&&this.isEnd()&&!i&&this.type!=="!"){let l=this.toString();return this.#r=[l],this.type=null,this.#t=void 0,[l,un(this.toString()),!1,!1]}let a=!r||e||t||!dl?"":this.#m(!0);a===i&&(a=""),a&&(i=`(?:${i})(?:${a})*?`);let s="";if(this.type==="!"&&this.#o)s=(this.isStart()&&!t?dl:"")+jS;else{let l=this.type==="!"?"))"+(this.isStart()&&!t&&!e?dl:"")+HS+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&a?")":this.type==="*"&&a?")?":`)${this.type}`;s=o+i+l}return[s,un(i),this.#t=!!this.#t,this.#i]}#m(e){return this.#r.map(t=>{if(typeof t=="string")throw new Error("string type in extglob ast??");let[r,o,i,a]=t.toRegExpSource(e);return this.#i=this.#i||a,r}).filter(t=>!(this.isStart()&&this.isEnd())||!!t).join("|")}static#u(e,t,r=!1){let o=!1,i="",a=!1;for(let s=0;s<e.length;s++){let l=e.charAt(s);if(o){o=!1,i+=(kI.has(l)?"\\":"")+l;continue}if(l==="\\"){s===e.length-1?i+="\\\\":o=!0;continue}if(l==="["){let[c,d,p,u]=BS(e,s);if(p){i+=c,a=a||d,s+=p-1,t=t||u;continue}}if(l==="*"){r&&e==="*"?i+=jS:i+=HS,t=!0;continue}if(l==="?"){i+=tp,t=!0;continue}i+=_I(l)}return[i,un(e),!!t,a]}};var qo=(n,{windowsPathsNoEscape:e=!1}={})=>e?n.replace(/[?*()[\]]/g,"[$&]"):n.replace(/[?*()[\]\\]/g,"\\$&");var xt=(n,e,t={})=>(ya(e),!t.nocomment&&e.charAt(0)==="#"?!1:new _t(e,t).match(n)),DI=/^\*+([^+@!?\*\[\(]*)$/,FI=n=>e=>!e.startsWith(".")&&e.endsWith(n),UI=n=>e=>e.endsWith(n),BI=n=>(n=n.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(n)),zI=n=>(n=n.toLowerCase(),e=>e.toLowerCase().endsWith(n)),HI=/^\*+\.\*+$/,jI=n=>!n.startsWith(".")&&n.includes("."),$I=n=>n!=="."&&n!==".."&&n.includes("."),GI=/^\.\*+$/,WI=n=>n!=="."&&n!==".."&&n.startsWith("."),VI=/^\*+$/,qI=n=>n.length!==0&&!n.startsWith("."),KI=n=>n.length!==0&&n!=="."&&n!=="..",YI=/^\?+([^+@!?\*\[\(]*)?$/,XI=([n,e=""])=>{let t=VS([n]);return e?(e=e.toLowerCase(),r=>t(r)&&r.toLowerCase().endsWith(e)):t},JI=([n,e=""])=>{let t=qS([n]);return e?(e=e.toLowerCase(),r=>t(r)&&r.toLowerCase().endsWith(e)):t},QI=([n,e=""])=>{let t=qS([n]);return e?r=>t(r)&&r.endsWith(e):t},ZI=([n,e=""])=>{let t=VS([n]);return e?r=>t(r)&&r.endsWith(e):t},VS=([n])=>{let e=n.length;return t=>t.length===e&&!t.startsWith(".")},qS=([n])=>{let e=n.length;return t=>t.length===e&&t!=="."&&t!==".."},KS=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",$S={win32:{sep:"\\"},posix:{sep:"/"}},eP=KS==="win32"?$S.win32.sep:$S.posix.sep;xt.sep=eP;var st=Symbol("globstar **");xt.GLOBSTAR=st;var tP="[^/]",nP=tP+"*?",rP="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",oP="(?:(?!(?:\\/|^)\\.).)*?",iP=(n,e={})=>t=>xt(t,n,e);xt.filter=iP;var Zt=(n,e={})=>Object.assign({},n,e),aP=n=>{if(!n||typeof n!="object"||!Object.keys(n).length)return xt;let e=xt;return Object.assign((r,o,i={})=>e(r,o,Zt(n,i)),{Minimatch:class extends e.Minimatch{constructor(o,i={}){super(o,Zt(n,i))}static defaults(o){return e.defaults(Zt(n,o)).Minimatch}},AST:class extends e.AST{constructor(o,i,a={}){super(o,i,Zt(n,a))}static fromGlob(o,i={}){return e.AST.fromGlob(o,Zt(n,i))}},unescape:(r,o={})=>e.unescape(r,Zt(n,o)),escape:(r,o={})=>e.escape(r,Zt(n,o)),filter:(r,o={})=>e.filter(r,Zt(n,o)),defaults:r=>e.defaults(Zt(n,r)),makeRe:(r,o={})=>e.makeRe(r,Zt(n,o)),braceExpand:(r,o={})=>e.braceExpand(r,Zt(n,o)),match:(r,o,i={})=>e.match(r,o,Zt(n,i)),sep:e.sep,GLOBSTAR:st})};xt.defaults=aP;var YS=(n,e={})=>(ya(n),e.nobrace||!/\{(?:(?!\{).)*\}/.test(n)?[n]:(0,WS.default)(n));xt.braceExpand=YS;var sP=(n,e={})=>new _t(n,e).makeRe();xt.makeRe=sP;var lP=(n,e,t={})=>{let r=new _t(e,t);return n=n.filter(o=>r.match(o)),r.options.nonull&&!n.length&&n.push(e),n};xt.match=lP;var GS=/[?*]|[+@!]\(.*?\)|\[|\]/,cP=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),_t=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){ya(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||KS,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!="string")return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...i)=>console.error(...i)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(i=>this.slashSplit(i));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let o=this.globParts.map((i,a,s)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=i[0]===""&&i[1]===""&&(i[2]==="?"||!GS.test(i[2]))&&!GS.test(i[3]),c=/^[a-z]:/i.test(i[0]);if(l)return[...i.slice(0,4),...i.slice(4).map(d=>this.parse(d))];if(c)return[i[0],...i.slice(1).map(d=>this.parse(d))]}return i.map(l=>this.parse(l))});if(this.debug(this.pattern,o),this.set=o.filter(i=>i.indexOf(!1)===-1),this.isWindows)for(let i=0;i<this.set.length;i++){let a=this.set[i];a[0]===""&&a[1]===""&&this.globParts[i][2]==="?"&&typeof a[3]=="string"&&/^[a-z]:$/i.test(a[3])&&(a[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let r=0;r<e.length;r++)for(let o=0;o<e[r].length;o++)e[r][o]==="**"&&(e[r][o]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let r=-1;for(;(r=t.indexOf("**",r+1))!==-1;){let o=r;for(;t[o+1]==="**";)o++;o!==r&&t.splice(r,o-r)}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((r,o)=>{let i=r[r.length-1];return o==="**"&&i==="**"?r:o===".."&&i&&i!==".."&&i!=="."&&i!=="**"?(r.pop(),r):(r.push(o),r)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let o=1;o<e.length-1;o++){let i=e[o];o===1&&i===""&&e[0]===""||(i==="."||i==="")&&(t=!0,e.splice(o,1),o--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=!0,e.pop())}let r=0;for(;(r=e.indexOf("..",r+1))!==-1;){let o=e[r-1];o&&o!=="."&&o!==".."&&o!=="**"&&(t=!0,e.splice(r-1,2),r-=2)}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let r of e){let o=-1;for(;(o=r.indexOf("**",o+1))!==-1;){let a=o;for(;r[a+1]==="**";)a++;a>o&&r.splice(o+1,a-o);let s=r[o+1],l=r[o+2],c=r[o+3];if(s!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;t=!0,r.splice(o,1);let d=r.slice(0);d[o]="**",e.push(d),o--}if(!this.preserveMultipleSlashes){for(let a=1;a<r.length-1;a++){let s=r[a];a===1&&s===""&&r[0]===""||(s==="."||s==="")&&(t=!0,r.splice(a,1),a--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(t=!0,r.pop())}let i=0;for(;(i=r.indexOf("..",i+1))!==-1;){let a=r[i-1];if(a&&a!=="."&&a!==".."&&a!=="**"){t=!0;let l=i===1&&r[i+1]==="**"?["."]:[];r.splice(i-1,2,...l),r.length===0&&r.push(""),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let r=t+1;r<e.length;r++){let o=this.partsMatch(e[t],e[r],!this.preserveMultipleSlashes);if(o){e[t]=[],e[r]=o;break}}return e.filter(t=>t.length)}partsMatch(e,t,r=!1){let o=0,i=0,a=[],s="";for(;o<e.length&&i<t.length;)if(e[o]===t[i])a.push(s==="b"?t[i]:e[o]),o++,i++;else if(r&&e[o]==="**"&&t[i]===e[o+1])a.push(e[o]),o++;else if(r&&t[i]==="**"&&e[o]===t[i+1])a.push(t[i]),i++;else if(e[o]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(s==="b")return!1;s="a",a.push(e[o]),o++,i++}else if(t[i]==="*"&&e[o]&&(this.options.dot||!e[o].startsWith("."))&&e[o]!=="**"){if(s==="a")return!1;s="b",a.push(t[i]),o++,i++}else return!1;return e.length===t.length&&a}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,r=0;for(let o=0;o<e.length&&e.charAt(o)==="!";o++)t=!t,r++;r&&(this.pattern=e.slice(r)),this.negate=t}matchOne(e,t,r=!1){let o=this.options;if(this.isWindows){let g=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),f=!g&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),S=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),b=!S&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),w=f?3:g?0:void 0,T=b?3:S?0:void 0;if(typeof w=="number"&&typeof T=="number"){let[C,E]=[e[w],t[T]];C.toLowerCase()===E.toLowerCase()&&(t[T]=C,T>w?t=t.slice(T):w>T&&(e=e.slice(w)))}}let{optimizationLevel:i=1}=this.options;i>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var a=0,s=0,l=e.length,c=t.length;a<l&&s<c;a++,s++){this.debug("matchOne loop");var d=t[s],p=e[a];if(this.debug(t,d,p),d===!1)return!1;if(d===st){this.debug("GLOBSTAR",[t,d,p]);var u=a,m=s+1;if(m===c){for(this.debug("** at the end");a<l;a++)if(e[a]==="."||e[a]===".."||!o.dot&&e[a].charAt(0)===".")return!1;return!0}for(;u<l;){var h=e[u];if(this.debug(`
|
|
39
39
|
globstar while`,e,u,t,m,h),this.matchOne(e.slice(u),t.slice(m),r))return this.debug("globstar found match!",u,l,h),!0;if(h==="."||h===".."||!o.dot&&h.charAt(0)==="."){this.debug("dot detected!",e,u,t,m);break}this.debug("globstar swallow a segment, and continue"),u++}return!!(r&&(this.debug(`
|
|
40
40
|
>>> no match, partial?`,e,u,t,m),u===l))}let g;if(typeof d=="string"?(g=p===d,this.debug("string match",d,p,g)):(g=d.test(p),this.debug("pattern match",d,p,g)),!g)return!1}if(a===l&&s===c)return!0;if(a===l)return r;if(s===c)return a===l-1&&e[a]==="";throw new Error("wtf?")}braceExpand(){return YS(this.pattern,this.options)}parse(e){ya(e);let t=this.options;if(e==="**")return st;if(e==="")return"";let r,o=null;(r=e.match(VI))?o=t.dot?KI:qI:(r=e.match(DI))?o=(t.nocase?t.dot?zI:BI:t.dot?UI:FI)(r[1]):(r=e.match(YI))?o=(t.nocase?t.dot?JI:XI:t.dot?QI:ZI)(r):(r=e.match(HI))?o=t.dot?$I:jI:(r=e.match(GI))&&(o=WI);let i=Vo.fromGlob(e,this.options).toMMPattern();return o&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:o}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,r=t.noglobstar?nP:t.dot?rP:oP,o=new Set(t.nocase?["i"]:[]),i=e.map(l=>{let c=l.map(d=>{if(d instanceof RegExp)for(let p of d.flags.split(""))o.add(p);return typeof d=="string"?cP(d):d===st?st:d._src});return c.forEach((d,p)=>{let u=c[p+1],m=c[p-1];d!==st||m===st||(m===void 0?u!==void 0&&u!==st?c[p+1]="(?:\\/|"+r+"\\/)?"+u:c[p]=r:u===void 0?c[p-1]=m+"(?:\\/|"+r+")?":u!==st&&(c[p-1]=m+"(?:\\/|\\/"+r+"\\/)"+u,c[p+1]=st))}),c.filter(d=>d!==st).join("/")}).join("|"),[a,s]=e.length>1?["(?:",")"]:["",""];i="^"+a+i+s+"$",this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...o].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(e)?["",...e.split(/\/+/)]:e.split(/\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&t)return!0;let r=this.options;this.isWindows&&(e=e.split("\\").join("/"));let o=this.slashSplit(e);this.debug(this.pattern,"split",o);let i=this.set;this.debug(this.pattern,"set",i);let a=o[o.length-1];if(!a)for(let s=o.length-2;!a&&s>=0;s--)a=o[s];for(let s=0;s<i.length;s++){let l=i[s],c=o;if(r.matchBase&&l.length===1&&(c=[a]),this.matchOne(c,l,t))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(e){return xt.defaults(e).Minimatch}};xt.AST=Vo;xt.Minimatch=_t;xt.escape=qo;xt.unescape=un;import{fileURLToPath as HP}from"node:url";var Ko=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,JS=new Set,np=typeof process=="object"&&process?process:{},QS=(n,e,t,r)=>{typeof np.emitWarning=="function"?np.emitWarning(n,e,t,r):console.error(`[${t}] ${e}: ${n}`)},pl=globalThis.AbortController,XS=globalThis.AbortSignal;if(typeof pl>"u"){XS=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},pl=class{constructor(){e()}signal=new XS;abort(r){if(!this.signal.aborted){this.signal.reason=r,this.signal.aborted=!0;for(let o of this.signal._onabort)o(r);this.signal.onabort?.(r)}}};let n=np.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{n&&(n=!1,QS("AbortController is not defined. If using lru-cache in node 14, load an AbortController polyfill from the `node-abort-controller` package. A minimal polyfill is provided for use by LRUCache.fetch(), but it should not be relied upon in other contexts (eg, passing it to other APIs that use AbortController/AbortSignal might have undesirable effects). You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.","NO_ABORT_CONTROLLER","ENOTSUP",e))}}var dP=n=>!JS.has(n),B4=Symbol("type"),fr=n=>n&&n===Math.floor(n)&&n>0&&isFinite(n),ZS=n=>fr(n)?n<=Math.pow(2,8)?Uint8Array:n<=Math.pow(2,16)?Uint16Array:n<=Math.pow(2,32)?Uint32Array:n<=Number.MAX_SAFE_INTEGER?Yo:null:null,Yo=class extends Array{constructor(e){super(e),this.fill(0)}},rp=class n{heap;length;static#e=!1;static create(e){let t=ZS(e);if(!t)return[];n.#e=!0;let r=new n(e,t);return n.#e=!1,r}constructor(e,t){if(!n.#e)throw new TypeError("instantiate Stack using Stack.create(n)");this.heap=new t(e),this.length=0}push(e){this.heap[this.length++]=e}pop(){return this.heap[--this.length]}},wa=class n{#e;#t;#i;#r;#a;#w;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#p;#s;#l;#o;#f;#S;#m;#u;#E;#g;#x;#C;#b;#v;#T;#h;static unsafeExposeInternals(e){return{starts:e.#C,ttls:e.#b,sizes:e.#x,keyMap:e.#s,keyList:e.#l,valList:e.#o,next:e.#f,prev:e.#S,get head(){return e.#m},get tail(){return e.#u},free:e.#E,isBackgroundFetch:t=>e.#d(t),backgroundFetch:(t,r,o,i)=>e.#U(t,r,o,i),moveToTail:t=>e.#z(t),indexes:t=>e.#A(t),rindexes:t=>e.#I(t),isStale:t=>e.#y(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#p}get size(){return this.#c}get fetchMethod(){return this.#a}get memoMethod(){return this.#w}get dispose(){return this.#i}get disposeAfter(){return this.#r}constructor(e){let{max:t=0,ttl:r,ttlResolution:o=1,ttlAutopurge:i,updateAgeOnGet:a,updateAgeOnHas:s,allowStale:l,dispose:c,disposeAfter:d,noDisposeOnSet:p,noUpdateTTL:u,maxSize:m=0,maxEntrySize:h=0,sizeCalculation:g,fetchMethod:f,memoMethod:S,noDeleteOnFetchRejection:b,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:C,ignoreFetchAbort:E}=e;if(t!==0&&!fr(t))throw new TypeError("max option must be a nonnegative integer");let A=t?ZS(t):Array;if(!A)throw new Error("invalid max value: "+t);if(this.#e=t,this.#t=m,this.maxEntrySize=h||this.#t,this.sizeCalculation=g,this.sizeCalculation){if(!this.#t&&!this.maxEntrySize)throw new TypeError("cannot set sizeCalculation without setting maxSize or maxEntrySize");if(typeof this.sizeCalculation!="function")throw new TypeError("sizeCalculation set to non-function")}if(S!==void 0&&typeof S!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#w=S,f!==void 0&&typeof f!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#a=f,this.#T=!!f,this.#s=new Map,this.#l=new Array(t).fill(void 0),this.#o=new Array(t).fill(void 0),this.#f=new A(t),this.#S=new A(t),this.#m=0,this.#u=0,this.#E=rp.create(t),this.#c=0,this.#p=0,typeof c=="function"&&(this.#i=c),typeof d=="function"?(this.#r=d,this.#g=[]):(this.#r=void 0,this.#g=void 0),this.#v=!!this.#i,this.#h=!!this.#r,this.noDisposeOnSet=!!p,this.noUpdateTTL=!!u,this.noDeleteOnFetchRejection=!!b,this.allowStaleOnFetchRejection=!!T,this.allowStaleOnFetchAbort=!!C,this.ignoreFetchAbort=!!E,this.maxEntrySize!==0){if(this.#t!==0&&!fr(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!fr(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#L()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!a,this.updateAgeOnHas=!!s,this.ttlResolution=fr(o)||o===0?o:1,this.ttlAutopurge=!!i,this.ttl=r||0,this.ttl){if(!fr(this.ttl))throw new TypeError("ttl must be a positive integer if specified");this.#P()}if(this.#e===0&&this.ttl===0&&this.#t===0)throw new TypeError("At least one of max, maxSize, or ttl is required");if(!this.ttlAutopurge&&!this.#e&&!this.#t){let k="LRU_CACHE_UNBOUNDED";dP(k)&&(JS.add(k),QS("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",k,n))}}getRemainingTTL(e){return this.#s.has(e)?1/0:0}#P(){let e=new Yo(this.#e),t=new Yo(this.#e);this.#b=e,this.#C=t,this.#M=(i,a,s=Ko.now())=>{if(t[i]=a!==0?s:0,e[i]=a,a!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#y(i)&&this.#O(this.#l[i],"expire")},a+1);l.unref&&l.unref()}},this.#R=i=>{t[i]=e[i]!==0?Ko.now():0},this.#n=(i,a)=>{if(e[a]){let s=e[a],l=t[a];if(!s||!l)return;i.ttl=s,i.start=l,i.now=r||o();let c=i.now-l;i.remainingTTL=s-c}};let r=0,o=()=>{let i=Ko.now();if(this.ttlResolution>0){r=i;let a=setTimeout(()=>r=0,this.ttlResolution);a.unref&&a.unref()}return i};this.getRemainingTTL=i=>{let a=this.#s.get(i);if(a===void 0)return 0;let s=e[a],l=t[a];if(!s||!l)return 1/0;let c=(r||o())-l;return s-c},this.#y=i=>{let a=t[i],s=e[i];return!!s&&!!a&&(r||o())-a>s}}#R=()=>{};#n=()=>{};#M=()=>{};#y=()=>!1;#L(){let e=new Yo(this.#e);this.#p=0,this.#x=e,this.#N=t=>{this.#p-=e[t],e[t]=0},this.#_=(t,r,o,i)=>{if(this.#d(r))return 0;if(!fr(o))if(i){if(typeof i!="function")throw new TypeError("sizeCalculation must be a function");if(o=i(r,t),!fr(o))throw new TypeError("sizeCalculation return invalid (expect positive integer)")}else throw new TypeError("invalid size value (must be positive integer). When maxSize or maxEntrySize is used, sizeCalculation or size must be set.");return o},this.#k=(t,r,o)=>{if(e[t]=r,this.#t){let i=this.#t-e[t];for(;this.#p>i;)this.#F(!0)}this.#p+=e[t],o&&(o.entrySize=r,o.totalCalculatedSize=this.#p)}}#N=e=>{};#k=(e,t,r)=>{};#_=(e,t,r,o)=>{if(r||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#A({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#u;!(!this.#D(t)||((e||!this.#y(t))&&(yield t),t===this.#m));)t=this.#S[t]}*#I({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#m;!(!this.#D(t)||((e||!this.#y(t))&&(yield t),t===this.#u));)t=this.#f[t]}#D(e){return e!==void 0&&this.#s.get(this.#l[e])===e}*entries(){for(let e of this.#A())this.#o[e]!==void 0&&this.#l[e]!==void 0&&!this.#d(this.#o[e])&&(yield[this.#l[e],this.#o[e]])}*rentries(){for(let e of this.#I())this.#o[e]!==void 0&&this.#l[e]!==void 0&&!this.#d(this.#o[e])&&(yield[this.#l[e],this.#o[e]])}*keys(){for(let e of this.#A()){let t=this.#l[e];t!==void 0&&!this.#d(this.#o[e])&&(yield t)}}*rkeys(){for(let e of this.#I()){let t=this.#l[e];t!==void 0&&!this.#d(this.#o[e])&&(yield t)}}*values(){for(let e of this.#A())this.#o[e]!==void 0&&!this.#d(this.#o[e])&&(yield this.#o[e])}*rvalues(){for(let e of this.#I())this.#o[e]!==void 0&&!this.#d(this.#o[e])&&(yield this.#o[e])}[Symbol.iterator](){return this.entries()}[Symbol.toStringTag]="LRUCache";find(e,t={}){for(let r of this.#A()){let o=this.#o[r],i=this.#d(o)?o.__staleWhileFetching:o;if(i!==void 0&&e(i,this.#l[r],this))return this.get(this.#l[r],t)}}forEach(e,t=this){for(let r of this.#A()){let o=this.#o[r],i=this.#d(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#l[r],this)}}rforEach(e,t=this){for(let r of this.#I()){let o=this.#o[r],i=this.#d(o)?o.__staleWhileFetching:o;i!==void 0&&e.call(t,i,this.#l[r],this)}}purgeStale(){let e=!1;for(let t of this.#I({allowStale:!0}))this.#y(t)&&(this.#O(this.#l[t],"expire"),e=!0);return e}info(e){let t=this.#s.get(e);if(t===void 0)return;let r=this.#o[t],o=this.#d(r)?r.__staleWhileFetching:r;if(o===void 0)return;let i={value:o};if(this.#b&&this.#C){let a=this.#b[t],s=this.#C[t];if(a&&s){let l=a-(Ko.now()-s);i.ttl=l,i.start=Date.now()}}return this.#x&&(i.size=this.#x[t]),i}dump(){let e=[];for(let t of this.#A({allowStale:!0})){let r=this.#l[t],o=this.#o[t],i=this.#d(o)?o.__staleWhileFetching:o;if(i===void 0||r===void 0)continue;let a={value:i};if(this.#b&&this.#C){a.ttl=this.#b[t];let s=Ko.now()-this.#C[t];a.start=Math.floor(Date.now()-s)}this.#x&&(a.size=this.#x[t]),e.unshift([r,a])}return e}load(e){this.clear();for(let[t,r]of e){if(r.start){let o=Date.now()-r.start;r.start=Ko.now()-o}this.set(t,r.value,r)}}set(e,t,r={}){if(t===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:i,noDisposeOnSet:a=this.noDisposeOnSet,sizeCalculation:s=this.sizeCalculation,status:l}=r,{noUpdateTTL:c=this.noUpdateTTL}=r,d=this.#_(e,t,r.size||0,s);if(this.maxEntrySize&&d>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#O(e,"set"),this;let p=this.#c===0?void 0:this.#s.get(e);if(p===void 0)p=this.#c===0?this.#u:this.#E.length!==0?this.#E.pop():this.#c===this.#e?this.#F(!1):this.#c,this.#l[p]=e,this.#o[p]=t,this.#s.set(e,p),this.#f[this.#u]=p,this.#S[p]=this.#u,this.#u=p,this.#c++,this.#k(p,d,l),l&&(l.set="add"),c=!1;else{this.#z(p);let u=this.#o[p];if(t!==u){if(this.#T&&this.#d(u)){u.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:m}=u;m!==void 0&&!a&&(this.#v&&this.#i?.(m,e,"set"),this.#h&&this.#g?.push([m,e,"set"]))}else a||(this.#v&&this.#i?.(u,e,"set"),this.#h&&this.#g?.push([u,e,"set"]));if(this.#N(p),this.#k(p,d,l),this.#o[p]=t,l){l.set="replace";let m=u&&this.#d(u)?u.__staleWhileFetching:u;m!==void 0&&(l.oldValue=m)}}else l&&(l.set="update")}if(o!==0&&!this.#b&&this.#P(),this.#b&&(c||this.#M(p,o,i),l&&this.#n(l,p)),!a&&this.#h&&this.#g){let u=this.#g,m;for(;m=u?.shift();)this.#r?.(...m)}return this}pop(){try{for(;this.#c;){let e=this.#o[this.#m];if(this.#F(!0),this.#d(e)){if(e.__staleWhileFetching)return e.__staleWhileFetching}else if(e!==void 0)return e}}finally{if(this.#h&&this.#g){let e=this.#g,t;for(;t=e?.shift();)this.#r?.(...t)}}}#F(e){let t=this.#m,r=this.#l[t],o=this.#o[t];return this.#T&&this.#d(o)?o.__abortController.abort(new Error("evicted")):(this.#v||this.#h)&&(this.#v&&this.#i?.(o,r,"evict"),this.#h&&this.#g?.push([o,r,"evict"])),this.#N(t),e&&(this.#l[t]=void 0,this.#o[t]=void 0,this.#E.push(t)),this.#c===1?(this.#m=this.#u=0,this.#E.length=0):this.#m=this.#f[t],this.#s.delete(r),this.#c--,t}has(e,t={}){let{updateAgeOnHas:r=this.updateAgeOnHas,status:o}=t,i=this.#s.get(e);if(i!==void 0){let a=this.#o[i];if(this.#d(a)&&a.__staleWhileFetching===void 0)return!1;if(this.#y(i))o&&(o.has="stale",this.#n(o,i));else return r&&this.#R(i),o&&(o.has="hit",this.#n(o,i)),!0}else o&&(o.has="miss");return!1}peek(e,t={}){let{allowStale:r=this.allowStale}=t,o=this.#s.get(e);if(o===void 0||!r&&this.#y(o))return;let i=this.#o[o];return this.#d(i)?i.__staleWhileFetching:i}#U(e,t,r,o){let i=t===void 0?void 0:this.#o[t];if(this.#d(i))return i;let a=new pl,{signal:s}=r;s?.addEventListener("abort",()=>a.abort(s.reason),{signal:a.signal});let l={signal:a.signal,options:r,context:o},c=(g,f=!1)=>{let{aborted:S}=a.signal,b=r.ignoreFetchAbort&&g!==void 0;if(r.status&&(S&&!f?(r.status.fetchAborted=!0,r.status.fetchError=a.signal.reason,b&&(r.status.fetchAbortIgnored=!0)):r.status.fetchResolved=!0),S&&!b&&!f)return p(a.signal.reason);let w=m;return this.#o[t]===m&&(g===void 0?w.__staleWhileFetching?this.#o[t]=w.__staleWhileFetching:this.#O(e,"fetch"):(r.status&&(r.status.fetchUpdated=!0),this.set(e,g,l.options))),g},d=g=>(r.status&&(r.status.fetchRejected=!0,r.status.fetchError=g),p(g)),p=g=>{let{aborted:f}=a.signal,S=f&&r.allowStaleOnFetchAbort,b=S||r.allowStaleOnFetchRejection,w=b||r.noDeleteOnFetchRejection,T=m;if(this.#o[t]===m&&(!w||T.__staleWhileFetching===void 0?this.#O(e,"fetch"):S||(this.#o[t]=T.__staleWhileFetching)),b)return r.status&&T.__staleWhileFetching!==void 0&&(r.status.returnedStale=!0),T.__staleWhileFetching;if(T.__returned===T)throw g},u=(g,f)=>{let S=this.#a?.(e,i,l);S&&S instanceof Promise&&S.then(b=>g(b===void 0?void 0:b),f),a.signal.addEventListener("abort",()=>{(!r.ignoreFetchAbort||r.allowStaleOnFetchAbort)&&(g(void 0),r.allowStaleOnFetchAbort&&(g=b=>c(b,!0)))})};r.status&&(r.status.fetchDispatched=!0);let m=new Promise(u).then(c,d),h=Object.assign(m,{__abortController:a,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,h,{...l.options,status:void 0}),t=this.#s.get(e)):this.#o[t]=h,h}#d(e){if(!this.#T)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof pl}async fetch(e,t={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,ttl:a=this.ttl,noDisposeOnSet:s=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:d=this.noUpdateTTL,noDeleteOnFetchRejection:p=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:u=this.allowStaleOnFetchRejection,ignoreFetchAbort:m=this.ignoreFetchAbort,allowStaleOnFetchAbort:h=this.allowStaleOnFetchAbort,context:g,forceRefresh:f=!1,status:S,signal:b}=t;if(!this.#T)return S&&(S.fetch="get"),this.get(e,{allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:i,status:S});let w={allowStale:r,updateAgeOnGet:o,noDeleteOnStaleGet:i,ttl:a,noDisposeOnSet:s,size:l,sizeCalculation:c,noUpdateTTL:d,noDeleteOnFetchRejection:p,allowStaleOnFetchRejection:u,allowStaleOnFetchAbort:h,ignoreFetchAbort:m,status:S,signal:b},T=this.#s.get(e);if(T===void 0){S&&(S.fetch="miss");let C=this.#U(e,T,w,g);return C.__returned=C}else{let C=this.#o[T];if(this.#d(C)){let $=r&&C.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",$&&(S.returnedStale=!0)),$?C.__staleWhileFetching:C.__returned=C}let E=this.#y(T);if(!f&&!E)return S&&(S.fetch="hit"),this.#z(T),o&&this.#R(T),S&&this.#n(S,T),C;let A=this.#U(e,T,w,g),O=A.__staleWhileFetching!==void 0&&r;return S&&(S.fetch=E?"stale":"refresh",O&&E&&(S.returnedStale=!0)),O?A.__staleWhileFetching:A.__returned=A}}async forceFetch(e,t={}){let r=await this.fetch(e,t);if(r===void 0)throw new Error("fetch() returned undefined");return r}memo(e,t={}){let r=this.#w;if(!r)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:i,...a}=t,s=this.get(e,a);if(!i&&s!==void 0)return s;let l=r(e,s,{options:a,context:o});return this.set(e,l,a),l}get(e,t={}){let{allowStale:r=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:i=this.noDeleteOnStaleGet,status:a}=t,s=this.#s.get(e);if(s!==void 0){let l=this.#o[s],c=this.#d(l);return a&&this.#n(a,s),this.#y(s)?(a&&(a.get="stale"),c?(a&&r&&l.__staleWhileFetching!==void 0&&(a.returnedStale=!0),r?l.__staleWhileFetching:void 0):(i||this.#O(e,"expire"),a&&r&&(a.returnedStale=!0),r?l:void 0)):(a&&(a.get="hit"),c?l.__staleWhileFetching:(this.#z(s),o&&this.#R(s),l))}else a&&(a.get="miss")}#B(e,t){this.#S[t]=e,this.#f[e]=t}#z(e){e!==this.#u&&(e===this.#m?this.#m=this.#f[e]:this.#B(this.#S[e],this.#f[e]),this.#B(this.#u,e),this.#u=e)}delete(e){return this.#O(e,"delete")}#O(e,t){let r=!1;if(this.#c!==0){let o=this.#s.get(e);if(o!==void 0)if(r=!0,this.#c===1)this.#H(t);else{this.#N(o);let i=this.#o[o];if(this.#d(i)?i.__abortController.abort(new Error("deleted")):(this.#v||this.#h)&&(this.#v&&this.#i?.(i,e,t),this.#h&&this.#g?.push([i,e,t])),this.#s.delete(e),this.#l[o]=void 0,this.#o[o]=void 0,o===this.#u)this.#u=this.#S[o];else if(o===this.#m)this.#m=this.#f[o];else{let a=this.#S[o];this.#f[a]=this.#f[o];let s=this.#f[o];this.#S[s]=this.#S[o]}this.#c--,this.#E.push(o)}}if(this.#h&&this.#g?.length){let o=this.#g,i;for(;i=o?.shift();)this.#r?.(...i)}return r}clear(){return this.#H("delete")}#H(e){for(let t of this.#I({allowStale:!0})){let r=this.#o[t];if(this.#d(r))r.__abortController.abort(new Error("deleted"));else{let o=this.#l[t];this.#v&&this.#i?.(r,o,e),this.#h&&this.#g?.push([r,o,e])}}if(this.#s.clear(),this.#o.fill(void 0),this.#l.fill(void 0),this.#b&&this.#C&&(this.#b.fill(0),this.#C.fill(0)),this.#x&&this.#x.fill(0),this.#m=0,this.#u=0,this.#E.length=0,this.#p=0,this.#c=0,this.#h&&this.#g){let t=this.#g,r;for(;r=t?.shift();)this.#r?.(...r)}}};import{posix as vP,win32 as mp}from"node:path";import{fileURLToPath as TP}from"node:url";import{lstatSync as EP,readdir as xP,readdirSync as CP,readlinkSync as RP,realpathSync as AP}from"fs";import*as IP from"node:fs";import{lstat as LP,readdir as OP,readlink as MP,realpath as NP}from"node:fs/promises";import{EventEmitter as dp}from"node:events";import oy from"node:stream";import{StringDecoder as pP}from"node:string_decoder";var ey=typeof process=="object"&&process?process:{stdout:null,stderr:null},uP=n=>!!n&&typeof n=="object"&&(n instanceof yr||n instanceof oy||mP(n)||hP(n)),mP=n=>!!n&&typeof n=="object"&&n instanceof dp&&typeof n.pipe=="function"&&n.pipe!==oy.Writable.prototype.pipe,hP=n=>!!n&&typeof n=="object"&&n instanceof dp&&typeof n.write=="function"&&typeof n.end=="function",Xn=Symbol("EOF"),Jn=Symbol("maybeEmitEnd"),Sr=Symbol("emittedEnd"),ul=Symbol("emittingEnd"),va=Symbol("emittedError"),ml=Symbol("closed"),ty=Symbol("read"),hl=Symbol("flush"),ny=Symbol("flushChunk"),mn=Symbol("encoding"),Xo=Symbol("decoder"),et=Symbol("flowing"),Ta=Symbol("paused"),Jo=Symbol("resume"),tt=Symbol("buffer"),Ct=Symbol("pipes"),nt=Symbol("bufferLength"),op=Symbol("bufferPush"),gl=Symbol("bufferShift"),gt=Symbol("objectMode"),He=Symbol("destroyed"),ip=Symbol("error"),ap=Symbol("emitData"),ry=Symbol("emitEnd"),sp=Symbol("emitEnd2"),On=Symbol("async"),lp=Symbol("abort"),fl=Symbol("aborted"),Ea=Symbol("signal"),no=Symbol("dataListeners"),Dt=Symbol("discarded"),xa=n=>Promise.resolve().then(n),gP=n=>n(),fP=n=>n==="end"||n==="finish"||n==="prefinish",SP=n=>n instanceof ArrayBuffer||!!n&&typeof n=="object"&&n.constructor&&n.constructor.name==="ArrayBuffer"&&n.byteLength>=0,yP=n=>!Buffer.isBuffer(n)&&ArrayBuffer.isView(n),Sl=class{src;dest;opts;ondrain;constructor(e,t,r){this.src=e,this.dest=t,this.opts=r,this.ondrain=()=>e[Jo](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},cp=class extends Sl{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,r){super(e,t,r),this.proxyErrors=o=>t.emit("error",o),e.on("error",this.proxyErrors)}},bP=n=>!!n.objectMode,wP=n=>!n.objectMode&&!!n.encoding&&n.encoding!=="buffer",yr=class extends dp{[et]=!1;[Ta]=!1;[Ct]=[];[tt]=[];[gt];[mn];[On];[Xo];[Xn]=!1;[Sr]=!1;[ul]=!1;[ml]=!1;[va]=null;[nt]=0;[He]=!1;[Ea];[fl]=!1;[no]=0;[Dt]=!1;writable=!0;readable=!0;constructor(...e){let t=e[0]||{};if(super(),t.objectMode&&typeof t.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");bP(t)?(this[gt]=!0,this[mn]=null):wP(t)?(this[mn]=t.encoding,this[gt]=!1):(this[gt]=!1,this[mn]=null),this[On]=!!t.async,this[Xo]=this[mn]?new pP(this[mn]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[tt]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Ct]});let{signal:r}=t;r&&(this[Ea]=r,r.aborted?this[lp]():r.addEventListener("abort",()=>this[lp]()))}get bufferLength(){return this[nt]}get encoding(){return this[mn]}set encoding(e){throw new Error("Encoding must be set at instantiation time")}setEncoding(e){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[gt]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[On]}set async(e){this[On]=this[On]||!!e}[lp](){this[fl]=!0,this.emit("abort",this[Ea]?.reason),this.destroy(this[Ea]?.reason)}get aborted(){return this[fl]}set aborted(e){}write(e,t,r){if(this[fl])return!1;if(this[Xn])throw new Error("write after end");if(this[He])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof t=="function"&&(r=t,t="utf8"),t||(t="utf8");let o=this[On]?xa:gP;if(!this[gt]&&!Buffer.isBuffer(e)){if(yP(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(SP(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[gt]?(this[et]&&this[nt]!==0&&this[hl](!0),this[et]?this.emit("data",e):this[op](e),this[nt]!==0&&this.emit("readable"),r&&o(r),this[et]):e.length?(typeof e=="string"&&!(t===this[mn]&&!this[Xo]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[mn]&&(e=this[Xo].write(e)),this[et]&&this[nt]!==0&&this[hl](!0),this[et]?this.emit("data",e):this[op](e),this[nt]!==0&&this.emit("readable"),r&&o(r),this[et]):(this[nt]!==0&&this.emit("readable"),r&&o(r),this[et])}read(e){if(this[He])return null;if(this[Dt]=!1,this[nt]===0||e===0||e&&e>this[nt])return this[Jn](),null;this[gt]&&(e=null),this[tt].length>1&&!this[gt]&&(this[tt]=[this[mn]?this[tt].join(""):Buffer.concat(this[tt],this[nt])]);let t=this[ty](e||null,this[tt][0]);return this[Jn](),t}[ty](e,t){if(this[gt])this[gl]();else{let r=t;e===r.length||e===null?this[gl]():typeof r=="string"?(this[tt][0]=r.slice(e),t=r.slice(0,e),this[nt]-=e):(this[tt][0]=r.subarray(e),t=r.subarray(0,e),this[nt]-=e)}return this.emit("data",t),!this[tt].length&&!this[Xn]&&this.emit("drain"),t}end(e,t,r){return typeof e=="function"&&(r=e,e=void 0),typeof t=="function"&&(r=t,t="utf8"),e!==void 0&&this.write(e,t),r&&this.once("end",r),this[Xn]=!0,this.writable=!1,(this[et]||!this[Ta])&&this[Jn](),this}[Jo](){this[He]||(!this[no]&&!this[Ct].length&&(this[Dt]=!0),this[Ta]=!1,this[et]=!0,this.emit("resume"),this[tt].length?this[hl]():this[Xn]?this[Jn]():this.emit("drain"))}resume(){return this[Jo]()}pause(){this[et]=!1,this[Ta]=!0,this[Dt]=!1}get destroyed(){return this[He]}get flowing(){return this[et]}get paused(){return this[Ta]}[op](e){this[gt]?this[nt]+=1:this[nt]+=e.length,this[tt].push(e)}[gl](){return this[gt]?this[nt]-=1:this[nt]-=this[tt][0].length,this[tt].shift()}[hl](e=!1){do;while(this[ny](this[gl]())&&this[tt].length);!e&&!this[tt].length&&!this[Xn]&&this.emit("drain")}[ny](e){return this.emit("data",e),this[et]}pipe(e,t){if(this[He])return e;this[Dt]=!1;let r=this[Sr];return t=t||{},e===ey.stdout||e===ey.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this[Ct].push(t.proxyErrors?new cp(this,e,t):new Sl(this,e,t)),this[On]?xa(()=>this[Jo]()):this[Jo]()),e}unpipe(e){let t=this[Ct].find(r=>r.dest===e);t&&(this[Ct].length===1?(this[et]&&this[no]===0&&(this[et]=!1),this[Ct]=[]):this[Ct].splice(this[Ct].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let r=super.on(e,t);if(e==="data")this[Dt]=!1,this[no]++,!this[Ct].length&&!this[et]&&this[Jo]();else if(e==="readable"&&this[nt]!==0)super.emit("readable");else if(fP(e)&&this[Sr])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[va]){let o=t;this[On]?xa(()=>o.call(this,this[va])):o.call(this,this[va])}return r}removeListener(e,t){return this.off(e,t)}off(e,t){let r=super.off(e,t);return e==="data"&&(this[no]=this.listeners("data").length,this[no]===0&&!this[Dt]&&!this[Ct].length&&(this[et]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[no]=0,!this[Dt]&&!this[Ct].length&&(this[et]=!1)),t}get emittedEnd(){return this[Sr]}[Jn](){!this[ul]&&!this[Sr]&&!this[He]&&this[tt].length===0&&this[Xn]&&(this[ul]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[ml]&&this.emit("close"),this[ul]=!1)}emit(e,...t){let r=t[0];if(e!=="error"&&e!=="close"&&e!==He&&this[He])return!1;if(e==="data")return!this[gt]&&!r?!1:this[On]?(xa(()=>this[ap](r)),!0):this[ap](r);if(e==="end")return this[ry]();if(e==="close"){if(this[ml]=!0,!this[Sr]&&!this[He])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[va]=r,super.emit(ip,r);let i=!this[Ea]||this.listeners("error").length?super.emit("error",r):!1;return this[Jn](),i}else if(e==="resume"){let i=super.emit("resume");return this[Jn](),i}else if(e==="finish"||e==="prefinish"){let i=super.emit(e);return this.removeAllListeners(e),i}let o=super.emit(e,...t);return this[Jn](),o}[ap](e){for(let r of this[Ct])r.dest.write(e)===!1&&this.pause();let t=this[Dt]?!1:super.emit("data",e);return this[Jn](),t}[ry](){return this[Sr]?!1:(this[Sr]=!0,this.readable=!1,this[On]?(xa(()=>this[sp]()),!0):this[sp]())}[sp](){if(this[Xo]){let t=this[Xo].end();if(t){for(let r of this[Ct])r.dest.write(t);this[Dt]||super.emit("data",t)}}for(let t of this[Ct])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[gt]||(e.dataLength=0);let t=this.promise();return this.on("data",r=>{e.push(r),this[gt]||(e.dataLength+=r.length)}),await t,e}async concat(){if(this[gt])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[mn]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(He,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[Dt]=!1;let e=!1,t=async()=>(this.pause(),e=!0,{value:void 0,done:!0});return{next:()=>{if(e)return t();let o=this.read();if(o!==null)return Promise.resolve({done:!1,value:o});if(this[Xn])return t();let i,a,s=p=>{this.off("data",l),this.off("end",c),this.off(He,d),t(),a(p)},l=p=>{this.off("error",s),this.off("end",c),this.off(He,d),this.pause(),i({value:p,done:!!this[Xn]})},c=()=>{this.off("error",s),this.off("data",l),this.off(He,d),t(),i({done:!0,value:void 0})},d=()=>s(new Error("stream destroyed"));return new Promise((p,u)=>{a=u,i=p,this.once(He,d),this.once("error",s),this.once("end",c),this.once("data",l)})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[Dt]=!1;let e=!1,t=()=>(this.pause(),this.off(ip,t),this.off(He,t),this.off("end",t),e=!0,{done:!0,value:void 0}),r=()=>{if(e)return t();let o=this.read();return o===null?t():{done:!1,value:o}};return this.once("end",t),this.once(ip,t),this.once(He,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[He])return e?this.emit("error",e):this.emit(He),this;this[He]=!0,this[Dt]=!0,this[tt].length=0,this[nt]=0;let t=this;return typeof t.close=="function"&&!this[ml]&&t.close(),e?this.emit("error",e):this.emit(He),this}static get isStream(){return uP}};var PP=AP.native,Ra={lstatSync:EP,readdir:xP,readdirSync:CP,readlinkSync:RP,realpathSync:PP,promises:{lstat:LP,readdir:OP,readlink:MP,realpath:NP}},cy=n=>!n||n===Ra||n===IP?Ra:{...Ra,...n,promises:{...Ra.promises,...n.promises||{}}},dy=/^\\\\\?\\([a-z]:)\\?$/i,kP=n=>n.replace(/\//g,"\\").replace(dy,"$1\\"),_P=/[\\\/]/,tn=0,py=1,uy=2,Mn=4,my=6,hy=8,ro=10,gy=12,en=15,Ca=~en,pp=16,iy=32,Aa=64,hn=128,yl=256,wl=512,ay=Aa|hn|wl,DP=1023,up=n=>n.isFile()?hy:n.isDirectory()?Mn:n.isSymbolicLink()?ro:n.isCharacterDevice()?uy:n.isBlockDevice()?my:n.isSocket()?gy:n.isFIFO()?py:tn,sy=new Map,Ia=n=>{let e=sy.get(n);if(e)return e;let t=n.normalize("NFKD");return sy.set(n,t),t},ly=new Map,bl=n=>{let e=ly.get(n);if(e)return e;let t=Ia(n.toLowerCase());return ly.set(n,t),t},vl=class extends wa{constructor(){super({max:256})}},hp=class extends wa{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1})}},fy=Symbol("PathScurry setAsCwd"),ft=class{name;root;roots;parent;nocase;isCWD=!1;#e;#t;get dev(){return this.#t}#i;get mode(){return this.#i}#r;get nlink(){return this.#r}#a;get uid(){return this.#a}#w;get gid(){return this.#w}#c;get rdev(){return this.#c}#p;get blksize(){return this.#p}#s;get ino(){return this.#s}#l;get size(){return this.#l}#o;get blocks(){return this.#o}#f;get atimeMs(){return this.#f}#S;get mtimeMs(){return this.#S}#m;get ctimeMs(){return this.#m}#u;get birthtimeMs(){return this.#u}#E;get atime(){return this.#E}#g;get mtime(){return this.#g}#x;get ctime(){return this.#x}#C;get birthtime(){return this.#C}#b;#v;#T;#h;#P;#R;#n;#M;#y;#L;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=tn,r,o,i,a,s){this.name=e,this.#b=i?bl(e):Ia(e),this.#n=t&DP,this.nocase=i,this.roots=o,this.root=r||this,this.#M=a,this.#T=s.fullpath,this.#P=s.relative,this.#R=s.relativePosix,this.parent=s.parent,this.parent?this.#e=this.parent.#e:this.#e=cy(s.fs)}depth(){return this.#v!==void 0?this.#v:this.parent?this.#v=this.parent.depth()+1:this.#v=0}childrenCache(){return this.#M}resolve(e){if(!e)return this;let t=this.getRootString(e),o=e.substring(t.length).split(this.splitSep);return t?this.getRoot(t).#N(o):this.#N(o)}#N(e){let t=this;for(let r of e)t=t.child(r);return t}children(){let e=this.#M.get(this);if(e)return e;let t=Object.assign([],{provisional:0});return this.#M.set(this,t),this.#n&=~pp,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let r=this.children(),o=this.nocase?bl(e):Ia(e);for(let l of r)if(l.#b===o)return l;let i=this.parent?this.sep:"",a=this.#T?this.#T+i+e:void 0,s=this.newChild(e,tn,{...t,parent:this,fullpath:a});return this.canReaddir()||(s.#n|=hn),r.push(s),s}relative(){if(this.isCWD)return"";if(this.#P!==void 0)return this.#P;let e=this.name,t=this.parent;if(!t)return this.#P=this.name;let r=t.relative();return r+(!r||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#R!==void 0)return this.#R;let e=this.name,t=this.parent;if(!t)return this.#R=this.fullpathPosix();let r=t.relativePosix();return r+(!r||!t.parent?"":"/")+e}fullpath(){if(this.#T!==void 0)return this.#T;let e=this.name,t=this.parent;if(!t)return this.#T=this.name;let o=t.fullpath()+(t.parent?this.sep:"")+e;return this.#T=o}fullpathPosix(){if(this.#h!==void 0)return this.#h;if(this.sep==="/")return this.#h=this.fullpath();if(!this.parent){let o=this.fullpath().replace(/\\/g,"/");return/^[a-z]:\//i.test(o)?this.#h=`//?/${o}`:this.#h=o}let e=this.parent,t=e.fullpathPosix(),r=t+(!t||!e.parent?"":"/")+this.name;return this.#h=r}isUnknown(){return(this.#n&en)===tn}isType(e){return this[`is${e}`]()}getType(){return this.isUnknown()?"Unknown":this.isDirectory()?"Directory":this.isFile()?"File":this.isSymbolicLink()?"SymbolicLink":this.isFIFO()?"FIFO":this.isCharacterDevice()?"CharacterDevice":this.isBlockDevice()?"BlockDevice":this.isSocket()?"Socket":"Unknown"}isFile(){return(this.#n&en)===hy}isDirectory(){return(this.#n&en)===Mn}isCharacterDevice(){return(this.#n&en)===uy}isBlockDevice(){return(this.#n&en)===my}isFIFO(){return(this.#n&en)===py}isSocket(){return(this.#n&en)===gy}isSymbolicLink(){return(this.#n&ro)===ro}lstatCached(){return this.#n&iy?this:void 0}readlinkCached(){return this.#y}realpathCached(){return this.#L}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#y)return!0;if(!this.parent)return!1;let e=this.#n&en;return!(e!==tn&&e!==ro||this.#n&yl||this.#n&hn)}calledReaddir(){return!!(this.#n&pp)}isENOENT(){return!!(this.#n&hn)}isNamed(e){return this.nocase?this.#b===bl(e):this.#b===Ia(e)}async readlink(){let e=this.#y;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await this.#e.promises.readlink(this.fullpath()),r=(await this.parent.realpath())?.resolve(t);if(r)return this.#y=r}catch(t){this.#d(t.code);return}}readlinkSync(){let e=this.#y;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=this.#e.readlinkSync(this.fullpath()),r=this.parent.realpathSync()?.resolve(t);if(r)return this.#y=r}catch(t){this.#d(t.code);return}}#k(e){this.#n|=pp;for(let t=e.provisional;t<e.length;t++){let r=e[t];r&&r.#_()}}#_(){this.#n&hn||(this.#n=(this.#n|hn)&Ca,this.#A())}#A(){let e=this.children();e.provisional=0;for(let t of e)t.#_()}#I(){this.#n|=wl,this.#D()}#D(){if(this.#n&Aa)return;let e=this.#n;(e&en)===Mn&&(e&=Ca),this.#n=e|Aa,this.#A()}#F(e=""){e==="ENOTDIR"||e==="EPERM"?this.#D():e==="ENOENT"?this.#_():this.children().provisional=0}#U(e=""){e==="ENOTDIR"?this.parent.#D():e==="ENOENT"&&this.#_()}#d(e=""){let t=this.#n;t|=yl,e==="ENOENT"&&(t|=hn),(e==="EINVAL"||e==="UNKNOWN")&&(t&=Ca),this.#n=t,e==="ENOTDIR"&&this.parent&&this.parent.#D()}#B(e,t){return this.#O(e,t)||this.#z(e,t)}#z(e,t){let r=up(e),o=this.newChild(e.name,r,{parent:this}),i=o.#n&en;return i!==Mn&&i!==ro&&i!==tn&&(o.#n|=Aa),t.unshift(o),t.provisional++,o}#O(e,t){for(let r=t.provisional;r<t.length;r++){let o=t[r];if((this.nocase?bl(e.name):Ia(e.name))===o.#b)return this.#H(e,o,r,t)}}#H(e,t,r,o){let i=t.name;return t.#n=t.#n&Ca|up(e),i!==e.name&&(t.name=e.name),r!==o.provisional&&(r===o.length-1?o.pop():o.splice(r,1),o.unshift(t)),o.provisional++,t}async lstat(){if(!(this.#n&hn))try{return this.#W(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#U(e.code)}}lstatSync(){if(!(this.#n&hn))try{return this.#W(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#U(e.code)}}#W(e){let{atime:t,atimeMs:r,birthtime:o,birthtimeMs:i,blksize:a,blocks:s,ctime:l,ctimeMs:c,dev:d,gid:p,ino:u,mode:m,mtime:h,mtimeMs:g,nlink:f,rdev:S,size:b,uid:w}=e;this.#E=t,this.#f=r,this.#C=o,this.#u=i,this.#p=a,this.#o=s,this.#x=l,this.#m=c,this.#t=d,this.#w=p,this.#s=u,this.#i=m,this.#g=h,this.#S=g,this.#r=f,this.#c=S,this.#l=b,this.#a=w;let T=up(e);this.#n=this.#n&Ca|T|iy,T!==tn&&T!==Mn&&T!==ro&&(this.#n|=Aa)}#$=[];#G=!1;#V(e){this.#G=!1;let t=this.#$.slice();this.#$.length=0,t.forEach(r=>r(null,e))}readdirCB(e,t=!1){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let r=this.children();if(this.calledReaddir()){let i=r.slice(0,r.provisional);t?e(null,i):queueMicrotask(()=>e(null,i));return}if(this.#$.push(e),this.#G)return;this.#G=!0;let o=this.fullpath();this.#e.readdir(o,{withFileTypes:!0},(i,a)=>{if(i)this.#F(i.code),r.provisional=0;else{for(let s of a)this.#B(s,r);this.#k(r)}this.#V(r.slice(0,r.provisional))})}#j;async readdir(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();if(this.#j)await this.#j;else{let r=()=>{};this.#j=new Promise(o=>r=o);try{for(let o of await this.#e.promises.readdir(t,{withFileTypes:!0}))this.#B(o,e);this.#k(e)}catch(o){this.#F(o.code),e.provisional=0}this.#j=void 0,r()}return e.slice(0,e.provisional)}readdirSync(){if(!this.canReaddir())return[];let e=this.children();if(this.calledReaddir())return e.slice(0,e.provisional);let t=this.fullpath();try{for(let r of this.#e.readdirSync(t,{withFileTypes:!0}))this.#B(r,e);this.#k(e)}catch(r){this.#F(r.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#n&ay)return!1;let e=en&this.#n;return e===tn||e===Mn||e===ro}shouldWalk(e,t){return(this.#n&Mn)===Mn&&!(this.#n&ay)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#L)return this.#L;if(!((wl|yl|hn)&this.#n))try{let e=await this.#e.promises.realpath(this.fullpath());return this.#L=this.resolve(e)}catch{this.#I()}}realpathSync(){if(this.#L)return this.#L;if(!((wl|yl|hn)&this.#n))try{let e=this.#e.realpathSync(this.fullpath());return this.#L=this.resolve(e)}catch{this.#I()}}[fy](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let t=new Set([]),r=[],o=this;for(;o&&o.parent;)t.add(o),o.#P=r.join(this.sep),o.#R=r.join("/"),o=o.parent,r.push("..");for(o=e;o&&o.parent&&!t.has(o);)o.#P=void 0,o.#R=void 0,o=o.parent}},Tl=class n extends ft{sep="\\";splitSep=_P;constructor(e,t=tn,r,o,i,a,s){super(e,t,r,o,i,a,s)}newChild(e,t=tn,r={}){return new n(e,t,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(e){return mp.parse(e).root}getRoot(e){if(e=kP(e.toUpperCase()),e===this.root.name)return this.root;for(let[t,r]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=r;return this.roots[e]=new Qo(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(dy,"$1\\"),e===t}},El=class n extends ft{splitSep="/";sep="/";constructor(e,t=tn,r,o,i,a,s){super(e,t,r,o,i,a,s)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,t=tn,r={}){return new n(e,t,this.root,this.roots,this.nocase,this.childrenCache(),r)}},xl=class{root;rootPath;roots;cwd;#e;#t;#i;nocase;#r;constructor(e=process.cwd(),t,r,{nocase:o,childrenCacheSize:i=16*1024,fs:a=Ra}={}){this.#r=cy(a),(e instanceof URL||e.startsWith("file://"))&&(e=TP(e));let s=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(s),this.#e=new vl,this.#t=new vl,this.#i=new hp(i);let l=s.substring(this.rootPath.length).split(r);if(l.length===1&&!l[0]&&l.pop(),o===void 0)throw new TypeError("must provide nocase setting to PathScurryBase ctor");this.nocase=o,this.root=this.newRoot(this.#r),this.roots[this.rootPath]=this.root;let c=this.root,d=l.length-1,p=t.sep,u=this.rootPath,m=!1;for(let h of l){let g=d--;c=c.child(h,{relative:new Array(g).fill("..").join(p),relativePosix:new Array(g).fill("..").join("/"),fullpath:u+=(m?"":p)+h}),m=!0}this.cwd=c}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#i}resolve(...e){let t="";for(let i=e.length-1;i>=0;i--){let a=e[i];if(!(!a||a===".")&&(t=t?`${a}/${t}`:a,this.isAbsolute(a)))break}let r=this.#e.get(t);if(r!==void 0)return r;let o=this.cwd.resolve(t).fullpath();return this.#e.set(t,o),o}resolvePosix(...e){let t="";for(let i=e.length-1;i>=0;i--){let a=e[i];if(!(!a||a===".")&&(t=t?`${a}/${t}`:a,this.isAbsolute(a)))break}let r=this.#t.get(t);if(r!==void 0)return r;let o=this.cwd.resolve(t).fullpathPosix();return this.#t.set(t,o),o}relative(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relative()}relativePosix(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.relativePosix()}basename(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.name}dirname(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),(e.parent||e).fullpath()}async readdir(e=this.cwd,t={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ft||(t=e,e=this.cwd);let{withFileTypes:r}=t;if(e.canReaddir()){let o=await e.readdir();return r?o:o.map(i=>i.name)}else return[]}readdirSync(e=this.cwd,t={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ft||(t=e,e=this.cwd);let{withFileTypes:r=!0}=t;return e.canReaddir()?r?e.readdirSync():e.readdirSync().map(o=>o.name):[]}async lstat(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstat()}lstatSync(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.lstatSync()}async readlink(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ft||(t=e.withFileTypes,e=this.cwd);let r=await e.readlink();return t?r:r?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ft||(t=e.withFileTypes,e=this.cwd);let r=e.readlinkSync();return t?r:r?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ft||(t=e.withFileTypes,e=this.cwd);let r=await e.realpath();return t?r:r?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ft||(t=e.withFileTypes,e=this.cwd);let r=e.realpathSync();return t?r:r?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ft||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:a}=t,s=[];(!i||i(e))&&s.push(r?e:e.fullpath());let l=new Set,c=(p,u)=>{l.add(p),p.readdirCB((m,h)=>{if(m)return u(m);let g=h.length;if(!g)return u();let f=()=>{--g===0&&u()};for(let S of h)(!i||i(S))&&s.push(r?S:S.fullpath()),o&&S.isSymbolicLink()?S.realpath().then(b=>b?.isUnknown()?b.lstat():b).then(b=>b?.shouldWalk(l,a)?c(b,f):f()):S.shouldWalk(l,a)?c(S,f):f()},!0)},d=e;return new Promise((p,u)=>{c(d,m=>{if(m)return u(m);p(s)})})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ft||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:a}=t,s=[];(!i||i(e))&&s.push(r?e:e.fullpath());let l=new Set([e]);for(let c of l){let d=c.readdirSync();for(let p of d){(!i||i(p))&&s.push(r?p:p.fullpath());let u=p;if(p.isSymbolicLink()){if(!(o&&(u=p.realpathSync())))continue;u.isUnknown()&&u.lstatSync()}u.shouldWalk(l,a)&&l.add(u)}}return s}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof ft||(t=e,e=this.cwd),this.stream(e,t)[Symbol.asyncIterator]()}[Symbol.iterator](){return this.iterateSync()}*iterateSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ft||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:a}=t;(!i||i(e))&&(yield r?e:e.fullpath());let s=new Set([e]);for(let l of s){let c=l.readdirSync();for(let d of c){(!i||i(d))&&(yield r?d:d.fullpath());let p=d;if(d.isSymbolicLink()){if(!(o&&(p=d.realpathSync())))continue;p.isUnknown()&&p.lstatSync()}p.shouldWalk(s,a)&&s.add(p)}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ft||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:a}=t,s=new yr({objectMode:!0});(!i||i(e))&&s.write(r?e:e.fullpath());let l=new Set,c=[e],d=0,p=()=>{let u=!1;for(;!u;){let m=c.shift();if(!m){d===0&&s.end();return}d++,l.add(m);let h=(f,S,b=!1)=>{if(f)return s.emit("error",f);if(o&&!b){let w=[];for(let T of S)T.isSymbolicLink()&&w.push(T.realpath().then(C=>C?.isUnknown()?C.lstat():C));if(w.length){Promise.all(w).then(()=>h(null,S,!0));return}}for(let w of S)w&&(!i||i(w))&&(s.write(r?w:w.fullpath())||(u=!0));d--;for(let w of S){let T=w.realpathCached()||w;T.shouldWalk(l,a)&&c.push(T)}u&&!s.flowing?s.once("drain",p):g||p()},g=!0;m.readdirCB(h,!0),g=!1}};return p(),s}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof ft||(t=e,e=this.cwd);let{withFileTypes:r=!0,follow:o=!1,filter:i,walkFilter:a}=t,s=new yr({objectMode:!0}),l=new Set;(!i||i(e))&&s.write(r?e:e.fullpath());let c=[e],d=0,p=()=>{let u=!1;for(;!u;){let m=c.shift();if(!m){d===0&&s.end();return}d++,l.add(m);let h=m.readdirSync();for(let g of h)(!i||i(g))&&(s.write(r?g:g.fullpath())||(u=!0));d--;for(let g of h){let f=g;if(g.isSymbolicLink()){if(!(o&&(f=g.realpathSync())))continue;f.isUnknown()&&f.lstatSync()}f.shouldWalk(l,a)&&c.push(f)}}u&&!s.flowing&&s.once("drain",p)};return p(),s}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[fy](t)}},Qo=class extends xl{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,mp,"\\",{...t,nocase:r}),this.nocase=r;for(let o=this.cwd;o;o=o.parent)o.nocase=this.nocase}parseRootPath(e){return mp.parse(e).root.toUpperCase()}newRoot(e){return new Tl(this.rootPath,Mn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},Zo=class extends xl{sep="/";constructor(e=process.cwd(),t={}){let{nocase:r=!1}=t;super(e,vP,"/",{...t,nocase:r}),this.nocase=r}parseRootPath(e){return"/"}newRoot(e){return new El(this.rootPath,Mn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},Pa=class extends Zo{constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,{...t,nocase:r})}},J4=process.platform==="win32"?Tl:El,Sy=process.platform==="win32"?Qo:process.platform==="darwin"?Pa:Zo;var FP=n=>n.length>=1,UP=n=>n.length>=1,ei=class n{#e;#t;#i;length;#r;#a;#w;#c;#p;#s;#l=!0;constructor(e,t,r,o){if(!FP(e))throw new TypeError("empty pattern list");if(!UP(t))throw new TypeError("empty glob list");if(t.length!==e.length)throw new TypeError("mismatched pattern list and glob list lengths");if(this.length=e.length,r<0||r>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#t=t,this.#i=r,this.#r=o,this.#i===0){if(this.isUNC()){let[i,a,s,l,...c]=this.#e,[d,p,u,m,...h]=this.#t;c[0]===""&&(c.shift(),h.shift());let g=[i,a,s,l,""].join("/"),f=[d,p,u,m,""].join("/");this.#e=[g,...c],this.#t=[f,...h],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[i,...a]=this.#e,[s,...l]=this.#t;a[0]===""&&(a.shift(),l.shift());let c=i+"/",d=s+"/";this.#e=[c,...a],this.#t=[d,...l],this.length=this.#e.length}}}pattern(){return this.#e[this.#i]}isString(){return typeof this.#e[this.#i]=="string"}isGlobstar(){return this.#e[this.#i]===st}isRegExp(){return this.#e[this.#i]instanceof RegExp}globString(){return this.#w=this.#w||(this.#i===0?this.isAbsolute()?this.#t[0]+this.#t.slice(1).join("/"):this.#t.join("/"):this.#t.slice(this.#i).join("/"))}hasMore(){return this.length>this.#i+1}rest(){return this.#a!==void 0?this.#a:this.hasMore()?(this.#a=new n(this.#e,this.#t,this.#i+1,this.#r),this.#a.#s=this.#s,this.#a.#p=this.#p,this.#a.#c=this.#c,this.#a):this.#a=null}isUNC(){let e=this.#e;return this.#p!==void 0?this.#p:this.#p=this.#r==="win32"&&this.#i===0&&e[0]===""&&e[1]===""&&typeof e[2]=="string"&&!!e[2]&&typeof e[3]=="string"&&!!e[3]}isDrive(){let e=this.#e;return this.#c!==void 0?this.#c:this.#c=this.#r==="win32"&&this.#i===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#s!==void 0?this.#s:this.#s=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#i===0?e:""}checkFollowGlobstar(){return!(this.#i===0||!this.isGlobstar()||!this.#l)}markFollowGlobstar(){return this.#i===0||!this.isGlobstar()||!this.#l?!1:(this.#l=!1,!0)}};var BP=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",ti=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:r,noext:o,noglobstar:i,platform:a=BP}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=a,this.mmopts={dot:!0,nobrace:t,nocase:r,noext:o,noglobstar:i,optimizationLevel:2,platform:a,nocomment:!0,nonegate:!0};for(let s of e)this.add(s)}add(e){let t=new _t(e,this.mmopts);for(let r=0;r<t.set.length;r++){let o=t.set[r],i=t.globParts[r];if(!o||!i)throw new Error("invalid pattern object");for(;o[0]==="."&&i[0]===".";)o.shift(),i.shift();let a=new ei(o,i,0,this.platform),s=new _t(a.globString(),this.mmopts),l=i[i.length-1]==="**",c=a.isAbsolute();c?this.absolute.push(s):this.relative.push(s),l&&(c?this.absoluteChildren.push(s):this.relativeChildren.push(s))}}ignored(e){let t=e.fullpath(),r=`${t}/`,o=e.relative()||".",i=`${o}/`;for(let a of this.relative)if(a.match(o)||a.match(i))return!0;for(let a of this.absolute)if(a.match(t)||a.match(r))return!0;return!1}childrenIgnored(e){let t=e.fullpath()+"/",r=(e.relative()||".")+"/";for(let o of this.relativeChildren)if(o.match(r))return!0;for(let o of this.absoluteChildren)if(o.match(t))return!0;return!1}};var gp=class n{store;constructor(e=new Map){this.store=e}copy(){return new n(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){let r=e.fullpath(),o=this.store.get(r);o?o.add(t.globString()):this.store.set(r,new Set([t.globString()]))}},fp=class{store=new Map;add(e,t,r){let o=(t?2:0)|(r?1:0),i=this.store.get(e);this.store.set(e,i===void 0?o:o&i)}entries(){return[...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},Sp=class{store=new Map;add(e,t){if(!e.canReaddir())return;let r=this.store.get(e);r?r.find(o=>o.globString()===t.globString())||r.push(t):this.store.set(e,[t])}get(e){let t=this.store.get(e);if(!t)throw new Error("attempting to walk unknown path");return t}entries(){return this.keys().map(e=>[e,this.store.get(e)])}keys(){return[...this.store.keys()].filter(e=>e.canReaddir())}},La=class n{hasWalkedCache;matches=new fp;subwalks=new Sp;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new gp}processPatterns(e,t){this.patterns=t;let r=t.map(o=>[e,o]);for(let[o,i]of r){this.hasWalkedCache.storeWalked(o,i);let a=i.root(),s=i.isAbsolute()&&this.opts.absolute!==!1;if(a){o=o.resolve(a==="/"&&this.opts.root!==void 0?this.opts.root:a);let p=i.rest();if(p)i=p;else{this.matches.add(o,!0,!1);continue}}if(o.isENOENT())continue;let l,c,d=!1;for(;typeof(l=i.pattern())=="string"&&(c=i.rest());)o=o.resolve(l),i=c,d=!0;if(l=i.pattern(),c=i.rest(),d){if(this.hasWalkedCache.hasWalked(o,i))continue;this.hasWalkedCache.storeWalked(o,i)}if(typeof l=="string"){let p=l===".."||l===""||l===".";this.matches.add(o.resolve(l),s,p);continue}else if(l===st){(!o.isSymbolicLink()||this.follow||i.checkFollowGlobstar())&&this.subwalks.add(o,i);let p=c?.pattern(),u=c?.rest();if(!c||(p===""||p===".")&&!u)this.matches.add(o,s,p===""||p===".");else if(p===".."){let m=o.parent||o;u?this.hasWalkedCache.hasWalked(m,u)||this.subwalks.add(m,u):this.matches.add(m,s,!0)}}else l instanceof RegExp&&this.subwalks.add(o,i)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new n(this.opts,this.hasWalkedCache)}filterEntries(e,t){let r=this.subwalks.get(e),o=this.child();for(let i of t)for(let a of r){let s=a.isAbsolute(),l=a.pattern(),c=a.rest();l===st?o.testGlobstar(i,a,c,s):l instanceof RegExp?o.testRegExp(i,l,c,s):o.testString(i,l,c,s)}return o}testGlobstar(e,t,r,o){if((this.dot||!e.name.startsWith("."))&&(t.hasMore()||this.matches.add(e,o,!1),e.canReaddir()&&(this.follow||!e.isSymbolicLink()?this.subwalks.add(e,t):e.isSymbolicLink()&&(r&&t.checkFollowGlobstar()?this.subwalks.add(e,r):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),r){let i=r.pattern();if(typeof i=="string"&&i!==".."&&i!==""&&i!==".")this.testString(e,i,r.rest(),o);else if(i===".."){let a=e.parent||e;this.subwalks.add(a,r)}else i instanceof RegExp&&this.testRegExp(e,i,r.rest(),o)}}testRegExp(e,t,r,o){t.test(e.name)&&(r?this.subwalks.add(e,r):this.matches.add(e,o,!1))}testString(e,t,r,o){e.isNamed(t)&&(r?this.subwalks.add(e,r):this.matches.add(e,o,!1))}};var zP=(n,e)=>typeof n=="string"?new ti([n],e):Array.isArray(n)?new ti(n,e):n,Cl=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#e=[];#t;#i;signal;maxDepth;includeChildMatches;constructor(e,t,r){if(this.patterns=e,this.path=t,this.opts=r,this.#i=!r.posix&&r.platform==="win32"?"\\":"/",this.includeChildMatches=r.includeChildMatches!==!1,(r.ignore||!this.includeChildMatches)&&(this.#t=zP(r.ignore??[],r),!this.includeChildMatches&&typeof this.#t.add!="function")){let o="cannot ignore child matches, ignore lacks add() method.";throw new Error(o)}this.maxDepth=r.maxDepth||1/0,r.signal&&(this.signal=r.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0}))}#r(e){return this.seen.has(e)||!!this.#t?.ignored?.(e)}#a(e){return!!this.#t?.childrenIgnored?.(e)}pause(){this.paused=!0}resume(){if(this.signal?.aborted)return;this.paused=!1;let e;for(;!this.paused&&(e=this.#e.shift());)e()}onResume(e){this.signal?.aborted||(this.paused?this.#e.push(e):e())}async matchCheck(e,t){if(t&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=e.realpathCached()||await e.realpath(),!r)return;e=r}let i=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let a=await i.realpath();a&&(a.isUnknown()||this.opts.stat)&&await a.lstat()}return this.matchCheckTest(i,t)}matchCheckTest(e,t){return e&&(this.maxDepth===1/0||e.depth()<=this.maxDepth)&&(!t||e.canReaddir())&&(!this.opts.nodir||!e.isDirectory())&&(!this.opts.nodir||!this.opts.follow||!e.isSymbolicLink()||!e.realpathCached()?.isDirectory())&&!this.#r(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let r;if(this.opts.realpath){if(r=e.realpathCached()||e.realpathSync(),!r)return;e=r}let i=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&i?.isSymbolicLink()){let a=i.realpathSync();a&&(a?.isUnknown()||this.opts.stat)&&a.lstatSync()}return this.matchCheckTest(i,t)}matchFinish(e,t){if(this.#r(e))return;if(!this.includeChildMatches&&this.#t?.add){let i=`${e.relativePosix()}/**`;this.#t.add(i)}let r=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let o=this.opts.mark&&e.isDirectory()?this.#i:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(r){let i=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(i+o)}else{let i=this.opts.posix?e.relativePosix():e.relative(),a=this.opts.dotRelative&&!i.startsWith(".."+this.#i)?"."+this.#i:"";this.matchEmit(i?a+i+o:"."+o)}}async match(e,t,r){let o=await this.matchCheck(e,r);o&&this.matchFinish(o,t)}matchSync(e,t,r){let o=this.matchCheckSync(e,r);o&&this.matchFinish(o,t)}walkCB(e,t,r){this.signal?.aborted&&r(),this.walkCB2(e,t,new La(this.opts),r)}walkCB2(e,t,r,o){if(this.#a(e))return o();if(this.signal?.aborted&&o(),this.paused){this.onResume(()=>this.walkCB2(e,t,r,o));return}r.processPatterns(e,t);let i=1,a=()=>{--i===0&&o()};for(let[s,l,c]of r.matches.entries())this.#r(s)||(i++,this.match(s,l,c).then(()=>a()));for(let s of r.subwalkTargets()){if(this.maxDepth!==1/0&&s.depth()>=this.maxDepth)continue;i++;let l=s.readdirCached();s.calledReaddir()?this.walkCB3(s,l,r,a):s.readdirCB((c,d)=>this.walkCB3(s,d,r,a),!0)}a()}walkCB3(e,t,r,o){r=r.filterEntries(e,t);let i=1,a=()=>{--i===0&&o()};for(let[s,l,c]of r.matches.entries())this.#r(s)||(i++,this.match(s,l,c).then(()=>a()));for(let[s,l]of r.subwalks.entries())i++,this.walkCB2(s,l,r.child(),a);a()}walkCBSync(e,t,r){this.signal?.aborted&&r(),this.walkCB2Sync(e,t,new La(this.opts),r)}walkCB2Sync(e,t,r,o){if(this.#a(e))return o();if(this.signal?.aborted&&o(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,r,o));return}r.processPatterns(e,t);let i=1,a=()=>{--i===0&&o()};for(let[s,l,c]of r.matches.entries())this.#r(s)||this.matchSync(s,l,c);for(let s of r.subwalkTargets()){if(this.maxDepth!==1/0&&s.depth()>=this.maxDepth)continue;i++;let l=s.readdirSync();this.walkCB3Sync(s,l,r,a)}a()}walkCB3Sync(e,t,r,o){r=r.filterEntries(e,t);let i=1,a=()=>{--i===0&&o()};for(let[s,l,c]of r.matches.entries())this.#r(s)||this.matchSync(s,l,c);for(let[s,l]of r.subwalks.entries())i++,this.walkCB2Sync(s,l,r.child(),a);a()}},Oa=class extends Cl{matches=new Set;constructor(e,t,r){super(e,t,r)}matchEmit(e){this.matches.add(e)}async walk(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&await this.path.lstat(),await new Promise((e,t)=>{this.walkCB(this.path,this.patterns,()=>{this.signal?.aborted?t(this.signal.reason):e(this.matches)})}),this.matches}walkSync(){if(this.signal?.aborted)throw this.signal.reason;return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>{if(this.signal?.aborted)throw this.signal.reason}),this.matches}},Ma=class extends Cl{results;constructor(e,t,r){super(e,t,r),this.results=new yr({signal:this.signal,objectMode:!0}),this.results.on("drain",()=>this.resume()),this.results.on("resume",()=>this.resume())}matchEmit(e){this.results.write(e),this.results.flowing||this.pause()}stream(){let e=this.path;return e.isUnknown()?e.lstat().then(()=>{this.walkCB(e,this.patterns,()=>this.results.end())}):this.walkCB(e,this.patterns,()=>this.results.end()),this.results}streamSync(){return this.path.isUnknown()&&this.path.lstatSync(),this.walkCBSync(this.path,this.patterns,()=>this.results.end()),this.results}};var jP=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",gn=class{absolute;cwd;root;dot;dotRelative;follow;ignore;magicalBraces;mark;matchBase;maxDepth;nobrace;nocase;nodir;noext;noglobstar;pattern;platform;realpath;scurry;stat;signal;windowsPathsNoEscape;withFileTypes;includeChildMatches;opts;patterns;constructor(e,t){if(!t)throw new TypeError("glob options required");if(this.withFileTypes=!!t.withFileTypes,this.signal=t.signal,this.follow=!!t.follow,this.dot=!!t.dot,this.dotRelative=!!t.dotRelative,this.nodir=!!t.nodir,this.mark=!!t.mark,t.cwd?(t.cwd instanceof URL||t.cwd.startsWith("file://"))&&(t.cwd=HP(t.cwd)):this.cwd="",this.cwd=t.cwd||"",this.root=t.root,this.magicalBraces=!!t.magicalBraces,this.nobrace=!!t.nobrace,this.noext=!!t.noext,this.realpath=!!t.realpath,this.absolute=t.absolute,this.includeChildMatches=t.includeChildMatches!==!1,this.noglobstar=!!t.noglobstar,this.matchBase=!!t.matchBase,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:1/0,this.stat=!!t.stat,this.ignore=t.ignore,this.withFileTypes&&this.absolute!==void 0)throw new Error("cannot set absolute and withFileTypes:true");if(typeof e=="string"&&(e=[e]),this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(e=e.map(l=>l.replace(/\\/g,"/"))),this.matchBase){if(t.noglobstar)throw new TypeError("base matching requires globstar");e=e.map(l=>l.includes("/")?l:`./**/${l}`)}if(this.pattern=e,this.platform=t.platform||jP,this.opts={...t,platform:this.platform},t.scurry){if(this.scurry=t.scurry,t.nocase!==void 0&&t.nocase!==t.scurry.nocase)throw new Error("nocase option contradicts provided scurry option")}else{let l=t.platform==="win32"?Qo:t.platform==="darwin"?Pa:t.platform?Zo:Sy;this.scurry=new l(this.cwd,{nocase:t.nocase,fs:t.fs})}this.nocase=this.scurry.nocase;let r=this.platform==="darwin"||this.platform==="win32",o={...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:r,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},i=this.pattern.map(l=>new _t(l,o)),[a,s]=i.reduce((l,c)=>(l[0].push(...c.set),l[1].push(...c.globParts),l),[[],[]]);this.patterns=a.map((l,c)=>{let d=s[c];if(!d)throw new Error("invalid pattern object");return new ei(l,d,0,this.platform)})}async walk(){return[...await new Oa(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walk()]}walkSync(){return[...new Oa(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).walkSync()]}stream(){return new Ma(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).stream()}streamSync(){return new Ma(this.patterns,this.scurry.cwd,{...this.opts,maxDepth:this.maxDepth!==1/0?this.maxDepth+this.scurry.cwd.depth():1/0,platform:this.platform,nocase:this.nocase,includeChildMatches:this.includeChildMatches}).streamSync()}iterateSync(){return this.streamSync()[Symbol.iterator]()}[Symbol.iterator](){return this.iterateSync()}iterate(){return this.stream()[Symbol.asyncIterator]()}[Symbol.asyncIterator](){return this.iterate()}};var yp=(n,e={})=>{Array.isArray(n)||(n=[n]);for(let t of n)if(new _t(t,e).hasMagic())return!0;return!1};function Rl(n,e={}){return new gn(n,e).streamSync()}function wy(n,e={}){return new gn(n,e).stream()}function br(n,e={}){return new gn(n,e).walkSync()}async function yy(n,e={}){return new gn(n,e).walk()}function Al(n,e={}){return new gn(n,e).iterateSync()}function vy(n,e={}){return new gn(n,e).iterate()}var $P=Rl,GP=Object.assign(wy,{sync:Rl}),WP=Al,VP=Object.assign(vy,{sync:Al}),qP=Object.assign(br,{stream:Rl,iterate:Al}),by=Object.assign(yy,{glob:yy,globSync:br,sync:qP,globStream:wy,stream:GP,globStreamSync:Rl,streamSync:$P,globIterate:vy,iterate:VP,globIterateSync:Al,iterateSync:WP,Glob:gn,hasMagic:yp,escape:qo,unescape:un});by.glob=by;import oo,{dirname as Cy}from"path";import{cwd as Ep}from"process";import Ry from"yaml";import{z as Ce}from"zod";import Ty from"fs";import Na from"path";import KP from"yaml";import{z as bp}from"zod";var Ey=!1,wp=[`**/*.${Et.TEST}`,`**/*.${Et.MODULE}`],vp=bp.string().refine(n=>/^[a-zA-Z0-9-]+$/.test(n)),Tp=50,YP=bp.object({fileType:bp.nativeEnum(ve)});function de(n,e){let t={project:n,tests:{},modules:{},duplicateEntities:{}},r=n.config.include??wp,o=Array.from(n.config.exclude??[]).concat(qs),i=br(r,{absolute:!1,cwd:n.rootDir,ignore:o,dotRelative:!1,maxDepth:Tp,nodir:!0});for(let a of i){let s=XP(n.rootDir,a,t,e);s&&(t.duplicateEntities[s.id]=s.paths)}return Ey=!0,t}function XP(n,e,t,r){let o=Na.join(n,e),i;try{i=Ty.readFileSync(o,"utf-8")}catch(u){r.warn(`Could not read possible Momentic file at ${o}, skipping: ${u}`);return}let a;try{if(a=KP.parse(i),typeof a!="object"||a===null)throw new Error("The YAML document should parse as a map with key-value pairs")}catch(u){r.warn(`Could not parse possible Momentic file at ${o}, skipping: ${u}`);return}let s=YP.safeParse(a);if(s.success===!1){r.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${s.error}`);return}let l=s.data.fileType,c;try{c=Ty.statSync(o)}catch(u){r.warn(`Skipping path '${o}' because it could not be stat, skipping: ${u}`);return}let d={relativePath:e,fullFilePath:o,platformSep:Na.sep,fullPathSegments:o.split(Na.sep),relativePathSegments:e.split(Na.sep),fileName:Na.basename(o),lastModified:c.mtime,createdAt:c.birthtime},p;switch(l){case ve.TEST:try{let u=Xt.parse(a);if(t.tests[u.id]){let m=t.tests[u.id].fullFilePath;p={id:u.id,paths:[m,o]}}return t.tests[u.id]={type:ve.TEST,name:u.name,id:u.id,description:u.description??void 0,labels:u.labels,...d},p}catch(u){r.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${u}`);return}case ve.MODULE:try{let u=It.parse(a);if(t.modules[u.moduleId]){let h=t.modules[u.moduleId].fullFilePath;p={id:u.moduleId,paths:[h,o]}}t.modules[u.moduleId]={type:ve.MODULE,name:u.name,id:u.moduleId,description:u.description??void 0,...d};let m=d.fileName.replace(".module.yaml","");return!Ey&&Ee(u.name)!==m&&r.warn(`The module with ID ${u.moduleId} has a name (${u.name}) that does not match its file name (${m}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),p}catch(u){r.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${u}`);return}default:r.warn(`Unsupported file type ${l}, skipping...`);return}}var ni="momentic.config.yaml",xy="momentic.workspace.yaml",tL=Ce.object({projects:Ce.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),nL=Ce.union([Ce.string(),Ce.object({fromFile:Ce.string(),json:Ce.boolean().optional()})]),rL=Ce.object({name:vp,baseUrl:Ce.string(),envFile:Ce.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:Ce.record(Ce.string(),nL).optional(),inheritFromShell:Ce.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:Fr.optional()}),oL=Ce.object({postSave:Ce.string().optional()}),iL=Ce.object({name:vp,include:Ce.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:Ce.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:Ce.string().optional(),reporterDir:Ce.string().optional(),outputDir:Ce.string().optional(),retries:Ce.number().optional().describe("number of retries per test"),parallel:Ce.number().optional().describe("degree of parallelism"),environments:Ce.array(rL).optional(),gitMainBranch:Ce.string().optional(),gitProtectedBranches:Ce.string().array().optional(),ai:zd.optional(),browser:Fr.optional(),advanced:Hd.optional(),hooks:oL.optional()});function Ay(n,e){let t;try{t=QP(n,"utf-8")}catch(o){y.warn(`Could not read possible Momentic ${e} file at ${n}: ${o}`);return}let r;try{if(r=Ry.parse(t),typeof r!="object"||r===null)throw new Error(`The ${e} file should parse as a map with key-value pairs, but is type ${typeof r} instead`)}catch(o){y.warn(`Possible Momentic ${e} file at ${n} does not parse as valid YAML: ${o}`);return}return r}function xp(n){let e=Ay(n,"project configuration");if(e!==void 0)try{return iL.parse(e)}catch(t){y.warn(`Possible Momentic project configuration file at ${n} does not adhere to the required schema: ${t}`);return}}function aL(n){let e=Ay(n,"workspace configuration");if(e!==void 0)try{return tL.parse(e)}catch(t){y.warn(`Possible Momentic workspace configuration file at ${n} does not adhere to the required schema: ${t}`);return}}function sL(){let n=[],e=Ep(),t=oo.parse(e).root,r=15,o=0;for(;o<r;){o++;let i=oo.basename(e);if(Vs.includes(i))return y.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),n;for(let a of ZP(e))if(a.endsWith(ni)){let s=oo.join(e,a),l=xp(s);l&&n.push({configFilePath:s,config:l,rootDir:Cy(s)})}if(n.length)return n;if(e=oo.dirname(e),e===t)break}return n}function rt(n={}){let{configFilePath:e,nameFilter:t}=n,r=Cp(e);if(t&&(r=r.filter(o=>o.config.name===t)),r.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
|
|
41
|
-
${r.map(o=>o.configFilePath)}`);if(r.length===0)throw new Error("No valid Momentic project file available.");return y.debug(`Found valid project configuration at ${r[0].configFilePath}`),r[0]}function lL(n){let e=aL(n);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(i=>(i.endsWith("/")||(i+="/"),`${i}*${ni}`)),r=br(t,{absolute:!1,cwd:Ep(),dotRelative:!1,maxDepth:Tp,nodir:!0}),o=[];for(let i of r){let a=oo.join(Ep(),i),s=xp(a);s&&o.push({configFilePath:a,config:s,rootDir:Cy(a)})}return o}function Cp(n){if(n){n=oo.resolve(n);let t=xp(n);return t||(console.error(`No valid Momentic project file found at ${n}.`),process.exit(1)),[{config:t,configFilePath:n,rootDir:oo.dirname(n)}]}if(JP(xy)){let t=lL(xy);if(t)return t}return sL()}function ri(n,e){let t=Ry.stringify(n);eL(e,t)}import oi from"fs";import Rp from"path";import{z as Ap}from"zod";var Iy="golden/visual-diff",Py="reports",Ly="test-results";var cL=Ap.object({width:Ap.number(),height:Ap.number()}),ii=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,t){let r=Rp.join(e.rootDir,e.config.goldenFileDir??Iy);this.defaultGoldenScreenshotDir=r,this.regenerateGoldenFiles=t}async prepareGoldenScreenshotForComparison(e,t,r){if(t.screenshot?.data?.startsWith("https://")){let a=await fetch(t.screenshot.data);return{buffer:Buffer.from(await a.arrayBuffer()),width:t.screenshot.width,height:t.screenshot.height}}let o=t.screenshot?.data;o||(o=Rp.join(this.defaultGoldenScreenshotDir,`${t.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return oi.mkdirSync(Rp.dirname(o),{recursive:!0}),oi.writeFileSync(o,r.buffer),oi.writeFileSync(i,JSON.stringify({width:r.width,height:r.height})),{buffer:Buffer.from(r.buffer),width:r.width,height:r.height};if(oi.existsSync(o)){let a=oi.readFileSync(o),s=cL.parse(JSON.parse(oi.readFileSync(i,"utf-8")));return{buffer:a,width:s.width,height:s.height}}else throw new R("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};var ai=class{flags;constructor(e){this.flags={auto_expand_iframes:e.browser?.autoExpandIframes??!1,rag_v2:e.ai?.aiPageFiltering??!1,faker_constant_seed:e.advanced?.fakerConstantSeed??!1,disable_secondary_cache_resolution:e.browser?.disableSecondaryCacheResolution??!1,global_locator_redirect:e.browser?.globalLocatorRedirect??!0,visual_actions:e.browser?.visualActions??!1,mini_model_initial_assertion:!1,mini_model_initial_locator:!1,show_test_plans:!1,icon_knowledge_base:!1,disable_clickhouse_caches:!1,disable_clickhouse_last_updated_endpoint:!1}}isBooleanFlagEnabled(e){return this.flags[e]??!1}getAllFlags(){return{...this.flags}}getFlagPayload(e){}async refresh(){}};import dL from"simple-git";var Re=dL();function Il(n){if(n.startsWith("git@")){let e=n.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let r=t[0],o=t[1];return`${r}/${o}`}}}else if(n.startsWith("http")||n.startsWith("https")){let t=new URL(n).pathname.split("/").filter(Boolean);if(t.length>=2){let r=t[0],o=t[1].replace(".git","");return`${r}/${o}`}}}async function Ae(n,e){try{return(await e).trim()}catch(t){n.error({err:t},"Failed to run git command");return}}function pL(){if(process.env.GITHUB_ACTION)return"GithubActions";if(process.env.GITLAB_CI)return"GitlabCI";if(process.env.CIRCLECI)return"CircleCI";if(process.env.BUILDKITE)return"Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return"AzureDevOps";if(process.env.PROJECT_ID&&process.env.BUILD_ID)return"GCPCloudBuild"}async function uL(n){let[e,t,r,o]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:t,gitCommitMessage:r,gitCommitAuthorName:o,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function mL(n){let[e,t,r]=await Promise.all([Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:r,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function hL(n){let[e,t,r,o]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),s=t?Il(t):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:r,gitCommitAuthorName:o,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function gL(n){let[e,t,r]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Il(o):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:r,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function fL(n){let[e,t,r]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Il(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:r,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function SL(n,e){let[t,r,o,i,a,s,l,c]=await Promise.all([Ae(n,Re.revparse(["HEAD"])),Ae(n,Re.revparse(["--short","HEAD"])),Ae(n,Re.revparse(["--abbrev-ref","HEAD"])),Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"])),e?Ae(n,Re.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0)]),d=c?await Ae(n,Re.show(["--no-patch","--format=%ci",c])):void 0,p=i?.includes("github.com"),u=i?.includes("gitlab.com"),m=i?Il(i):void 0;return{gitCommitSha:t,gitCommitShaShort:r,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:s,gitCommitAuthorName:l,lastCommitOnMainSha:c,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?m:void 0,gitlabProjectPath:u?m:void 0,pipelineId:void 0}}async function yL(){let n=process.env._HEAD_REPO_URL;return{gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:n?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:n?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function bL(n){let e=n.config.gitProtectedBranches??[];return n.config.gitMainBranch&&e.push(n.config.gitMainBranch),{gitMainBranch:n.config.gitMainBranch,gitProtectedBranches:e}}async function Ip(n,e){let t=pL();if(!t)return SL(n,e);switch(t){case"GithubActions":return uL(n);case"GitlabCI":return mL(n);case"CircleCI":return hL(n);case"Buildkite":return gL(n);case"AzureDevOps":return fL(n);case"GCPCloudBuild":return yL()}}async function wL(n,e,t,r){let o=r;if(!r.gitCommitSha)return o;if(r.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp)){let i=await e.getMergeBaseCommitFromGitlab(t,r.gitMainBranch,r.gitCommitSha);o={...o,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName){let i=await e.getCommitFromGitlab(t,r.gitCommitSha);i&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??i.author.name,gitCommitMessage:o.gitCommitMessage??i.message})}return o}async function vL(n,e,t,r,o){let i=o;if(!o.gitCommitSha)return i;if(o.gitMainBranch&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)){let a=await e.getMergeBaseCommitFromGithub(t,r,o.gitMainBranch,o.gitCommitSha);i={...i,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName){let a=await e.getCommitFromGithub(t,r,o.gitCommitSha);a&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??a.author.name,gitCommitMessage:i.gitCommitMessage??a.message})}return i}async function TL(n,e,t){try{if(t.githubRepository){let[r,o]=t.githubRepository.split("/");return await vL(n,e,r,o,t)}else if(t.gitlabProjectPath)return await wL(n,e,t.gitlabProjectPath,t)}catch(r){n.warn({err:r},"Failed to get remote git metadata")}return t}async function si(n,e,t){let r=await bL(t),o=await Ip(n,r.gitMainBranch),i={...r,...o};(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)&&i.gitBranchName===r.gitMainBranch&&(i.lastCommitOnMainSha=i.gitCommitSha,i.lastCommitOnMainTimestamp=i.gitCommitTimestamp);let a=await TL(n,e,i);return{...r,...o,...a}}import _k from"http";import{z as Op}from"zod";var j="v1",ka="2.10.1";var wr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Oy=n=>{let e=n.reason===void 0?new DOMException("This operation was aborted.","AbortError"):n.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function z(n,e){let{milliseconds:t,fallback:r,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a,s;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((l,c)=>{if(e.signal){let{signal:p}=e;if(p.aborted)return c(Oy(p));s=()=>c(Oy(p)),p.addEventListener("abort",s)}let d=()=>{if(r)try{l(r())}catch(p){c(p)}else{typeof n.cancel=="function"&&Promise.resolve().then(()=>n.cancel()).catch(()=>{});let p=o instanceof Error?o:new wr(o??`Promise timed out after ${t}ms`);c(p)}};a=i.setTimeout(d,t),Promise.resolve(n).then(p=>l(p)).catch(p=>c(p))}).finally(()=>{i.clearTimeout(a),e.signal&&s&&e.signal.removeEventListener("abort",s)})}var Pl=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let r=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(s=>r-s<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let r=Date.now(),o=`${t}:${e}`;this._cleanup(t,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(r),!1)}};var Pp=["ability","able","aboard","about","above","accept","accident","according","account","accurate","acres","across","act","action","active","activity","actual","actually","add","addition","additional","adjective","adult","adventure","advice","affect","afraid","after","afternoon","again","against","age","ago","agree","ahead","aid","air","airplane","alike","alive","all","allow","almost","alone","along","aloud","alphabet","already","also","although","am","among","amount","ancient","angle","angry","animal","announced","another","answer","ants","any","anybody","anyone","anything","anyway","anywhere","apart","apartment","appearance","apple","applied","appropriate","are","area","arm","army","around","arrange","arrangement","arrive","arrow","art","article","as","aside","ask","asleep","at","ate","atmosphere","atom","atomic","attached","attack","attempt","attention","audience","author","automobile","available","average","avoid","aware","away","baby","back","bad","badly","bag","balance","ball","balloon","band","bank","bar","bare","bark","barn","base","baseball","basic","basis","basket","bat","battle","be","bean","bear","beat","beautiful","beauty","became","because","become","becoming","bee","been","before","began","beginning","begun","behavior","behind","being","believed","bell","belong","below","belt","bend","beneath","bent","beside","best","bet","better","between","beyond","bicycle","bigger","biggest","bill","birds","birth","birthday","bit","bite","black","blank","blanket","blew","blind","block","blood","blow","blue","board","boat","body","bone","book","border","born","both","bottle","bottom","bound","bow","bowl","box","boy","brain","branch","brass","brave","bread","break","breakfast","breath","breathe","breathing","breeze","brick","bridge","brief","bright","bring","broad","broke","broken","brother","brought","brown","brush","buffalo","build","building","built","buried","burn","burst","bus","bush","business","busy","but","butter","buy","by","cabin","cage","cake","call","calm","came","camera","camp","can","canal","cannot","cap","capital","captain","captured","car","carbon","card","care","careful","carefully","carried","carry","case","cast","castle","cat","catch","cattle","caught","cause","cave","cell","cent","center","central","century","certain","certainly","chain","chair","chamber","chance","change","changing","chapter","character","characteristic","charge","chart","check","cheese","chemical","chest","chicken","chief","child","children","choice","choose","chose","chosen","church","circle","circus","citizen","city","class","classroom","claws","clay","clean","clear","clearly","climate","climb","clock","close","closely","closer","cloth","clothes","clothing","cloud","club","coach","coal","coast","coat","coffee","cold","collect","college","colony","color","column","combination","combine","come","comfortable","coming","command","common","community","company","compare","compass","complete","completely","complex","composed","composition","compound","concerned","condition","congress","connected","consider","consist","consonant","constantly","construction","contain","continent","continued","contrast","control","conversation","cook","cookies","cool","copper","copy","corn","corner","correct","correctly","cost","cotton","could","count","country","couple","courage","course","court","cover","cow","cowboy","crack","cream","create","creature","crew","crop","cross","crowd","cry","cup","curious","current","curve","customs","cut","cutting","daily","damage","dance","danger","dangerous","dark","darkness","date","daughter","dawn","day","dead","deal","dear","death","decide","declared","deep","deeply","deer","definition","degree","depend","depth","describe","desert","design","desk","detail","determine","develop","development","diagram","diameter","did","die","differ","difference","different","difficult","difficulty","dig","dinner","direct","direction","directly","dirt","dirty","disappear","discover","discovery","discuss","discussion","disease","dish","distance","distant","divide","division","do","doctor","does","dog","doing","doll","dollar","done","donkey","door","dot","double","doubt","down","dozen","draw","drawn","dream","dress","drew","dried","drink","drive","driven","driver","driving","drop","dropped","drove","dry","duck","due","dug","dull","during","dust","duty","each","eager","ear","earlier","early","earn","earth","easier","easily","east","easy","eat","eaten","edge","education","effect","effort","egg","eight","either","electric","electricity","element","elephant","eleven","else","empty","end","enemy","energy","engine","engineer","enjoy","enough","enter","entire","entirely","environment","equal","equally","equator","equipment","escape","especially","essential","establish","even","evening","event","eventually","ever","every","everybody","everyone","everything","everywhere","evidence","exact","exactly","examine","example","excellent","except","exchange","excited","excitement","exciting","exclaimed","exercise","exist","expect","experience","experiment","explain","explanation","explore","express","expression","extra","eye","face","facing","fact","factor","factory","failed","fair","fairly","fall","fallen","familiar","family","famous","far","farm","farmer","farther","fast","fastened","faster","fat","father","favorite","fear","feathers","feature","fed","feed","feel","feet","fell","fellow","felt","fence","few","fewer","field","fierce","fifteen","fifth","fifty","fight","fighting","figure","fill","film","final","finally","find","fine","finest","finger","finish","fire","fireplace","firm","first","fish","five","fix","flag","flame","flat","flew","flies","flight","floating","floor","flow","flower","fly","fog","folks","follow","food","foot","football","for","force","foreign","forest","forget","forgot","forgotten","form","former","fort","forth","forty","forward","fought","found","four","fourth","fox","frame","free","freedom","frequently","fresh","friend","friendly","frighten","frog","from","front","frozen","fruit","fuel","full","fully","fun","function","funny","fur","furniture","further","future","gain","game","garage","garden","gas","gasoline","gate","gather","gave","general","generally","gentle","gently","get","getting","giant","gift","girl","give","given","giving","glad","glass","globe","go","goes","gold","golden","gone","good","goose","got","government","grabbed","grade","gradually","grain","grandfather","grandmother","graph","grass","gravity","gray","great","greater","greatest","greatly","green","grew","ground","group","grow","grown","growth","guard","guess","guide","gulf","gun","habit","had","hair","half","halfway","hall","hand","handle","handsome","hang","happen","happened","happily","happy","harbor","hard","harder","hardly","has","hat","have","having","hay","he","headed","heading","health","heard","hearing","heart","heat","heavy","height","held","hello","help","helpful","her","herd","here","herself","hidden","hide","high","higher","highest","highway","hill","him","himself","his","history","hit","hold","hole","hollow","home","honor","hope","horn","horse","hospital","hot","hour","house","how","however","huge","human","hundred","hung","hungry","hunt","hunter","hurried","hurry","hurt","husband","ice","idea","identity","if","ill","image","imagine","immediately","importance","important","impossible","improve","in","inch","include","including","income","increase","indeed","independent","indicate","individual","industrial","industry","influence","information","inside","instance","instant","instead","instrument","interest","interior","into","introduced","invented","involved","iron","is","island","it","its","itself","jack","jar","jet","job","join","joined","journey","joy","judge","jump","jungle","just","keep","kept","key","kids","kill","kind","kitchen","knew","knife","know","knowledge","known","label","labor","lack","lady","laid","lake","lamp","land","language","large","larger","largest","last","late","later","laugh","law","lay","layers","lead","leader","leaf","learn","least","leather","leave","leaving","led","left","leg","length","lesson","let","letter","level","library","lie","life","lift","light","like","likely","limited","line","lion","lips","liquid","list","listen","little","live","living","load","local","locate","location","log","lonely","long","longer","look","loose","lose","loss","lost","lot","loud","love","lovely","low","lower","luck","lucky","lunch","lungs","lying","machine","machinery","mad","made","magic","magnet","mail","main","mainly","major","make","making","man","managed","manner","manufacturing","many","map","mark","market","married","mass","massage","master","material","mathematics","matter","may","maybe","me","meal","mean","means","meant","measure","meat","medicine","meet","melted","member","memory","men","mental","merely","met","metal","method","mice","middle","might","mighty","mile","military","milk","mill","mind","mine","minerals","minute","mirror","missing","mission","mistake","mix","mixture","model","modern","molecular","moment","money","monkey","month","mood","moon","more","morning","most","mostly","mother","motion","motor","mountain","mouse","mouth","move","movement","movie","moving","mud","muscle","music","musical","must","my","myself","mysterious","nails","name","nation","national","native","natural","naturally","nature","near","nearby","nearer","nearest","nearly","necessary","neck","needed","needle","needs","negative","neighbor","neighborhood","nervous","nest","never","new","news","newspaper","next","nice","night","nine","no","nobody","nodded","noise","none","noon","nor","north","nose","not","note","noted","nothing","notice","noun","now","number","numeral","nuts","object","observe","obtain","occasionally","occur","ocean","of","off","offer","office","officer","official","oil","old","older","oldest","on","once","one","only","onto","open","operation","opinion","opportunity","opposite","or","orange","orbit","order","ordinary","organization","organized","origin","original","other","ought","our","ourselves","out","outer","outline","outside","over","own","owner","oxygen","pack","package","page","paid","pain","paint","pair","palace","pale","pan","paper","paragraph","parallel","parent","park","part","particles","particular","particularly","partly","parts","party","pass","passage","past","path","pattern","pay","peace","pen","pencil","people","per","percent","perfect","perfectly","perhaps","period","person","personal","pet","phrase","physical","piano","pick","picture","pictured","pie","piece","pig","pile","pilot","pine","pink","pipe","pitch","place","plain","plan","plane","planet","planned","planning","plant","plastic","plate","plates","play","pleasant","please","pleasure","plenty","plural","plus","pocket","poem","poet","poetry","point","pole","police","policeman","political","pond","pony","pool","poor","popular","population","porch","port","position","positive","possible","possibly","post","pot","potatoes","pound","pour","powder","power","powerful","practical","practice","prepare","present","president","press","pressure","pretty","prevent","previous","price","pride","primitive","principal","principle","printed","private","prize","probably","problem","process","produce","product","production","program","progress","promised","proper","properly","property","protection","proud","prove","provide","public","pull","pupil","pure","purple","purpose","push","put","putting","quarter","queen","question","quick","quickly","quiet","quietly","quite","rabbit","race","radio","railroad","rain","raise","ran","ranch","range","rapidly","rate","rather","raw","rays","reach","read","reader","ready","real","realize","rear","reason","recall","receive","recent","recently","recognize","record","red","refer","refused","region","regular","related","relationship","religious","remain","remarkable","remember","remove","repeat","replace","replied","report","represent","require","research","respect","rest","result","return","review","rhyme","rhythm","rice","rich","ride","riding","right","ring","rise","rising","river","road","roar","rock","rocket","rocky","rod","roll","roof","room","root","rope","rose","rough","round","route","row","rubbed","rubber","rule","ruler","run","running","rush","sad","saddle","safe","safety","said","sail","sale","salmon","salt","same","sand","sang","sat","satellites","satisfied","save","saved","saw","say","scale","scared","scene","school","science","scientific","scientist","score","screen","sea","search","season","seat","second","secret","section","see","seed","seeing","seems","seen","seldom","select","selection","sell","send","sense","sent","sentence","separate","series","serious","serve","service","sets","setting","settle","settlers","seven","several","shade","shadow","shake","shaking","shall","shallow","shape","share","sharp","she","sheep","sheet","shelf","shells","shelter","shine","shinning","ship","shirt","shoe","shoot","shop","shore","short","shorter","shot","should","shoulder","shout","show","shown","shut","sick","sides","sight","sign","signal","silence","silent","silk","silly","silver","similar","simple","simplest","simply","since","sing","single","sink","sister","sit","sitting","situation","six","size","skill","skin","sky","slabs","slave","sleep","slept","slide","slight","slightly","slip","slipped","slope","slow","slowly","small","smaller","smallest","smell","smile","smoke","smooth","snake","snow","so","soap","social","society","soft","softly","soil","solar","sold","soldier","solid","solution","solve","some","somebody","somehow","someone","something","sometime","somewhere","son","song","soon","sort","sound","source","south","southern","space","speak","special","species","specific","speech","speed","spell","spend","spent","spider","spin","spirit","spite","split","spoken","sport","spread","spring","square","stage","stairs","stand","standard","star","stared","start","state","statement","station","stay","steady","steam","steel","steep","stems","step","stepped","stick","stiff","still","stock","stomach","stone","stood","stop","stopped","store","storm","story","stove","straight","strange","stranger","straw","stream","street","strength","stretch","strike","string","strip","strong","stronger","struck","structure","struggle","stuck","student","studied","studying","subject","substance","success","successful","such","sudden","suddenly","sugar","suggest","suit","sum","summer","sun","sunlight","supper","supply","support","suppose","sure","surface","surprise","surrounded","swam","sweet","swept","swim","swimming","swing","swung","syllable","symbol","system","table","tail","take","taken","tales","talk","tall","tank","tape","task","taste","taught","tax","tea","teach","teacher","team","tears","teeth","telephone","television","tell","temperature","ten","tent","term","terrible","test","than","thank","that","thee","them","themselves","then","theory","there","therefore","these","they","thick","thin","thing","think","third","thirty","this","those","thou","though","thought","thousand","thread","three","threw","throat","through","throughout","throw","thrown","thumb","thus","thy","tide","tie","tight","tightly","till","time","tin","tiny","tip","tired","title","to","tobacco","today","together","told","tomorrow","tone","tongue","tonight","too","took","tool","top","topic","torn","total","touch","toward","tower","town","toy","trace","track","trade","traffic","trail","train","transportation","trap","travel","treated","tree","triangle","tribe","trick","tried","trip","troops","tropical","trouble","truck","trunk","truth","try","tube","tune","turn","twelve","twenty","twice","two","type","typical","uncle","under","underline","understanding","unhappy","union","unit","universe","unknown","unless","until","unusual","up","upon","upper","upward","us","use","useful","using","usual","usually","valley","valuable","value","vapor","variety","various","vast","vegetable","verb","vertical","very","vessels","victory","view","village","visit","visitor","voice","volume","vote","vowel","voyage","wagon","wait","walk","wall","want","war","warm","warn","was","wash","waste","watch","water","wave","way","we","weak","wealth","wear","weather","week","weigh","weight","welcome","well","went","were","west","western","wet","whale","what","whatever","wheat","wheel","when","whenever","where","wherever","whether","which","while","whispered","whistle","white","who","whole","whom","whose","why","wide","widely","wife","wild","will","willing","win","wind","window","wing","winter","wire","wise","wish","with","within","without","wolf","women","won","wonder","wonderful","wood","wooden","wool","word","wore","work","worker","world","worried","worry","worse","worth","would","wrapped","write","writer","writing","written","wrong","wrote","yard","year","yellow","yes","yesterday","yet","you","young","younger","your","yourself","youth","zero","zebra","zipper","zoo","zulu"];function My(n){return new Array(n).fill(0).map(()=>Pp[Math.floor(Math.random()*Pp.length)]).join("-")}var EL=9e4,xL=3,CL=1500,RL=15e3,fn=class extends Error{status;rawError;constructor(e,t,r,o={}){super(r,o),this.status=e,this.rawError=t}};async function AL(n){return n.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Lp=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return ka&&(e[Og]=ka),e}async sendRequest(e,t){let{retries:r=xL,requestTimeoutMs:o=EL,initialRetryDelayMs:i=CL,maxRetryDelayMs:a=RL}=t,s=r,l=r,c,d={path:e,baseUrl:this.baseUrl,method:t.method};for(;s>0;)try{return s--,await this.sendSingleRequestHelper(e,t,o)}catch(p){if(c=p,p instanceof fn&&p.status>=400&&p.status<500)throw p;if(p instanceof Error&&p.name==="AbortError"&&(c=new wr),s===0)throw c;let u=l-s,m=Math.min(i*Math.pow(2,u-1),a);await new Promise(h=>setTimeout(h,m))}throw this.logger.warn({...d,err:c},"Got fatal error response from Momentic server"),c}async sendSingleRequestHelper(e,t,r){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),r),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s);let l={...this.getHeaders(),...t.extraHeaders};try{let c=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:l,signal:i.signal});if(!c.ok){let p=await AL(c);throw new fn(c.status,p,`Request to ${t.method} ${e} failed with status ${c.status}: ${p}`)}let d;if(c.status===204)d={};else{let p=await c.text();try{d=JSON.parse(p)}catch{d=p}}return this.logger&&!t.noLog&&d&&this.logger.debug({result:d,status:c.status,...o},"Got response from Momentic server"),d}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},nn=class extends Lp{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var Xe=class extends nn{constructor(e){super(e)}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${j}/auth/check`,{method:"GET",noLog:!0,retries:10,requestTimeoutMs:5e3});return Jg.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${j}/runs/status`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:1e4});return qg.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${j}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return jg.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${j}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let r=await this.sendRequest(`/${j}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return $g.parse(r)}async queueTests(e){let t=await this.sendRequest(`/${j}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Hg.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${j}/screenshots`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:5e3});return Xg.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${j}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Qg.parse(e)}async acquireCacheLock(e,t){let r=await this.sendRequest(`/${j}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return sf.parse(r)}async releaseCacheLock(e){await this.sendRequest(`/${j}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${j}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${j}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${j}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${j}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Zg.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},r=await this.sendRequest(`/${j}/run-groups/status`,{method:"POST",body:t,noLog:!0,retries:3,requestTimeoutMs:5e3});return Oh.array().parse(r)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${j}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(r){t.error({err:r},"Failed to upload proposed steps")}}async reportBillableEvents(e,t){try{await this.sendRequest(`/${j}/billing/events`,{method:"POST",body:t,noLog:!0,retries:10,requestTimeoutMs:1e4})}catch(r){e.error({err:r},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${j}/test-fragments/${e}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return ef.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${j}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let r=await this.sendRequest(`/${j}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return tf.parse(r)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${j}/results/uploads`,{method:"POST",noLog:!0,retries:3,requestTimeoutMs:1e4});return nf.parse(e)}async startProcessingResultsUpload(e,t){let r=await this.sendRequest(`/${j}/results/uploads/${e}/process`,{method:"POST",noLog:!0,body:t,retries:3,requestTimeoutMs:1e4});return rf.parse(r)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${j}/knowledge-base/icons`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return mf.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${j}/knowledge-base/icons`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:5e3})}catch(r){t.error({err:r},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,t,r,o){let i=new URLSearchParams;i.set("base",r),i.set("head",o);let a=await this.sendRequest(`/${j}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return la.parse(a)}async getCommitFromGithub(e,t,r){let o=await this.sendRequest(`/${j}/git/github/${e}/${t}/commits/${r}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return la.parse(o)}async getMergeBaseCommitFromGitlab(e,t,r){let o=new URLSearchParams;o.set("base",t),o.set("head",r);let i=await this.sendRequest(`/${j}/git/gitlab/${e}/merge-base-commit?${o.toString()}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return la.parse(i)}async getCommitFromGitlab(e,t){let r=await this.sendRequest(`/${j}/git/gitlab/${e}/commits/${t}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return la.parse(r)}async getAgentConfig(){let e=await this.sendRequest(`/${j}/web-agent/agent-config`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return Op.record(Op.string(),Op.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${j}/quarantine`,{method:"GET",noLog:!0});return of.parse(e)}async quarantineTest(e,t){await this.sendRequest(`/${j}/quarantine`,{method:"POST",body:{testId:e,reason:t},noLog:!0,retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t){await this.sendRequest(`/${j}/quarantine/${e}`,{method:"DELETE",body:{reason:t},noLog:!0,retries:3,requestTimeoutMs:1e4})}};import{randomUUID as Ny}from"crypto";var Ll=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvent(e,t,r){try{return await this.apiClient.reportBillableEvents(e,[{event:t,timestamp:new Date().toISOString(),transactionId:r?.eventId??Ny(),properties:Od({},r)}])}catch(o){e.error({err:o},"Failed to report billable event")}}async reportCreditsUsed(e,t,r,o){if(r)try{return await this.apiClient.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:o?.eventId??Ny(),properties:Od({creditsUsed:r,usedBy:t},o)}])}catch(i){e.error({err:i},"Failed to report credits used")}}};var li=class{constructor(e,t){this.client=e;this.orgId=t}async acquireCacheLock(e,t){return this.client.acquireCacheLock(e,t)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}fetchIconKnowledgeBase(e){return this.client.fetchIconKnowledgeBase(e)}saveNewIcons(e,t){return this.client.saveNewIcons(e,t)}};import{Faker as IL,en as PL}from"@faker-js/faker";var ci="v1",di=class{httpClient;fakerInstance;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this)};ai={generate:this.sendAiGenerate.bind(this)};constructor(e){this.httpClient=e.httpClient,e.fakerSeed&&(this.fakerInstance=new IL({locale:PL}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${ci}/tools/ai/generate`,{method:"POST",body:t}).catch(r=>{throw r instanceof fn?new Error(r.rawError):new Error(`Failed to send AI generation: ${r.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${ci}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof fn?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${ci}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof fn?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${ci}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof fn?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${ci}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof fn?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${ci}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof fn?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as LL}from"zod";var pi=class extends nn{agentConfig;constructor(e,t){super(t),this.agentConfig=e}async rankChunksWithAi(e,t){let r={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${j}/web-agent/recommend-chunks-ai`,{method:"POST",body:r,signal:t.abortSignal});return Fh.parse(o)}async rankChunksWithRag(e,t){let r=await this.sendRequest(`/${j}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:ka,...e},signal:t.abortSignal});return Dh.parse(r)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${j}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return LL.string().parse(t)}async getElementLocation(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${j}/web-agent/locate-element`,{method:"POST",body:r,signal:t.abortSignal});return Bg.parse(o)}async getAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${j}/web-agent/assertion`,{method:"POST",body:r,signal:t.abortSignal});return jd.parse(o)}async getLintStepResult(e,t){let r={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${j}/web-agent/lint/step`,{method:"POST",body:r,signal:t.abortSignal});return Ug.parse(o)}async getVisualAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${j}/web-agent/visual-assertion`,{method:"POST",body:r,signal:t.abortSignal});return jd.parse(o)}async getAiActionCommand(e,t){let r=await this.sendRequest(`/${j}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Fg.parse(r)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${j}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let r=await this.sendRequest(`/${j}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return rd.parse(r)}async getReverseMappedDescription(e,t){let r=await this.sendRequest(`/${j}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return zg.parse(r)}async getTextExtraction(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${j}/web-agent/text-extraction`,{method:"POST",body:r,signal:t.abortSignal});return nd.parse(o)}async getTestResultClassification(e,t){let r=await this.sendRequest(`/${j}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return gd.parse(r)}async getExtractedKeywords(e,t){let r=await this.sendRequest(`/${j}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return Vh.parse(r)}async getAutohealingProposal(e,t){let r=await this.sendRequest(`/${j}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return km.parse(r)}async getFailureRecoveryProposal(e,t){let r=await this.sendRequest(`/${j}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return _m.parse(r)}async getIframeRegex(e,t){let r=await this.sendRequest(`/${j}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return gm.parse(r)}};var ui=class extends nn{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let r=await this.sendRequest(`/${j}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return fm.parse(r)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};function ky(n,e,t){return fetch(n,{method:"PUT",body:t,headers:{"Content-Type":e}})}var Ol=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:r,id:o}=await this.client.generateTestResultsUploadUrl(),i=await ky(r,"application/zip",t);if(!i.ok)throw new Error(`Failed to upload test results: ${await i.text()}`);let{runGroupId:a}=await this.client.startProcessingResultsUpload(o,{runGroupId:e});return a}};function mi({orgId:n,client:e,gitMetadata:t,alwaysSaveCache:r,noCache:o}){return o?new ns:new Mp(n,e,t,r)}var Mp=class{constructor(e,t,{gitMainBranch:r,gitBranchName:o,gitProtectedBranches:i,gitCommitTimestamp:a,lastCommitOnMainSha:s,lastCommitOnMainTimestamp:l},c){this.orgId=e;this.client=t;this.cacheHeaders={},r&&(this.cacheHeaders[Mg]=r),o&&(this.cacheHeaders[Ng]=o),a&&(this.cacheHeaders[kg]=a.toISOString()),s&&(this.cacheHeaders[_g]=s),l&&(this.cacheHeaders[Dg]=l.toISOString()),c?this.writeCaches=!0:o?this.writeCaches=!i.includes(o):this.writeCaches=!0}cacheHeaders;writeCaches;async saveStepCacheEntries({entries:e,testId:t,logger:r}){if(!this.writeCaches){r.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){r.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let{steps:t,beforeSteps:r,afterSteps:o}=e.stepLists,i=await this.client.getStepCacheForTest({testId:e.testId,steps:t,schemaVersion:e.schemaVersion},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping cache last used at update because branch is protected");return}for(let s of[t,r,o])s&&Ho({steps:s,stepCacheEntries:i,logger:e.logger});let{cachesToSave:a}=await mt({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:a,testId:e.testId},this.cacheHeaders)}};import Dk from"path";import{Server as ok}from"socket.io";var OL=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return async()=>{e.info({sessionId:r},"Cancel event received");let o=t.getSession(r);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},_y={event:"cancel",createHandler:OL};var ML=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return async(o,i)=>{let a=t.getSession(r);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let c=(await s.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:c},"Fetched a11y tree from the browser"),i({a11yTree:c})}catch(l){e.error({err:l},"Error fetching a11y tree from the browser"),i({err:l.message})}}},Dy={event:"fetchA11yTree",createHandler:ML};var NL=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return async(o,i)=>{let a=t.getSession(r);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let l=await s.html();i({html:l})}catch(l){e.error({err:l},"Error fetching DOM from the browser"),l.name==="TimeoutError"?i({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):i({err:l.message})}}},Fy={event:"fetchDom",createHandler:NL};var kL=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return o=>{e.info({sessionId:r,reason:o},`Disconnect event received (${o})`),t.removeSession(r,e)}},Uy={event:"disconnect",createHandler:kL};function Nn(n){let{result:e,nestedResults:t}=n;if(!n.nestedResults.length)return;let{firstMetadata:r,lastMetadata:o}=_L(t);DL(e,r,o);let i=[...n.asyncTasks];n.asyncTasks.push((async()=>{try{await FL(i,e,r,o)}catch(a){n.logger.error({result:n.result,err:a},"Error hoisting scalar result metadata")}})())}function _L(n){let e=n[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertion){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){t=e;break}e=e.results[e.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let r=n[n.length-1],o;for(;;){switch(r.type){case"PRESET_ACTION":{o=r;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":if(!r.results.length){o=r;break}r=r.results[r.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function DL(n,e,t){e&&(n.beforeUrl=e.beforeUrl),t&&(n.afterUrl=t.afterUrl,n.data=t.data,t.status!=="SUCCESS"&&(n.message=t.message))}async function FL(n,e,t,r){await Promise.allSettled(n),t&&(e.beforeSnapshot=t.beforeSnapshot),r&&(e.afterSnapshot=r.afterSnapshot)}import _a from"os";import UL from"v8";var By,kn,BL=_a.platform(),zL=_a.cpus().map(n=>({model:n.model,speed:n.speed}));function zy(n){let e=()=>{try{let t=!1,r=HL(),o=jL();r.freeMemory<1e6&&(t=!0);let i=UL.getHeapStatistics(),a=i.used_heap_size,s=i.heap_size_limit;a/s>.9&&(t=!0),t?n.warn({memory:r,cpu:o,heapStats:i},"Critical resource usage metrics detected"):n.debug({memory:r,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,1e4),cpuMetadata:zL,platform:BL}}function HL(){let n=_a.totalmem(),e=_a.freemem(),t=n-e;return{totalMemory:n,freeMemory:e,usedMemory:t}}function jL(){let n=_a.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of n)t.user+=o.times.user,t.nice+=o.times.nice,t.sys+=o.times.sys,t.idle+=o.times.idle,t.irq+=o.times.irq;if(t.total=t.user+t.nice+t.sys+t.idle+t.irq,!kn)return kn=t,null;let r={user:t.user-kn.user,nice:t.nice-kn.nice,sys:t.sys-kn.sys,idle:t.idle-kn.idle,irq:t.irq-kn.irq,total:t.total-kn.total};return By={measurementTime:e,intervalMs:e-kn.measurementTime,user:r.user/r.total*100,nice:r.nice/r.total*100,sys:r.sys/r.total*100,idle:r.idle/r.total*100,irq:r.irq/r.total*100,total:100-r.idle/r.total*100},kn=t,By}import{randomUUID as JL}from"crypto";import{faker as $L}from"@faker-js/faker";import GL from"assert";import WL from"axios";import*as VL from"child_process";import qL from"moment";import*as KL from"otpauth";import YL from"pg";async function Hy(n){let e;try{e=new URL(n.url).hostname}catch{}let t=[];return n.headers.getSetCookie()?.forEach(r=>{let o=Bs(r,e);t.push(...o)}),t}var XL=Object.getPrototypeOf(async function(){}).constructor;async function jy(n,e,t){let r=e.code;e.options.fragment&&(r=`return ${e.code}`);let{env:o}=e.bindings,i=e.tools,a={},s=(f,S)=>{o[f]=S,a[f]=S},l={},c=(f,S)=>{o[f]=S,l[f]=S},d;r.includes("Octokit")&&(d=(await import("@octokit/rest")).Octokit);let p;r.includes("createAppAuth")&&(p=(await import("@octokit/auth-app")).createAppAuth);let u=async()=>await Promise.resolve(new XL("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai",r)(WL,qL,i.fakerInstance??$L,GL,YL,d,p,KL,VL,Hy,o,s,c,S=>i.sms.send(S),S=>i.sms.fetchLatest(S),i.email,i.sms,i.ai)),m=!0,h,g;try{h=await z(u(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal})}catch(f){t.error({err:f,env:o,evalCode:r},`[${n}] Error executing code: ${f}`),m=!1,f instanceof wr?g=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:g=f instanceof Error?f.message:`${f}`}return{result:h,variableUpdates:a,persistentVariableUpdates:l,success:m,error:g}}async function $y({code:n,fragment:e,context:t,localTools:r,logger:o,signal:i,timeoutMs:a=mr}){let s=JL(),l=await jy(s,{code:n,options:{fragment:e,timeoutMs:a},bindings:t.toObjectCopy(),tools:r,signal:i},o);return y.debug(`[${s}] Got execution result: ${JSON.stringify(l)}`),l}import{createHmac as QL,randomUUID as ZL}from"crypto";import eO from"fetch-retry";var tO=eO(global.fetch,{retries:3,retryOn:function(n,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(n){return Math.pow(2,n)*500}}),Gy=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,Wy=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function Vy({orgId:n,code:e,fragment:t,context:r,timeoutMs:o=mr,retries:i=2,signal:a,logger:s}){if(!Gy)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let l,c,d=0;if(!Wy)throw new Error("Missing lambda auth secret.");let p=QL("sha256",Wy).update(n).digest("hex");for(;d<=i;){d++,a?.throwIfAborted();let m={id:ZL(),orgId:n,momenticLambdaAuthHash:p,code:e,fragment:t,state:r.toObjectCopy(),timeoutMs:o};try{if(l=await z(tO(Gy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!l)throw new Error("Got empty response from code evaluation server");if(!l.ok)throw new Error(`Code evaluation server returned error code ${l.status}`);c=void 0;break}catch(h){c=h}}if(c)throw s.error({err:c},"Failed to evaluate code remotely"),c;if(!l)throw new Error(`An unexpected code evaluation error occurred${c?`: ${c}`:""}`);let u;try{u=tg.parse(await l.json())}catch(m){throw new Error(`Code evaluation server returned invalid response: ${m}`)}if(u.error)throw new Error(`Code evaluation error: ${u.error}`);return u}async function io(n){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await Vy(n);else if(n.localTools)e=await $y({...n,localTools:n.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
|
|
41
|
+
${r.map(o=>o.configFilePath)}`);if(r.length===0)throw new Error("No valid Momentic project file available.");return y.debug(`Found valid project configuration at ${r[0].configFilePath}`),r[0]}function lL(n){let e=aL(n);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(i=>(i.endsWith("/")||(i+="/"),`${i}*${ni}`)),r=br(t,{absolute:!1,cwd:Ep(),dotRelative:!1,maxDepth:Tp,nodir:!0}),o=[];for(let i of r){let a=oo.join(Ep(),i),s=xp(a);s&&o.push({configFilePath:a,config:s,rootDir:Cy(a)})}return o}function Cp(n){if(n){n=oo.resolve(n);let t=xp(n);return t||(console.error(`No valid Momentic project file found at ${n}.`),process.exit(1)),[{config:t,configFilePath:n,rootDir:oo.dirname(n)}]}if(JP(xy)){let t=lL(xy);if(t)return t}return sL()}function ri(n,e){let t=Ry.stringify(n);eL(e,t)}import oi from"fs";import Rp from"path";import{z as Ap}from"zod";var Iy="golden/visual-diff",Py="reports",Ly="test-results";var cL=Ap.object({width:Ap.number(),height:Ap.number()}),ii=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,t){let r=Rp.join(e.rootDir,e.config.goldenFileDir??Iy);this.defaultGoldenScreenshotDir=r,this.regenerateGoldenFiles=t}async prepareGoldenScreenshotForComparison(e,t,r){if(t.screenshot?.data?.startsWith("https://")){let a=await fetch(t.screenshot.data);return{buffer:Buffer.from(await a.arrayBuffer()),width:t.screenshot.width,height:t.screenshot.height}}let o=t.screenshot?.data;o||(o=Rp.join(this.defaultGoldenScreenshotDir,`${t.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return oi.mkdirSync(Rp.dirname(o),{recursive:!0}),oi.writeFileSync(o,r.buffer),oi.writeFileSync(i,JSON.stringify({width:r.width,height:r.height})),{buffer:Buffer.from(r.buffer),width:r.width,height:r.height};if(oi.existsSync(o)){let a=oi.readFileSync(o),s=cL.parse(JSON.parse(oi.readFileSync(i,"utf-8")));return{buffer:a,width:s.width,height:s.height}}else throw new R("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};var ai=class{flags;constructor(e){this.flags={auto_expand_iframes:e.browser?.autoExpandIframes??!1,rag_v2:e.ai?.aiPageFiltering??!1,faker_constant_seed:e.advanced?.fakerConstantSeed??!1,disable_secondary_cache_resolution:e.browser?.disableSecondaryCacheResolution??!1,global_locator_redirect:e.browser?.globalLocatorRedirect??!0,visual_actions:e.browser?.visualActions??!1,mini_model_initial_assertion:!1,mini_model_initial_locator:!1,show_test_plans:!1,icon_knowledge_base:!1,disable_clickhouse_caches:!1,disable_clickhouse_last_updated_endpoint:!1}}isBooleanFlagEnabled(e){return this.flags[e]??!1}getAllFlags(){return{...this.flags}}getFlagPayload(e){}async refresh(){}};import dL from"simple-git";var Re=dL();function Il(n){if(n.startsWith("git@")){let e=n.split(":");if(e.length===2){let t=e[1].replace(".git","").split("/");if(t.length===2){let r=t[0],o=t[1];return`${r}/${o}`}}}else if(n.startsWith("http")||n.startsWith("https")){let t=new URL(n).pathname.split("/").filter(Boolean);if(t.length>=2){let r=t[0],o=t[1].replace(".git","");return`${r}/${o}`}}}async function Ae(n,e){try{return(await e).trim()}catch(t){n.error({err:t},"Failed to run git command");return}}function pL(){if(process.env.GITHUB_ACTION)return"GithubActions";if(process.env.GITLAB_CI)return"GitlabCI";if(process.env.CIRCLECI)return"CircleCI";if(process.env.BUILDKITE)return"Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return"AzureDevOps";if(process.env.PROJECT_ID&&process.env.BUILD_ID)return"GCPCloudBuild"}async function uL(n){let[e,t,r,o]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:t,gitCommitMessage:r,gitCommitAuthorName:o,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function mL(n){let[e,t,r]=await Promise.all([Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:t,gitCommitAuthorName:r,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function hL(n){let[e,t,r,o]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),s=t?Il(t):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:r,gitCommitAuthorName:o,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function gL(n){let[e,t,r]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Il(o):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:r,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function fL(n){let[e,t,r]=await Promise.all([Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Il(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:t,gitCommitAuthorName:r,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function SL(n,e){let[t,r,o,i,a,s,l,c]=await Promise.all([Ae(n,Re.revparse(["HEAD"])),Ae(n,Re.revparse(["--short","HEAD"])),Ae(n,Re.revparse(["--abbrev-ref","HEAD"])),Ae(n,Re.listRemote(["--get-url","origin"])),Ae(n,Re.show(["--no-patch","--format=%ci"])),Ae(n,Re.show(["-s","--pretty=%B"])),Ae(n,Re.show(["-s","--pretty=%an"])),e?Ae(n,Re.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0)]),d=c?await Ae(n,Re.show(["--no-patch","--format=%ci",c])):void 0,p=i?.includes("github.com"),u=i?.includes("gitlab.com"),m=i?Il(i):void 0;return{gitCommitSha:t,gitCommitShaShort:r,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:s,gitCommitAuthorName:l,lastCommitOnMainSha:c,lastCommitOnMainTimestamp:d?new Date(d):void 0,githubRepository:p?m:void 0,gitlabProjectPath:u?m:void 0,pipelineId:void 0}}async function yL(){let n=process.env._HEAD_REPO_URL;return{gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:n?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:n?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function bL(n){let e=n.config.gitProtectedBranches??[];return n.config.gitMainBranch&&e.push(n.config.gitMainBranch),{gitMainBranch:n.config.gitMainBranch,gitProtectedBranches:e}}async function Ip(n,e){let t=pL();if(!t)return SL(n,e);switch(t){case"GithubActions":return uL(n);case"GitlabCI":return mL(n);case"CircleCI":return hL(n);case"Buildkite":return gL(n);case"AzureDevOps":return fL(n);case"GCPCloudBuild":return yL()}}async function wL(n,e,t,r){let o=r;if(!r.gitCommitSha)return o;if(r.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp)){let i=await e.getMergeBaseCommitFromGitlab(t,r.gitMainBranch,r.gitCommitSha);o={...o,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName){let i=await e.getCommitFromGitlab(t,r.gitCommitSha);i&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??i.author.name,gitCommitMessage:o.gitCommitMessage??i.message})}return o}async function vL(n,e,t,r,o){let i=o;if(!o.gitCommitSha)return i;if(o.gitMainBranch&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)){let a=await e.getMergeBaseCommitFromGithub(t,r,o.gitMainBranch,o.gitCommitSha);i={...i,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName){let a=await e.getCommitFromGithub(t,r,o.gitCommitSha);a&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??a.author.name,gitCommitMessage:i.gitCommitMessage??a.message})}return i}async function TL(n,e,t){try{if(t.githubRepository){let[r,o]=t.githubRepository.split("/");return await vL(n,e,r,o,t)}else if(t.gitlabProjectPath)return await wL(n,e,t.gitlabProjectPath,t)}catch(r){n.warn({err:r},"Failed to get remote git metadata")}return t}async function si(n,e,t){let r=await bL(t),o=await Ip(n,r.gitMainBranch),i={...r,...o};(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)&&i.gitBranchName===r.gitMainBranch&&(i.lastCommitOnMainSha=i.gitCommitSha,i.lastCommitOnMainTimestamp=i.gitCommitTimestamp);let a=await TL(n,e,i);return{...r,...o,...a}}import _k from"http";import{z as Op}from"zod";var j="v1",ka="2.10.2";var wr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Oy=n=>{let e=n.reason===void 0?new DOMException("This operation was aborted.","AbortError"):n.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function z(n,e){let{milliseconds:t,fallback:r,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a,s;if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);return new Promise((l,c)=>{if(e.signal){let{signal:p}=e;if(p.aborted)return c(Oy(p));s=()=>c(Oy(p)),p.addEventListener("abort",s)}let d=()=>{if(r)try{l(r())}catch(p){c(p)}else{typeof n.cancel=="function"&&Promise.resolve().then(()=>n.cancel()).catch(()=>{});let p=o instanceof Error?o:new wr(o??`Promise timed out after ${t}ms`);c(p)}};a=i.setTimeout(d,t),Promise.resolve(n).then(p=>l(p)).catch(p=>c(p))}).finally(()=>{i.clearTimeout(a),e.signal&&s&&e.signal.removeEventListener("abort",s)})}var Pl=class{limit;windowMs;userActions;constructor(e,t){this.limit=e,this.windowMs=t,this.userActions=new Map}_cleanup(e,t="DEFAULT_USER"){let r=Date.now(),o=`${t}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(s=>r-s<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,t="DEFAULT_USER"){let r=Date.now(),o=`${t}:${e}`;this._cleanup(t,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(r),!1)}};var Pp=["ability","able","aboard","about","above","accept","accident","according","account","accurate","acres","across","act","action","active","activity","actual","actually","add","addition","additional","adjective","adult","adventure","advice","affect","afraid","after","afternoon","again","against","age","ago","agree","ahead","aid","air","airplane","alike","alive","all","allow","almost","alone","along","aloud","alphabet","already","also","although","am","among","amount","ancient","angle","angry","animal","announced","another","answer","ants","any","anybody","anyone","anything","anyway","anywhere","apart","apartment","appearance","apple","applied","appropriate","are","area","arm","army","around","arrange","arrangement","arrive","arrow","art","article","as","aside","ask","asleep","at","ate","atmosphere","atom","atomic","attached","attack","attempt","attention","audience","author","automobile","available","average","avoid","aware","away","baby","back","bad","badly","bag","balance","ball","balloon","band","bank","bar","bare","bark","barn","base","baseball","basic","basis","basket","bat","battle","be","bean","bear","beat","beautiful","beauty","became","because","become","becoming","bee","been","before","began","beginning","begun","behavior","behind","being","believed","bell","belong","below","belt","bend","beneath","bent","beside","best","bet","better","between","beyond","bicycle","bigger","biggest","bill","birds","birth","birthday","bit","bite","black","blank","blanket","blew","blind","block","blood","blow","blue","board","boat","body","bone","book","border","born","both","bottle","bottom","bound","bow","bowl","box","boy","brain","branch","brass","brave","bread","break","breakfast","breath","breathe","breathing","breeze","brick","bridge","brief","bright","bring","broad","broke","broken","brother","brought","brown","brush","buffalo","build","building","built","buried","burn","burst","bus","bush","business","busy","but","butter","buy","by","cabin","cage","cake","call","calm","came","camera","camp","can","canal","cannot","cap","capital","captain","captured","car","carbon","card","care","careful","carefully","carried","carry","case","cast","castle","cat","catch","cattle","caught","cause","cave","cell","cent","center","central","century","certain","certainly","chain","chair","chamber","chance","change","changing","chapter","character","characteristic","charge","chart","check","cheese","chemical","chest","chicken","chief","child","children","choice","choose","chose","chosen","church","circle","circus","citizen","city","class","classroom","claws","clay","clean","clear","clearly","climate","climb","clock","close","closely","closer","cloth","clothes","clothing","cloud","club","coach","coal","coast","coat","coffee","cold","collect","college","colony","color","column","combination","combine","come","comfortable","coming","command","common","community","company","compare","compass","complete","completely","complex","composed","composition","compound","concerned","condition","congress","connected","consider","consist","consonant","constantly","construction","contain","continent","continued","contrast","control","conversation","cook","cookies","cool","copper","copy","corn","corner","correct","correctly","cost","cotton","could","count","country","couple","courage","course","court","cover","cow","cowboy","crack","cream","create","creature","crew","crop","cross","crowd","cry","cup","curious","current","curve","customs","cut","cutting","daily","damage","dance","danger","dangerous","dark","darkness","date","daughter","dawn","day","dead","deal","dear","death","decide","declared","deep","deeply","deer","definition","degree","depend","depth","describe","desert","design","desk","detail","determine","develop","development","diagram","diameter","did","die","differ","difference","different","difficult","difficulty","dig","dinner","direct","direction","directly","dirt","dirty","disappear","discover","discovery","discuss","discussion","disease","dish","distance","distant","divide","division","do","doctor","does","dog","doing","doll","dollar","done","donkey","door","dot","double","doubt","down","dozen","draw","drawn","dream","dress","drew","dried","drink","drive","driven","driver","driving","drop","dropped","drove","dry","duck","due","dug","dull","during","dust","duty","each","eager","ear","earlier","early","earn","earth","easier","easily","east","easy","eat","eaten","edge","education","effect","effort","egg","eight","either","electric","electricity","element","elephant","eleven","else","empty","end","enemy","energy","engine","engineer","enjoy","enough","enter","entire","entirely","environment","equal","equally","equator","equipment","escape","especially","essential","establish","even","evening","event","eventually","ever","every","everybody","everyone","everything","everywhere","evidence","exact","exactly","examine","example","excellent","except","exchange","excited","excitement","exciting","exclaimed","exercise","exist","expect","experience","experiment","explain","explanation","explore","express","expression","extra","eye","face","facing","fact","factor","factory","failed","fair","fairly","fall","fallen","familiar","family","famous","far","farm","farmer","farther","fast","fastened","faster","fat","father","favorite","fear","feathers","feature","fed","feed","feel","feet","fell","fellow","felt","fence","few","fewer","field","fierce","fifteen","fifth","fifty","fight","fighting","figure","fill","film","final","finally","find","fine","finest","finger","finish","fire","fireplace","firm","first","fish","five","fix","flag","flame","flat","flew","flies","flight","floating","floor","flow","flower","fly","fog","folks","follow","food","foot","football","for","force","foreign","forest","forget","forgot","forgotten","form","former","fort","forth","forty","forward","fought","found","four","fourth","fox","frame","free","freedom","frequently","fresh","friend","friendly","frighten","frog","from","front","frozen","fruit","fuel","full","fully","fun","function","funny","fur","furniture","further","future","gain","game","garage","garden","gas","gasoline","gate","gather","gave","general","generally","gentle","gently","get","getting","giant","gift","girl","give","given","giving","glad","glass","globe","go","goes","gold","golden","gone","good","goose","got","government","grabbed","grade","gradually","grain","grandfather","grandmother","graph","grass","gravity","gray","great","greater","greatest","greatly","green","grew","ground","group","grow","grown","growth","guard","guess","guide","gulf","gun","habit","had","hair","half","halfway","hall","hand","handle","handsome","hang","happen","happened","happily","happy","harbor","hard","harder","hardly","has","hat","have","having","hay","he","headed","heading","health","heard","hearing","heart","heat","heavy","height","held","hello","help","helpful","her","herd","here","herself","hidden","hide","high","higher","highest","highway","hill","him","himself","his","history","hit","hold","hole","hollow","home","honor","hope","horn","horse","hospital","hot","hour","house","how","however","huge","human","hundred","hung","hungry","hunt","hunter","hurried","hurry","hurt","husband","ice","idea","identity","if","ill","image","imagine","immediately","importance","important","impossible","improve","in","inch","include","including","income","increase","indeed","independent","indicate","individual","industrial","industry","influence","information","inside","instance","instant","instead","instrument","interest","interior","into","introduced","invented","involved","iron","is","island","it","its","itself","jack","jar","jet","job","join","joined","journey","joy","judge","jump","jungle","just","keep","kept","key","kids","kill","kind","kitchen","knew","knife","know","knowledge","known","label","labor","lack","lady","laid","lake","lamp","land","language","large","larger","largest","last","late","later","laugh","law","lay","layers","lead","leader","leaf","learn","least","leather","leave","leaving","led","left","leg","length","lesson","let","letter","level","library","lie","life","lift","light","like","likely","limited","line","lion","lips","liquid","list","listen","little","live","living","load","local","locate","location","log","lonely","long","longer","look","loose","lose","loss","lost","lot","loud","love","lovely","low","lower","luck","lucky","lunch","lungs","lying","machine","machinery","mad","made","magic","magnet","mail","main","mainly","major","make","making","man","managed","manner","manufacturing","many","map","mark","market","married","mass","massage","master","material","mathematics","matter","may","maybe","me","meal","mean","means","meant","measure","meat","medicine","meet","melted","member","memory","men","mental","merely","met","metal","method","mice","middle","might","mighty","mile","military","milk","mill","mind","mine","minerals","minute","mirror","missing","mission","mistake","mix","mixture","model","modern","molecular","moment","money","monkey","month","mood","moon","more","morning","most","mostly","mother","motion","motor","mountain","mouse","mouth","move","movement","movie","moving","mud","muscle","music","musical","must","my","myself","mysterious","nails","name","nation","national","native","natural","naturally","nature","near","nearby","nearer","nearest","nearly","necessary","neck","needed","needle","needs","negative","neighbor","neighborhood","nervous","nest","never","new","news","newspaper","next","nice","night","nine","no","nobody","nodded","noise","none","noon","nor","north","nose","not","note","noted","nothing","notice","noun","now","number","numeral","nuts","object","observe","obtain","occasionally","occur","ocean","of","off","offer","office","officer","official","oil","old","older","oldest","on","once","one","only","onto","open","operation","opinion","opportunity","opposite","or","orange","orbit","order","ordinary","organization","organized","origin","original","other","ought","our","ourselves","out","outer","outline","outside","over","own","owner","oxygen","pack","package","page","paid","pain","paint","pair","palace","pale","pan","paper","paragraph","parallel","parent","park","part","particles","particular","particularly","partly","parts","party","pass","passage","past","path","pattern","pay","peace","pen","pencil","people","per","percent","perfect","perfectly","perhaps","period","person","personal","pet","phrase","physical","piano","pick","picture","pictured","pie","piece","pig","pile","pilot","pine","pink","pipe","pitch","place","plain","plan","plane","planet","planned","planning","plant","plastic","plate","plates","play","pleasant","please","pleasure","plenty","plural","plus","pocket","poem","poet","poetry","point","pole","police","policeman","political","pond","pony","pool","poor","popular","population","porch","port","position","positive","possible","possibly","post","pot","potatoes","pound","pour","powder","power","powerful","practical","practice","prepare","present","president","press","pressure","pretty","prevent","previous","price","pride","primitive","principal","principle","printed","private","prize","probably","problem","process","produce","product","production","program","progress","promised","proper","properly","property","protection","proud","prove","provide","public","pull","pupil","pure","purple","purpose","push","put","putting","quarter","queen","question","quick","quickly","quiet","quietly","quite","rabbit","race","radio","railroad","rain","raise","ran","ranch","range","rapidly","rate","rather","raw","rays","reach","read","reader","ready","real","realize","rear","reason","recall","receive","recent","recently","recognize","record","red","refer","refused","region","regular","related","relationship","religious","remain","remarkable","remember","remove","repeat","replace","replied","report","represent","require","research","respect","rest","result","return","review","rhyme","rhythm","rice","rich","ride","riding","right","ring","rise","rising","river","road","roar","rock","rocket","rocky","rod","roll","roof","room","root","rope","rose","rough","round","route","row","rubbed","rubber","rule","ruler","run","running","rush","sad","saddle","safe","safety","said","sail","sale","salmon","salt","same","sand","sang","sat","satellites","satisfied","save","saved","saw","say","scale","scared","scene","school","science","scientific","scientist","score","screen","sea","search","season","seat","second","secret","section","see","seed","seeing","seems","seen","seldom","select","selection","sell","send","sense","sent","sentence","separate","series","serious","serve","service","sets","setting","settle","settlers","seven","several","shade","shadow","shake","shaking","shall","shallow","shape","share","sharp","she","sheep","sheet","shelf","shells","shelter","shine","shinning","ship","shirt","shoe","shoot","shop","shore","short","shorter","shot","should","shoulder","shout","show","shown","shut","sick","sides","sight","sign","signal","silence","silent","silk","silly","silver","similar","simple","simplest","simply","since","sing","single","sink","sister","sit","sitting","situation","six","size","skill","skin","sky","slabs","slave","sleep","slept","slide","slight","slightly","slip","slipped","slope","slow","slowly","small","smaller","smallest","smell","smile","smoke","smooth","snake","snow","so","soap","social","society","soft","softly","soil","solar","sold","soldier","solid","solution","solve","some","somebody","somehow","someone","something","sometime","somewhere","son","song","soon","sort","sound","source","south","southern","space","speak","special","species","specific","speech","speed","spell","spend","spent","spider","spin","spirit","spite","split","spoken","sport","spread","spring","square","stage","stairs","stand","standard","star","stared","start","state","statement","station","stay","steady","steam","steel","steep","stems","step","stepped","stick","stiff","still","stock","stomach","stone","stood","stop","stopped","store","storm","story","stove","straight","strange","stranger","straw","stream","street","strength","stretch","strike","string","strip","strong","stronger","struck","structure","struggle","stuck","student","studied","studying","subject","substance","success","successful","such","sudden","suddenly","sugar","suggest","suit","sum","summer","sun","sunlight","supper","supply","support","suppose","sure","surface","surprise","surrounded","swam","sweet","swept","swim","swimming","swing","swung","syllable","symbol","system","table","tail","take","taken","tales","talk","tall","tank","tape","task","taste","taught","tax","tea","teach","teacher","team","tears","teeth","telephone","television","tell","temperature","ten","tent","term","terrible","test","than","thank","that","thee","them","themselves","then","theory","there","therefore","these","they","thick","thin","thing","think","third","thirty","this","those","thou","though","thought","thousand","thread","three","threw","throat","through","throughout","throw","thrown","thumb","thus","thy","tide","tie","tight","tightly","till","time","tin","tiny","tip","tired","title","to","tobacco","today","together","told","tomorrow","tone","tongue","tonight","too","took","tool","top","topic","torn","total","touch","toward","tower","town","toy","trace","track","trade","traffic","trail","train","transportation","trap","travel","treated","tree","triangle","tribe","trick","tried","trip","troops","tropical","trouble","truck","trunk","truth","try","tube","tune","turn","twelve","twenty","twice","two","type","typical","uncle","under","underline","understanding","unhappy","union","unit","universe","unknown","unless","until","unusual","up","upon","upper","upward","us","use","useful","using","usual","usually","valley","valuable","value","vapor","variety","various","vast","vegetable","verb","vertical","very","vessels","victory","view","village","visit","visitor","voice","volume","vote","vowel","voyage","wagon","wait","walk","wall","want","war","warm","warn","was","wash","waste","watch","water","wave","way","we","weak","wealth","wear","weather","week","weigh","weight","welcome","well","went","were","west","western","wet","whale","what","whatever","wheat","wheel","when","whenever","where","wherever","whether","which","while","whispered","whistle","white","who","whole","whom","whose","why","wide","widely","wife","wild","will","willing","win","wind","window","wing","winter","wire","wise","wish","with","within","without","wolf","women","won","wonder","wonderful","wood","wooden","wool","word","wore","work","worker","world","worried","worry","worse","worth","would","wrapped","write","writer","writing","written","wrong","wrote","yard","year","yellow","yes","yesterday","yet","you","young","younger","your","yourself","youth","zero","zebra","zipper","zoo","zulu"];function My(n){return new Array(n).fill(0).map(()=>Pp[Math.floor(Math.random()*Pp.length)]).join("-")}var EL=9e4,xL=3,CL=1500,RL=15e3,fn=class extends Error{status;rawError;constructor(e,t,r,o={}){super(r,o),this.status=e,this.rawError=t}};async function AL(n){return n.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Lp=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return ka&&(e[Og]=ka),e}async sendRequest(e,t){let{retries:r=xL,requestTimeoutMs:o=EL,initialRetryDelayMs:i=CL,maxRetryDelayMs:a=RL}=t,s=r,l=r,c,d={path:e,baseUrl:this.baseUrl,method:t.method};for(;s>0;)try{return s--,await this.sendSingleRequestHelper(e,t,o)}catch(p){if(c=p,p instanceof fn&&p.status>=400&&p.status<500)throw p;if(p instanceof Error&&p.name==="AbortError"&&(c=new wr),s===0)throw c;let u=l-s,m=Math.min(i*Math.pow(2,u-1),a);await new Promise(h=>setTimeout(h,m))}throw this.logger.warn({...d,err:c},"Got fatal error response from Momentic server"),c}async sendSingleRequestHelper(e,t,r){let o={path:e,baseUrl:this.baseUrl,method:t.method},i=new AbortController,a=setTimeout(()=>i.abort(),r),s=()=>i.abort();t.signal&&t.signal.addEventListener("abort",s);let l={...this.getHeaders(),...t.extraHeaders};try{let c=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:l,signal:i.signal});if(!c.ok){let p=await AL(c);throw new fn(c.status,p,`Request to ${t.method} ${e} failed with status ${c.status}: ${p}`)}let d;if(c.status===204)d={};else{let p=await c.text();try{d=JSON.parse(p)}catch{d=p}}return this.logger&&!t.noLog&&d&&this.logger.debug({result:d,status:c.status,...o},"Got response from Momentic server"),d}finally{clearTimeout(a),t.signal&&t.signal.removeEventListener("abort",s)}}},nn=class extends Lp{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var Xe=class extends nn{constructor(e){super(e)}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${j}/auth/check`,{method:"GET",noLog:!0,retries:10,requestTimeoutMs:5e3});return Jg.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${j}/runs/status`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:1e4});return qg.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${j}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return jg.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${j}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let r=await this.sendRequest(`/${j}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return $g.parse(r)}async queueTests(e){let t=await this.sendRequest(`/${j}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Hg.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${j}/screenshots`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:5e3});return Xg.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${j}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Qg.parse(e)}async acquireCacheLock(e,t){let r=await this.sendRequest(`/${j}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return sf.parse(r)}async releaseCacheLock(e){await this.sendRequest(`/${j}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${j}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${j}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${j}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${j}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Zg.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},r=await this.sendRequest(`/${j}/run-groups/status`,{method:"POST",body:t,noLog:!0,retries:3,requestTimeoutMs:5e3});return Oh.array().parse(r)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${j}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(r){t.error({err:r},"Failed to upload proposed steps")}}async reportBillableEvents(e,t){try{await this.sendRequest(`/${j}/billing/events`,{method:"POST",body:t,noLog:!0,retries:10,requestTimeoutMs:1e4})}catch(r){e.error({err:r},"Failed to report billable event")}}async fetchTestFragment(e){let t=await this.sendRequest(`/${j}/test-fragments/${e}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return ef.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${j}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let r=await this.sendRequest(`/${j}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return tf.parse(r)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${j}/results/uploads`,{method:"POST",noLog:!0,retries:3,requestTimeoutMs:1e4});return nf.parse(e)}async startProcessingResultsUpload(e,t){let r=await this.sendRequest(`/${j}/results/uploads/${e}/process`,{method:"POST",noLog:!0,body:t,retries:3,requestTimeoutMs:1e4});return rf.parse(r)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${j}/knowledge-base/icons`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return mf.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${j}/knowledge-base/icons`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:5e3})}catch(r){t.error({err:r},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,t,r,o){let i=new URLSearchParams;i.set("base",r),i.set("head",o);let a=await this.sendRequest(`/${j}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return la.parse(a)}async getCommitFromGithub(e,t,r){let o=await this.sendRequest(`/${j}/git/github/${e}/${t}/commits/${r}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return la.parse(o)}async getMergeBaseCommitFromGitlab(e,t,r){let o=new URLSearchParams;o.set("base",t),o.set("head",r);let i=await this.sendRequest(`/${j}/git/gitlab/${e}/merge-base-commit?${o.toString()}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return la.parse(i)}async getCommitFromGitlab(e,t){let r=await this.sendRequest(`/${j}/git/gitlab/${e}/commits/${t}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return la.parse(r)}async getAgentConfig(){let e=await this.sendRequest(`/${j}/web-agent/agent-config`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return Op.record(Op.string(),Op.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${j}/quarantine`,{method:"GET",noLog:!0});return of.parse(e)}async quarantineTest(e,t){await this.sendRequest(`/${j}/quarantine`,{method:"POST",body:{testId:e,reason:t},noLog:!0,retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t){await this.sendRequest(`/${j}/quarantine/${e}`,{method:"DELETE",body:{reason:t},noLog:!0,retries:3,requestTimeoutMs:1e4})}};import{randomUUID as Ny}from"crypto";var Ll=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvent(e,t,r){try{return await this.apiClient.reportBillableEvents(e,[{event:t,timestamp:new Date().toISOString(),transactionId:r?.eventId??Ny(),properties:Od({},r)}])}catch(o){e.error({err:o},"Failed to report billable event")}}async reportCreditsUsed(e,t,r,o){if(r)try{return await this.apiClient.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:o?.eventId??Ny(),properties:Od({creditsUsed:r,usedBy:t},o)}])}catch(i){e.error({err:i},"Failed to report credits used")}}};var li=class{constructor(e,t){this.client=e;this.orgId=t}async acquireCacheLock(e,t){return this.client.acquireCacheLock(e,t)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}fetchIconKnowledgeBase(e){return this.client.fetchIconKnowledgeBase(e)}saveNewIcons(e,t){return this.client.saveNewIcons(e,t)}};import{Faker as IL,en as PL}from"@faker-js/faker";var ci="v1",di=class{httpClient;fakerInstance;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this)};ai={generate:this.sendAiGenerate.bind(this)};constructor(e){this.httpClient=e.httpClient,e.fakerSeed&&(this.fakerInstance=new IL({locale:PL}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let t=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${ci}/tools/ai/generate`,{method:"POST",body:t}).catch(r=>{throw r instanceof fn?new Error(r.rawError):new Error(`Failed to send AI generation: ${r.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${ci}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof fn?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${ci}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof fn?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${ci}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof fn?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${ci}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof fn?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${ci}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof fn?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as LL}from"zod";var pi=class extends nn{agentConfig;constructor(e,t){super(t),this.agentConfig=e}async rankChunksWithAi(e,t){let r={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${j}/web-agent/recommend-chunks-ai`,{method:"POST",body:r,signal:t.abortSignal});return Fh.parse(o)}async rankChunksWithRag(e,t){let r=await this.sendRequest(`/${j}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:ka,...e},signal:t.abortSignal});return Dh.parse(r)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${j}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return LL.string().parse(t)}async getElementLocation(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${j}/web-agent/locate-element`,{method:"POST",body:r,signal:t.abortSignal});return Bg.parse(o)}async getAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${j}/web-agent/assertion`,{method:"POST",body:r,signal:t.abortSignal});return jd.parse(o)}async getLintStepResult(e,t){let r={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${j}/web-agent/lint/step`,{method:"POST",body:r,signal:t.abortSignal});return Ug.parse(o)}async getVisualAssertionResult(e,t){let r={...e,disableCache:!!t.disableCache,useConsensus:!!t.useConsensus,attemptNumber:t.attemptNumber,loggerTags:t.loggerTags,useMemory:t.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${j}/web-agent/visual-assertion`,{method:"POST",body:r,signal:t.abortSignal});return jd.parse(o)}async getAiActionCommand(e,t){let r=await this.sendRequest(`/${j}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Fg.parse(r)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${j}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal})}async getMultiturnAiActionEvaluation(e,t){let r=await this.sendRequest(`/${j}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return rd.parse(r)}async getReverseMappedDescription(e,t){let r=await this.sendRequest(`/${j}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return zg.parse(r)}async getTextExtraction(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${j}/web-agent/text-extraction`,{method:"POST",body:r,signal:t.abortSignal});return nd.parse(o)}async getTestResultClassification(e,t){let r=await this.sendRequest(`/${j}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return gd.parse(r)}async getExtractedKeywords(e,t){let r=await this.sendRequest(`/${j}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return Vh.parse(r)}async getAutohealingProposal(e,t){let r=await this.sendRequest(`/${j}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return km.parse(r)}async getFailureRecoveryProposal(e,t){let r=await this.sendRequest(`/${j}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return _m.parse(r)}async getIframeRegex(e,t){let r=await this.sendRequest(`/${j}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return gm.parse(r)}};var ui=class extends nn{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let r=await this.sendRequest(`/${j}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return fm.parse(r)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};function ky(n,e,t){return fetch(n,{method:"PUT",body:t,headers:{"Content-Type":e}})}var Ol=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:r,id:o}=await this.client.generateTestResultsUploadUrl(),i=await ky(r,"application/zip",t);if(!i.ok)throw new Error(`Failed to upload test results: ${await i.text()}`);let{runGroupId:a}=await this.client.startProcessingResultsUpload(o,{runGroupId:e});return a}};function mi({orgId:n,client:e,gitMetadata:t,alwaysSaveCache:r,noCache:o}){return o?new ns:new Mp(n,e,t,r)}var Mp=class{constructor(e,t,{gitMainBranch:r,gitBranchName:o,gitProtectedBranches:i,gitCommitTimestamp:a,lastCommitOnMainSha:s,lastCommitOnMainTimestamp:l},c){this.orgId=e;this.client=t;this.cacheHeaders={},r&&(this.cacheHeaders[Mg]=r),o&&(this.cacheHeaders[Ng]=o),a&&(this.cacheHeaders[kg]=a.toISOString()),s&&(this.cacheHeaders[_g]=s),l&&(this.cacheHeaders[Dg]=l.toISOString()),c?this.writeCaches=!0:o?this.writeCaches=!i.includes(o):this.writeCaches=!0}cacheHeaders;writeCaches;async saveStepCacheEntries({entries:e,testId:t,logger:r}){if(!this.writeCaches){r.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:e,testId:t},this.cacheHeaders)}catch(o){r.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let{steps:t,beforeSteps:r,afterSteps:o}=e.stepLists,i=await this.client.getStepCacheForTest({testId:e.testId,steps:t,schemaVersion:e.schemaVersion},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping cache last used at update because branch is protected");return}for(let s of[t,r,o])s&&Ho({steps:s,stepCacheEntries:i,logger:e.logger});let{cachesToSave:a}=await mt({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:a,testId:e.testId},this.cacheHeaders)}};import Dk from"path";import{Server as ok}from"socket.io";var OL=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return async()=>{e.info({sessionId:r},"Cancel event received");let o=t.getSession(r);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},_y={event:"cancel",createHandler:OL};var ML=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return async(o,i)=>{let a=t.getSession(r);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let c=(await s.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:c},"Fetched a11y tree from the browser"),i({a11yTree:c})}catch(l){e.error({err:l},"Error fetching a11y tree from the browser"),i({err:l.message})}}},Dy={event:"fetchA11yTree",createHandler:ML};var NL=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return async(o,i)=>{let a=t.getSession(r);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let l=await s.html();i({html:l})}catch(l){e.error({err:l},"Error fetching DOM from the browser"),l.name==="TimeoutError"?i({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):i({err:l.message})}}},Fy={event:"fetchDom",createHandler:NL};var kL=({metadata:n,logger:e,globalE2eStateManager:t})=>{let{sessionId:r}=n;return o=>{e.info({sessionId:r,reason:o},`Disconnect event received (${o})`),t.removeSession(r,e)}},Uy={event:"disconnect",createHandler:kL};function Nn(n){let{result:e,nestedResults:t}=n;if(!n.nestedResults.length)return;let{firstMetadata:r,lastMetadata:o}=_L(t);DL(e,r,o);let i=[...n.asyncTasks];n.asyncTasks.push((async()=>{try{await FL(i,e,r,o)}catch(a){n.logger.error({result:n.result,err:a},"Error hoisting scalar result metadata")}})())}function _L(n){let e=n[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertion){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){t=e;break}e=e.results[e.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let r=n[n.length-1],o;for(;;){switch(r.type){case"PRESET_ACTION":{o=r;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":if(!r.results.length){o=r;break}r=r.results[r.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function DL(n,e,t){e&&(n.beforeUrl=e.beforeUrl),t&&(n.afterUrl=t.afterUrl,n.data=t.data,t.status!=="SUCCESS"&&(n.message=t.message))}async function FL(n,e,t,r){await Promise.allSettled(n),t&&(e.beforeSnapshot=t.beforeSnapshot),r&&(e.afterSnapshot=r.afterSnapshot)}import _a from"os";import UL from"v8";var By,kn,BL=_a.platform(),zL=_a.cpus().map(n=>({model:n.model,speed:n.speed}));function zy(n){let e=()=>{try{let t=!1,r=HL(),o=jL();r.freeMemory<1e6&&(t=!0);let i=UL.getHeapStatistics(),a=i.used_heap_size,s=i.heap_size_limit;a/s>.9&&(t=!0),t?n.warn({memory:r,cpu:o,heapStats:i},"Critical resource usage metrics detected"):n.debug({memory:r,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,1e4),cpuMetadata:zL,platform:BL}}function HL(){let n=_a.totalmem(),e=_a.freemem(),t=n-e;return{totalMemory:n,freeMemory:e,usedMemory:t}}function jL(){let n=_a.cpus(),e=Date.now(),t={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of n)t.user+=o.times.user,t.nice+=o.times.nice,t.sys+=o.times.sys,t.idle+=o.times.idle,t.irq+=o.times.irq;if(t.total=t.user+t.nice+t.sys+t.idle+t.irq,!kn)return kn=t,null;let r={user:t.user-kn.user,nice:t.nice-kn.nice,sys:t.sys-kn.sys,idle:t.idle-kn.idle,irq:t.irq-kn.irq,total:t.total-kn.total};return By={measurementTime:e,intervalMs:e-kn.measurementTime,user:r.user/r.total*100,nice:r.nice/r.total*100,sys:r.sys/r.total*100,idle:r.idle/r.total*100,irq:r.irq/r.total*100,total:100-r.idle/r.total*100},kn=t,By}import{randomUUID as JL}from"crypto";import{faker as $L}from"@faker-js/faker";import GL from"assert";import WL from"axios";import*as VL from"child_process";import qL from"moment";import*as KL from"otpauth";import YL from"pg";async function Hy(n){let e;try{e=new URL(n.url).hostname}catch{}let t=[];return n.headers.getSetCookie()?.forEach(r=>{let o=Bs(r,e);t.push(...o)}),t}var XL=Object.getPrototypeOf(async function(){}).constructor;async function jy(n,e,t){let r=e.code;e.options.fragment&&(r=`return ${e.code}`);let{env:o}=e.bindings,i=e.tools,a={},s=(f,S)=>{o[f]=S,a[f]=S},l={},c=(f,S)=>{o[f]=S,l[f]=S},d;r.includes("Octokit")&&(d=(await import("@octokit/rest")).Octokit);let p;r.includes("createAppAuth")&&(p=(await import("@octokit/auth-app")).createAppAuth);let u=async()=>await Promise.resolve(new XL("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai",r)(WL,qL,i.fakerInstance??$L,GL,YL,d,p,KL,VL,Hy,o,s,c,S=>i.sms.send(S),S=>i.sms.fetchLatest(S),i.email,i.sms,i.ai)),m=!0,h,g;try{h=await z(u(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal})}catch(f){t.error({err:f,env:o,evalCode:r},`[${n}] Error executing code: ${f}`),m=!1,f instanceof wr?g=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:g=f instanceof Error?f.message:`${f}`}return{result:h,variableUpdates:a,persistentVariableUpdates:l,success:m,error:g}}async function $y({code:n,fragment:e,context:t,localTools:r,logger:o,signal:i,timeoutMs:a=mr}){let s=JL(),l=await jy(s,{code:n,options:{fragment:e,timeoutMs:a},bindings:t.toObjectCopy(),tools:r,signal:i},o);return y.debug(`[${s}] Got execution result: ${JSON.stringify(l)}`),l}import{createHmac as QL,randomUUID as ZL}from"crypto";import eO from"fetch-retry";var tO=eO(global.fetch,{retries:3,retryOn:function(n,e,t){return!!(e!==null||t&&t.status>=500)},retryDelay:function(n){return Math.pow(2,n)*500}}),Gy=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,Wy=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function Vy({orgId:n,code:e,fragment:t,context:r,timeoutMs:o=mr,retries:i=2,signal:a,logger:s}){if(!Gy)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let l,c,d=0;if(!Wy)throw new Error("Missing lambda auth secret.");let p=QL("sha256",Wy).update(n).digest("hex");for(;d<=i;){d++,a?.throwIfAborted();let m={id:ZL(),orgId:n,momenticLambdaAuthHash:p,code:e,fragment:t,state:r.toObjectCopy(),timeoutMs:o};try{if(l=await z(tO(Gy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!l)throw new Error("Got empty response from code evaluation server");if(!l.ok)throw new Error(`Code evaluation server returned error code ${l.status}`);c=void 0;break}catch(h){c=h}}if(c)throw s.error({err:c},"Failed to evaluate code remotely"),c;if(!l)throw new Error(`An unexpected code evaluation error occurred${c?`: ${c}`:""}`);let u;try{u=tg.parse(await l.json())}catch(m){throw new Error(`Code evaluation server returned invalid response: ${m}`)}if(u.error)throw new Error(`Code evaluation error: ${u.error}`);return u}async function io(n){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await Vy(n);else if(n.localTools)e=await $y({...n,localTools:n.localTools});else throw new Error("No code evaluation environment available");if(e.error){let t=`Failed to evaluate code:
|
|
42
42
|
${e.error}
|
|
43
43
|
Code received:
|
|
44
44
|
${n.code}`;throw n.logger.error({err:e.error,code:n.code,env:n.context.toObjectCopy()},t),new Error(t)}if(e.variableUpdates)for(let[t,r]of Object.entries(e.variableUpdates))n.context.setVariable(t,r);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await n.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[t,r]of Object.entries(e.persistentVariableUpdates))n.context.setVariable(t,r)}return e.result}import{set as nO}from"lodash-es";async function Ft(n){let{orgId:e,s:t,context:r,logger:o,signal:i,flagStore:a,retries:s=2,timeoutMs:l=mr,allowUndefined:c=!1}=n,d=/{{(.*?)}}/g,p=t.matchAll(d),u=t;for(let m of p){if(m.length<2)continue;let h=m[1].trim(),g;try{g=await io({orgId:e,code:h,fragment:!0,context:r,timeoutMs:l,logger:o,retries:s,localTools:n.localTools,signal:i,flagStore:a})}catch(S){throw o.error({err:S,value:t},"Error evaluating template string"),S}if(g===void 0&&!c)throw new R("UserConfigurationError",`Template fragment '${h}' evaluated to undefined. Please ensure that the variable name is spelled correctly and it is only referenced after being assigned a value.`);let f=typeof g=="string"?g:`${g}`;f=f.replaceAll(/\$/g,"$$$$"),u=u.replace(m[0],f)}return u}async function Ml(n){return qy(n)}async function qy({obj:n,bannedKeys:e,allowList:t,context:r,prefixPath:o=[],replacements:i=[],...a}){for(let s in n){if(e.includes(s))continue;let l=!1;if(t)if(t.includes(s))l=!0;else continue;let c=n[s],d=[...o,s];if(typeof c=="string"&&c.includes("{{")){let p=await Ft({s:c,context:r,...a});if(c===p)continue;i.push({path:d,original:c}),n[s]=p}else typeof c=="object"&&c!==null&&!Array.isArray(c)&&await qy({obj:c,bannedKeys:e,context:r,prefixPath:d,replacements:i,allowList:l?void 0:t,...a})}return i}function Ky(n,e){for(let{path:t,original:r}of e)nO(n,t,r)}import rO from"fetch-retry";var l8=process.env.MAILINATOR_API_KEY,c8=rO(global.fetch,{retryOn:function(n,e,t){return n>3?!1:!!(e!==null||t&&t.status>=400)},retryDelay:function(n){return 500}});import{hostname as cO}from"os";async function Yy(n){let{command:e,tracer:t,timeoutMs:r,targetingWrapper:o,disableCache:i,fixtures:a}=n,{logger:s,abortSignal:l}=a;if(e.target&&!dr(e.target))throw new Error("Element assertion with x/y is not supported yet");let c=e.assertion.type==="ELEMENT_EXISTENCE"&&e.assertion.negated&&(e.assertion.condition==="EXISTS"||e.assertion.condition==="VISIBLE"),d=Date.now(),p=0,u,m=500;for(;p<2||Date.now()-d<r;){p++,p>1&&await Y(m,l),l?.throwIfAborted();try{let{newTarget:h,elementInteractedDisplayString:g,result:f}=await o({ctx:a.ctx,tracer:t,command:e,target:e.target,cache:e.cache?.target,action:async S=>oO(S.locator,n),options:{...e,disableCache:i,disableGlobalLocatorRedirect:!0,source:Dr(e),allowZeroOpacityOverride:!0}});if(u={success:f.success,data:f.data,err:f.err,newTarget:h,elementInteractedDisplayString:g},!f.success){u=f,m=Math.min(m*2,1e4);continue}return u}catch(h){if(l?.throwIfAborted(),c)return{success:!0,thoughts:`The element described does not exist on the page: ${h.message}`};if(s.warn({err:h},"Element assertion ended in error, retrying..."),!(h instanceof R)||h.reason!="ActionFailureError")throw h;u={success:!1,err:h}}}if(!u)throw new Error(`Failed to evaluate manual element assertion in ${r}ms.`);return u}async function oO(n,{command:e,fixtures:t}){let r=e.assertion;await t.browser.highlight(n);let o=!0,i,a;switch(r.type){case"ELEMENT_CONTENT":{let l=await n.textContent()??"";if(a={elementTextContent:ze(l,500,!0)},!Nl(l,r.value,r.operation,!!r.negated)){let c=r.negated?Jt[r.operation]:Qt[r.operation];o=!1,i=new R("AssertionFailureError",`The content ${c} '${r.value}': ${l}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:ze(await n.evaluate(c=>c.cloneNode(!1).outerHTML),500,!0)};let l;try{l=await n.getAttribute(r.attr,{timeout:3e3})??""}catch(c){i=new R("AssertionFailureError",`The element does not have an attribute named ${r.attr}: ${c}`),o=!1;break}if(!Nl(l,r.value,r.operation,!!r.negated)){let c=r.negated?Jt[r.operation]:Qt[r.operation];o=!1,r.operation==="EXISTS"?i=new R("AssertionFailureError",`The attribute ${r.attr} ${c}`):i=new R("AssertionFailureError",`The attribute ${r.attr} ${c} '${r.value}': ${l}`)}break}case"ELEMENT_EXISTENCE":{switch(r.condition){case"VISIBLE":{o=await n.evaluate(async(c,d)=>{let p=Date.now();for(;Date.now()-p<d;){await new Promise(m=>setTimeout(m,250));let u=c.getBoundingClientRect();if(!(u.width===0||u.height===0)&&window.getComputedStyle(c).visibility!=="hidden"&&window.getComputedStyle(c).display!=="none")return!0}return!1},xn*1e3);break}case"EDITABLE":{o=await n.isEditable({timeout:xn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await n.isEnabled({timeout:xn*1e3});break}case"FOCUSED":{o=await n.evaluate(c=>c===document.activeElement);break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.condition)}if(o=r.negated?!o:o,!o){let l=r.negated?Kd[r.condition]:Yd[r.condition];i=new R("AssertionFailureError",`The element ${l}`)}break}case"ELEMENT_NAME":{let l=await n.evaluate(c=>c.tagName);if(!Nl(l,r.value,r.operation,!!r.negated)){let c=r.negated?Jt[r.operation]:Qt[r.operation];o=!1,i=new R("AssertionFailureError",`The element tag name ${c} '${r.value}': ${l}`)}break}case"ELEMENT_STYLE":{let l=await n.evaluate((c,d)=>window.getComputedStyle(c).getPropertyValue(d),r.property);if(!Nl(l,r.value,r.operation,!!r.negated)){let c=r.negated?Jt[r.operation]:Qt[r.operation];o=!1,r.operation==="EXISTS"?i=new R("AssertionFailureError",`The style property ${r.property} ${c}`):i=new R("AssertionFailureError",`The style property ${r.property} ${c} '${r.value}': ${l}`)}break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return{success:o,data:a,err:i}}function Nl(n,e,t,r){let o;switch(t){case"CONTAINS":{o=n.includes(e);break}case"EQUALS":{o=n.trim()===e.trim();break}case"STARTS_WITH":{o=n.trim().startsWith(e);break}case"EXISTS":{o=n.trim().length>0;break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return r?!o:o}import{Jimp as iO}from"jimp";async function Da(n,e){let t=await n.screenshot(e),r=await iO.fromBuffer(t);return{buffer:t,width:Math.ceil(r.bitmap.width??0),height:Math.ceil(r.bitmap.height??0)}}import{Jimp as Xy}from"jimp";import Np from"jpeg-js";import aO from"pixelmatch";async function Jy({ctx:n,tracer:e,command:t,disableCache:r,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(t.target&&!dr(t.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let l={clearHighlights:!0,hideCaret:!0},c;t.target?.elementDescriptor?c=(await i({ctx:n,tracer:e,command:t,target:t.target,cache:t.cache?.target??t.target?.a11yData,action:async D=>Da(o,{locator:D.locator,...l}),options:{...t,disableCache:r,disableGlobalLocatorRedirect:!0}})).result:c=await Da(o,l);let d=await s.prepareGoldenScreenshotForComparison(a,t,c);if((c.height!==d.height||c.width!==d.width)&&a.debug({currHeight:c.height,currWidth:c.width,savedHeight:d.height,savedWidth:d.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(c.height-d.height)>10||Math.abs(c.width-d.width)>10){let $=`${c.width}x${c.height}`,D=`${d.width}x${d.height}`;return{fail:!0,thoughts:`Current screenshot (${$}) does not match saved screenshot dimensions (${D}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:d.buffer,afterScreenshotOverride:c.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let p=await Xy.fromBuffer(c.buffer),u={width:c.width,height:c.height},m=await Xy.fromBuffer(d.buffer),h={width:d.width,height:d.height},g,f=u.width*u.height,S=h.width*h.height,b=Math.abs(u.height-h.height),w=Math.abs(u.width-h.width);if(f>S){let $=p.cover({w:h.width,h:h.height});c.buffer=await $.getBuffer("image/jpeg"),g="current",c.width=h.width,c.height=h.height}else if(S>f){let $=m.cover({w:u.width,h:u.height});d.buffer=await $.getBuffer("image/jpeg"),g="saved"}let T={data:Buffer.alloc(c.width*c.height*4),width:c.width,height:c.height},C=t.threshold??.1,A=aO(Np.decode(d.buffer).data,Np.decode(c.buffer).data,T.data,c.width,c.height,{threshold:C,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,k=A>C*100,O=`Visual diff of ${A.toFixed(2)}% detected, which is ${k?"over":"under"} the threshold of ${C*100}%.`;if(g&&(O+=` The ${g} screenshot was cropped since it was taller by ${b} pixels and wider by ${w} pixels.`),k)throw new R("ActionFailureError",O);return{fail:k,thoughts:O,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:Np.encode(T,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var sO=3e4;async function Qy({command:n,logger:e,baseUrl:t,fetchImplementation:r=fetch}){let o=n.timeout??sO/1e3,i=Object.fromEntries(Object.entries(n.headers||{}).filter(([m,h])=>m&&h)),a=new URLSearchParams;Object.entries(n.params||{}).filter(([m,h])=>m&&h).forEach(([m,h])=>{a.append(m,h)});let s=a.toString(),l;if($o(n.url)&&(l=n.url),t&&Go(n.url,t)&&(l=new URL(n.url,t).toString()),!l)throw new R("ActionFailureError",`Invalid URL: ${n.url}`);e.debug({url:l,searchParams:s,headers:i,body:n.body,method:n.method},"Making HTTP request");let d=await z((async()=>{let m=s?`${l}?${s}`:l;try{return await r(m,{headers:i,method:n.method,body:n.body})}catch(h){throw e.error({err:h},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${h}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new R("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok){let m;try{m=await d.text()}catch(h){m=`Failed to read response body: ${h}`}throw new R("ActionFailureError",`Fetch request failed with status ${d.status}: ${m}`)}let p={};d.headers.forEach((m,h)=>{p[h]=m});let u={status:d.status,headers:p};if(d.headers.get("content-type")?.includes("json"))try{u.json=await d.json()}catch{}else d.headers.get("content-type")?.includes("text")&&(u.text=await d.text());return u}var lO=5e3;async function kl({timeout:n=xn,...e}){let t=Date.now(),r=n*1e3,o=r+1e4,i,a=0,s=500;for(;a-t<r;){if(Date.now()-t>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let l=Date.now();i=await Zy(e),a=Date.now();let c=a-l;if(c>1e3&&e.logger.warn({pageAssertDuration:c},"Page assertion took longer than expected"),!i.success)await Y(s,e.signal),s=Math.min(Math.floor(s*1.5),lO);else return i}return i=await Zy(e),i}async function Zy({assertion:n,browser:e,autoExpandIframes:t}){switch(n.type){case"CONTENT":{let o,i=!1,a;try{let s;if(t){let l=await e.evaluateFunctionInAllFrames(eb,{value:n.value,negated:!!n.negated,returnHtml:!1});i=n.negated?l.every(c=>c.evaluation):l.some(c=>c.evaluation),s=l.find(c=>c.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:s}=await e.evaluateFunctionInPage(eb,{value:n.value,negated:!!n.negated,returnHtml:!0},"checking page content"));if(!i){let l=n.negated?Jt.CONTAINS:Qt.CONTAINS;a=new R("AssertionFailureError",`The page ${l} '${n.value}'.`),o=s}}catch(s){a=new R("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n.type)}}function eb({value:n,negated:e,returnHtml:t}){let r=document.documentElement.outerHTML,o=r.includes(n)===!e;return r.length>1e4&&(r=r.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&t?r:void 0}}var kp=async n=>{let{step:e,resolvedInputs:t}=n.moduleParams,{logger:r,context:o,storage:i,codeEvalTools:a,controller:s}=n.fixtures,l=s.browser,{orgId:c,runId:d}=n.inputs,p=s.executeAbortController.signal;Object.keys(t).length>0&&(o.setInputs(t),r.debug({inputs:t,moduleId:e.moduleId},"Set module inputs"));let u,m=!1,h,g;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",S=await Ft({orgId:c,s:f,context:o,logger:r,localTools:a,signal:p,flagStore:s.flagStore});g={orgId:c,cacheKeys:[S,...Object.entries(t).map(([w,T])=>`${w}:${T}`)]},r.debug({original:f,keyParams:g},"Module cache key params");let b=Date.now();for(;Date.now()-b<Lg;){p?.throwIfAborted();let w=await i.getCacheResult(g);if(w){r.debug({cacheResult:w},"Got result from module execution cache"),u=_l(e,t,"SUCCESS"),u.message="Used cached module result.",u.data=JSON.parse(w),m=!0;break}else r.debug({cacheKey:f,keyParams:g},"No cache result found, continuing with lock acquisition");let T=await i.acquireCacheLock({keyParams:g,clientMetadata:`hostName:${cO()};runId:${d}`},p);if(T.acquired){h=T.keyPrefix,r.info({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Acquired cache lock and proceeding with module execution");break}else r.debug({cacheKeyPrefixIfLockAcquired:h,cacheKey:f,keyParams:g},"Failed to acquire cache lock, retrying...");await Y(2500+Math.random()*1e4,p)}}try{if(!u)u=await dO(n);else if(e.autoAuth){let f=zs.safeParse(u.data);if(!f.success)throw new R("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${f.error.message}`);r.debug("Automatically loading auth state after cached module result"),await l.loadAuthState(f.data);let S=!1,b=e.advanced?.cacheInvalidation;if(b&&b.type==="PAGE_CHECK"){let w={type:"CONTENT",value:b.substring},T=await kl({timeout:xn,assertion:w,browser:l,logger:r,signal:p,autoExpandIframes:!!l.userBrowserSettings.autoExpandIframes});T.success?r.debug({invalResult:T},"Cached result still valid after page check, continuing..."):(r.info({invalResult:T},"Invalidating cached result due to page check failure"),S=!0)}if(g&&S)return await i.deleteCacheResult(g),kp(n)}}finally{try{h!==void 0&&!m&&u?.status==="SUCCESS"&&await pO({step:e,result:u,browser:s.browser,cacheKeyPrefix:h,logger:r,storage:i})}finally{h!==void 0&&await i.releaseCacheLock(h)}}return u},dO=async n=>{let{step:e,tracer:t}=n.moduleParams,r=_l(e,n.moduleParams.resolvedInputs,"SUCCESS"),o=await t.startSubSteps(),{status:i,results:a}=await vr(n.work,()=>n.executeStepList({...n,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}}));return r.results=a,r.status=i,r.finishedAt=new Date,Nn({asyncTasks:n.work.asyncTasks,nestedResults:a,result:r,logger:n.fixtures.logger}),r};function _l(n,e,t){let r={};return Object.entries(e).forEach(([i,a])=>{r[i]=JSON.stringify(a)}),{type:"MODULE",id:n.id,moduleId:n.moduleId,moduleName:n.name,startedAt:new Date,cacheConfig:n.cacheConfig,inputs:r,results:[],finishedAt:new Date,status:t}}async function tb({orgId:n,step:e,context:t,logger:r,flagStore:o,codeEvalTools:i,signal:a}){let s={};try{for(let l of e.parameters??[]){let c=e.inputs?.[l]??e.defaultParameters?.[l];if(!c){r.warn(`No value or default found for parameter '${l}' that is required by module '${e.name}'`);continue}s[l]=await io({orgId:n,code:c,fragment:!0,context:t,logger:r,localTools:i,signal:a,flagStore:o})}return s}catch(l){throw a?.throwIfAborted(),new R("UserConfigurationError",`Failed to evaluate module inputs: ${l}`)}}async function pO({step:n,result:e,browser:t,cacheKeyPrefix:r,logger:o,storage:i}){let a=n.cacheConfig?.cacheExpiryMs;(!a||a===lf)&&(a=n.defaultCacheTtl??cf);let s;n.autoAuth?s=JSON.stringify(await t.saveAuthState()):e.data!==void 0?s=JSON.stringify(e.data):s='""',o.debug({cacheKeyPrefix:r,ttlMs:a,truncatedCacheResultJson:Ff(s)},"Setting module cache result"),await i.setCacheResult({result:s,keyPrefix:r,ttlMs:a})}async function ao(n,e,t){return uO(n,e,t)}async function uO(n,e,t){let r=new Date;try{return t.throwIfAborted(),await e()}catch(o){let i=new Date,a="FAILED",s;if(t.aborted||o instanceof DOMException&&o.name==="AbortError"?(s="Step aborted by user.",a="CANCELLED"):o instanceof R?s=`${o}`:s=`An unexpected error occurred: ${o.message}`,n.type==="RESOLVED_MODULE"){let l=_l(n,{},"FAILED");return l.message=s,l.startedAt=r,l.finishedAt=i,l}return{...il(n),startedAt:r,finishedAt:i,status:a,data:null,message:s,results:[]}}}async function vr(n,e){let t=!1;try{return n&&!n.state.failureRecoveryDisabled&&(n.state.failureRecoveryDisabled=!0,t=!0),await e()}finally{n&&t&&(n.state.failureRecoveryDisabled=void 0)}}import{randomUUID as nb}from"crypto";import{cloneDeep as hO}from"lodash-es";function Dl(n,e){n.state.healingDetails?n.state.healingDetails.push(e):n.state.healingDetails=[e]}var Fl=async n=>{let{step:e,tracer:t}=n.presetParams,{logger:r,controller:o,context:i,billingReporter:a}=n.fixtures,{collectDebugData:s}=n.options,{testMetadata:l,suiteMetadata:c}=n.inputs,d=e.command.type,p=r.child({commandType:d,stepId:e.id,commandId:e.command.id}),u=ra(e.command);n.work.asyncTasks.push(a.reportCreditsUsed(p,d,u,{testId:l?.id,testName:l?.name,suiteId:c?.id,suiteName:c?.name}));let m=o.browser.url(),h=new Date,g,f=nb(),S=nb();if(s)try{g=await o.browser.screenshot({retries:1,clearHighlights:!0,quality:75});let E=await o.browser.getRawCondensedHtml();t.attachBeforeHtmlSnapshot({logger:p,snapshotId:f,html:E}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeHtmlSnapshot(p,f,E))}catch(E){p.debug({err:E},"Failed to take before screenshot, continuing...")}let b,w,T,C=Ds();try{let E=await o.executePresetCommand(C,t,e.command,i,l?.advanced.disableAICaching??!1);E.beforeScreenshotOverride&&(g=E.beforeScreenshotOverride),T=E.afterScreenshotOverride;let{proposedStep:A}=gO({work:n.work,step:e,newTargets:E.newTargets,logger:p}),k=new Date,O=o.browser.url();w={beforeUrl:m,afterUrl:O,startedAt:h,finishedAt:k,viewport:o.browser.getViewport(),status:E.fail?"FAILED":"SUCCESS",elementInteracted:E.elementInteracted},b={...e,message:E.thoughts??fO(E.newTargets)??"Successfully executed preset action.",beforeUrl:m,afterUrl:O,finishedAt:k,startedAt:h,status:E.fail?"FAILED":"SUCCESS",data:E.data,results:[w],details:C.details,proposedStep:A},"assertion"in e.command&&(b.message=E.thoughts||"Assertion passed.")}catch(E){p.error({message:E.message,stack:E.stack},`Failed executing preset step ${qr(e.command)}`);let A=o.browser.url(),k=new Date,O=E instanceof Error?E.message:`${E}`;E instanceof R&&E.getLastScreenshotBuffer()&&(T=E.getLastScreenshotBuffer()),w={beforeUrl:m,afterUrl:A,startedAt:h,finishedAt:k,viewport:o.browser.getViewport(),status:E instanceof DOMException&&E.name==="AbortError"?"CANCELLED":"FAILED",message:O},b={...e,startedAt:h,finishedAt:k,beforeUrl:m,afterUrl:A,status:E instanceof DOMException&&E.name==="AbortError"?"CANCELLED":"FAILED",message:O,failureReason:E instanceof R?E.reason:void 0,results:[w],details:C.details}}if(s)try{T||(T=await o.browser.screenshot({retries:1,quality:75}));let E=await o.browser.getRawCondensedHtml();t.attachAfterHtmlSnapshot({logger:p,snapshotId:S,html:E}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeHtmlSnapshot(p,S,E))}catch(E){p.debug({err:E},"Failed store debug data after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return w.beforeSnapshot=f,b.beforeSnapshot=f,w.afterSnapshot=S,b.afterSnapshot=S,g&&(t.attachBeforeScreenshot({logger:p,snapshotId:f,screenshot:g}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(p,f,g))),T&&(t.attachAfterScreenshot({logger:p,snapshotId:S,screenshot:T}),n.work.asyncTasks.push(n.fixtures.debugDataStorage.storeScreenshot(p,S,T))),b};function gO({work:n,step:e,newTargets:t,logger:r}){if(!t?.length)return{proposedStep:void 0};let o=e.command;Lf(o,t,r);let i=t[0]?.description;if(i&&"target"in o&&o.target&&o.target.type==="description"){let a={...o,target:{...o.target,elementDescriptor:i}},s={...hO(e),command:a};return Dl(n,{type:"DESCRIPTION_UPDATE",thoughts:`Updated element description after the original element could not be found on the page. New element location reasoning: ${t[0]?.thoughts}`}),{proposedStep:s}}return{proposedStep:void 0}}function fO(n){if(n?.length){if(n.length===1&&n[0]?.thoughts)return n[0].thoughts;if(n.length===2&&n.every(e=>e.thoughts))return`Located first element: ${n[0]?.thoughts}
|
|
@@ -3928,7 +3928,7 @@ ${a.stack}`),l.status(500).send("Internal Server Error")}),n){let a=Fv.static(n,
|
|
|
3928
3928
|
for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
|
|
3929
3929
|
`)}import cD from"events";import Dc from"fs";import dD from"open";import{cpus as lE}from"os";import _c from"path";import{fileURLToPath as pD}from"url";import i_ from"diff-lines";import{gt as a_}from"semver";import{execSync as Uk}from"child_process";import{platform as Bk}from"os";function Lu(){return Hv()?(y.dimmed("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),y.dimmed(`If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
|
|
3930
3930
|
`),2):(y.dimmed("Setting device pixel ratio to 1."),y.dimmed(`If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
|
|
3931
|
-
l.`),1)}function Hv(){return Bk()==="darwin"&&Uk("system_profiler SPDisplaysDataType").toString().includes("Retina")}function Ou(n){Hv()&&n===1&&(y.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),y.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import zk from"@actions/exec";import Hk from"@actions/io";import jk from"quote";import $k from"string-argv";async function jv(n,e=!0){let t=$k(n),r=await Hk.which(t[0],!0),o=t.slice(1),i=zk.exec(jk(r),o,{delay:100});if(e)return i}import{existsSync as Gk,statSync as Wk}from"fs";var Va=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;function $v(n){try{return Gk(n)&&Wk(n).isDirectory()}catch(e){return y.error({err:e},`Error reading path ${n} during directory existence check`),!1}}import Vk from"csv-parser";import{createReadStream as qk}from"fs";function Mu(n){return new Promise((e,t)=>{let r=[];qk(n).pipe(Vk()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>t(o))})}import pc from"semver";import{z as uc}from"zod";var zn="2.10.1",Kk="https://registry.npmjs.org/momentic",Yk=uc.object({versions:uc.record(uc.string(),uc.unknown()).optional()});async function Gv(n){try{await Xk(n)}catch(e){y.warn({err:e},"Failed to check CLI version against NPM servers")}}async function Xk(n){if(!zn){n.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let r=0;r<2;r++)try{let o=await z(fetch(Kk),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=Yk.parse(i).versions;break}catch(o){n.warn({err:o},"Failed to fetch npm registry data")}if(!e){n.warn("Failed to fetch npm registry data. Skipping version check.");return}let t;for(let r of Object.keys(e))pc.valid(r)&&(!t||pc.gt(r,t))&&pc.gt(r,zn)&&pc.lt(r,"2.0.0")&&!r.includes("alpha")&&(t=r);t&&(y.warn(`Update available: v${zn} -> v${t}`),y.warn("This version may be missing critical fixes, features, and security updates."),y.warn(`Run "npx momentic@${t} -V" to update`))}import{confirm as Qk,input as Zk}from"@inquirer/prompts";import{existsSync as e_,mkdirSync as t_,statSync as n_}from"fs";import{dirname as r_}from"path";import{hostname as Jk}from"os";var X=rc({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:Jk(),disableConsoleLogs:!0}).child({version:"2.10.1"});var o_=!1,Vv=(()=>{try{return n_("/.dockerenv"),!0}catch{return!1}})();async function St(n,e){return Va||o_||Vv?!0:(X.flush(),await new Promise(r=>setTimeout(r,500)),await Qk({message:n}))}async function Nu(n){let e=r_(n);return $v(e)?e_(n)?St(`File '${Wv(n)}' already exists. Overwrite existing content?`,!0):!0:await St(`Directory '${Wv(e)}' doesn't exist. Create it now?`,!0)?(t_(e,{recursive:!0}),!0):!1}function Wv(n){return n.replace(/(\s+)/g,"\\$1")}async function qv(n,e){return Va||Vv?e:(await Zk({message:n,default:e})).trim()||e}async function Kv({test:n,fragment:e,entities:t,client:r,logger:o,yes:i}){a_(e.schemaVersion,Le)&&(y.error(`This version of the CLI does not support the schema version of the fragment (${e.schemaVersion}). Please update to the latest version of the CLI and retry this command.`),process.exit(1)),Pf(e.steps).forEach(h=>{t.modules[h]||(y.error(`The test patch contains a module with id ${h} that could not be found in the current project. This suggests that either this test patch or your local file system may be out of date.`),process.exit(1))}),e.createdAt.getTime()<Date.now()-7*24*60*60*1e3&&!i&&!await St("The test patch you are applying is more than 7 days old. Are you sure you want to continue?",!0)&&process.exit(1);let s=n.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<s&&!i&&!await St("The test patch you are applying was created before the test was last updated. Are you sure you want to continue?",!0)&&process.exit(1);let l=to(n.fullFilePath,o,t),c=l.steps;if(!Array.isArray(c))throw new Error(`Test ${n.fullFilePath} is missing steps array`);let d,p;if(e.schemaVersion!==Le){let{steps:h,newVersion:g}=await da({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:y});d=g,p=Ne.array().parse(h)}else p=Ne.array().parse(e.steps);let{stepsToSave:u}=await mt({stepLists:{steps:p}});u.beforeSteps=l.beforeSteps??void 0,u.afterSteps=l.afterSteps??void 0;let m=i_(JSON.stringify(c,void 0,2),JSON.stringify(u,void 0,2),{n_surrounding:5});y.dimmed("=".repeat(30)),y.dimmed(m),y.dimmed("=".repeat(30)),y.dimmed(""),d&&y.warn(`If this patch is applied, your test will also be automatically upgraded to the latest schema version (${d}). Schema upgrades have no impact on functionality, although you may notice minor differences in the test YAML.`),!i&&!await St("Do you want to apply this patch?")&&(y.dimmed("Cancelled."),process.exit(1)),Yn({relativeTestPath:n.relativePath,steps:u,schemaVersion:d??e.schemaVersion,project:t.project}),y.success("Patch applied successfully."),await r.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{randomUUID as Bt}from"crypto";import{z as gT}from"zod";var it=" ".repeat(6);import hT from"chalk";import{Argument as go,InvalidArgumentError as qa,Option as we}from"@commander-js/extra-typings";import{validateHeaderValue as s_}from"http";import{z as Xv}from"zod";var Yv=58888,mc=30*60*1e3;function rr(n){let e=parseInt(n,10);if(isNaN(e))throw new qa("Not a number.");return e}function hc(n){if(n===void 0)return;let e={};for(let t of n){let r=t.indexOf("=");if(r===-1)throw new Error(`Header value pair does not contain '=': ${t}`);let o=t.slice(0,r),i=t.slice(r+1);s_(o,i),e[o]=i}return e}var yn=new we("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(n=>{if(!n)throw new qa("API key is required.");return n}).makeOptionMandatory(),bn=new we("--server <server>","Momentic server to use.").default("https://api.momentic.ai").argParser(n=>{try{return Xv.string().url().parse(n),n}catch{throw new qa("Not a valid URL.")}}),Rr=new we("-y, --yes","Skip all confirmation prompts.").env("CI"),ku=new we("-w, --wait","Wait for tests to finish running before exiting."),_u=new we("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Defaults to ${mc/1e3} seconds.`).default(mc/1e3).implies({wait:!0}).argParser(rr),gc=new we("--custom-headers <customHeaders...>","Specify custom headers in the form HEADER=VALUE to be sent with each request during the test. Multiple entries can be provided."),Jv=new we("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(_s)),Qv=new we("--reporter-dir <reporterDir>","Output directory to store report files. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml.").default("reports"),Du=new we("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),Zv=new we("--upload-results","Upload test results to Momentic Cloud.").default(!1),Fu=new we("--include <includePatterns...>","Only include tests that match the provided regex patterns. Multiple patterns can be provided. The patterns will be matched against the test file paths and the pattern only needs to match a part of the path for the test to be included."),Uu=new we("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),Bu=new we("--pixel-ratio <pixelRatio>","Device pixel ratio of your screen or monitor. Mac OS Retina displays and machines marketed as 'HiDPI' should set this to 2. Visit https://www.mydevice.io/ to find your device's pixel ratio.").argParser(rr),eT=new we("--port <port>",`Port to run the app on. Defaults to ${Yv}.`).default(Yv).argParser(rr),zu=new we("--input-csv <inputCsv>","Path to a CSV file on disk where each row represents a set of inputs that will be made available to all tests that are ran. The first line of the CSV must be the input names."),fc=new we("--env <env>","Name of the environment to use when running tests."),Sc=new we("--url-override <urlOverride>","Fully qualified URL (e.g. https://www.google.com) to start all tests from. Overrides any default starting URL set from the test or environment.").argParser(n=>{try{return Xv.string().url().parse(n),n}catch{throw new qa("Not a valid URL.")}}),tT=new we("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(n=>{let e=rr(n);if(e<1)throw new qa("Shard index must be greater than 0.");return e}),nT=new we("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(rr),Ut=new we("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),xi=new we("-f, --filter <filter>","Run tests within the project that has a name equal to the filter provided. This option cannot be used together with file path or directory arguments, but substring matches are allowed."),rT=new we("--fix","Attempt to fix any issues found."),Hu=new we("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI"),ju=new we("--disable-cache","Disable caching of test results."),oT=new we("--skip-quarantined","Skip quarantined tests entirely.").implies({onlyQuarantined:!1,ignoreQuarantine:!1}),iT=new we("--only-quarantined","Run only tests that are currently quarantined. When running with this option, any test failures will cause the pipeline to fail, even though the tests are quarantined.").implies({skipQuarantined:!1,ignoreQuarantine:!1}),aT=new we("--ignore-quarantine","Run all tests even if they are quarantined. This is useful for validating that quarantined tests are fixed before moving them out of quarantine.").implies({skipQuarantined:!1,onlyQuarantined:!1}),sT=new go("<tests...>","One or more test paths to queue on Momentic Cloud."),lT=new go("<tests...>","One or more test paths to import from Momentic Cloud.").argOptional(),$u=new go("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional(),cT=new go("<suites...>","One or more suite paths that exist on Momentic Cloud."),dT=new go("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),pT=new go("<results>","Path to the results archive.").argRequired(),Gu=new we("--reason <reason>","The reason for quarantining the test. This will be used to generate a report on the test run."),Wu=new go("<test>","Name of the test to quarantine.").argOptional();async function Vu(n){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(y.error(`Node.js version 18 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),y.debug(`Identified node version ${e}`);let r=await n.client.getAuthInfo();return y.debug("Got auth info from API"),r}import{Console as uT}from"console";import{format as Ka}from"util";var qu=class extends Error{constructor(e,t,r){let o=Error.stackTraceLimit;r&&(Error.stackTraceLimit=Math.max(r,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},yc=class n extends uT{_buffer=[];_groupDepth=0;Console=uT;constructor(){super({write:e=>(n.write(this._buffer,"log",e),!0)})}static write(e,t,r,o=2){let i=new qu(void 0,n.write).stack;if(!i)return e;let a=i.split(`
|
|
3931
|
+
l.`),1)}function Hv(){return Bk()==="darwin"&&Uk("system_profiler SPDisplaysDataType").toString().includes("Retina")}function Ou(n){Hv()&&n===1&&(y.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),y.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import zk from"@actions/exec";import Hk from"@actions/io";import jk from"quote";import $k from"string-argv";async function jv(n,e=!0){let t=$k(n),r=await Hk.which(t[0],!0),o=t.slice(1),i=zk.exec(jk(r),o,{delay:100});if(e)return i}import{existsSync as Gk,statSync as Wk}from"fs";var Va=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;function $v(n){try{return Gk(n)&&Wk(n).isDirectory()}catch(e){return y.error({err:e},`Error reading path ${n} during directory existence check`),!1}}import Vk from"csv-parser";import{createReadStream as qk}from"fs";function Mu(n){return new Promise((e,t)=>{let r=[];qk(n).pipe(Vk()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>t(o))})}import pc from"semver";import{z as uc}from"zod";var zn="2.10.2",Kk="https://registry.npmjs.org/momentic",Yk=uc.object({versions:uc.record(uc.string(),uc.unknown()).optional()});async function Gv(n){try{await Xk(n)}catch(e){y.warn({err:e},"Failed to check CLI version against NPM servers")}}async function Xk(n){if(!zn){n.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let r=0;r<2;r++)try{let o=await z(fetch(Kk),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=Yk.parse(i).versions;break}catch(o){n.warn({err:o},"Failed to fetch npm registry data")}if(!e){n.warn("Failed to fetch npm registry data. Skipping version check.");return}let t;for(let r of Object.keys(e))pc.valid(r)&&(!t||pc.gt(r,t))&&pc.gt(r,zn)&&pc.lt(r,"2.0.0")&&!r.includes("alpha")&&(t=r);t&&(y.warn(`Update available: v${zn} -> v${t}`),y.warn("This version may be missing critical fixes, features, and security updates."),y.warn(`Run "npx momentic@${t} -V" to update`))}import{confirm as Qk,input as Zk}from"@inquirer/prompts";import{existsSync as e_,mkdirSync as t_,statSync as n_}from"fs";import{dirname as r_}from"path";import{hostname as Jk}from"os";var X=rc({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:Jk(),disableConsoleLogs:!0}).child({version:"2.10.2"});var o_=!1,Vv=(()=>{try{return n_("/.dockerenv"),!0}catch{return!1}})();async function St(n,e){return Va||o_||Vv?!0:(X.flush(),await new Promise(r=>setTimeout(r,500)),await Qk({message:n}))}async function Nu(n){let e=r_(n);return $v(e)?e_(n)?St(`File '${Wv(n)}' already exists. Overwrite existing content?`,!0):!0:await St(`Directory '${Wv(e)}' doesn't exist. Create it now?`,!0)?(t_(e,{recursive:!0}),!0):!1}function Wv(n){return n.replace(/(\s+)/g,"\\$1")}async function qv(n,e){return Va||Vv?e:(await Zk({message:n,default:e})).trim()||e}async function Kv({test:n,fragment:e,entities:t,client:r,logger:o,yes:i}){a_(e.schemaVersion,Le)&&(y.error(`This version of the CLI does not support the schema version of the fragment (${e.schemaVersion}). Please update to the latest version of the CLI and retry this command.`),process.exit(1)),Pf(e.steps).forEach(h=>{t.modules[h]||(y.error(`The test patch contains a module with id ${h} that could not be found in the current project. This suggests that either this test patch or your local file system may be out of date.`),process.exit(1))}),e.createdAt.getTime()<Date.now()-7*24*60*60*1e3&&!i&&!await St("The test patch you are applying is more than 7 days old. Are you sure you want to continue?",!0)&&process.exit(1);let s=n.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<s&&!i&&!await St("The test patch you are applying was created before the test was last updated. Are you sure you want to continue?",!0)&&process.exit(1);let l=to(n.fullFilePath,o,t),c=l.steps;if(!Array.isArray(c))throw new Error(`Test ${n.fullFilePath} is missing steps array`);let d,p;if(e.schemaVersion!==Le){let{steps:h,newVersion:g}=await da({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:y});d=g,p=Ne.array().parse(h)}else p=Ne.array().parse(e.steps);let{stepsToSave:u}=await mt({stepLists:{steps:p}});u.beforeSteps=l.beforeSteps??void 0,u.afterSteps=l.afterSteps??void 0;let m=i_(JSON.stringify(c,void 0,2),JSON.stringify(u,void 0,2),{n_surrounding:5});y.dimmed("=".repeat(30)),y.dimmed(m),y.dimmed("=".repeat(30)),y.dimmed(""),d&&y.warn(`If this patch is applied, your test will also be automatically upgraded to the latest schema version (${d}). Schema upgrades have no impact on functionality, although you may notice minor differences in the test YAML.`),!i&&!await St("Do you want to apply this patch?")&&(y.dimmed("Cancelled."),process.exit(1)),Yn({relativeTestPath:n.relativePath,steps:u,schemaVersion:d??e.schemaVersion,project:t.project}),y.success("Patch applied successfully."),await r.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{randomUUID as Bt}from"crypto";import{z as gT}from"zod";var it=" ".repeat(6);import hT from"chalk";import{Argument as go,InvalidArgumentError as qa,Option as we}from"@commander-js/extra-typings";import{validateHeaderValue as s_}from"http";import{z as Xv}from"zod";var Yv=58888,mc=30*60*1e3;function rr(n){let e=parseInt(n,10);if(isNaN(e))throw new qa("Not a number.");return e}function hc(n){if(n===void 0)return;let e={};for(let t of n){let r=t.indexOf("=");if(r===-1)throw new Error(`Header value pair does not contain '=': ${t}`);let o=t.slice(0,r),i=t.slice(r+1);s_(o,i),e[o]=i}return e}var yn=new we("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(n=>{if(!n)throw new qa("API key is required.");return n}).makeOptionMandatory(),bn=new we("--server <server>","Momentic server to use.").default("https://api.momentic.ai").argParser(n=>{try{return Xv.string().url().parse(n),n}catch{throw new qa("Not a valid URL.")}}),Rr=new we("-y, --yes","Skip all confirmation prompts.").env("CI"),ku=new we("-w, --wait","Wait for tests to finish running before exiting."),_u=new we("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Defaults to ${mc/1e3} seconds.`).default(mc/1e3).implies({wait:!0}).argParser(rr),gc=new we("--custom-headers <customHeaders...>","Specify custom headers in the form HEADER=VALUE to be sent with each request during the test. Multiple entries can be provided."),Jv=new we("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(_s)),Qv=new we("--reporter-dir <reporterDir>","Output directory to store report files. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml.").default("reports"),Du=new we("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),Zv=new we("--upload-results","Upload test results to Momentic Cloud.").default(!1),Fu=new we("--include <includePatterns...>","Only include tests that match the provided regex patterns. Multiple patterns can be provided. The patterns will be matched against the test file paths and the pattern only needs to match a part of the path for the test to be included."),Uu=new we("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),Bu=new we("--pixel-ratio <pixelRatio>","Device pixel ratio of your screen or monitor. Mac OS Retina displays and machines marketed as 'HiDPI' should set this to 2. Visit https://www.mydevice.io/ to find your device's pixel ratio.").argParser(rr),eT=new we("--port <port>",`Port to run the app on. Defaults to ${Yv}.`).default(Yv).argParser(rr),zu=new we("--input-csv <inputCsv>","Path to a CSV file on disk where each row represents a set of inputs that will be made available to all tests that are ran. The first line of the CSV must be the input names."),fc=new we("--env <env>","Name of the environment to use when running tests."),Sc=new we("--url-override <urlOverride>","Fully qualified URL (e.g. https://www.google.com) to start all tests from. Overrides any default starting URL set from the test or environment.").argParser(n=>{try{return Xv.string().url().parse(n),n}catch{throw new qa("Not a valid URL.")}}),tT=new we("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(n=>{let e=rr(n);if(e<1)throw new qa("Shard index must be greater than 0.");return e}),nT=new we("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(rr),Ut=new we("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),xi=new we("-f, --filter <filter>","Run tests within the project that has a name equal to the filter provided. This option cannot be used together with file path or directory arguments, but substring matches are allowed."),rT=new we("--fix","Attempt to fix any issues found."),Hu=new we("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI"),ju=new we("--disable-cache","Disable caching of test results."),oT=new we("--skip-quarantined","Skip quarantined tests entirely.").implies({onlyQuarantined:!1,ignoreQuarantine:!1}),iT=new we("--only-quarantined","Run only tests that are currently quarantined. When running with this option, any test failures will cause the pipeline to fail, even though the tests are quarantined.").implies({skipQuarantined:!1,ignoreQuarantine:!1}),aT=new we("--ignore-quarantine","Run all tests even if they are quarantined. This is useful for validating that quarantined tests are fixed before moving them out of quarantine.").implies({skipQuarantined:!1,onlyQuarantined:!1}),sT=new go("<tests...>","One or more test paths to queue on Momentic Cloud."),lT=new go("<tests...>","One or more test paths to import from Momentic Cloud.").argOptional(),$u=new go("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional(),cT=new go("<suites...>","One or more suite paths that exist on Momentic Cloud."),dT=new go("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),pT=new go("<results>","Path to the results archive.").argRequired(),Gu=new we("--reason <reason>","The reason for quarantining the test. This will be used to generate a report on the test run."),Wu=new go("<test>","Name of the test to quarantine.").argOptional();async function Vu(n){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<18)&&(y.error(`Node.js version 18 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),y.debug(`Identified node version ${e}`);let r=await n.client.getAuthInfo();return y.debug("Got auth info from API"),r}import{Console as uT}from"console";import{format as Ka}from"util";var qu=class extends Error{constructor(e,t,r){let o=Error.stackTraceLimit;r&&(Error.stackTraceLimit=Math.max(r,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},yc=class n extends uT{_buffer=[];_groupDepth=0;Console=uT;constructor(){super({write:e=>(n.write(this._buffer,"log",e),!0)})}static write(e,t,r,o=2){let i=new qu(void 0,n.write).stack;if(!i)return e;let a=i.split(`
|
|
3932
3932
|
`).slice(o).filter(Boolean).join(`
|
|
3933
3933
|
`);return e.push({message:r,origin:a,type:t}),e}_log(e,t){n.write(this._buffer,e," ".repeat(this._groupDepth)+t,3)}debug(e,...t){this._log("debug",Ka(e,...t))}error(e,...t){this._log("error",Ka(e,...t))}info(e,...t){this._log("info",Ka(e,...t))}log(e,...t){this._log("log",Ka(e,...t))}warn(e,...t){this._log("warn",Ka(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function mT(n){let e=globalThis.console,t=new yc;globalThis.console=t;try{n()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
|
|
3934
3934
|
`);process.stderr.write(`${o}
|