momentic 2.11.0 → 2.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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=Vo.parse(r)}catch(i){throw new Error(`Could not parse test file ${t} as YAML: ${i}`)}return ht.parse(o)}function no(n,e,t){let r=t.project.rootDir,o;try{o=dn.readFileSync(n,"utf-8")}catch(a){throw e.error({err:a,projectRoot:r},a.message),new Error(a.message)}let i=Vo.parse(o);if(!i.steps||!Array.isArray(i.steps))throw new Error(`Test ${n} is missing steps`);return i}async function Sa(n,e,t){let r=no(n,e,t),o;try{o=Jt.parse(r)}catch(a){throw new Error(`Test ${n} is missing metadata or has invalid metadata: ${a}`)}let{resolvedTest:i}=await hS({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 Yn(l,s)}}});return i}import bI from"@dotenvx/dotenvx";import wI from"fs";import xS from"path";function RS(n,e){return(n.config.environments??[]).map(t=>ya(t.name,n,e))}function CS(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 ya(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={[Ze]:CS(r.baseUrl)};if(r.envVariables){let a={};for(let[s,l]of Object.entries(r.envVariables))if(typeof l=="string"){let c=CS(l);c&&(a[s]=c)}else{let c=l.fromFile,d;try{d=wI.readFileSync(xS.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:xS.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 qS=CE(BS(),1);var wa=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]},va=n=>n.replace(/[[\]\\-]/g,"\\$&"),PI=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),zS=n=>n.join(""),HS=(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(va(p)+"-"+va(g)):g===p&&r.push(va(g)),p="",i++;continue}if(n.startsWith("-]",i+1)){r.push(va(g+"-")),i+=2;continue}if(n.startsWith("-",i+1)){p=g,i+=2;continue}r.push(va(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?"^":"")+zS(r)+"]",h="["+(c?"":"^")+zS(o)+"]";return[r.length&&o.length?"("+u+"|"+h+")":r.length?u:h,s,d-t,!0]};var pn=(n,{windowsPathsNoEscape:e=!1}={})=>e?n.replace(/\[([^\/\\])\]/g,"$1"):n.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var LI=new Set(["!","?","+","*","@"]),jS=n=>LI.has(n),OI="(?!(?:^|/)\\.\\.?(?:$|/))",ml="(?!\\.)",MI=new Set(["[","."]),NI=new Set(["..","."]),kI=new Set("().*{}+?[]^$\\!"),_I=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),ip="[^/]",$S=ip+"*?",GS=ip+"+?",qo=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 h=r,m="";for(;h<e.length;){let g=e.charAt(h++);if(i||g==="\\"){i=!i,m+=g;continue}if(a){h===s+1?(g==="^"||g==="!")&&(l=!0):g==="]"&&!(h===s+2&&l)&&(a=!1),m+=g;continue}else if(g==="["){a=!0,s=h,l=!1,m+=g;continue}if(!o.noext&&jS(g)&&e.charAt(h)==="("){t.push(m),m="";let f=new n(g,t);h=n.#S(e,f,h,o),t.push(f);continue}m+=g}return t.push(m),h}let c=r+1,d=new n(null,t),p=[],u="";for(;c<e.length;){let h=e.charAt(c++);if(i||h==="\\"){i=!i,u+=h;continue}if(a){c===s+1?(h==="^"||h==="!")&&(l=!0):h==="]"&&!(c===s+2&&l)&&(a=!1),u+=h;continue}else if(h==="["){a=!0,s=c,l=!1,u+=h;continue}if(jS(h)&&e.charAt(c)==="("){d.push(u),u="";let m=new n(h,d);d.push(m),c=n.#S(e,m,c,o);continue}if(h==="|"){d.push(u),u="",p.push(d),d=new n(null,t);continue}if(h===")")return u===""&&t.#r.length===0&&(t.#o=!0),d.push(u),u="",t.push(...p,d),c;u+=h}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(h=>{let[m,g,f,S]=typeof h=="string"?n.#u(h,this.#t,l):h.toRegExpSource(e);return this.#t=this.#t||f,this.#i=this.#i||S,m}).join(""),d="";if(this.isStart()&&typeof this.#r[0]=="string"&&!(this.#r.length===1&&NI.has(this.#r[0]))){let m=MI,g=t&&m.has(c.charAt(0))||c.startsWith("\\.")&&m.has(c.charAt(2))||c.startsWith("\\.\\.")&&m.has(c.charAt(4)),f=!t&&!e&&m.has(c.charAt(0));d=g?OI:f?ml:""}let p="";return this.isEnd()&&this.#e.#p&&this.#a?.type==="!"&&(p="(?:$|\\/)"),[d+c+p,pn(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,pn(this.toString()),!1,!1]}let a=!r||e||t||!ml?"":this.#m(!0);a===i&&(a=""),a&&(i=`(?:${i})(?:${a})*?`);let s="";if(this.type==="!"&&this.#o)s=(this.isStart()&&!t?ml:"")+GS;else{let l=this.type==="!"?"))"+(this.isStart()&&!t&&!e?ml:"")+$S+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&a?")":this.type==="*"&&a?")?":`)${this.type}`;s=o+i+l}return[s,pn(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]=HS(e,s);if(p){i+=c,a=a||d,s+=p-1,t=t||u;continue}}if(l==="*"){r&&e==="*"?i+=GS:i+=$S,t=!0;continue}if(l==="?"){i+=ip,t=!0;continue}i+=_I(l)}return[i,pn(e),!!t,a]}};var Ko=(n,{windowsPathsNoEscape:e=!1}={})=>e?n.replace(/[?*()[\]]/g,"[$&]"):n.replace(/[?*()[\]\\]/g,"\\$&");var Ct=(n,e,t={})=>(wa(e),!t.nocomment&&e.charAt(0)==="#"?!1:new Dt(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=KS([n]);return e?(e=e.toLowerCase(),r=>t(r)&&r.toLowerCase().endsWith(e)):t},JI=([n,e=""])=>{let t=YS([n]);return e?(e=e.toLowerCase(),r=>t(r)&&r.toLowerCase().endsWith(e)):t},QI=([n,e=""])=>{let t=YS([n]);return e?r=>t(r)&&r.endsWith(e):t},ZI=([n,e=""])=>{let t=KS([n]);return e?r=>t(r)&&r.endsWith(e):t},KS=([n])=>{let e=n.length;return t=>t.length===e&&!t.startsWith(".")},YS=([n])=>{let e=n.length;return t=>t.length===e&&t!=="."&&t!==".."},XS=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",WS={win32:{sep:"\\"},posix:{sep:"/"}},eP=XS==="win32"?WS.win32.sep:WS.posix.sep;Ct.sep=eP;var ct=Symbol("globstar **");Ct.GLOBSTAR=ct;var tP="[^/]",nP=tP+"*?",rP="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",oP="(?:(?!(?:\\/|^)\\.).)*?",iP=(n,e={})=>t=>Ct(t,n,e);Ct.filter=iP;var en=(n,e={})=>Object.assign({},n,e),aP=n=>{if(!n||typeof n!="object"||!Object.keys(n).length)return Ct;let e=Ct;return Object.assign((r,o,i={})=>e(r,o,en(n,i)),{Minimatch:class extends e.Minimatch{constructor(o,i={}){super(o,en(n,i))}static defaults(o){return e.defaults(en(n,o)).Minimatch}},AST:class extends e.AST{constructor(o,i,a={}){super(o,i,en(n,a))}static fromGlob(o,i={}){return e.AST.fromGlob(o,en(n,i))}},unescape:(r,o={})=>e.unescape(r,en(n,o)),escape:(r,o={})=>e.escape(r,en(n,o)),filter:(r,o={})=>e.filter(r,en(n,o)),defaults:r=>e.defaults(en(n,r)),makeRe:(r,o={})=>e.makeRe(r,en(n,o)),braceExpand:(r,o={})=>e.braceExpand(r,en(n,o)),match:(r,o,i={})=>e.match(r,o,en(n,i)),sep:e.sep,GLOBSTAR:ct})};Ct.defaults=aP;var JS=(n,e={})=>(wa(n),e.nobrace||!/\{(?:(?!\{).)*\}/.test(n)?[n]:(0,qS.default)(n));Ct.braceExpand=JS;var sP=(n,e={})=>new Dt(n,e).makeRe();Ct.makeRe=sP;var lP=(n,e,t={})=>{let r=new Dt(e,t);return n=n.filter(o=>r.match(o)),r.options.nonull&&!n.length&&n.push(e),n};Ct.match=lP;var VS=/[?*]|[+@!]\(.*?\)|\[|\]/,cP=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Dt=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){wa(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||XS,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]==="?"||!VS.test(i[2]))&&!VS.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===ct){this.debug("GLOBSTAR",[t,d,p]);var u=a,h=s+1;if(h===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 m=e[u];if(this.debug(`
|
|
39
39
|
globstar while`,e,u,t,h,m),this.matchOne(e.slice(u),t.slice(h),r))return this.debug("globstar found match!",u,l,m),!0;if(m==="."||m===".."||!o.dot&&m.charAt(0)==="."){this.debug("dot detected!",e,u,t,h);break}this.debug("globstar swallow a segment, and continue"),u++}return!!(r&&(this.debug(`
|
|
40
40
|
>>> no match, partial?`,e,u,t,h),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 JS(this.pattern,this.options)}parse(e){wa(e);let t=this.options;if(e==="**")return ct;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=qo.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===ct?ct:d._src});return c.forEach((d,p)=>{let u=c[p+1],h=c[p-1];d!==ct||h===ct||(h===void 0?u!==void 0&&u!==ct?c[p+1]="(?:\\/|"+r+"\\/)?"+u:c[p]=r:u===void 0?c[p-1]=h+"(?:\\/|"+r+")?":u!==ct&&(c[p-1]=h+"(?:\\/|\\/"+r+"\\/)"+u,c[p+1]=ct))}),c.filter(d=>d!==ct).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 Ct.defaults(e).Minimatch}};Ct.AST=qo;Ct.Minimatch=Dt;Ct.escape=Ko;Ct.unescape=pn;import{fileURLToPath as HP}from"node:url";var Yo=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,ZS=new Set,ap=typeof process=="object"&&process?process:{},ey=(n,e,t,r)=>{typeof ap.emitWarning=="function"?ap.emitWarning(n,e,t,r):console.error(`[${t}] ${e}: ${n}`)},hl=globalThis.AbortController,QS=globalThis.AbortSignal;if(typeof hl>"u"){QS=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(r,o){this._onabort.push(o)}},hl=class{constructor(){e()}signal=new QS;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=ap.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{n&&(n=!1,ey("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=>!ZS.has(n),B4=Symbol("type"),fr=n=>n&&n===Math.floor(n)&&n>0&&isFinite(n),ty=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?Xo:null:null,Xo=class extends Array{constructor(e){super(e),this.fill(0)}},sp=class n{heap;length;static#e=!1;static create(e){let t=ty(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]}},Ta=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:h=0,maxEntrySize:m=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?ty(t):Array;if(!A)throw new Error("invalid max value: "+t);if(this.#e=t,this.#t=h,this.maxEntrySize=m||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=sp.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 N="LRU_CACHE_UNBOUNDED";dP(N)&&(ZS.add(N),ey("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",N,n))}}getRemainingTTL(e){return this.#s.has(e)?1/0:0}#P(){let e=new Xo(this.#e),t=new Xo(this.#e);this.#b=e,this.#C=t,this.#M=(i,a,s=Yo.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?Yo.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=Yo.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 Xo(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-(Yo.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=Yo.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=Yo.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:h}=u;h!==void 0&&!a&&(this.#v&&this.#i?.(h,e,"set"),this.#h&&this.#g?.push([h,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 h=u&&this.#d(u)?u.__staleWhileFetching:u;h!==void 0&&(l.oldValue=h)}}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,h;for(;h=u?.shift();)this.#r?.(...h)}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 hl,{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=h;return this.#o[t]===h&&(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=h;if(this.#o[t]===h&&(!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 h=new Promise(u).then(c,d),m=Object.assign(h,{__abortController:a,__staleWhileFetching:i,__returned:void 0});return t===void 0?(this.set(e,m,{...l.options,status:void 0}),t=this.#s.get(e)):this.#o[t]=m,m}#d(e){if(!this.#T)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof hl}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:h=this.ignoreFetchAbort,allowStaleOnFetchAbort:m=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:m,ignoreFetchAbort:h,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 z=r&&C.__staleWhileFetching!==void 0;return S&&(S.fetch="inflight",z&&(S.returnedStale=!0)),z?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 Sp}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 hp}from"node:events";import ay from"node:stream";import{StringDecoder as pP}from"node:string_decoder";var ny=typeof process=="object"&&process?process:{stdout:null,stderr:null},uP=n=>!!n&&typeof n=="object"&&(n instanceof yr||n instanceof ay||mP(n)||hP(n)),mP=n=>!!n&&typeof n=="object"&&n instanceof hp&&typeof n.pipe=="function"&&n.pipe!==ay.Writable.prototype.pipe,hP=n=>!!n&&typeof n=="object"&&n instanceof hp&&typeof n.write=="function"&&typeof n.end=="function",Jn=Symbol("EOF"),Qn=Symbol("maybeEmitEnd"),Sr=Symbol("emittedEnd"),gl=Symbol("emittingEnd"),Ea=Symbol("emittedError"),fl=Symbol("closed"),ry=Symbol("read"),Sl=Symbol("flush"),oy=Symbol("flushChunk"),un=Symbol("encoding"),Jo=Symbol("decoder"),tt=Symbol("flowing"),xa=Symbol("paused"),Qo=Symbol("resume"),nt=Symbol("buffer"),Rt=Symbol("pipes"),rt=Symbol("bufferLength"),lp=Symbol("bufferPush"),yl=Symbol("bufferShift"),St=Symbol("objectMode"),ze=Symbol("destroyed"),cp=Symbol("error"),dp=Symbol("emitData"),iy=Symbol("emitEnd"),pp=Symbol("emitEnd2"),On=Symbol("async"),up=Symbol("abort"),bl=Symbol("aborted"),Ca=Symbol("signal"),ro=Symbol("dataListeners"),Ft=Symbol("discarded"),Ra=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),wl=class{src;dest;opts;ondrain;constructor(e,t,r){this.src=e,this.dest=t,this.opts=r,this.ondrain=()=>e[Qo](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},mp=class extends wl{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 hp{[tt]=!1;[xa]=!1;[Rt]=[];[nt]=[];[St];[un];[On];[Jo];[Jn]=!1;[Sr]=!1;[gl]=!1;[fl]=!1;[Ea]=null;[rt]=0;[ze]=!1;[Ca];[bl]=!1;[ro]=0;[Ft]=!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[St]=!0,this[un]=null):wP(t)?(this[un]=t.encoding,this[St]=!1):(this[St]=!1,this[un]=null),this[On]=!!t.async,this[Jo]=this[un]?new pP(this[un]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[nt]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Rt]});let{signal:r}=t;r&&(this[Ca]=r,r.aborted?this[up]():r.addEventListener("abort",()=>this[up]()))}get bufferLength(){return this[rt]}get encoding(){return this[un]}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[St]}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}[up](){this[bl]=!0,this.emit("abort",this[Ca]?.reason),this.destroy(this[Ca]?.reason)}get aborted(){return this[bl]}set aborted(e){}write(e,t,r){if(this[bl])return!1;if(this[Jn])throw new Error("write after end");if(this[ze])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]?Ra:gP;if(!this[St]&&!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[St]?(this[tt]&&this[rt]!==0&&this[Sl](!0),this[tt]?this.emit("data",e):this[lp](e),this[rt]!==0&&this.emit("readable"),r&&o(r),this[tt]):e.length?(typeof e=="string"&&!(t===this[un]&&!this[Jo]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[un]&&(e=this[Jo].write(e)),this[tt]&&this[rt]!==0&&this[Sl](!0),this[tt]?this.emit("data",e):this[lp](e),this[rt]!==0&&this.emit("readable"),r&&o(r),this[tt]):(this[rt]!==0&&this.emit("readable"),r&&o(r),this[tt])}read(e){if(this[ze])return null;if(this[Ft]=!1,this[rt]===0||e===0||e&&e>this[rt])return this[Qn](),null;this[St]&&(e=null),this[nt].length>1&&!this[St]&&(this[nt]=[this[un]?this[nt].join(""):Buffer.concat(this[nt],this[rt])]);let t=this[ry](e||null,this[nt][0]);return this[Qn](),t}[ry](e,t){if(this[St])this[yl]();else{let r=t;e===r.length||e===null?this[yl]():typeof r=="string"?(this[nt][0]=r.slice(e),t=r.slice(0,e),this[rt]-=e):(this[nt][0]=r.subarray(e),t=r.subarray(0,e),this[rt]-=e)}return this.emit("data",t),!this[nt].length&&!this[Jn]&&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[Jn]=!0,this.writable=!1,(this[tt]||!this[xa])&&this[Qn](),this}[Qo](){this[ze]||(!this[ro]&&!this[Rt].length&&(this[Ft]=!0),this[xa]=!1,this[tt]=!0,this.emit("resume"),this[nt].length?this[Sl]():this[Jn]?this[Qn]():this.emit("drain"))}resume(){return this[Qo]()}pause(){this[tt]=!1,this[xa]=!0,this[Ft]=!1}get destroyed(){return this[ze]}get flowing(){return this[tt]}get paused(){return this[xa]}[lp](e){this[St]?this[rt]+=1:this[rt]+=e.length,this[nt].push(e)}[yl](){return this[St]?this[rt]-=1:this[rt]-=this[nt][0].length,this[nt].shift()}[Sl](e=!1){do;while(this[oy](this[yl]())&&this[nt].length);!e&&!this[nt].length&&!this[Jn]&&this.emit("drain")}[oy](e){return this.emit("data",e),this[tt]}pipe(e,t){if(this[ze])return e;this[Ft]=!1;let r=this[Sr];return t=t||{},e===ny.stdout||e===ny.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,r?t.end&&e.end():(this[Rt].push(t.proxyErrors?new mp(this,e,t):new wl(this,e,t)),this[On]?Ra(()=>this[Qo]()):this[Qo]()),e}unpipe(e){let t=this[Rt].find(r=>r.dest===e);t&&(this[Rt].length===1?(this[tt]&&this[ro]===0&&(this[tt]=!1),this[Rt]=[]):this[Rt].splice(this[Rt].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[Ft]=!1,this[ro]++,!this[Rt].length&&!this[tt]&&this[Qo]();else if(e==="readable"&&this[rt]!==0)super.emit("readable");else if(fP(e)&&this[Sr])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[Ea]){let o=t;this[On]?Ra(()=>o.call(this,this[Ea])):o.call(this,this[Ea])}return r}removeListener(e,t){return this.off(e,t)}off(e,t){let r=super.off(e,t);return e==="data"&&(this[ro]=this.listeners("data").length,this[ro]===0&&!this[Ft]&&!this[Rt].length&&(this[tt]=!1)),r}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[ro]=0,!this[Ft]&&!this[Rt].length&&(this[tt]=!1)),t}get emittedEnd(){return this[Sr]}[Qn](){!this[gl]&&!this[Sr]&&!this[ze]&&this[nt].length===0&&this[Jn]&&(this[gl]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[fl]&&this.emit("close"),this[gl]=!1)}emit(e,...t){let r=t[0];if(e!=="error"&&e!=="close"&&e!==ze&&this[ze])return!1;if(e==="data")return!this[St]&&!r?!1:this[On]?(Ra(()=>this[dp](r)),!0):this[dp](r);if(e==="end")return this[iy]();if(e==="close"){if(this[fl]=!0,!this[Sr]&&!this[ze])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(e==="error"){this[Ea]=r,super.emit(cp,r);let i=!this[Ca]||this.listeners("error").length?super.emit("error",r):!1;return this[Qn](),i}else if(e==="resume"){let i=super.emit("resume");return this[Qn](),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[Qn](),o}[dp](e){for(let r of this[Rt])r.dest.write(e)===!1&&this.pause();let t=this[Ft]?!1:super.emit("data",e);return this[Qn](),t}[iy](){return this[Sr]?!1:(this[Sr]=!0,this.readable=!1,this[On]?(Ra(()=>this[pp]()),!0):this[pp]())}[pp](){if(this[Jo]){let t=this[Jo].end();if(t){for(let r of this[Rt])r.dest.write(t);this[Ft]||super.emit("data",t)}}for(let t of this[Rt])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[St]||(e.dataLength=0);let t=this.promise();return this.on("data",r=>{e.push(r),this[St]||(e.dataLength+=r.length)}),await t,e}async concat(){if(this[St])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[un]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(ze,()=>t(new Error("stream destroyed"))),this.on("error",r=>t(r)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[Ft]=!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[Jn])return t();let i,a,s=p=>{this.off("data",l),this.off("end",c),this.off(ze,d),t(),a(p)},l=p=>{this.off("error",s),this.off("end",c),this.off(ze,d),this.pause(),i({value:p,done:!!this[Jn]})},c=()=>{this.off("error",s),this.off("data",l),this.off(ze,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(ze,d),this.once("error",s),this.once("end",c),this.once("data",l)})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[Ft]=!1;let e=!1,t=()=>(this.pause(),this.off(cp,t),this.off(ze,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(cp,t),this.once(ze,t),{next:r,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[ze])return e?this.emit("error",e):this.emit(ze),this;this[ze]=!0,this[Ft]=!0,this[nt].length=0,this[rt]=0;let t=this;return typeof t.close=="function"&&!this[fl]&&t.close(),e?this.emit("error",e):this.emit(ze),this}static get isStream(){return uP}};var PP=AP.native,Ia={lstatSync:EP,readdir:xP,readdirSync:CP,readlinkSync:RP,realpathSync:PP,promises:{lstat:LP,readdir:OP,readlink:MP,realpath:NP}},py=n=>!n||n===Ia||n===IP?Ia:{...Ia,...n,promises:{...Ia.promises,...n.promises||{}}},uy=/^\\\\\?\\([a-z]:)\\?$/i,kP=n=>n.replace(/\//g,"\\").replace(uy,"$1\\"),_P=/[\\\/]/,nn=0,my=1,hy=2,Mn=4,gy=6,fy=8,oo=10,Sy=12,tn=15,Aa=~tn,gp=16,sy=32,Pa=64,mn=128,vl=256,El=512,ly=Pa|mn|El,DP=1023,fp=n=>n.isFile()?fy:n.isDirectory()?Mn:n.isSymbolicLink()?oo:n.isCharacterDevice()?hy:n.isBlockDevice()?gy:n.isSocket()?Sy:n.isFIFO()?my:nn,cy=new Map,La=n=>{let e=cy.get(n);if(e)return e;let t=n.normalize("NFKD");return cy.set(n,t),t},dy=new Map,Tl=n=>{let e=dy.get(n);if(e)return e;let t=La(n.toLowerCase());return dy.set(n,t),t},xl=class extends Ta{constructor(){super({max:256})}},yp=class extends Ta{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1})}},yy=Symbol("PathScurry setAsCwd"),yt=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=nn,r,o,i,a,s){this.name=e,this.#b=i?Tl(e):La(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=py(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&=~gp,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let r=this.children(),o=this.nocase?Tl(e):La(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,nn,{...t,parent:this,fullpath:a});return this.canReaddir()||(s.#n|=mn),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&tn)===nn}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&tn)===fy}isDirectory(){return(this.#n&tn)===Mn}isCharacterDevice(){return(this.#n&tn)===hy}isBlockDevice(){return(this.#n&tn)===gy}isFIFO(){return(this.#n&tn)===my}isSocket(){return(this.#n&tn)===Sy}isSymbolicLink(){return(this.#n&oo)===oo}lstatCached(){return this.#n&sy?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&tn;return!(e!==nn&&e!==oo||this.#n&vl||this.#n&mn)}calledReaddir(){return!!(this.#n&gp)}isENOENT(){return!!(this.#n&mn)}isNamed(e){return this.nocase?this.#b===Tl(e):this.#b===La(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|=gp;for(let t=e.provisional;t<e.length;t++){let r=e[t];r&&r.#_()}}#_(){this.#n&mn||(this.#n=(this.#n|mn)&Aa,this.#A())}#A(){let e=this.children();e.provisional=0;for(let t of e)t.#_()}#I(){this.#n|=El,this.#D()}#D(){if(this.#n&Pa)return;let e=this.#n;(e&tn)===Mn&&(e&=Aa),this.#n=e|Pa,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|=vl,e==="ENOENT"&&(t|=mn),(e==="EINVAL"||e==="UNKNOWN")&&(t&=Aa),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=fp(e),o=this.newChild(e.name,r,{parent:this}),i=o.#n&tn;return i!==Mn&&i!==oo&&i!==nn&&(o.#n|=Pa),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?Tl(e.name):La(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&Aa|fp(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&mn))try{return this.#W(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#U(e.code)}}lstatSync(){if(!(this.#n&mn))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:h,mtime:m,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=h,this.#g=m,this.#S=g,this.#r=f,this.#c=S,this.#l=b,this.#a=w;let T=fp(e);this.#n=this.#n&Aa|T|sy,T!==nn&&T!==Mn&&T!==oo&&(this.#n|=Pa)}#$=[];#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&ly)return!1;let e=tn&this.#n;return e===nn||e===Mn||e===oo}shouldWalk(e,t){return(this.#n&Mn)===Mn&&!(this.#n&ly)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#L)return this.#L;if(!((El|vl|mn)&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(!((El|vl|mn)&this.#n))try{let e=this.#e.realpathSync(this.fullpath());return this.#L=this.resolve(e)}catch{this.#I()}}[yy](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}},Cl=class n extends yt{sep="\\";splitSep=_P;constructor(e,t=nn,r,o,i,a,s){super(e,t,r,o,i,a,s)}newChild(e,t=nn,r={}){return new n(e,t,this.root,this.roots,this.nocase,this.childrenCache(),r)}getRootString(e){return Sp.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 Zo(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(uy,"$1\\"),e===t}},Rl=class n extends yt{splitSep="/";sep="/";constructor(e,t=nn,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=nn,r={}){return new n(e,t,this.root,this.roots,this.nocase,this.childrenCache(),r)}},Al=class{root;rootPath;roots;cwd;#e;#t;#i;nocase;#r;constructor(e=process.cwd(),t,r,{nocase:o,childrenCacheSize:i=16*1024,fs:a=Ia}={}){this.#r=py(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 xl,this.#t=new xl,this.#i=new yp(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,h=!1;for(let m of l){let g=d--;c=c.child(m,{relative:new Array(g).fill("..").join(p),relativePosix:new Array(g).fill("..").join("/"),fullpath:u+=(h?"":p)+m}),h=!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 yt||(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 yt||(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 yt||(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 yt||(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 yt||(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 yt||(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 yt||(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((h,m)=>{if(h)return u(h);let g=m.length;if(!g)return u();let f=()=>{--g===0&&u()};for(let S of m)(!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,h=>{if(h)return u(h);p(s)})})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof yt||(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 yt||(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 yt||(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 yt||(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 h=c.shift();if(!h){d===0&&s.end();return}d++,l.add(h);let m=(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(()=>m(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;h.readdirCB(m,!0),g=!1}};return p(),s}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof yt||(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 h=c.shift();if(!h){d===0&&s.end();return}d++,l.add(h);let m=h.readdirSync();for(let g of m)(!i||i(g))&&(s.write(r?g:g.fullpath())||(u=!0));d--;for(let g of m){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[yy](t)}},Zo=class extends Al{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,Sp,"\\",{...t,nocase:r}),this.nocase=r;for(let o=this.cwd;o;o=o.parent)o.nocase=this.nocase}parseRootPath(e){return Sp.parse(e).root.toUpperCase()}newRoot(e){return new Cl(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)}},ei=class extends Al{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 Rl(this.rootPath,Mn,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},Oa=class extends ei{constructor(e=process.cwd(),t={}){let{nocase:r=!0}=t;super(e,{...t,nocase:r})}},J4=process.platform==="win32"?Cl:Rl,by=process.platform==="win32"?Zo:process.platform==="darwin"?Oa:ei;var FP=n=>n.length>=1,UP=n=>n.length>=1,ti=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,h,...m]=this.#t;c[0]===""&&(c.shift(),m.shift());let g=[i,a,s,l,""].join("/"),f=[d,p,u,h,""].join("/");this.#e=[g,...c],this.#t=[f,...m],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]===ct}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",ni=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 Dt(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 ti(o,i,0,this.platform),s=new Dt(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 bp=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()]))}},wp=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)])}},vp=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())}},Ma=class n{hasWalkedCache;matches=new wp;subwalks=new vp;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new bp}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===ct){(!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 h=o.parent||o;u?this.hasWalkedCache.hasWalked(h,u)||this.subwalks.add(h,u):this.matches.add(h,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===ct?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 ni([n],e):Array.isArray(n)?new ni(n,e):n,Il=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 Ma(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 Ma(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()}},Na=class extends Il{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}},ka=class extends Il{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",hn=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"?Zo:t.platform==="darwin"?Oa:t.platform?ei:by;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 Dt(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 ti(l,d,0,this.platform)})}async walk(){return[...await new Na(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 Na(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 ka(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 ka(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 Tp=(n,e={})=>{Array.isArray(n)||(n=[n]);for(let t of n)if(new Dt(t,e).hasMagic())return!0;return!1};function Pl(n,e={}){return new hn(n,e).streamSync()}function Ty(n,e={}){return new hn(n,e).stream()}function br(n,e={}){return new hn(n,e).walkSync()}async function wy(n,e={}){return new hn(n,e).walk()}function Ll(n,e={}){return new hn(n,e).iterateSync()}function Ey(n,e={}){return new hn(n,e).iterate()}var $P=Pl,GP=Object.assign(Ty,{sync:Pl}),WP=Ll,VP=Object.assign(Ey,{sync:Ll}),qP=Object.assign(br,{stream:Pl,iterate:Ll}),vy=Object.assign(wy,{glob:wy,globSync:br,sync:qP,globStream:Ty,stream:GP,globStreamSync:Pl,streamSync:$P,globIterate:Ey,iterate:VP,globIterateSync:Ll,iterateSync:WP,Glob:hn,hasMagic:Tp,escape:Ko,unescape:pn});vy.glob=vy;import io,{dirname as Ay}from"path";import{cwd as Ap}from"process";import Iy from"yaml";import{z as Ee}from"zod";import xy from"fs";import _a from"path";import KP from"yaml";import{z as Ep}from"zod";var Cy=!1,xp=[`**/*.${xt.TEST}`,`**/*.${xt.MODULE}`],Cp=Ep.string().refine(n=>/^[a-zA-Z0-9-]+$/.test(n)),Rp=50,YP=Ep.object({fileType:Ep.nativeEnum(be)});function ce(n,e){let t={project:n,tests:{},modules:{},duplicateEntities:{}},r=n.config.include??xp,o=Array.from(n.config.exclude??[]).concat(Ys),i=br(r,{absolute:!1,cwd:n.rootDir,ignore:o,dotRelative:!1,maxDepth:Rp,nodir:!0});for(let a of i){let s=XP(n.rootDir,a,t,e);s&&(t.duplicateEntities[s.id]=s.paths)}return Cy=!0,t}function XP(n,e,t,r){let o=_a.join(n,e),i;try{i=xy.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=xy.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:_a.sep,fullPathSegments:o.split(_a.sep),relativePathSegments:e.split(_a.sep),fileName:_a.basename(o),lastModified:c.mtime,createdAt:c.birthtime},p;switch(l){case be.TEST:try{let u=Jt.parse(a);if(t.tests[u.id]){let h=t.tests[u.id].fullFilePath;p={id:u.id,paths:[h,o]}}return t.tests[u.id]={type:be.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 be.MODULE:try{let u=Lt.parse(a);if(t.modules[u.moduleId]){let m=t.modules[u.moduleId].fullFilePath;p={id:u.moduleId,paths:[m,o]}}t.modules[u.moduleId]={type:be.MODULE,name:u.name,id:u.moduleId,description:u.description??void 0,...d};let h=d.fileName.replace(".module.yaml","");return!Cy&&ve(u.name)!==h&&r.warn(`The module with ID ${u.moduleId} has a name (${u.name}) that does not match its file name (${h}). 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 ri="momentic.config.yaml",Ry="momentic.workspace.yaml",tL=Ee.object({projects:Ee.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),nL=Ee.union([Ee.string(),Ee.object({fromFile:Ee.string(),json:Ee.boolean().optional()})]),rL=Ee.object({name:Cp,baseUrl:Ee.string(),envFile:Ee.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:Ee.record(Ee.string(),nL).optional(),inheritFromShell:Ee.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:Ur.optional()}),oL=Ee.object({postSave:Ee.string().optional()}),iL=Ee.object({name:Cp,include:Ee.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:Ee.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:Ee.string().optional(),reporterDir:Ee.string().optional(),outputDir:Ee.string().optional(),retries:Ee.number().optional().describe("number of retries per test"),parallel:Ee.number().optional().describe("degree of parallelism"),environments:Ee.array(rL).optional(),gitMainBranch:Ee.string().optional(),gitProtectedBranches:Ee.string().array().optional(),ai:Gd.optional(),browser:Ur.optional(),advanced:Wd.optional(),hooks:oL.optional()});function Py(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=Iy.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 Ip(n){let e=Py(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=Py(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=Ap(),t=io.parse(e).root,r=15,o=0;for(;o<r;){o++;let i=io.basename(e);if(Ks.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(ri)){let s=io.join(e,a),l=Ip(s);l&&n.push({configFilePath:s,config:l,rootDir:Ay(s)})}if(n.length)return n;if(e=io.dirname(e),e===t)break}return n}function ot(n={}){let{configFilePath:e,nameFilter:t}=n,r=Pp(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}*${ri}`)),r=br(t,{absolute:!1,cwd:Ap(),dotRelative:!1,maxDepth:Rp,nodir:!0}),o=[];for(let i of r){let a=io.join(Ap(),i),s=Ip(a);s&&o.push({configFilePath:a,config:s,rootDir:Ay(a)})}return o}function Pp(n){if(n){n=io.resolve(n);let t=Ip(n);return t||(console.error(`No valid Momentic project file found at ${n}.`),process.exit(1)),[{config:t,configFilePath:n,rootDir:io.dirname(n)}]}if(JP(Ry)){let t=lL(Ry);if(t)return t}return sL()}function oi(n,e){let t=Iy.stringify(n);eL(e,t)}import ii from"fs";import Lp from"path";import{z as Op}from"zod";var Ly="golden/visual-diff",Oy="reports",My="test-results";var cL=Op.object({width:Op.number(),height:Op.number()}),ai=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,t){let r=Lp.join(e.rootDir,e.config.goldenFileDir??Ly);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=Lp.join(this.defaultGoldenScreenshotDir,`${t.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return ii.mkdirSync(Lp.dirname(o),{recursive:!0}),ii.writeFileSync(o,r.buffer),ii.writeFileSync(i,JSON.stringify({width:r.width,height:r.height})),{buffer:Buffer.from(r.buffer),width:r.width,height:r.height};if(ii.existsSync(o)){let a=ii.readFileSync(o),s=cL.parse(JSON.parse(ii.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 si=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 xe=dL();function Ol(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 Ce(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([Ce(n,xe.show(["--no-patch","--format=%ci"])),Ce(n,xe.listRemote(["--get-url","origin"])),Ce(n,xe.show(["-s","--pretty=%B"])),Ce(n,xe.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([Ce(n,xe.listRemote(["--get-url","origin"])),Ce(n,xe.show(["-s","--pretty=%B"])),Ce(n,xe.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([Ce(n,xe.show(["--no-patch","--format=%ci"])),Ce(n,xe.listRemote(["--get-url","origin"])),Ce(n,xe.show(["-s","--pretty=%B"])),Ce(n,xe.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),s=t?Ol(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([Ce(n,xe.show(["--no-patch","--format=%ci"])),Ce(n,xe.show(["-s","--pretty=%B"])),Ce(n,xe.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Ol(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([Ce(n,xe.show(["--no-patch","--format=%ci"])),Ce(n,xe.show(["-s","--pretty=%B"])),Ce(n,xe.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Ol(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([Ce(n,xe.revparse(["HEAD"])),Ce(n,xe.revparse(["--short","HEAD"])),Ce(n,xe.revparse(["--abbrev-ref","HEAD"])),Ce(n,xe.listRemote(["--get-url","origin"])),Ce(n,xe.show(["--no-patch","--format=%ci"])),Ce(n,xe.show(["-s","--pretty=%B"])),Ce(n,xe.show(["-s","--pretty=%an"])),e?Ce(n,xe.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0)]),d=c?await Ce(n,xe.show(["--no-patch","--format=%ci",c])):void 0,p=i?.includes("github.com"),u=i?.includes("gitlab.com"),h=i?Ol(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?h:void 0,gitlabProjectPath:u?h: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 Mp(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 li(n,e,t){let r=await bL(t),o=await Mp(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 Nk from"http";import{z as kp}from"zod";var G="v1",Da="2.11.0";var wr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Ny=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 B(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(Ny(p));s=()=>c(Ny(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 Ml=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 EL=9e4,xL=3,CL=1500,RL=15e3,gn=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 Np=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Da&&(e[Ng]=Da),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 gn&&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,h=Math.min(i*Math.pow(2,u-1),a);await new Promise(m=>setTimeout(m,h))}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 gn(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)}}},rn=class extends Np{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var Xe=class extends rn{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(`/${G}/auth/check`,{method:"GET",noLog:!0,retries:10,requestTimeoutMs:5e3});return Zg.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${G}/runs/status`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:1e4});return Yg.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${G}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return Gg.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${G}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let r=await this.sendRequest(`/${G}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Wg.parse(r)}async queueTests(e){let t=await this.sendRequest(`/${G}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return $g.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${G}/screenshots`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:5e3});return Qg.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${G}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ef.parse(e)}async acquireCacheLock(e,t){let r=await this.sendRequest(`/${G}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return cf.parse(r)}async releaseCacheLock(e){await this.sendRequest(`/${G}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${G}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${G}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${G}/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(`/${G}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return tf.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},r=await this.sendRequest(`/${G}/run-groups/status`,{method:"POST",body:t,noLog:!0,retries:3,requestTimeoutMs:5e3});return Nh.array().parse(r)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${G}/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(`/${G}/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(`/${G}/test-fragments/${e}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return nf.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${G}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let r=await this.sendRequest(`/${G}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return rf.parse(r)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${G}/results/uploads`,{method:"POST",noLog:!0,retries:3,requestTimeoutMs:1e4});return of.parse(e)}async startProcessingResultsUpload(e,t){let r=await this.sendRequest(`/${G}/results/uploads/${e}/process`,{method:"POST",noLog:!0,body:t,retries:3,requestTimeoutMs:1e4});return af.parse(r)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${G}/knowledge-base/icons`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return gf.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${G}/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(`/${G}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return da.parse(a)}async getCommitFromGithub(e,t,r){let o=await this.sendRequest(`/${G}/git/github/${e}/${t}/commits/${r}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return da.parse(o)}async getMergeBaseCommitFromGitlab(e,t,r){let o=new URLSearchParams;o.set("base",t),o.set("head",r);let i=await this.sendRequest(`/${G}/git/gitlab/${e}/merge-base-commit?${o.toString()}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return da.parse(i)}async getCommitFromGitlab(e,t){let r=await this.sendRequest(`/${G}/git/gitlab/${e}/commits/${t}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return da.parse(r)}async getAgentConfig(){let e=await this.sendRequest(`/${G}/web-agent/agent-config`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return kp.record(kp.string(),kp.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${G}/quarantine`,{method:"GET",noLog:!0});return sf.parse(e)}async quarantineTest(e,t){await this.sendRequest(`/${G}/quarantine`,{method:"POST",body:{testId:e,reason:t},noLog:!0,retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t){await this.sendRequest(`/${G}/quarantine/${e}`,{method:"DELETE",body:{reason:t},noLog:!0,retries:3,requestTimeoutMs:1e4})}};import{randomUUID as ky}from"crypto";var Nl=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??ky(),properties:kd({},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??ky(),properties:kd({creditsUsed:r,usedBy:t},o)}])}catch(i){e.error({err:i},"Failed to report credits used")}}};var ci=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 di="v1",pi=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(`/${di}/tools/ai/generate`,{method:"POST",body:t}).catch(r=>{throw r instanceof gn?new Error(r.rawError):new Error(`Failed to send AI generation: ${r.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${di}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof gn?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${di}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof gn?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${di}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof gn?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${di}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof gn?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${di}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof gn?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as LL}from"zod";var ui=class extends rn{agentConfig;constructor(e,t){super(t),this.agentConfig=e}async rankChunksWithAi(e,t){let r={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${G}/web-agent/recommend-chunks-ai`,{method:"POST",body:r,signal:t.abortSignal});return Bh.parse(o)}async rankChunksWithRag(e,t){let r=await this.sendRequest(`/${G}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Da,...e},signal:t.abortSignal});return Uh.parse(r)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${G}/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(`/${G}/web-agent/locate-element`,{method:"POST",body:r,signal:t.abortSignal});return Hg.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(`/${G}/web-agent/assertion`,{method:"POST",body:r,signal:t.abortSignal});return Vd.parse(o)}async getLintStepResult(e,t){let r={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${G}/web-agent/lint/step`,{method:"POST",body:r,signal:t.abortSignal});return zg.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(`/${G}/web-agent/visual-assertion`,{method:"POST",body:r,signal:t.abortSignal});return Vd.parse(o)}async getAiActionCommand(e,t){let r=await this.sendRequest(`/${G}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Bg.parse(r)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${G}/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(`/${G}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return ad.parse(r)}async getReverseMappedDescription(e,t){let r=await this.sendRequest(`/${G}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return jg.parse(r)}async getTextExtraction(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${G}/web-agent/text-extraction`,{method:"POST",body:r,signal:t.abortSignal});return od.parse(o)}async getTestResultClassification(e,t){let r=await this.sendRequest(`/${G}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return yd.parse(r)}async getExtractedKeywords(e,t){let r=await this.sendRequest(`/${G}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return Kh.parse(r)}async getAutohealingProposal(e,t){let r=await this.sendRequest(`/${G}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return _m.parse(r)}async getFailureRecoveryProposal(e,t){let r=await this.sendRequest(`/${G}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Fm.parse(r)}async getFailureRecoveryPlan(e,t){let r=await this.sendRequest(`/${G}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Dm.parse(r)}async getIframeRegex(e,t){let r=await this.sendRequest(`/${G}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Sm.parse(r)}};var mi=class extends rn{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let r=await this.sendRequest(`/${G}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return ym.parse(r)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};function _y(n,e,t){return fetch(n,{method:"PUT",body:t,headers:{"Content-Type":e}})}var kl=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:r,id:o}=await this.client.generateTestResultsUploadUrl(),i=await _y(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 hi({orgId:n,client:e,gitMetadata:t,alwaysSaveCache:r,noCache:o}){return o?new os:new _p(n,e,t,r)}var _p=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[kg]=r),o&&(this.cacheHeaders[_g]=o),a&&(this.cacheHeaders[Dg]=a.toISOString()),s&&(this.cacheHeaders[Fg]=s),l&&(this.cacheHeaders[Ug]=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&&jo({steps:s,stepCacheEntries:i,logger:e.logger});let{cachesToSave:a}=await gt({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:a,testId:e.testId},this.cacheHeaders)}};import kk from"path";import{Server as nk}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{}}},Dy={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})}}},Fy={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})}}},Uy={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)}},By={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.assertionResult){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 Fa from"os";import UL from"v8";var zy,kn,BL=Fa.platform(),zL=Fa.cpus().map(n=>({model:n.model,speed:n.speed}));function Hy(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=Fa.totalmem(),e=Fa.freemem(),t=n-e;return{totalMemory:n,freeMemory:e,usedMemory:t}}function jL(){let n=Fa.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 zy={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,zy}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 jy(n){let e;try{e=new URL(n.url).hostname}catch{}let t=[];return n.headers.getSetCookie()?.forEach(r=>{let o=Hs(r,e);t.push(...o)}),t}var XL=Object.getPrototypeOf(async function(){}).constructor;async function $y(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,jy,o,s,c,S=>i.sms.send(S),S=>i.sms.fetchLatest(S),i.email,i.sms,i.ai)),h=!0,m,g;try{m=await B(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}`),h=!1,f instanceof wr?g=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:g=f instanceof Error?f.message:`${f}`}return{result:m,variableUpdates:a,persistentVariableUpdates:l,success:h,error:g}}async function Gy({code:n,fragment:e,context:t,localTools:r,logger:o,signal:i,timeoutMs:a=mr}){let s=JL(),l=await $y(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}}),Wy=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,Vy=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function qy({orgId:n,code:e,fragment:t,context:r,timeoutMs:o=mr,retries:i=2,signal:a,logger:s}){if(!Wy)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let l,c,d=0;if(!Vy)throw new Error("Missing lambda auth secret.");let p=QL("sha256",Vy).update(n).digest("hex");for(;d<=i;){d++,a?.throwIfAborted();let h={id:ZL(),orgId:n,momenticLambdaAuthHash:p,code:e,fragment:t,state:r.toObjectCopy(),timeoutMs:o};try{if(l=await B(tO(Wy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)}),{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(m){c=m}}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=rg.parse(await l.json())}catch(h){throw new Error(`Code evaluation server returned invalid response: ${h}`)}if(u.error)throw new Error(`Code evaluation error: ${u.error}`);return u}async function ao(n){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await qy(n);else if(n.localTools)e=await Gy({...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}*${ri}`)),r=br(t,{absolute:!1,cwd:Ap(),dotRelative:!1,maxDepth:Rp,nodir:!0}),o=[];for(let i of r){let a=io.join(Ap(),i),s=Ip(a);s&&o.push({configFilePath:a,config:s,rootDir:Ay(a)})}return o}function Pp(n){if(n){n=io.resolve(n);let t=Ip(n);return t||(console.error(`No valid Momentic project file found at ${n}.`),process.exit(1)),[{config:t,configFilePath:n,rootDir:io.dirname(n)}]}if(JP(Ry)){let t=lL(Ry);if(t)return t}return sL()}function oi(n,e){let t=Iy.stringify(n);eL(e,t)}import ii from"fs";import Lp from"path";import{z as Op}from"zod";var Ly="golden/visual-diff",Oy="reports",My="test-results";var cL=Op.object({width:Op.number(),height:Op.number()}),ai=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,t){let r=Lp.join(e.rootDir,e.config.goldenFileDir??Ly);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=Lp.join(this.defaultGoldenScreenshotDir,`${t.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return ii.mkdirSync(Lp.dirname(o),{recursive:!0}),ii.writeFileSync(o,r.buffer),ii.writeFileSync(i,JSON.stringify({width:r.width,height:r.height})),{buffer:Buffer.from(r.buffer),width:r.width,height:r.height};if(ii.existsSync(o)){let a=ii.readFileSync(o),s=cL.parse(JSON.parse(ii.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 si=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 xe=dL();function Ol(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 Ce(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([Ce(n,xe.show(["--no-patch","--format=%ci"])),Ce(n,xe.listRemote(["--get-url","origin"])),Ce(n,xe.show(["-s","--pretty=%B"])),Ce(n,xe.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([Ce(n,xe.listRemote(["--get-url","origin"])),Ce(n,xe.show(["-s","--pretty=%B"])),Ce(n,xe.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([Ce(n,xe.show(["--no-patch","--format=%ci"])),Ce(n,xe.listRemote(["--get-url","origin"])),Ce(n,xe.show(["-s","--pretty=%B"])),Ce(n,xe.show(["-s","--pretty=%an"]))]),i=t?.includes("github.com"),a=t?.includes("gitlab.com"),s=t?Ol(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([Ce(n,xe.show(["--no-patch","--format=%ci"])),Ce(n,xe.show(["-s","--pretty=%B"])),Ce(n,xe.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Ol(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([Ce(n,xe.show(["--no-patch","--format=%ci"])),Ce(n,xe.show(["-s","--pretty=%B"])),Ce(n,xe.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Ol(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([Ce(n,xe.revparse(["HEAD"])),Ce(n,xe.revparse(["--short","HEAD"])),Ce(n,xe.revparse(["--abbrev-ref","HEAD"])),Ce(n,xe.listRemote(["--get-url","origin"])),Ce(n,xe.show(["--no-patch","--format=%ci"])),Ce(n,xe.show(["-s","--pretty=%B"])),Ce(n,xe.show(["-s","--pretty=%an"])),e?Ce(n,xe.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0)]),d=c?await Ce(n,xe.show(["--no-patch","--format=%ci",c])):void 0,p=i?.includes("github.com"),u=i?.includes("gitlab.com"),h=i?Ol(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?h:void 0,gitlabProjectPath:u?h: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 Mp(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 li(n,e,t){let r=await bL(t),o=await Mp(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 Nk from"http";import{z as kp}from"zod";var G="v1",Da="2.11.1";var wr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Ny=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 B(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(Ny(p));s=()=>c(Ny(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 Ml=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 EL=9e4,xL=3,CL=1500,RL=15e3,gn=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 Np=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Da&&(e[Ng]=Da),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 gn&&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,h=Math.min(i*Math.pow(2,u-1),a);await new Promise(m=>setTimeout(m,h))}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 gn(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)}}},rn=class extends Np{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var Xe=class extends rn{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(`/${G}/auth/check`,{method:"GET",noLog:!0,retries:10,requestTimeoutMs:5e3});return Zg.parse(e)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${G}/runs/status`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:1e4});return Yg.parse(t)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${G}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return Gg.parse(t)}async updateStepCaches(e,t){await this.sendRequest(`/${G}/cache`,{method:"PATCH",body:e,extraHeaders:t,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,t){let r=await this.sendRequest(`/${G}/cache`,{method:"POST",body:e,extraHeaders:t,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Wg.parse(r)}async queueTests(e){let t=await this.sendRequest(`/${G}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return $g.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${G}/screenshots`,{method:"POST",body:e,noLog:!0,retries:3,requestTimeoutMs:5e3});return Qg.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${G}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ef.parse(e)}async acquireCacheLock(e,t){let r=await this.sendRequest(`/${G}/result-cache/lock`,{method:"POST",body:e,signal:t,retries:3,requestTimeoutMs:3e4});return cf.parse(r)}async releaseCacheLock(e){await this.sendRequest(`/${G}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${G}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${G}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${G}/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(`/${G}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return tf.parse(t)}async bulkGetRunGroupStatus(e){let t={runGroupIds:e},r=await this.sendRequest(`/${G}/run-groups/status`,{method:"POST",body:t,noLog:!0,retries:3,requestTimeoutMs:5e3});return Nh.array().parse(r)}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${G}/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(`/${G}/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(`/${G}/test-fragments/${e}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return nf.parse(t)}async patchTestFragment(e,t){await this.sendRequest(`/${G}/test-fragments/${e}`,{method:"PATCH",body:t,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,t){let r=await this.sendRequest(`/${G}/results/tests/${e}`,{method:"POST",body:t,retries:3,requestTimeoutMs:1e4});return rf.parse(r)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${G}/results/uploads`,{method:"POST",noLog:!0,retries:3,requestTimeoutMs:1e4});return of.parse(e)}async startProcessingResultsUpload(e,t){let r=await this.sendRequest(`/${G}/results/uploads/${e}/process`,{method:"POST",noLog:!0,body:t,retries:3,requestTimeoutMs:1e4});return af.parse(r)}async fetchIconKnowledgeBase(e){try{let t=await this.sendRequest(`/${G}/knowledge-base/icons`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return gf.parse(t)}catch(t){return e.error({err:t},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,t){try{await this.sendRequest(`/${G}/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(`/${G}/git/github/${e}/${t}/merge-base-commit?${i.toString()}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return da.parse(a)}async getCommitFromGithub(e,t,r){let o=await this.sendRequest(`/${G}/git/github/${e}/${t}/commits/${r}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return da.parse(o)}async getMergeBaseCommitFromGitlab(e,t,r){let o=new URLSearchParams;o.set("base",t),o.set("head",r);let i=await this.sendRequest(`/${G}/git/gitlab/${e}/merge-base-commit?${o.toString()}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return da.parse(i)}async getCommitFromGitlab(e,t){let r=await this.sendRequest(`/${G}/git/gitlab/${e}/commits/${t}`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:1e4});return da.parse(r)}async getAgentConfig(){let e=await this.sendRequest(`/${G}/web-agent/agent-config`,{method:"GET",noLog:!0,retries:3,requestTimeoutMs:5e3});return kp.record(kp.string(),kp.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${G}/quarantine`,{method:"GET",noLog:!0});return sf.parse(e)}async quarantineTest(e,t){await this.sendRequest(`/${G}/quarantine`,{method:"POST",body:{testId:e,reason:t},noLog:!0,retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,t){await this.sendRequest(`/${G}/quarantine/${e}`,{method:"DELETE",body:{reason:t},noLog:!0,retries:3,requestTimeoutMs:1e4})}};import{randomUUID as ky}from"crypto";var Nl=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??ky(),properties:kd({},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??ky(),properties:kd({creditsUsed:r,usedBy:t},o)}])}catch(i){e.error({err:i},"Failed to report credits used")}}};var ci=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 di="v1",pi=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(`/${di}/tools/ai/generate`,{method:"POST",body:t}).catch(r=>{throw r instanceof gn?new Error(r.rawError):new Error(`Failed to send AI generation: ${r.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${di}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof gn?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${di}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof gn?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${di}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof gn?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${di}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof gn?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${di}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof gn?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import{z as LL}from"zod";var ui=class extends rn{agentConfig;constructor(e,t){super(t),this.agentConfig=e}async rankChunksWithAi(e,t){let r={...e,loggerTags:t.loggerTags},o=await this.sendRequest(`/${G}/web-agent/recommend-chunks-ai`,{method:"POST",body:r,signal:t.abortSignal});return Bh.parse(o)}async rankChunksWithRag(e,t){let r=await this.sendRequest(`/${G}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Da,...e},signal:t.abortSignal});return Uh.parse(r)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${G}/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(`/${G}/web-agent/locate-element`,{method:"POST",body:r,signal:t.abortSignal});return Hg.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(`/${G}/web-agent/assertion`,{method:"POST",body:r,signal:t.abortSignal});return Vd.parse(o)}async getLintStepResult(e,t){let r={...e,disableCache:!!t.disableCache,loggerTags:t.loggerTags},o=await this.sendRequest(`/${G}/web-agent/lint/step`,{method:"POST",body:r,signal:t.abortSignal});return zg.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(`/${G}/web-agent/visual-assertion`,{method:"POST",body:r,signal:t.abortSignal});return Vd.parse(o)}async getAiActionCommand(e,t){let r=await this.sendRequest(`/${G}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return Bg.parse(r)}async getMultiturnAiActionCommand(e,t){return await this.sendRequest(`/${G}/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(`/${G}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return ad.parse(r)}async getReverseMappedDescription(e,t){let r=await this.sendRequest(`/${G}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:t.disableCache,loggerTags:t.loggerTags},signal:t.abortSignal});return jg.parse(r)}async getTextExtraction(e,t){let r={...e,disableCache:t.disableCache,loggerTags:t.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${G}/web-agent/text-extraction`,{method:"POST",body:r,signal:t.abortSignal});return od.parse(o)}async getTestResultClassification(e,t){let r=await this.sendRequest(`/${G}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return yd.parse(r)}async getExtractedKeywords(e,t){let r=await this.sendRequest(`/${G}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:t.disableCache,context:e},signal:t.abortSignal});return Kh.parse(r)}async getAutohealingProposal(e,t){let r=await this.sendRequest(`/${G}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return _m.parse(r)}async getFailureRecoveryProposal(e,t){let r=await this.sendRequest(`/${G}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Fm.parse(r)}async getFailureRecoveryPlan(e,t){let r=await this.sendRequest(`/${G}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:t.loggerTags},signal:t.abortSignal});return Dm.parse(r)}async getIframeRegex(e,t){let r=await this.sendRequest(`/${G}/web-agent/iframe-regex`,{method:"POST",body:e,signal:t.abortSignal});return Sm.parse(r)}};var mi=class extends rn{generator;constructor(e,t){super(e),this.generator=t}async runTemplateMatching(e,t={}){let r=await this.sendRequest(`/${G}/web-agent/template-matching`,{method:"POST",body:e,signal:t?.signal});return ym.parse(r)}async constructIframeRegex(e,t={}){return this.generator.getIframeRegex(e,{abortSignal:t.signal})}};function _y(n,e,t){return fetch(n,{method:"PUT",body:t,headers:{"Content-Type":e}})}var kl=class{constructor(e){this.client=e}async uploadResultsArchive(e,t){let{uploadUrl:r,id:o}=await this.client.generateTestResultsUploadUrl(),i=await _y(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 hi({orgId:n,client:e,gitMetadata:t,alwaysSaveCache:r,noCache:o}){return o?new os:new _p(n,e,t,r)}var _p=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[kg]=r),o&&(this.cacheHeaders[_g]=o),a&&(this.cacheHeaders[Dg]=a.toISOString()),s&&(this.cacheHeaders[Fg]=s),l&&(this.cacheHeaders[Ug]=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&&jo({steps:s,stepCacheEntries:i,logger:e.logger});let{cachesToSave:a}=await gt({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:a,testId:e.testId},this.cacheHeaders)}};import kk from"path";import{Server as nk}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{}}},Dy={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})}}},Fy={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})}}},Uy={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)}},By={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.assertionResult){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 Fa from"os";import UL from"v8";var zy,kn,BL=Fa.platform(),zL=Fa.cpus().map(n=>({model:n.model,speed:n.speed}));function Hy(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=Fa.totalmem(),e=Fa.freemem(),t=n-e;return{totalMemory:n,freeMemory:e,usedMemory:t}}function jL(){let n=Fa.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 zy={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,zy}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 jy(n){let e;try{e=new URL(n.url).hostname}catch{}let t=[];return n.headers.getSetCookie()?.forEach(r=>{let o=Hs(r,e);t.push(...o)}),t}var XL=Object.getPrototypeOf(async function(){}).constructor;async function $y(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,jy,o,s,c,S=>i.sms.send(S),S=>i.sms.fetchLatest(S),i.email,i.sms,i.ai)),h=!0,m,g;try{m=await B(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}`),h=!1,f instanceof wr?g=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:g=f instanceof Error?f.message:`${f}`}return{result:m,variableUpdates:a,persistentVariableUpdates:l,success:h,error:g}}async function Gy({code:n,fragment:e,context:t,localTools:r,logger:o,signal:i,timeoutMs:a=mr}){let s=JL(),l=await $y(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}}),Wy=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,Vy=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function qy({orgId:n,code:e,fragment:t,context:r,timeoutMs:o=mr,retries:i=2,signal:a,logger:s}){if(!Wy)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let l,c,d=0;if(!Vy)throw new Error("Missing lambda auth secret.");let p=QL("sha256",Vy).update(n).digest("hex");for(;d<=i;){d++,a?.throwIfAborted();let h={id:ZL(),orgId:n,momenticLambdaAuthHash:p,code:e,fragment:t,state:r.toObjectCopy(),timeoutMs:o};try{if(l=await B(tO(Wy,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(h)}),{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(m){c=m}}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=rg.parse(await l.json())}catch(h){throw new Error(`Code evaluation server returned invalid response: ${h}`)}if(u.error)throw new Error(`Code evaluation error: ${u.error}`);return u}async function ao(n){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await qy(n);else if(n.localTools)e=await Gy({...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 Ut(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 h of p){if(h.length<2)continue;let m=h[1].trim(),g;try{g=await ao({orgId:e,code:m,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 '${m}' 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(h[0],f)}return u}async function _l(n){return Ky(n)}async function Ky({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 Ut({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 Ky({obj:c,bannedKeys:e,context:r,prefixPath:d,replacements:i,allowList:l?void 0:t,...a})}return i}function Yy(n,e){for(let{path:t,original:r}of e)nO(n,t,r)}import rO from"fetch-retry";var d8=process.env.MAILINATOR_API_KEY,p8=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 Xy(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,h=500;for(;p<2||Date.now()-d<r;){p++,p>1&&await K(h,l),l?.throwIfAborted();try{let{newTarget:m,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:Fr(e),allowZeroOpacityOverride:!0}});if(u={success:f.success,data:f.data,err:f.err,newTarget:m,elementInteractedDisplayString:g},!f.success){u=f,h=Math.min(h*2,1e4);continue}return u}catch(m){if(l?.throwIfAborted(),c)return{success:!0,thoughts:`The element described does not exist on the page: ${m.message}`};if(s.warn({err:m},"Element assertion ended in error, retrying..."),!(m instanceof R)||m.reason!="ActionFailureError")throw m;u={success:!1,err:m}}}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:Be(l,500,!0)},!Dl(l,r.value,r.operation,!!r.negated)){let c=r.negated?Qt[r.operation]:Zt[r.operation];o=!1,i=new R("AssertionFailureError",`The content ${c} '${r.value}': ${l}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:Be(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(!Dl(l,r.value,r.operation,!!r.negated)){let c=r.negated?Qt[r.operation]:Zt[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(h=>setTimeout(h,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?Qd[r.condition]:Zd[r.condition];i=new R("AssertionFailureError",`The element ${l}`)}break}case"ELEMENT_NAME":{let l=await n.evaluate(c=>c.tagName);if(!Dl(l,r.value,r.operation,!!r.negated)){let c=r.negated?Qt[r.operation]:Zt[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(!Dl(l,r.value,r.operation,!!r.negated)){let c=r.negated?Qt[r.operation]:Zt[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 Dl(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 Ua(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 Jy}from"jimp";import Dp from"jpeg-js";import aO from"pixelmatch";async function Qy({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 _=>Ua(o,{locator:_.locator,...l}),options:{...t,disableCache:r,disableGlobalLocatorRedirect:!0}})).result:c=await Ua(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 z=`${c.width}x${c.height}`,_=`${d.width}x${d.height}`;return{fail:!0,thoughts:`Current screenshot (${z}) does not match saved screenshot dimensions (${_}) - 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 Jy.fromBuffer(c.buffer),u={width:c.width,height:c.height},h=await Jy.fromBuffer(d.buffer),m={width:d.width,height:d.height},g,f=u.width*u.height,S=m.width*m.height,b=Math.abs(u.height-m.height),w=Math.abs(u.width-m.width);if(f>S){let z=p.cover({w:m.width,h:m.height});c.buffer=await z.getBuffer("image/jpeg"),g="current",c.width=m.width,c.height=m.height}else if(S>f){let z=h.cover({w:u.width,h:u.height});d.buffer=await z.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(Dp.decode(d.buffer).data,Dp.decode(c.buffer).data,T.data,c.width,c.height,{threshold:C,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,N=A>C*100,O=`Visual diff of ${A.toFixed(2)}% detected, which is ${N?"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.`),N)throw new R("ActionFailureError",O);return{fail:N,thoughts:O,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:Dp.encode(T,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var sO=3e4;async function Zy({command:n,logger:e,baseUrl:t,fetchImplementation:r=fetch}){let o=n.timeout??sO/1e3,i=Object.fromEntries(Object.entries(n.headers||{}).filter(([h,m])=>h&&m)),a=new URLSearchParams;Object.entries(n.params||{}).filter(([h,m])=>h&&m).forEach(([h,m])=>{a.append(h,m)});let s=a.toString(),l;if(Go(n.url)&&(l=n.url),t&&Wo(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 B((async()=>{let h=s?`${l}?${s}`:l;try{return await r(h,{headers:i,method:n.method,body:n.body})}catch(m){throw e.error({err:m},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${m}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new R("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok){let h;try{h=await d.text()}catch(m){h=`Failed to read response body: ${m}`}throw new R("ActionFailureError",`Fetch request failed with status ${d.status}: ${h}`)}let p={};d.headers.forEach((h,m)=>{p[m]=h});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 Fl({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 eb(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 K(s,e.signal),s=Math.min(Math.floor(s*1.5),lO);else return i}return i=await eb(e),i}async function eb({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(tb,{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(tb,{value:n.value,negated:!!n.negated,returnHtml:!0},"checking page content"));if(!i){let l=n.negated?Qt.CONTAINS:Zt.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 tb({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 Fp=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,h=!1,m,g;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",S=await Ut({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<Mg;){p?.throwIfAborted();let w=await i.getCacheResult(g);if(w){r.debug({cacheResult:w},"Got result from module execution cache"),u=Ul(e,t,"SUCCESS"),u.message="Used cached module result.",u.data=JSON.parse(w),h=!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){m=T.keyPrefix,r.info({cacheKeyPrefixIfLockAcquired:m,cacheKey:f,keyParams:g},"Acquired cache lock and proceeding with module execution");break}else r.debug({cacheKeyPrefixIfLockAcquired:m,cacheKey:f,keyParams:g},"Failed to acquire cache lock, retrying...");await K(2500+Math.random()*1e4,p)}}try{if(!u)u=await dO(n);else if(e.autoAuth){let f=js.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 Fl({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),Fp(n)}}finally{try{m!==void 0&&!h&&u?.status==="SUCCESS"&&await pO({step:e,result:u,browser:s.browser,cacheKeyPrefix:m,logger:r,storage:i})}finally{m!==void 0&&await i.releaseCacheLock(m)}}return u},dO=async n=>{let{step:e,tracer:t}=n.moduleParams,r=Ul(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 Ul(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 nb({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 ao({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===df)&&(a=n.defaultCacheTtl??pf);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:Bf(s)},"Setting module cache result"),await i.setCacheResult({result:s,keyPrefix:r,ttlMs:a})}async function so(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=Ul(n,{},"FAILED");return l.message=s,l.startedAt=r,l.finishedAt=i,l}return{...ll(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 rb}from"crypto";var Bl=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=ia(e.command);n.work.asyncTasks.push(a.reportCreditsUsed(p,d,u,{testId:l?.id,testName:l?.name,suiteId:c?.id,suiteName:c?.name}));let h=o.browser.url(),m=new Date,g,f=rb(),S=rb();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=Us();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}=mO({work:n.work,step:e,newTargets:E.newTargets,logger:p}),N=new Date,O=o.browser.url();w={beforeUrl:h,afterUrl:O,startedAt:m,finishedAt:N,viewport:o.browser.getViewport(),status:E.fail?"FAILED":"SUCCESS",elementInteracted:E.elementInteracted},b={...e,message:E.thoughts??hO(E.newTargets)??"Successfully executed preset action.",beforeUrl:h,afterUrl:O,finishedAt:N,startedAt:m,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 ${Kr(e.command)}`);let A=o.browser.url(),N=new Date,O=E instanceof Error?E.message:`${E}`;E instanceof R&&E.getLastScreenshotBuffer()&&(T=E.getLastScreenshotBuffer()),w={beforeUrl:h,afterUrl:A,startedAt:m,finishedAt:N,viewport:o.browser.getViewport(),status:E instanceof DOMException&&E.name==="AbortError"?"CANCELLED":"FAILED",message:O},b={...e,startedAt:m,finishedAt:N,beforeUrl:h,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 mO({step:n,newTargets:e,logger:t}){if(!e?.length)return{proposedStep:void 0};let r=n.command;return Mf(r,e,t),{proposedStep:void 0}}function hO(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}
|
|
@@ -3929,7 +3929,7 @@ ${a.stack}`),l.status(500).send("Internal Server Error")}),n){let a=Fv.static(n,
|
|
|
3929
3929
|
for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
|
|
3930
3930
|
`)}import sD from"events";import Uc from"fs";import lD from"open";import{cpus as cE}from"os";import Fc from"path";import{fileURLToPath as cD}from"url";import r_ from"diff-lines";import{gt as o_}from"semver";import{execSync as Dk}from"child_process";import{platform as Fk}from"os";function Nu(){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.
|
|
3931
3931
|
`),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.
|
|
3932
|
-
l.`),1)}function Hv(){return Fk()==="darwin"&&Dk("system_profiler SPDisplaysDataType").toString().includes("Retina")}function ku(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 Uk from"@actions/exec";import Bk from"@actions/io";import zk from"quote";import Hk from"string-argv";async function jv(n,e=!0){let t=Hk(n),r=await Bk.which(t[0],!0),o=t.slice(1),i=Uk.exec(zk(r),o,{delay:100});if(e)return i}import{existsSync as jk,statSync as $k}from"fs";var Ka=!!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 jk(n)&&$k(n).isDirectory()}catch(e){return y.error({err:e},`Error reading path ${n} during directory existence check`),!1}}import Gk from"csv-parser";import{createReadStream as Wk}from"fs";function _u(n){return new Promise((e,t)=>{let r=[];Wk(n).pipe(Gk()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>t(o))})}import mc from"semver";import{z as hc}from"zod";var zn="2.11.0",Vk="https://registry.npmjs.org/momentic",qk=hc.object({versions:hc.record(hc.string(),hc.unknown()).optional()});async function Gv(n){try{await Kk(n)}catch(e){y.warn({err:e},"Failed to check CLI version against NPM servers")}}async function Kk(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 B(fetch(Vk),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=qk.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))mc.valid(r)&&(!t||mc.gt(r,t))&&mc.gt(r,zn)&&mc.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 Xk,input as Jk}from"@inquirer/prompts";import{existsSync as Qk,mkdirSync as Zk,statSync as e_}from"fs";import{dirname as t_}from"path";import{hostname as Yk}from"os";var Y=ic({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:Yk(),disableConsoleLogs:!0}).child({version:"2.11.0"});var n_=!1,Vv=(()=>{try{return e_("/.dockerenv"),!0}catch{return!1}})();async function bt(n,e){return Ka||n_||Vv?!0:(Y.flush(),await new Promise(r=>setTimeout(r,500)),await Xk({message:n}))}async function Du(n){let e=t_(n);return $v(e)?Qk(n)?bt(`File '${Wv(n)}' already exists. Overwrite existing content?`,!0):!0:await bt(`Directory '${Wv(e)}' doesn't exist. Create it now?`,!0)?(Zk(e,{recursive:!0}),!0):!1}function Wv(n){return n.replace(/(\s+)/g,"\\$1")}async function qv(n,e){return Ka||Vv?e:(await Jk({message:n,default:e})).trim()||e}async function Kv({test:n,fragment:e,entities:t,client:r,logger:o,yes:i}){o_(e.schemaVersion,Ie)&&(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)),Of(e.steps).forEach(m=>{t.modules[m]||(y.error(`The test patch contains a module with id ${m} 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 bt("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 bt("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=no(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!==Ie){let{steps:m,newVersion:g}=await ua({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:y});d=g,p=ke.array().parse(m)}else p=ke.array().parse(e.steps);let{stepsToSave:u}=await gt({stepLists:{steps:p}});u.beforeSteps=l.beforeSteps??void 0,u.afterSteps=l.afterSteps??void 0;let h=r_(JSON.stringify(c,void 0,2),JSON.stringify(u,void 0,2),{n_surrounding:5});y.dimmed("=".repeat(30)),y.dimmed(h),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 bt("Do you want to apply this patch?")&&(y.dimmed("Cancelled."),process.exit(1)),Xn({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 zt}from"crypto";import{z as fT}from"zod";var at=" ".repeat(6);import gT from"chalk";import{Argument as fo,InvalidArgumentError as Ya,Option as ye}from"@commander-js/extra-typings";import{validateHeaderValue as i_}from"http";import{z as Xv}from"zod";var Yv=58888,gc=30*60*1e3;function or(n){let e=parseInt(n,10);if(isNaN(e))throw new Ya("Not a number.");return e}function fc(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);i_(o,i),e[o]=i}return e}var Sn=new ye("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(n=>{if(!n)throw new Ya("API key is required.");return n}).makeOptionMandatory(),yn=new ye("--server <server>","Momentic server to use.").default("https://api.momentic.ai").argParser(n=>{try{return Xv.string().url().parse(n),n}catch{throw new Ya("Not a valid URL.")}}),Rr=new ye("-y, --yes","Skip all confirmation prompts.").env("CI"),Fu=new ye("-w, --wait","Wait for tests to finish running before exiting."),Uu=new ye("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Defaults to ${gc/1e3} seconds.`).default(gc/1e3).implies({wait:!0}).argParser(or),Sc=new ye("--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 ye("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(Fs)),Qv=new ye("--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"),Bu=new ye("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),Zv=new ye("--upload-results","Upload test results to Momentic Cloud.").default(!1),zu=new ye("--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."),Hu=new ye("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),ju=new ye("--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(or),eT=new ye("--port <port>",`Port to run the app on. Defaults to ${Yv}.`).default(Yv).argParser(or),$u=new ye("--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."),yc=new ye("--env <env>","Name of the environment to use when running tests."),bc=new ye("--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 Ya("Not a valid URL.")}}),tT=new ye("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(n=>{let e=or(n);if(e<1)throw new Ya("Shard index must be greater than 0.");return e}),nT=new ye("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(or),Bt=new ye("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),Ci=new ye("-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 ye("--fix","Attempt to fix any issues found."),Gu=new ye("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI"),Wu=new ye("--disable-cache","Disable caching of test results."),oT=new ye("--skip-quarantined","Skip quarantined tests entirely.").implies({onlyQuarantined:!1,ignoreQuarantine:!1}),iT=new ye("--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 ye("--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 ye("--ignore-failed-setup","Set the status of tests that failed during setup to 'cancelled' instead of failed, in order to not fail the entire pipeline."),lT=new fo("<tests...>","One or more test paths to queue on Momentic Cloud."),cT=new fo("<tests...>","One or more test paths to import from Momentic Cloud.").argOptional(),Vu=new fo("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional(),dT=new fo("<suites...>","One or more suite paths that exist on Momentic Cloud."),pT=new fo("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),uT=new fo("<results>","Path to the results archive.").argRequired(),qu=new ye("--reason <reason>","The reason for quarantining the test. This will be used to generate a report on the test run."),Ku=new fo("<test>","Name of the test to quarantine.").argOptional();async function Yu(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 mT}from"console";import{format as Xa}from"util";var Xu=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}},wc=class n extends mT{_buffer=[];_groupDepth=0;Console=mT;constructor(){super({write:e=>(n.write(this._buffer,"log",e),!0)})}static write(e,t,r,o=2){let i=new Xu(void 0,n.write).stack;if(!i)return e;let a=i.split(`
|
|
3932
|
+
l.`),1)}function Hv(){return Fk()==="darwin"&&Dk("system_profiler SPDisplaysDataType").toString().includes("Retina")}function ku(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 Uk from"@actions/exec";import Bk from"@actions/io";import zk from"quote";import Hk from"string-argv";async function jv(n,e=!0){let t=Hk(n),r=await Bk.which(t[0],!0),o=t.slice(1),i=Uk.exec(zk(r),o,{delay:100});if(e)return i}import{existsSync as jk,statSync as $k}from"fs";var Ka=!!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 jk(n)&&$k(n).isDirectory()}catch(e){return y.error({err:e},`Error reading path ${n} during directory existence check`),!1}}import Gk from"csv-parser";import{createReadStream as Wk}from"fs";function _u(n){return new Promise((e,t)=>{let r=[];Wk(n).pipe(Gk()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>t(o))})}import mc from"semver";import{z as hc}from"zod";var zn="2.11.1",Vk="https://registry.npmjs.org/momentic",qk=hc.object({versions:hc.record(hc.string(),hc.unknown()).optional()});async function Gv(n){try{await Kk(n)}catch(e){y.warn({err:e},"Failed to check CLI version against NPM servers")}}async function Kk(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 B(fetch(Vk),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=qk.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))mc.valid(r)&&(!t||mc.gt(r,t))&&mc.gt(r,zn)&&mc.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 Xk,input as Jk}from"@inquirer/prompts";import{existsSync as Qk,mkdirSync as Zk,statSync as e_}from"fs";import{dirname as t_}from"path";import{hostname as Yk}from"os";var Y=ic({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:Yk(),disableConsoleLogs:!0}).child({version:"2.11.1"});var n_=!1,Vv=(()=>{try{return e_("/.dockerenv"),!0}catch{return!1}})();async function bt(n,e){return Ka||n_||Vv?!0:(Y.flush(),await new Promise(r=>setTimeout(r,500)),await Xk({message:n}))}async function Du(n){let e=t_(n);return $v(e)?Qk(n)?bt(`File '${Wv(n)}' already exists. Overwrite existing content?`,!0):!0:await bt(`Directory '${Wv(e)}' doesn't exist. Create it now?`,!0)?(Zk(e,{recursive:!0}),!0):!1}function Wv(n){return n.replace(/(\s+)/g,"\\$1")}async function qv(n,e){return Ka||Vv?e:(await Jk({message:n,default:e})).trim()||e}async function Kv({test:n,fragment:e,entities:t,client:r,logger:o,yes:i}){o_(e.schemaVersion,Ie)&&(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)),Of(e.steps).forEach(m=>{t.modules[m]||(y.error(`The test patch contains a module with id ${m} 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 bt("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 bt("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=no(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!==Ie){let{steps:m,newVersion:g}=await ua({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:y});d=g,p=ke.array().parse(m)}else p=ke.array().parse(e.steps);let{stepsToSave:u}=await gt({stepLists:{steps:p}});u.beforeSteps=l.beforeSteps??void 0,u.afterSteps=l.afterSteps??void 0;let h=r_(JSON.stringify(c,void 0,2),JSON.stringify(u,void 0,2),{n_surrounding:5});y.dimmed("=".repeat(30)),y.dimmed(h),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 bt("Do you want to apply this patch?")&&(y.dimmed("Cancelled."),process.exit(1)),Xn({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 zt}from"crypto";import{z as fT}from"zod";var at=" ".repeat(6);import gT from"chalk";import{Argument as fo,InvalidArgumentError as Ya,Option as ye}from"@commander-js/extra-typings";import{validateHeaderValue as i_}from"http";import{z as Xv}from"zod";var Yv=58888,gc=30*60*1e3;function or(n){let e=parseInt(n,10);if(isNaN(e))throw new Ya("Not a number.");return e}function fc(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);i_(o,i),e[o]=i}return e}var Sn=new ye("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(n=>{if(!n)throw new Ya("API key is required.");return n}).makeOptionMandatory(),yn=new ye("--server <server>","Momentic server to use.").default("https://api.momentic.ai").argParser(n=>{try{return Xv.string().url().parse(n),n}catch{throw new Ya("Not a valid URL.")}}),Rr=new ye("-y, --yes","Skip all confirmation prompts.").env("CI"),Fu=new ye("-w, --wait","Wait for tests to finish running before exiting."),Uu=new ye("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Defaults to ${gc/1e3} seconds.`).default(gc/1e3).implies({wait:!0}).argParser(or),Sc=new ye("--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 ye("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(Fs)),Qv=new ye("--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"),Bu=new ye("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),Zv=new ye("--upload-results","Upload test results to Momentic Cloud.").default(!1),zu=new ye("--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."),Hu=new ye("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),ju=new ye("--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(or),eT=new ye("--port <port>",`Port to run the app on. Defaults to ${Yv}.`).default(Yv).argParser(or),$u=new ye("--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."),yc=new ye("--env <env>","Name of the environment to use when running tests."),bc=new ye("--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 Ya("Not a valid URL.")}}),tT=new ye("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(n=>{let e=or(n);if(e<1)throw new Ya("Shard index must be greater than 0.");return e}),nT=new ye("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(or),Bt=new ye("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),Ci=new ye("-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 ye("--fix","Attempt to fix any issues found."),Gu=new ye("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI"),Wu=new ye("--disable-cache","Disable caching of test results."),oT=new ye("--skip-quarantined","Skip quarantined tests entirely.").implies({onlyQuarantined:!1,ignoreQuarantine:!1}),iT=new ye("--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 ye("--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 ye("--ignore-failed-setup","Set the status of tests that failed during setup to 'cancelled' instead of failed, in order to not fail the entire pipeline."),lT=new fo("<tests...>","One or more test paths to queue on Momentic Cloud."),cT=new fo("<tests...>","One or more test paths to import from Momentic Cloud.").argOptional(),Vu=new fo("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional(),dT=new fo("<suites...>","One or more suite paths that exist on Momentic Cloud."),pT=new fo("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),uT=new fo("<results>","Path to the results archive.").argRequired(),qu=new ye("--reason <reason>","The reason for quarantining the test. This will be used to generate a report on the test run."),Ku=new fo("<test>","Name of the test to quarantine.").argOptional();async function Yu(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 mT}from"console";import{format as Xa}from"util";var Xu=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}},wc=class n extends mT{_buffer=[];_groupDepth=0;Console=mT;constructor(){super({write:e=>(n.write(this._buffer,"log",e),!0)})}static write(e,t,r,o=2){let i=new Xu(void 0,n.write).stack;if(!i)return e;let a=i.split(`
|
|
3933
3933
|
`).slice(o).filter(Boolean).join(`
|
|
3934
3934
|
`);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",Xa(e,...t))}error(e,...t){this._log("error",Xa(e,...t))}info(e,...t){this._log("info",Xa(e,...t))}log(e,...t){this._log("log",Xa(e,...t))}warn(e,...t){this._log("warn",Xa(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function hT(n){let e=globalThis.console,t=new wc;globalThis.console=t;try{n()}finally{let o=t.getBuffer()?.map(i=>i.message).join(`
|
|
3935
3935
|
`);process.stderr.write(`${o}
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "momentic",
|
|
3
|
-
"version": "2.11.
|
|
3
|
+
"version": "2.11.1",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "momentic",
|
|
9
|
-
"version": "2.11.
|
|
9
|
+
"version": "2.11.1",
|
|
10
10
|
"dependencies": {
|
|
11
11
|
"@actions/exec": "^1.1.1",
|
|
12
12
|
"@actions/io": "^1.1.3",
|