momentic 1.0.18 → 1.0.19
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 +4 -4
- package/package.json +1 -1
package/bin/cli.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
var Ff=Object.create;var nc=Object.defineProperty;var Uf=Object.getOwnPropertyDescriptor;var $f=Object.getOwnPropertyNames;var Bf=Object.getPrototypeOf,zf=Object.prototype.hasOwnProperty;var oc=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Wf=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of $f(e))!zf.call(r,o)&&o!==t&&nc(r,o,{get:()=>e[o],enumerable:!(n=Uf(e,o))||n.enumerable});return r};var jf=(r,e,t)=>(t=r!=null?Ff(Bf(r)):{},Wf(e||!r||!r.__esModule?nc(t,"default",{value:r,enumerable:!0}):t,r));var Rp=oc((Nq,xp)=>{"use strict";xp.exports=vp;function vp(r,e,t){r instanceof RegExp&&(r=Cp(r,t)),e instanceof RegExp&&(e=Cp(e,t));var n=Ap(r,e,t);return n&&{start:n[0],end:n[1],pre:t.slice(0,n[0]),body:t.slice(n[0]+r.length,n[1]),post:t.slice(n[1]+e.length)}}function Cp(r,e){var t=e.match(r);return t?t[0]:null}vp.range=Ap;function Ap(r,e,t){var n,o,s,i,a,l=t.indexOf(r),c=t.indexOf(e,l+1),u=l;if(l>=0&&c>0){if(r===e)return[l,c];for(n=[],s=t.length;u>=0&&!a;)u==l?(n.push(u),l=t.indexOf(r,u+1)):n.length==1?a=[n.pop(),c]:(o=n.pop(),o<s&&(s=o,i=c),c=t.indexOf(e,u+1)),u=l<c&&l>=0?l:c;n.length&&(a=[s,i])}return a}});var kp=oc((_q,_p)=>{"use strict";var Ip=Rp();_p.exports=JT;var Pp="\0SLASH"+Math.random()+"\0",Op="\0OPEN"+Math.random()+"\0",cl="\0CLOSE"+Math.random()+"\0",Lp="\0COMMA"+Math.random()+"\0",Mp="\0PERIOD"+Math.random()+"\0";function ll(r){return parseInt(r,10)==r?parseInt(r,10):r.charCodeAt(0)}function YT(r){return r.split("\\\\").join(Pp).split("\\{").join(Op).split("\\}").join(cl).split("\\,").join(Lp).split("\\.").join(Mp)}function XT(r){return r.split(Pp).join("\\").split(Op).join("{").split(cl).join("}").split(Lp).join(",").split(Mp).join(".")}function Np(r){if(!r)return[""];var e=[],t=Ip("{","}",r);if(!t)return r.split(",");var n=t.pre,o=t.body,s=t.post,i=n.split(",");i[i.length-1]+="{"+o+"}";var a=Np(s);return s.length&&(i[i.length-1]+=a.shift(),i.push.apply(i,a)),e.push.apply(e,i),e}function JT(r){return r?(r.substr(0,2)==="{}"&&(r="\\{\\}"+r.substr(2)),ho(YT(r),!0).map(XT)):[]}function ZT(r){return"{"+r+"}"}function QT(r){return/^-?0\d/.test(r)}function eE(r,e){return r<=e}function tE(r,e){return r>=e}function ho(r,e){var t=[],n=Ip("{","}",r);if(!n)return[r];var o=n.pre,s=n.post.length?ho(n.post,!1):[""];if(/\$$/.test(n.pre))for(var i=0;i<s.length;i++){var a=o+"{"+n.body+"}"+s[i];t.push(a)}else{var l=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(n.body),c=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(n.body),u=l||c,d=n.body.indexOf(",")>=0;if(!u&&!d)return n.post.match(/,.*\}/)?(r=n.pre+"{"+n.body+cl+n.post,ho(r)):[r];var m;if(u)m=n.body.split(/\.\./);else if(m=Np(n.body),m.length===1&&(m=ho(m[0],!1).map(ZT),m.length===1))return s.map(function(j){return n.pre+m[0]+j});var p;if(u){var h=ll(m[0]),f=ll(m[1]),g=Math.max(m[0].length,m[1].length),y=m.length==3?Math.abs(ll(m[2])):1,S=eE,w=f<h;w&&(y*=-1,S=tE);var T=m.some(QT);p=[];for(var C=h;S(C,f);C+=y){var A;if(c)A=String.fromCharCode(C),A==="\\"&&(A="");else if(A=String(C),T){var I=g-A.length;if(I>0){var O=new Array(I+1).join("0");C<0?A="-"+O+A.slice(1):A=O+A}}p.push(A)}}else{p=[];for(var x=0;x<m.length;x++)p.push.apply(p,ho(m[x],!1))}for(var x=0;x<p.length;x++)for(var i=0;i<s.length;i++){var a=o+p[x]+s[i];(!e||u||a)&&t.push(a)}}return t}});import{Command as Gv,Option as mr}from"@commander-js/extra-typings";import{execSync as Vv}from"child_process";import{z as jo}from"zod";import{z as Xi}from"zod";function Z(r){if(typeof r.ZodType.prototype.openapi<"u")return;r.ZodType.prototype.openapi=function(o){return new this.constructor({...this._def,openapi:o})};let e=r.ZodObject.prototype.extend;r.ZodObject.prototype.extend=function(...o){let s=e.apply(this,o);return s._def.extendMetadata={extends:this},delete s._def.openapi,s};let t=r.ZodObject.prototype.omit;r.ZodObject.prototype.omit=function(...o){let s=t.apply(this,o);return delete s._def.extendMetadata,delete s._def.openapi,s};let n=r.ZodObject.prototype.pick;r.ZodObject.prototype.pick=function(...o){let s=n.apply(this,o);return delete s._def.extendMetadata,delete s._def.openapi,s}}import{z as Yi}from"zod";import{v4 as le}from"uuid";import*as b from"zod";import{z as K}from"zod";Z(K);var sc=K.object({thoughts:K.string(),result:K.boolean(),relevantElements:K.array(K.number()).optional()}),Pn=(n=>(n.CONTAINS="CONTAINS",n.STARTS_WITH="STARTS_WITH",n.EQUALS="EQUALS",n))(Pn||{});var Hf=K.object({type:K.literal("ELEMENT_CONTENT"),negated:K.boolean().optional(),operation:K.nativeEnum(Pn),value:K.string()}).openapi({ref:"ElementContentAssertion"}),Gf=K.object({type:K.literal("ELEMENT_ATTRIBUTE"),negated:K.boolean().optional(),operation:K.nativeEnum(Pn),attr:K.string(),value:K.string()}).openapi({ref:"ElementAttributeValueAssertion"}),On=(o=>(o.EXISTS="EXISTS",o.VISIBLE="VISIBLE",o.ENABLED="ENABLED",o.EDITABLE="EDITABLE",o))(On||{}),Vf=K.object({type:K.literal("ELEMENT_EXISTENCE"),negated:K.boolean().optional(),condition:K.nativeEnum(On)}).openapi({ref:"ElementExistenceAssertion"}),ic=K.discriminatedUnion("type",[Hf,Gf,Vf]).openapi({ref:"ManualElementAssertion"});var qf=K.object({type:K.literal("CONTENT"),negated:K.boolean().optional(),value:K.string()}).openapi({ref:"PageContentAssertion"}),ac=K.discriminatedUnion("type",[qf]).openapi({ref:"ManualPageAssertion"});import*as F from"zod";Z(F);var hr=(a=>(a.AI="AI",a.AI_HEALED="AI_HEALED",a.CLICK_TO_FIND="CLICK_TO_FIND",a.XY_PERCENT="XY_PERCENT",a.RECORDING="RECORDING",a.USER_CSS_SELECTOR="USER_CSS_SELECTOR",a.HEURISTIC_HEALED="HEURISTIC_HEALED",a))(hr||{}),fr=F.object({id:F.number().int(),dataMomenticId:F.number().int().optional(),selector:F.string().optional(),generatedSelectors:F.string().array().optional(),role:F.string().optional(),name:F.string().optional(),numChildren:F.number().optional(),content:F.string().optional(),pathFromRoot:F.string().optional(),serializedForm:F.string().optional(),nodeOnlySerializedForm:F.string().optional(),serializedHtml:F.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:F.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:F.string().url().optional(),boundingBox:F.object({x:F.number().optional(),y:F.number().optional(),width:F.number(),height:F.number()}).describe("css pixel bounding box").optional(),inputDescription:F.string().optional().describe("the description that generated this cache"),targetSource:F.nativeEnum(hr).optional(),targetUpdateTime:F.string().optional()}).openapi({ref:"A11yTargetWithCache"});function Do(r){return!!(r.name||r.role||r.content||r.serializedForm||r.serializedHtml||r.screenshotUrl)}var Kf=F.object({percentX:F.number().describe("between 0 and 1"),percentY:F.number()}),Yf=F.object({type:F.literal("description"),elementDescriptor:F.string(),a11yData:fr.optional().describe("DEPRECATED: new a11y cache is stored in DB and resolved into the 'cache' field")}).openapi({ref:"DescriptionTarget"});function vt(r){return r.type==="description"}function gr(r){return r.type==="coordinates"}var Ie=F.discriminatedUnion("type",[Yf,F.object({type:F.literal("coordinates"),percentXYLocation:Kf}).openapi({ref:"CoordinatesTarget"})]).openapi({ref:"ElementTarget"});function ji(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor;case"coordinates":return r.percentXYLocation.percentX>=0||r.percentXYLocation.percentY>=0}return!0}function Pe(r){if(!r)return"";switch(r.type){case"description":return r.elementDescriptor;case"coordinates":return`x: ${r.percentXYLocation.percentX}, y: ${r.percentXYLocation.percentY}`}}import{z as Q}from"zod";var Fo=Q.object({url:Q.string(),method:Q.union([Q.literal("GET"),Q.literal("POST"),Q.literal("PUT"),Q.literal("DELETE"),Q.literal("PATCH")]),headers:Q.record(Q.string(),Q.string()).optional(),params:Q.record(Q.string(),Q.string()).optional(),body:Q.string().optional(),timeout:Q.number().int().optional().describe("Max seconds to wait for the request to complete")}),Uo=Q.object({code:Q.string(),fragment:Q.boolean().optional(),environment:Q.union([Q.literal("NODE"),Q.literal("BROWSER")]).optional().describe("default NODE"),timeout:Q.number().int().max(60).optional().describe("Max seconds for the code to complete")});var he=(k=>(k.AI_EXTRACT="AI_EXTRACT",k.AI_ASSERTION="AI_ASSERTION",k.AI_WAIT="AI_WAIT",k.AUTH_LOAD="AUTH_LOAD",k.AUTH_SAVE="AUTH_SAVE",k.BLUR="BLUR",k.CAPTCHA="CAPTCHA",k.CLICK="CLICK",k.COOKIE="COOKIE",k.DIALOG="DIALOG",k.DRAG="DRAG",k.ELEMENT_CHECK="ELEMENT_CHECK",k.FILE_UPLOAD="FILE_UPLOAD",k.FOCUS="FOCUS",k.GO_BACK="GO_BACK",k.GO_FORWARD="GO_FORWARD",k.HOVER="HOVER",k.JAVASCRIPT="JAVASCRIPT",k.LOCAL_STORAGE="LOCAL_STORAGE",k.MOUSE_DRAG="MOUSE_DRAG",k.NAVIGATE="NAVIGATE",k.NEW_TAB="NEW_TAB",k.PAGE_CHECK="PAGE_CHECK",k.PRESS="PRESS",k.REFRESH="REFRESH",k.REQUEST="REQUEST",k.SCROLL_DOWN="SCROLL_DOWN",k.SCROLL_UP="SCROLL_UP",k.SCROLL_LEFT="SCROLL_LEFT",k.SCROLL_RIGHT="SCROLL_RIGHT",k.SELECT_OPTION="SELECT_OPTION",k.TAB="TAB",k.TYPE="TYPE",k.VISUAL_DIFF="VISUAL_DIFF",k.WAIT="WAIT",k.WAIT_FOR_URL="WAIT_FOR_URL",k.SUCCESS="SUCCESS",k))(he||{});Z(b);var B=b.object({thoughts:b.string().optional(),id:b.string().uuid().describe("unique identifier to this step, used for step cache")}),nt=b.object({useSelector:b.boolean().optional(),useXY:b.boolean().optional(),force:b.boolean().optional(),disableCache:b.boolean().optional().describe("disable element caching for this step"),iframeUrl:b.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),At=b.object({target:fr}).optional().openapi({ref:"SingleTargetCache"}),$o=b.object({loadTimeout:b.number().int().max(60).optional().describe("Max seconds for the page to load")}),Xf=B.merge($o).merge(b.object({type:b.literal("NAVIGATE"),url:b.string()})).openapi({ref:"NavigateCommand"}),Bo=nt.merge(b.object({cache:At})),$r=B.merge(Bo.merge(b.object({target:Ie.optional(),type:b.literal("SCROLL_UP"),deltaY:b.number().optional()}))).openapi({ref:"ScrollUpCommand"}),Br=B.merge(Bo.merge(b.object({target:Ie.optional(),type:b.literal("SCROLL_DOWN"),deltaY:b.number().optional()}))).openapi({ref:"ScrollDownCommand"}),zr=B.merge(Bo.merge(b.object({target:Ie.optional(),type:b.literal("SCROLL_LEFT"),deltaX:b.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Wr=B.merge(Bo.merge(b.object({target:Ie.optional(),type:b.literal("SCROLL_RIGHT"),deltaX:b.number().optional()}))).openapi({ref:"ScrollRightCommand"}),fA=b.discriminatedUnion("type",[$r,Br,zr,Wr]).openapi({ref:"AllScrollCommands"}),Jf=B.merge(b.object({type:b.literal("DIALOG"),action:b.union([b.literal("ACCEPT"),b.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),Zf=B.merge(b.object({type:b.literal("WAIT"),delay:b.number()})).openapi({ref:"WaitCommand"}),Qf=B.merge(b.object({type:b.literal("WAIT_FOR_URL"),url:b.string(),timeout:b.number().int().optional().describe("Max seconds to wait for the URL to match")})).openapi({ref:"WaitUrlCommand"}),eg=B.merge($o).merge(b.object({type:b.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),tg=B.merge(b.object({type:b.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),rg=B.merge(b.object({type:b.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),ng=B.extend({type:b.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),og=B.extend({type:b.literal("AUTH_LOAD"),storageState:b.string().describe("JSON string auth state")}).openapi({ref:"AuthLoadCommand"}),Gi=B.merge(nt).extend({type:b.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),sg=B.merge(Uo).extend({type:b.literal("JAVASCRIPT"),envKey:b.string().optional()}).openapi({ref:"JavaScriptCommand"}),Ln=B.merge(nt).merge(b.object({type:b.literal("CLICK"),target:Ie,doubleClick:b.boolean().optional(),rightClick:b.boolean().optional(),waitForUrl:b.string().optional().describe("Wait for the click to trigger a page load or new tab that matches the provided URL or URL glob (e.g. https://google.com/**/*)."),waitForDownload:b.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),cache:At})).openapi({ref:"ClickCommand"}),Mn=B.merge(nt).merge(b.object({type:b.literal("DRAG"),fromTarget:Ie,toTarget:Ie,hoverSeconds:b.number().optional().describe("Seconds to hover the object before dropping"),cache:b.object({fromTarget:fr.optional(),toTarget:fr.optional()}).optional()})).openapi({ref:"DragCommand"}),Nn=B.merge(nt).merge(b.object({type:b.literal("MOUSE_DRAG"),target:Ie.optional(),deltaX:b.string().describe("pixels to move horizontally, can be template"),deltaY:b.string().describe("pixels to move vertically, can be template"),steps:b.number().optional(),cache:At})).openapi({ref:"MouseDragCommand"}),_n=B.merge(nt).merge(b.object({type:b.literal("HOVER"),target:Ie,cache:At})).openapi({ref:"HoverCommand"}),kn=B.merge(nt).merge(b.object({type:b.literal("FOCUS"),target:Ie,cache:At})).openapi({ref:"FocusCommand"}),Dn=B.merge(nt).merge(b.object({type:b.literal("BLUR"),target:Ie,cache:At})).openapi({ref:"BlurCommand"}),ig=b.object({type:b.literal("URL"),url:b.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),ag=B.extend({type:b.literal("FILE_UPLOAD"),fileSource:b.discriminatedUnion("type",[ig])}).openapi({ref:"FileUploadCommand"}),lg=b.discriminatedUnion("type",[b.object({type:b.literal("VALUE"),value:b.string()}),b.object({type:b.literal("LABEL"),label:b.string()}),b.object({type:b.literal("INDEX"),index:b.number().int()})]),Fn=B.merge(nt).extend({type:b.literal("SELECT_OPTION"),target:Ie,cache:At,option:b.string().describe("option value, deprecated old field").optional(),choice:lg.optional().describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),Vi=B.merge(b.object({type:b.literal("AI_ASSERTION"),assertion:b.string(),disableCache:b.boolean().optional(),iframeUrl:b.string().optional(),timeout:b.number().int().optional().describe("Max seconds to wait for assertion to be true")})).openapi({ref:"AIAssertionCommand"}),cg=Vi.extend({type:b.literal("AI_WAIT")}).openapi({ref:"AIWaitCommand"}),yr=5,qi=600,Un=B.merge(nt).extend({type:b.literal("ELEMENT_CHECK"),target:Ie,assertion:ic,cache:At,timeout:b.number().int().min(0).max(qi).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),dg=B.extend({type:b.literal("PAGE_CHECK"),assertion:ac,iframeUrl:b.string().optional().describe("url or url regex for the iframe"),timeout:b.number().int().min(0).max(qi).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),ug=B.merge(b.object({type:b.literal("AI_EXTRACT"),goal:b.string(),schema:b.string().optional(),envKey:b.string().optional(),disableCache:b.boolean().optional(),iframeUrl:b.string().optional()})).openapi({ref:"AIExtractCommand"}),mg=b.object({clearContent:b.boolean().optional(),pressKeysSequentially:b.boolean().optional(),force:b.boolean().optional(),pressEnter:b.boolean().optional()}),$n=B.merge(nt).merge(mg).extend({type:b.literal("TYPE"),target:Ie.optional(),value:b.string(),cache:At}).openapi({ref:"TypeCommand"}),pg=B.merge(b.object({type:b.literal("PRESS"),value:b.string()})).openapi({ref:"PressCommand"}),hg=b.object({type:b.literal("SUBSTRING"),substring:b.string()}),fg=b.object({type:b.literal("REGEX"),pattern:b.string()}),gg=b.object({type:b.literal("INDEX"),index:b.number()}),yg=b.discriminatedUnion("type",[hg,fg,gg]),Sg=B.merge($o).merge(b.object({type:b.literal("TAB"),url:b.string().optional().describe("deprecated field - new instances should use the discriminated union"),action:yg.optional()})).openapi({ref:"TabCommand"}),wg=B.merge($o).merge(b.object({type:b.literal("NEW_TAB"),url:b.string()})).openapi({ref:"NewTabCommand"}),bg=B.merge(b.object({type:b.literal("COOKIE"),value:b.string()})).openapi({ref:"CookieCommand"}),Tg=B.merge(b.object({type:b.literal("LOCAL_STORAGE"),key:b.string(),value:b.string()})).openapi({ref:"LocalStorageCommand"}),Eg=B.extend({type:b.literal("REQUEST")}).merge(Fo).openapi({ref:"RequestCommand"}),Cg=B.merge(b.object({type:b.literal("SUCCESS"),condition:Vi.optional()})).openapi({ref:"SuccessCommand"}),vg=B.merge(b.object({type:b.literal("FAILURE")})).openapi({ref:"FailureCommand"}),Ag=b.object({data:b.string().describe("s3 url to a jpg"),width:b.number(),height:b.number()}),Bn=B.merge(nt).merge(b.object({type:b.literal("VISUAL_DIFF"),threshold:b.number().optional().describe("default 0.1"),target:Ie.optional(),screenshot:Ag.optional(),cache:At})).openapi({ref:"VisualDiffCommand"}),zo=b.discriminatedUnion("type",[Ln,$n,pg,Fn,Xf,Br,$r,Vi,_n,Zf,Cg]),xg=b.discriminatedUnion("type",[cg,ug,og,ng,Gi,bg,Jf,Mn,Un,ag,tg,rg,sg,Tg,Nn,wg,dg,eg,Eg,zr,Wr,Sg,Bn,kn,Dn,Qf]),Wo=b.discriminatedUnion("type",[...zo.options,...xg.options]).openapi({ref:"Command"}),Ki=b.discriminatedUnion("type",[...zo.options,vg]);function Qt(r){let e;switch(r){case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:le(),type:r};break;case"AUTH_LOAD":{e={id:le(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:le(),type:r,goal:""};break;case"DIALOG":e={id:le(),type:r,action:"DISMISS"};break;case"DRAG":e={id:le(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:le(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:le(),type:r,url:""};break;case"WAIT":e={id:le(),type:r,delay:1};break;case"HOVER":case"BLUR":case"FOCUS":case"CLICK":e={id:le(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"TYPE":e={id:le(),type:r,value:"",clearContent:!0};break;case"SELECT_OPTION":e={id:le(),type:r,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":case"TAB":e={id:le(),type:r,url:""};break;case"REQUEST":e={id:le(),type:r,url:"",method:"GET"};break;case"LOCAL_STORAGE":e={id:le(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:le(),type:r,code:""};break;case"AI_WAIT":case"AI_ASSERTION":e={id:le(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:le(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:le(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:le(),type:r,assertion:{type:"CONTENT",value:""}};break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return e}import{z as zn}from"zod";var He=zn.object({index:zn.number().optional().describe("global index within a test (in-order traversal)"),id:zn.string(),skipped:zn.boolean().optional(),envKey:zn.string().optional().describe("key in the environment to save the result of this step to")});Z(Yi);var ot=He.extend({type:Yi.literal("PRESET_ACTION"),command:Wo,skipped:Yi.boolean().optional()}).openapi({ref:"PresetAction"});Z(Xi);var jr=He.extend({type:Xi.literal("AI_ACTION"),text:Xi.string(),steps:ot.array().optional()}).openapi({ref:"AIAction"});import{z as re}from"zod";var Rg=re.object({cacheKey:re.string(),cacheExpiryMs:re.number()}),Ji=He.extend({id:re.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:re.record(re.string()).optional(),cacheConfig:Rg.optional()}),Hr=Ji.extend({type:re.literal("MODULE"),moduleId:re.string().uuid()}),Ig=re.union([Hr.pick({type:!0,moduleId:!0}),re.record(re.unknown())]),st=re.object({moduleId:re.string().uuid(),name:re.string(),description:re.string().nullish(),enabled:re.boolean().nullish(),parameters:re.string().array().nullish(),defaultParameters:re.record(re.string(),re.string()).nullish(),defaultCacheKey:re.string().nullish(),defaultCacheTtl:re.number().nullish()});import{z as Ee}from"zod";import{z as Zi}from"zod";Z(Zi);var Wn=He.extend({type:Zi.literal("AI_ACTION_DYNAMIC"),text:Zi.string()}).openapi({ref:"AIActionDynamic"});import{z as cc}from"zod";var jn=He.extend({type:cc.literal("CONDITIONAL"),skipped:cc.boolean().optional()});import{z as it}from"zod";var Pg=it.object({type:it.literal("attr"),name:it.string(),value:it.string()}),Og=it.object({type:it.literal("css"),selector:it.string()}),Lg=it.object({type:it.literal("url"),url:it.string()}),Mg=it.union([Pg,Lg,Og]),Hn=He.extend({type:it.literal("IFRAME"),identifier:Mg});import{z as at}from"zod";var Qi=(n=>(n.ALWAYS="ALWAYS",n.ON_FAILURE="ON_FAILURE",n.ON_ACTION_FAILURE="ON_ACTION_FAILURE",n))(Qi||{});var Ng=at.discriminatedUnion("type",[at.object({type:at.literal("NAVIGATE_URL"),url:at.string().url()}),at.object({type:at.literal("GO_TO_SECTION_START")})]),_g=at.object({trigger:at.nativeEnum(Qi).optional(),attempts:at.number().int().optional(),restartBehavior:Ng}),Gn=He.extend({type:at.literal("SECTION"),description:at.string().describe("user provided goal of what the section should accomplish"),plan:at.string().array().optional(),autohealingConfig:_g.optional()});var dc=st.merge(Ji).extend({type:Ee.literal("RESOLVED_MODULE"),steps:Ee.lazy(()=>fe.array())}),ea=st.extend({steps:Ee.lazy(()=>fe.array())}),kg=Hn.extend({steps:Ee.lazy(()=>lt.array())}),Dg=Hn.extend({steps:Ee.lazy(()=>fe.array())}),Fg=Gn.extend({steps:Ee.lazy(()=>lt.array())}),Ug=Gn.extend({steps:Ee.lazy(()=>fe.array())}),$g=jn.extend({blocks:Ee.object({assertion:Ee.lazy(()=>ot),steps:Ee.lazy(()=>lt.array())}).array(),elseSteps:Ee.lazy(()=>lt.array().optional())}),Bg=jn.extend({blocks:Ee.object({assertion:Ee.lazy(()=>ot),steps:Ee.lazy(()=>fe.array())}).array(),elseSteps:Ee.lazy(()=>fe.array().optional())}),lt=Ee.discriminatedUnion("type",[ot,jr,Wn,Hr,$g,kg,Fg]),fe=Ee.discriminatedUnion("type",[ot,jr,Wn,dc,Bg,Dg,Ug]);var ct="1.0.17";import{z as wr}from"zod";import{z as zg}from"zod";var Ax=zg.discriminatedUnion("type",[Dn,Gi,Ln,Mn,kn,_n,Nn,$r,Br,zr,Wr,Fn,$n,Bn,Un]);function uc(r){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(r)}import{z as Wg}from"zod";var Ge={type:!0,cache:!0},Sr=Wg.discriminatedUnion("type",[Dn.pick(Ge),Ln.pick(Ge),Mn.pick(Ge),Un.pick(Ge),kn.pick(Ge),_n.pick(Ge),Nn.pick(Ge),$r.pick(Ge),Br.pick(Ge),zr.pick(Ge),Wr.pick(Ge),Fn.pick(Ge),$n.pick(Ge),Bn.pick(Ge)]),ta=Object.values(he).filter(r=>Sr.options.some(e=>e.shape.type.safeParse(r).success));Wo.options.forEach(r=>{if("target"in r.shape&&!ta.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});var ra=wr.object({key:wr.string(),testId:wr.string().optional(),moduleId:wr.string().optional(),organizationId:wr.string(),value:Sr}),mc=wr.record(wr.string(),ra);var dR=jo.object({testId:jo.string(),orgId:jo.string(),runId:jo.string(),steps:fe.array()});import{z as br}from"zod";var pc=br.object({id:br.string().uuid(),skipped:br.boolean().optional(),envKey:br.string().optional().describe("key in the environment to save the result of this step to")}),na=pc.merge(Fo).extend({type:br.literal("REQUEST")}),oa=pc.merge(Uo).extend({type:br.literal("JAVASCRIPT")}),sa=br.discriminatedUnion("type",[oa,na]);import{z as ft}from"zod";import{z as Tr}from"zod";var jg=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,ge=r=>{let e=r.trim().toLowerCase().replace(/[^a-z0-9]/g,"-");for(;e.includes("--");)e=e.replaceAll("--","-");return e.startsWith("-")&&(e=e.slice(1)),e.endsWith("-")&&(e=e.slice(0,e.length-1)),e};var Ho=Tr.string().min(1).max(255).superRefine((r,e)=>{try{Vn(r)}catch(t){return e.addIssue({code:Tr.ZodIssueCode.custom,message:t.message,fatal:!0}),Tr.NEVER}});function Vn(r){if(r=r.toLowerCase().trim(),r.length===0||r.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(r))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(r.endsWith("-")||r.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(r.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(r))throw new Error(`"${r}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(r)||/^\s|\s$/.test(r))throw new Error("Name cannot start or end with a space or dot.");if(r.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(r==="none")throw new Error("Name cannot be 'none'.");if(r.match(jg))throw new Error("Name cannot be a UUID. Please choose a different name.")}var Go=Tr.preprocess(r=>r===null?"":r,Tr.union([Tr.string().url(),Tr.literal("")])).optional();import{isValidCron as Hg}from"cron-validator";import{z as Y}from"zod";import{z as ia}from"zod";var Vo=ia.object({width:ia.number().min(200).max(1e4),height:ia.number().min(200).max(1e4)}),hc={"Desktop Large":{width:1920,height:1080},"Desktop Small":{width:1280,height:800},iPad:{width:768,height:1024},"Pixel 8":{width:448,height:998},"iPhone 15":{width:393,height:852}},SR=Object.keys(hc);var $t=hc["Desktop Large"];import{z as Je}from"zod";var oe="BASE_URL",qo="CURRENT_URL",Gr="ENV_NAME",TR={[oe]:"https://www.google.com"},fc=Je.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),Ko=Je.object({name:Je.string(),variables:Je.record(Je.string().describe("variable name"),Je.string().describe("variable value"))}),aa=Je.object({localChromeExtensionPaths:Je.string().array().optional()}),Yo=Je.object({name:Je.string(),variables:Je.record(Je.string().describe("variable name"),Je.unknown().describe("variable value")),browser:aa.optional()});var gc=1e4,yc=6e4,Vr=(t=>(t.CHROMIUM="Chromium",t.GOOGLE_CHROME="Google Chrome",t))(Vr||{}),qn=Y.object({browserType:Y.nativeEnum(Vr).default("Chromium").optional(),pageLoadTimeoutMs:Y.number().optional().refine(r=>r===void 0||r<=yc&&r>=-1,{message:`Page load timeout must be between 0 and ${yc/1e3} seconds`}),smartWaitingTimeoutMs:Y.number().optional().refine(r=>r===void 0||r<=gc&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${gc/1e3} seconds`}),extraHeaders:Y.record(Y.string(),Y.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:Y.string().optional(),localChromeExtensionPaths:Y.string().array().optional()});var Gg=Y.object({disableAICaching:Y.boolean().default(!1),viewport:Vo.optional()}),qr=Gg.merge(qn),Xo=Y.object({cron:Y.string().refine(r=>Hg(r),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:Y.boolean().default(!1),env:Y.string().optional(),timeZone:Y.string().default("America/Los_Angeles"),jobKey:Y.string().optional()}),Jo=Y.object({onSuccess:Y.boolean().default(!1),onFailure:Y.boolean().default(!0)}),Vg=Y.object({name:Y.string(),required:Y.boolean().optional(),defaultValue:Y.string().describe("this is not optional because we need a value when the editor is first loaded")}),Zo=Vg.array(),Qo=Y.object({name:Y.string(),default:Y.boolean().optional(),fixtures:fc.array().optional()});var Sc=ft.object({id:ft.string(),name:Ho,baseUrl:Go.nullish(),schemaVersion:ft.string(),advanced:ft.unknown().optional(),retries:ft.number(),envs:ft.array(Qo).nullish(),parameters:Zo.nullish()}),qg=ft.object({createdAt:ft.coerce.date(),updatedAt:ft.coerce.date(),schedule:Xo.nullish(),notification:Jo.nullish(),createdBy:ft.string(),organizationId:ft.string()}),Kg=Sc.merge(qg),MR=Kg.extend({steps:sa.array()}),NR=Sc.extend({steps:sa.array()});import{z as qe}from"zod";import{z as Jn}from"zod";import{z as N}from"zod";import*as U from"zod";import{cloneDeep as Kr}from"lodash-es";var Yg=r=>{let e=wc(r,0);if(e===void 0||!Jg(r[e]))return;let t=wc(r,e+1);if(t!==void 0)return Zg(r,e,t)},bc=Yg,wc=(r,e)=>{for(let t=e;t<r.length;t+=1){let n=r[t];if(!Xg(n))return t}},Xg=r=>r===" "||r===" "||r===`
|
|
3
3
|
`||r==="\r",Jg=r=>r==="{"||r==="[",Zg=(r,e,t)=>{let n;for(let o=t-1;o>e;o-=1){let s=r[o];if(s==="\r")return;if(s===`
|
|
4
4
|
`)return Qg(n);if(n===void 0)n=s;else if(n[0]===s)n+=s;else return}},Qg=r=>r===void 0?0:r[0]===" "?r.length:r;var Tc=(r,e)=>{let t=la(r,"toPrecision",e,e);return t===void 0?la(r,"toExponential",e,e):t},la=(r,e,t,n)=>{let s=r[e](n).replace(ey,"$1").replace(ty,"$1");return s.length<=t?s:n===1?void 0:la(r,e,t,n-1)},ey=/(e)\+/iu,ty=/\.?0*($|e)/iu;var Cc=(r,e)=>{if(typeof r!="string")throw new TypeError(`Input must be a JSON string: ${r}`);ry(e)},ry=r=>{if(ny(r),r<0)throw new TypeError(`"maxSize" argument must be positive: ${r}`);if(r<Ec)throw new TypeError(`"maxSize" argument must be at least ${Ec}: ${r}`)},ny=r=>{if(r===void 0)throw new TypeError('"maxSize" argument must be defined');if(!Number.isInteger(r))throw new TypeError(`"maxSize" argument must be an integer: ${r}`)},Ec=7;var es=(r,e,t)=>{let n=Ac(e,t);return vc(r,e,n)},vc=(r,e,t)=>{if(t>=e)return t;let n=r[t];return n>=my&&n<=py?vc(r,e,t+1):t},ts=(r,e,t)=>{if(t===void 0)return t;let n=Ac(e,t);return oy(r,n)},oy=(r,e)=>sy(r,e)?e-3:iy(r,e)?e-2:ay(r,e)?e-1:e,sy=(r,e)=>e>=3&&r[e-3]>=ly&&r[e-3]<=cy,iy=(r,e)=>e>=2&&r[e-2]>=dy,ay=(r,e)=>e>=1&&r[e-1]>=uy,Ac=(r,e)=>e<0||Object.is(e,-0)?Math.max(r+e,0):e,ly=240,cy=244,dy=224,uy=194,my=128,py=191;var xc=(r,e,t)=>{let n=globalThis.Buffer.from(r),o=es(n,n.length,e),s=ts(n,n.length,t);return o===0&&s>=n.length?n.toString():n.toString("utf8",o,s)};var Rc=/[\uD800-\uDFFF]/gu,Ic="\uFFFD";var rs=r=>hy(r)?r.replace(Rc,Ic):r,hy=r=>{for(let e=0;e<r.length;e+=1){let t=r.codePointAt(e);if(t>=55296&&t<=57343)return!0}return!1};var ua=({input:r,targetByteCount:e,firstStartSurrogate:t,lastStartSurrogate:n,firstEndSurrogate:o,lastEndSurrogate:s,increment:i,canBacktrack:a,shift:l,charIndexInit:c})=>{let u=c,d=u,m=0;for(;m<e;u+=i){d=u;let h=r.charCodeAt(u);if(Number.isNaN(h))break;if(h<=127){m+=1;continue}if(h<=2047){m+=2;continue}if(m+=3,h<t||h>n)continue;let f=r.charCodeAt(u+i);Number.isNaN(f)||f<o||f>s||(m+=1,u+=i)}return(a&&m>e?d:u)+l};var ma=(r,e,t)=>e<0||Object.is(e,-0)?by(r,e,t):wy(r,e,t),wy=(r,e,t)=>ua({input:r,targetByteCount:e,firstStartSurrogate:55296,lastStartSurrogate:56319,firstEndSurrogate:56320,lastEndSurrogate:57343,increment:1,canBacktrack:t,shift:0,charIndexInit:0}),by=(r,e,t)=>ua({input:r,targetByteCount:-e,firstStartSurrogate:56320,lastStartSurrogate:57343,firstEndSurrogate:55296,lastEndSurrogate:56319,increment:-1,canBacktrack:!t,shift:1,charIndexInit:r.length-1});var ns=(r,e,t)=>{let n=ma(r,e,!1),o=Ty(r,t),s=n===0&&o===void 0?r:r.slice(n,o);return rs(s)},Ty=(r,e)=>{if(e===void 0)return e;let t=ma(r,e,!0);return t===r.length?void 0:t};var Oc=(r,e,t)=>{let{textEncoder:n,textDecoder:o}=Ey(),s=Cy(r),{written:i}=n.encodeInto(r,s),a=es(s,i,e),l=ts(s,i,t),c=l===void 0?i:Math.min(l,i),u=s.subarray(a,c);return o.decode(u)},Ey=()=>(pa===void 0&&(pa=new globalThis.TextEncoder,Pc=new globalThis.TextDecoder("utf8",{fatal:!1})),{textEncoder:pa,textDecoder:Pc}),pa,Pc,Cy=r=>{let e=r.length*3;return e>vy?new Uint8Array(e):((os===void 0||os.length<e)&&(os=new Uint8Array(e)),os)},vy=1e5,os;var Lc=(r,e)=>{if(e===void 0)return e;let t=ha(r,e);return t>=r.length*Mc?void 0:t},ha=(r,e)=>e<=r.length*-Mc?0:e,Mc=4;var Nc=(r,e,t)=>{if(typeof r!="string")throw new TypeError(`First argument must be a string: ${r}`);Ay(e),xy(t)},Ay=r=>{if(r===void 0)throw new TypeError("Second argument is required.");_c("Second",r)},xy=r=>{r!==void 0&&_c("Third",r)},_c=(r,e)=>{if(!Number.isInteger(e))throw new TypeError(`${r} argument must be an integer: ${e}`)};var kc=r=>{let e=!0,t=0;for(let n=0;n<fa;n+=1){let o=Ry(r,n);o<=127||(e&&(e=!1),o>2047&&(t+=1))}return{asciiOnly:e,longCharsPercentage:t/fa}},Ry=(r,e)=>{let t=fa-1,n=1-(t-e)/t,o=Math.round(n*(r.length-1));return r.charCodeAt(o)},fa=50;var Iy=(r,e,t)=>{if(Nc(r,e,t),r==="")return r;let n=ha(r,e),o=Lc(r,t);return o===void 0&&Object.is(n,0)?rs(r):Py(r,n,o)},Dc=Iy,Py=(r,e,t)=>{if(r.length<=Oy)return ns(r,e,t);let{asciiOnly:n,longCharsPercentage:o}=kc(r);return n?My(r,e,t):o>=Ly?ns(r,e,t):Fc(r,e,t)},Oy=200,Ly=.4,My=(r,e,t)=>"Buffer"in globalThis&&"from"in globalThis.Buffer?xc(r,e,t):Fc(r,e,t),Fc=(r,e,t)=>"TextEncoder"in globalThis?Oc(r,e,t):ns(r,e,t);var $c=(r,e)=>{let t=JSON.stringify(r),n=ky(t),o=Dc(n,0,e-Uc.length-Kn.length*2),i=`${Ny(o)}${Uc}`;return Dy(i)},Ny=r=>r.replace(_y,""),_y=/(\\|\\u[0-9a-fA-F]{0,3})$/u,ky=r=>r.slice(Kn.length,-Kn.length),Dy=r=>`${Kn}${r}${Kn}`,Kn='"',Uc="...";var Bc=r=>globalThis.Buffer.byteLength(r);var ga=r=>{let e=r.length,t=e;for(let n=0;n<e;n+=1){let o=r.charCodeAt(n);if(o<=Fy)continue;if(o<=Uy){t+=1;continue}if(t+=2,o<$y||o>By)continue;let s=r.charCodeAt(n+1);s<zy||s>Wy||(n+=1)}return t},Fy=127,Uy=2047,$y=55296,By=56319,zy=56320,Wy=57343;var zc=()=>jy.bind(void 0,new TextEncoder),jy=(r,e)=>{let t=Hy(e);return r.encodeInto(e,t).written},Hy=r=>{let e=r.length*3;return e>Gy?new Uint8Array(e):((ss===void 0||ss.length<e)&&(ss=new Uint8Array(e)),ss)},Gy=1e5,ss;var qy=()=>"Buffer"in globalThis&&"byteLength"in globalThis.Buffer?Bc:"TextEncoder"in globalThis?Ky.bind(void 0,zc()):ga,Ky=(r,e)=>e.length<100?ga(e):r(e),Wc=qy();var jc=r=>{if(r===null)return Yy;if(r===!0)return Xy;if(r===!1)return Jy;let e=typeof r;return e==="object"?Zy:e==="number"?JSON.stringify(r).length:ya(r)},Yy=4,Xy=4,Jy=5,Zy=2,ya=r=>Wc(JSON.stringify(r));var is=({size:r,increment:e,maxSize:t,truncatedProps:n,path:o,value:s})=>{let i=r+e,a=i>t;return a?{size:r,stop:a,truncatedProps:[...n,{path:o,value:s}]}:{size:i,stop:a,truncatedProps:n}},Gc=r=>jc(r),Vc=(r,e,t)=>{let n=Kc({empty:r,indent:e,depth:t,keySpaceSize:0}),o=Yc(r);return n+o},qc=({key:r,empty:e,indent:t,depth:n})=>{let o=Kc({empty:e,indent:t,depth:n,keySpaceSize:1}),s=ya(r),i=Yc(e);return o+s+Qy+i},Qy=1,Kc=({empty:r,indent:e,depth:t,keySpaceSize:n})=>{if(e===void 0)return 0;let o=Hc+e*(t+1),s=r?Hc+e*t:0;return n+o+s},Hc=1,Yc=r=>r?0:eS,eS=1;var as=({parent:r,truncatedProps:e,path:t,increment:n,maxSize:o,key:s,empty:i,size:a,truncateValue:l,indent:c,depth:u})=>{let d=r[s],m=[...t,s],{size:p,stop:h,truncatedProps:f}=is({size:a,increment:n,maxSize:o,truncatedProps:e,path:m,value:d});return h?{empty:i,size:p,truncatedProps:f}:tS({value:d,truncatedProps:e,path:m,maxSize:o,empty:i,size:a,newSize:p,truncateValue:l,indent:c,depth:u})},tS=({value:r,truncatedProps:e,path:t,maxSize:n,empty:o,size:s,newSize:i,truncateValue:a,indent:l,depth:c})=>{let{value:u,size:d,truncatedProps:m}=a({value:r,truncatedProps:e,path:t,size:i,maxSize:n,indent:l,depth:c+1});return u===void 0?{empty:o,size:s,truncatedProps:m}:{empty:!1,size:d,value:u,truncatedProps:m}};var Xc=({array:r,truncatedProps:e,path:t,size:n,maxSize:o,truncateValue:s,indent:i,depth:a})=>{let l=[],c={empty:!0,size:n,truncatedProps:e};for(let u=0;u<r.length;u+=1){let d=Vc(c.empty,i,a);c=as({parent:r,truncatedProps:c.truncatedProps,path:t,increment:d,maxSize:o,key:u,empty:c.empty,size:c.size,truncateValue:s,indent:i,depth:a}),c.value!==void 0&&l.push(c.value)}return{value:l,size:c.size,truncatedProps:c.truncatedProps}};var Jc=({object:r,truncatedProps:e,path:t,size:n,maxSize:o,truncateValue:s,indent:i,depth:a})=>{let l={},c={empty:!0,size:n,truncatedProps:e};for(let u in r){let d=qc({key:u,empty:c.empty,indent:i,depth:a});c=as({parent:r,truncatedProps:c.truncatedProps,path:t,increment:d,maxSize:o,key:u,empty:c.empty,size:c.size,truncateValue:s,indent:i,depth:a}),c.value!==void 0&&(l[u]=c.value)}return{value:l,size:c.size,truncatedProps:c.truncatedProps}};var ls=({value:r,truncatedProps:e,path:t,size:n,maxSize:o,indent:s,depth:i})=>{let a=Gc(r),{size:l,stop:c,truncatedProps:u}=is({size:n,increment:a,maxSize:o,truncatedProps:e,path:t,value:r});return c?{value:void 0,size:l,truncatedProps:u}:rS({value:r,truncatedProps:u,path:t,size:l,maxSize:o,indent:s,depth:i})},rS=({value:r,truncatedProps:e,path:t,size:n,maxSize:o,indent:s,depth:i})=>typeof r!="object"||r===null?{value:r,size:n,truncatedProps:e}:Array.isArray(r)?Xc({array:r,truncatedProps:e,path:t,size:n,maxSize:o,truncateValue:ls,indent:s,depth:i}):Jc({object:r,truncatedProps:e,path:t,size:n,maxSize:o,truncateValue:ls,indent:s,depth:i});var nS=(r,e)=>{Cc(r,e);let t=oS(r),n=sS(r),{value:o,truncatedProps:s}=ls({value:n,truncatedProps:[],path:[],size:0,maxSize:e,indent:t,depth:0});return{jsonString:iS({newValue:o,value:n,maxSize:e,indent:t}),truncatedProps:s}},Yn=nS,oS=r=>{let e=bc(r);return typeof e=="string"?e.length:e},sS=r=>{try{return JSON.parse(r)}catch(e){throw new TypeError(`Invalid JSON string: "${r}"
|
|
5
|
-
${e.message}`)}},iS=({newValue:r,value:e,maxSize:t,indent:n})=>r!==void 0?JSON.stringify(r,void 0,n):typeof e=="number"?Tc(e,t):$c(e,t);import*as xt from"zod";Z(xt);var Sa=xt.object({env:xt.record(xt.unknown()),results:xt.array(xt.unknown()).optional()}).openapi({ref:"TestContextSnapshot"}),aS="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",lS=[oe,Gr],Zc=[qo,oe,Gr],Ve=class r{env={};varsFromMomenticEnvironment={};results=[];constructor(e){this.reset(e)}static dummyContext(e=void 0,t={}){return new r({baseUrl:"about:blank",currentUrl:"about:blank",envName:e,variablesFromEnvironment:t})}static fromSnapshot({snapshot:e,environmentVariables:t}){let n=e.env[oe]??"about:blank",o=e.env[qo]??"about:blank",s=e.env[Gr],i={};for(let[l,c]of Object.entries(e.env))Zc.includes(l)||(t??{})[l]===void 0&&(i[l]=c);let a=new r({baseUrl:n,currentUrl:o,dynamicVariables:i,envName:s,variablesFromEnvironment:t??{}});return a.setResults(e.results??[]),a}setEnvVariables(e){let t=Kr(e);this.env=Object.assign(this.env,t)}setInputs(e){e&&this.setEnvVariables(e)}setResult(e,t){this.results[e]=t||null;for(let n=0;n<e;n++)this.results[n]===void 0&&(this.results[n]=null)}setResults(e){this.results=e}getResult(e){return this.results[e]}getResultsCopy(){return Kr(this.results)}setMomenticSystemVariable(e,t){this.varsFromMomenticEnvironment[e]=t}getVariable(e){return this.env[e]}setVariable(e,t){lS.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[Gr]}toObjectCopy(){let e={results:this.results,env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return Kr(e)}toEditorDisplayCopy(){let e=this.toObjectCopy();return e.results=void 0,e}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>Zc.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,aS])),e.results=void 0;let{jsonString:t}=Yn(JSON.stringify(e),5e3);try{return JSON.parse(t)}catch{return{env:{},results:void 0}}}setCurrentUrl(e){this.env[qo]=e}reset(e){this.results=[],this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=Kr(e.variablesFromEnvironment),this.setMomenticSystemVariable(oe,e.baseUrl),e.envName&&this.setMomenticSystemVariable(Gr,e.envName)}getDynamicVariablesCopy(){return Kr(this.env)}getVariablesFromEnvironmentCopy(){return Kr(this.varsFromMomenticEnvironment)}};import{z as Er}from"zod";Z(Er);var te=(l=>(l.AI_PROVIDER="AIProviderError",l.ACTION_FAILURE="ActionFailureError",l.ASSERTION_FAILURE="AssertionFailureError",l.CONFIG_ERROR="UserConfigurationError",l.JOB_TIMEOUT="JobTimeoutError",l.WEB_AGENT_PLATFORM="InternalWebAgentError",l.UNKNOWN_PLATFORM="InternalPlatformError",l.UNKNOWN="UnknownError",l))(te||{});var Qc={ActionFailureError:"Action failure",AssertionFailureError:"Assertion failure",UserConfigurationError:"Configuration error",AIProviderError:"AI provider error",InternalWebAgentError:"Momentic AI agent error",InternalPlatformError:"Unknown Momentic platform error",UnknownError:"Unknown error",JobTimeoutError:"Job timeout"},ed={ActionFailureError:"A browser action such as a click or type failed to execute because of the underlying page state is incorrect, suggesting a bug in the application itself.",AssertionFailureError:"An AI assertion or check failed for a legitimate reason, such as a missing element, a change in the page structure, or an unexpected state (e.g. loading state).",UserConfigurationError:"The error message suggests a misconfiguration in the test, such as a variable being undefined, an environment variable missing, or a typo in a step. Do not use this reason if the error is caused by a bug in the application being tested, or Momentic's AI software.",AIProviderError:"The AI provider failed to return a response or returned a malformed response.",InternalWebAgentError:"The AI testing framework failed to find the correct element or evaluate the assertion correctly, even though the test steps and application state look valid. In other words, the AI agent failed to understand the page.",InternalPlatformError:"An unknown error occurred with the Momentic platform. Please reach out to Momentic Support for assistance.",UnknownError:"An unknown error occurred. Please refer to the error message for more details or reach out to Momentic Support for assistance.",JobTimeoutError:"The test took too long to complete, suggesting a problem with the test itself."},wa=Er.object({reason:Er.nativeEnum(te),summary:Er.string()}).openapi({ref:"TestResultClassification"}),cs=Er.object({errorMessage:Er.string(),errorStack:Er.string().optional(),classification:wa.optional()}).openapi({ref:"TestFailureDetails"});Z(U);var Oe=(s=>(s.SUCCESS="SUCCESS",s.FAILED="FAILED",s.RUNNING="RUNNING",s.IDLE="IDLE",s.CANCELLED="CANCELLED",s))(Oe||{}),ds=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(ds||{}),td=U.object({beforeUrl:U.string().optional(),afterUrl:U.string().optional(),beforeScreenshot:U.string().optional(),afterScreenshot:U.string().optional(),startedAt:U.coerce.date(),finishedAt:U.coerce.date()}),cS=td.extend({viewport:U.object({height:U.number(),width:U.number()}),status:U.nativeEnum(ds),message:U.string().optional(),elementInteracted:U.string().optional()}),er=td.extend({status:U.nativeEnum(Oe),message:U.string().optional(),data:U.unknown().optional(),beforeTestContext:Sa.optional(),afterTestContext:Sa.optional(),failureReason:U.nativeEnum(te).optional(),details:U.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information.")}).openapi({ref:"StepResultMetadata"}),us=er.merge(ot).extend({results:cS.array()}),dS=er.merge(jr).extend({results:U.lazy(()=>us.array())}),uS=er.merge(Wn).extend({results:U.lazy(()=>us.array())}),mS=er.merge(Hr).extend({moduleName:U.string().optional(),results:U.lazy(()=>Rt.array())}),pS=er.merge(jn).extend({assertion:us.optional(),results:U.lazy(()=>Rt.array()).describe("results for the block actually executed")}),hS=er.merge(Hn).extend({results:U.lazy(()=>Rt.array())}),fS=er.merge(Gn).extend({results:U.lazy(()=>Rt.array()),healingAttempts:U.lazy(()=>Rt.array().array()).optional()}),Rt=U.discriminatedUnion("type",[dS,uS,us,mS,pS,hS,fS]),tr=er.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),oP=U.object({results:Rt.array(),errorMessage:U.string(),errorStack:U.string().optional()});import*as Ce from"zod";Z(Ce);var gS=Ce.object({url:Ce.string(),lineNumber:Ce.number(),columnNumber:Ce.number()}).openapi({ref:"CodeLocation"}),yS=Ce.object({timestamp:Ce.number(),text:Ce.string(),type:Ce.string(),tabIndex:Ce.number(),args:Ce.unknown().array().optional(),url:Ce.string().optional(),location:gS.optional()}).openapi({ref:"ConsoleLog"}),rd=Ce.object({logsPerPage:yS.array().array()}).openapi({ref:"DebugData"});Z(N);var Cr={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},ce=(a=>(a.PENDING="PENDING",a.RUNNING="RUNNING",a.PASSED="PASSED",a.FAILED="FAILED",a.CANCELLED="CANCELLED",a.RETRYING="RETRYING",a.WAITING_FOR_USER="WAITING_FOR_USER",a))(ce||{});var Le=N.string().pipe(N.coerce.date()).or(N.date()),Xn=N.object({id:N.string(),runKey:N.string(),organizationId:N.string(),createdAt:Le,createdBy:N.string(),flake:N.boolean().nullish(),scheduledAt:Le.or(N.null()),startedAt:Le.or(N.null()),updatedAt:Le.nullish(),finishedAt:Le.or(N.null()),resolvedBaseUrl:N.string().nullish(),status:N.nativeEnum(ce),trigger:N.nativeEnum(Cr),attempts:N.number(),runAttempts:N.array(N.object({id:N.string(),status:N.nativeEnum(ce),startedAt:Le.or(N.null()),finishedAt:Le.or(N.null())})).optional(),videos:N.array(N.string()).optional(),failureReason:N.nativeEnum(te).nullish(),failureDetails:cs.nullish(),testId:N.string().or(N.null()),testName:N.string().or(N.null()).optional(),test:N.object({name:N.string(),id:N.string()}).or(N.null()),suiteId:N.string().or(N.null()).optional()}).openapi({ref:"RunMetadata"}),SS={id:!0,status:!0,testName:!0,testId:!0,test:{select:{name:!0,id:!0}},failureReason:!0,failureDetails:!0},nd=Xn.pick({...SS,test:!0}),gP=Xn.omit({failureReason:!0,failureDetails:!0}),ba=Xn.merge(N.object({results:Rt.array(),debugData:rd.nullish().catch(void 0),resolvedInputs:N.record(N.string(),N.string()).nullish(),test:N.object({name:N.string(),id:N.string(),baseUrl:N.string().nullish(),advanced:qr.nullish()}).nullish()})),yP=N.object({id:N.string(),name:N.string()}),od=r=>r.includes("PASSED")&&r.includes("FAILED");var wS=Jn.object({id:Jn.string().uuid(),startedAt:Le.or(Jn.null()),finishedAt:Le.or(Jn.null()),status:Jn.nativeEnum(ce)}),TP=wS.array();var ms=(t=>(t.JUNIT="junit",t.ALLURE="allure",t))(ms||{});import{z as ye}from"zod";import*as G from"zod";var IP=G.object({thoughts:G.string().optional().describe("only provided if a description was provided"),target:fr.optional().describe("only provided if a description was provided"),pageState:G.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:G.object({label:G.string(),value:G.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:G.object({data:G.string(),height:G.number().int(),width:G.number().int()}).optional().describe("only provided if returnScreenshot is true")});function Zn(r,e){if(!e||"useSelector"in r&&r.useSelector)return e;switch(r.type){case"SELECT_OPTION":return`<select> element: ${e}`;case"TYPE":return`text input element: ${e}`;default:return e}return e}var Qn=G.object({matched:G.boolean(),reason:G.string().optional().describe("Human understandable description"),logs:G.string().array().optional().describe("Logs for debugging")}),bS=Qn.extend({type:G.literal("A11Y_ID")}),TS=Qn.extend({type:G.literal("USER_SELECTOR")}),ES=Qn.extend({type:G.literal("CSS_SELECTOR"),selectors:G.string().array()}),CS=Qn.extend({type:G.literal("HTML_DISTANCE"),distance:G.number().optional(),closestElement:G.string().optional(),savedElement:G.string().optional()}),vS=Qn.extend({type:G.literal("TEMPLATE_MATCHING"),elementImageUrl:G.string().url()}),sd=G.discriminatedUnion("type",[bS,TS,ES,CS,vS]);var AS=ye.object({type:ye.literal("TARGETING"),name:ye.string().optional().describe("Target name for steps with multiple targets"),elementLocationDecisions:sd.array(),pageState:ye.string().optional(),targetSource:ye.nativeEnum(hr).optional(),targetUpdateTime:ye.string().optional()}),xS=ye.object({type:ye.literal("AI_LOCATION"),matched:ye.boolean(),pageState:ye.string().optional(),ragUsed:ye.boolean().optional(),thoughts:ye.string().optional()}),RS=ye.object({type:ye.literal("ASSERTION"),relevantElementsSerialized:ye.string().array().optional(),pageState:ye.string().optional(),ragUsed:ye.boolean().optional()}),IS=ye.discriminatedUnion("type",[AS,xS,RS]);function ps(){return{details:[]}}import{z as It}from"zod";var id=It.object({id:It.string().uuid(),orgId:It.string(),createdAt:Le,startedAt:Le.or(It.null()),finishedAt:Le.or(It.null()),status:It.nativeEnum(ce),trigger:It.nativeEnum(Cr),suite:It.object({id:It.string(),name:It.string()}).nullish(),runs:Xn.array()}),DP=id.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),ad=id.extend({runs:nd.array()});var ld=qe.object({startedAt:qe.coerce.date(),finishedAt:qe.coerce.date(),status:qe.nativeEnum(Oe),message:qe.string().optional(),data:qe.unknown().optional()}),OS=ld.merge(oa).extend({type:qe.literal("JAVASCRIPT")}),LS=ld.merge(na).extend({type:qe.literal("REQUEST")}),MS=qe.discriminatedUnion("type",[OS,LS]),cd=qe.object({startedAt:qe.coerce.date(),finishedAt:qe.coerce.date().nullish(),status:qe.nativeEnum(ce),results:MS.array(),failureReason:qe.string().nullish(),failureDetails:cs.nullish()});import{z as Ke}from"zod";var NS=Ke.object({id:Ke.string(),organizationId:Ke.string(),createdAt:Ke.coerce.date(),updatedAt:Ke.coerce.date(),createdBy:Ke.string(),scheduledAt:Ke.coerce.date().nullish(),startedAt:Ke.coerce.date().nullish(),finishedAt:Ke.coerce.date().nullish(),status:Ke.nativeEnum(ce),trigger:Ke.nativeEnum(Cr),results:cd.array().nullish(),apiTestName:Ke.string().nullish(),apiTestPath:Ke.string().nullish(),apiTestId:Ke.string().nullish()}),tO=NS.pick({status:!0,startedAt:!0,finishedAt:!0});import{z as Bt}from"zod";var hs=Bt.object({x:Bt.number(),y:Bt.number(),correlation:Bt.number()}),dO=Bt.object({searchImageBase64String:Bt.string(),pageImageBase64String:Bt.string(),id:Bt.string().uuid(),timeoutMs:Bt.number().max(1e4).min(0).optional()});import gO from"string-argv";import{v4 as SO}from"uuid";import{z as M}from"zod";var fs=class extends Error{constructor(e,t,n,o={}){super(`The ${n} with id ${t} is invalid: ${e}`,o),this.name="InvalidEntityError"}};var gs=class extends Error{constructor(e,t={}){super(e,t),this.name="TemplateMatcherThresholdError"}};function dd(r){for(let e of Object.values(te))if(r.includes(e))return e}var R=class extends Error{reason;constructor(e,t,n={}){let o=!1;for(let s of Object.values(te))if(t.startsWith(s)){o=!0,e=s;break}o?super(t,n):super(`${e}${t?`: ${t}`:""}`,n),this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message}}},rr=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundError"}toString(){return`${this.message}
|
|
5
|
+
${e.message}`)}},iS=({newValue:r,value:e,maxSize:t,indent:n})=>r!==void 0?JSON.stringify(r,void 0,n):typeof e=="number"?Tc(e,t):$c(e,t);import*as xt from"zod";Z(xt);var Sa=xt.object({env:xt.record(xt.unknown()),results:xt.array(xt.unknown()).optional()}).openapi({ref:"TestContextSnapshot"}),aS="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",lS=[oe,Gr],Zc=[qo,oe,Gr],Ve=class r{env={};varsFromMomenticEnvironment={};results=[];constructor(e){this.reset(e)}static dummyContext(e=void 0,t={}){return new r({baseUrl:"about:blank",currentUrl:"about:blank",envName:e,variablesFromEnvironment:t})}static fromSnapshot({snapshot:e,environmentVariables:t}){let n=e.env[oe]??"about:blank",o=e.env[qo]??"about:blank",s=e.env[Gr],i={};for(let[l,c]of Object.entries(e.env))Zc.includes(l)||(t??{})[l]===void 0&&(i[l]=c);let a=new r({baseUrl:n,currentUrl:o,dynamicVariables:i,envName:s,variablesFromEnvironment:t??{}});return a.setResults(e.results??[]),a}setEnvVariables(e){let t=Kr(e);this.env=Object.assign(this.env,t)}setInputs(e){e&&this.setEnvVariables(e)}setResult(e,t){this.results[e]=t||null;for(let n=0;n<e;n++)this.results[n]===void 0&&(this.results[n]=null)}setResults(e){this.results=e}getResult(e){return this.results[e]}getResultsCopy(){return Kr(this.results)}setMomenticSystemVariable(e,t){this.varsFromMomenticEnvironment[e]=t}getVariable(e){return this.env[e]}setVariable(e,t){lS.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[Gr]}toObjectCopy(){let e={results:this.results,env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return Kr(e)}toEditorDisplayCopy(){let e=this.toObjectCopy();return e.results=void 0,e}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([n,o])=>Zc.includes(n)||this.varsFromMomenticEnvironment[n]===void 0?[n,o]:[n,aS])),e.results=void 0;for(let[n,o]of Object.entries(e.env)){let{jsonString:s}=Yn(JSON.stringify(o),1e3);try{e.env[n]=JSON.parse(s)}catch{e.env[n]=void 0}}let{jsonString:t}=Yn(JSON.stringify(e.env),5e3);try{e.env=JSON.parse(t)}catch{e.env={}}return e}setCurrentUrl(e){this.env[qo]=e}reset(e){this.results=[],this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=Kr(e.variablesFromEnvironment),this.setMomenticSystemVariable(oe,e.baseUrl),e.envName&&this.setMomenticSystemVariable(Gr,e.envName)}getDynamicVariablesCopy(){return Kr(this.env)}getVariablesFromEnvironmentCopy(){return Kr(this.varsFromMomenticEnvironment)}};import{z as Er}from"zod";Z(Er);var te=(l=>(l.AI_PROVIDER="AIProviderError",l.ACTION_FAILURE="ActionFailureError",l.ASSERTION_FAILURE="AssertionFailureError",l.CONFIG_ERROR="UserConfigurationError",l.JOB_TIMEOUT="JobTimeoutError",l.WEB_AGENT_PLATFORM="InternalWebAgentError",l.UNKNOWN_PLATFORM="InternalPlatformError",l.UNKNOWN="UnknownError",l))(te||{});var Qc={ActionFailureError:"Action failure",AssertionFailureError:"Assertion failure",UserConfigurationError:"Configuration error",AIProviderError:"AI provider error",InternalWebAgentError:"Momentic AI agent error",InternalPlatformError:"Unknown Momentic platform error",UnknownError:"Unknown error",JobTimeoutError:"Job timeout"},ed={ActionFailureError:"A browser action such as a click or type failed to execute because of the underlying page state is incorrect, suggesting a bug in the application itself.",AssertionFailureError:"An AI assertion or check failed for a legitimate reason, such as a missing element, a change in the page structure, or an unexpected state (e.g. loading state).",UserConfigurationError:"The error message suggests a misconfiguration in the test, such as a variable being undefined, an environment variable missing, or a typo in a step. Do not use this reason if the error is caused by a bug in the application being tested, or Momentic's AI software.",AIProviderError:"The AI provider failed to return a response or returned a malformed response.",InternalWebAgentError:"The AI testing framework failed to find the correct element or evaluate the assertion correctly, even though the test steps and application state look valid. In other words, the AI agent failed to understand the page.",InternalPlatformError:"An unknown error occurred with the Momentic platform. Please reach out to Momentic Support for assistance.",UnknownError:"An unknown error occurred. Please refer to the error message for more details or reach out to Momentic Support for assistance.",JobTimeoutError:"The test took too long to complete, suggesting a problem with the test itself."},wa=Er.object({reason:Er.nativeEnum(te),summary:Er.string()}).openapi({ref:"TestResultClassification"}),cs=Er.object({errorMessage:Er.string(),errorStack:Er.string().optional(),classification:wa.optional()}).openapi({ref:"TestFailureDetails"});Z(U);var Oe=(s=>(s.SUCCESS="SUCCESS",s.FAILED="FAILED",s.RUNNING="RUNNING",s.IDLE="IDLE",s.CANCELLED="CANCELLED",s))(Oe||{}),ds=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(ds||{}),td=U.object({beforeUrl:U.string().optional(),afterUrl:U.string().optional(),beforeScreenshot:U.string().optional(),afterScreenshot:U.string().optional(),startedAt:U.coerce.date(),finishedAt:U.coerce.date()}),cS=td.extend({viewport:U.object({height:U.number(),width:U.number()}),status:U.nativeEnum(ds),message:U.string().optional(),elementInteracted:U.string().optional()}),er=td.extend({status:U.nativeEnum(Oe),message:U.string().optional(),data:U.unknown().optional(),beforeTestContext:Sa.optional(),afterTestContext:Sa.optional(),failureReason:U.nativeEnum(te).optional(),details:U.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information.")}).openapi({ref:"StepResultMetadata"}),us=er.merge(ot).extend({results:cS.array()}),dS=er.merge(jr).extend({results:U.lazy(()=>us.array())}),uS=er.merge(Wn).extend({results:U.lazy(()=>us.array())}),mS=er.merge(Hr).extend({moduleName:U.string().optional(),results:U.lazy(()=>Rt.array())}),pS=er.merge(jn).extend({assertion:us.optional(),results:U.lazy(()=>Rt.array()).describe("results for the block actually executed")}),hS=er.merge(Hn).extend({results:U.lazy(()=>Rt.array())}),fS=er.merge(Gn).extend({results:U.lazy(()=>Rt.array()),healingAttempts:U.lazy(()=>Rt.array().array()).optional()}),Rt=U.discriminatedUnion("type",[dS,uS,us,mS,pS,hS,fS]),tr=er.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),oP=U.object({results:Rt.array(),errorMessage:U.string(),errorStack:U.string().optional()});import*as Ce from"zod";Z(Ce);var gS=Ce.object({url:Ce.string(),lineNumber:Ce.number(),columnNumber:Ce.number()}).openapi({ref:"CodeLocation"}),yS=Ce.object({timestamp:Ce.number(),text:Ce.string(),type:Ce.string(),tabIndex:Ce.number(),args:Ce.unknown().array().optional(),url:Ce.string().optional(),location:gS.optional()}).openapi({ref:"ConsoleLog"}),rd=Ce.object({logsPerPage:yS.array().array()}).openapi({ref:"DebugData"});Z(N);var Cr={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},ce=(a=>(a.PENDING="PENDING",a.RUNNING="RUNNING",a.PASSED="PASSED",a.FAILED="FAILED",a.CANCELLED="CANCELLED",a.RETRYING="RETRYING",a.WAITING_FOR_USER="WAITING_FOR_USER",a))(ce||{});var Le=N.string().pipe(N.coerce.date()).or(N.date()),Xn=N.object({id:N.string(),runKey:N.string(),organizationId:N.string(),createdAt:Le,createdBy:N.string(),flake:N.boolean().nullish(),scheduledAt:Le.or(N.null()),startedAt:Le.or(N.null()),updatedAt:Le.nullish(),finishedAt:Le.or(N.null()),resolvedBaseUrl:N.string().nullish(),status:N.nativeEnum(ce),trigger:N.nativeEnum(Cr),attempts:N.number(),runAttempts:N.array(N.object({id:N.string(),status:N.nativeEnum(ce),startedAt:Le.or(N.null()),finishedAt:Le.or(N.null())})).optional(),videos:N.array(N.string()).optional(),failureReason:N.nativeEnum(te).nullish(),failureDetails:cs.nullish(),testId:N.string().or(N.null()),testName:N.string().or(N.null()).optional(),test:N.object({name:N.string(),id:N.string()}).or(N.null()),suiteId:N.string().or(N.null()).optional()}).openapi({ref:"RunMetadata"}),SS={id:!0,status:!0,testName:!0,testId:!0,test:{select:{name:!0,id:!0}},failureReason:!0,failureDetails:!0},nd=Xn.pick({...SS,test:!0}),gP=Xn.omit({failureReason:!0,failureDetails:!0}),ba=Xn.merge(N.object({results:Rt.array(),debugData:rd.nullish().catch(void 0),resolvedInputs:N.record(N.string(),N.string()).nullish(),test:N.object({name:N.string(),id:N.string(),baseUrl:N.string().nullish(),advanced:qr.nullish()}).nullish()})),yP=N.object({id:N.string(),name:N.string()}),od=r=>r.includes("PASSED")&&r.includes("FAILED");var wS=Jn.object({id:Jn.string().uuid(),startedAt:Le.or(Jn.null()),finishedAt:Le.or(Jn.null()),status:Jn.nativeEnum(ce)}),TP=wS.array();var ms=(t=>(t.JUNIT="junit",t.ALLURE="allure",t))(ms||{});import{z as ye}from"zod";import*as G from"zod";var IP=G.object({thoughts:G.string().optional().describe("only provided if a description was provided"),target:fr.optional().describe("only provided if a description was provided"),pageState:G.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:G.object({label:G.string(),value:G.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:G.object({data:G.string(),height:G.number().int(),width:G.number().int()}).optional().describe("only provided if returnScreenshot is true")});function Zn(r,e){if(!e||"useSelector"in r&&r.useSelector)return e;switch(r.type){case"SELECT_OPTION":return`<select> element: ${e}`;case"TYPE":return`text input element: ${e}`;default:return e}return e}var Qn=G.object({matched:G.boolean(),reason:G.string().optional().describe("Human understandable description"),logs:G.string().array().optional().describe("Logs for debugging")}),bS=Qn.extend({type:G.literal("A11Y_ID")}),TS=Qn.extend({type:G.literal("USER_SELECTOR")}),ES=Qn.extend({type:G.literal("CSS_SELECTOR"),selectors:G.string().array()}),CS=Qn.extend({type:G.literal("HTML_DISTANCE"),distance:G.number().optional(),closestElement:G.string().optional(),savedElement:G.string().optional()}),vS=Qn.extend({type:G.literal("TEMPLATE_MATCHING"),elementImageUrl:G.string().url()}),sd=G.discriminatedUnion("type",[bS,TS,ES,CS,vS]);var AS=ye.object({type:ye.literal("TARGETING"),name:ye.string().optional().describe("Target name for steps with multiple targets"),elementLocationDecisions:sd.array(),pageState:ye.string().optional(),targetSource:ye.nativeEnum(hr).optional(),targetUpdateTime:ye.string().optional()}),xS=ye.object({type:ye.literal("AI_LOCATION"),matched:ye.boolean(),pageState:ye.string().optional(),ragUsed:ye.boolean().optional(),thoughts:ye.string().optional()}),RS=ye.object({type:ye.literal("ASSERTION"),relevantElementsSerialized:ye.string().array().optional(),pageState:ye.string().optional(),ragUsed:ye.boolean().optional()}),IS=ye.discriminatedUnion("type",[AS,xS,RS]);function ps(){return{details:[]}}import{z as It}from"zod";var id=It.object({id:It.string().uuid(),orgId:It.string(),createdAt:Le,startedAt:Le.or(It.null()),finishedAt:Le.or(It.null()),status:It.nativeEnum(ce),trigger:It.nativeEnum(Cr),suite:It.object({id:It.string(),name:It.string()}).nullish(),runs:Xn.array()}),DP=id.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),ad=id.extend({runs:nd.array()});var ld=qe.object({startedAt:qe.coerce.date(),finishedAt:qe.coerce.date(),status:qe.nativeEnum(Oe),message:qe.string().optional(),data:qe.unknown().optional()}),OS=ld.merge(oa).extend({type:qe.literal("JAVASCRIPT")}),LS=ld.merge(na).extend({type:qe.literal("REQUEST")}),MS=qe.discriminatedUnion("type",[OS,LS]),cd=qe.object({startedAt:qe.coerce.date(),finishedAt:qe.coerce.date().nullish(),status:qe.nativeEnum(ce),results:MS.array(),failureReason:qe.string().nullish(),failureDetails:cs.nullish()});import{z as Ke}from"zod";var NS=Ke.object({id:Ke.string(),organizationId:Ke.string(),createdAt:Ke.coerce.date(),updatedAt:Ke.coerce.date(),createdBy:Ke.string(),scheduledAt:Ke.coerce.date().nullish(),startedAt:Ke.coerce.date().nullish(),finishedAt:Ke.coerce.date().nullish(),status:Ke.nativeEnum(ce),trigger:Ke.nativeEnum(Cr),results:cd.array().nullish(),apiTestName:Ke.string().nullish(),apiTestPath:Ke.string().nullish(),apiTestId:Ke.string().nullish()}),tO=NS.pick({status:!0,startedAt:!0,finishedAt:!0});import{z as Bt}from"zod";var hs=Bt.object({x:Bt.number(),y:Bt.number(),correlation:Bt.number()}),dO=Bt.object({searchImageBase64String:Bt.string(),pageImageBase64String:Bt.string(),id:Bt.string().uuid(),timeoutMs:Bt.number().max(1e4).min(0).optional()});import gO from"string-argv";import{v4 as SO}from"uuid";import{z as M}from"zod";var fs=class extends Error{constructor(e,t,n,o={}){super(`The ${n} with id ${t} is invalid: ${e}`,o),this.name="InvalidEntityError"}};var gs=class extends Error{constructor(e,t={}){super(e,t),this.name="TemplateMatcherThresholdError"}};function dd(r){for(let e of Object.values(te))if(r.includes(e))return e}var R=class extends Error{reason;constructor(e,t,n={}){let o=!1;for(let s of Object.values(te))if(t.startsWith(s)){o=!0,e=s;break}o?super(t,n):super(`${e}${t?`: ${t}`:""}`,n),this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message}}},rr=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundError"}toString(){return`${this.message}
|
|
6
6
|
Decisions:
|
|
7
7
|
${this.decisions.map(e=>e.toString()).join(`
|
|
8
8
|
`)}`}};var AO=M.object({command:M.string(),thoughts:M.string()}),xO=M.string().pipe(M.coerce.number());var ud=M.object({phrase:M.string()}),Ta=M.object({result:M.union([M.literal("NOT_FOUND"),M.string(),M.number(),M.array(M.unknown()),M.record(M.unknown(),M.unknown())])}),md=M.object({thoughts:M.string(),id:M.number().int()}),RO=M.object({results:M.array(Rt),goal:M.string(),errorMessage:M.string()}),_S=M.discriminatedUnion("op",[M.object({op:M.literal("replace"),path:M.string(),value:M.string()}),M.object({op:M.literal("add"),path:M.string(),value:M.string()}),M.object({op:M.literal("remove"),path:M.string()})]),IO=M.object({thoughts:M.string(),patches:_S.array()}),kS=M.discriminatedUnion("op",[M.object({op:M.literal("replace"),path:M.string(),value:fe}),M.object({op:M.literal("add"),path:M.string(),value:fe}),M.object({op:M.literal("remove"),path:M.string()})]),pd=M.object({patches:kS.array(),thoughts:M.string()});import{z as Ue}from"zod";var DS=Ue.object({content:Ue.string(),ids:Ue.string().array(),tokenLength:Ue.number()}),FS=Ue.object({chunks:DS.array(),numRecs:Ue.number()}),LO=Ue.object({ids:Ue.string().array(),score:Ue.number(),tokenLength:Ue.number()}),MO=Ue.object({description:Ue.string(),tokenLimit:Ue.number()}).merge(FS),hd=Ue.object({ids:Ue.number().array()});import{z as W}from"zod";var Ea=W.object({generatedStep:zo.optional(),serializedCommand:W.string().optional(),elementInteracted:W.string().optional()}),US=Ea.extend({state:W.union([W.literal("PENDING"),W.literal("DONE")]),screenshotBase64AfterCommand:W.string().optional(),urlAfterCommand:W.string().optional()}),DO=W.object({goal:W.string(),browserState:W.string(),screenshot:W.string(),feedback:W.string().optional()}),FO=W.object({goal:W.string(),browserState:W.string()}),fd=W.object({goal:W.string(),browserState:W.string(),returnSchema:W.string().optional()}),gd=W.object({goal:W.string(),browserState:W.string(),screenshot:W.string().optional(),url:W.string()}),UO=W.object({url:W.string(),goal:W.string()}),yd=W.object({goal:W.string(),browserState:W.string(),startingScreenshot:W.string(),screenshot:W.string(),url:W.string(),history:US.array()});import{z as Yr}from"zod";var zO=Yr.object({goal:Yr.string(),completionType:Yr.string().describe("type of completion these keywords will be used for")}),Sd=Yr.object({keywords:Yr.array(Yr.string())});var ZO=new Set(Object.values(he));var $S={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"Dynamic AI action",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_WAIT:"AI wait",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"Local storage",REQUEST:"API request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",SUCCESS:"Done"},QO={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","asserrt","make sure"],AI_WAIT:[],AI_EXTRACT:["ai","extract","data"],CLICK:["click","press"],TYPE:["type","input","write","press"],JAVASCRIPT:["js","javascript","code","execute"],SELECT_OPTION:["select","option","choose"],PRESS:["keyboard","type","key"],NAVIGATE:["go to","visit"],SCROLL_UP:[],SCROLL_DOWN:[],SCROLL_LEFT:[],SCROLL_RIGHT:[],HOVER:["scroll into view","go to"],BLUR:[],FILE_UPLOAD:[],FOCUS:[],GO_BACK:[],GO_FORWARD:[],WAIT:[],REFRESH:[],TAB:[],NEW_TAB:[],COOKIE:[],LOCAL_STORAGE:[],REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],SUCCESS:[]},eL={AI_ACTION:"Ask AI achieve a specific goal. Caches the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic. Our most capable AI agent.",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI whether something is true on the page, retrying until a configurable timeout.",AI_WAIT:"Wait until AI considers a condition to be true.",CLICK:"Click on an element on the page based on a description.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page based on a description.",HOVER:"Hover over an element on the page based on a description.",FILE_UPLOAD:"Automatically upload a file when the next file chooser is activated.",FOCUS:"Focus an element on the page based on a description.",BLUR:"Remove focus from an element on the page based on a description.",SELECT_OPTION:"Select an option from an HTML Select <select> element based on a description.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Ctrl+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session",LOCAL_STORAGE:"Set a local storage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",JAVASCRIPT:"Run JavaScript code.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load auth state (cookies, local storage) from the JavaScript object format returned by 'Save auth state' and then refresh the page.",AUTH_SAVE:"Save auth state (cookies, local storage) into a JavaScript object format usable by 'Load auth state'.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's state using pre-built conditions, including URL and content checks.",WAIT_FOR_URL:"Wait for the active page's URL to match a specific URL or glob pattern. If a new tab is opened, this command will wait for the new tab's URL to match instead.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."};import{z as D}from"zod";var nL=D.object({body:D.string(),to:D.string(),from:D.string()}),oL=D.object({from:D.string().optional(),to:D.string(),timeout:D.number().optional(),beforeDate:D.string().pipe(D.coerce.date()).or(D.date()).optional(),afterDate:D.string().pipe(D.coerce.date()).or(D.date()).optional()}),sL=D.object({to:D.string(),from:D.string(),subject:D.string(),body:D.string()}),iL=D.object({inbox:D.string(),afterDate:D.string().pipe(D.coerce.date()).or(D.date()).optional(),timeout:D.number().optional(),trimWhitespace:D.boolean().optional()}),aL=D.object({inbox:D.string(),limit:D.number().optional(),afterDate:D.string().pipe(D.coerce.date()).or(D.date()).optional(),trimWhitespace:D.boolean().optional()});var wd=D.object({result:D.unknown(),variableUpdates:D.record(D.string(),D.unknown()).optional(),error:D.string().optional(),success:D.boolean()}),Xr=15e3;import{parseString as BS,splitCookiesString as zS}from"set-cookie-parser";import{z as ie}from"zod";var bd=ie.object({name:ie.string(),value:ie.string(),url:ie.string().optional(),domain:ie.string().optional(),path:ie.string().optional(),expires:ie.number().default(Date.now()/1e3+60*60*24*365),httpOnly:ie.boolean().optional(),secure:ie.boolean().default(!0),sameSite:ie.union([ie.literal("Strict"),ie.literal("Lax"),ie.literal("None")]).default("None")});function Td(r){let e=[],t=zS(r);for(let n of t){let o=BS(n);if(!o.name)throw new Error("Name missing from cookie");if(!o.value)throw new Error("Value missing from cookie");let s;if(o.sameSite){let c=o.sameSite.trim().toLowerCase();if(c==="strict")s="Strict";else if(c==="lax")s="Lax";else if(c==="none")s="None";else throw new Error(`Invalid sameSite setting in cookie: ${c}`)}o.httpOnly===void 0&&(o.httpOnly=!1),!o.path&&o.domain&&(o.path="/");let i=bd.parse({...o,expires:o.expires?o.expires.getTime()/1e3:void 0,sameSite:s});e.push(i);let a=[i.name,...Object.keys(i)].map(c=>c.toLowerCase()),l=n.match(/\b(\w+)=([^;]*)/g);if(l)for(let c of l){let[u,d]=c.split("=");if(!u||!d)throw new Error(`Invalid key-value pair in cookie: ${c}`);a.includes(u.toLowerCase())||e.push({...i,name:u,value:d})}}return e}var WS=ie.object({origin:ie.string(),localStorage:ie.array(ie.object({name:ie.string(),value:ie.string()}))}),Ed=ie.object({cookies:bd.array(),origins:WS.array()});import{z as Ye}from"zod";var jS=Ye.object({orgId:Ye.string(),cacheKeys:Ye.string().array()}),pL=Ye.object({keyParams:jS,clientMetadata:Ye.string(),lockAcquisitionTimeoutMs:Ye.number().optional()}),Cd=Ye.object({acquired:Ye.boolean(),acquiredByMetadata:Ye.string(),keyPrefix:Ye.string()}),hL=Ye.object({keyPrefix:Ye.string(),result:Ye.string(),ttlMs:Ye.number()}),vd=0,Ad=5*60*1e3;var ys=class{flags;constructor(e){this.flags=e}isBooleanFlagEnabled(e){return this.flags[e]===!0}getAllFlags(){return this.flags}};import{z as V}from"zod";import{z as Me}from"zod";var Ne=Me.object({id:Me.string(),name:Ho,baseUrl:Go,schemaVersion:Me.string(),advanced:qr,retries:Me.number(),envs:Me.array(Qo).nullish(),parameters:Zo.nullish()}),TL=Ne.pick({name:!0,baseUrl:!0,retries:!0,advanced:!0,parameters:!0}),HS=Me.object({createdAt:Me.coerce.date(),updatedAt:Me.coerce.date(),schedule:Xo,notification:Jo,createdBy:Me.string(),organizationId:Me.string()}),GS=Ne.merge(HS),EL=GS.extend({steps:Me.array(fe)}),Ss=Ne.merge(Me.object({steps:Me.array(fe)})),CL=Ne.extend({steps:Me.record(Me.string(),Me.unknown()).array()});var ML=V.array(V.object({id:V.string(),name:V.string(),platformSep:V.string(),fullPathSegments:V.string().array(),relativePath:V.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:V.string(),lastModified:V.coerce.date(),createdAt:V.coerce.date()}));var xd=V.object({schemaVersion:V.string(),steps:fe.array()}),Rd=Ne.partial().merge(Ne.pick({id:!0})),Id=V.object({name:V.string(),baseUrl:V.string().url().optional(),environment:V.string().optional(),browserType:V.nativeEnum(Vr).optional(),viewport:Vo.optional()}),NL=Ss.merge(V.object({relativeFilePath:V.string().describe("relative to project root")})),Pd=V.object({name:V.string(),description:V.string(),enabled:V.boolean(),steps:V.lazy(()=>fe.array()),testFilePath:V.string().describe("relative to the project root")});var _L=ea.array(),kL=V.array(Yo),Od=V.object({defaultEnv:V.string().optional().describe("name of the default env, or undefined to unset")}),Ld=V.object({configFilePath:V.string().describe("full path on disk")});var eo=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],Md=eo.map(r=>`**/${r}/**`);import Pt from"chalk";var Ca=class r{minLogLevel;logBindings;constructor(e,t){this.minLogLevel=e,this.logBindings=t}logWithLevel(e,t,...n){if(e<this.minLogLevel)return;let o;Array.isArray(n[0])?(o=n[0],n=n.slice(1)):typeof n[0]=="object"&&!(n[0]instanceof Error)&&Object.entries(n[0]).length&&(o={...n[0],...this.logBindings},n=n.slice(1));let s=[];if(s.push(...n),console.log(t(...s)),o&&!Array.isArray(o)){let i=Object.entries(o);for(let[a,l]of i){let c=l;l instanceof Error?c=l.message:typeof l=="object"&&(c=JSON.stringify(l,void 0,2),c=c.split(`
|
|
@@ -10,7 +10,7 @@ ${this.decisions.map(e=>e.toString()).join(`
|
|
|
10
10
|
`)),console.log(t(` ${a}:`,c))}}else if(o)for(let i of o){let a=i;typeof i=="object"&&(a=JSON.stringify(i,void 0,2),a=a.split(`
|
|
11
11
|
`).map((l,c)=>c>0?` ${l}`:l).join(`
|
|
12
12
|
`)),console.log(" ",t(a))}}setMinLevel(e){this.minLogLevel=e}log(...e){this.logWithLevel(1,Pt.reset,...e)}info(...e){this.logWithLevel(1,Pt.blue,...e)}debug(...e){this.logWithLevel(0,Pt.dim,...e)}warn(...e){this.logWithLevel(2,Pt.yellow,...e)}error(...e){this.logWithLevel(3,Pt.red,...e)}success(...e){this.logWithLevel(4,Pt.green,...e)}dimmed(...e){this.logWithLevel(1,Pt.dim,...e)}underline(...e){this.logWithLevel(2,Pt.underline,...e)}bold(...e){this.logWithLevel(2,Pt.bold,...e)}grey(...e){this.logWithLevel(0,Pt.grey,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},E=new Ca(0,{});var ws={},Jr=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,s,...i)=>{let a=ws[e];a?clearTimeout(a.timer):(a={count:0,totalCount:0},ws[e]=a),a.totalCount++,a.count<t&&(a.count++,r.debug(o,s,...i)),a.timer=setTimeout(()=>{let l=ws[e];l?.totalCount!==l?.count&&r.debug({logKey:e,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${e}`),delete ws[e]},n)};import{z as _e}from"zod";var VS=_e.object({id:_e.string(),createdAt:_e.coerce.date(),createdBy:_e.string(),organizationId:_e.string(),name:_e.string(),description:_e.string().nullish(),enabled:_e.boolean(),schemaVersion:_e.string().describe("Schema version for steps"),parameters:_e.string().array().nullish().describe("Parameter list"),defaultParameters:_e.record(_e.string(),_e.string()).nullish(),defaultCacheKey:_e.string().nullish(),defaultCacheTtl:_e.number().nullish()}),VL=VS.extend({steps:_e.lazy(()=>lt.array())}),Nd=5*60*1e3;import{formatInTimeZone as YL}from"date-fns-tz";import*as v from"zod";var Zr=v.object({disableCache:v.boolean().optional()}),iM=v.object({error:v.boolean(),reason:v.string(),message:v.string()}),aM=v.object({goal:v.string(),url:v.string(),browserState:v.string(),history:v.string(),numPrevious:v.number(),lastCommand:Ea.or(v.null()),screenshot:v.string().optional()}),lM=yd.merge(Zr),va=Ki,cM=gd.merge(Zr).extend({useConsensus:v.boolean().optional()}),_d=sc,dM=v.object({browserState:v.string(),goal:v.string()}).merge(Zr).extend({screenshot:v.string()}),kd=md,uM=v.object({goal:v.string(),url:v.string()}).merge(Zr),Dd=v.string().array(),mM=v.object({goal:v.string(),browserState:v.string()}).merge(Zr),Fd=ud,pM=fd.merge(Zr);var hM=v.object({testPaths:v.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:v.string().optional(),all:v.boolean().optional(),urlOverride:v.string().optional(),customHeaders:v.record(v.string(),v.string()).optional(),testInputMatrix:v.record(v.string(),v.string()).array().optional()}),Ud=v.object({message:v.string(),queuedTests:v.object({name:v.string(),id:v.string()}).array(),runIds:v.string().uuid().array()}),$d=Ss,Bd=v.string().array(),fM=v.union([v.object({paths:v.string().array().describe("run specific test paths (e.g. todo-test)"),all:v.boolean().describe("run all tests").optional()}),v.object({path:v.string().describe("deprecated; present for backcompat")})]),zd=v.object({tests:v.record(v.string().describe("Test name"),v.string().describe("Test YAML")),modules:v.record(v.string().describe("Module name"),v.string().describe("Module YAML"))}),qS=v.object({test:v.string().describe("test YAML"),modules:v.record(v.string().describe("moduleId"),v.string().describe("module YAML"))}),gM=qS.array(),yM=v.object({testId:v.string(),schemaVersion:v.string(),steps:v.array(v.record(v.unknown()))}),SM=v.object({entries:v.array(ra),testId:v.string()}),wM=v.object({steps:v.array(v.record(v.unknown())),testId:v.string(),schemaVersion:v.string(),organizationId:v.string()}),Wd=mc,bM=v.object({testId:v.string(),testName:v.string(),resolvedBaseUrl:v.string().optional(),trigger:v.nativeEnum(Cr),schemaVersion:v.string().optional()}),jd=v.object({id:v.string()}),KS=ba.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Hd=KS.array(),TM=ba.pick({startedAt:!0,finishedAt:!0,results:!0,status:!0,failureDetails:!0,failureReason:!0,debugData:!0,resolvedBaseUrl:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),Gd=v.object({id:v.string()}),EM=v.object({status:v.nativeEnum(ce),finishedAt:Le.optional()}),CM=v.object({screenshot:v.string()}),Vd=v.object({key:v.string()}),qd=v.object({orgId:v.string()}),Kd=v.array(Ko),Yd=v.record(v.string(),v.union([v.string(),v.boolean()])),vM=v.object({paths:v.string().array(),env:v.string().optional(),urlOverride:v.string().optional(),customHeaders:v.record(v.string(),v.string()).optional()}),Xd=v.object({suiteRunIds:v.string().array()});var Jd=ad.array();import{z as $e}from"zod";var Zd="test",Qd="module",zt=(t=>(t.TEST=`${Zd}.yaml`,t.MODULE=`${Qd}.yaml`,t))(zt||{}),ne=(o=>(o.TEST=`momentic/${Zd}`,o.MODULE=`momentic/${Qd}`,o.FIXTURE="momentic/fixture",o.ENVIRONMENT="momentic/environment",o))(ne||{}),LM=Ne.extend({steps:$e.array($e.record($e.string(),$e.unknown()))}),Aa=st.extend({steps:$e.array($e.record($e.string(),$e.unknown())),schemaVersion:$e.string()}),MM=Aa.extend({fileType:$e.literal(ne.MODULE)}),NM=$e.object({test:$e.string().describe("YAML for the test, including metadata and steps"),modules:$e.record($e.string(),$e.string()).describe("Map of module name to YAML for the module")});import{validator as $M}from"@exodus/schemasafe";var eu=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"];var tu=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};import{z as XM}from"zod";var Ot=class extends Error{status;rawError;constructor(e,t,n,o={}){super(n,o),this.status=e,this.rawError=t}};async function YS(r){return r.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var xa=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){return{"Content-Type":"application/json"}}async sendRequest(e,t,n=3,o=3e4){let s=new AbortController,i=setTimeout(()=>s.abort(),o),a=()=>s.abort();t.signal&&t.signal.addEventListener("abort",a);try{return await this.sendRequestHelper(e,t,Math.max(1,n),s.signal)}finally{clearTimeout(i),t.signal&&t.signal.removeEventListener("abort",a)}}async sendRequestHelper(e,t,n,o){let s=n,i;for(;n>0;)try{n--;let a=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:this.getHeaders(),signal:o});if(!a.ok){let c=await YS(a);throw new Ot(a.status,c,`Request to ${e} failed with status ${a.status}: ${c}`)}let l;return a.status===204?l=await a.text():l=await a.json(),this.logger&&!t.noLog&&this.logger.debug({result:l,path:e,baseUrl:this.baseUrl,status:a.status},"Got response from Momentic server"),l}catch(a){if(i=a,this.logger&&this.logger.warn({path:e,baseUrl:this.baseUrl,err:a},`Got error response from Momentic server${n>0?", retrying":""}`),a instanceof Ot&&a.status>=400&&a.status<500||n===0)throw a;await new Promise(l=>setTimeout(l,1500*(s-n)))}throw i}},Ze=class extends xa{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var X="v1",Be=class extends Ze{constructor(e){super(e)}getAppUrl(){return this.baseUrl.replace(/\/\/api/,"//app")}async getOrgId(){let e=await this.sendRequest(`/${X}/auth/check`,{method:"GET",noLog:!0}),{orgId:t}=qd.parse(e);return t}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${X}/runs/status`,{method:"POST",body:e,noLog:!0});return Hd.parse(t)}async createRun(e){let t=await this.sendRequest(`/${X}/runs`,{method:"POST",body:e,noLog:!0});return jd.parse(t)}async updateRun(e,t){await this.sendRequest(`/${X}/runs/${e}`,{method:"PATCH",body:t,noLog:!0})}async createRunAttempt(e){let t=await this.sendRequest(`/${X}/runs/${e}/attempts`,{method:"POST",noLog:!0});return Gd.parse(t)}async updateRunAttempt(e,t,n){await this.sendRequest(`/${X}/runs/${e}/attempts/${t}`,{method:"PATCH",body:n,noLog:!0})}async getTest(e){let t=await this.sendRequest(`/${X}/tests/${e}`,{method:"GET"});return $d.parse(t)}async getAllTestIds(){let e=await this.sendRequest(`/${X}/tests`,{method:"GET"});return Bd.parse(e)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${X}/tests/export`,{method:"POST",body:e});return zd.parse(t)}async updateTestWithYAML(e){await this.sendRequest(`/${X}/tests/update`,{method:"POST",body:e})}async updateStepCaches(e){await this.sendRequest(`/${X}/cache`,{method:"PATCH",body:e})}async getStepCacheForTest(e){let t=await this.sendRequest(`/${X}/cache`,{method:"POST",body:e});return Wd.parse(t)}async queueTests(e){let t=await this.sendRequest(`/${X}/tests/queue`,{method:"POST",body:e});return Ud.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${X}/screenshots`,{method:"POST",body:e,noLog:!0});return Vd.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${X}/environments`,{method:"GET"});return Kd.parse(e)}async getEnvironment(e){let t=await this.sendRequest(`/${X}/environments/${e}`,{method:"GET"});return Ko.parse(t)}async getAllFeatureFlags(){let e=await this.sendRequest(`/${X}/auth/flags`,{method:"GET",noLog:!0});return Yd.parse(e)}async acquireCacheLock(e,t){let n=await this.sendRequest(`/${X}/result-cache/entry`,{method:"POST",body:e,signal:t});return Cd.parse(n)}async releaseCacheLock(e){await this.sendRequest(`/${X}/result-cache/entry`,{method:"DELETE",body:{key:e}})}async setCacheResult(e){await this.sendRequest(`/${X}/result-cache/entry`,{method:"PATCH",body:e})}async getCacheResult(e){try{return await this.sendRequest(`/${X}/result-cache/entry`,{method:"POST",body:e})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${X}/suites/queue`,{method:"POST",body:e});return Xd.parse(t)}async bulkGetSuiteStatus(e){let t={suiteRunIds:e},n=await this.sendRequest(`/${X}/suites/status`,{method:"POST",body:t,noLog:!0});return Jd.parse(n)}async updateCacheLastUsedDate(e,t){try{await this.sendRequest(`/${X}/cache/lastUsedAt`,{method:"PATCH",body:e})}catch(n){t.error({err:n},"Failed to update cache last used date")}}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${X}/runs/proposed-steps`,{method:"POST",body:e})}catch(n){t.error({err:n},"Failed to upload proposed steps")}}};function Qr({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:s}=t,i=[],a=[],l=0,c=(d,m)=>{try{let p=Sr.parse(m.value);if(p.type!==d.type){o.warn({parsedCacheEntry:p,command:d},"Not using step cache due to type mismatch"),a.push(m.key);return}d.cache=p.cache,i.push(m.key)}catch(p){a.push(m.key),o.error({err:p,cacheEntry:m},"Not using step cache due to parsing error")}},u=(d,m)=>{let p=XS(d.id,m),h=p.find(f=>!!n[f]);h?c(d,n[h]):(a.push(p[0]),o.debug({command:d,possibleKeys:p},"Step cache miss"))};for(let d of r)switch(d.type){case"RESOLVED_MODULE":{l+=d.steps.length;let{hits:p,misses:h}=Qr({...t,steps:d.steps,keyPrefix:s?`${s}:${d.id}`:d.id,topLevel:!1});i=i.concat(p),a=a.concat(h);break}case"IFRAME":case"SECTION":case"AI_ACTION":{if(l+=d.steps?.length??0,!d.steps?.length)break;let{hits:p,misses:h}=Qr({...t,steps:d.steps,topLevel:!1});i=i.concat(p),a=a.concat(h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!ta.includes(d.command.type)||d.command.type==="TYPE"&&!d.command.target||d.command.type==="MOUSE_DRAG"&&!d.command.target||"cache"in d.command&&d.command.cache)continue;l++,u(d.command,s);break}case"CONDITIONAL":{for(let p of d.blocks){l++,u(p.assertion.command,s),l+=p.steps.length;let{hits:h,misses:f}=Qr({...t,steps:p.steps,topLevel:!1});i=i.concat(h),a=a.concat(f);break}if(d.elseSteps){l+=d.elseSteps.length;let{hits:p,misses:h}=Qr({...t,steps:d.elseSteps,topLevel:!1});i=i.concat(p),a=a.concat(h)}break}default:return(p=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(d)}return e&&l&&a.length>0&&o.debug({totalSteps:l,cacheMisses:a,cacheHits:i,cacheEntries:n.length},"Step cache did not fully resolve"),{hits:i,misses:a}}function ru(r,e){return e?`${e}:${r}`:r}function XS(r,e){let t=[],n=e?.split(":")??[];for(let o=n.length;o>=0;o--){let s=[...n.slice(o),r];t.push(s.join(":"))}return t}function nu(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
|
|
13
|
-
${JSON.stringify(t)}`);let n=[];if(!r.skipIntermediateEntries)for(let o=e.length;o>0;o--){let s=t[o-1],i=e.slice(o,e.length).join(":");n.push({key:ru(r.id,i),moduleId:s,organizationId:r.orgId,value:r.value})}return n.push({key:ru(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function ou(r){switch(r.type){case"DRAG":{if(r.fromTarget.type==="coordinates"||r.toTarget.type==="coordinates"||!r.fromTarget?.a11yData||!r.toTarget?.a11yData)return;r.cache={fromTarget:r.fromTarget.a11yData,toTarget:r.toTarget.a11yData},delete r.fromTarget.a11yData,delete r.toTarget.a11yData;return}case"MOUSE_DRAG":case"HOVER":case"SCROLL_UP":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SELECT_OPTION":case"TYPE":case"VISUAL_DIFF":case"CLICK":case"FOCUS":case"BLUR":{if(r.target?.type==="coordinates"||!r.target?.a11yData)return;r.cache={target:r.target.a11yData},delete r.target.a11yData;return}default:return}}function ze(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var vr={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with"},Ar={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with"},Ra={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable"},Ia={EXISTS:"does not exists",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable"};function JS(r){switch(r.type){case"ELEMENT_CONTENT":return`${r.negated?Ar[r.operation]:vr[r.operation]} '${r.value}'`;case"ELEMENT_ATTRIBUTE":{let t=r.negated?Ar[r.operation]:vr[r.operation];return`attribute '${r.attr}' ${t} '${r.value}'`}case"ELEMENT_EXISTENCE":return r.negated?Ia[r.condition]:Ra[r.condition];default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var O_={CONTENT:"The page"};function ZS(r){switch(r.type){case"VALUE":return`the option with value ${r.value}`;case"LABEL":return`the option with label ${r.label}`;case"INDEX":return`the option at index ${r.index}`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function QS(r){switch(r.type){case"CONTENT":return`${r.negated?Ar.CONTAINS:vr.CONTAINS} '${r.value}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function nr(r){switch(r.type){case"SUCCESS":return r.condition?.assertion?`Check success condition: ${r.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${r.goal}`;case"NAVIGATE":return`Go to URL: ${ze(r.url,30)}`;case"DIALOG":return`Automatically ${r.action.toLowerCase()} the next dialog`;case"CAPTCHA":return"Solve captchas on the page";case"GO_BACK":return"Go back to the previous page";case"GO_FORWARD":return"Go forward to the next page";case"SCROLL_DOWN":return`Scroll down ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${Pe(r.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${Pe(r.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${Pe(r.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${Pe(r.target)}`:""}`;case"WAIT":return`Wait for ${r.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(r.target?.type==="coordinates")return`Click at coordinates: ${Pe(r.target)}`;let n="";return r.target?.elementDescriptor.length?n=` on element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` on element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Click${n}`}case"FOCUS":return`Focus ${Pe(r.target)}`;case"BLUR":return`Focus ${Pe(r.target)}`;case"DRAG":return`Drag ${Pe(r.fromTarget)} onto ${Pe(r.toTarget)}`;case"MOUSE_DRAG":return r.target?`Click and drag ${Pe(r.target)} by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`:`Click and drag mouse by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`;case"TYPE":{let n="";return r.target?.type==="coordinates"?n=` in element at coordinates: ${Pe(r.target)}`:r.target?.elementDescriptor.length?n=` in element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` in element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Type '${r.value}'${n||""}`}case"HOVER":{let n="";return r.target.type==="coordinates"?n=` over coordinates: ${Pe(r.target)}`:r.target.elementDescriptor.length>0?n=` over element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` over element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Hover${n}`}case"PRESS":return`Press ${r.value}`;case"SELECT_OPTION":{let n="",o=r.option??ZS(r.choice);return r.target.type==="coordinates"?n=` from element at coordinates: ${Pe(r.target)}`:r.target.elementDescriptor.length>0?n=` from: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` from: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${o}'${n}`}case"TAB":if(r.url)return`Switch to tab with substring: ${r.url}`;if(r.action)switch(r.action.type){case"SUBSTRING":return`Switch to tab with substring: ${r.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${r.action.pattern}`;case"INDEX":return`Switch to tab at index: ${r.action.index}`;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${r.url}`;case"REQUEST":return`Send ${r.method} request to ${r.url}`;case"COOKIE":return`Set cookie: ${r.value}`;case"LOCAL_STORAGE":return`Set local storage: ${r.key}: ${r.value}`;case"JAVASCRIPT":return`Run JavaScript: ${ze(r.code,30)}`;case"AI_ASSERTION":return`Assertion: '${r.assertion}'`;case"AI_WAIT":return`Wait until assertion is true: '${r.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${r.target?`for element: ${Pe(r.target)}`:"for entire page"}`;case"FILE_UPLOAD":return`Upload file: ${r.fileSource.url}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Assert the element ${Pe(r.target)} ${JS(r.assertion)}`;case"PAGE_CHECK":return`Assert the page ${QS(r.assertion)}`;case"WAIT_FOR_URL":return`Wait for the page URL to match: ${r.url}`;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function su(r){let e=[];for(let t of r){t.sort((i,a)=>i.timestamp-a.timestamp);let n=[],o,s=1;for(let i of t)o&&o.text===i.text&&o.type===i.type&&JSON.stringify(o.args??null)===JSON.stringify(i.args??null)?s++:(o&&(s>1?o.args&&o.args.length?o.args.push(`(repeated ${s} times)`):o.text+=` (repeated ${s} times)`:n.push(o)),o=i,s=1);o&&n.push(o),e.push(n)}return e}function Wt(r){let{onPresetAction:e,onSimpleStepContainer:t,onConditional:n}=r;for(let o of r.steps)switch(o.type){case"PRESET_ACTION":e(o);break;case"CONDITIONAL":n?.(o);for(let i of o.blocks)e(i.assertion),Wt({...r,steps:i.steps});Wt({...r,steps:o.elseSteps??[]});break;case"RESOLVED_MODULE":case"IFRAME":case"SECTION":case"AI_ACTION":t?.(o),o.steps&&Wt({...r,steps:o.steps});break;case"AI_ACTION_DYNAMIC":{t?.(o);break}default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(o)}}function bs(r){let e=0;Wt({steps:r,onPresetAction:t=>{t.index=e++},onConditional:t=>{t.index=e++},onSimpleStepContainer:t=>{t.index=e++}})}function iu(r){Wt({steps:r,onPresetAction:e=>{delete e.index},onConditional:e=>{delete e.index},onSimpleStepContainer:e=>{delete e.index}})}var ew=(r,e)=>{switch(r.type){case"RESOLVED_MODULE":return r.steps[e];case"AI_ACTION":return r.steps[e];case"CONDITIONAL":{let n=r.blocks.map(o=>[o.assertion,...o.steps]).flat();return r.elseSteps&&(n=n.concat(r.elseSteps)),n[e]}case"SECTION":case"IFRAME":return r.steps[e];case"PRESET_ACTION":default:throw new Error(`Cannot get a child step from step type ${r.type}`)}};function Ts(r,e){let t=r[e[0]],n;for(let o=1;o<e.length;o++)n=t,t=ew(t,e[o]);return{step:t,parent:n}}function au(r){let e=0;return Wt({steps:r,onPresetAction:t=>{e=Math.max(e,t.index)},onConditional:t=>{e=Math.max(e,t.index)},onSimpleStepContainer:t=>{e=Math.max(e,t.index)}}),e}import{cloneDeep as q_,unset as K_}from"lodash-es";function to(r){switch(r.type){case"AI_ACTION":return`AI action: ${ze(r.text,100)}`;case"AI_ACTION_DYNAMIC":return`Dynamic AI action: ${ze(r.text,100)}`;case"PRESET_ACTION":return nr(r.command);case"MODULE":return`Module: ${r.id}`;case"RESOLVED_MODULE":return`Module: ${r.name}`;case"CONDITIONAL":return"Conditional step";case"IFRAME":return"Frame step";case"SECTION":return`Section${r.description?`with goal: ${ze(r.description,100)}`:""}`;default:return(t=>{throw new Error("You missed a case in the switch above")})(r)}}function Es(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{n.data&&(n.data=JSON.parse(Yn(JSON.stringify(n.data),1e3).jsonString))}catch(o){e.error({err:o},"Failed to serialize individual result output data"),n.data=`Result output data could not be serialized: ${o}`}switch(n.details&&(n.details=void 0),n.type){case"PRESET_ACTION":lu(n);try{r[t]=JSON.parse(Yn(JSON.stringify(n),1e4).jsonString)}catch(o){e.error({err:o},"Failed to truncate individual preset action result")}break;case"CONDITIONAL":n.assertion&&lu(n.assertion),Es(n.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"IFRAME":case"MODULE":case"SECTION":{Es(n.results,e);break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}}function lu(r){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}function cu(r,e){if(!(!r.envs||!r.envs.length)){for(let t of r.envs){let n=t;e in t&&(n[e]&&(t.default=!0),delete n.defaultOnCloud,delete n.defaultOnLocal)}r.envs.some(t=>t.default)||(r.envs[0].default=!0)}}import sw from"diff-lines";import vs,{gte as iw}from"semver";var du={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>(r=r.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),r=r.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),r)};var uu={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,n=t[t.length-1];return n&&n.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var tw=["target","fromTarget","toTarget"];function mu(r){for(let e of tw){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var pu={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":return mu(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])mu(n);return e}default:return e}})};import{v4 as rw}from"uuid";var hu={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=rw()),e;default:return e}})};import{v4 as fu}from"uuid";var gu={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??fu(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??fu()}})),delete e.commands),e;default:return e}})};var yu={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return typeof t.type!="string"||t.type!=="AI_WAIT"||(t.type="AI_ASSERTION",t.timeout||(t.timeout=10)),e}default:return e}})};import{v4 as nw}from"uuid";var Su={name:"Add ids to all steps",fromVersion:"1.0.10",toVersion:"1.0.11",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>("id"in e&&typeof e.id=="string"||(e.id=nw()),e))};import{v4 as wu}from"uuid";var bu={name:"Add ids to all steps",fromVersion:"1.0.11",toVersion:"1.0.12",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let t=e.condition;t.id||(t.id=wu())}return e.id=wu(),e})};var Tu={name:"Move env key to steps",fromVersion:"1.0.12",toVersion:"1.0.13",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};import{v4 as ow}from"uuid";var Eu={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=ow()),e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};var Cu={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:t.option},e.option=void 0),e})};var vu={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return t&&Au(t),e})};function Au(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){Au(r[e]);return}if(typeof r[e]!="string")return;let t=r[e];e==="code"?r[e]=t.replace(/inputs\./g,"env."):t.includes("{{")&&t.includes("}}")&&(r[e]=t.replace(/inputs\./g,"env."))})}var xu={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TAB"||e.url===void 0||(e.action={type:"SUBSTRING",substring:e.url},e.url=void 0),e})};var Ru={name:"Migrate AI assertions to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async r=>r.map(e=>{if(e.type!=="AI_ASSERTION")return e;let n={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...n};return delete o.text,o}),stopOnFailure:!0};var Cs=new Set(["CLICK","TYPE","SELECT_OPTION"]),Iu={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type,o=t?.elementDescriptor;return(o!==void 0||Cs.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let a=i?.elementDescriptor,l=i?.type;(a!==void 0||Cs.has(l))&&(i.target={elementDescriptor:a??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let a=i.command,l=a?.elementDescriptor,c=a?.type;(l!==void 0||Cs.has(c))&&(a.target={elementDescriptor:l??""}),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(d=>{let m=d?.elementDescriptor,p=d?.type;(m!==void 0||Cs.has(p))&&(d.target={elementDescriptor:m??""})})}),e}),stopOnFailure:!0};var Pu={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(n=>{if(n&&typeof n=="object"){let o=n;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var Ou={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type;return n?.startsWith("PRESET_")&&(t.type=n.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(s=>{let i=s.type;i?.startsWith("PRESET_")&&(s.type=i.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(s=>{let i=s.command,a=i?.type;a?.startsWith("PRESET_")&&(i.type=a.slice(7)),s.commands&&Array.isArray(s.commands)&&s.commands.forEach(c=>{let u=c.type;u?.startsWith("PRESET_")&&(c.type=u.slice(7))})}),e}),stopOnFailure:!0};var xr=[Ru,Pu,Ou,Iu,du,uu,pu,hu,gu,yu,Su,bu,Tu,Eu,Cu,vu,xu];if(ct!==xr[xr.length-1].toVersion)throw new Error("Please bump LATEST_VERSION in types package after adding a migration");xr.forEach((r,e)=>{if(!vs.valid(r.toVersion)||!vs.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!vs.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(xr[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});function aw(r){return r.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var Pa=async({metadata:r,steps:e,logger:t,toVersion:n})=>{let o=e,{schemaVersion:s,id:i}=r,a=xr.findIndex(u=>vs.gt(u.toVersion,s));if(a===-1)return{steps:o,newVersion:s};let l=s;for(let u=a;u<xr.length;u++){if(n&&iw(l,n)){t.debug("Stopping migration early because toVersion was reached");break}let d=xr[u],m={id:i,migration:d.name,toVersion:d.toVersion};try{o=await Lu(o,d),l=d.toVersion}catch(p){throw t.error({err:p,...m},"Migration failed"),new Error(`Step migration ${d.name} failed: ${p}`)}}let c=sw(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return c.trim()&&t.debug({diffs:c,id:i},"Migration diffs"),{newVersion:l,steps:o}};async function Lu(r,e){let t=await e.execute(r);for(let n of t)for(let o of Object.keys(n)){if(!e.recursiveKeys.has(o))continue;let s=n[o];!s||!Array.isArray(s)||aw(s)&&(n[o]=await Lu(s,e))}return t}async function Mu({rawSteps:r,metadata:e,logger:t,callbacks:n}){cu(e,"defaultOnCloud");let o={},{resolvedSteps:s,newSchemaVersion:i}=await Oa({rawSteps:r,metadata:e,logger:t,callbacks:n,resolvedModuleCache:o});return{resolvedTest:{...e,steps:s,schemaVersion:i},moduleIds:Array.from(Object.keys(o))}}async function Oa({rawSteps:r,metadata:e,logger:t,callbacks:n,resolvedModuleCache:o={}}){let{newVersion:s,steps:i}=await Pa({metadata:e,steps:r,logger:t}),a;try{a=lt.array().parse(i)}catch(c){throw t.error({type:"zod",err:c,newVersion:s,id:e.id,steps:i},"Failed to parse test steps while migrating test"),new fs(`Failed to parse test steps while migrating test: ${c}`,e.id,"entity",{cause:c})}let l=[];for(let c of a)l.push(await ro({step:c,callbacks:n,logger:t,resolvedModuleCache:o}));return{resolvedSteps:l,newSchemaVersion:s}}async function ro({step:r,callbacks:e,logger:t,resolvedModuleCache:n}){switch(r.type){case"AI_ACTION":return r;case"AI_ACTION_DYNAMIC":return r;case"PRESET_ACTION":return r;case"MODULE":{let l=r.moduleId,c=n[l];if(c)return{...c,...r,type:"RESOLVED_MODULE"};let u=await e.onFetchModule({id:l,logger:t});if(!u)throw new Error(`Could not find module with id ${l}`);let{newVersion:d,steps:m}=await Pa({metadata:{id:l,schemaVersion:u.schemaVersion},steps:u.steps,logger:t}),p;try{p=lt.array().parse(m)}catch(g){throw t.error({type:"zod",err:g,steps:m,newVersion:d,id:l},"Module failed to parse"),g}let h;try{h=await Promise.all(p.map(g=>ro({step:g,callbacks:e,logger:t,resolvedModuleCache:n})))}catch(g){throw t.error({err:g,...r},`Failed to recursively resolve module '${u.name}': ${g}`),g}let f={...u,steps:h};return n[l]=f,{...f,...r,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let l of r.blocks){let c=[];for(let u of l.steps)c.push(await ro({step:u,callbacks:e,logger:t,resolvedModuleCache:n}));o.push({...l,steps:c})}let s;if(r.elseSteps){s=[];for(let l of r.elseSteps)s.push(await ro({step:l,callbacks:e,logger:t,resolvedModuleCache:n}))}return{...r,blocks:o,elseSteps:s};case"SECTION":case"IFRAME":let i=[];for(let l of r.steps)i.push(await ro({step:l,callbacks:e,logger:t,resolvedModuleCache:n}));return{...r,steps:i};default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}import{cloneDeep as lw}from"lodash-es";import{v4 as Nu}from"uuid";async function gt(r){let e=lw(r.steps);return en({...r,steps:e,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:new Map,seenModules:new Set})}async function en({steps:r,...e}){let{seenModules:t,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:s,moduleIdReplacements:i,shouldCreateNewModuleId:a}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let c of r)switch(delete c.index,c.type){case"PRESET_ACTION":{let d=c.command;d.id=n?.createNewCacheIds?Nu():d.id,ou(d),"cache"in d&&d.cache&&(n&&(l.cachesToSave=l.cachesToSave.concat(nu({id:d.id,orgId:n.orgId,testId:n.testId,value:Sr.parse(d),moduleIdParents:o,moduleStepParents:s,skipIntermediateEntries:e.skipCacheIntermediateEntries}))),delete d.cache),l.stepsToSave.push({...c,command:d});break}case"RESOLVED_MODULE":{let d=n?.createNewCacheIds?Nu():c.id,m=c.moduleId;if(i.has(m))m=i.get(m);else if(a){let y=await a(c);i.set(c.moduleId,y)}let{cachesToSave:p,stepsToSave:h,moduleUpdates:f}=await en({...e,steps:c.steps,cacheCreationParams:n?{...n,createNewCacheIds:!1}:void 0,moduleStepParents:[...s,d],moduleIdParents:[...o,m],skipCacheIntermediateEntries:n?.createNewCacheIds});l.moduleUpdates=l.moduleUpdates.concat(f),l.cachesToSave=l.cachesToSave.concat(p),t.has(m)||(t.add(m),l.moduleUpdates.push({...st.parse(c),steps:lt.array().parse(h)}));let g={type:"MODULE",moduleId:m,inputs:c.inputs,id:d,skipped:c.skipped,cacheConfig:c.cacheConfig,envKey:c.envKey};l.stepsToSave.push(g);break}case"AI_ACTION":{if(!c.steps){l.stepsToSave.push(c);break}let{stepsToSave:d,cachesToSave:m}=await en({...e,steps:c.steps});try{c.steps=ot.array().parse(d)}catch(p){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${p}`)}l.stepsToSave.push(c),l.cachesToSave=l.cachesToSave.concat(m);break}case"AI_ACTION_DYNAMIC":{l.stepsToSave.push(c);break}case"CONDITIONAL":{let d=[];for(let p of c.blocks){let{stepsToSave:h,cachesToSave:f,moduleUpdates:g}=await en({...e,steps:p.steps});d.push({...p,steps:h}),l.cachesToSave=l.cachesToSave.concat(f),l.moduleUpdates=l.moduleUpdates.concat(g)}let m={...c,elseSteps:void 0,blocks:d};if(c.elseSteps){let{stepsToSave:p,cachesToSave:h,moduleUpdates:f}=await en({...e,steps:c.elseSteps});m.elseSteps=p,l.cachesToSave=l.cachesToSave.concat(h),l.moduleUpdates=l.moduleUpdates.concat(f)}l.stepsToSave.push(m);break}case"IFRAME":case"SECTION":{let{stepsToSave:d,cachesToSave:m,moduleUpdates:p}=await en({...e,steps:c.steps}),h={...c,steps:d};l.moduleUpdates=l.moduleUpdates.concat(p),l.stepsToSave.push(h),l.cachesToSave=l.cachesToSave.concat(m);break}default:return(d=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(c)}return l}import{cloneDeep as cw}from"lodash-es";import{stringify as _u}from"yaml";async function ku(r,e=new Set){let t={id:r.id,name:r.name,baseUrl:r.baseUrl,schemaVersion:r.schemaVersion,advanced:r.advanced,retries:r.retries,envs:r.envs},n={},o=await dw(r.steps,r.schemaVersion,n,e),s={fileType:ne.TEST,...t,steps:o};return{test:_u(s),modules:n}}async function dw(r,e,t,n){let o=cw(r);uw(o);let{stepsToSave:s,moduleUpdates:i}=await gt({steps:o});for(let a of i)n.has(a.name)||(t[a.name]=mw(a),n.add(a.name));return s}function uw(r){Wt({steps:r,onPresetAction:e=>{e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.index=void 0},onSimpleStepContainer:e=>{e.index=void 0}})}function mw(r){let e=st.parse(r),t={fileType:ne.MODULE,...e,schemaVersion:ct,steps:r.steps};return _u(t)}async function q(r,e){return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",s);let o=setTimeout(()=>{e?.removeEventListener("abort",s),t()},r);function s(){clearTimeout(o),e?.removeEventListener("abort",s),n(e?.reason)}})}async function Lt(r,e){return new Promise((t,n)=>{if(e?.aborted){n(e?.reason);return}e?.addEventListener("abort",o),Promise.resolve(r).then(t).catch(n).finally(()=>{e?.removeEventListener("abort",o)});function o(){e?.removeEventListener("abort",o),n(e?.reason)}})}var tn=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 setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}async saveStepCacheEntries(e,t,n){try{await this.client.updateStepCaches({entries:e,testId:t})}catch(o){n.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let t=await this.client.getStepCacheForTest({testId:e.testId,organizationId:e.organizationId,steps:e.steps,schemaVersion:e.schemaVersion}),{hits:n}=Qr({steps:e.steps,stepCacheEntries:t,logger:e.logger});this.client.updateCacheLastUsedDate(n,e.logger)}};var no="v1",yt=class{httpClient;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)};constructor(e){this.httpClient=e.httpClient}async sendSms(e){return this.httpClient.sendRequest(`/${no}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Ot?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${no}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ot?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${no}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Ot?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${no}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ot?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${no}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ot?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import $h from"body-parser";import VC from"cors";import qC from"events";import Bh,{Router as KC}from"express";import YC from"http";import XC from"open";import{Server as $T}from"socket.io";var pw={showOverlay:!1},La=class{sessions=new Map;sessionCountByIp=new Map;getCurrentConnectionsByIp(e){return this.sessionCountByIp.get(e)??0}getCurrentSessionsByIp(){return Object.fromEntries(this.sessionCountByIp)}reserveCapacityByIp(e){e&&this.sessionCountByIp.set(e,(this.sessionCountByIp.get(e)??0)+1)}releaseCapacityByIp(e){e&&this.sessionCountByIp.set(e,Math.max(this.getCurrentConnectionsByIp(e)-1,0))}registerSession({controller:e,context:t,cleanup:n,clientIp:o,sessionId:s,browserbaseSessionId:i}){return this.sessions.set(s,{controller:e,context:t,cleanup:n,clientIp:o,browserbaseSessionId:i,browserBehavior:pw}),s}removeSession(e,t){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:s}=o;try{s.setClosed(),await s.browser.cleanup()}catch(i){t.error({err:i},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(i){t.error({err:i},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}},z=new La;var hw=200;function Du(r,e,t){let n=Date.now(),o=-1,s=0,i=Date.now(),a,l,c=async(m,p)=>{if(!m.closed){if(s>0&&Math.random()>=1/Math.max(s,8)){s<8&&t.error({sessionId:e},"Dropping screenshot due to previous failures");return}try{let h;(!a||!l||Date.now()-i>=1500)&&(a=await m.getViewport(),l=await m.getAllFrameUrls(),i=Date.now(),h=m.retrieveAndClearConsoleLogs()),r.emit("browserState",{logsPerPage:h,viewport:a,buffer:await m.screenshot({retries:0,timeout:750,scale:"device",quality:75}),url:m.url(),iframeSrcUrls:l,context:p.toEditorDisplayCopy()}),n=Date.now(),s=0}catch(h){if(!r.connected)return;let f=h instanceof Error?h.message:`${h}`;if(f.includes("Frame was detached")||f.includes("Not attached to an active page")||f.includes("browser has been closed"))return;s++,t.error({err:h,sessionId:e},"Error taking screenshot")}finally{r.connected&&Date.now()-n>15e3&&Date.now()-o>3e4&&(t.error({sessionId:e},"Screenshots to client are stale"),o=Date.now())}}},u={timer:void 0},d=()=>{let m=z.getSession(e),p=m?.controller?.browser;if(!p||p.closed){t.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(u.timer);return}c(p,m.context)};return u.timer=setInterval(d,hw),u}var or={};var fw=r=>()=>{let{sessionId:e}=r.metadata;or[e]?.abort?.abort()},Fu={event:"cancelApiTest",createHandler:fw};import{CookieJar as Lw}from"tough-cookie";import{randomUUID as Cw}from"crypto";import{faker as gw}from"@faker-js/faker";import yw from"assert";import Sw from"axios";import ww from"moment";import*as bw from"otpauth";import Tw from"pg";var rn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Uu=r=>{let e=r.reason===void 0?new DOMException("This operation was aborted.","AbortError"):r.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};async function J(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,a;return new Promise((l,c)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:d}=e;d.aborted&&c(Uu(d)),a=()=>{c(Uu(d))},d.addEventListener("abort",a)}if(t===Number.POSITIVE_INFINITY){r.then(l,c);return}let u=new rn;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(d){c(d)}return}"cancel"in r&&typeof r.cancel=="function"&&r.cancel(),o instanceof Error?c(o):(u.message=o??`Promise timed out after ${t} milliseconds`,c(u))},t),(async()=>{try{l(await r)}catch(d){c(d)}})()}).finally(()=>{i!==void 0&&s.clearTimeout.call(void 0,i),a!==void 0&&e.signal&&e.signal.removeEventListener("abort",a)})}var Ew=Object.getPrototypeOf(async function(){}).constructor;async function $u(r,e,t){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,results:s}=e.bindings,i=e.tools,a={},l=(f,g)=>{o[f]=g,a[f]=g},c;n.includes("Octokit")&&(c=(await import("@octokit/rest")).Octokit);let u;n.includes("createAppAuth")&&(u=(await import("@octokit/auth-app")).createAppAuth);let d=async()=>await Promise.resolve(new Ew("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","env","results","setVariable","sendSms","waitForLatestSms","email","sms",n)(Sw,ww,gw,yw,Tw,c,u,bw,o,s,l,g=>i.sms.send(g),g=>i.sms.fetchLatest(g),i.email,i.sms)),m=!0,p,h;try{p=await J(d(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal}),t.debug(`[${r}] Got execution result: ${JSON.stringify(p)}`),t.debug(`[${r}] Got variable updates: ${JSON.stringify(a)}`)}catch(f){t.error(`[${r}] Error executing code: ${f}`),m=!1,f instanceof rn?h=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:h=f instanceof Error?f.message:`${f}`}return{result:p,variableUpdates:a,success:m,error:h}}async function Bu({code:r,fragment:e,context:t,localTools:n,logger:o,signal:s,timeoutMs:i=Xr}){let a=Cw();return $u(a,{code:r,options:{fragment:e,timeoutMs:i},bindings:t.toObjectCopy(),tools:n,signal:s},o)}import{createHmac as vw,randomUUID as Aw}from"crypto";var zu=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,Wu=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function ju({orgId:r,code:e,fragment:t,context:n,logger:o,timeoutMs:s=Xr,retries:i=1,signal:a}){if(!zu)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let l,c,u=0;if(!Wu)throw new Error("Missing lambda auth secret.");let d=vw("sha256",Wu).update(r).digest("hex");for(;u<=i;){u++,a?.throwIfAborted();let p={id:Aw(),orgId:r,momenticLambdaAuthHash:d,code:e,fragment:t,state:n.toObjectCopy(),timeoutMs:s};o.debug(p,"Sending request to code evaluation server");try{if(l=await J(fetch(zu,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)}),{milliseconds:s,message:`Timeout of ${s}ms exceeded for code execution`,signal:a}),!l)throw new Error("Got empty response from code evaluation server");if(!l.ok)throw new Error(`Code evaluation server returned error code ${l.status}`);c=void 0;break}catch(h){c=h}}if(c)throw c;if(!l)throw new Error(`An unexpected code evaluation error occurred${c?`: ${c}`:""}`);let m;try{m=wd.parse(await l.json()),o.debug({response:m},"Response from code evaluation server")}catch(p){throw new Error(`Code evaluation server returned invalid response: ${p}`)}if(m.error)throw new Error(`Code evaluation error: ${m.error}`);return m}async function jt(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await ju(r);else if(r.localTools)e=await Bu({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error)throw new Error(`Code evaluation error: ${e.error}`);if(e.variableUpdates)for(let[t,n]of Object.entries(e.variableUpdates))r.context.setVariable(t,n);return e.result}var rF=process.env.MAILINATOR_API_KEY;import"twilio";async function St(r){let{orgId:e,s:t,context:n,logger:o,timeoutMs:s=Xr,retries:i=1,signal:a}=r,l=/{{(.*?)}}/g,c=t.matchAll(l),u=t;for(let d of c){if(d.length<2)continue;let m=d[1].trim(),p;try{p=await jt({orgId:e,code:m,fragment:!0,context:n,timeoutMs:s,logger:o,retries:i,localTools:r.localTools,signal:a})}catch(f){throw o.error({err:f,value:t},"Error evaluating template string"),f}if(p===void 0)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 h=typeof p=="string"?p:`${p}`;h=h.replace(/\$/g,"$$$$"),h=h.replace(/\\/g,"\\\\"),u=u.replace(d[0],h)}return o.debug({s:t,result:u},"Substituted template string"),u}async function oo({cmd:r,bannedKeys:e,context:t,prefixPath:n="",replacements:o={},...s}){for(let i in r){if(e.includes(i))continue;let a=r[i],l=n?`${n}.${i}`:i;if(typeof a=="string"&&a.includes("{{")){let c=await St({s:a,context:t,...s});if(a===c)continue;o[l]=a,r[i]=c}else typeof a=="object"&&a!==null&&!Array.isArray(a)&&await oo({cmd:a,bannedKeys:e,context:t,prefixPath:l,replacements:o,...s})}return o}import Iw from"fetch-cookie";import{cloneDeep as Pw}from"lodash-es";var As=(r,e)=>{try{let{hostname:t,pathname:n}=new URL(r),{hostname:o,pathname:s}=new URL(e);return t!==o||n!==s}catch{return!1}},xs=r=>{try{return new URL(r),!0}catch{return!1}},Hu=r=>!r.toLowerCase().startsWith("http"),Rs=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function Rr(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}var Rw=3e4;async function Is({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??Rw/1e3,s=null,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([g,y])=>g&&y)),l=new URLSearchParams;Object.entries(r.params||{}).filter(([g,y])=>g&&y).forEach(([g,y])=>{l.append(g,y)});let c=l.toString(),u;if(xs(r.url)&&(u=r.url),t&&Rs(r.url,t)&&(u=new URL(r.url,t).toString()),!u)throw new R("ActionFailureError",`Invalid URL: ${r.url}`);let d=async()=>{let g=c?`${u}?${c}`:u;try{s=await n(g,{headers:a,method:r.method,body:r.body,signal:i.signal})}catch(y){e.error({err:y},"Failed to make HTTP request")}},m=async()=>{await new Promise(g=>setTimeout(g,o*1e3)),i.abort()};await Promise.race([m(),d()]);let p=s;if(!p)throw new R("ActionFailureError",`Fetch request timed out after ${o} seconds`);if(!p.ok)throw new R("ActionFailureError",`Fetch request failed with status ${p.status}`);let h={};p.headers.forEach((g,y)=>{h[y]=g});let f={status:p.status,headers:h};return p.headers.get("content-type")?.includes("json")?f.json=await p.json():p.headers.get("content-type")?.includes("text")&&(f.text=await p.text()),f}async function Gu(r){let{fixtures:e,inputs:t}=r,{context:n}=e,{orgId:o,step:s}=t,i=Pw(s);await oo({cmd:i,orgId:o,bannedKeys:["code"],...e});let a=await Ow(r);return i.envKey&&a.data&&n.setVariable(i.envKey,a.data),a}async function Ow(r){let{fixtures:e,inputs:t}=r,{step:n,orgId:o,baseUrl:s}=t,{cookieJar:i}=e,a=new Date;switch(n.type){case"JAVASCRIPT":{let c=await jt({code:n.code,orgId:o,fragment:!!n.fragment,timeoutMs:n.timeout?n.timeout*1e3:void 0,...e});try{JSON.stringify(c)}catch(u){return{...n,startedAt:a,finishedAt:new Date,status:"FAILED",message:`JavaScript return value is not serializable: ${u instanceof Error?u.message:`${u}`}`}}return{...n,startedAt:a,finishedAt:new Date,message:"JavaScript code executed successfully",status:"SUCCESS",data:c}}case"REQUEST":{let c=Iw(fetch,i),u=await Is({command:n,logger:e.logger,baseUrl:s,fetchImplementation:c});return{...n,startedAt:a,finishedAt:new Date,status:"SUCCESS",message:"Request executed successfully",data:u}}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}async function Vu(r){let{inputs:e,fixtures:t,callbacks:n}=r,{signal:o}=t,{test:s,orgId:i}=e,{test:a,step:l}=n,c={startedAt:new Date,status:"RUNNING",results:[]},u=c.results,d=new Lw,m={cookieJar:d,...t};for(let p of s.steps){let h=new Date;l.onStarted?.(p.id);let f;try{o?.throwIfAborted(),f=await Gu({inputs:{step:p,baseUrl:s.baseUrl,orgId:i},fixtures:m})}catch(g){o?.aborted?f={...p,startedAt:h,finishedAt:new Date,status:"CANCELLED",message:"Step cancelled by user."}:f={...p,startedAt:h,finishedAt:new Date,status:"FAILED",message:`Step failed: ${g instanceof Error?g.message:`${g}`}`}}if(u.push(f),l.onFinished?.({result:f,cookies:d.cloneSync()?.serializeSync()?.cookies??[]}),a.updateAttemptProgress?.({results:u}),f.status!=="SUCCESS"){c.status=f.status==="CANCELLED"?"CANCELLED":"FAILED";break}}return c.status==="RUNNING"&&(c.status="PASSED"),c.finishedAt=new Date,a.onFinished?.(),c}var Mw=r=>async(e,t)=>{let{test:n}=e,{authorization:o,metadata:s,socket:i}=r,{orgId:a,testId:l,sessionId:c}=s,{logger:u}=r,d=or[c];if(!d)throw new Error(`No api testing session with id ${c} could be found. Please reconnect and try again.`);let m=new AbortController;d.abort=m,u=u.child({testId:l,orgId:a,sessionId:c});let p=o?.type==="API_KEY"?new yt({httpClient:new Ze(o)}):void 0,f={context:d.latestContext,logger:u,localTools:p,signal:m.signal},S=await Vu({inputs:{test:n,orgId:a},fixtures:f,callbacks:{test:{onFinished:()=>{i.emit("apiTestFinished")}},step:{onStarted:w=>{i.emit("apiStepStarted",w)},onFinished:w=>{i.emit("apiStepFinished",w)}}}});t({result:S})},qu={event:"executeApiTest",createHandler:Mw};var Nw=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async()=>{e.info({sessionId:t},"Cancel event received");let n=z.getSession(t);if(!n)throw new Error("No active session found");try{n.controller.setClosed()}catch{}}},Ku={event:"cancel",createHandler:Nw};var _w=({metadata:r,logger:e})=>{let{sessionId:t,type:n}=r;return o=>{e.info({sessionId:t,reason:o},`Disconnect event received (${o})`),n==="e2e"?z.removeSession(t,e):n==="api-test"&&delete or[t]}},Yu={event:"disconnect",createHandler:_w};import{diff as Zw}from"deep-object-diff";async function Ps(r,e,t,n,o,s){try{let[i,a]=await Promise.all([t?o(t):void 0,n?o(n):void 0]);i&&(r&&(r.beforeScreenshot=i),e.beforeScreenshot=i),a&&(r&&(r.afterScreenshot=a),e.afterScreenshot=a)}catch(i){s.debug({err:i},"Error saving screenshot to S3")}}var Os=async r=>{let e=r.presetParams.step,{logger:t,controller:n,context:o}=r.fixtures,{takeScreenshots:s}=r.options,{testMetadata:i}=r.inputs,a=t.child({commandType:e.command.type,stepId:e.id,commandId:e.command.id}),l=r.callbacks.test,c=n.browser.url(),u=new Date,d;if(s)try{d=await n.browser.screenshot({retries:1,clearHighlights:!0})}catch(g){a.debug({err:g},"Failed to take screenshot before step, likely because the page is still loading. This is non-fatal and does not affect the test.")}let m,p,h,f=ps();try{a.debug("Starting preset action");let g=await n.executePresetStep(f,e.command,o,i.advanced.disableAICaching);g.beforeScreenshotOverride&&(d=g.beforeScreenshotOverride),h=g.afterScreenshotOverride;let y=new Date,S=n.browser.url();p={beforeUrl:c,afterUrl:S,startedAt:u,finishedAt:y,viewport:await n.browser.getViewport(),status:g.fail?"FAILED":"SUCCESS"},m={...e,message:g.thoughts??"Successfully executed preset action.",beforeUrl:c,afterUrl:S,finishedAt:y,startedAt:u,status:g.fail?"FAILED":"SUCCESS",data:g.data,results:[p],details:f.details},"assertion"in e.command&&(m.message=g.thoughts||"Assertion passed."),(e.command.type==="AI_EXTRACT"||e.command.type==="JAVASCRIPT")&&e.command.envKey&&o.setVariable(e.command.envKey,m.data)}catch(g){a.error({err:g},`Failed executing preset step ${nr(e.command)}`);let y=n.browser.url(),S=new Date,w=g instanceof Error?g.message:`${g}`;p={beforeUrl:c,afterUrl:y,startedAt:u,finishedAt:S,viewport:await n.browser.getViewport(),status:g instanceof DOMException&&g.name==="AbortError"?"CANCELLED":"FAILED",message:w},m={...e,startedAt:u,finishedAt:S,beforeUrl:c,afterUrl:y,status:g instanceof DOMException&&g.name==="AbortError"?"CANCELLED":"FAILED",message:w,failureReason:g instanceof R?g.reason:void 0,results:[p],details:f.details}}if(s&&!h)try{h=await n.browser.screenshot({retries:1})}catch(g){a.debug({err:g},"Failed to take screenshot after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return r.work.asyncTasks.push(Ps(p,m,d,h,l.onSaveScreenshot,a)),m};function Mt(r){let{result:e,nestedResults:t}=r;if(!r.nestedResults.length)return;let{firstMetadata:n,lastMetadata:o}=kw(t);Dw(e,n,o);let s=[...r.asyncTasks];r.asyncTasks.push((async()=>{try{await Fw(s,e,n,o)}catch(i){r.logger.error({result:r.result,err:i},"Error hoisting scalar result metadata")}})())}function kw(r){let e=r[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertion){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!e.results.length){t=e;break}e=e.results[e.results.length-1];break;default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let n=r[r.length-1],o;for(;;){switch(n.type){case"PRESET_ACTION":{o=n;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!n.results.length){o=n;break}n=n.results[n.results.length-1];break;default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function Dw(r,e,t){e&&(r.beforeUrl=e.beforeUrl),t&&(r.afterUrl=t.afterUrl,r.data=t.data,t.status!=="SUCCESS"&&(r.message=t.message))}async function Fw(r,e,t,n){await Promise.allSettled(r),t&&(e.beforeScreenshot=t.beforeScreenshot),n&&(e.afterScreenshot=n.afterScreenshot)}import Ma from"os";import Uw from"v8";function Xu(r){let e=()=>{try{let t=!1,n=$w(),o=Bw();n.freeMemory<1e6&&(t=!0);let s=Uw.getHeapStatistics(),i=s.used_heap_size,a=s.heap_size_limit;i/a>.9&&(t=!0),t?r.warn({memory:n,cpu:o,heapStats:s},"Critical resource usage metrics detected"):r.debug({memory:n,cpu:o,heapStats:s},"Got machine resource usage metrics")}catch{}};return e(),setInterval(e,15e3)}function $w(){let r=Ma.totalmem(),e=Ma.freemem(),t=r-e;return{totalMemory:r,freeMemory:e,usedMemory:t}}function Bw(){let r=Ma.cpus(),e=0,t=0,n=0,o=0,s=0,i=0;for(let a of r)e+=a.times.user,t+=a.times.nice,n+=a.times.sys,o+=a.times.idle,s+=a.times.irq;return i=e+t+n+o+s,{user:e/i*100,nice:t/i*100,sys:n/i*100,idle:o/i*100,irq:s/i*100,total:100-o/i*100}}var Ju=async r=>{let{step:e,resolvedInputs:t}=r.moduleParams,{logger:n,context:o,storage:s,codeEvalTools:i,controller:a}=r.fixtures,{orgId:l,testMetadata:c}=r.inputs;Object.keys(t).length>0&&(o.setInputs(t),n.debug({inputs:t,moduleId:e.moduleId},"Set module inputs"));let u,d;if(e.cacheConfig){let m=e.cacheConfig.cacheKey||e.defaultCacheKey||"",p=await St({orgId:l,s:m,context:o,logger:n,localTools:i,signal:a.executeAbortController.signal}),h={orgId:l,cacheKeys:[p,...Object.entries(t).map(([g,y])=>`${g}:${y}`)]};n.debug({cacheKey:m,keyParams:h},"Module cache key params");let f=Date.now();for(;Date.now()-f<Nd;){let g=await s.getCacheResult(h);if(g){n.info({cacheResult:g},"Got result from module execution cache"),u=Ls(e,t,"SUCCESS"),u.message="Used cached module result.",u.data=JSON.parse(g);break}let y=await s.acquireCacheLock({keyParams:h,clientMetadata:`testId:${c.id}`},a.executeAbortController.signal);if(y.acquired){d=y.keyPrefix,n.info({cacheKeyPrefix:d,cacheKey:m,keyParams:h},"Acquired cache lock and proceeding with module execution");break}await q(2500+Math.random()*1e4,a.executeAbortController.signal)}}try{u||(u=await zw(r))}finally{if(d!==void 0){let m=e.cacheConfig.cacheExpiryMs;if(m===vd&&(m=e.defaultCacheTtl??Ad),u&&u.status==="SUCCESS"){let p=JSON.stringify(u.data===void 0?"":u.data);n.debug({cacheKeyPrefix:d,ttlMs:m,cacheResult:p},"Setting module cache result"),await s.setCacheResult({result:p,keyPrefix:d,ttlMs:m})}await s.releaseCacheLock(d)}}return u},zw=async r=>{let{step:e}=r.moduleParams,t=Ls(e,r.moduleParams.resolvedInputs,"SUCCESS"),{status:n,results:o}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:`module ('${e.name}')`}});return t.results=o,t.status=n,t.finishedAt=new Date,Mt({asyncTasks:r.work.asyncTasks,nestedResults:o,result:t,logger:r.fixtures.logger}),t};function Ls(r,e,t){let n={};return Object.entries(e).forEach(([s,i])=>{n[s]=JSON.stringify(i)}),{type:"MODULE",id:r.id,moduleId:r.moduleId,moduleName:r.name,startedAt:new Date,cacheConfig:r.cacheConfig,inputs:n,results:[],finishedAt:new Date,status:t}}async function Ms({orgId:r,step:e,context:t,logger:n,codeEvalTools:o,signal:s}){let i={};try{for(let a of e.parameters??[]){let l=e.inputs?.[a]??e.defaultParameters?.[a];if(!l){n.warn(`No value or default found for parameter '${a}' that is required by module '${e.name}'`);continue}i[a]=await jt({orgId:r,code:l,fragment:!0,context:t,logger:n,localTools:o,signal:s})}return i}catch(a){throw s?.throwIfAborted(),new R("UserConfigurationError",`Failed to evaluate module inputs: ${a}`)}}async function sr(r,e,t){let n=new Date;try{return t.throwIfAborted(),await e()}catch(o){let s=new Date,i="FAILED",a;if(t.aborted||o instanceof DOMException&&o.name==="AbortError"?(a="Step aborted by user.",i="CANCELLED"):o instanceof R?a=`${o}`:a=`An unexpected error occurred: ${o.message}`,r.type==="RESOLVED_MODULE"){let l=Ls(r,{},"FAILED");return l.message=a,l.startedAt=n,l.finishedAt=s,l}return{...r,startedAt:n,finishedAt:s,status:i,data:null,message:a,results:[]}}}async function Ns(r,e){let t=!1;try{return r&&!r.healingDisabled&&(r.healingDisabled=!0,t=!0),await e()}finally{r&&t&&(r.healingDisabled=void 0)}}import{randomUUID as Ww}from"crypto";var Na=async r=>{let e=await jw(r);return e.finishedAt=new Date,Mt({asyncTasks:r.work.asyncTasks,result:e,nestedResults:e.results,logger:r.fixtures.logger}),e},jw=async r=>{let e=r.aiStepParams.step,t=e.index,{testMetadata:n,steps:o}=r.inputs,{takeScreenshots:s}=r.options,{controller:i,context:a,logger:l}=r.fixtures,{test:c,step:u}=r.callbacks;if(t===void 0)throw new Error("Attempted to execute AI action step without index");i.resetHistory();let d={...e,startedAt:new Date,beforeTestContext:a.toRedactedDisplayCopy(),finishedAt:new Date,results:[],status:"SUCCESS"};"steps"in e&&e.steps===void 0&&(e.steps=[]);let m="steps"in e&&!!e.steps&&e.steps.length>0&&e.steps[e.steps.length-1]?.command.type==="SUCCESS";if(e.type==="AI_ACTION"&&m)try{let{status:f,results:g}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"AI action"}});return d.finishedAt=new Date,d.status=f,d.results=g,d}catch(f){l.warn({err:f},"Failed executing saved AI action steps, attempting to re-generate...")}"steps"in e&&(e.steps=[]);let p=(await i.browser.screenshot({clearHighlights:!0})).toString("base64"),h=0;for(;;){if(h>12)return d.message=`Exceeded max number of commands per step (${12})`,d.status="FAILED",d;if(i.executeAbortController.signal.aborted)return d.message="Test execution was cancelled",d.status="CANCELLED",d;let f=t+h+1;e.type==="AI_ACTION_DYNAMIC"&&u.onDynamicAIActionThinkingEvent?.({parentStepId:e.id});let g,y;if(s)try{y=await i.browser.screenshot({clearHighlights:!0})}catch(I){l.debug({err:I},"Failed to take screenshot before AI command, likely because the page is still loading. This is non-fatal.")}l.info(`Generating new sub-command ${h} within AI step`);let S;try{S=await i.promptToCommand(e.text,p,n.advanced.disableAICaching);let I=S.command.type;if(I==="FAILURE")return d.status="FAILED",d.message=S.command.thoughts,d;if(I==="SUCCESS")return d.status="SUCCESS",d.message=S.command.thoughts,d;g=S.command,l.debug({command:g},"Generated new command")}catch(I){throw i.throwIfClosed(),l.error({err:I,commandIndex:h},"Failed to generate command within AI step"),I}let w={id:Ww(),type:"PRESET_ACTION",index:f,command:g},T={index:f,message:S.command.thoughts||"Generated new command."};e.type==="AI_ACTION_DYNAMIC"&&u.onDynamicAIActionDescribingEvent?.({parentStepId:e.id}),await Gw({newStep:w,controller:i,currentStep:e,pageContext:S?.context,logger:l,currentIndex:h}),e.type==="AI_ACTION"?u.onCommandGenerated?.({...T,step:w,parentStepId:e.id}):e.type==="AI_ACTION_DYNAMIC"&&u.onDynamicCommandGenerated?.({...T,step:w,parentStepId:e.id}),l.info({commandId:g.id},`Executing sub-command ${h} within AI step: ${nr(g)}`),u.onStarted?.(w.id,f);let C=await Vw({step:w,controller:i,context:a,beforeScreenshotBuff:y,onSaveScreenshot:c.onSaveScreenshot,work:r.work,logger:l,useSavedCommands:m,disableCaching:n.advanced.disableAICaching,takeScreenshots:s});"steps"in e&&(e.steps[h]=w),bs(o),d.results.push(C);let A={index:f,output:{...C,message:g.thoughts??C.message??"Successfully executed preset action."},step:w,parentStepId:e.id};switch(e.type==="AI_ACTION"?u.onCommandExecuted?.(A):e.type==="AI_ACTION_DYNAMIC"&&u.onDynamicCommandStarted?.(A),C.status){case"SUCCESS":u.onSuccess?.({index:f,output:tr.parse(C),step:C,message:C.command.thoughts||C.message});break;case"FAILED":return u.onFailure?.({index:f,output:tr.parse(C),step:C,message:C.message}),d.status="FAILED",d.message=C.command.thoughts||C.message,d;case"CANCELLED":return u.onCancelled?.({index:f,output:tr.parse(C),step:C,message:C.message}),d.status="CANCELLED",d.message=C.command.thoughts||C.message,d}if(C.status!=="SUCCESS")break;h++}return d};async function Hw(r,e,t){let n=t.id;if(!n||t.id<=0)throw new Error("Attempted to get reverse mapping for command with no a11y id target");return r.getReverseMappedTarget(e,n,!0)}async function Gw({controller:r,currentIndex:e,currentStep:t,newStep:n,pageContext:o,logger:s}){if(!o)return;let i=n.command;if("target"in i&&i.target&&"cache"in i&&i.cache)try{let a=await Hw(r,o,i.cache.target);i.target={elementDescriptor:a,type:"description"},"steps"in t&&(t.steps[e]=n)}catch(a){s.warn({err:a,currentIndex:e,currentStep:t},"Failed to generate element description, continuing...")}}async function Vw({step:r,controller:e,context:t,logger:n,beforeScreenshotBuff:o,onSaveScreenshot:s,work:i,takeScreenshots:a,useSavedCommands:l,disableCaching:c}){let u=new Date,d={beforeUrl:e.browser.url(),viewport:await e.browser.getViewport(),startedAt:u,finishedAt:new Date,status:"SUCCESS"},m=t.toRedactedDisplayCopy(),p={...r,beforeUrl:d.beforeUrl,beforeTestContext:m,startedAt:d.startedAt,results:[d],message:r.command.thoughts,finishedAt:d.finishedAt,status:"FAILED"};try{let f=await e.executeCommand(r.command,t,l&&c,l);d.elementInteracted=f.elementInteracted,d.status="SUCCESS",p.data=f.data,p.status="SUCCESS"}catch(f){let g=e.executeAbortController.signal.aborted,y=f instanceof Error?f.message:`${f}`;d.status=g?"CANCELLED":"FAILED",d.message=y,p.message=y,p.failureReason=f instanceof R?f.reason:void 0,p.status=g?"CANCELLED":"FAILED"}let h;if(a)try{h=await e.browser.screenshot({})}catch(f){n.debug({err:f},"Failed to take screenshot after AI command, likely because the page is still loading. This is non-fatal.")}return d.afterUrl=e.browser.url(),d.finishedAt=new Date,p.afterUrl=d.afterUrl,p.finishedAt=d.finishedAt,p.afterTestContext=t.toRedactedDisplayCopy(),i.asyncTasks.push(Ps(d,p,o,h,s,n)),p}async function Qu(r){let{step:e}=r.conditionalParams,{logger:t,controller:n}=r.fixtures,o=new Date,s=e.elseSteps,i=!0,a=[],l,c=ps();for(let p=0;p<e.blocks.length;p++){t.info(`Evaluating condition ${p} in conditional step`);let h=e.blocks[p];try{let f=await Os({...r,presetParams:{step:h.assertion}});a.push(f),t.info(`Condition ${p} resolved to true, executing the corresponding ${h.steps.length} steps`),i=!1,s=h.steps,l=f}catch(f){t.info({err:f},`Condition ${p} resolved to false`)}finally{n.throwIfClosed()}}if(s)i&&t.info("No conditions resolved to true, executing the else block steps");else return t.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped"),{...e,status:"SUCCESS",startedAt:o,data:a[a.length-1]?.data,message:a[a.length-1]?.message,results:[],finishedAt:new Date,details:c.details};t.info(`Executing ${s.length} steps in the selected conditional block`);let u=await r.executeStepList({...r,listParams:{steps:s,containerName:"conditional block"}}),m={...e,assertion:l,...u,startedAt:o,finishedAt:new Date};return Mt({asyncTasks:r.work.asyncTasks,nestedResults:[...a,...u.results],result:m,logger:t}),m}async function em(r){let{step:e}=r.frameParams,{logger:t,controller:n}=r.fixtures,o=new Date,s=n.browser.getActiveFrame();n.browser.setActiveFrame(e.identifier);let i;try{i=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"frame step list"}})}finally{n.browser.setActiveFrame(s)}let l={...e,...i,startedAt:o,finishedAt:new Date};return Mt({asyncTasks:r.work.asyncTasks,nestedResults:i.results,result:l,logger:t}),l}import{randomUUID as _s}from"crypto";import qw from"fast-json-patch";import{cloneDeep as Kw}from"lodash-es";async function tm(r){let e=r.failedResults,t=[],{sectionParams:n,fixtures:o,work:s,startingUrl:i,startingContextSnapshot:a}=r,{step:l}=n,{controller:c}=o,u=l?.autohealingConfig,d=u?.restartBehavior??{type:"GO_TO_SECTION_START"},m=u?.attempts??1;for(let p=0;p<m;p++){if(!e.terminalResult?.message)throw new Error("No error message in terminal result");let h=Kw(l.steps);await Promise.allSettled(s.asyncTasks??[]);let f=await c.runSectionAutohealing({results:e.results,errorMessage:e.terminalResult?.message,goal:l.description});for(let S of f.patches)h=qw.applyOperation(h,S).newDocument;let g=Ve.fromSnapshot({snapshot:a,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await Yw({controller:c,context:g,restartConfig:d,startingUrl:i});let y=await Ns(r.work,()=>r.executeStepList({...r,fixtures:{...r.fixtures,context:g},listParams:{steps:h,containerName:"auto-healed step list"}}));if(t.push(y.results),y.status==="SUCCESS")return{successfulHealing:{proposedStep:{...l,steps:h},listResult:y,context:g},healingAttempts:t};e=y}return{healingAttempts:t}}async function Yw({controller:r,restartConfig:e,context:t,startingUrl:n}){switch(e.type){case"NAVIGATE_URL":{let o={id:_s(),type:"PRESET_ACTION",command:{id:_s(),type:"NAVIGATE",url:e.url}};await r.executePresetStep(null,o.command,t,!1);break}case"GO_TO_SECTION_START":{let o={id:_s(),type:"PRESET_ACTION",command:{id:_s(),type:"NAVIGATE",url:n}};await r.executePresetStep(null,o.command,t,!1);break}}}function rm(r,e){switch(r||(r="ON_FAILURE"),r){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&uc(e.command.type))}}async function nm(r){let{step:e}=r.sectionParams,{logger:t,controller:n,context:o}=r.fixtures,s=new Date,i=n.browser.url(),a=o.toObjectCopy(),l=async()=>r.executeStepList({...r,listParams:{steps:e.steps,containerName:"section step list"}}),c=e.autohealingConfig?await Ns(r.work,l):await l(),u,d;if(c.status==="FAILED"&&e.autohealingConfig&&!r.work.healingDisabled&&rm(e.autohealingConfig.trigger,c.terminalResult)){let p=await tm({...r,startingContextSnapshot:a,startingUrl:i,failedResults:c});p.successfulHealing&&(u=p.successfulHealing.proposedStep,c=p.successfulHealing.listResult,r.fixtures.context=p.successfulHealing.context),d=p.healingAttempts}let m={...e,...c,startedAt:s,finishedAt:new Date,proposedStep:u,healingAttempts:d};return Mt({asyncTasks:r.work.asyncTasks,nestedResults:c.results,result:m,logger:t}),m}async function ir(r){let{results:e=[],containerName:t,steps:n}=r.listParams,{logger:o,context:s,controller:i,codeEvalTools:a}=r.fixtures,{step:l}=r.callbacks,{orgId:c,fromIndex:u,toStepId:d}=r.inputs,m=r.work,p=[],h="SUCCESS",f,g=0;for(g;g<n.length;g++){let y=n[g],S,w=to(y),T=y.index;if(T===void 0)throw new Error(`Executing step without index: ${w}`);if(y.skipped)continue;if(u&&T<u&&(y.type==="PRESET_ACTION"||au([y])<u))continue;o.info({step:y},`Executing step ${g+1}/${n.length} in ${t}: ${w}`),l.onStarted?.(y.id,T);let C=s.toRedactedDisplayCopy(),A=i.browser.url(),I=i.executeAbortController.signal,O,x;switch(y.type){case"PRESET_ACTION":{O="Preset action",x=await sr(y,()=>Os({...r,presetParams:{step:y}}),I);break}case"AI_ACTION":{O="AI action",x=await sr(y,()=>Na({...r,aiStepParams:{step:y},executeStepList:ir}),I);break}case"AI_ACTION_DYNAMIC":{O="Dynamic AI action",x=await sr(y,()=>Na({...r,aiStepParams:{step:y},executeStepList:ir}),I);break}case"RESOLVED_MODULE":{O=`Module (${y.name})`;let H=s.getResultsCopy();x=await sr(y,async()=>{let P=await Ms({orgId:c,step:y,context:s,logger:o,codeEvalTools:a,signal:I});return Ju({...r,executeStepList:ir,moduleParams:{step:y,resolvedInputs:P}})},I),s.setResults(H);break}case"CONDITIONAL":{O="Conditional step",x=await sr(y,()=>Qu({...r,conditionalParams:{step:y},executeStepList:ir}),I);break}case"IFRAME":{O="Frame step",x=await sr(y,()=>em({...r,frameParams:{step:y},executeStepList:ir}),I);break}case"SECTION":{O="Section";let H=await sr(y,()=>nm({...r,sectionParams:{step:y},executeStepList:ir}),I);"proposedStep"in H&&H.proposedStep&&(S=H.proposedStep,H.proposedStep=void 0,m&&(m.autoHealed=!0)),x=H;break}default:return(P=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(y)}S?p.push(S):p.push(y),x.beforeUrl=x.beforeUrl??A,x.beforeTestContext=C,s.setResult(g,x.data),y.envKey&&s.setVariable(y.envKey,x.data);let j=i.browser.url();if(s.setCurrentUrl(j),x.afterUrl=x.afterUrl??j,x.afterTestContext=s.toRedactedDisplayCopy(),e.push(x),Xw(O,T,x,r.callbacks,o,r.work),x.status!=="SUCCESS"||i.closed){h=x.status,f=x;break}else if(y.id===d){i.setClosed();break}}return{status:h,results:e,terminalResult:f,proposedSteps:p}}function Xw(r,e,t,n,o,s){let{step:i,test:a}=n,l=r.toLowerCase(),c=r.charAt(0).toUpperCase()+r.slice(1);switch(t.status){case"SUCCESS":i.onSuccess?.({index:e,step:t,message:t.message??`${c} executed successfully.`,output:tr.parse(t)});break;case"FAILED":i.onFailure?.({index:e,step:t,message:t.message??`${c} failed.`,output:tr.parse(t)});break;case"CANCELLED":i.onCancelled?.({index:e,step:t,message:t.message??`${c} cancelled.`,output:tr.parse(t)});break;default:throw new Error(`Unexpected ${l} status: ${t.status}`)}t.status==="SUCCESS"&&s&&a.onUpdateRun?.({results:s.results})}import{randomUUID as om}from"crypto";async function sm(r){let e=new Date;try{return await r.navigate({url:r.baseUrl,initialNavigation:!0}),{status:"PASSED",results:[]}}catch(t){let n={id:om(),type:"PRESET_ACTION",status:t.name==="AbortError"?"CANCELLED":"FAILED",failureReason:"UserConfigurationError",message:t.message,startedAt:e,finishedAt:new Date,results:[],command:{id:om(),type:"NAVIGATE",url:r.baseUrl}};return{status:t.name==="AbortError"?"CANCELLED":"FAILED",results:[],failedStepResult:n}}}var ks=async r=>{r.fixtures.logger=r.fixtures.logger.child({orgId:r.inputs.orgId,runId:r.inputs.runId,testId:r.inputs.testMetadata.id});let{logger:e,controller:t}=r.fixtures,{onTestComplete:n,onTestSuccess:o}=r.callbacks.test;if(r.options.reinitializeBrowser){let a=await sm(t.browser);if(t.executeAbortController.signal.aborted)return a.status="CANCELLED",await n?.(),a;if(a.status==="FAILED")return await n?.(),a}let s;s=Xu(e),bs(r.inputs.steps);let i;try{return i=await Jw(r),i}finally{if(clearInterval(s),iu(r.inputs.steps),await n?.(),i?.status==="PASSED")try{await o?.(r.inputs.steps)}catch(a){e.warn({err:a},"Error running test success handler, continuing...")}}},Jw=async r=>{let{runId:e,testMetadata:t,fromIndices:n,toIndices:o,indicesFilter:s,steps:i,orgId:a}=r.inputs,{logger:l,controller:c,context:u,codeEvalTools:d}=r.fixtures;u.setCurrentUrl(c.browser.url()),l.info(`Starting run ${e} for test '${t.name}'`);let m=i,p="test",h;if(n){let{step:C,parent:A}=Ts(i,n);if(!C)throw new Error(`Could not find starting step using indices: ${n}`);A&&A.type==="RESOLVED_MODULE"&&(h=A),r.inputs.fromIndex=C.index,l.debug({fromIndices:n,fromStep:C,filteredParentModule:h},"Identified starting step using fromIndices"),p="partial steps list"}if(o){let{step:C}=Ts(i,o);if(!C)throw new Error(`Could not find step at indices: ${o}`);r.inputs.toStepId=C.id,l.debug({toIndices:o,toStep:C},"Identified ending step using toIndices"),p="partial steps list"}if(s){let{step:C,parent:A}=Ts(i,s);if(!C)throw new Error(`Could not find ending step at indices: ${r.inputs.indicesFilter}`);A&&A.type==="RESOLVED_MODULE"&&(h=A),m=[C],p="filtered step"}if(h){let C=await Ms({orgId:a,step:h,context:u,logger:l,codeEvalTools:d,signal:c.executeAbortController.signal});u.setInputs(C)}l.debug({stepsToRun:m,indicesFilter:s},"Executing steps");let f=[],g={results:f,healingDisabled:!!s||!!n||!!o||void 0,asyncTasks:[]},{status:y,terminalResult:S,proposedSteps:w}=await ir({...r,work:g,listParams:{steps:m,containerName:p,results:f}});r.options.takeScreenshots&&await Promise.allSettled(g.asyncTasks);let T;if(r.options.consumeDebuggingData){T={logsPerPage:su(c.browser.retrieveAndClearConsoleLogs())};try{let A=await c.browser.html();l.debug({finalPageHtml:A},"Final page state HTML")}catch{}}return r.callbacks.test.onUpdateRun?.({results:f,debugData:T}),y==="FAILED"?{status:"FAILED",results:f,failedStepResult:S}:(w&&g.autoHealed&&await r.callbacks.test.onProposedTestSteps?.({testId:t.id,orgId:r.inputs.orgId,runId:r.inputs.runId,steps:w}),{status:"PASSED",results:f})};import{cloneDeep as Qw}from"lodash-es";var _a={currentlyExecutingRequests:{}},eb=r=>async(e,t)=>{let n,{testId:o}=r.metadata,{baseUrl:s}=e,i=`${o}|${s}`;try{let a=_a.currentlyExecutingRequests[i]??0;_a.currentlyExecutingRequests[i]=a+1,n=await tb({...r,...e,done:t})}finally{r.logger.info({result:n,sessionId:r.metadata.sessionId},"Test execution complete"),_a.currentlyExecutingRequests[i]--}},tb=async({socket:r,steps:e,baseUrl:t,testMetadata:n,reInitialize:o,indicesFilter:s,toIndices:i,fromIndices:a,storage:l,metadata:c,logger:u,envName:d,environmentVariables:m,testInputs:p,authorization:h,done:f})=>{let{testId:g,sessionId:y,orgId:S}=c,w=y,T=z.getSession(y);if(!T)throw new Error("No active session found");let{controller:C,context:A}=T;C.setOpen();let I=h?.type==="API_KEY"?new yt({httpClient:new Ze(h)}):void 0;u=u.child({testId:g,orgId:S,baseUrl:t,sessionId:y,runId:w}),u.info({indicesFilter:s,fromIndices:a,toIndices:i,reInitialize:o,envName:d,baseUrl:t,context:A,flags:C.flagStore.getAllFlags()},"Starting execution");let O=m??{};await Promise.all((n.parameters??[]).map(async L=>{let Fe=(p??{})[L.name]??L.defaultValue;if(Fe===void 0)return;let Ut=await St({orgId:S,s:Fe,context:Ve.dummyContext(d),logger:u,localTools:I});O[L.name]=Ut}));let x=async()=>{if(o){let L={url:t,clearCookies:!0,clearStorage:!0};await C.resetState(L),A.reset({baseUrl:t,currentUrl:C.browser.url(),variablesFromEnvironment:O,envName:d})}},j=async()=>{try{await l.resolveStepCacheEntries({schemaVersion:n.schemaVersion,organizationId:S,testId:g,steps:e,logger:u})}catch(L){u.error({err:L},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};try{await Lt(Promise.all([x(),j()]),C.executeAbortController.signal),C.setOpen()}catch(L){if(r.emit("finished"),L.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${L}`)}let H=Qw(e),pr=await ks({fixtures:{controller:C,context:A,storage:l,codeEvalTools:I,logger:u},options:{takeScreenshots:!1,consumeDebuggingData:!1,reinitializeBrowser:!1},callbacks:{test:{onTestComplete:async()=>{r.emit("finished")},onSaveScreenshot:rb,onTestSuccess:async L=>{let Fe=Zw(H,L);if(Object.keys(Fe).length>0){u.debug({changes:Fe},"Updating steps post-run success");let{cachesToSave:Ut}=await gt({steps:e,cacheCreationParams:{testId:g,orgId:S}});try{await l.saveStepCacheEntries(Ut,n.id,u)}catch(Ur){u.warn({err:Ur},"Failed to save step cache entries after execution success")}}else u.debug("No changes detected in steps post-run success")}},step:{onStarted:(L,Fe)=>r.emit("started",{stepId:L,globalIndex:Fe}),onSuccess:L=>{r.emit("success",L)},onFailure:L=>{r.emit("failure",L)},onCancelled:L=>{r.emit("cancelled",L)},onCommandGenerated:L=>{r.emit("commandGenerated",L)},onCommandExecuted:L=>{r.emit("commandExecuted",L)},onDynamicAIActionThinkingEvent:L=>{r.emit("dynamicCommandThinking",L)},onDynamicAIActionDescribingEvent:L=>{r.emit("dynamicCommandDescribing",L)},onDynamicCommandGenerated:L=>{r.emit("dynamicCommandGenerated",L)},onDynamicCommandStarted:L=>{r.emit("dynamicCommandStarted",L)}}},inputs:{orgId:S,runId:w,testMetadata:n,steps:e,indicesFilter:s,fromIndices:a,toIndices:i}});return f?.(pr),pr.status},rb=async r=>r.toString("base64");var im={event:"execute",createHandler:eb};var nb=({metadata:r,logger:e,storage:t})=>{let{sessionId:n}=r;return async(o,s)=>{let{command:i,testMetadata:a,returnScreenshot:l}=o,c=Zn(i,o.description);e.debug({description:c,params:o},"Locate handler params"),e.info({description:c},"Locate handler called");let u=z.getSession(n);if(!u)throw new Error("No active session found");let{controller:d,context:m}=u;d.setOpen();let p=qr.parse(a.advanced??{}),h={},f;if(c){if("useSelector"in i&&i.useSelector)try{let g=await d.locateElementWithSelector(c,"iframeUrl"in i?i.iframeUrl:void 0);f=g.resolution.locator,h={target:g.target,thoughts:g.thoughts}}catch(g){e.warn({err:g},"Failed resolving target with selector"),s({err:`Failed locating element with CSS selector: ${g.message}`,decisions:g instanceof rr?g.decisions:void 0});return}else try{let g=await d.locateElement({description:c,disableCache:p.disableAICaching,iframeUrl:"iframeUrl"in i?i.iframeUrl:void 0,testContext:m,returnConflicts:!0});h={target:g.target,thoughts:g.thoughts},f=g.resolution.locator}catch(g){let y;try{y=await d.browser.html()}catch{}e.warn({err:g,html:y},"Failed locating element with AI"),s({err:`Failed locating element with AI: ${g.message}`});return}if(i.type==="SELECT_OPTION"&&f)try{h.options=await d.browser.getSelectOptions(f)}catch(g){e.warn({err:g},"Failed getting select options"),s({err:`Failed getting select options: ${g.message}`});return}e.info({result:h},"Locate handler result")}if(l)try{let{buffer:g,width:y,height:S}=await d.screenshotWithDimensions({clearHighlights:!0,target:h?.target,hideCaret:!0}),w=await t.uploadScreenshot(g);h.screenshot={data:w,width:y,height:S}}catch(g){e.error({err:g},"Error capturing screenshot during locate"),s({err:`Error taking screenshot: ${g.message}`});return}if(s({result:h}),f)try{await Promise.all([d.browser.scrollIntoView(f),d.browser.highlightTarget(f)])}catch(g){e.warn({err:g},"Error highlighting element, continuing...")}}},am={event:"locate",createHandler:nb};var ob=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async({percentX:n,percentY:o},s)=>{let i=z.getSession(t);if(!i)throw new Error("No active session found");let a=i.controller.browser;try{await a.clickMouseFromPositionPercentages(n,o)}catch(l){e.error({err:l},"Error performing click during cloud recording in control mode"),s({err:l.message})}}},lm={event:"cloudClick",createHandler:ob};var sb=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async(n,o)=>{let s=z.getSession(t);if(!s)throw new Error("No active session found");let{controller:i}=s;i.setOpen(),s.browserBehavior.showOverlay=!0;try{let a=await i.browser.captureTargetFromClick();o({result:a})}catch(a){e.error({err:a},"Record click failed"),o({err:a instanceof Error?a.message:`${a}`})}finally{s.browserBehavior.showOverlay=!1}}},cm={event:"recordTargetClick",createHandler:sb};var ib=({metadata:r,logger:e})=>{let{sessionId:t}=r,n,o=0,s=(a,l)=>{let c=async()=>{n=void 0;try{await a.highlightFromPositionPercentages(l),o=0}catch(u){e.error({err:u},"Error highlighting element on mouse move"),o++}};clearTimeout(n),n=setTimeout(c,50*(o+1))},i=0;return async a=>{let l=z.getSession(t);if(!l)throw new Error("No active session found");let{controller:c,browserBehavior:u}=l,d=c.browser;if(!d.closed){if(d.getActivePage().isClosed()){e.warn("Ignoring mouse move because the page is closed");return}u.showOverlay&&s(d,a);try{await d.moveMouseFromPositionPercentages(a.percentX,a.percentY),i=0}catch(m){i++,i%5===0&&e.warn({err:m,mouseErrors:i},"Error in socket mouse move handler")}}}},dm={event:"cloudMouseMove",createHandler:ib};var ab=({metadata:r})=>{let{sessionId:e}=r;return async({percentDeltaX:t,percentDeltaY:n})=>{let o=z.getSession(e);if(!o)throw new Error("No active session found");let s=o.controller.browser;if(s.closed)return;let i=await s.scrollFromPositionPercentages(t,n);if(!i)return;let a=o.browserBehavior.recordingState?.transformer;a&&a.recordScroll({...i,url:s.url()})}},um={event:"cloudScroll",createHandler:ab};var lb=({metadata:r,generator:e,socket:t,storage:n,logger:o})=>{let{sessionId:s,orgId:i,testId:a}=r;return async({indices:l})=>{let c=z.getSession(s);if(!c)throw new Error("No active session found");let{controller:u,browserBehavior:d}=c;o.info("Starting cloud recording");let m=await u.startRecordMode({generator:e,initialIndices:l,storage:n,logger:o,testId:a,orgId:i,onStepRecord:(p,h)=>{t.emit("stepRecorded",{step:p,indices:h})}});d.recordingState={transformer:m},d.showOverlay=!0}},mm={event:"cloudStartRecording",createHandler:lb};var cb=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async()=>{let n=z.getSession(t);if(!n)throw new Error("No active session found");e.info("Stopping cloud recording"),await n.controller.stopRecordMode(),n.browserBehavior.recordingState=void 0,n.browserBehavior.showOverlay=!1}},pm={event:"cloudStopRecording",createHandler:cb};var db=["Dead","Meta","AudioVolumeUp","AudioVolumeDown"],ub=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async({key:n})=>{let o=z.getSession(t);if(!o)throw new Error("No active session found");if(db.includes(n))return;let{controller:s}=o;if(s.browser.closed||s.browser.getActivePage().isClosed()){e.debug({sessionId:t},"Browser is closed, ignoring typing action");return}try{n.length>1?await s.browser.press(n):await s.browser.type(n,{clearContent:!1,pressKeysSequentially:!0})}catch(i){if(i.message.includes("has been closed")){e.debug({sessionId:t,err:i},"Browser is closed, ignoring typing action error");return}throw i}}},hm={event:"cloudType",createHandler:ub};var so={vimiumJs:'var K=Object.defineProperty;var P=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var F=(t,e,n)=>e in t?K(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,D=(t,e)=>{for(var n in e||(e={}))z.call(e,n)&&F(t,n,e[n]);if(P)for(var n of P(e))B.call(e,n)&&F(t,n,e[n]);return t};var g=(t,e,n)=>(F(t,typeof e!="symbol"?e+"":e,n),n);var _=(t,e,n)=>new Promise((o,r)=>{var i=s=>{try{d(n.next(s))}catch(l){r(l)}},a=s=>{try{d(n.throw(s))}catch(l){r(l)}},d=s=>s.done?o(s.value):Promise.resolve(s.value).then(i,a);d((n=n.apply(t,e)).next())});var E=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=E);var k={create(t,e,n,o){return{bottom:o,top:e,left:t,right:n,width:n-t,height:o-e}},copy(t){return{bottom:t.bottom,top:t.top,left:t.left,right:t.right,width:t.width,height:t.height}},translate(t,e,n){return e==null&&(e=0),n==null&&(n=0),{bottom:t.bottom+n,top:t.top+n,left:t.left+e,right:t.right+e,width:t.width,height:t.height}},subtract(t,e){return e=this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom)),e.width<0||e.height<0?[k.copy(t)]:[this.create(t.left,t.top,e.left,e.top),this.create(e.left,t.top,e.right,e.top),this.create(e.right,t.top,t.right,e.top),this.create(t.left,e.top,e.left,e.bottom),this.create(e.right,e.top,t.right,e.bottom),this.create(t.left,e.bottom,e.left,t.bottom),this.create(e.left,e.bottom,e.right,t.bottom),this.create(e.right,e.bottom,t.right,t.bottom)].filter(o=>o.height>0&&o.width>0)},intersects(t,e){return t.right>e.left&&t.left<e.right&&t.bottom>e.top&&t.top<e.bottom},intersectsStrict(t,e){return t.right>=e.left&&t.left<=e.right&&t.bottom>=e.top&&t.top<=e.bottom},equals(t,e){for(let n of["top","bottom","left","right","width","height"])if(t[n]!==e[n])return!1;return!0},intersect(t,e){return this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom))}};var N={_browserInfoLoaded:!0,_firefoxVersion:null,_isFirefox:!1,isFirefox(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._isFirefox},firefoxVersion(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._firefoxVersion},isString(t){return typeof t=="string"||t instanceof String}};var f={isReady(){return document.readyState!=="loading"},documentReady:function(){let t=document.readyState!=="loading",e=[];if(!t){let n;globalThis.addEventListener("DOMContentLoaded",n=E(function(){globalThis.removeEventListener("DOMContentLoaded",n,!0),t=!0;for(let o of e)o();e=null}),!0)}return function(n){if(t)return n();e.push(n)}}(),documentComplete:function(){let t=document.readyState==="complete",e=[];if(!t){let n;globalThis.addEventListener("load",n=E(function(o){if(o.target===document){globalThis.removeEventListener("load",n,!0),t=!0;for(let r of e)r();e=null}}),!0)}return function(n){t?n():e.push(n)}}(),createElement(t){let e=document.createElement(t);return e instanceof HTMLElement?(this.createElement=n=>document.createElement(n),e):(this.createElement=n=>document.createElementNS("http://www.w3.org/1999/xhtml",n),this.createElement(t))},addElementsToPage(t,e){let n=this.createElement("div");e.id!=null&&(n.id=e.id),e.className!=null&&(n.className=e.className);for(let o of t)n.appendChild(o);return document.body.appendChild(n),n},removeElement(t){return t.parentNode.removeChild(t)},isTopFrame(){return globalThis.top===globalThis.self},makeXPath(t){let e=[];for(let n of t)e.push(".//"+n,".//xhtml:"+n);return e.join(" | ")},evaluateXPath(t,e){let n=document.webkitIsFullScreen?document.webkitFullscreenElement:document.documentElement,o=function(r){return r==="xhtml"?"http://www.w3.org/1999/xhtml":null};return document.evaluate(t,n,o,e,null)},getVisibleClientRect(t,e){let n;e==null&&(e=!1);let o=(()=>{let i=[];for(n of t.getClientRects())i.push(k.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),a=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>a,a};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let a of Array.from(t.children)){i=window.getComputedStyle(a,null);let d=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(d)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(a,!0);if(!(s===null||s.width<3||s.height<3))return s}else{if(n=this.cropRectToVisible(n),n===null||n.width<3||n.height<3||(i=window.getComputedStyle(t,null),i.getPropertyValue("visibility")!=="visible"))continue;return n}}return null},cropRectToVisible(t){let e=k.create(Math.max(t.left,0),Math.max(t.top,0),t.right,t.bottom);return e.top>=window.innerHeight-4||e.left>=window.innerWidth-4?null:e},getClientRectsForAreas(t,e){let n=[];for(let o of e){let r,i,a,d,s=o.coords.split(",").map(p=>parseInt(p,10)),l=o.shape.toLowerCase();if(["rect","rectangle"].includes(l))s.length==4&&([r,a,i,d]=s);else if(["circle","circ"].includes(l)){if(s.length==3){let[p,w,v]=s,u=v/Math.sqrt(2);r=p-u,i=p+u,a=w-u,d=w+u}}else l==="default"?s.length==2&&([r,a,i,d]=[0,0,t.width,t.height]):s.length>=4&&([r,a,i,d]=s);let c=k.translate(k.create(r,a,i,d),t.left,t.top);c=this.cropRectToVisible(c),c&&!isNaN(c.top)&&!isNaN(c.left)&&!isNaN(c.width)&&!isNaN(c.height)&&n.push({element:o,rect:c})}return n},isSelectable(t){if(!(t instanceof Element))return!1;let e=["button","checkbox","color","file","hidden","image","radio","reset","submit"];return t.nodeName.toLowerCase()==="input"&&e.indexOf(t.type)===-1||t.nodeName.toLowerCase()==="textarea"||t.isContentEditable},isEditable(t){return this.isSelectable(t)||(t.nodeName!=null?t.nodeName.toLowerCase():void 0)==="select"},isEmbed(t){let e=t.nodeName!=null?t.nodeName.toLowerCase():null;return["embed","object"].includes(e)},isFocusable(t){return t&&(this.isEditable(t)||this.isEmbed(t))},isDOMDescendant(t,e){let n=e;for(;n!==null;){if(n===t)return!0;n=n.parentNode}return!1},isSelected(t){let e=document.getSelection();if(t.isContentEditable){let n=e.anchorNode;return n&&this.isDOMDescendant(t,n)}else if(f.getSelectionType(e)==="Range"&&e.isCollapsed){let n=e.anchorNode.childNodes[e.anchorOffset];return t===n}else return!1},simulateSelect(t){if(t===document.activeElement&&f.isEditable(document.activeElement))return handlerStack.bubbleEvent("click",{target:t});if(t.focus(),t.tagName.toLowerCase()!=="textarea"||t.value.indexOf(`\n`)<0)try{if(t.selectionStart===0&&t.selectionEnd===0)return t.setSelectionRange(t.value.length,t.value.length)}catch(e){}},simulateClick(t,e){e==null&&(e={});let n=["mouseover","mousedown","mouseup","click"],o=[];for(let r of n){let i=this.simulateMouseEvent(r,t,e);o.push(i)}return o},simulateMouseEvent(t,e,n){if(n==null&&(n={}),t==="mouseout"){if(e==null&&(e=this.lastHoveredElement),this.lastHoveredElement=void 0,e==null)return}else t==="mouseover"&&(this.simulateMouseEvent("mouseout",void 0,n),this.lastHoveredElement=e);let o=new MouseEvent(t,{bubbles:!0,cancelable:!0,composed:!0,view:window,detail:1,ctrlKey:n.ctrlKey,altKey:n.altKey,shiftKey:n.shiftKey,metaKey:n.metaKey});return e.dispatchEvent(o)},simulateClickDefaultAction(t,e){let n;if(e==null&&(e={}),(t.tagName!=null?t.tagName.toLowerCase():void 0)!=="a"||!t.href)return;let{ctrlKey:o,shiftKey:r,metaKey:i,altKey:a}=e;KeyboardUtils.platform==="Mac"?n=i===!0&&o===!1:n=i===!1&&o===!0,n?chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:r===!0}):r===!0&&i===!1&&o===!1&&a===!1?chrome.runtime.sendMessage({handler:"openUrlInNewWindow",url:t.href}):t.target==="_blank"&&chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:!0})},simulateHover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseover",t,e)},simulateUnhover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseout",t,e)},addFlashRect(t){let e=this.createElement("div");return e.classList.add("vimiumReset"),e.classList.add("vimiumFlash"),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.width=t.width+"px",e.style.height=t.height+"px",document.documentElement.appendChild(e),e},getViewportTopLeft(){let t=document.documentElement,e=getComputedStyle(t),n=t.getBoundingClientRect();if(e.position==="static"&&!/content|paint|strict/.test(e.contain||"")){let o=parseInt(e.marginTop),r=parseInt(e.marginLeft);return{top:-n.top+o,left:-n.left+r}}else{let o,r;return N.isFirefox()?(r=parseInt(e.borderTopWidth),o=parseInt(e.borderLeftWidth)):{clientTop:r,clientLeft:o}=t,{top:-n.top-r,left:-n.left-o}}},suppressPropagation(t){t.stopImmediatePropagation()},suppressEvent(t){t.preventDefault(),this.suppressPropagation(t)},consumeKeyup:function(){let t=null;return function(e,n=null,o){if(!e.repeat){t!=null&&handlerStack.remove(t);let{code:r}=e;t=handlerStack.push({_name:"dom_utils/consumeKeyup",keyup(i){return i.code!==r||(this.remove(),o?f.suppressPropagation(i):f.suppressEvent(i)),handlerStack.continueBubbling},blur(i){return i.target===window&&this.remove(),handlerStack.continueBubbling}})}return typeof n=="function"&&n(),o?(f.suppressPropagation(e),handlerStack.suppressPropagation):(f.suppressEvent(e),handlerStack.suppressEvent)}}(),getSelectionType(t){return t==null&&(t=document.getSelection()),t.type?t.type:t.rangeCount===0?"None":t.isCollapsed?"Caret":"Range"},getElementWithFocus(t,e){let n,o=n=t.getRangeAt(0);f.getSelectionType(t)==="Range"&&(o=n.cloneRange(),o.collapse(e)),n=o.startContainer,n.nodeType===1&&(n=n.childNodes[o.startOffset]);let r=n;for(;r&&r.nodeType!==1;)r=r.previousSibling;return n=r||(n!=null?n.parentNode:void 0),n},getSelectionFocusElement(){let t=window.getSelection(),e=t.focusNode;return e==null?null:(e===t.anchorNode&&t.focusOffset===t.anchorOffset&&(e=e.childNodes[t.focusOffset]||e),e.nodeType!==Node.ELEMENT_NODE?e.parentElement:e)},getContainingElement(t){return(typeof t.getDestinationInsertionPoints=="function"?t.getDestinationInsertionPoints()[0]:void 0)||t.parentElement},windowIsTooSmall(){return window.innerWidth<3||window.innerHeight<3},injectUserCss(){let t=document.createElement("style");t.type="text/css",t.textContent=Settings.get("userDefinedLinkHintCss"),document.head.appendChild(t)}};var O={MAX_CONTENT_LENGTH:1e3,MAX_ATTRIBUTE_LENGTH:500,MAX_NUM_DATA_ATTRIBUTES:10,commonAttributes:["id","className","title","aria-label","aria-labelledby"],attributeNamesMapping:new Map([["a",["href","title","rel","target"]],["label",["for"]],["input",["type","name","placeholder","checked","maximumLength"]],["textarea",["placeholder","maximumLength"]],["button",["type"]],["select",["name","multiple"]],["div",["role"]],["iframe",["src"]],["img",["src","alt"]]]),describe(t){var r,i;let e={};this.addAttributes(t,this.commonAttributes,e);let n=((i=(r=t.tagName).toLowerCase)==null?void 0:i.call(r))||"";this.attributeNamesMapping.has(n)&&this.addAttributes(t,this.attributeNamesMapping.get(n),e),this.addDataAttrs(t,e);let o=this.getContent(t);return this.additionalHandling(t,D({tag:n,attributes:e},o&&{content:o}))},getContent(t){var n,o;let e=((o=(n=t.tagName).toLowerCase)==null?void 0:o.call(n))||"";return["input","textarea"].includes(e)?t.value:["div","iframe","img","body"].includes(e)?null:(["a","button","select","label"].includes(e),t.innerText)},additionalHandling(t,e){var o,r;if((((r=(o=t.tagName).toLowerCase)==null?void 0:r.call(o))||"")=="label"&&t.hasAttribute("for")){let i=t.getAttribute("for"),a=document.getElementById(i);a&&(e.target=this.describe(a))}return e},addAttributes(t,e,n){n||(n={});for(let o of e)t.hasAttribute(o)&&(n[o]=t.getAttribute(o).substring(0,this.MAX_ATTRIBUTE_LENGTH));return n},addDataAttrs(t,e){let n=0;for(let o in t.dataset)if(e[`data-${o}`]=t.dataset[o].substring(0,this.MAX_ATTRIBUTE_LENGTH),n++,n>this.MAX_NUM_DATA_ATTRIBUTES)return e;return e}};var x=null,C=()=>G()||document.scrollingElement||document.body,W=function(t){return t?t<0?-1:1:0},U={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},X=function(t,e,n){if(N.isString(n)){let o=n;return o==="viewSize"&&t===C()?e==="x"?window.innerWidth:window.innerHeight:t[U[e][o]]}else return n},V=function(t,e,n){let o=U[e].axisName,r=t[o];if(t.scrollBy){let i={behavior:"instant"};i[e==="x"?"left":"top"]=n,t.scrollBy(i)}else t[o]+=n;return t[o]!==r},q=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},T=function(t,e,n,o){let r=o*X(t,e,n)||-1;return r=W(r),V(t,e,r)&&V(t,e,-r)},$=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),T(t,e,n,o)&&q(t,e)},j=function(t=null){let e;if(!t){let n=C();if(T(n,"y",1,1)||T(n,"y",-1,1))return n;t=document.body||C()}if(T(t,"y",1,1)||T(t,"y",-1,1))return t;{let n=Array.from(t.children).map(o=>({element:o,rect:f.getVisibleClientRect(o)})).filter(o=>o.rect);n.map(o=>o.area=o.rect.width*o.rect.height);for(e of n.sort((o,r)=>r.area-o.area)){let o=j(e.element);if(o)return o}return null}},L={init(){x=null},isScrollableElement(t){return x||(x=C()&&j()||C()),t!==x&&$(t)}},G=function(){let t=J[window.location.host];if(t)return document.querySelector(t)},J={"twitter.com":"div.permalink-container div.permalink[role=main]","reddit.com":"#overlayScrollContainer","new.reddit.com":"#overlayScrollContainer","www.reddit.com":"#overlayScrollContainer","web.telegram.org":".MessageList"};window.Scroller=L;var A=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",E(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",E(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:A});var R=class{constructor(e){g(this,"element");g(this,"image");g(this,"rect");g(this,"linkText");g(this,"showLinkText");g(this,"reason");g(this,"secondClassCitizen");g(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},M={getLocalHintsForElement(t){var p,w,v;let e=((w=(p=t.tagName).toLowerCase)==null?void 0:w.call(p))||"",n=!1,o=!1,r=!1,i=[],a=[],d=null;if(e==="img"){let u=t.getAttribute("usemap");if(u){let h=t.getClientRects();u=u.replace(/^#/,"").replace(\'"\',\'\\\\"\');let m=document.querySelector(`map[name="${u}"]`);if(m&&h.length>0){n=!0;let y=m.getElementsByTagName("area"),S=f.getClientRectsForAreas(h[0],y);S=S.map(I=>Object.assign(I,{image:t})),a.push(...S)}}}let s=t.getAttribute("aria-disabled");if(s&&["","true"].includes(s.toLowerCase()))return[];if(this.checkForAngularJs||(this.checkForAngularJs=function(){if(document.getElementsByClassName("ng-scope").length===0)return()=>!1;{let h=[];for(let m of["","data-","x-"])for(let y of["-",":","_"])h.push(`${m}ng${y}click`);return function(m){for(let y of h)if(m.hasAttribute(y))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let u=t.getAttribute("role"),h=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(u!=null&&h.includes(u.toLowerCase()))n=!0;else{let m=t.getAttribute("contentEditable");m!=null&&["","contenteditable","true","plaintext-only"].includes(m.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let u=t.getAttribute("jsaction").split(";");for(let h of u){let m=h.trim().split(":");if(m.length>=1&&m.length<=2){let[y,S,I]=m.length===1?["click",...m[0].trim().split("."),"_"]:[m[0],...m[1].trim().split("."),"_"];n||(n=y==="click"&&S!=="none"&&I!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||(n=!t.disabled&&!t.readOnly);break;case"input":n||(n=!(((v=t.getAttribute("type"))==null?void 0:v.toLowerCase())=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t)));break;case"button":case"select":n||(n=!t.disabled);break;case"object":case"embed":n=!0;break;case"label":n||(n=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0);break;case"body":n||(n=t===document.body&&!A()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?d="Frame.":void 0),n||(n=t===document.body&&A()&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"img":n||(n=["zoom-in","zoom-out"].includes(t.style.cursor));break;case"div":case"ol":case"ul":n||(n=t.clientHeight<t.scrollHeight&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"details":n=!0,d="Open.";break}let l=t.getAttribute("class");!n&&(l!=null&&l.toLowerCase().includes("button"))&&(n=!0,r=!0);let c=t.getAttribute("tabindex"),b=c?parseInt(c):-1;if(!n&&!(b<0)&&!isNaN(b)&&(n=!0,o=!0),n)if(a.length>0){let u=a.map(h=>new R({element:h.element,image:t,rect:h.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:d}));i.push(...u)}else{let u=f.getVisibleClientRect(t,!0);if(u!==null){let h=new R({element:t,rect:u,secondClassCitizen:o,possibleFalsePositive:r,reason:d});i.push(h)}}return i},getElementFromPoint(t,e,n,o){n==null&&(n=document),o==null&&(o=[]);let r=n.elementsFromPoint?n.elementsFromPoint(t,e)[0]:n.elementFromPoint(t,e);return o.includes(r)?r:(o.push(r),r&&r.shadowRoot?M.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,l)=>{l==null&&(l=[]);for(let c of Array.from(s.querySelectorAll("*")))l.push(c),c.shadowRoot&&e(c.shadowRoot,l);return l},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let l=this.getLocalHintsForElement(s);o.push(...l)}o=o.reverse();let r=[1,2,3];o=o.filter((s,l)=>{if(!s.possibleFalsePositive)return!0;let b=Math.max(0,l-6);for(;b<l;){let p=o[b].element;for(let w of r)if(p=p==null?void 0:p.parentElement,p===s.element)return!1;b+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let l=s.rect,c=M.getElementFromPoint(l.left+l.width*.5,l.top+l.height*.5);if(c&&(s.element.contains(c)||c.contains(s.element))||s.element.localName=="area"&&c==s.image)return!0;let p=[l.top+.1,l.bottom-.1],w=[l.left+.1,l.right-.1];for(let v of p)for(let u of w){let h=M.getElementFromPoint(u,v);if(h&&(s.element.contains(h)||h.contains(s.element)))return!0}});i.reverse();let{top:a,left:d}=f.getViewportTopLeft();for(let s of i)s.rect.top+=a,s.rect.left+=d;return i}};var H=class{constructor(){this.hints=null;this.hintMarkers=null;this.markersDiv=null;this.enrichedMarkers=null}reset(){this.removeMarkers(),this.hints=null,this.hintMarkers=null,this.markersDiv=null}capture(){return _(this,null,function*(){this.reset(),this.createMarkers(),this.displayMarkers()})}createMarkers(){this.hints=M.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{var i,a;let o=f.createElement("div"),r=(a=(i=e.element.attributes["data-momentic-id"])==null?void 0:i.value)!=null?a:void 0;if(!r){console.warn(`[MOMENTIC] No data-momentic-id found for interactive element ${e.element.outerHTML}`);return}o.style.left=e.rect.left+"px",o.style.top=e.rect.top+"px",o.style.zIndex=214e7+n,o.className="vimiumReset internalVimiumHintMarker vimiumHintMarker",Z(o,r),this.hintMarkers.set(r,{hint:e,marker:o})})}enrichMarkers(){if(this.hintMarkers){this.enrichedMarkers=[];for(let[e,n]of this.hintMarkers)this.enrichedMarkers.push(Object.assign(O.describe(n.hint.element),{hintString:e}))}}displayMarkers(){this.hintMarkers&&(this.markersDiv||(this.markersDiv=f.addElementsToPage(Array.from(this.hintMarkers.values()).map(e=>e.marker),{id:"vimiumHintMarkerContainer",className:"vimiumReset"})))}removeMarkers(){this.markersDiv&&(f.removeElement(this.markersDiv),this.markersDiv=null)}toggleMarkers(){this.markersDiv?this.removeMarkers():this.displayMarkers()}},Z=(t,e)=>{for(let n of e){let o=document.createElement("span");o.className="vimiumReset",o.textContent=n,t.appendChild(o)}};window.HintManager=H;\n',vimiumCss:'.vimiumReset,a.vimiumReset,a:hover.vimiumReset,a:link.vimiumReset,a:visited.vimiumReset,div.vimiumReset,span.vimiumReset,table.vimiumReset,td.vimiumReset,tr.vimiumReset{background:none;border:none;bottom:auto;box-shadow:none;color:#000;cursor:auto;display:inline;float:none;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:inherit;font-style:normal;font-variant:normal;font-weight:400;height:auto;left:auto;letter-spacing:0;line-height:100%;margin:0;max-height:none;max-width:none;min-height:0;min-width:0;opacity:1;padding:0;position:static;right:auto;text-align:left;text-decoration:none;text-indent:0;text-shadow:none;text-transform:none;top:auto;vertical-align:baseline;white-space:normal;width:auto;z-index:2140000000}tbody.vimiumReset,thead.vimiumReset{display:table-header-group}tbody.vimiumReset{display:table-row-group}div.internalVimiumHintMarker{background:linear-gradient(180deg,#fff785 0,#ffc542);border:1px solid #c38a22;border-radius:3px;box-shadow:0 3px 7px 0 rgba(0,0,0,.3);display:block;font-size:11px;left:-1px;overflow:hidden;padding:1px 3px 0;position:absolute;top:-1px;white-space:nowrap}div.internalVimiumHintMarker span{color:#302505;font-family:Helvetica,Arial,sans-serif;font-size:11px;font-weight:700;text-shadow:0 1px 0 hsla(0,0%,100%,.6)}div.internalVimiumHintMarker>.matchingCharacter{color:#d4ac3a}div>.vimiumActiveHintMarker span{color:#a07555!important}div.internalVimiumInputHint{background-color:rgba(255,247,133,.3);border:1px solid #c38a22;display:block;pointer-events:none;position:absolute}div.internalVimiumSelectedInputHint{background-color:hsla(0,100%,70%,.3);border:1px solid #933!important}div.internalVimiumSelectedInputHint span{color:#fff!important}div.vimiumHighlightedFrame{border:5px solid #ff0;box-sizing:border-box;margin:0;pointer-events:none}div.vimiumHighlightedFrame,iframe.vimiumHelpDialogFrame{height:100%;left:0;padding:0;position:fixed;top:0;width:100%}iframe.vimiumHelpDialogFrame{background-color:hsla(0,0%,4%,.6);border:none;display:block;z-index:2139999997}div#vimiumHelpDialogContainer{background-color:#fff;border:2px solid #b3b3b3;border-radius:6px;margin:50px auto;max-height:calc(100% - 100px);max-width:calc(100% - 100px);opacity:1;overflow-x:auto;overflow-y:auto;width:840px}div#vimiumHelpDialog{min-width:600px;padding:8px 12px}span#vimiumTitle,span#vimiumTitle *,span#vimiumTitle span{font-size:20px}#vimiumTitle{display:block;line-height:130%;white-space:nowrap}td.vimiumHelpDialogTopButtons{text-align:right;width:100%}#helpDialogOptionsPage,#helpDialogWikiPage{font-size:14px;padding-left:5px;padding-right:5px}div.vimiumColumn{float:left;font-size:11px;line-height:130%;width:50%}div.vimiumColumn tr{display:table-row}div.vimiumColumn td{display:table-cell;font-size:11px;line-height:130%}div.vimiumColumn table,div.vimiumColumn td,div.vimiumColumn tr{margin:0;padding:0}div.vimiumColumn table{table-layout:auto;width:100%}div.vimiumColumn td{padding:1px;vertical-align:top}div#vimiumHelpDialog div.vimiumColumn tr>td:first-of-type{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;text-align:right;white-space:nowrap}span.vimiumHelpDialogKey{background-color:#f3f3f3;border:1px solid;border-color:#ccc #ccc #bbb;border-radius:3px;box-shadow:inset 0 -1px 0 #bbb;color:#212121;font-family:monospace;font-size:11px;margin-left:2px;padding:1px 4px}div#vimiumHelpDialog div.vimiumColumn tr>td:nth-of-type(3){width:100%}div#vimiumHelpDialog div.vimiumDivider{background-color:#9a9a9a;display:block;height:1px;margin:10px auto;width:100%}div#vimiumHelpDialog td.vimiumHelpSectionTitle{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:16px;font-weight:700;padding-top:3px}div#vimiumHelpDialog td.vimiumHelpDescription{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px}div#vimiumHelpDialog span.vimiumCopyCommandNameName{cursor:pointer;font-size:12px;font-style:italic}div#vimiumHelpDialog tr.advanced{display:none}div#vimiumHelpDialog.showAdvanced tr.advanced{display:table-row}div#vimiumHelpDialog div.advanced td:nth-of-type(3){color:#555}div#vimiumHelpDialog a.closeButton{color:#555;cursor:pointer;font-family:courier new;font-size:24px;font-weight:700;padding-left:5px;position:relative;text-decoration:none;top:3px}div#vimiumHelpDialog a{text-decoration:underline}div#vimiumHelpDialog a.closeButton:hover{color:#000;-webkit-user-select:none}div#vimiumHelpDialogFooter{display:block;margin-bottom:37px;position:relative}table.helpDialogBottom{width:100%}td.helpDialogBottomRight{float:right;text-align:right;width:100%}td.helpDialogBottomLeft,td.helpDialogBottomRight{padding:0}div#vimiumHelpDialogFooter *{font-size:10px}a#toggleAdvancedCommands,span#help-dialog-tip{font-size:10px;position:relative;top:19px;white-space:nowrap}a#toggleAdvancedCommands,a:active.vimiumHelDialogLink,a:hover.vimiumHelDialogLink,a:link.vimiumHelDialogLink,a:visited.vimiumHelDialogLink{color:#2f508e;cursor:pointer;text-decoration:underline}div.vimiumHUD{background:#f1f1f1;border:1px solid #aaa;border-radius:4px;bottom:8px;box-shadow:0 2px 10px rgba(0,0,0,.8);display:block;left:8px;position:fixed;text-align:left;width:calc(100% - 20px);z-index:2139999999}iframe.vimiumHUDFrame{background-color:transparent;border:none;bottom:-14px;display:block;height:58px;margin:0 0 0 -40%;min-width:300px;opacity:0;overflow:hidden;padding:0;position:fixed;right:20px;width:20%;z-index:2139999998}div.vimiumHUD .vimiumHUDSearchArea{background-color:#f1f1f1;border-radius:4px 4px 0 0;display:block;padding:3px}div.vimiumHUD .vimiumHUDSearchAreaInner{border-radius:3px;box-sizing:border-box;color:#777;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;height:30px;line-height:20px;margin-bottom:0;outline:none;padding:2px 4px;width:100%}div.vimiumHUD .hud-find{background:#fff;border:1px solid #ccc}div.vimiumHUD span#hud-find-input,div.vimiumHUD span#hud-match-count{color:#000;display:inline;outline:none;overflow-y:hidden;white-space:nowrap}div.vimiumHUD span#hud-find-input:before{content:"/"}div.vimiumHUD span#hud-match-count{color:#aaa;font-size:12px}div.vimiumHUD span#hud-find-input br{display:none}div.vimiumHUD span#hud-find-input *{display:inline;white-space:nowrap}body.vimiumFindMode ::selection{background:#ff9632}iframe.vomnibarFrame{background-color:transparent;border:none;display:block;font-family:sans-serif;height:calc(100% - 70px);left:50%;margin:0 0 0 -40%;min-width:400px;overflow:hidden;padding:0;position:fixed;top:70px;width:calc(80% + 20px);z-index:2139999998}div.vimiumFlash{background-color:transparent;box-shadow:0 0 4px 2px #4183c4;padding:1px;position:absolute;z-index:2140000000}iframe.vimiumUIComponentHidden{display:none}iframe.vimiumUIComponentVisible{color-scheme:light dark;display:block}iframe.vimiumUIComponentReactivated{border:5px solid #ff0}iframe.vimiumNonClickable{pointer-events:none}@media (prefers-color-scheme:dark){iframe.reverseDarkReaderFilter{-webkit-filter:invert(100%) hue-rotate(180deg)!important;filter:invert(100%) hue-rotate(180deg)!important}body.vimiumBody{background-color:#292a2d;color:#fff}body.vimiumBody a,body.vimiumBody a:visited{color:#8ab4f8}body.vimiumBody input,body.vimiumBody textarea{background-color:#1d1d1f;border-color:#1d1d1f;color:#e8eaed}body.vimiumBody div.example{color:#9aa0a6}body.vimiumBody div#footer,body.vimiumBody div#state,div#vimiumHelpDialogContainer{background-color:#202124;border-color:hsla(0,0%,100%,.1)}div#vimiumHelpDialog{background-color:#292a2d;color:#fff}div#vimiumHelpDialog td.vimiumHelpDescription{color:#c9cccf}div#vimiumHelpDialog td.vimiumHelpSectionTitle,span#vimiumTitle{color:#fff}#vimiumTitle>span:first-child{color:#8ab4f8!important}div#vimiumHelpDialog a{color:#8ab4f8}div#vimiumHelpDialog div.vimiumDivider{background-color:hsla(0,0%,100%,.1)}span.vimiumHelpDialogKey{background-color:#1d1d1f;border:1px solid #000;box-shadow:none;color:#fff}}',htmlUtilsLibJs:`var __defProp = Object.defineProperty;
|
|
13
|
+
${JSON.stringify(t)}`);let n=[];if(!r.skipIntermediateEntries)for(let o=e.length;o>0;o--){let s=t[o-1],i=e.slice(o,e.length).join(":");n.push({key:ru(r.id,i),moduleId:s,organizationId:r.orgId,value:r.value})}return n.push({key:ru(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function ou(r){switch(r.type){case"DRAG":{if(r.fromTarget.type==="coordinates"||r.toTarget.type==="coordinates"||!r.fromTarget?.a11yData||!r.toTarget?.a11yData)return;r.cache={fromTarget:r.fromTarget.a11yData,toTarget:r.toTarget.a11yData},delete r.fromTarget.a11yData,delete r.toTarget.a11yData;return}case"MOUSE_DRAG":case"HOVER":case"SCROLL_UP":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SELECT_OPTION":case"TYPE":case"VISUAL_DIFF":case"CLICK":case"FOCUS":case"BLUR":{if(r.target?.type==="coordinates"||!r.target?.a11yData)return;r.cache={target:r.target.a11yData},delete r.target.a11yData;return}default:return}}function ze(r,e,t=!1){return r.length<e?r:r.slice(0,e-3)+(t?"...TRUNCATED...":"[...]")}var vr={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with"},Ar={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with"},Ra={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable"},Ia={EXISTS:"does not exists",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable"};function JS(r){switch(r.type){case"ELEMENT_CONTENT":return`${r.negated?Ar[r.operation]:vr[r.operation]} '${r.value}'`;case"ELEMENT_ATTRIBUTE":{let t=r.negated?Ar[r.operation]:vr[r.operation];return`attribute '${r.attr}' ${t} '${r.value}'`}case"ELEMENT_EXISTENCE":return r.negated?Ia[r.condition]:Ra[r.condition];default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var O_={CONTENT:"The page"};function ZS(r){switch(r.type){case"VALUE":return`the option with value ${r.value}`;case"LABEL":return`the option with label ${r.label}`;case"INDEX":return`the option at index ${r.index}`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function QS(r){switch(r.type){case"CONTENT":return`${r.negated?Ar.CONTAINS:vr.CONTAINS} '${r.value}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function nr(r){switch(r.type){case"SUCCESS":return r.condition?.assertion?`Check success condition: ${r.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${r.goal}`;case"NAVIGATE":return`Go to URL: ${ze(r.url,30)}`;case"DIALOG":return`Automatically ${r.action.toLowerCase()} the next dialog`;case"CAPTCHA":return"Solve captchas on the page";case"GO_BACK":return"Go back to the previous page";case"GO_FORWARD":return"Go forward to the next page";case"SCROLL_DOWN":return`Scroll down ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${Pe(r.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${Pe(r.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${Pe(r.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${Pe(r.target)}`:""}`;case"WAIT":return`Wait for ${r.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(r.target?.type==="coordinates")return`Click at coordinates: ${Pe(r.target)}`;let n="";return r.target?.elementDescriptor.length?n=` on element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` on element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Click${n}`}case"FOCUS":return`Focus ${Pe(r.target)}`;case"BLUR":return`Focus ${Pe(r.target)}`;case"DRAG":return`Drag ${Pe(r.fromTarget)} onto ${Pe(r.toTarget)}`;case"MOUSE_DRAG":return r.target?`Click and drag ${Pe(r.target)} by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`:`Click and drag mouse by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`;case"TYPE":{let n="";return r.target?.type==="coordinates"?n=` in element at coordinates: ${Pe(r.target)}`:r.target?.elementDescriptor.length?n=` in element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` in element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Type '${r.value}'${n||""}`}case"HOVER":{let n="";return r.target.type==="coordinates"?n=` over coordinates: ${Pe(r.target)}`:r.target.elementDescriptor.length>0?n=` over element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` over element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Hover${n}`}case"PRESS":return`Press ${r.value}`;case"SELECT_OPTION":{let n="",o=r.option??ZS(r.choice);return r.target.type==="coordinates"?n=` from element at coordinates: ${Pe(r.target)}`:r.target.elementDescriptor.length>0?n=` from: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(n=` from: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${o}'${n}`}case"TAB":if(r.url)return`Switch to tab with substring: ${r.url}`;if(r.action)switch(r.action.type){case"SUBSTRING":return`Switch to tab with substring: ${r.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${r.action.pattern}`;case"INDEX":return`Switch to tab at index: ${r.action.index}`;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${r.url}`;case"REQUEST":return`Send ${r.method} request to ${r.url}`;case"COOKIE":return`Set cookie: ${r.value}`;case"LOCAL_STORAGE":return`Set local storage: ${r.key}: ${r.value}`;case"JAVASCRIPT":return`Run JavaScript: ${ze(r.code,30)}`;case"AI_ASSERTION":return`Assertion: '${r.assertion}'`;case"AI_WAIT":return`Wait until assertion is true: '${r.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${r.target?`for element: ${Pe(r.target)}`:"for entire page"}`;case"FILE_UPLOAD":return`Upload file: ${r.fileSource.url}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Assert the element ${Pe(r.target)} ${JS(r.assertion)}`;case"PAGE_CHECK":return`Assert the page ${QS(r.assertion)}`;case"WAIT_FOR_URL":return`Wait for the page URL to match: ${r.url}`;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function su(r){let e=[];for(let t of r){t.sort((i,a)=>i.timestamp-a.timestamp);let n=[],o,s=1;for(let i of t)o&&o.text===i.text&&o.type===i.type&&JSON.stringify(o.args??null)===JSON.stringify(i.args??null)?s++:(o&&(s>1?o.args&&o.args.length?o.args.push(`(repeated ${s} times)`):o.text+=` (repeated ${s} times)`:n.push(o)),o=i,s=1);o&&n.push(o),e.push(n)}return e}function Wt(r){let{onPresetAction:e,onSimpleStepContainer:t,onConditional:n}=r;for(let o of r.steps)switch(o.type){case"PRESET_ACTION":e(o);break;case"CONDITIONAL":n?.(o);for(let i of o.blocks)e(i.assertion),Wt({...r,steps:i.steps});Wt({...r,steps:o.elseSteps??[]});break;case"RESOLVED_MODULE":case"IFRAME":case"SECTION":case"AI_ACTION":t?.(o),o.steps&&Wt({...r,steps:o.steps});break;case"AI_ACTION_DYNAMIC":{t?.(o);break}default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(o)}}function bs(r){let e=0;Wt({steps:r,onPresetAction:t=>{t.index=e++},onConditional:t=>{t.index=e++},onSimpleStepContainer:t=>{t.index=e++}})}function iu(r){Wt({steps:r,onPresetAction:e=>{delete e.index},onConditional:e=>{delete e.index},onSimpleStepContainer:e=>{delete e.index}})}var ew=(r,e)=>{switch(r.type){case"RESOLVED_MODULE":return r.steps[e];case"AI_ACTION":return r.steps[e];case"CONDITIONAL":{let n=r.blocks.map(o=>[o.assertion,...o.steps]).flat();return r.elseSteps&&(n=n.concat(r.elseSteps)),n[e]}case"SECTION":case"IFRAME":return r.steps[e];case"PRESET_ACTION":default:throw new Error(`Cannot get a child step from step type ${r.type}`)}};function Ts(r,e){let t=r[e[0]],n;for(let o=1;o<e.length;o++)n=t,t=ew(t,e[o]);return{step:t,parent:n}}function au(r){let e=0;return Wt({steps:r,onPresetAction:t=>{e=Math.max(e,t.index)},onConditional:t=>{e=Math.max(e,t.index)},onSimpleStepContainer:t=>{e=Math.max(e,t.index)}}),e}import{cloneDeep as q_,unset as K_}from"lodash-es";function to(r){switch(r.type){case"AI_ACTION":return`AI action: ${ze(r.text,100)}`;case"AI_ACTION_DYNAMIC":return`Dynamic AI action: ${ze(r.text,100)}`;case"PRESET_ACTION":return nr(r.command);case"MODULE":return`Module: ${r.id}`;case"RESOLVED_MODULE":return`Module: ${r.name}`;case"CONDITIONAL":return"Conditional step";case"IFRAME":return"Frame step";case"SECTION":return`Section${r.description?`with goal: ${ze(r.description,100)}`:""}`;default:return(t=>{throw new Error("You missed a case in the switch above")})(r)}}function Es(r,e){for(let t=0;t<r.length;t++){let n=r[t];try{if(n.data){let{jsonString:o}=Yn(JSON.stringify(n.data),1e3);n.data=JSON.parse(o)}}catch(o){e.error({err:o},"Failed to serialize individual result output data"),n.data=`Result output data could not be serialized: ${o}`}switch(n.details&&(n.details=void 0),n.type){case"PRESET_ACTION":lu(n);break;case"CONDITIONAL":n.assertion&&lu(n.assertion),Es(n.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"IFRAME":case"MODULE":case"SECTION":{Es(n.results,e);break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}}function lu(r){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0)}function cu(r,e){if(!(!r.envs||!r.envs.length)){for(let t of r.envs){let n=t;e in t&&(n[e]&&(t.default=!0),delete n.defaultOnCloud,delete n.defaultOnLocal)}r.envs.some(t=>t.default)||(r.envs[0].default=!0)}}import sw from"diff-lines";import vs,{gte as iw}from"semver";var du={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>(r=r.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),r=r.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),r)};var uu={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,n=t[t.length-1];return n&&n.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var tw=["target","fromTarget","toTarget"];function mu(r){for(let e of tw){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var pu={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":return mu(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])mu(n);return e}default:return e}})};import{v4 as rw}from"uuid";var hu={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=rw()),e;default:return e}})};import{v4 as fu}from"uuid";var gu={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??fu(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??fu()}})),delete e.commands),e;default:return e}})};var yu={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return typeof t.type!="string"||t.type!=="AI_WAIT"||(t.type="AI_ASSERTION",t.timeout||(t.timeout=10)),e}default:return e}})};import{v4 as nw}from"uuid";var Su={name:"Add ids to all steps",fromVersion:"1.0.10",toVersion:"1.0.11",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>("id"in e&&typeof e.id=="string"||(e.id=nw()),e))};import{v4 as wu}from"uuid";var bu={name:"Add ids to all steps",fromVersion:"1.0.11",toVersion:"1.0.12",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let t=e.condition;t.id||(t.id=wu())}return e.id=wu(),e})};var Tu={name:"Move env key to steps",fromVersion:"1.0.12",toVersion:"1.0.13",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};import{v4 as ow}from"uuid";var Eu={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=ow()),e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};var Cu={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:t.option},e.option=void 0),e})};var vu={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return t&&Au(t),e})};function Au(r){r&&Object.keys(r).forEach(e=>{if(typeof r[e]=="object"&&r[e]){Au(r[e]);return}if(typeof r[e]!="string")return;let t=r[e];e==="code"?r[e]=t.replace(/inputs\./g,"env."):t.includes("{{")&&t.includes("}}")&&(r[e]=t.replace(/inputs\./g,"env."))})}var xu={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||t.type!=="TAB"||e.url===void 0||(e.action={type:"SUBSTRING",substring:e.url},e.url=void 0),e})};var Ru={name:"Migrate AI assertions to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async r=>r.map(e=>{if(e.type!=="AI_ASSERTION")return e;let n={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...n};return delete o.text,o}),stopOnFailure:!0};var Cs=new Set(["CLICK","TYPE","SELECT_OPTION"]),Iu={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type,o=t?.elementDescriptor;return(o!==void 0||Cs.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let a=i?.elementDescriptor,l=i?.type;(a!==void 0||Cs.has(l))&&(i.target={elementDescriptor:a??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let a=i.command,l=a?.elementDescriptor,c=a?.type;(l!==void 0||Cs.has(c))&&(a.target={elementDescriptor:l??""}),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(d=>{let m=d?.elementDescriptor,p=d?.type;(m!==void 0||Cs.has(p))&&(d.target={elementDescriptor:m??""})})}),e}),stopOnFailure:!0};var Pu={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(n=>{if(n&&typeof n=="object"){let o=n;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var Ou={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type;return n?.startsWith("PRESET_")&&(t.type=n.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(s=>{let i=s.type;i?.startsWith("PRESET_")&&(s.type=i.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(s=>{let i=s.command,a=i?.type;a?.startsWith("PRESET_")&&(i.type=a.slice(7)),s.commands&&Array.isArray(s.commands)&&s.commands.forEach(c=>{let u=c.type;u?.startsWith("PRESET_")&&(c.type=u.slice(7))})}),e}),stopOnFailure:!0};var xr=[Ru,Pu,Ou,Iu,du,uu,pu,hu,gu,yu,Su,bu,Tu,Eu,Cu,vu,xu];if(ct!==xr[xr.length-1].toVersion)throw new Error("Please bump LATEST_VERSION in types package after adding a migration");xr.forEach((r,e)=>{if(!vs.valid(r.toVersion)||!vs.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!vs.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(xr[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});function aw(r){return r.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var Pa=async({metadata:r,steps:e,logger:t,toVersion:n})=>{let o=e,{schemaVersion:s,id:i}=r,a=xr.findIndex(u=>vs.gt(u.toVersion,s));if(a===-1)return{steps:o,newVersion:s};let l=s;for(let u=a;u<xr.length;u++){if(n&&iw(l,n)){t.debug("Stopping migration early because toVersion was reached");break}let d=xr[u],m={id:i,migration:d.name,toVersion:d.toVersion};try{o=await Lu(o,d),l=d.toVersion}catch(p){throw t.error({err:p,...m},"Migration failed"),new Error(`Step migration ${d.name} failed: ${p}`)}}let c=sw(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return c.trim()&&t.debug({diffs:c,id:i},"Migration diffs"),{newVersion:l,steps:o}};async function Lu(r,e){let t=await e.execute(r);for(let n of t)for(let o of Object.keys(n)){if(!e.recursiveKeys.has(o))continue;let s=n[o];!s||!Array.isArray(s)||aw(s)&&(n[o]=await Lu(s,e))}return t}async function Mu({rawSteps:r,metadata:e,logger:t,callbacks:n}){cu(e,"defaultOnCloud");let o={},{resolvedSteps:s,newSchemaVersion:i}=await Oa({rawSteps:r,metadata:e,logger:t,callbacks:n,resolvedModuleCache:o});return{resolvedTest:{...e,steps:s,schemaVersion:i},moduleIds:Array.from(Object.keys(o))}}async function Oa({rawSteps:r,metadata:e,logger:t,callbacks:n,resolvedModuleCache:o={}}){let{newVersion:s,steps:i}=await Pa({metadata:e,steps:r,logger:t}),a;try{a=lt.array().parse(i)}catch(c){throw t.error({type:"zod",err:c,newVersion:s,id:e.id,steps:i},"Failed to parse test steps while migrating test"),new fs(`Failed to parse test steps while migrating test: ${c}`,e.id,"entity",{cause:c})}let l=[];for(let c of a)l.push(await ro({step:c,callbacks:n,logger:t,resolvedModuleCache:o}));return{resolvedSteps:l,newSchemaVersion:s}}async function ro({step:r,callbacks:e,logger:t,resolvedModuleCache:n}){switch(r.type){case"AI_ACTION":return r;case"AI_ACTION_DYNAMIC":return r;case"PRESET_ACTION":return r;case"MODULE":{let l=r.moduleId,c=n[l];if(c)return{...c,...r,type:"RESOLVED_MODULE"};let u=await e.onFetchModule({id:l,logger:t});if(!u)throw new Error(`Could not find module with id ${l}`);let{newVersion:d,steps:m}=await Pa({metadata:{id:l,schemaVersion:u.schemaVersion},steps:u.steps,logger:t}),p;try{p=lt.array().parse(m)}catch(g){throw t.error({type:"zod",err:g,steps:m,newVersion:d,id:l},"Module failed to parse"),g}let h;try{h=await Promise.all(p.map(g=>ro({step:g,callbacks:e,logger:t,resolvedModuleCache:n})))}catch(g){throw t.error({err:g,...r},`Failed to recursively resolve module '${u.name}': ${g}`),g}let f={...u,steps:h};return n[l]=f,{...f,...r,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let l of r.blocks){let c=[];for(let u of l.steps)c.push(await ro({step:u,callbacks:e,logger:t,resolvedModuleCache:n}));o.push({...l,steps:c})}let s;if(r.elseSteps){s=[];for(let l of r.elseSteps)s.push(await ro({step:l,callbacks:e,logger:t,resolvedModuleCache:n}))}return{...r,blocks:o,elseSteps:s};case"SECTION":case"IFRAME":let i=[];for(let l of r.steps)i.push(await ro({step:l,callbacks:e,logger:t,resolvedModuleCache:n}));return{...r,steps:i};default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}import{cloneDeep as lw}from"lodash-es";import{v4 as Nu}from"uuid";async function gt(r){let e=lw(r.steps);return en({...r,steps:e,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:new Map,seenModules:new Set})}async function en({steps:r,...e}){let{seenModules:t,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:s,moduleIdReplacements:i,shouldCreateNewModuleId:a}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let c of r)switch(delete c.index,c.type){case"PRESET_ACTION":{let d=c.command;d.id=n?.createNewCacheIds?Nu():d.id,ou(d),"cache"in d&&d.cache&&(n&&(l.cachesToSave=l.cachesToSave.concat(nu({id:d.id,orgId:n.orgId,testId:n.testId,value:Sr.parse(d),moduleIdParents:o,moduleStepParents:s,skipIntermediateEntries:e.skipCacheIntermediateEntries}))),delete d.cache),l.stepsToSave.push({...c,command:d});break}case"RESOLVED_MODULE":{let d=n?.createNewCacheIds?Nu():c.id,m=c.moduleId;if(i.has(m))m=i.get(m);else if(a){let y=await a(c);i.set(c.moduleId,y)}let{cachesToSave:p,stepsToSave:h,moduleUpdates:f}=await en({...e,steps:c.steps,cacheCreationParams:n?{...n,createNewCacheIds:!1}:void 0,moduleStepParents:[...s,d],moduleIdParents:[...o,m],skipCacheIntermediateEntries:n?.createNewCacheIds});l.moduleUpdates=l.moduleUpdates.concat(f),l.cachesToSave=l.cachesToSave.concat(p),t.has(m)||(t.add(m),l.moduleUpdates.push({...st.parse(c),steps:lt.array().parse(h)}));let g={type:"MODULE",moduleId:m,inputs:c.inputs,id:d,skipped:c.skipped,cacheConfig:c.cacheConfig,envKey:c.envKey};l.stepsToSave.push(g);break}case"AI_ACTION":{if(!c.steps){l.stepsToSave.push(c);break}let{stepsToSave:d,cachesToSave:m}=await en({...e,steps:c.steps});try{c.steps=ot.array().parse(d)}catch(p){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${p}`)}l.stepsToSave.push(c),l.cachesToSave=l.cachesToSave.concat(m);break}case"AI_ACTION_DYNAMIC":{l.stepsToSave.push(c);break}case"CONDITIONAL":{let d=[];for(let p of c.blocks){let{stepsToSave:h,cachesToSave:f,moduleUpdates:g}=await en({...e,steps:p.steps});d.push({...p,steps:h}),l.cachesToSave=l.cachesToSave.concat(f),l.moduleUpdates=l.moduleUpdates.concat(g)}let m={...c,elseSteps:void 0,blocks:d};if(c.elseSteps){let{stepsToSave:p,cachesToSave:h,moduleUpdates:f}=await en({...e,steps:c.elseSteps});m.elseSteps=p,l.cachesToSave=l.cachesToSave.concat(h),l.moduleUpdates=l.moduleUpdates.concat(f)}l.stepsToSave.push(m);break}case"IFRAME":case"SECTION":{let{stepsToSave:d,cachesToSave:m,moduleUpdates:p}=await en({...e,steps:c.steps}),h={...c,steps:d};l.moduleUpdates=l.moduleUpdates.concat(p),l.stepsToSave.push(h),l.cachesToSave=l.cachesToSave.concat(m);break}default:return(d=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(c)}return l}import{cloneDeep as cw}from"lodash-es";import{stringify as _u}from"yaml";async function ku(r,e=new Set){let t={id:r.id,name:r.name,baseUrl:r.baseUrl,schemaVersion:r.schemaVersion,advanced:r.advanced,retries:r.retries,envs:r.envs},n={},o=await dw(r.steps,r.schemaVersion,n,e),s={fileType:ne.TEST,...t,steps:o};return{test:_u(s),modules:n}}async function dw(r,e,t,n){let o=cw(r);uw(o);let{stepsToSave:s,moduleUpdates:i}=await gt({steps:o});for(let a of i)n.has(a.name)||(t[a.name]=mw(a),n.add(a.name));return s}function uw(r){Wt({steps:r,onPresetAction:e=>{e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.index=void 0},onSimpleStepContainer:e=>{e.index=void 0}})}function mw(r){let e=st.parse(r),t={fileType:ne.MODULE,...e,schemaVersion:ct,steps:r.steps};return _u(t)}async function q(r,e){return new Promise((t,n)=>{if(e?.aborted){n(e.reason);return}e?.addEventListener("abort",s);let o=setTimeout(()=>{e?.removeEventListener("abort",s),t()},r);function s(){clearTimeout(o),e?.removeEventListener("abort",s),n(e?.reason)}})}async function Lt(r,e){return new Promise((t,n)=>{if(e?.aborted){n(e?.reason);return}e?.addEventListener("abort",o),Promise.resolve(r).then(t).catch(n).finally(()=>{e?.removeEventListener("abort",o)});function o(){e?.removeEventListener("abort",o),n(e?.reason)}})}var tn=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 setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}async saveStepCacheEntries(e,t,n){try{await this.client.updateStepCaches({entries:e,testId:t})}catch(o){n.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let t=await this.client.getStepCacheForTest({testId:e.testId,organizationId:e.organizationId,steps:e.steps,schemaVersion:e.schemaVersion}),{hits:n}=Qr({steps:e.steps,stepCacheEntries:t,logger:e.logger});this.client.updateCacheLastUsedDate(n,e.logger)}};var no="v1",yt=class{httpClient;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)};constructor(e){this.httpClient=e.httpClient}async sendSms(e){return this.httpClient.sendRequest(`/${no}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Ot?new Error(t.rawError):new Error(`Failed to send sms: ${t.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${no}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ot?new Error(t.rawError):t})}async sendEmail(e){return this.httpClient.sendRequest(`/${no}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(t=>{throw t instanceof Ot?new Error(t.rawError):new Error(`Failed to send email: ${t.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${no}/tools/email/fetchAll`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ot?new Error(t.rawError):new Error(`Failed to fetch all emails: ${t.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${no}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(t=>{throw t instanceof Ot?new Error(t.rawError):new Error(`Failed to fetch latest emails: ${t.message}`)})}};import $h from"body-parser";import VC from"cors";import qC from"events";import Bh,{Router as KC}from"express";import YC from"http";import XC from"open";import{Server as $T}from"socket.io";var pw={showOverlay:!1},La=class{sessions=new Map;sessionCountByIp=new Map;getCurrentConnectionsByIp(e){return this.sessionCountByIp.get(e)??0}getCurrentSessionsByIp(){return Object.fromEntries(this.sessionCountByIp)}reserveCapacityByIp(e){e&&this.sessionCountByIp.set(e,(this.sessionCountByIp.get(e)??0)+1)}releaseCapacityByIp(e){e&&this.sessionCountByIp.set(e,Math.max(this.getCurrentConnectionsByIp(e)-1,0))}registerSession({controller:e,context:t,cleanup:n,clientIp:o,sessionId:s,browserbaseSessionId:i}){return this.sessions.set(s,{controller:e,context:t,cleanup:n,clientIp:o,browserbaseSessionId:i,browserBehavior:pw}),s}removeSession(e,t){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:s}=o;try{s.setClosed(),await s.browser.cleanup()}catch(i){t.error({err:i},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(i){t.error({err:i},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}},z=new La;var hw=200;function Du(r,e,t){let n=Date.now(),o=-1,s=0,i=Date.now(),a,l,c=async(m,p)=>{if(!m.closed){if(s>0&&Math.random()>=1/Math.max(s,8)){s<8&&t.error({sessionId:e},"Dropping screenshot due to previous failures");return}try{let h;(!a||!l||Date.now()-i>=1500)&&(a=await m.getViewport(),l=await m.getAllFrameUrls(),i=Date.now(),h=m.retrieveAndClearConsoleLogs()),r.emit("browserState",{logsPerPage:h,viewport:a,buffer:await m.screenshot({retries:0,timeout:750,scale:"device",quality:75}),url:m.url(),iframeSrcUrls:l,context:p.toEditorDisplayCopy()}),n=Date.now(),s=0}catch(h){if(!r.connected)return;let f=h instanceof Error?h.message:`${h}`;if(f.includes("Frame was detached")||f.includes("Not attached to an active page")||f.includes("browser has been closed"))return;s++,t.error({err:h,sessionId:e},"Error taking screenshot")}finally{r.connected&&Date.now()-n>15e3&&Date.now()-o>3e4&&(t.error({sessionId:e},"Screenshots to client are stale"),o=Date.now())}}},u={timer:void 0},d=()=>{let m=z.getSession(e),p=m?.controller?.browser;if(!p||p.closed){t.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(u.timer);return}c(p,m.context)};return u.timer=setInterval(d,hw),u}var or={};var fw=r=>()=>{let{sessionId:e}=r.metadata;or[e]?.abort?.abort()},Fu={event:"cancelApiTest",createHandler:fw};import{CookieJar as Lw}from"tough-cookie";import{randomUUID as Cw}from"crypto";import{faker as gw}from"@faker-js/faker";import yw from"assert";import Sw from"axios";import ww from"moment";import*as bw from"otpauth";import Tw from"pg";var rn=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Uu=r=>{let e=r.reason===void 0?new DOMException("This operation was aborted.","AbortError"):r.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};async function J(r,e){let{milliseconds:t,fallback:n,message:o,customTimers:s={setTimeout,clearTimeout}}=e,i,a;return new Promise((l,c)=>{if(typeof t!="number"||Math.sign(t)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${t}\``);if(e.signal){let{signal:d}=e;d.aborted&&c(Uu(d)),a=()=>{c(Uu(d))},d.addEventListener("abort",a)}if(t===Number.POSITIVE_INFINITY){r.then(l,c);return}let u=new rn;i=s.setTimeout.call(void 0,()=>{if(n){try{l(n())}catch(d){c(d)}return}"cancel"in r&&typeof r.cancel=="function"&&r.cancel(),o instanceof Error?c(o):(u.message=o??`Promise timed out after ${t} milliseconds`,c(u))},t),(async()=>{try{l(await r)}catch(d){c(d)}})()}).finally(()=>{i!==void 0&&s.clearTimeout.call(void 0,i),a!==void 0&&e.signal&&e.signal.removeEventListener("abort",a)})}var Ew=Object.getPrototypeOf(async function(){}).constructor;async function $u(r,e,t){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{env:o,results:s}=e.bindings,i=e.tools,a={},l=(f,g)=>{o[f]=g,a[f]=g},c;n.includes("Octokit")&&(c=(await import("@octokit/rest")).Octokit);let u;n.includes("createAppAuth")&&(u=(await import("@octokit/auth-app")).createAppAuth);let d=async()=>await Promise.resolve(new Ew("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","env","results","setVariable","sendSms","waitForLatestSms","email","sms",n)(Sw,ww,gw,yw,Tw,c,u,bw,o,s,l,g=>i.sms.send(g),g=>i.sms.fetchLatest(g),i.email,i.sms)),m=!0,p,h;try{p=await J(d(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal}),t.debug(`[${r}] Got execution result: ${JSON.stringify(p)}`),t.debug(`[${r}] Got variable updates: ${JSON.stringify(a)}`)}catch(f){t.error(`[${r}] Error executing code: ${f}`),m=!1,f instanceof rn?h=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:h=f instanceof Error?f.message:`${f}`}return{result:p,variableUpdates:a,success:m,error:h}}async function Bu({code:r,fragment:e,context:t,localTools:n,logger:o,signal:s,timeoutMs:i=Xr}){let a=Cw();return $u(a,{code:r,options:{fragment:e,timeoutMs:i},bindings:t.toObjectCopy(),tools:n,signal:s},o)}import{createHmac as vw,randomUUID as Aw}from"crypto";var zu=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,Wu=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function ju({orgId:r,code:e,fragment:t,context:n,logger:o,timeoutMs:s=Xr,retries:i=1,signal:a}){if(!zu)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let l,c,u=0;if(!Wu)throw new Error("Missing lambda auth secret.");let d=vw("sha256",Wu).update(r).digest("hex");for(;u<=i;){u++,a?.throwIfAborted();let p={id:Aw(),orgId:r,momenticLambdaAuthHash:d,code:e,fragment:t,state:n.toObjectCopy(),timeoutMs:s};o.debug(p,"Sending request to code evaluation server");try{if(l=await J(fetch(zu,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)}),{milliseconds:s,message:`Timeout of ${s}ms exceeded for code execution`,signal:a}),!l)throw new Error("Got empty response from code evaluation server");if(!l.ok)throw new Error(`Code evaluation server returned error code ${l.status}`);c=void 0;break}catch(h){c=h}}if(c)throw c;if(!l)throw new Error(`An unexpected code evaluation error occurred${c?`: ${c}`:""}`);let m;try{m=wd.parse(await l.json()),o.debug({response:m},"Response from code evaluation server")}catch(p){throw new Error(`Code evaluation server returned invalid response: ${p}`)}if(m.error)throw new Error(`Code evaluation error: ${m.error}`);return m}async function jt(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await ju(r);else if(r.localTools)e=await Bu({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error)throw new Error(`Code evaluation error: ${e.error}`);if(e.variableUpdates)for(let[t,n]of Object.entries(e.variableUpdates))r.context.setVariable(t,n);return e.result}var rF=process.env.MAILINATOR_API_KEY;import"twilio";async function St(r){let{orgId:e,s:t,context:n,logger:o,timeoutMs:s=Xr,retries:i=1,signal:a}=r,l=/{{(.*?)}}/g,c=t.matchAll(l),u=t;for(let d of c){if(d.length<2)continue;let m=d[1].trim(),p;try{p=await jt({orgId:e,code:m,fragment:!0,context:n,timeoutMs:s,logger:o,retries:i,localTools:r.localTools,signal:a})}catch(f){throw o.error({err:f,value:t},"Error evaluating template string"),f}if(p===void 0)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 h=typeof p=="string"?p:`${p}`;h=h.replace(/\$/g,"$$$$"),h=h.replace(/\\/g,"\\\\"),u=u.replace(d[0],h)}return o.debug({s:t,result:u},"Substituted template string"),u}async function oo({cmd:r,bannedKeys:e,context:t,prefixPath:n="",replacements:o={},...s}){for(let i in r){if(e.includes(i))continue;let a=r[i],l=n?`${n}.${i}`:i;if(typeof a=="string"&&a.includes("{{")){let c=await St({s:a,context:t,...s});if(a===c)continue;o[l]=a,r[i]=c}else typeof a=="object"&&a!==null&&!Array.isArray(a)&&await oo({cmd:a,bannedKeys:e,context:t,prefixPath:l,replacements:o,...s})}return o}import Iw from"fetch-cookie";import{cloneDeep as Pw}from"lodash-es";var As=(r,e)=>{try{let{hostname:t,pathname:n}=new URL(r),{hostname:o,pathname:s}=new URL(e);return t!==o||n!==s}catch{return!1}},xs=r=>{try{return new URL(r),!0}catch{return!1}},Hu=r=>!r.toLowerCase().startsWith("http"),Rs=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function Rr(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}var Rw=3e4;async function Is({command:r,logger:e,baseUrl:t,fetchImplementation:n=fetch}){let o=r.timeout??Rw/1e3,s=null,i=new AbortController,a=Object.fromEntries(Object.entries(r.headers||{}).filter(([g,y])=>g&&y)),l=new URLSearchParams;Object.entries(r.params||{}).filter(([g,y])=>g&&y).forEach(([g,y])=>{l.append(g,y)});let c=l.toString(),u;if(xs(r.url)&&(u=r.url),t&&Rs(r.url,t)&&(u=new URL(r.url,t).toString()),!u)throw new R("ActionFailureError",`Invalid URL: ${r.url}`);let d=async()=>{let g=c?`${u}?${c}`:u;try{s=await n(g,{headers:a,method:r.method,body:r.body,signal:i.signal})}catch(y){e.error({err:y},"Failed to make HTTP request")}},m=async()=>{await new Promise(g=>setTimeout(g,o*1e3)),i.abort()};await Promise.race([m(),d()]);let p=s;if(!p)throw new R("ActionFailureError",`Fetch request timed out after ${o} seconds`);if(!p.ok)throw new R("ActionFailureError",`Fetch request failed with status ${p.status}`);let h={};p.headers.forEach((g,y)=>{h[y]=g});let f={status:p.status,headers:h};return p.headers.get("content-type")?.includes("json")?f.json=await p.json():p.headers.get("content-type")?.includes("text")&&(f.text=await p.text()),f}async function Gu(r){let{fixtures:e,inputs:t}=r,{context:n}=e,{orgId:o,step:s}=t,i=Pw(s);await oo({cmd:i,orgId:o,bannedKeys:["code"],...e});let a=await Ow(r);return i.envKey&&a.data&&n.setVariable(i.envKey,a.data),a}async function Ow(r){let{fixtures:e,inputs:t}=r,{step:n,orgId:o,baseUrl:s}=t,{cookieJar:i}=e,a=new Date;switch(n.type){case"JAVASCRIPT":{let c=await jt({code:n.code,orgId:o,fragment:!!n.fragment,timeoutMs:n.timeout?n.timeout*1e3:void 0,...e});try{JSON.stringify(c)}catch(u){return{...n,startedAt:a,finishedAt:new Date,status:"FAILED",message:`JavaScript return value is not serializable: ${u instanceof Error?u.message:`${u}`}`}}return{...n,startedAt:a,finishedAt:new Date,message:"JavaScript code executed successfully",status:"SUCCESS",data:c}}case"REQUEST":{let c=Iw(fetch,i),u=await Is({command:n,logger:e.logger,baseUrl:s,fetchImplementation:c});return{...n,startedAt:a,finishedAt:new Date,status:"SUCCESS",message:"Request executed successfully",data:u}}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}}async function Vu(r){let{inputs:e,fixtures:t,callbacks:n}=r,{signal:o}=t,{test:s,orgId:i}=e,{test:a,step:l}=n,c={startedAt:new Date,status:"RUNNING",results:[]},u=c.results,d=new Lw,m={cookieJar:d,...t};for(let p of s.steps){let h=new Date;l.onStarted?.(p.id);let f;try{o?.throwIfAborted(),f=await Gu({inputs:{step:p,baseUrl:s.baseUrl,orgId:i},fixtures:m})}catch(g){o?.aborted?f={...p,startedAt:h,finishedAt:new Date,status:"CANCELLED",message:"Step cancelled by user."}:f={...p,startedAt:h,finishedAt:new Date,status:"FAILED",message:`Step failed: ${g instanceof Error?g.message:`${g}`}`}}if(u.push(f),l.onFinished?.({result:f,cookies:d.cloneSync()?.serializeSync()?.cookies??[]}),a.updateAttemptProgress?.({results:u}),f.status!=="SUCCESS"){c.status=f.status==="CANCELLED"?"CANCELLED":"FAILED";break}}return c.status==="RUNNING"&&(c.status="PASSED"),c.finishedAt=new Date,a.onFinished?.(),c}var Mw=r=>async(e,t)=>{let{test:n}=e,{authorization:o,metadata:s,socket:i}=r,{orgId:a,testId:l,sessionId:c}=s,{logger:u}=r,d=or[c];if(!d)throw new Error(`No api testing session with id ${c} could be found. Please reconnect and try again.`);let m=new AbortController;d.abort=m,u=u.child({testId:l,orgId:a,sessionId:c});let p=o?.type==="API_KEY"?new yt({httpClient:new Ze(o)}):void 0,f={context:d.latestContext,logger:u,localTools:p,signal:m.signal},S=await Vu({inputs:{test:n,orgId:a},fixtures:f,callbacks:{test:{onFinished:()=>{i.emit("apiTestFinished")}},step:{onStarted:w=>{i.emit("apiStepStarted",w)},onFinished:w=>{i.emit("apiStepFinished",w)}}}});t({result:S})},qu={event:"executeApiTest",createHandler:Mw};var Nw=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async()=>{e.info({sessionId:t},"Cancel event received");let n=z.getSession(t);if(!n)throw new Error("No active session found");try{n.controller.setClosed()}catch{}}},Ku={event:"cancel",createHandler:Nw};var _w=({metadata:r,logger:e})=>{let{sessionId:t,type:n}=r;return o=>{e.info({sessionId:t,reason:o},`Disconnect event received (${o})`),n==="e2e"?z.removeSession(t,e):n==="api-test"&&delete or[t]}},Yu={event:"disconnect",createHandler:_w};import{diff as Zw}from"deep-object-diff";async function Ps(r,e,t,n,o,s){try{let[i,a]=await Promise.all([t?o(t):void 0,n?o(n):void 0]);i&&(r&&(r.beforeScreenshot=i),e.beforeScreenshot=i),a&&(r&&(r.afterScreenshot=a),e.afterScreenshot=a)}catch(i){s.debug({err:i},"Error saving screenshot to S3")}}var Os=async r=>{let e=r.presetParams.step,{logger:t,controller:n,context:o}=r.fixtures,{takeScreenshots:s}=r.options,{testMetadata:i}=r.inputs,a=t.child({commandType:e.command.type,stepId:e.id,commandId:e.command.id}),l=r.callbacks.test,c=n.browser.url(),u=new Date,d;if(s)try{d=await n.browser.screenshot({retries:1,clearHighlights:!0})}catch(g){a.debug({err:g},"Failed to take screenshot before step, likely because the page is still loading. This is non-fatal and does not affect the test.")}let m,p,h,f=ps();try{a.debug("Starting preset action");let g=await n.executePresetStep(f,e.command,o,i.advanced.disableAICaching);g.beforeScreenshotOverride&&(d=g.beforeScreenshotOverride),h=g.afterScreenshotOverride;let y=new Date,S=n.browser.url();p={beforeUrl:c,afterUrl:S,startedAt:u,finishedAt:y,viewport:await n.browser.getViewport(),status:g.fail?"FAILED":"SUCCESS"},m={...e,message:g.thoughts??"Successfully executed preset action.",beforeUrl:c,afterUrl:S,finishedAt:y,startedAt:u,status:g.fail?"FAILED":"SUCCESS",data:g.data,results:[p],details:f.details},"assertion"in e.command&&(m.message=g.thoughts||"Assertion passed."),(e.command.type==="AI_EXTRACT"||e.command.type==="JAVASCRIPT")&&e.command.envKey&&o.setVariable(e.command.envKey,m.data)}catch(g){a.error({err:g},`Failed executing preset step ${nr(e.command)}`);let y=n.browser.url(),S=new Date,w=g instanceof Error?g.message:`${g}`;p={beforeUrl:c,afterUrl:y,startedAt:u,finishedAt:S,viewport:await n.browser.getViewport(),status:g instanceof DOMException&&g.name==="AbortError"?"CANCELLED":"FAILED",message:w},m={...e,startedAt:u,finishedAt:S,beforeUrl:c,afterUrl:y,status:g instanceof DOMException&&g.name==="AbortError"?"CANCELLED":"FAILED",message:w,failureReason:g instanceof R?g.reason:void 0,results:[p],details:f.details}}if(s&&!h)try{h=await n.browser.screenshot({retries:1})}catch(g){a.debug({err:g},"Failed to take screenshot after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return r.work.asyncTasks.push(Ps(p,m,d,h,l.onSaveScreenshot,a)),m};function Mt(r){let{result:e,nestedResults:t}=r;if(!r.nestedResults.length)return;let{firstMetadata:n,lastMetadata:o}=kw(t);Dw(e,n,o);let s=[...r.asyncTasks];r.asyncTasks.push((async()=>{try{await Fw(s,e,n,o)}catch(i){r.logger.error({result:r.result,err:i},"Error hoisting scalar result metadata")}})())}function kw(r){let e=r[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertion){t=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!e.results.length){t=e;break}e=e.results[e.results.length-1];break;default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let n=r[r.length-1],o;for(;;){switch(n.type){case"PRESET_ACTION":{o=n;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!n.results.length){o=n;break}n=n.results[n.results.length-1];break;default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function Dw(r,e,t){e&&(r.beforeUrl=e.beforeUrl),t&&(r.afterUrl=t.afterUrl,r.data=t.data,t.status!=="SUCCESS"&&(r.message=t.message))}async function Fw(r,e,t,n){await Promise.allSettled(r),t&&(e.beforeScreenshot=t.beforeScreenshot),n&&(e.afterScreenshot=n.afterScreenshot)}import Ma from"os";import Uw from"v8";function Xu(r){let e=()=>{try{let t=!1,n=$w(),o=Bw();n.freeMemory<1e6&&(t=!0);let s=Uw.getHeapStatistics(),i=s.used_heap_size,a=s.heap_size_limit;i/a>.9&&(t=!0),t?r.warn({memory:n,cpu:o,heapStats:s},"Critical resource usage metrics detected"):r.debug({memory:n,cpu:o,heapStats:s},"Got machine resource usage metrics")}catch{}};return e(),setInterval(e,15e3)}function $w(){let r=Ma.totalmem(),e=Ma.freemem(),t=r-e;return{totalMemory:r,freeMemory:e,usedMemory:t}}function Bw(){let r=Ma.cpus(),e=0,t=0,n=0,o=0,s=0,i=0;for(let a of r)e+=a.times.user,t+=a.times.nice,n+=a.times.sys,o+=a.times.idle,s+=a.times.irq;return i=e+t+n+o+s,{user:e/i*100,nice:t/i*100,sys:n/i*100,idle:o/i*100,irq:s/i*100,total:100-o/i*100}}var Ju=async r=>{let{step:e,resolvedInputs:t}=r.moduleParams,{logger:n,context:o,storage:s,codeEvalTools:i,controller:a}=r.fixtures,{orgId:l,testMetadata:c}=r.inputs;Object.keys(t).length>0&&(o.setInputs(t),n.debug({inputs:t,moduleId:e.moduleId},"Set module inputs"));let u,d;if(e.cacheConfig){let m=e.cacheConfig.cacheKey||e.defaultCacheKey||"",p=await St({orgId:l,s:m,context:o,logger:n,localTools:i,signal:a.executeAbortController.signal}),h={orgId:l,cacheKeys:[p,...Object.entries(t).map(([g,y])=>`${g}:${y}`)]};n.debug({cacheKey:m,keyParams:h},"Module cache key params");let f=Date.now();for(;Date.now()-f<Nd;){let g=await s.getCacheResult(h);if(g){n.info({cacheResult:g},"Got result from module execution cache"),u=Ls(e,t,"SUCCESS"),u.message="Used cached module result.",u.data=JSON.parse(g);break}let y=await s.acquireCacheLock({keyParams:h,clientMetadata:`testId:${c.id}`},a.executeAbortController.signal);if(y.acquired){d=y.keyPrefix,n.info({cacheKeyPrefix:d,cacheKey:m,keyParams:h},"Acquired cache lock and proceeding with module execution");break}await q(2500+Math.random()*1e4,a.executeAbortController.signal)}}try{u||(u=await zw(r))}finally{if(d!==void 0){let m=e.cacheConfig.cacheExpiryMs;if(m===vd&&(m=e.defaultCacheTtl??Ad),u&&u.status==="SUCCESS"){let p=JSON.stringify(u.data===void 0?"":u.data);n.debug({cacheKeyPrefix:d,ttlMs:m,cacheResult:p},"Setting module cache result"),await s.setCacheResult({result:p,keyPrefix:d,ttlMs:m})}await s.releaseCacheLock(d)}}return u},zw=async r=>{let{step:e}=r.moduleParams,t=Ls(e,r.moduleParams.resolvedInputs,"SUCCESS"),{status:n,results:o}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:`module ('${e.name}')`}});return t.results=o,t.status=n,t.finishedAt=new Date,Mt({asyncTasks:r.work.asyncTasks,nestedResults:o,result:t,logger:r.fixtures.logger}),t};function Ls(r,e,t){let n={};return Object.entries(e).forEach(([s,i])=>{n[s]=JSON.stringify(i)}),{type:"MODULE",id:r.id,moduleId:r.moduleId,moduleName:r.name,startedAt:new Date,cacheConfig:r.cacheConfig,inputs:n,results:[],finishedAt:new Date,status:t}}async function Ms({orgId:r,step:e,context:t,logger:n,codeEvalTools:o,signal:s}){let i={};try{for(let a of e.parameters??[]){let l=e.inputs?.[a]??e.defaultParameters?.[a];if(!l){n.warn(`No value or default found for parameter '${a}' that is required by module '${e.name}'`);continue}i[a]=await jt({orgId:r,code:l,fragment:!0,context:t,logger:n,localTools:o,signal:s})}return i}catch(a){throw s?.throwIfAborted(),new R("UserConfigurationError",`Failed to evaluate module inputs: ${a}`)}}async function sr(r,e,t){let n=new Date;try{return t.throwIfAborted(),await e()}catch(o){let s=new Date,i="FAILED",a;if(t.aborted||o instanceof DOMException&&o.name==="AbortError"?(a="Step aborted by user.",i="CANCELLED"):o instanceof R?a=`${o}`:a=`An unexpected error occurred: ${o.message}`,r.type==="RESOLVED_MODULE"){let l=Ls(r,{},"FAILED");return l.message=a,l.startedAt=n,l.finishedAt=s,l}return{...r,startedAt:n,finishedAt:s,status:i,data:null,message:a,results:[]}}}async function Ns(r,e){let t=!1;try{return r&&!r.healingDisabled&&(r.healingDisabled=!0,t=!0),await e()}finally{r&&t&&(r.healingDisabled=void 0)}}import{randomUUID as Ww}from"crypto";var Na=async r=>{let e=await jw(r);return e.finishedAt=new Date,Mt({asyncTasks:r.work.asyncTasks,result:e,nestedResults:e.results,logger:r.fixtures.logger}),e},jw=async r=>{let e=r.aiStepParams.step,t=e.index,{testMetadata:n,steps:o}=r.inputs,{takeScreenshots:s}=r.options,{controller:i,context:a,logger:l}=r.fixtures,{test:c,step:u}=r.callbacks;if(t===void 0)throw new Error("Attempted to execute AI action step without index");i.resetHistory();let d={...e,startedAt:new Date,beforeTestContext:a.toRedactedDisplayCopy(),finishedAt:new Date,results:[],status:"SUCCESS"};"steps"in e&&e.steps===void 0&&(e.steps=[]);let m="steps"in e&&!!e.steps&&e.steps.length>0&&e.steps[e.steps.length-1]?.command.type==="SUCCESS";if(e.type==="AI_ACTION"&&m)try{let{status:f,results:g}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"AI action"}});return d.finishedAt=new Date,d.status=f,d.results=g,d}catch(f){l.warn({err:f},"Failed executing saved AI action steps, attempting to re-generate...")}"steps"in e&&(e.steps=[]);let p=(await i.browser.screenshot({clearHighlights:!0})).toString("base64"),h=0;for(;;){if(h>12)return d.message=`Exceeded max number of commands per step (${12})`,d.status="FAILED",d;if(i.executeAbortController.signal.aborted)return d.message="Test execution was cancelled",d.status="CANCELLED",d;let f=t+h+1;e.type==="AI_ACTION_DYNAMIC"&&u.onDynamicAIActionThinkingEvent?.({parentStepId:e.id});let g,y;if(s)try{y=await i.browser.screenshot({clearHighlights:!0})}catch(I){l.debug({err:I},"Failed to take screenshot before AI command, likely because the page is still loading. This is non-fatal.")}l.info(`Generating new sub-command ${h} within AI step`);let S;try{S=await i.promptToCommand(e.text,p,n.advanced.disableAICaching);let I=S.command.type;if(I==="FAILURE")return d.status="FAILED",d.message=S.command.thoughts,d;if(I==="SUCCESS")return d.status="SUCCESS",d.message=S.command.thoughts,d;g=S.command,l.debug({command:g},"Generated new command")}catch(I){throw i.throwIfClosed(),l.error({err:I,commandIndex:h},"Failed to generate command within AI step"),I}let w={id:Ww(),type:"PRESET_ACTION",index:f,command:g},T={index:f,message:S.command.thoughts||"Generated new command."};e.type==="AI_ACTION_DYNAMIC"&&u.onDynamicAIActionDescribingEvent?.({parentStepId:e.id}),await Gw({newStep:w,controller:i,currentStep:e,pageContext:S?.context,logger:l,currentIndex:h}),e.type==="AI_ACTION"?u.onCommandGenerated?.({...T,step:w,parentStepId:e.id}):e.type==="AI_ACTION_DYNAMIC"&&u.onDynamicCommandGenerated?.({...T,step:w,parentStepId:e.id}),l.info({commandId:g.id},`Executing sub-command ${h} within AI step: ${nr(g)}`),u.onStarted?.(w.id,f);let C=await Vw({step:w,controller:i,context:a,beforeScreenshotBuff:y,onSaveScreenshot:c.onSaveScreenshot,work:r.work,logger:l,useSavedCommands:m,disableCaching:n.advanced.disableAICaching,takeScreenshots:s});"steps"in e&&(e.steps[h]=w),bs(o),d.results.push(C);let A={index:f,output:{...C,message:g.thoughts??C.message??"Successfully executed preset action."},step:w,parentStepId:e.id};switch(e.type==="AI_ACTION"?u.onCommandExecuted?.(A):e.type==="AI_ACTION_DYNAMIC"&&u.onDynamicCommandStarted?.(A),C.status){case"SUCCESS":u.onSuccess?.({index:f,output:tr.parse(C),step:C,message:C.command.thoughts||C.message});break;case"FAILED":return u.onFailure?.({index:f,output:tr.parse(C),step:C,message:C.message}),d.status="FAILED",d.message=C.command.thoughts||C.message,d;case"CANCELLED":return u.onCancelled?.({index:f,output:tr.parse(C),step:C,message:C.message}),d.status="CANCELLED",d.message=C.command.thoughts||C.message,d}if(C.status!=="SUCCESS")break;h++}return d};async function Hw(r,e,t){let n=t.id;if(!n||t.id<=0)throw new Error("Attempted to get reverse mapping for command with no a11y id target");return r.getReverseMappedTarget(e,n,!0)}async function Gw({controller:r,currentIndex:e,currentStep:t,newStep:n,pageContext:o,logger:s}){if(!o)return;let i=n.command;if("target"in i&&i.target&&"cache"in i&&i.cache)try{let a=await Hw(r,o,i.cache.target);i.target={elementDescriptor:a,type:"description"},"steps"in t&&(t.steps[e]=n)}catch(a){s.warn({err:a,currentIndex:e,currentStep:t},"Failed to generate element description, continuing...")}}async function Vw({step:r,controller:e,context:t,logger:n,beforeScreenshotBuff:o,onSaveScreenshot:s,work:i,takeScreenshots:a,useSavedCommands:l,disableCaching:c}){let u=new Date,d={beforeUrl:e.browser.url(),viewport:await e.browser.getViewport(),startedAt:u,finishedAt:new Date,status:"SUCCESS"},m=t.toRedactedDisplayCopy(),p={...r,beforeUrl:d.beforeUrl,beforeTestContext:m,startedAt:d.startedAt,results:[d],message:r.command.thoughts,finishedAt:d.finishedAt,status:"FAILED"};try{let f=await e.executeCommand(r.command,t,l&&c,l);d.elementInteracted=f.elementInteracted,d.status="SUCCESS",p.data=f.data,p.status="SUCCESS"}catch(f){let g=e.executeAbortController.signal.aborted,y=f instanceof Error?f.message:`${f}`;d.status=g?"CANCELLED":"FAILED",d.message=y,p.message=y,p.failureReason=f instanceof R?f.reason:void 0,p.status=g?"CANCELLED":"FAILED"}let h;if(a)try{h=await e.browser.screenshot({})}catch(f){n.debug({err:f},"Failed to take screenshot after AI command, likely because the page is still loading. This is non-fatal.")}return d.afterUrl=e.browser.url(),d.finishedAt=new Date,p.afterUrl=d.afterUrl,p.finishedAt=d.finishedAt,p.afterTestContext=t.toRedactedDisplayCopy(),i.asyncTasks.push(Ps(d,p,o,h,s,n)),p}async function Qu(r){let{step:e}=r.conditionalParams,{logger:t,controller:n}=r.fixtures,o=new Date,s=e.elseSteps,i=!0,a=[],l,c=ps();for(let p=0;p<e.blocks.length;p++){t.info(`Evaluating condition ${p} in conditional step`);let h=e.blocks[p];try{let f=await Os({...r,presetParams:{step:h.assertion}});a.push(f),t.info(`Condition ${p} resolved to true, executing the corresponding ${h.steps.length} steps`),i=!1,s=h.steps,l=f}catch(f){t.info({err:f},`Condition ${p} resolved to false`)}finally{n.throwIfClosed()}}if(s)i&&t.info("No conditions resolved to true, executing the else block steps");else return t.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped"),{...e,status:"SUCCESS",startedAt:o,data:a[a.length-1]?.data,message:a[a.length-1]?.message,results:[],finishedAt:new Date,details:c.details};t.info(`Executing ${s.length} steps in the selected conditional block`);let u=await r.executeStepList({...r,listParams:{steps:s,containerName:"conditional block"}}),m={...e,assertion:l,...u,startedAt:o,finishedAt:new Date};return Mt({asyncTasks:r.work.asyncTasks,nestedResults:[...a,...u.results],result:m,logger:t}),m}async function em(r){let{step:e}=r.frameParams,{logger:t,controller:n}=r.fixtures,o=new Date,s=n.browser.getActiveFrame();n.browser.setActiveFrame(e.identifier);let i;try{i=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"frame step list"}})}finally{n.browser.setActiveFrame(s)}let l={...e,...i,startedAt:o,finishedAt:new Date};return Mt({asyncTasks:r.work.asyncTasks,nestedResults:i.results,result:l,logger:t}),l}import{randomUUID as _s}from"crypto";import qw from"fast-json-patch";import{cloneDeep as Kw}from"lodash-es";async function tm(r){let e=r.failedResults,t=[],{sectionParams:n,fixtures:o,work:s,startingUrl:i,startingContextSnapshot:a}=r,{step:l}=n,{controller:c}=o,u=l?.autohealingConfig,d=u?.restartBehavior??{type:"GO_TO_SECTION_START"},m=u?.attempts??1;for(let p=0;p<m;p++){if(!e.terminalResult?.message)throw new Error("No error message in terminal result");let h=Kw(l.steps);await Promise.allSettled(s.asyncTasks??[]);let f=await c.runSectionAutohealing({results:e.results,errorMessage:e.terminalResult?.message,goal:l.description});for(let S of f.patches)h=qw.applyOperation(h,S).newDocument;let g=Ve.fromSnapshot({snapshot:a,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await Yw({controller:c,context:g,restartConfig:d,startingUrl:i});let y=await Ns(r.work,()=>r.executeStepList({...r,fixtures:{...r.fixtures,context:g},listParams:{steps:h,containerName:"auto-healed step list"}}));if(t.push(y.results),y.status==="SUCCESS")return{successfulHealing:{proposedStep:{...l,steps:h},listResult:y,context:g},healingAttempts:t};e=y}return{healingAttempts:t}}async function Yw({controller:r,restartConfig:e,context:t,startingUrl:n}){switch(e.type){case"NAVIGATE_URL":{let o={id:_s(),type:"PRESET_ACTION",command:{id:_s(),type:"NAVIGATE",url:e.url}};await r.executePresetStep(null,o.command,t,!1);break}case"GO_TO_SECTION_START":{let o={id:_s(),type:"PRESET_ACTION",command:{id:_s(),type:"NAVIGATE",url:n}};await r.executePresetStep(null,o.command,t,!1);break}}}function rm(r,e){switch(r||(r="ON_FAILURE"),r){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&uc(e.command.type))}}async function nm(r){let{step:e}=r.sectionParams,{logger:t,controller:n,context:o}=r.fixtures,s=new Date,i=n.browser.url(),a=o.toObjectCopy(),l=async()=>r.executeStepList({...r,listParams:{steps:e.steps,containerName:"section step list"}}),c=e.autohealingConfig?await Ns(r.work,l):await l(),u,d;if(c.status==="FAILED"&&e.autohealingConfig&&!r.work.healingDisabled&&rm(e.autohealingConfig.trigger,c.terminalResult)){let p=await tm({...r,startingContextSnapshot:a,startingUrl:i,failedResults:c});p.successfulHealing&&(u=p.successfulHealing.proposedStep,c=p.successfulHealing.listResult,r.fixtures.context=p.successfulHealing.context),d=p.healingAttempts}let m={...e,...c,startedAt:s,finishedAt:new Date,proposedStep:u,healingAttempts:d};return Mt({asyncTasks:r.work.asyncTasks,nestedResults:c.results,result:m,logger:t}),m}async function ir(r){let{results:e=[],containerName:t,steps:n}=r.listParams,{logger:o,context:s,controller:i,codeEvalTools:a}=r.fixtures,{step:l}=r.callbacks,{orgId:c,fromIndex:u,toStepId:d}=r.inputs,m=r.work,p=[],h="SUCCESS",f,g=0;for(g;g<n.length;g++){let y=n[g],S,w=to(y),T=y.index;if(T===void 0)throw new Error(`Executing step without index: ${w}`);if(y.skipped)continue;if(u&&T<u&&(y.type==="PRESET_ACTION"||au([y])<u))continue;o.info({step:y},`Executing step ${g+1}/${n.length} in ${t}: ${w}`),l.onStarted?.(y.id,T);let C=s.toRedactedDisplayCopy(),A=i.browser.url(),I=i.executeAbortController.signal,O,x;switch(y.type){case"PRESET_ACTION":{O="Preset action",x=await sr(y,()=>Os({...r,presetParams:{step:y}}),I);break}case"AI_ACTION":{O="AI action",x=await sr(y,()=>Na({...r,aiStepParams:{step:y},executeStepList:ir}),I);break}case"AI_ACTION_DYNAMIC":{O="Dynamic AI action",x=await sr(y,()=>Na({...r,aiStepParams:{step:y},executeStepList:ir}),I);break}case"RESOLVED_MODULE":{O=`Module (${y.name})`;let H=s.getResultsCopy();x=await sr(y,async()=>{let P=await Ms({orgId:c,step:y,context:s,logger:o,codeEvalTools:a,signal:I});return Ju({...r,executeStepList:ir,moduleParams:{step:y,resolvedInputs:P}})},I),s.setResults(H);break}case"CONDITIONAL":{O="Conditional step",x=await sr(y,()=>Qu({...r,conditionalParams:{step:y},executeStepList:ir}),I);break}case"IFRAME":{O="Frame step",x=await sr(y,()=>em({...r,frameParams:{step:y},executeStepList:ir}),I);break}case"SECTION":{O="Section";let H=await sr(y,()=>nm({...r,sectionParams:{step:y},executeStepList:ir}),I);"proposedStep"in H&&H.proposedStep&&(S=H.proposedStep,H.proposedStep=void 0,m&&(m.autoHealed=!0)),x=H;break}default:return(P=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(y)}S?p.push(S):p.push(y),x.beforeUrl=x.beforeUrl??A,x.beforeTestContext=C,s.setResult(g,x.data),y.envKey&&s.setVariable(y.envKey,x.data);let j=i.browser.url();if(s.setCurrentUrl(j),x.afterUrl=x.afterUrl??j,x.afterTestContext=s.toRedactedDisplayCopy(),e.push(x),Xw(O,T,x,r.callbacks,o,r.work),x.status!=="SUCCESS"||i.closed){h=x.status,f=x;break}else if(y.id===d){i.setClosed();break}}return{status:h,results:e,terminalResult:f,proposedSteps:p}}function Xw(r,e,t,n,o,s){let{step:i,test:a}=n,l=r.toLowerCase(),c=r.charAt(0).toUpperCase()+r.slice(1);switch(t.status){case"SUCCESS":i.onSuccess?.({index:e,step:t,message:t.message??`${c} executed successfully.`,output:tr.parse(t)});break;case"FAILED":i.onFailure?.({index:e,step:t,message:t.message??`${c} failed.`,output:tr.parse(t)});break;case"CANCELLED":i.onCancelled?.({index:e,step:t,message:t.message??`${c} cancelled.`,output:tr.parse(t)});break;default:throw new Error(`Unexpected ${l} status: ${t.status}`)}t.status==="SUCCESS"&&s&&a.onUpdateRun?.({results:s.results})}import{randomUUID as om}from"crypto";async function sm(r){let e=new Date;try{return await r.navigate({url:r.baseUrl,initialNavigation:!0}),{status:"PASSED",results:[]}}catch(t){let n={id:om(),type:"PRESET_ACTION",status:t.name==="AbortError"?"CANCELLED":"FAILED",failureReason:"UserConfigurationError",message:t.message,startedAt:e,finishedAt:new Date,results:[],command:{id:om(),type:"NAVIGATE",url:r.baseUrl}};return{status:t.name==="AbortError"?"CANCELLED":"FAILED",results:[],failedStepResult:n}}}var ks=async r=>{r.fixtures.logger=r.fixtures.logger.child({orgId:r.inputs.orgId,runId:r.inputs.runId,testId:r.inputs.testMetadata.id});let{logger:e,controller:t}=r.fixtures,{onTestComplete:n,onTestSuccess:o}=r.callbacks.test;if(r.options.reinitializeBrowser){let a=await sm(t.browser);if(t.executeAbortController.signal.aborted)return a.status="CANCELLED",await n?.(),a;if(a.status==="FAILED")return await n?.(),a}let s;s=Xu(e),bs(r.inputs.steps);let i;try{return i=await Jw(r),i}finally{if(clearInterval(s),iu(r.inputs.steps),await n?.(),i?.status==="PASSED")try{await o?.(r.inputs.steps)}catch(a){e.warn({err:a},"Error running test success handler, continuing...")}}},Jw=async r=>{let{runId:e,testMetadata:t,fromIndices:n,toIndices:o,indicesFilter:s,steps:i,orgId:a}=r.inputs,{logger:l,controller:c,context:u,codeEvalTools:d}=r.fixtures;u.setCurrentUrl(c.browser.url()),l.info(`Starting run ${e} for test '${t.name}'`);let m=i,p="test",h;if(n){let{step:C,parent:A}=Ts(i,n);if(!C)throw new Error(`Could not find starting step using indices: ${n}`);A&&A.type==="RESOLVED_MODULE"&&(h=A),r.inputs.fromIndex=C.index,l.debug({fromIndices:n,fromStep:C,filteredParentModule:h},"Identified starting step using fromIndices"),p="partial steps list"}if(o){let{step:C}=Ts(i,o);if(!C)throw new Error(`Could not find step at indices: ${o}`);r.inputs.toStepId=C.id,l.debug({toIndices:o,toStep:C},"Identified ending step using toIndices"),p="partial steps list"}if(s){let{step:C,parent:A}=Ts(i,s);if(!C)throw new Error(`Could not find ending step at indices: ${r.inputs.indicesFilter}`);A&&A.type==="RESOLVED_MODULE"&&(h=A),m=[C],p="filtered step"}if(h){let C=await Ms({orgId:a,step:h,context:u,logger:l,codeEvalTools:d,signal:c.executeAbortController.signal});u.setInputs(C)}l.debug({stepsToRun:m,indicesFilter:s},"Executing steps");let f=[],g={results:f,healingDisabled:!!s||!!n||!!o||void 0,asyncTasks:[]},{status:y,terminalResult:S,proposedSteps:w}=await ir({...r,work:g,listParams:{steps:m,containerName:p,results:f}});r.options.takeScreenshots&&await Promise.allSettled(g.asyncTasks);let T;if(r.options.consumeDebuggingData){T={logsPerPage:su(c.browser.retrieveAndClearConsoleLogs())};try{let A=await c.browser.html();l.debug({finalPageHtml:A},"Final page state HTML")}catch{}}return r.callbacks.test.onUpdateRun?.({results:f,debugData:T}),y==="FAILED"?{status:"FAILED",results:f,failedStepResult:S}:(w&&g.autoHealed&&await r.callbacks.test.onProposedTestSteps?.({testId:t.id,orgId:r.inputs.orgId,runId:r.inputs.runId,steps:w}),{status:"PASSED",results:f})};import{cloneDeep as Qw}from"lodash-es";var _a={currentlyExecutingRequests:{}},eb=r=>async(e,t)=>{let n,{testId:o}=r.metadata,{baseUrl:s}=e,i=`${o}|${s}`;try{let a=_a.currentlyExecutingRequests[i]??0;_a.currentlyExecutingRequests[i]=a+1,n=await tb({...r,...e,done:t})}finally{r.logger.info({result:n,sessionId:r.metadata.sessionId},"Test execution complete"),_a.currentlyExecutingRequests[i]--}},tb=async({socket:r,steps:e,baseUrl:t,testMetadata:n,reInitialize:o,indicesFilter:s,toIndices:i,fromIndices:a,storage:l,metadata:c,logger:u,envName:d,environmentVariables:m,testInputs:p,authorization:h,done:f})=>{let{testId:g,sessionId:y,orgId:S}=c,w=y,T=z.getSession(y);if(!T)throw new Error("No active session found");let{controller:C,context:A}=T;C.setOpen();let I=h?.type==="API_KEY"?new yt({httpClient:new Ze(h)}):void 0;u=u.child({testId:g,orgId:S,baseUrl:t,sessionId:y,runId:w}),u.info({indicesFilter:s,fromIndices:a,toIndices:i,reInitialize:o,envName:d,baseUrl:t,context:A,flags:C.flagStore.getAllFlags()},"Starting execution");let O=m??{};await Promise.all((n.parameters??[]).map(async L=>{let Fe=(p??{})[L.name]??L.defaultValue;if(Fe===void 0)return;let Ut=await St({orgId:S,s:Fe,context:Ve.dummyContext(d),logger:u,localTools:I});O[L.name]=Ut}));let x=async()=>{if(o){let L={url:t,clearCookies:!0,clearStorage:!0};await C.resetState(L),A.reset({baseUrl:t,currentUrl:C.browser.url(),variablesFromEnvironment:O,envName:d})}},j=async()=>{try{await l.resolveStepCacheEntries({schemaVersion:n.schemaVersion,organizationId:S,testId:g,steps:e,logger:u})}catch(L){u.error({err:L},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};try{await Lt(Promise.all([x(),j()]),C.executeAbortController.signal),C.setOpen()}catch(L){if(r.emit("finished"),L.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${L}`)}let H=Qw(e),pr=await ks({fixtures:{controller:C,context:A,storage:l,codeEvalTools:I,logger:u},options:{takeScreenshots:!1,consumeDebuggingData:!1,reinitializeBrowser:!1},callbacks:{test:{onTestComplete:async()=>{r.emit("finished")},onSaveScreenshot:rb,onTestSuccess:async L=>{let Fe=Zw(H,L);if(Object.keys(Fe).length>0){u.debug({changes:Fe},"Updating steps post-run success");let{cachesToSave:Ut}=await gt({steps:e,cacheCreationParams:{testId:g,orgId:S}});try{await l.saveStepCacheEntries(Ut,n.id,u)}catch(Ur){u.warn({err:Ur},"Failed to save step cache entries after execution success")}}else u.debug("No changes detected in steps post-run success")}},step:{onStarted:(L,Fe)=>r.emit("started",{stepId:L,globalIndex:Fe}),onSuccess:L=>{r.emit("success",L)},onFailure:L=>{r.emit("failure",L)},onCancelled:L=>{r.emit("cancelled",L)},onCommandGenerated:L=>{r.emit("commandGenerated",L)},onCommandExecuted:L=>{r.emit("commandExecuted",L)},onDynamicAIActionThinkingEvent:L=>{r.emit("dynamicCommandThinking",L)},onDynamicAIActionDescribingEvent:L=>{r.emit("dynamicCommandDescribing",L)},onDynamicCommandGenerated:L=>{r.emit("dynamicCommandGenerated",L)},onDynamicCommandStarted:L=>{r.emit("dynamicCommandStarted",L)}}},inputs:{orgId:S,runId:w,testMetadata:n,steps:e,indicesFilter:s,fromIndices:a,toIndices:i}});return f?.(pr),pr.status},rb=async r=>r.toString("base64");var im={event:"execute",createHandler:eb};var nb=({metadata:r,logger:e,storage:t})=>{let{sessionId:n}=r;return async(o,s)=>{let{command:i,testMetadata:a,returnScreenshot:l}=o,c=Zn(i,o.description);e.debug({description:c,params:o},"Locate handler params"),e.info({description:c},"Locate handler called");let u=z.getSession(n);if(!u)throw new Error("No active session found");let{controller:d,context:m}=u;d.setOpen();let p=qr.parse(a.advanced??{}),h={},f;if(c){if("useSelector"in i&&i.useSelector)try{let g=await d.locateElementWithSelector(c,"iframeUrl"in i?i.iframeUrl:void 0);f=g.resolution.locator,h={target:g.target,thoughts:g.thoughts}}catch(g){e.warn({err:g},"Failed resolving target with selector"),s({err:`Failed locating element with CSS selector: ${g.message}`,decisions:g instanceof rr?g.decisions:void 0});return}else try{let g=await d.locateElement({description:c,disableCache:p.disableAICaching,iframeUrl:"iframeUrl"in i?i.iframeUrl:void 0,testContext:m,returnConflicts:!0});h={target:g.target,thoughts:g.thoughts},f=g.resolution.locator}catch(g){let y;try{y=await d.browser.html()}catch{}e.warn({err:g,html:y},"Failed locating element with AI"),s({err:`Failed locating element with AI: ${g.message}`});return}if(i.type==="SELECT_OPTION"&&f)try{h.options=await d.browser.getSelectOptions(f)}catch(g){e.warn({err:g},"Failed getting select options"),s({err:`Failed getting select options: ${g.message}`});return}e.info({result:h},"Locate handler result")}if(l)try{let{buffer:g,width:y,height:S}=await d.screenshotWithDimensions({clearHighlights:!0,target:h?.target,hideCaret:!0}),w=await t.uploadScreenshot(g);h.screenshot={data:w,width:y,height:S}}catch(g){e.error({err:g},"Error capturing screenshot during locate"),s({err:`Error taking screenshot: ${g.message}`});return}if(s({result:h}),f)try{await Promise.all([d.browser.scrollIntoView(f),d.browser.highlightTarget(f)])}catch(g){e.warn({err:g},"Error highlighting element, continuing...")}}},am={event:"locate",createHandler:nb};var ob=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async({percentX:n,percentY:o},s)=>{let i=z.getSession(t);if(!i)throw new Error("No active session found");let a=i.controller.browser;try{await a.clickMouseFromPositionPercentages(n,o)}catch(l){e.error({err:l},"Error performing click during cloud recording in control mode"),s({err:l.message})}}},lm={event:"cloudClick",createHandler:ob};var sb=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async(n,o)=>{let s=z.getSession(t);if(!s)throw new Error("No active session found");let{controller:i}=s;i.setOpen(),s.browserBehavior.showOverlay=!0;try{let a=await i.browser.captureTargetFromClick();o({result:a})}catch(a){e.error({err:a},"Record click failed"),o({err:a instanceof Error?a.message:`${a}`})}finally{s.browserBehavior.showOverlay=!1}}},cm={event:"recordTargetClick",createHandler:sb};var ib=({metadata:r,logger:e})=>{let{sessionId:t}=r,n,o=0,s=(a,l)=>{let c=async()=>{n=void 0;try{await a.highlightFromPositionPercentages(l),o=0}catch(u){e.error({err:u},"Error highlighting element on mouse move"),o++}};clearTimeout(n),n=setTimeout(c,50*(o+1))},i=0;return async a=>{let l=z.getSession(t);if(!l)throw new Error("No active session found");let{controller:c,browserBehavior:u}=l,d=c.browser;if(!d.closed){if(d.getActivePage().isClosed()){e.warn("Ignoring mouse move because the page is closed");return}u.showOverlay&&s(d,a);try{await d.moveMouseFromPositionPercentages(a.percentX,a.percentY),i=0}catch(m){i++,i%5===0&&e.warn({err:m,mouseErrors:i},"Error in socket mouse move handler")}}}},dm={event:"cloudMouseMove",createHandler:ib};var ab=({metadata:r})=>{let{sessionId:e}=r;return async({percentDeltaX:t,percentDeltaY:n})=>{let o=z.getSession(e);if(!o)throw new Error("No active session found");let s=o.controller.browser;if(s.closed)return;let i=await s.scrollFromPositionPercentages(t,n);if(!i)return;let a=o.browserBehavior.recordingState?.transformer;a&&a.recordScroll({...i,url:s.url()})}},um={event:"cloudScroll",createHandler:ab};var lb=({metadata:r,generator:e,socket:t,storage:n,logger:o})=>{let{sessionId:s,orgId:i,testId:a}=r;return async({indices:l})=>{let c=z.getSession(s);if(!c)throw new Error("No active session found");let{controller:u,browserBehavior:d}=c;o.info("Starting cloud recording");let m=await u.startRecordMode({generator:e,initialIndices:l,storage:n,logger:o,testId:a,orgId:i,onStepRecord:(p,h)=>{t.emit("stepRecorded",{step:p,indices:h})}});d.recordingState={transformer:m},d.showOverlay=!0}},mm={event:"cloudStartRecording",createHandler:lb};var cb=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async()=>{let n=z.getSession(t);if(!n)throw new Error("No active session found");e.info("Stopping cloud recording"),await n.controller.stopRecordMode(),n.browserBehavior.recordingState=void 0,n.browserBehavior.showOverlay=!1}},pm={event:"cloudStopRecording",createHandler:cb};var db=["Dead","Meta","AudioVolumeUp","AudioVolumeDown"],ub=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async({key:n})=>{let o=z.getSession(t);if(!o)throw new Error("No active session found");if(db.includes(n))return;let{controller:s}=o;if(s.browser.closed||s.browser.getActivePage().isClosed()){e.debug({sessionId:t},"Browser is closed, ignoring typing action");return}try{n.length>1?await s.browser.press(n):await s.browser.type(n,{clearContent:!1,pressKeysSequentially:!0})}catch(i){if(i.message.includes("has been closed")){e.debug({sessionId:t,err:i},"Browser is closed, ignoring typing action error");return}throw i}}},hm={event:"cloudType",createHandler:ub};var so={vimiumJs:'var K=Object.defineProperty;var P=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var F=(t,e,n)=>e in t?K(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,D=(t,e)=>{for(var n in e||(e={}))z.call(e,n)&&F(t,n,e[n]);if(P)for(var n of P(e))B.call(e,n)&&F(t,n,e[n]);return t};var g=(t,e,n)=>(F(t,typeof e!="symbol"?e+"":e,n),n);var _=(t,e,n)=>new Promise((o,r)=>{var i=s=>{try{d(n.next(s))}catch(l){r(l)}},a=s=>{try{d(n.throw(s))}catch(l){r(l)}},d=s=>s.done?o(s.value):Promise.resolve(s.value).then(i,a);d((n=n.apply(t,e)).next())});var E=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=E);var k={create(t,e,n,o){return{bottom:o,top:e,left:t,right:n,width:n-t,height:o-e}},copy(t){return{bottom:t.bottom,top:t.top,left:t.left,right:t.right,width:t.width,height:t.height}},translate(t,e,n){return e==null&&(e=0),n==null&&(n=0),{bottom:t.bottom+n,top:t.top+n,left:t.left+e,right:t.right+e,width:t.width,height:t.height}},subtract(t,e){return e=this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom)),e.width<0||e.height<0?[k.copy(t)]:[this.create(t.left,t.top,e.left,e.top),this.create(e.left,t.top,e.right,e.top),this.create(e.right,t.top,t.right,e.top),this.create(t.left,e.top,e.left,e.bottom),this.create(e.right,e.top,t.right,e.bottom),this.create(t.left,e.bottom,e.left,t.bottom),this.create(e.left,e.bottom,e.right,t.bottom),this.create(e.right,e.bottom,t.right,t.bottom)].filter(o=>o.height>0&&o.width>0)},intersects(t,e){return t.right>e.left&&t.left<e.right&&t.bottom>e.top&&t.top<e.bottom},intersectsStrict(t,e){return t.right>=e.left&&t.left<=e.right&&t.bottom>=e.top&&t.top<=e.bottom},equals(t,e){for(let n of["top","bottom","left","right","width","height"])if(t[n]!==e[n])return!1;return!0},intersect(t,e){return this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom))}};var N={_browserInfoLoaded:!0,_firefoxVersion:null,_isFirefox:!1,isFirefox(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._isFirefox},firefoxVersion(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._firefoxVersion},isString(t){return typeof t=="string"||t instanceof String}};var f={isReady(){return document.readyState!=="loading"},documentReady:function(){let t=document.readyState!=="loading",e=[];if(!t){let n;globalThis.addEventListener("DOMContentLoaded",n=E(function(){globalThis.removeEventListener("DOMContentLoaded",n,!0),t=!0;for(let o of e)o();e=null}),!0)}return function(n){if(t)return n();e.push(n)}}(),documentComplete:function(){let t=document.readyState==="complete",e=[];if(!t){let n;globalThis.addEventListener("load",n=E(function(o){if(o.target===document){globalThis.removeEventListener("load",n,!0),t=!0;for(let r of e)r();e=null}}),!0)}return function(n){t?n():e.push(n)}}(),createElement(t){let e=document.createElement(t);return e instanceof HTMLElement?(this.createElement=n=>document.createElement(n),e):(this.createElement=n=>document.createElementNS("http://www.w3.org/1999/xhtml",n),this.createElement(t))},addElementsToPage(t,e){let n=this.createElement("div");e.id!=null&&(n.id=e.id),e.className!=null&&(n.className=e.className);for(let o of t)n.appendChild(o);return document.body.appendChild(n),n},removeElement(t){return t.parentNode.removeChild(t)},isTopFrame(){return globalThis.top===globalThis.self},makeXPath(t){let e=[];for(let n of t)e.push(".//"+n,".//xhtml:"+n);return e.join(" | ")},evaluateXPath(t,e){let n=document.webkitIsFullScreen?document.webkitFullscreenElement:document.documentElement,o=function(r){return r==="xhtml"?"http://www.w3.org/1999/xhtml":null};return document.evaluate(t,n,o,e,null)},getVisibleClientRect(t,e){let n;e==null&&(e=!1);let o=(()=>{let i=[];for(n of t.getClientRects())i.push(k.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),a=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>a,a};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let a of Array.from(t.children)){i=window.getComputedStyle(a,null);let d=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(d)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(a,!0);if(!(s===null||s.width<3||s.height<3))return s}else{if(n=this.cropRectToVisible(n),n===null||n.width<3||n.height<3||(i=window.getComputedStyle(t,null),i.getPropertyValue("visibility")!=="visible"))continue;return n}}return null},cropRectToVisible(t){let e=k.create(Math.max(t.left,0),Math.max(t.top,0),t.right,t.bottom);return e.top>=window.innerHeight-4||e.left>=window.innerWidth-4?null:e},getClientRectsForAreas(t,e){let n=[];for(let o of e){let r,i,a,d,s=o.coords.split(",").map(p=>parseInt(p,10)),l=o.shape.toLowerCase();if(["rect","rectangle"].includes(l))s.length==4&&([r,a,i,d]=s);else if(["circle","circ"].includes(l)){if(s.length==3){let[p,w,v]=s,u=v/Math.sqrt(2);r=p-u,i=p+u,a=w-u,d=w+u}}else l==="default"?s.length==2&&([r,a,i,d]=[0,0,t.width,t.height]):s.length>=4&&([r,a,i,d]=s);let c=k.translate(k.create(r,a,i,d),t.left,t.top);c=this.cropRectToVisible(c),c&&!isNaN(c.top)&&!isNaN(c.left)&&!isNaN(c.width)&&!isNaN(c.height)&&n.push({element:o,rect:c})}return n},isSelectable(t){if(!(t instanceof Element))return!1;let e=["button","checkbox","color","file","hidden","image","radio","reset","submit"];return t.nodeName.toLowerCase()==="input"&&e.indexOf(t.type)===-1||t.nodeName.toLowerCase()==="textarea"||t.isContentEditable},isEditable(t){return this.isSelectable(t)||(t.nodeName!=null?t.nodeName.toLowerCase():void 0)==="select"},isEmbed(t){let e=t.nodeName!=null?t.nodeName.toLowerCase():null;return["embed","object"].includes(e)},isFocusable(t){return t&&(this.isEditable(t)||this.isEmbed(t))},isDOMDescendant(t,e){let n=e;for(;n!==null;){if(n===t)return!0;n=n.parentNode}return!1},isSelected(t){let e=document.getSelection();if(t.isContentEditable){let n=e.anchorNode;return n&&this.isDOMDescendant(t,n)}else if(f.getSelectionType(e)==="Range"&&e.isCollapsed){let n=e.anchorNode.childNodes[e.anchorOffset];return t===n}else return!1},simulateSelect(t){if(t===document.activeElement&&f.isEditable(document.activeElement))return handlerStack.bubbleEvent("click",{target:t});if(t.focus(),t.tagName.toLowerCase()!=="textarea"||t.value.indexOf(`\n`)<0)try{if(t.selectionStart===0&&t.selectionEnd===0)return t.setSelectionRange(t.value.length,t.value.length)}catch(e){}},simulateClick(t,e){e==null&&(e={});let n=["mouseover","mousedown","mouseup","click"],o=[];for(let r of n){let i=this.simulateMouseEvent(r,t,e);o.push(i)}return o},simulateMouseEvent(t,e,n){if(n==null&&(n={}),t==="mouseout"){if(e==null&&(e=this.lastHoveredElement),this.lastHoveredElement=void 0,e==null)return}else t==="mouseover"&&(this.simulateMouseEvent("mouseout",void 0,n),this.lastHoveredElement=e);let o=new MouseEvent(t,{bubbles:!0,cancelable:!0,composed:!0,view:window,detail:1,ctrlKey:n.ctrlKey,altKey:n.altKey,shiftKey:n.shiftKey,metaKey:n.metaKey});return e.dispatchEvent(o)},simulateClickDefaultAction(t,e){let n;if(e==null&&(e={}),(t.tagName!=null?t.tagName.toLowerCase():void 0)!=="a"||!t.href)return;let{ctrlKey:o,shiftKey:r,metaKey:i,altKey:a}=e;KeyboardUtils.platform==="Mac"?n=i===!0&&o===!1:n=i===!1&&o===!0,n?chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:r===!0}):r===!0&&i===!1&&o===!1&&a===!1?chrome.runtime.sendMessage({handler:"openUrlInNewWindow",url:t.href}):t.target==="_blank"&&chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:!0})},simulateHover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseover",t,e)},simulateUnhover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseout",t,e)},addFlashRect(t){let e=this.createElement("div");return e.classList.add("vimiumReset"),e.classList.add("vimiumFlash"),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.width=t.width+"px",e.style.height=t.height+"px",document.documentElement.appendChild(e),e},getViewportTopLeft(){let t=document.documentElement,e=getComputedStyle(t),n=t.getBoundingClientRect();if(e.position==="static"&&!/content|paint|strict/.test(e.contain||"")){let o=parseInt(e.marginTop),r=parseInt(e.marginLeft);return{top:-n.top+o,left:-n.left+r}}else{let o,r;return N.isFirefox()?(r=parseInt(e.borderTopWidth),o=parseInt(e.borderLeftWidth)):{clientTop:r,clientLeft:o}=t,{top:-n.top-r,left:-n.left-o}}},suppressPropagation(t){t.stopImmediatePropagation()},suppressEvent(t){t.preventDefault(),this.suppressPropagation(t)},consumeKeyup:function(){let t=null;return function(e,n=null,o){if(!e.repeat){t!=null&&handlerStack.remove(t);let{code:r}=e;t=handlerStack.push({_name:"dom_utils/consumeKeyup",keyup(i){return i.code!==r||(this.remove(),o?f.suppressPropagation(i):f.suppressEvent(i)),handlerStack.continueBubbling},blur(i){return i.target===window&&this.remove(),handlerStack.continueBubbling}})}return typeof n=="function"&&n(),o?(f.suppressPropagation(e),handlerStack.suppressPropagation):(f.suppressEvent(e),handlerStack.suppressEvent)}}(),getSelectionType(t){return t==null&&(t=document.getSelection()),t.type?t.type:t.rangeCount===0?"None":t.isCollapsed?"Caret":"Range"},getElementWithFocus(t,e){let n,o=n=t.getRangeAt(0);f.getSelectionType(t)==="Range"&&(o=n.cloneRange(),o.collapse(e)),n=o.startContainer,n.nodeType===1&&(n=n.childNodes[o.startOffset]);let r=n;for(;r&&r.nodeType!==1;)r=r.previousSibling;return n=r||(n!=null?n.parentNode:void 0),n},getSelectionFocusElement(){let t=window.getSelection(),e=t.focusNode;return e==null?null:(e===t.anchorNode&&t.focusOffset===t.anchorOffset&&(e=e.childNodes[t.focusOffset]||e),e.nodeType!==Node.ELEMENT_NODE?e.parentElement:e)},getContainingElement(t){return(typeof t.getDestinationInsertionPoints=="function"?t.getDestinationInsertionPoints()[0]:void 0)||t.parentElement},windowIsTooSmall(){return window.innerWidth<3||window.innerHeight<3},injectUserCss(){let t=document.createElement("style");t.type="text/css",t.textContent=Settings.get("userDefinedLinkHintCss"),document.head.appendChild(t)}};var O={MAX_CONTENT_LENGTH:1e3,MAX_ATTRIBUTE_LENGTH:500,MAX_NUM_DATA_ATTRIBUTES:10,commonAttributes:["id","className","title","aria-label","aria-labelledby"],attributeNamesMapping:new Map([["a",["href","title","rel","target"]],["label",["for"]],["input",["type","name","placeholder","checked","maximumLength"]],["textarea",["placeholder","maximumLength"]],["button",["type"]],["select",["name","multiple"]],["div",["role"]],["iframe",["src"]],["img",["src","alt"]]]),describe(t){var r,i;let e={};this.addAttributes(t,this.commonAttributes,e);let n=((i=(r=t.tagName).toLowerCase)==null?void 0:i.call(r))||"";this.attributeNamesMapping.has(n)&&this.addAttributes(t,this.attributeNamesMapping.get(n),e),this.addDataAttrs(t,e);let o=this.getContent(t);return this.additionalHandling(t,D({tag:n,attributes:e},o&&{content:o}))},getContent(t){var n,o;let e=((o=(n=t.tagName).toLowerCase)==null?void 0:o.call(n))||"";return["input","textarea"].includes(e)?t.value:["div","iframe","img","body"].includes(e)?null:(["a","button","select","label"].includes(e),t.innerText)},additionalHandling(t,e){var o,r;if((((r=(o=t.tagName).toLowerCase)==null?void 0:r.call(o))||"")=="label"&&t.hasAttribute("for")){let i=t.getAttribute("for"),a=document.getElementById(i);a&&(e.target=this.describe(a))}return e},addAttributes(t,e,n){n||(n={});for(let o of e)t.hasAttribute(o)&&(n[o]=t.getAttribute(o).substring(0,this.MAX_ATTRIBUTE_LENGTH));return n},addDataAttrs(t,e){let n=0;for(let o in t.dataset)if(e[`data-${o}`]=t.dataset[o].substring(0,this.MAX_ATTRIBUTE_LENGTH),n++,n>this.MAX_NUM_DATA_ATTRIBUTES)return e;return e}};var x=null,C=()=>G()||document.scrollingElement||document.body,W=function(t){return t?t<0?-1:1:0},U={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},X=function(t,e,n){if(N.isString(n)){let o=n;return o==="viewSize"&&t===C()?e==="x"?window.innerWidth:window.innerHeight:t[U[e][o]]}else return n},V=function(t,e,n){let o=U[e].axisName,r=t[o];if(t.scrollBy){let i={behavior:"instant"};i[e==="x"?"left":"top"]=n,t.scrollBy(i)}else t[o]+=n;return t[o]!==r},q=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},T=function(t,e,n,o){let r=o*X(t,e,n)||-1;return r=W(r),V(t,e,r)&&V(t,e,-r)},$=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),T(t,e,n,o)&&q(t,e)},j=function(t=null){let e;if(!t){let n=C();if(T(n,"y",1,1)||T(n,"y",-1,1))return n;t=document.body||C()}if(T(t,"y",1,1)||T(t,"y",-1,1))return t;{let n=Array.from(t.children).map(o=>({element:o,rect:f.getVisibleClientRect(o)})).filter(o=>o.rect);n.map(o=>o.area=o.rect.width*o.rect.height);for(e of n.sort((o,r)=>r.area-o.area)){let o=j(e.element);if(o)return o}return null}},L={init(){x=null},isScrollableElement(t){return x||(x=C()&&j()||C()),t!==x&&$(t)}},G=function(){let t=J[window.location.host];if(t)return document.querySelector(t)},J={"twitter.com":"div.permalink-container div.permalink[role=main]","reddit.com":"#overlayScrollContainer","new.reddit.com":"#overlayScrollContainer","www.reddit.com":"#overlayScrollContainer","web.telegram.org":".MessageList"};window.Scroller=L;var A=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",E(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",E(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:A});var R=class{constructor(e){g(this,"element");g(this,"image");g(this,"rect");g(this,"linkText");g(this,"showLinkText");g(this,"reason");g(this,"secondClassCitizen");g(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},M={getLocalHintsForElement(t){var p,w,v;let e=((w=(p=t.tagName).toLowerCase)==null?void 0:w.call(p))||"",n=!1,o=!1,r=!1,i=[],a=[],d=null;if(e==="img"){let u=t.getAttribute("usemap");if(u){let h=t.getClientRects();u=u.replace(/^#/,"").replace(\'"\',\'\\\\"\');let m=document.querySelector(`map[name="${u}"]`);if(m&&h.length>0){n=!0;let y=m.getElementsByTagName("area"),S=f.getClientRectsForAreas(h[0],y);S=S.map(I=>Object.assign(I,{image:t})),a.push(...S)}}}let s=t.getAttribute("aria-disabled");if(s&&["","true"].includes(s.toLowerCase()))return[];if(this.checkForAngularJs||(this.checkForAngularJs=function(){if(document.getElementsByClassName("ng-scope").length===0)return()=>!1;{let h=[];for(let m of["","data-","x-"])for(let y of["-",":","_"])h.push(`${m}ng${y}click`);return function(m){for(let y of h)if(m.hasAttribute(y))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let u=t.getAttribute("role"),h=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(u!=null&&h.includes(u.toLowerCase()))n=!0;else{let m=t.getAttribute("contentEditable");m!=null&&["","contenteditable","true","plaintext-only"].includes(m.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let u=t.getAttribute("jsaction").split(";");for(let h of u){let m=h.trim().split(":");if(m.length>=1&&m.length<=2){let[y,S,I]=m.length===1?["click",...m[0].trim().split("."),"_"]:[m[0],...m[1].trim().split("."),"_"];n||(n=y==="click"&&S!=="none"&&I!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||(n=!t.disabled&&!t.readOnly);break;case"input":n||(n=!(((v=t.getAttribute("type"))==null?void 0:v.toLowerCase())=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t)));break;case"button":case"select":n||(n=!t.disabled);break;case"object":case"embed":n=!0;break;case"label":n||(n=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0);break;case"body":n||(n=t===document.body&&!A()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?d="Frame.":void 0),n||(n=t===document.body&&A()&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"img":n||(n=["zoom-in","zoom-out"].includes(t.style.cursor));break;case"div":case"ol":case"ul":n||(n=t.clientHeight<t.scrollHeight&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"details":n=!0,d="Open.";break}let l=t.getAttribute("class");!n&&(l!=null&&l.toLowerCase().includes("button"))&&(n=!0,r=!0);let c=t.getAttribute("tabindex"),b=c?parseInt(c):-1;if(!n&&!(b<0)&&!isNaN(b)&&(n=!0,o=!0),n)if(a.length>0){let u=a.map(h=>new R({element:h.element,image:t,rect:h.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:d}));i.push(...u)}else{let u=f.getVisibleClientRect(t,!0);if(u!==null){let h=new R({element:t,rect:u,secondClassCitizen:o,possibleFalsePositive:r,reason:d});i.push(h)}}return i},getElementFromPoint(t,e,n,o){n==null&&(n=document),o==null&&(o=[]);let r=n.elementsFromPoint?n.elementsFromPoint(t,e)[0]:n.elementFromPoint(t,e);return o.includes(r)?r:(o.push(r),r&&r.shadowRoot?M.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,l)=>{l==null&&(l=[]);for(let c of Array.from(s.querySelectorAll("*")))l.push(c),c.shadowRoot&&e(c.shadowRoot,l);return l},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let l=this.getLocalHintsForElement(s);o.push(...l)}o=o.reverse();let r=[1,2,3];o=o.filter((s,l)=>{if(!s.possibleFalsePositive)return!0;let b=Math.max(0,l-6);for(;b<l;){let p=o[b].element;for(let w of r)if(p=p==null?void 0:p.parentElement,p===s.element)return!1;b+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let l=s.rect,c=M.getElementFromPoint(l.left+l.width*.5,l.top+l.height*.5);if(c&&(s.element.contains(c)||c.contains(s.element))||s.element.localName=="area"&&c==s.image)return!0;let p=[l.top+.1,l.bottom-.1],w=[l.left+.1,l.right-.1];for(let v of p)for(let u of w){let h=M.getElementFromPoint(u,v);if(h&&(s.element.contains(h)||h.contains(s.element)))return!0}});i.reverse();let{top:a,left:d}=f.getViewportTopLeft();for(let s of i)s.rect.top+=a,s.rect.left+=d;return i}};var H=class{constructor(){this.hints=null;this.hintMarkers=null;this.markersDiv=null;this.enrichedMarkers=null}reset(){this.removeMarkers(),this.hints=null,this.hintMarkers=null,this.markersDiv=null}capture(){return _(this,null,function*(){this.reset(),this.createMarkers(),this.displayMarkers()})}createMarkers(){this.hints=M.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{var i,a;let o=f.createElement("div"),r=(a=(i=e.element.attributes["data-momentic-id"])==null?void 0:i.value)!=null?a:void 0;if(!r){console.warn(`[MOMENTIC] No data-momentic-id found for interactive element ${e.element.outerHTML}`);return}o.style.left=e.rect.left+"px",o.style.top=e.rect.top+"px",o.style.zIndex=214e7+n,o.className="vimiumReset internalVimiumHintMarker vimiumHintMarker",Z(o,r),this.hintMarkers.set(r,{hint:e,marker:o})})}enrichMarkers(){if(this.hintMarkers){this.enrichedMarkers=[];for(let[e,n]of this.hintMarkers)this.enrichedMarkers.push(Object.assign(O.describe(n.hint.element),{hintString:e}))}}displayMarkers(){this.hintMarkers&&(this.markersDiv||(this.markersDiv=f.addElementsToPage(Array.from(this.hintMarkers.values()).map(e=>e.marker),{id:"vimiumHintMarkerContainer",className:"vimiumReset"})))}removeMarkers(){this.markersDiv&&(f.removeElement(this.markersDiv),this.markersDiv=null)}toggleMarkers(){this.markersDiv?this.removeMarkers():this.displayMarkers()}},Z=(t,e)=>{for(let n of e){let o=document.createElement("span");o.className="vimiumReset",o.textContent=n,t.appendChild(o)}};window.HintManager=H;\n',vimiumCss:'.vimiumReset,a.vimiumReset,a:hover.vimiumReset,a:link.vimiumReset,a:visited.vimiumReset,div.vimiumReset,span.vimiumReset,table.vimiumReset,td.vimiumReset,tr.vimiumReset{background:none;border:none;bottom:auto;box-shadow:none;color:#000;cursor:auto;display:inline;float:none;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:inherit;font-style:normal;font-variant:normal;font-weight:400;height:auto;left:auto;letter-spacing:0;line-height:100%;margin:0;max-height:none;max-width:none;min-height:0;min-width:0;opacity:1;padding:0;position:static;right:auto;text-align:left;text-decoration:none;text-indent:0;text-shadow:none;text-transform:none;top:auto;vertical-align:baseline;white-space:normal;width:auto;z-index:2140000000}tbody.vimiumReset,thead.vimiumReset{display:table-header-group}tbody.vimiumReset{display:table-row-group}div.internalVimiumHintMarker{background:linear-gradient(180deg,#fff785 0,#ffc542);border:1px solid #c38a22;border-radius:3px;box-shadow:0 3px 7px 0 rgba(0,0,0,.3);display:block;font-size:11px;left:-1px;overflow:hidden;padding:1px 3px 0;position:absolute;top:-1px;white-space:nowrap}div.internalVimiumHintMarker span{color:#302505;font-family:Helvetica,Arial,sans-serif;font-size:11px;font-weight:700;text-shadow:0 1px 0 hsla(0,0%,100%,.6)}div.internalVimiumHintMarker>.matchingCharacter{color:#d4ac3a}div>.vimiumActiveHintMarker span{color:#a07555!important}div.internalVimiumInputHint{background-color:rgba(255,247,133,.3);border:1px solid #c38a22;display:block;pointer-events:none;position:absolute}div.internalVimiumSelectedInputHint{background-color:hsla(0,100%,70%,.3);border:1px solid #933!important}div.internalVimiumSelectedInputHint span{color:#fff!important}div.vimiumHighlightedFrame{border:5px solid #ff0;box-sizing:border-box;margin:0;pointer-events:none}div.vimiumHighlightedFrame,iframe.vimiumHelpDialogFrame{height:100%;left:0;padding:0;position:fixed;top:0;width:100%}iframe.vimiumHelpDialogFrame{background-color:hsla(0,0%,4%,.6);border:none;display:block;z-index:2139999997}div#vimiumHelpDialogContainer{background-color:#fff;border:2px solid #b3b3b3;border-radius:6px;margin:50px auto;max-height:calc(100% - 100px);max-width:calc(100% - 100px);opacity:1;overflow-x:auto;overflow-y:auto;width:840px}div#vimiumHelpDialog{min-width:600px;padding:8px 12px}span#vimiumTitle,span#vimiumTitle *,span#vimiumTitle span{font-size:20px}#vimiumTitle{display:block;line-height:130%;white-space:nowrap}td.vimiumHelpDialogTopButtons{text-align:right;width:100%}#helpDialogOptionsPage,#helpDialogWikiPage{font-size:14px;padding-left:5px;padding-right:5px}div.vimiumColumn{float:left;font-size:11px;line-height:130%;width:50%}div.vimiumColumn tr{display:table-row}div.vimiumColumn td{display:table-cell;font-size:11px;line-height:130%}div.vimiumColumn table,div.vimiumColumn td,div.vimiumColumn tr{margin:0;padding:0}div.vimiumColumn table{table-layout:auto;width:100%}div.vimiumColumn td{padding:1px;vertical-align:top}div#vimiumHelpDialog div.vimiumColumn tr>td:first-of-type{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;text-align:right;white-space:nowrap}span.vimiumHelpDialogKey{background-color:#f3f3f3;border:1px solid;border-color:#ccc #ccc #bbb;border-radius:3px;box-shadow:inset 0 -1px 0 #bbb;color:#212121;font-family:monospace;font-size:11px;margin-left:2px;padding:1px 4px}div#vimiumHelpDialog div.vimiumColumn tr>td:nth-of-type(3){width:100%}div#vimiumHelpDialog div.vimiumDivider{background-color:#9a9a9a;display:block;height:1px;margin:10px auto;width:100%}div#vimiumHelpDialog td.vimiumHelpSectionTitle{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:16px;font-weight:700;padding-top:3px}div#vimiumHelpDialog td.vimiumHelpDescription{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px}div#vimiumHelpDialog span.vimiumCopyCommandNameName{cursor:pointer;font-size:12px;font-style:italic}div#vimiumHelpDialog tr.advanced{display:none}div#vimiumHelpDialog.showAdvanced tr.advanced{display:table-row}div#vimiumHelpDialog div.advanced td:nth-of-type(3){color:#555}div#vimiumHelpDialog a.closeButton{color:#555;cursor:pointer;font-family:courier new;font-size:24px;font-weight:700;padding-left:5px;position:relative;text-decoration:none;top:3px}div#vimiumHelpDialog a{text-decoration:underline}div#vimiumHelpDialog a.closeButton:hover{color:#000;-webkit-user-select:none}div#vimiumHelpDialogFooter{display:block;margin-bottom:37px;position:relative}table.helpDialogBottom{width:100%}td.helpDialogBottomRight{float:right;text-align:right;width:100%}td.helpDialogBottomLeft,td.helpDialogBottomRight{padding:0}div#vimiumHelpDialogFooter *{font-size:10px}a#toggleAdvancedCommands,span#help-dialog-tip{font-size:10px;position:relative;top:19px;white-space:nowrap}a#toggleAdvancedCommands,a:active.vimiumHelDialogLink,a:hover.vimiumHelDialogLink,a:link.vimiumHelDialogLink,a:visited.vimiumHelDialogLink{color:#2f508e;cursor:pointer;text-decoration:underline}div.vimiumHUD{background:#f1f1f1;border:1px solid #aaa;border-radius:4px;bottom:8px;box-shadow:0 2px 10px rgba(0,0,0,.8);display:block;left:8px;position:fixed;text-align:left;width:calc(100% - 20px);z-index:2139999999}iframe.vimiumHUDFrame{background-color:transparent;border:none;bottom:-14px;display:block;height:58px;margin:0 0 0 -40%;min-width:300px;opacity:0;overflow:hidden;padding:0;position:fixed;right:20px;width:20%;z-index:2139999998}div.vimiumHUD .vimiumHUDSearchArea{background-color:#f1f1f1;border-radius:4px 4px 0 0;display:block;padding:3px}div.vimiumHUD .vimiumHUDSearchAreaInner{border-radius:3px;box-sizing:border-box;color:#777;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;height:30px;line-height:20px;margin-bottom:0;outline:none;padding:2px 4px;width:100%}div.vimiumHUD .hud-find{background:#fff;border:1px solid #ccc}div.vimiumHUD span#hud-find-input,div.vimiumHUD span#hud-match-count{color:#000;display:inline;outline:none;overflow-y:hidden;white-space:nowrap}div.vimiumHUD span#hud-find-input:before{content:"/"}div.vimiumHUD span#hud-match-count{color:#aaa;font-size:12px}div.vimiumHUD span#hud-find-input br{display:none}div.vimiumHUD span#hud-find-input *{display:inline;white-space:nowrap}body.vimiumFindMode ::selection{background:#ff9632}iframe.vomnibarFrame{background-color:transparent;border:none;display:block;font-family:sans-serif;height:calc(100% - 70px);left:50%;margin:0 0 0 -40%;min-width:400px;overflow:hidden;padding:0;position:fixed;top:70px;width:calc(80% + 20px);z-index:2139999998}div.vimiumFlash{background-color:transparent;box-shadow:0 0 4px 2px #4183c4;padding:1px;position:absolute;z-index:2140000000}iframe.vimiumUIComponentHidden{display:none}iframe.vimiumUIComponentVisible{color-scheme:light dark;display:block}iframe.vimiumUIComponentReactivated{border:5px solid #ff0}iframe.vimiumNonClickable{pointer-events:none}@media (prefers-color-scheme:dark){iframe.reverseDarkReaderFilter{-webkit-filter:invert(100%) hue-rotate(180deg)!important;filter:invert(100%) hue-rotate(180deg)!important}body.vimiumBody{background-color:#292a2d;color:#fff}body.vimiumBody a,body.vimiumBody a:visited{color:#8ab4f8}body.vimiumBody input,body.vimiumBody textarea{background-color:#1d1d1f;border-color:#1d1d1f;color:#e8eaed}body.vimiumBody div.example{color:#9aa0a6}body.vimiumBody div#footer,body.vimiumBody div#state,div#vimiumHelpDialogContainer{background-color:#202124;border-color:hsla(0,0%,100%,.1)}div#vimiumHelpDialog{background-color:#292a2d;color:#fff}div#vimiumHelpDialog td.vimiumHelpDescription{color:#c9cccf}div#vimiumHelpDialog td.vimiumHelpSectionTitle,span#vimiumTitle{color:#fff}#vimiumTitle>span:first-child{color:#8ab4f8!important}div#vimiumHelpDialog a{color:#8ab4f8}div#vimiumHelpDialog div.vimiumDivider{background-color:hsla(0,0%,100%,.1)}span.vimiumHelpDialogKey{background-color:#1d1d1f;border:1px solid #000;box-shadow:none;color:#fff}}',htmlUtilsLibJs:`var __defProp = Object.defineProperty;
|
|
14
14
|
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
15
15
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
16
16
|
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
@@ -1978,7 +1978,7 @@ Available pages:${JSON.stringify(n)}`);if(!Rr(o.url,this.logger)){this.logger.er
|
|
|
1978
1978
|
`)}catch(s){throw new Error(`Could not read test file ${t}: ${s}`)}let o;try{o=uo.parse(n)}catch(s){throw new Error(`Could not parse test file ${t} as YAML: ${s}`)}return Ne.parse(o)}async function ri(r,e,t){let n=t.project.rootDir,o;try{o=Xt.readFileSync(r,"utf-8")}catch(l){throw e.error({err:l,projectRoot:n},l.message),new Error(l.message)}let s=uo.parse(o);if(!s.steps||!Array.isArray(s.steps))throw new Error(`Test ${r} is missing steps`);let i;try{i=Ne.parse(s)}catch(l){throw new Error(`Test ${r} is missing metadata or has invalid metadata: ${l}`)}let{resolvedTest:a}=await Mu({rawSteps:s.steps,metadata:i,logger:e,callbacks:{onFetchModule:async({id:l,logger:c})=>{let u=t.modules[l]?.fullFilePath;if(u)return ei(u,c)}}});return a}import VT from"@dotenvx/dotenvx";import qT from"fs";import Tp from"path";function Ep(r,e){return(r.config.environments??[]).map(t=>po(t.name,r,e))}function KT(r){return r.includes("${")?r.replace(/\$\{([^}]+)\}/g,(e,t)=>{let[n,o]=t.split(/:-|-/,2),s=process.env[n];return t.includes(":-")?s&&s!==""?s:o||"":t.includes("-")?s!==void 0?s:o||"":s||""}):r}function po(r,e,t){let n=(e.config.environments??[]).find(i=>i.name===r);if(!n)throw new Error(`Environment ${r} not found in local project configuration file`);let o={[oe]:n.baseUrl};if(n.envVariables){let i={};for(let[a,l]of Object.entries(n.envVariables))if(typeof l=="string"){let c=KT(l);c&&(i[a]=c)}else{let c=l.fromFile,u;try{u=qT.readFileSync(Tp.resolve(e.rootDir,c),"utf-8")}catch(d){throw new Error(`Failed to read environment variable '${a}' from file '${c}': ${d}`)}if(l.json)try{i[a]=JSON.parse(u)}catch(d){throw new Error(`Failed to parse environment variable '${a}' from file '${c}' as JSON: ${d}`)}else i[a]=u}t.debug(i,"Set environment variables with interpolation from project configuration"),Object.assign(o,i)}if(n.envFile){let i={},a=VT.config({path:Tp.resolve(e.rootDir,n.envFile),processEnv:i,logLevel:"error",quiet:!0});if(a.error)throw new Error(`Failed to load .env file: ${a.error.message}`);t.debug(i,"Set environment variables from .env file"),Object.assign(o,i)}return n.inheritFromShell&&(t.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:r,variables:o,browser:n.browser}}import{existsSync as AC,readFileSync as xC,readdirSync as RC,writeFileSync as IC}from"fs";var jp=jf(kp(),1);var fo=r=>{if(typeof r!="string")throw new TypeError("invalid pattern");if(r.length>65536)throw new TypeError("pattern is too long")};var rE={"[: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]},go=r=>r.replace(/[[\]\\-]/g,"\\$&"),nE=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Dp=r=>r.join(""),Fp=(r,e)=>{let t=e;if(r.charAt(t)!=="[")throw new Error("not in a brace expression");let n=[],o=[],s=t+1,i=!1,a=!1,l=!1,c=!1,u=t,d="";e:for(;s<r.length;){let f=r.charAt(s);if((f==="!"||f==="^")&&s===t+1){c=!0,s++;continue}if(f==="]"&&i&&!l){u=s+1;break}if(i=!0,f==="\\"&&!l){l=!0,s++;continue}if(f==="["&&!l){for(let[g,[y,S,w]]of Object.entries(rE))if(r.startsWith(g,s)){if(d)return["$.",!1,r.length-t,!0];s+=g.length,w?o.push(y):n.push(y),a=a||S;continue e}}if(l=!1,d){f>d?n.push(go(d)+"-"+go(f)):f===d&&n.push(go(f)),d="",s++;continue}if(r.startsWith("-]",s+1)){n.push(go(f+"-")),s+=2;continue}if(r.startsWith("-",s+1)){d=f,s+=2;continue}n.push(go(f)),s++}if(u<s)return["",!1,0,!1];if(!n.length&&!o.length)return["$.",!1,r.length-t,!0];if(o.length===0&&n.length===1&&/^\\?.$/.test(n[0])&&!c){let f=n[0].length===2?n[0].slice(-1):n[0];return[nE(f),!1,u-t,!1]}let m="["+(c?"^":"")+Dp(n)+"]",p="["+(c?"":"^")+Dp(o)+"]";return[n.length&&o.length?"("+m+"|"+p+")":n.length?m:p,a,u-t,!0]};var wt=(r,{windowsPathsNoEscape:e=!1}={})=>e?r.replace(/\[([^\/\\])\]/g,"$1"):r.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var oE=new Set(["!","?","+","*","@"]),Up=r=>oE.has(r),sE="(?!(?:^|/)\\.\\.?(?:$|/))",ni="(?!\\.)",iE=new Set(["[","."]),aE=new Set(["..","."]),lE=new Set("().*{}+?[]^$\\!"),cE=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),dl="[^/]",$p=dl+"*?",Bp=dl+"+?",mn=class r{type;#e;#t;#s=!1;#n=[];#i;#b;#c;#u=!1;#a;#l;#o=!1;constructor(e,t,n={}){this.type=e,e&&(this.#t=!0),this.#i=t,this.#e=this.#i?this.#i.#e:this,this.#a=this.#e===this?n:this.#e.#a,this.#c=this.#e===this?[]:this.#e.#c,e==="!"&&!this.#e.#u&&this.#c.push(this),this.#b=this.#i?this.#i.#n.length:0}get hasMagic(){if(this.#t!==void 0)return this.#t;for(let e of this.#n)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.#n.map(e=>String(e)).join("|")+")":this.#l=this.#n.map(e=>String(e)).join("")}#g(){if(this!==this.#e)throw new Error("should only call on root");if(this.#u)return this;this.toString(),this.#u=!0;let e;for(;e=this.#c.pop();){if(e.type!=="!")continue;let t=e,n=t.#i;for(;n;){for(let o=t.#b+1;!n.type&&o<n.#n.length;o++)for(let s of e.#n){if(typeof s=="string")throw new Error("string part in extglob AST??");s.copyIn(n.#n[o])}t=n,n=t.#i}}return this}push(...e){for(let t of e)if(t!==""){if(typeof t!="string"&&!(t instanceof r&&t.#i===this))throw new Error("invalid part: "+t);this.#n.push(t)}}toJSON(){let e=this.type===null?this.#n.slice().map(t=>typeof t=="string"?t:t.toJSON()):[this.type,...this.#n.map(t=>t.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===this.#e||this.#e.#u&&this.#i?.type==="!")&&e.push({}),e}isStart(){if(this.#e===this)return!0;if(!this.#i?.isStart())return!1;if(this.#b===0)return!0;let e=this.#i;for(let t=0;t<this.#b;t++){let n=e.#n[t];if(!(n instanceof r&&n.type==="!"))return!1}return!0}isEnd(){if(this.#e===this||this.#i?.type==="!")return!0;if(!this.#i?.isEnd())return!1;if(!this.type)return this.#i?.isEnd();let e=this.#i?this.#i.#n.length:0;return this.#b===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let t=new r(this.type,e);for(let n of this.#n)t.copyIn(n);return t}static#y(e,t,n,o){let s=!1,i=!1,a=-1,l=!1;if(t.type===null){let p=n,h="";for(;p<e.length;){let f=e.charAt(p++);if(s||f==="\\"){s=!s,h+=f;continue}if(i){p===a+1?(f==="^"||f==="!")&&(l=!0):f==="]"&&!(p===a+2&&l)&&(i=!1),h+=f;continue}else if(f==="["){i=!0,a=p,l=!1,h+=f;continue}if(!o.noext&&Up(f)&&e.charAt(p)==="("){t.push(h),h="";let g=new r(f,t);p=r.#y(e,g,p,o),t.push(g);continue}h+=f}return t.push(h),p}let c=n+1,u=new r(null,t),d=[],m="";for(;c<e.length;){let p=e.charAt(c++);if(s||p==="\\"){s=!s,m+=p;continue}if(i){c===a+1?(p==="^"||p==="!")&&(l=!0):p==="]"&&!(c===a+2&&l)&&(i=!1),m+=p;continue}else if(p==="["){i=!0,a=c,l=!1,m+=p;continue}if(Up(p)&&e.charAt(c)==="("){u.push(m),m="";let h=new r(p,u);u.push(h),c=r.#y(e,h,c,o);continue}if(p==="|"){u.push(m),m="",d.push(u),u=new r(null,t);continue}if(p===")")return m===""&&t.#n.length===0&&(t.#o=!0),u.push(m),m="",t.push(...d,u),c;m+=p}return t.type=null,t.#t=void 0,t.#n=[e.substring(n-1)],c}static fromGlob(e,t={}){let n=new r(null,void 0,t);return r.#y(e,n,0,t),n}toMMPattern(){if(this!==this.#e)return this.#e.toMMPattern();let e=this.toString(),[t,n,o,s]=this.toRegExpSource();if(!(o||this.#t||this.#a.nocase&&!this.#a.nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return n;let a=(this.#a.nocase?"i":"")+(s?"u":"");return Object.assign(new RegExp(`^${t}$`,a),{_src:t,_glob:e})}get options(){return this.#a}toRegExpSource(e){let t=e??!!this.#a.dot;if(this.#e===this&&this.#g(),!this.type){let l=this.isStart()&&this.isEnd(),c=this.#n.map(p=>{let[h,f,g,y]=typeof p=="string"?r.#m(p,this.#t,l):p.toRegExpSource(e);return this.#t=this.#t||g,this.#s=this.#s||y,h}).join(""),u="";if(this.isStart()&&typeof this.#n[0]=="string"&&!(this.#n.length===1&&aE.has(this.#n[0]))){let h=iE,f=t&&h.has(c.charAt(0))||c.startsWith("\\.")&&h.has(c.charAt(2))||c.startsWith("\\.\\.")&&h.has(c.charAt(4)),g=!t&&!e&&h.has(c.charAt(0));u=f?sE:g?ni:""}let d="";return this.isEnd()&&this.#e.#u&&this.#i?.type==="!"&&(d="(?:$|\\/)"),[u+c+d,wt(c),this.#t=!!this.#t,this.#s]}let n=this.type==="*"||this.type==="+",o=this.type==="!"?"(?:(?!(?:":"(?:",s=this.#p(t);if(this.isStart()&&this.isEnd()&&!s&&this.type!=="!"){let l=this.toString();return this.#n=[l],this.type=null,this.#t=void 0,[l,wt(this.toString()),!1,!1]}let i=!n||e||t||!ni?"":this.#p(!0);i===s&&(i=""),i&&(s=`(?:${s})(?:${i})*?`);let a="";if(this.type==="!"&&this.#o)a=(this.isStart()&&!t?ni:"")+Bp;else{let l=this.type==="!"?"))"+(this.isStart()&&!t&&!e?ni:"")+$p+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&i?")":this.type==="*"&&i?")?":`)${this.type}`;a=o+s+l}return[a,wt(s),this.#t=!!this.#t,this.#s]}#p(e){return this.#n.map(t=>{if(typeof t=="string")throw new Error("string type in extglob ast??");let[n,o,s,i]=t.toRegExpSource(e);return this.#s=this.#s||i,n}).filter(t=>!(this.isStart()&&this.isEnd())||!!t).join("|")}static#m(e,t,n=!1){let o=!1,s="",i=!1;for(let a=0;a<e.length;a++){let l=e.charAt(a);if(o){o=!1,s+=(lE.has(l)?"\\":"")+l;continue}if(l==="\\"){a===e.length-1?s+="\\\\":o=!0;continue}if(l==="["){let[c,u,d,m]=Fp(e,a);if(d){s+=c,i=i||u,a+=d-1,t=t||m;continue}}if(l==="*"){n&&e==="*"?s+=Bp:s+=$p,t=!0;continue}if(l==="?"){s+=dl,t=!0;continue}s+=cE(l)}return[s,wt(e),!!t,i]}};var pn=(r,{windowsPathsNoEscape:e=!1}={})=>e?r.replace(/[?*()[\]]/g,"[$&]"):r.replace(/[?*()[\]\\]/g,"\\$&");var We=(r,e,t={})=>(fo(e),!t.nocomment&&e.charAt(0)==="#"?!1:new Qe(e,t).match(r)),dE=/^\*+([^+@!?\*\[\(]*)$/,uE=r=>e=>!e.startsWith(".")&&e.endsWith(r),mE=r=>e=>e.endsWith(r),pE=r=>(r=r.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(r)),hE=r=>(r=r.toLowerCase(),e=>e.toLowerCase().endsWith(r)),fE=/^\*+\.\*+$/,gE=r=>!r.startsWith(".")&&r.includes("."),yE=r=>r!=="."&&r!==".."&&r.includes("."),SE=/^\.\*+$/,wE=r=>r!=="."&&r!==".."&&r.startsWith("."),bE=/^\*+$/,TE=r=>r.length!==0&&!r.startsWith("."),EE=r=>r.length!==0&&r!=="."&&r!=="..",CE=/^\?+([^+@!?\*\[\(]*)?$/,vE=([r,e=""])=>{let t=Hp([r]);return e?(e=e.toLowerCase(),n=>t(n)&&n.toLowerCase().endsWith(e)):t},AE=([r,e=""])=>{let t=Gp([r]);return e?(e=e.toLowerCase(),n=>t(n)&&n.toLowerCase().endsWith(e)):t},xE=([r,e=""])=>{let t=Gp([r]);return e?n=>t(n)&&n.endsWith(e):t},RE=([r,e=""])=>{let t=Hp([r]);return e?n=>t(n)&&n.endsWith(e):t},Hp=([r])=>{let e=r.length;return t=>t.length===e&&!t.startsWith(".")},Gp=([r])=>{let e=r.length;return t=>t.length===e&&t!=="."&&t!==".."},Vp=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",zp={win32:{sep:"\\"},posix:{sep:"/"}},IE=Vp==="win32"?zp.win32.sep:zp.posix.sep;We.sep=IE;var ve=Symbol("globstar **");We.GLOBSTAR=ve;var PE="[^/]",OE=PE+"*?",LE="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",ME="(?:(?!(?:\\/|^)\\.).)*?",NE=(r,e={})=>t=>We(t,r,e);We.filter=NE;var ut=(r,e={})=>Object.assign({},r,e),_E=r=>{if(!r||typeof r!="object"||!Object.keys(r).length)return We;let e=We;return Object.assign((n,o,s={})=>e(n,o,ut(r,s)),{Minimatch:class extends e.Minimatch{constructor(o,s={}){super(o,ut(r,s))}static defaults(o){return e.defaults(ut(r,o)).Minimatch}},AST:class extends e.AST{constructor(o,s,i={}){super(o,s,ut(r,i))}static fromGlob(o,s={}){return e.AST.fromGlob(o,ut(r,s))}},unescape:(n,o={})=>e.unescape(n,ut(r,o)),escape:(n,o={})=>e.escape(n,ut(r,o)),filter:(n,o={})=>e.filter(n,ut(r,o)),defaults:n=>e.defaults(ut(r,n)),makeRe:(n,o={})=>e.makeRe(n,ut(r,o)),braceExpand:(n,o={})=>e.braceExpand(n,ut(r,o)),match:(n,o,s={})=>e.match(n,o,ut(r,s)),sep:e.sep,GLOBSTAR:ve})};We.defaults=_E;var qp=(r,e={})=>(fo(r),e.nobrace||!/\{(?:(?!\{).)*\}/.test(r)?[r]:(0,jp.default)(r));We.braceExpand=qp;var kE=(r,e={})=>new Qe(r,e).makeRe();We.makeRe=kE;var DE=(r,e,t={})=>{let n=new Qe(e,t);return r=r.filter(o=>n.match(o)),n.options.nonull&&!r.length&&r.push(e),r};We.match=DE;var Wp=/[?*]|[+@!]\(.*?\)|\[|\]/,FE=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),Qe=class{options;set;pattern;windowsPathsNoEscape;nonegate;negate;comment;empty;preserveMultipleSlashes;partial;globSet;globParts;nocase;isWindows;platform;windowsNoMagicRoot;regexp;constructor(e,t={}){fo(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||Vp,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=(...s)=>console.error(...s)),this.debug(this.pattern,this.globSet);let n=this.globSet.map(s=>this.slashSplit(s));this.globParts=this.preprocess(n),this.debug(this.pattern,this.globParts);let o=this.globParts.map((s,i,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let l=s[0]===""&&s[1]===""&&(s[2]==="?"||!Wp.test(s[2]))&&!Wp.test(s[3]),c=/^[a-z]:/i.test(s[0]);if(l)return[...s.slice(0,4),...s.slice(4).map(u=>this.parse(u))];if(c)return[s[0],...s.slice(1).map(u=>this.parse(u))]}return s.map(l=>this.parse(l))});if(this.debug(this.pattern,o),this.set=o.filter(s=>s.indexOf(!1)===-1),this.isWindows)for(let s=0;s<this.set.length;s++){let i=this.set[s];i[0]===""&&i[1]===""&&this.globParts[s][2]==="?"&&typeof i[3]=="string"&&/^[a-z]:$/i.test(i[3])&&(i[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let n=0;n<e.length;n++)for(let o=0;o<e[n].length;o++)e[n][o]==="**"&&(e[n][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 n=-1;for(;(n=t.indexOf("**",n+1))!==-1;){let o=n;for(;t[o+1]==="**";)o++;o!==n&&t.splice(n,o-n)}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((n,o)=>{let s=n[n.length-1];return o==="**"&&s==="**"?n:o===".."&&s&&s!==".."&&s!=="."&&s!=="**"?(n.pop(),n):(n.push(o),n)},[]),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 s=e[o];o===1&&s===""&&e[0]===""||(s==="."||s==="")&&(t=!0,e.splice(o,1),o--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=!0,e.pop())}let n=0;for(;(n=e.indexOf("..",n+1))!==-1;){let o=e[n-1];o&&o!=="."&&o!==".."&&o!=="**"&&(t=!0,e.splice(n-1,2),n-=2)}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let n of e){let o=-1;for(;(o=n.indexOf("**",o+1))!==-1;){let i=o;for(;n[i+1]==="**";)i++;i>o&&n.splice(o+1,i-o);let a=n[o+1],l=n[o+2],c=n[o+3];if(a!==".."||!l||l==="."||l===".."||!c||c==="."||c==="..")continue;t=!0,n.splice(o,1);let u=n.slice(0);u[o]="**",e.push(u),o--}if(!this.preserveMultipleSlashes){for(let i=1;i<n.length-1;i++){let a=n[i];i===1&&a===""&&n[0]===""||(a==="."||a==="")&&(t=!0,n.splice(i,1),i--)}n[0]==="."&&n.length===2&&(n[1]==="."||n[1]==="")&&(t=!0,n.pop())}let s=0;for(;(s=n.indexOf("..",s+1))!==-1;){let i=n[s-1];if(i&&i!=="."&&i!==".."&&i!=="**"){t=!0;let l=s===1&&n[s+1]==="**"?["."]:[];n.splice(s-1,2,...l),n.length===0&&n.push(""),s-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let n=t+1;n<e.length;n++){let o=this.partsMatch(e[t],e[n],!this.preserveMultipleSlashes);if(o){e[t]=[],e[n]=o;break}}return e.filter(t=>t.length)}partsMatch(e,t,n=!1){let o=0,s=0,i=[],a="";for(;o<e.length&&s<t.length;)if(e[o]===t[s])i.push(a==="b"?t[s]:e[o]),o++,s++;else if(n&&e[o]==="**"&&t[s]===e[o+1])i.push(e[o]),o++;else if(n&&t[s]==="**"&&e[o]===t[s+1])i.push(t[s]),s++;else if(e[o]==="*"&&t[s]&&(this.options.dot||!t[s].startsWith("."))&&t[s]!=="**"){if(a==="b")return!1;a="a",i.push(e[o]),o++,s++}else if(t[s]==="*"&&e[o]&&(this.options.dot||!e[o].startsWith("."))&&e[o]!=="**"){if(a==="a")return!1;a="b",i.push(t[s]),o++,s++}else return!1;return e.length===t.length&&i}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,n=0;for(let o=0;o<e.length&&e.charAt(o)==="!";o++)t=!t,n++;n&&(this.pattern=e.slice(n)),this.negate=t}matchOne(e,t,n=!1){let o=this.options;if(this.isWindows){let f=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),g=!f&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),y=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),S=!y&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),w=g?3:f?0:void 0,T=S?3:y?0:void 0;if(typeof w=="number"&&typeof T=="number"){let[C,A]=[e[w],t[T]];C.toLowerCase()===A.toLowerCase()&&(t[T]=C,T>w?t=t.slice(T):w>T&&(e=e.slice(w)))}}let{optimizationLevel:s=1}=this.options;s>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var i=0,a=0,l=e.length,c=t.length;i<l&&a<c;i++,a++){this.debug("matchOne loop");var u=t[a],d=e[i];if(this.debug(t,u,d),u===!1)return!1;if(u===ve){this.debug("GLOBSTAR",[t,u,d]);var m=i,p=a+1;if(p===c){for(this.debug("** at the end");i<l;i++)if(e[i]==="."||e[i]===".."||!o.dot&&e[i].charAt(0)===".")return!1;return!0}for(;m<l;){var h=e[m];if(this.debug(`
|
|
1979
1979
|
globstar while`,e,m,t,p,h),this.matchOne(e.slice(m),t.slice(p),n))return this.debug("globstar found match!",m,l,h),!0;if(h==="."||h===".."||!o.dot&&h.charAt(0)==="."){this.debug("dot detected!",e,m,t,p);break}this.debug("globstar swallow a segment, and continue"),m++}return!!(n&&(this.debug(`
|
|
1980
1980
|
>>> no match, partial?`,e,m,t,p),m===l))}let f;if(typeof u=="string"?(f=d===u,this.debug("string match",u,d,f)):(f=u.test(d),this.debug("pattern match",u,d,f)),!f)return!1}if(i===l&&a===c)return!0;if(i===l)return n;if(a===c)return i===l-1&&e[i]==="";throw new Error("wtf?")}braceExpand(){return qp(this.pattern,this.options)}parse(e){fo(e);let t=this.options;if(e==="**")return ve;if(e==="")return"";let n,o=null;(n=e.match(bE))?o=t.dot?EE:TE:(n=e.match(dE))?o=(t.nocase?t.dot?hE:pE:t.dot?mE:uE)(n[1]):(n=e.match(CE))?o=(t.nocase?t.dot?AE:vE:t.dot?xE:RE)(n):(n=e.match(fE))?o=t.dot?yE:gE:(n=e.match(SE))&&(o=wE);let s=mn.fromGlob(e,this.options).toMMPattern();return o&&typeof s=="object"&&Reflect.defineProperty(s,"test",{value:o}),s}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,n=t.noglobstar?OE:t.dot?LE:ME,o=new Set(t.nocase?["i"]:[]),s=e.map(l=>{let c=l.map(u=>{if(u instanceof RegExp)for(let d of u.flags.split(""))o.add(d);return typeof u=="string"?FE(u):u===ve?ve:u._src});return c.forEach((u,d)=>{let m=c[d+1],p=c[d-1];u!==ve||p===ve||(p===void 0?m!==void 0&&m!==ve?c[d+1]="(?:\\/|"+n+"\\/)?"+m:c[d]=n:m===void 0?c[d-1]=p+"(?:\\/|"+n+")?":m!==ve&&(c[d-1]=p+"(?:\\/|\\/"+n+"\\/)"+m,c[d+1]=ve))}),c.filter(u=>u!==ve).join("/")}).join("|"),[i,a]=e.length>1?["(?:",")"]:["",""];s="^"+i+s+a+"$",this.negate&&(s="^(?!"+s+").+$");try{this.regexp=new RegExp(s,[...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 n=this.options;this.isWindows&&(e=e.split("\\").join("/"));let o=this.slashSplit(e);this.debug(this.pattern,"split",o);let s=this.set;this.debug(this.pattern,"set",s);let i=o[o.length-1];if(!i)for(let a=o.length-2;!i&&a>=0;a--)i=o[a];for(let a=0;a<s.length;a++){let l=s[a],c=o;if(n.matchBase&&l.length===1&&(c=[i]),this.matchOne(c,l,t))return n.flipNegate?!0:!this.negate}return n.flipNegate?!1:this.negate}static defaults(e){return We.defaults(e).Minimatch}};We.AST=mn;We.Minimatch=Qe;We.escape=pn;We.unescape=wt;import{fileURLToPath as fC}from"node:url";var hn=typeof performance=="object"&&performance&&typeof performance.now=="function"?performance:Date,Yp=new Set,ul=typeof process=="object"&&process?process:{},Xp=(r,e,t,n)=>{typeof ul.emitWarning=="function"?ul.emitWarning(r,e,t,n):console.error(`[${t}] ${e}: ${r}`)},oi=globalThis.AbortController,Kp=globalThis.AbortSignal;if(typeof oi>"u"){Kp=class{onabort;_onabort=[];reason;aborted=!1;addEventListener(n,o){this._onabort.push(o)}},oi=class{constructor(){e()}signal=new Kp;abort(n){if(!this.signal.aborted){this.signal.reason=n,this.signal.aborted=!0;for(let o of this.signal._onabort)o(n);this.signal.onabort?.(n)}}};let r=ul.env?.LRU_CACHE_IGNORE_AC_WARNING!=="1",e=()=>{r&&(r=!1,Xp("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 UE=r=>!Yp.has(r),eK=Symbol("type"),lr=r=>r&&r===Math.floor(r)&&r>0&&isFinite(r),Jp=r=>lr(r)?r<=Math.pow(2,8)?Uint8Array:r<=Math.pow(2,16)?Uint16Array:r<=Math.pow(2,32)?Uint32Array:r<=Number.MAX_SAFE_INTEGER?fn:null:null,fn=class extends Array{constructor(e){super(e),this.fill(0)}},ml=class r{heap;length;static#e=!1;static create(e){let t=Jp(e);if(!t)return[];r.#e=!0;let n=new r(e,t);return r.#e=!1,n}constructor(e,t){if(!r.#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]}},yo=class r{#e;#t;#s;#n;#i;#b;ttl;ttlResolution;ttlAutopurge;updateAgeOnGet;updateAgeOnHas;allowStale;noDisposeOnSet;noUpdateTTL;maxEntrySize;sizeCalculation;noDeleteOnFetchRejection;noDeleteOnStaleGet;allowStaleOnFetchAbort;allowStaleOnFetchRejection;ignoreFetchAbort;#c;#u;#a;#l;#o;#g;#y;#p;#m;#C;#f;#v;#A;#w;#T;#E;#h;static unsafeExposeInternals(e){return{starts:e.#A,ttls:e.#w,sizes:e.#v,keyMap:e.#a,keyList:e.#l,valList:e.#o,next:e.#g,prev:e.#y,get head(){return e.#p},get tail(){return e.#m},free:e.#C,isBackgroundFetch:t=>e.#d(t),backgroundFetch:(t,n,o,s)=>e.#U(t,n,o,s),moveToTail:t=>e.#B(t),indexes:t=>e.#R(t),rindexes:t=>e.#I(t),isStale:t=>e.#S(t)}}get max(){return this.#e}get maxSize(){return this.#t}get calculatedSize(){return this.#u}get size(){return this.#c}get fetchMethod(){return this.#i}get memoMethod(){return this.#b}get dispose(){return this.#s}get disposeAfter(){return this.#n}constructor(e){let{max:t=0,ttl:n,ttlResolution:o=1,ttlAutopurge:s,updateAgeOnGet:i,updateAgeOnHas:a,allowStale:l,dispose:c,disposeAfter:u,noDisposeOnSet:d,noUpdateTTL:m,maxSize:p=0,maxEntrySize:h=0,sizeCalculation:f,fetchMethod:g,memoMethod:y,noDeleteOnFetchRejection:S,noDeleteOnStaleGet:w,allowStaleOnFetchRejection:T,allowStaleOnFetchAbort:C,ignoreFetchAbort:A}=e;if(t!==0&&!lr(t))throw new TypeError("max option must be a nonnegative integer");let I=t?Jp(t):Array;if(!I)throw new Error("invalid max value: "+t);if(this.#e=t,this.#t=p,this.maxEntrySize=h||this.#t,this.sizeCalculation=f,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(y!==void 0&&typeof y!="function")throw new TypeError("memoMethod must be a function if defined");if(this.#b=y,g!==void 0&&typeof g!="function")throw new TypeError("fetchMethod must be a function if specified");if(this.#i=g,this.#E=!!g,this.#a=new Map,this.#l=new Array(t).fill(void 0),this.#o=new Array(t).fill(void 0),this.#g=new I(t),this.#y=new I(t),this.#p=0,this.#m=0,this.#C=ml.create(t),this.#c=0,this.#u=0,typeof c=="function"&&(this.#s=c),typeof u=="function"?(this.#n=u,this.#f=[]):(this.#n=void 0,this.#f=void 0),this.#T=!!this.#s,this.#h=!!this.#n,this.noDisposeOnSet=!!d,this.noUpdateTTL=!!m,this.noDeleteOnFetchRejection=!!S,this.allowStaleOnFetchRejection=!!T,this.allowStaleOnFetchAbort=!!C,this.ignoreFetchAbort=!!A,this.maxEntrySize!==0){if(this.#t!==0&&!lr(this.#t))throw new TypeError("maxSize must be a positive integer if specified");if(!lr(this.maxEntrySize))throw new TypeError("maxEntrySize must be a positive integer if specified");this.#O()}if(this.allowStale=!!l,this.noDeleteOnStaleGet=!!w,this.updateAgeOnGet=!!i,this.updateAgeOnHas=!!a,this.ttlResolution=lr(o)||o===0?o:1,this.ttlAutopurge=!!s,this.ttl=n||0,this.ttl){if(!lr(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 O="LRU_CACHE_UNBOUNDED";UE(O)&&(Yp.add(O),Xp("TTL caching without ttlAutopurge, max, or maxSize can result in unbounded memory consumption.","UnboundedCacheWarning",O,r))}}getRemainingTTL(e){return this.#a.has(e)?1/0:0}#P(){let e=new fn(this.#e),t=new fn(this.#e);this.#w=e,this.#A=t,this.#M=(s,i,a=hn.now())=>{if(t[s]=i!==0?a:0,e[s]=i,i!==0&&this.ttlAutopurge){let l=setTimeout(()=>{this.#S(s)&&this.#L(this.#l[s],"expire")},i+1);l.unref&&l.unref()}},this.#x=s=>{t[s]=e[s]!==0?hn.now():0},this.#r=(s,i)=>{if(e[i]){let a=e[i],l=t[i];if(!a||!l)return;s.ttl=a,s.start=l,s.now=n||o();let c=s.now-l;s.remainingTTL=a-c}};let n=0,o=()=>{let s=hn.now();if(this.ttlResolution>0){n=s;let i=setTimeout(()=>n=0,this.ttlResolution);i.unref&&i.unref()}return s};this.getRemainingTTL=s=>{let i=this.#a.get(s);if(i===void 0)return 0;let a=e[i],l=t[i];if(!a||!l)return 1/0;let c=(n||o())-l;return a-c},this.#S=s=>{let i=t[s],a=e[s];return!!a&&!!i&&(n||o())-i>a}}#x=()=>{};#r=()=>{};#M=()=>{};#S=()=>!1;#O(){let e=new fn(this.#e);this.#u=0,this.#v=e,this.#N=t=>{this.#u-=e[t],e[t]=0},this.#k=(t,n,o,s)=>{if(this.#d(n))return 0;if(!lr(o))if(s){if(typeof s!="function")throw new TypeError("sizeCalculation must be a function");if(o=s(n,t),!lr(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.#_=(t,n,o)=>{if(e[t]=n,this.#t){let s=this.#t-e[t];for(;this.#u>s;)this.#F(!0)}this.#u+=e[t],o&&(o.entrySize=n,o.totalCalculatedSize=this.#u)}}#N=e=>{};#_=(e,t,n)=>{};#k=(e,t,n,o)=>{if(n||o)throw new TypeError("cannot set size without setting maxSize or maxEntrySize on cache");return 0};*#R({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#m;!(!this.#D(t)||((e||!this.#S(t))&&(yield t),t===this.#p));)t=this.#y[t]}*#I({allowStale:e=this.allowStale}={}){if(this.#c)for(let t=this.#p;!(!this.#D(t)||((e||!this.#S(t))&&(yield t),t===this.#m));)t=this.#g[t]}#D(e){return e!==void 0&&this.#a.get(this.#l[e])===e}*entries(){for(let e of this.#R())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.#R()){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.#R())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 n of this.#R()){let o=this.#o[n],s=this.#d(o)?o.__staleWhileFetching:o;if(s!==void 0&&e(s,this.#l[n],this))return this.get(this.#l[n],t)}}forEach(e,t=this){for(let n of this.#R()){let o=this.#o[n],s=this.#d(o)?o.__staleWhileFetching:o;s!==void 0&&e.call(t,s,this.#l[n],this)}}rforEach(e,t=this){for(let n of this.#I()){let o=this.#o[n],s=this.#d(o)?o.__staleWhileFetching:o;s!==void 0&&e.call(t,s,this.#l[n],this)}}purgeStale(){let e=!1;for(let t of this.#I({allowStale:!0}))this.#S(t)&&(this.#L(this.#l[t],"expire"),e=!0);return e}info(e){let t=this.#a.get(e);if(t===void 0)return;let n=this.#o[t],o=this.#d(n)?n.__staleWhileFetching:n;if(o===void 0)return;let s={value:o};if(this.#w&&this.#A){let i=this.#w[t],a=this.#A[t];if(i&&a){let l=i-(hn.now()-a);s.ttl=l,s.start=Date.now()}}return this.#v&&(s.size=this.#v[t]),s}dump(){let e=[];for(let t of this.#R({allowStale:!0})){let n=this.#l[t],o=this.#o[t],s=this.#d(o)?o.__staleWhileFetching:o;if(s===void 0||n===void 0)continue;let i={value:s};if(this.#w&&this.#A){i.ttl=this.#w[t];let a=hn.now()-this.#A[t];i.start=Math.floor(Date.now()-a)}this.#v&&(i.size=this.#v[t]),e.unshift([n,i])}return e}load(e){this.clear();for(let[t,n]of e){if(n.start){let o=Date.now()-n.start;n.start=hn.now()-o}this.set(t,n.value,n)}}set(e,t,n={}){if(t===void 0)return this.delete(e),this;let{ttl:o=this.ttl,start:s,noDisposeOnSet:i=this.noDisposeOnSet,sizeCalculation:a=this.sizeCalculation,status:l}=n,{noUpdateTTL:c=this.noUpdateTTL}=n,u=this.#k(e,t,n.size||0,a);if(this.maxEntrySize&&u>this.maxEntrySize)return l&&(l.set="miss",l.maxEntrySizeExceeded=!0),this.#L(e,"set"),this;let d=this.#c===0?void 0:this.#a.get(e);if(d===void 0)d=this.#c===0?this.#m:this.#C.length!==0?this.#C.pop():this.#c===this.#e?this.#F(!1):this.#c,this.#l[d]=e,this.#o[d]=t,this.#a.set(e,d),this.#g[this.#m]=d,this.#y[d]=this.#m,this.#m=d,this.#c++,this.#_(d,u,l),l&&(l.set="add"),c=!1;else{this.#B(d);let m=this.#o[d];if(t!==m){if(this.#E&&this.#d(m)){m.__abortController.abort(new Error("replaced"));let{__staleWhileFetching:p}=m;p!==void 0&&!i&&(this.#T&&this.#s?.(p,e,"set"),this.#h&&this.#f?.push([p,e,"set"]))}else i||(this.#T&&this.#s?.(m,e,"set"),this.#h&&this.#f?.push([m,e,"set"]));if(this.#N(d),this.#_(d,u,l),this.#o[d]=t,l){l.set="replace";let p=m&&this.#d(m)?m.__staleWhileFetching:m;p!==void 0&&(l.oldValue=p)}}else l&&(l.set="update")}if(o!==0&&!this.#w&&this.#P(),this.#w&&(c||this.#M(d,o,s),l&&this.#r(l,d)),!i&&this.#h&&this.#f){let m=this.#f,p;for(;p=m?.shift();)this.#n?.(...p)}return this}pop(){try{for(;this.#c;){let e=this.#o[this.#p];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.#f){let e=this.#f,t;for(;t=e?.shift();)this.#n?.(...t)}}}#F(e){let t=this.#p,n=this.#l[t],o=this.#o[t];return this.#E&&this.#d(o)?o.__abortController.abort(new Error("evicted")):(this.#T||this.#h)&&(this.#T&&this.#s?.(o,n,"evict"),this.#h&&this.#f?.push([o,n,"evict"])),this.#N(t),e&&(this.#l[t]=void 0,this.#o[t]=void 0,this.#C.push(t)),this.#c===1?(this.#p=this.#m=0,this.#C.length=0):this.#p=this.#g[t],this.#a.delete(n),this.#c--,t}has(e,t={}){let{updateAgeOnHas:n=this.updateAgeOnHas,status:o}=t,s=this.#a.get(e);if(s!==void 0){let i=this.#o[s];if(this.#d(i)&&i.__staleWhileFetching===void 0)return!1;if(this.#S(s))o&&(o.has="stale",this.#r(o,s));else return n&&this.#x(s),o&&(o.has="hit",this.#r(o,s)),!0}else o&&(o.has="miss");return!1}peek(e,t={}){let{allowStale:n=this.allowStale}=t,o=this.#a.get(e);if(o===void 0||!n&&this.#S(o))return;let s=this.#o[o];return this.#d(s)?s.__staleWhileFetching:s}#U(e,t,n,o){let s=t===void 0?void 0:this.#o[t];if(this.#d(s))return s;let i=new oi,{signal:a}=n;a?.addEventListener("abort",()=>i.abort(a.reason),{signal:i.signal});let l={signal:i.signal,options:n,context:o},c=(f,g=!1)=>{let{aborted:y}=i.signal,S=n.ignoreFetchAbort&&f!==void 0;if(n.status&&(y&&!g?(n.status.fetchAborted=!0,n.status.fetchError=i.signal.reason,S&&(n.status.fetchAbortIgnored=!0)):n.status.fetchResolved=!0),y&&!S&&!g)return d(i.signal.reason);let w=p;return this.#o[t]===p&&(f===void 0?w.__staleWhileFetching?this.#o[t]=w.__staleWhileFetching:this.#L(e,"fetch"):(n.status&&(n.status.fetchUpdated=!0),this.set(e,f,l.options))),f},u=f=>(n.status&&(n.status.fetchRejected=!0,n.status.fetchError=f),d(f)),d=f=>{let{aborted:g}=i.signal,y=g&&n.allowStaleOnFetchAbort,S=y||n.allowStaleOnFetchRejection,w=S||n.noDeleteOnFetchRejection,T=p;if(this.#o[t]===p&&(!w||T.__staleWhileFetching===void 0?this.#L(e,"fetch"):y||(this.#o[t]=T.__staleWhileFetching)),S)return n.status&&T.__staleWhileFetching!==void 0&&(n.status.returnedStale=!0),T.__staleWhileFetching;if(T.__returned===T)throw f},m=(f,g)=>{let y=this.#i?.(e,s,l);y&&y instanceof Promise&&y.then(S=>f(S===void 0?void 0:S),g),i.signal.addEventListener("abort",()=>{(!n.ignoreFetchAbort||n.allowStaleOnFetchAbort)&&(f(void 0),n.allowStaleOnFetchAbort&&(f=S=>c(S,!0)))})};n.status&&(n.status.fetchDispatched=!0);let p=new Promise(m).then(c,u),h=Object.assign(p,{__abortController:i,__staleWhileFetching:s,__returned:void 0});return t===void 0?(this.set(e,h,{...l.options,status:void 0}),t=this.#a.get(e)):this.#o[t]=h,h}#d(e){if(!this.#E)return!1;let t=e;return!!t&&t instanceof Promise&&t.hasOwnProperty("__staleWhileFetching")&&t.__abortController instanceof oi}async fetch(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,ttl:i=this.ttl,noDisposeOnSet:a=this.noDisposeOnSet,size:l=0,sizeCalculation:c=this.sizeCalculation,noUpdateTTL:u=this.noUpdateTTL,noDeleteOnFetchRejection:d=this.noDeleteOnFetchRejection,allowStaleOnFetchRejection:m=this.allowStaleOnFetchRejection,ignoreFetchAbort:p=this.ignoreFetchAbort,allowStaleOnFetchAbort:h=this.allowStaleOnFetchAbort,context:f,forceRefresh:g=!1,status:y,signal:S}=t;if(!this.#E)return y&&(y.fetch="get"),this.get(e,{allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:s,status:y});let w={allowStale:n,updateAgeOnGet:o,noDeleteOnStaleGet:s,ttl:i,noDisposeOnSet:a,size:l,sizeCalculation:c,noUpdateTTL:u,noDeleteOnFetchRejection:d,allowStaleOnFetchRejection:m,allowStaleOnFetchAbort:h,ignoreFetchAbort:p,status:y,signal:S},T=this.#a.get(e);if(T===void 0){y&&(y.fetch="miss");let C=this.#U(e,T,w,f);return C.__returned=C}else{let C=this.#o[T];if(this.#d(C)){let j=n&&C.__staleWhileFetching!==void 0;return y&&(y.fetch="inflight",j&&(y.returnedStale=!0)),j?C.__staleWhileFetching:C.__returned=C}let A=this.#S(T);if(!g&&!A)return y&&(y.fetch="hit"),this.#B(T),o&&this.#x(T),y&&this.#r(y,T),C;let I=this.#U(e,T,w,f),x=I.__staleWhileFetching!==void 0&&n;return y&&(y.fetch=A?"stale":"refresh",x&&A&&(y.returnedStale=!0)),x?I.__staleWhileFetching:I.__returned=I}}async forceFetch(e,t={}){let n=await this.fetch(e,t);if(n===void 0)throw new Error("fetch() returned undefined");return n}memo(e,t={}){let n=this.#b;if(!n)throw new Error("no memoMethod provided to constructor");let{context:o,forceRefresh:s,...i}=t,a=this.get(e,i);if(!s&&a!==void 0)return a;let l=n(e,a,{options:i,context:o});return this.set(e,l,i),l}get(e,t={}){let{allowStale:n=this.allowStale,updateAgeOnGet:o=this.updateAgeOnGet,noDeleteOnStaleGet:s=this.noDeleteOnStaleGet,status:i}=t,a=this.#a.get(e);if(a!==void 0){let l=this.#o[a],c=this.#d(l);return i&&this.#r(i,a),this.#S(a)?(i&&(i.get="stale"),c?(i&&n&&l.__staleWhileFetching!==void 0&&(i.returnedStale=!0),n?l.__staleWhileFetching:void 0):(s||this.#L(e,"expire"),i&&n&&(i.returnedStale=!0),n?l:void 0)):(i&&(i.get="hit"),c?l.__staleWhileFetching:(this.#B(a),o&&this.#x(a),l))}else i&&(i.get="miss")}#$(e,t){this.#y[t]=e,this.#g[e]=t}#B(e){e!==this.#m&&(e===this.#p?this.#p=this.#g[e]:this.#$(this.#y[e],this.#g[e]),this.#$(this.#m,e),this.#m=e)}delete(e){return this.#L(e,"delete")}#L(e,t){let n=!1;if(this.#c!==0){let o=this.#a.get(e);if(o!==void 0)if(n=!0,this.#c===1)this.#z(t);else{this.#N(o);let s=this.#o[o];if(this.#d(s)?s.__abortController.abort(new Error("deleted")):(this.#T||this.#h)&&(this.#T&&this.#s?.(s,e,t),this.#h&&this.#f?.push([s,e,t])),this.#a.delete(e),this.#l[o]=void 0,this.#o[o]=void 0,o===this.#m)this.#m=this.#y[o];else if(o===this.#p)this.#p=this.#g[o];else{let i=this.#y[o];this.#g[i]=this.#g[o];let a=this.#g[o];this.#y[a]=this.#y[o]}this.#c--,this.#C.push(o)}}if(this.#h&&this.#f?.length){let o=this.#f,s;for(;s=o?.shift();)this.#n?.(...s)}return n}clear(){return this.#z("delete")}#z(e){for(let t of this.#I({allowStale:!0})){let n=this.#o[t];if(this.#d(n))n.__abortController.abort(new Error("deleted"));else{let o=this.#l[t];this.#T&&this.#s?.(n,o,e),this.#h&&this.#f?.push([n,o,e])}}if(this.#a.clear(),this.#o.fill(void 0),this.#l.fill(void 0),this.#w&&this.#A&&(this.#w.fill(0),this.#A.fill(0)),this.#v&&this.#v.fill(0),this.#p=0,this.#m=0,this.#C.length=0,this.#u=0,this.#c=0,this.#h&&this.#f){let t=this.#f,n;for(;n=t?.shift();)this.#n?.(...n)}}};import{posix as YE,win32 as El}from"node:path";import{fileURLToPath as XE}from"node:url";import{lstatSync as JE,readdir as ZE,readdirSync as QE,readlinkSync as eC,realpathSync as tC}from"fs";import*as rC from"node:fs";import{lstat as oC,readdir as sC,readlink as iC,realpath as aC}from"node:fs/promises";import{EventEmitter as wl}from"node:events";import rh from"node:stream";import{StringDecoder as $E}from"node:string_decoder";var Zp=typeof process=="object"&&process?process:{stdout:null,stderr:null},BE=r=>!!r&&typeof r=="object"&&(r instanceof dr||r instanceof rh||zE(r)||WE(r)),zE=r=>!!r&&typeof r=="object"&&r instanceof wl&&typeof r.pipe=="function"&&r.pipe!==rh.Writable.prototype.pipe,WE=r=>!!r&&typeof r=="object"&&r instanceof wl&&typeof r.write=="function"&&typeof r.end=="function",Jt=Symbol("EOF"),Zt=Symbol("maybeEmitEnd"),cr=Symbol("emittedEnd"),si=Symbol("emittingEnd"),So=Symbol("emittedError"),ii=Symbol("closed"),Qp=Symbol("read"),ai=Symbol("flush"),eh=Symbol("flushChunk"),bt=Symbol("encoding"),gn=Symbol("decoder"),Se=Symbol("flowing"),wo=Symbol("paused"),yn=Symbol("resume"),we=Symbol("buffer"),je=Symbol("pipes"),be=Symbol("bufferLength"),pl=Symbol("bufferPush"),li=Symbol("bufferShift"),ke=Symbol("objectMode"),se=Symbol("destroyed"),hl=Symbol("error"),fl=Symbol("emitData"),th=Symbol("emitEnd"),gl=Symbol("emitEnd2"),kt=Symbol("async"),yl=Symbol("abort"),ci=Symbol("aborted"),bo=Symbol("signal"),Or=Symbol("dataListeners"),et=Symbol("discarded"),To=r=>Promise.resolve().then(r),jE=r=>r(),HE=r=>r==="end"||r==="finish"||r==="prefinish",GE=r=>r instanceof ArrayBuffer||!!r&&typeof r=="object"&&r.constructor&&r.constructor.name==="ArrayBuffer"&&r.byteLength>=0,VE=r=>!Buffer.isBuffer(r)&&ArrayBuffer.isView(r),di=class{src;dest;opts;ondrain;constructor(e,t,n){this.src=e,this.dest=t,this.opts=n,this.ondrain=()=>e[yn](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(e){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Sl=class extends di{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(e,t,n){super(e,t,n),this.proxyErrors=o=>t.emit("error",o),e.on("error",this.proxyErrors)}},qE=r=>!!r.objectMode,KE=r=>!r.objectMode&&!!r.encoding&&r.encoding!=="buffer",dr=class extends wl{[Se]=!1;[wo]=!1;[je]=[];[we]=[];[ke];[bt];[kt];[gn];[Jt]=!1;[cr]=!1;[si]=!1;[ii]=!1;[So]=null;[be]=0;[se]=!1;[bo];[ci]=!1;[Or]=0;[et]=!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");qE(t)?(this[ke]=!0,this[bt]=null):KE(t)?(this[bt]=t.encoding,this[ke]=!1):(this[ke]=!1,this[bt]=null),this[kt]=!!t.async,this[gn]=this[bt]?new $E(this[bt]):null,t&&t.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[we]}),t&&t.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[je]});let{signal:n}=t;n&&(this[bo]=n,n.aborted?this[yl]():n.addEventListener("abort",()=>this[yl]()))}get bufferLength(){return this[be]}get encoding(){return this[bt]}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[ke]}set objectMode(e){throw new Error("objectMode must be set at instantiation time")}get async(){return this[kt]}set async(e){this[kt]=this[kt]||!!e}[yl](){this[ci]=!0,this.emit("abort",this[bo]?.reason),this.destroy(this[bo]?.reason)}get aborted(){return this[ci]}set aborted(e){}write(e,t,n){if(this[ci])return!1;if(this[Jt])throw new Error("write after end");if(this[se])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof t=="function"&&(n=t,t="utf8"),t||(t="utf8");let o=this[kt]?To:jE;if(!this[ke]&&!Buffer.isBuffer(e)){if(VE(e))e=Buffer.from(e.buffer,e.byteOffset,e.byteLength);else if(GE(e))e=Buffer.from(e);else if(typeof e!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[ke]?(this[Se]&&this[be]!==0&&this[ai](!0),this[Se]?this.emit("data",e):this[pl](e),this[be]!==0&&this.emit("readable"),n&&o(n),this[Se]):e.length?(typeof e=="string"&&!(t===this[bt]&&!this[gn]?.lastNeed)&&(e=Buffer.from(e,t)),Buffer.isBuffer(e)&&this[bt]&&(e=this[gn].write(e)),this[Se]&&this[be]!==0&&this[ai](!0),this[Se]?this.emit("data",e):this[pl](e),this[be]!==0&&this.emit("readable"),n&&o(n),this[Se]):(this[be]!==0&&this.emit("readable"),n&&o(n),this[Se])}read(e){if(this[se])return null;if(this[et]=!1,this[be]===0||e===0||e&&e>this[be])return this[Zt](),null;this[ke]&&(e=null),this[we].length>1&&!this[ke]&&(this[we]=[this[bt]?this[we].join(""):Buffer.concat(this[we],this[be])]);let t=this[Qp](e||null,this[we][0]);return this[Zt](),t}[Qp](e,t){if(this[ke])this[li]();else{let n=t;e===n.length||e===null?this[li]():typeof n=="string"?(this[we][0]=n.slice(e),t=n.slice(0,e),this[be]-=e):(this[we][0]=n.subarray(e),t=n.subarray(0,e),this[be]-=e)}return this.emit("data",t),!this[we].length&&!this[Jt]&&this.emit("drain"),t}end(e,t,n){return typeof e=="function"&&(n=e,e=void 0),typeof t=="function"&&(n=t,t="utf8"),e!==void 0&&this.write(e,t),n&&this.once("end",n),this[Jt]=!0,this.writable=!1,(this[Se]||!this[wo])&&this[Zt](),this}[yn](){this[se]||(!this[Or]&&!this[je].length&&(this[et]=!0),this[wo]=!1,this[Se]=!0,this.emit("resume"),this[we].length?this[ai]():this[Jt]?this[Zt]():this.emit("drain"))}resume(){return this[yn]()}pause(){this[Se]=!1,this[wo]=!0,this[et]=!1}get destroyed(){return this[se]}get flowing(){return this[Se]}get paused(){return this[wo]}[pl](e){this[ke]?this[be]+=1:this[be]+=e.length,this[we].push(e)}[li](){return this[ke]?this[be]-=1:this[be]-=this[we][0].length,this[we].shift()}[ai](e=!1){do;while(this[eh](this[li]())&&this[we].length);!e&&!this[we].length&&!this[Jt]&&this.emit("drain")}[eh](e){return this.emit("data",e),this[Se]}pipe(e,t){if(this[se])return e;this[et]=!1;let n=this[cr];return t=t||{},e===Zp.stdout||e===Zp.stderr?t.end=!1:t.end=t.end!==!1,t.proxyErrors=!!t.proxyErrors,n?t.end&&e.end():(this[je].push(t.proxyErrors?new Sl(this,e,t):new di(this,e,t)),this[kt]?To(()=>this[yn]()):this[yn]()),e}unpipe(e){let t=this[je].find(n=>n.dest===e);t&&(this[je].length===1?(this[Se]&&this[Or]===0&&(this[Se]=!1),this[je]=[]):this[je].splice(this[je].indexOf(t),1),t.unpipe())}addListener(e,t){return this.on(e,t)}on(e,t){let n=super.on(e,t);if(e==="data")this[et]=!1,this[Or]++,!this[je].length&&!this[Se]&&this[yn]();else if(e==="readable"&&this[be]!==0)super.emit("readable");else if(HE(e)&&this[cr])super.emit(e),this.removeAllListeners(e);else if(e==="error"&&this[So]){let o=t;this[kt]?To(()=>o.call(this,this[So])):o.call(this,this[So])}return n}removeListener(e,t){return this.off(e,t)}off(e,t){let n=super.off(e,t);return e==="data"&&(this[Or]=this.listeners("data").length,this[Or]===0&&!this[et]&&!this[je].length&&(this[Se]=!1)),n}removeAllListeners(e){let t=super.removeAllListeners(e);return(e==="data"||e===void 0)&&(this[Or]=0,!this[et]&&!this[je].length&&(this[Se]=!1)),t}get emittedEnd(){return this[cr]}[Zt](){!this[si]&&!this[cr]&&!this[se]&&this[we].length===0&&this[Jt]&&(this[si]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[ii]&&this.emit("close"),this[si]=!1)}emit(e,...t){let n=t[0];if(e!=="error"&&e!=="close"&&e!==se&&this[se])return!1;if(e==="data")return!this[ke]&&!n?!1:this[kt]?(To(()=>this[fl](n)),!0):this[fl](n);if(e==="end")return this[th]();if(e==="close"){if(this[ii]=!0,!this[cr]&&!this[se])return!1;let s=super.emit("close");return this.removeAllListeners("close"),s}else if(e==="error"){this[So]=n,super.emit(hl,n);let s=!this[bo]||this.listeners("error").length?super.emit("error",n):!1;return this[Zt](),s}else if(e==="resume"){let s=super.emit("resume");return this[Zt](),s}else if(e==="finish"||e==="prefinish"){let s=super.emit(e);return this.removeAllListeners(e),s}let o=super.emit(e,...t);return this[Zt](),o}[fl](e){for(let n of this[je])n.dest.write(e)===!1&&this.pause();let t=this[et]?!1:super.emit("data",e);return this[Zt](),t}[th](){return this[cr]?!1:(this[cr]=!0,this.readable=!1,this[kt]?(To(()=>this[gl]()),!0):this[gl]())}[gl](){if(this[gn]){let t=this[gn].end();if(t){for(let n of this[je])n.dest.write(t);this[et]||super.emit("data",t)}}for(let t of this[je])t.end();let e=super.emit("end");return this.removeAllListeners("end"),e}async collect(){let e=Object.assign([],{dataLength:0});this[ke]||(e.dataLength=0);let t=this.promise();return this.on("data",n=>{e.push(n),this[ke]||(e.dataLength+=n.length)}),await t,e}async concat(){if(this[ke])throw new Error("cannot concat in objectMode");let e=await this.collect();return this[bt]?e.join(""):Buffer.concat(e,e.dataLength)}async promise(){return new Promise((e,t)=>{this.on(se,()=>t(new Error("stream destroyed"))),this.on("error",n=>t(n)),this.on("end",()=>e())})}[Symbol.asyncIterator](){this[et]=!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[Jt])return t();let s,i,a=d=>{this.off("data",l),this.off("end",c),this.off(se,u),t(),i(d)},l=d=>{this.off("error",a),this.off("end",c),this.off(se,u),this.pause(),s({value:d,done:!!this[Jt]})},c=()=>{this.off("error",a),this.off("data",l),this.off(se,u),t(),s({done:!0,value:void 0})},u=()=>a(new Error("stream destroyed"));return new Promise((d,m)=>{i=m,s=d,this.once(se,u),this.once("error",a),this.once("end",c),this.once("data",l)})},throw:t,return:t,[Symbol.asyncIterator](){return this}}}[Symbol.iterator](){this[et]=!1;let e=!1,t=()=>(this.pause(),this.off(hl,t),this.off(se,t),this.off("end",t),e=!0,{done:!0,value:void 0}),n=()=>{if(e)return t();let o=this.read();return o===null?t():{done:!1,value:o}};return this.once("end",t),this.once(hl,t),this.once(se,t),{next:n,throw:t,return:t,[Symbol.iterator](){return this}}}destroy(e){if(this[se])return e?this.emit("error",e):this.emit(se),this;this[se]=!0,this[et]=!0,this[we].length=0,this[be]=0;let t=this;return typeof t.close=="function"&&!this[ii]&&t.close(),e?this.emit("error",e):this.emit(se),this}static get isStream(){return BE}};var nC=tC.native,Co={lstatSync:JE,readdir:ZE,readdirSync:QE,readlinkSync:eC,realpathSync:nC,promises:{lstat:oC,readdir:sC,readlink:iC,realpath:aC}},ah=r=>!r||r===Co||r===rC?Co:{...Co,...r,promises:{...Co.promises,...r.promises||{}}},lh=/^\\\\\?\\([a-z]:)\\?$/i,lC=r=>r.replace(/\//g,"\\").replace(lh,"$1\\"),cC=/[\\\/]/,pt=0,ch=1,dh=2,Dt=4,uh=6,mh=8,Lr=10,ph=12,mt=15,Eo=~mt,bl=16,nh=32,vo=64,Tt=128,ui=256,pi=512,oh=vo|Tt|pi,dC=1023,Tl=r=>r.isFile()?mh:r.isDirectory()?Dt:r.isSymbolicLink()?Lr:r.isCharacterDevice()?dh:r.isBlockDevice()?uh:r.isSocket()?ph:r.isFIFO()?ch:pt,sh=new Map,Ao=r=>{let e=sh.get(r);if(e)return e;let t=r.normalize("NFKD");return sh.set(r,t),t},ih=new Map,mi=r=>{let e=ih.get(r);if(e)return e;let t=Ao(r.toLowerCase());return ih.set(r,t),t},hi=class extends yo{constructor(){super({max:256})}},Cl=class extends yo{constructor(e=16*1024){super({maxSize:e,sizeCalculation:t=>t.length+1})}},hh=Symbol("PathScurry setAsCwd"),De=class{name;root;roots;parent;nocase;isCWD=!1;#e;#t;get dev(){return this.#t}#s;get mode(){return this.#s}#n;get nlink(){return this.#n}#i;get uid(){return this.#i}#b;get gid(){return this.#b}#c;get rdev(){return this.#c}#u;get blksize(){return this.#u}#a;get ino(){return this.#a}#l;get size(){return this.#l}#o;get blocks(){return this.#o}#g;get atimeMs(){return this.#g}#y;get mtimeMs(){return this.#y}#p;get ctimeMs(){return this.#p}#m;get birthtimeMs(){return this.#m}#C;get atime(){return this.#C}#f;get mtime(){return this.#f}#v;get ctime(){return this.#v}#A;get birthtime(){return this.#A}#w;#T;#E;#h;#P;#x;#r;#M;#S;#O;get parentPath(){return(this.parent||this).fullpath()}get path(){return this.parentPath}constructor(e,t=pt,n,o,s,i,a){this.name=e,this.#w=s?mi(e):Ao(e),this.#r=t&dC,this.nocase=s,this.roots=o,this.root=n||this,this.#M=i,this.#E=a.fullpath,this.#P=a.relative,this.#x=a.relativePosix,this.parent=a.parent,this.parent?this.#e=this.parent.#e:this.#e=ah(a.fs)}depth(){return this.#T!==void 0?this.#T:this.parent?this.#T=this.parent.depth()+1:this.#T=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 n of e)t=t.child(n);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.#r&=~bl,t}child(e,t){if(e===""||e===".")return this;if(e==="..")return this.parent||this;let n=this.children(),o=this.nocase?mi(e):Ao(e);for(let l of n)if(l.#w===o)return l;let s=this.parent?this.sep:"",i=this.#E?this.#E+s+e:void 0,a=this.newChild(e,pt,{...t,parent:this,fullpath:i});return this.canReaddir()||(a.#r|=Tt),n.push(a),a}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 n=t.relative();return n+(!n||!t.parent?"":this.sep)+e}relativePosix(){if(this.sep==="/")return this.relative();if(this.isCWD)return"";if(this.#x!==void 0)return this.#x;let e=this.name,t=this.parent;if(!t)return this.#x=this.fullpathPosix();let n=t.relativePosix();return n+(!n||!t.parent?"":"/")+e}fullpath(){if(this.#E!==void 0)return this.#E;let e=this.name,t=this.parent;if(!t)return this.#E=this.name;let o=t.fullpath()+(t.parent?this.sep:"")+e;return this.#E=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(),n=t+(!t||!e.parent?"":"/")+this.name;return this.#h=n}isUnknown(){return(this.#r&mt)===pt}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.#r&mt)===mh}isDirectory(){return(this.#r&mt)===Dt}isCharacterDevice(){return(this.#r&mt)===dh}isBlockDevice(){return(this.#r&mt)===uh}isFIFO(){return(this.#r&mt)===ch}isSocket(){return(this.#r&mt)===ph}isSymbolicLink(){return(this.#r&Lr)===Lr}lstatCached(){return this.#r&nh?this:void 0}readlinkCached(){return this.#S}realpathCached(){return this.#O}readdirCached(){let e=this.children();return e.slice(0,e.provisional)}canReadlink(){if(this.#S)return!0;if(!this.parent)return!1;let e=this.#r&mt;return!(e!==pt&&e!==Lr||this.#r&ui||this.#r&Tt)}calledReaddir(){return!!(this.#r&bl)}isENOENT(){return!!(this.#r&Tt)}isNamed(e){return this.nocase?this.#w===mi(e):this.#w===Ao(e)}async readlink(){let e=this.#S;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=await this.#e.promises.readlink(this.fullpath()),n=(await this.parent.realpath())?.resolve(t);if(n)return this.#S=n}catch(t){this.#d(t.code);return}}readlinkSync(){let e=this.#S;if(e)return e;if(this.canReadlink()&&this.parent)try{let t=this.#e.readlinkSync(this.fullpath()),n=this.parent.realpathSync()?.resolve(t);if(n)return this.#S=n}catch(t){this.#d(t.code);return}}#_(e){this.#r|=bl;for(let t=e.provisional;t<e.length;t++){let n=e[t];n&&n.#k()}}#k(){this.#r&Tt||(this.#r=(this.#r|Tt)&Eo,this.#R())}#R(){let e=this.children();e.provisional=0;for(let t of e)t.#k()}#I(){this.#r|=pi,this.#D()}#D(){if(this.#r&vo)return;let e=this.#r;(e&mt)===Dt&&(e&=Eo),this.#r=e|vo,this.#R()}#F(e=""){e==="ENOTDIR"||e==="EPERM"?this.#D():e==="ENOENT"?this.#k():this.children().provisional=0}#U(e=""){e==="ENOTDIR"?this.parent.#D():e==="ENOENT"&&this.#k()}#d(e=""){let t=this.#r;t|=ui,e==="ENOENT"&&(t|=Tt),(e==="EINVAL"||e==="UNKNOWN")&&(t&=Eo),this.#r=t,e==="ENOTDIR"&&this.parent&&this.parent.#D()}#$(e,t){return this.#L(e,t)||this.#B(e,t)}#B(e,t){let n=Tl(e),o=this.newChild(e.name,n,{parent:this}),s=o.#r&mt;return s!==Dt&&s!==Lr&&s!==pt&&(o.#r|=vo),t.unshift(o),t.provisional++,o}#L(e,t){for(let n=t.provisional;n<t.length;n++){let o=t[n];if((this.nocase?mi(e.name):Ao(e.name))===o.#w)return this.#z(e,o,n,t)}}#z(e,t,n,o){let s=t.name;return t.#r=t.#r&Eo|Tl(e),s!==e.name&&(t.name=e.name),n!==o.provisional&&(n===o.length-1?o.pop():o.splice(n,1),o.unshift(t)),o.provisional++,t}async lstat(){if(!(this.#r&Tt))try{return this.#G(await this.#e.promises.lstat(this.fullpath())),this}catch(e){this.#U(e.code)}}lstatSync(){if(!(this.#r&Tt))try{return this.#G(this.#e.lstatSync(this.fullpath())),this}catch(e){this.#U(e.code)}}#G(e){let{atime:t,atimeMs:n,birthtime:o,birthtimeMs:s,blksize:i,blocks:a,ctime:l,ctimeMs:c,dev:u,gid:d,ino:m,mode:p,mtime:h,mtimeMs:f,nlink:g,rdev:y,size:S,uid:w}=e;this.#C=t,this.#g=n,this.#A=o,this.#m=s,this.#u=i,this.#o=a,this.#v=l,this.#p=c,this.#t=u,this.#b=d,this.#a=m,this.#s=p,this.#f=h,this.#y=f,this.#n=g,this.#c=y,this.#l=S,this.#i=w;let T=Tl(e);this.#r=this.#r&Eo|T|nh,T!==pt&&T!==Dt&&T!==Lr&&(this.#r|=vo)}#j=[];#H=!1;#V(e){this.#H=!1;let t=this.#j.slice();this.#j.length=0,t.forEach(n=>n(null,e))}readdirCB(e,t=!1){if(!this.canReaddir()){t?e(null,[]):queueMicrotask(()=>e(null,[]));return}let n=this.children();if(this.calledReaddir()){let s=n.slice(0,n.provisional);t?e(null,s):queueMicrotask(()=>e(null,s));return}if(this.#j.push(e),this.#H)return;this.#H=!0;let o=this.fullpath();this.#e.readdir(o,{withFileTypes:!0},(s,i)=>{if(s)this.#F(s.code),n.provisional=0;else{for(let a of i)this.#$(a,n);this.#_(n)}this.#V(n.slice(0,n.provisional))})}#W;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.#W)await this.#W;else{let n=()=>{};this.#W=new Promise(o=>n=o);try{for(let o of await this.#e.promises.readdir(t,{withFileTypes:!0}))this.#$(o,e);this.#_(e)}catch(o){this.#F(o.code),e.provisional=0}this.#W=void 0,n()}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 n of this.#e.readdirSync(t,{withFileTypes:!0}))this.#$(n,e);this.#_(e)}catch(n){this.#F(n.code),e.provisional=0}return e.slice(0,e.provisional)}canReaddir(){if(this.#r&oh)return!1;let e=mt&this.#r;return e===pt||e===Dt||e===Lr}shouldWalk(e,t){return(this.#r&Dt)===Dt&&!(this.#r&oh)&&!e.has(this)&&(!t||t(this))}async realpath(){if(this.#O)return this.#O;if(!((pi|ui|Tt)&this.#r))try{let e=await this.#e.promises.realpath(this.fullpath());return this.#O=this.resolve(e)}catch{this.#I()}}realpathSync(){if(this.#O)return this.#O;if(!((pi|ui|Tt)&this.#r))try{let e=this.#e.realpathSync(this.fullpath());return this.#O=this.resolve(e)}catch{this.#I()}}[hh](e){if(e===this)return;e.isCWD=!1,this.isCWD=!0;let t=new Set([]),n=[],o=this;for(;o&&o.parent;)t.add(o),o.#P=n.join(this.sep),o.#x=n.join("/"),o=o.parent,n.push("..");for(o=e;o&&o.parent&&!t.has(o);)o.#P=void 0,o.#x=void 0,o=o.parent}},fi=class r extends De{sep="\\";splitSep=cC;constructor(e,t=pt,n,o,s,i,a){super(e,t,n,o,s,i,a)}newChild(e,t=pt,n={}){return new r(e,t,this.root,this.roots,this.nocase,this.childrenCache(),n)}getRootString(e){return El.parse(e).root}getRoot(e){if(e=lC(e.toUpperCase()),e===this.root.name)return this.root;for(let[t,n]of Object.entries(this.roots))if(this.sameRoot(e,t))return this.roots[e]=n;return this.roots[e]=new Sn(e,this).root}sameRoot(e,t=this.root.name){return e=e.toUpperCase().replace(/\//g,"\\").replace(lh,"$1\\"),e===t}},gi=class r extends De{splitSep="/";sep="/";constructor(e,t=pt,n,o,s,i,a){super(e,t,n,o,s,i,a)}getRootString(e){return e.startsWith("/")?"/":""}getRoot(e){return this.root}newChild(e,t=pt,n={}){return new r(e,t,this.root,this.roots,this.nocase,this.childrenCache(),n)}},yi=class{root;rootPath;roots;cwd;#e;#t;#s;nocase;#n;constructor(e=process.cwd(),t,n,{nocase:o,childrenCacheSize:s=16*1024,fs:i=Co}={}){this.#n=ah(i),(e instanceof URL||e.startsWith("file://"))&&(e=XE(e));let a=t.resolve(e);this.roots=Object.create(null),this.rootPath=this.parseRootPath(a),this.#e=new hi,this.#t=new hi,this.#s=new Cl(s);let l=a.substring(this.rootPath.length).split(n);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.#n),this.roots[this.rootPath]=this.root;let c=this.root,u=l.length-1,d=t.sep,m=this.rootPath,p=!1;for(let h of l){let f=u--;c=c.child(h,{relative:new Array(f).fill("..").join(d),relativePosix:new Array(f).fill("..").join("/"),fullpath:m+=(p?"":d)+h}),p=!0}this.cwd=c}depth(e=this.cwd){return typeof e=="string"&&(e=this.cwd.resolve(e)),e.depth()}childrenCache(){return this.#s}resolve(...e){let t="";for(let s=e.length-1;s>=0;s--){let i=e[s];if(!(!i||i===".")&&(t=t?`${i}/${t}`:i,this.isAbsolute(i)))break}let n=this.#e.get(t);if(n!==void 0)return n;let o=this.cwd.resolve(t).fullpath();return this.#e.set(t,o),o}resolvePosix(...e){let t="";for(let s=e.length-1;s>=0;s--){let i=e[s];if(!(!i||i===".")&&(t=t?`${i}/${t}`:i,this.isAbsolute(i)))break}let n=this.#t.get(t);if(n!==void 0)return n;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 De||(t=e,e=this.cwd);let{withFileTypes:n}=t;if(e.canReaddir()){let o=await e.readdir();return n?o:o.map(s=>s.name)}else return[]}readdirSync(e=this.cwd,t={withFileTypes:!0}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof De||(t=e,e=this.cwd);let{withFileTypes:n=!0}=t;return e.canReaddir()?n?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 De||(t=e.withFileTypes,e=this.cwd);let n=await e.readlink();return t?n:n?.fullpath()}readlinkSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof De||(t=e.withFileTypes,e=this.cwd);let n=e.readlinkSync();return t?n:n?.fullpath()}async realpath(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof De||(t=e.withFileTypes,e=this.cwd);let n=await e.realpath();return t?n:n?.fullpath()}realpathSync(e=this.cwd,{withFileTypes:t}={withFileTypes:!1}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof De||(t=e.withFileTypes,e=this.cwd);let n=e.realpathSync();return t?n:n?.fullpath()}async walk(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof De||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:o=!1,filter:s,walkFilter:i}=t,a=[];(!s||s(e))&&a.push(n?e:e.fullpath());let l=new Set,c=(d,m)=>{l.add(d),d.readdirCB((p,h)=>{if(p)return m(p);let f=h.length;if(!f)return m();let g=()=>{--f===0&&m()};for(let y of h)(!s||s(y))&&a.push(n?y:y.fullpath()),o&&y.isSymbolicLink()?y.realpath().then(S=>S?.isUnknown()?S.lstat():S).then(S=>S?.shouldWalk(l,i)?c(S,g):g()):y.shouldWalk(l,i)?c(y,g):g()},!0)},u=e;return new Promise((d,m)=>{c(u,p=>{if(p)return m(p);d(a)})})}walkSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof De||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:o=!1,filter:s,walkFilter:i}=t,a=[];(!s||s(e))&&a.push(n?e:e.fullpath());let l=new Set([e]);for(let c of l){let u=c.readdirSync();for(let d of u){(!s||s(d))&&a.push(n?d:d.fullpath());let m=d;if(d.isSymbolicLink()){if(!(o&&(m=d.realpathSync())))continue;m.isUnknown()&&m.lstatSync()}m.shouldWalk(l,i)&&l.add(m)}}return a}[Symbol.asyncIterator](){return this.iterate()}iterate(e=this.cwd,t={}){return typeof e=="string"?e=this.cwd.resolve(e):e instanceof De||(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 De||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:o=!1,filter:s,walkFilter:i}=t;(!s||s(e))&&(yield n?e:e.fullpath());let a=new Set([e]);for(let l of a){let c=l.readdirSync();for(let u of c){(!s||s(u))&&(yield n?u:u.fullpath());let d=u;if(u.isSymbolicLink()){if(!(o&&(d=u.realpathSync())))continue;d.isUnknown()&&d.lstatSync()}d.shouldWalk(a,i)&&a.add(d)}}}stream(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof De||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:o=!1,filter:s,walkFilter:i}=t,a=new dr({objectMode:!0});(!s||s(e))&&a.write(n?e:e.fullpath());let l=new Set,c=[e],u=0,d=()=>{let m=!1;for(;!m;){let p=c.shift();if(!p){u===0&&a.end();return}u++,l.add(p);let h=(g,y,S=!1)=>{if(g)return a.emit("error",g);if(o&&!S){let w=[];for(let T of y)T.isSymbolicLink()&&w.push(T.realpath().then(C=>C?.isUnknown()?C.lstat():C));if(w.length){Promise.all(w).then(()=>h(null,y,!0));return}}for(let w of y)w&&(!s||s(w))&&(a.write(n?w:w.fullpath())||(m=!0));u--;for(let w of y){let T=w.realpathCached()||w;T.shouldWalk(l,i)&&c.push(T)}m&&!a.flowing?a.once("drain",d):f||d()},f=!0;p.readdirCB(h,!0),f=!1}};return d(),a}streamSync(e=this.cwd,t={}){typeof e=="string"?e=this.cwd.resolve(e):e instanceof De||(t=e,e=this.cwd);let{withFileTypes:n=!0,follow:o=!1,filter:s,walkFilter:i}=t,a=new dr({objectMode:!0}),l=new Set;(!s||s(e))&&a.write(n?e:e.fullpath());let c=[e],u=0,d=()=>{let m=!1;for(;!m;){let p=c.shift();if(!p){u===0&&a.end();return}u++,l.add(p);let h=p.readdirSync();for(let f of h)(!s||s(f))&&(a.write(n?f:f.fullpath())||(m=!0));u--;for(let f of h){let g=f;if(f.isSymbolicLink()){if(!(o&&(g=f.realpathSync())))continue;g.isUnknown()&&g.lstatSync()}g.shouldWalk(l,i)&&c.push(g)}}m&&!a.flowing&&a.once("drain",d)};return d(),a}chdir(e=this.cwd){let t=this.cwd;this.cwd=typeof e=="string"?this.cwd.resolve(e):e,this.cwd[hh](t)}},Sn=class extends yi{sep="\\";constructor(e=process.cwd(),t={}){let{nocase:n=!0}=t;super(e,El,"\\",{...t,nocase:n}),this.nocase=n;for(let o=this.cwd;o;o=o.parent)o.nocase=this.nocase}parseRootPath(e){return El.parse(e).root.toUpperCase()}newRoot(e){return new fi(this.rootPath,Dt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")||e.startsWith("\\")||/^[a-z]:(\/|\\)/i.test(e)}},wn=class extends yi{sep="/";constructor(e=process.cwd(),t={}){let{nocase:n=!1}=t;super(e,YE,"/",{...t,nocase:n}),this.nocase=n}parseRootPath(e){return"/"}newRoot(e){return new gi(this.rootPath,Dt,void 0,this.roots,this.nocase,this.childrenCache(),{fs:e})}isAbsolute(e){return e.startsWith("/")}},xo=class extends wn{constructor(e=process.cwd(),t={}){let{nocase:n=!0}=t;super(e,{...t,nocase:n})}},mK=process.platform==="win32"?fi:gi,fh=process.platform==="win32"?Sn:process.platform==="darwin"?xo:wn;var uC=r=>r.length>=1,mC=r=>r.length>=1,bn=class r{#e;#t;#s;length;#n;#i;#b;#c;#u;#a;#l=!0;constructor(e,t,n,o){if(!uC(e))throw new TypeError("empty pattern list");if(!mC(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,n<0||n>=this.length)throw new TypeError("index out of range");if(this.#e=e,this.#t=t,this.#s=n,this.#n=o,this.#s===0){if(this.isUNC()){let[s,i,a,l,...c]=this.#e,[u,d,m,p,...h]=this.#t;c[0]===""&&(c.shift(),h.shift());let f=[s,i,a,l,""].join("/"),g=[u,d,m,p,""].join("/");this.#e=[f,...c],this.#t=[g,...h],this.length=this.#e.length}else if(this.isDrive()||this.isAbsolute()){let[s,...i]=this.#e,[a,...l]=this.#t;i[0]===""&&(i.shift(),l.shift());let c=s+"/",u=a+"/";this.#e=[c,...i],this.#t=[u,...l],this.length=this.#e.length}}}pattern(){return this.#e[this.#s]}isString(){return typeof this.#e[this.#s]=="string"}isGlobstar(){return this.#e[this.#s]===ve}isRegExp(){return this.#e[this.#s]instanceof RegExp}globString(){return this.#b=this.#b||(this.#s===0?this.isAbsolute()?this.#t[0]+this.#t.slice(1).join("/"):this.#t.join("/"):this.#t.slice(this.#s).join("/"))}hasMore(){return this.length>this.#s+1}rest(){return this.#i!==void 0?this.#i:this.hasMore()?(this.#i=new r(this.#e,this.#t,this.#s+1,this.#n),this.#i.#a=this.#a,this.#i.#u=this.#u,this.#i.#c=this.#c,this.#i):this.#i=null}isUNC(){let e=this.#e;return this.#u!==void 0?this.#u:this.#u=this.#n==="win32"&&this.#s===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.#n==="win32"&&this.#s===0&&this.length>1&&typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0])}isAbsolute(){let e=this.#e;return this.#a!==void 0?this.#a:this.#a=e[0]===""&&e.length>1||this.isDrive()||this.isUNC()}root(){let e=this.#e[0];return typeof e=="string"&&this.isAbsolute()&&this.#s===0?e:""}checkFollowGlobstar(){return!(this.#s===0||!this.isGlobstar()||!this.#l)}markFollowGlobstar(){return this.#s===0||!this.isGlobstar()||!this.#l?!1:(this.#l=!1,!0)}};var pC=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Tn=class{relative;relativeChildren;absolute;absoluteChildren;platform;mmopts;constructor(e,{nobrace:t,nocase:n,noext:o,noglobstar:s,platform:i=pC}){this.relative=[],this.absolute=[],this.relativeChildren=[],this.absoluteChildren=[],this.platform=i,this.mmopts={dot:!0,nobrace:t,nocase:n,noext:o,noglobstar:s,optimizationLevel:2,platform:i,nocomment:!0,nonegate:!0};for(let a of e)this.add(a)}add(e){let t=new Qe(e,this.mmopts);for(let n=0;n<t.set.length;n++){let o=t.set[n],s=t.globParts[n];if(!o||!s)throw new Error("invalid pattern object");for(;o[0]==="."&&s[0]===".";)o.shift(),s.shift();let i=new bn(o,s,0,this.platform),a=new Qe(i.globString(),this.mmopts),l=s[s.length-1]==="**",c=i.isAbsolute();c?this.absolute.push(a):this.relative.push(a),l&&(c?this.absoluteChildren.push(a):this.relativeChildren.push(a))}}ignored(e){let t=e.fullpath(),n=`${t}/`,o=e.relative()||".",s=`${o}/`;for(let i of this.relative)if(i.match(o)||i.match(s))return!0;for(let i of this.absolute)if(i.match(t)||i.match(n))return!0;return!1}childrenIgnored(e){let t=e.fullpath()+"/",n=(e.relative()||".")+"/";for(let o of this.relativeChildren)if(o.match(n))return!0;for(let o of this.absoluteChildren)if(o.match(t))return!0;return!1}};var vl=class r{store;constructor(e=new Map){this.store=e}copy(){return new r(new Map(this.store))}hasWalked(e,t){return this.store.get(e.fullpath())?.has(t.globString())}storeWalked(e,t){let n=e.fullpath(),o=this.store.get(n);o?o.add(t.globString()):this.store.set(n,new Set([t.globString()]))}},Al=class{store=new Map;add(e,t,n){let o=(t?2:0)|(n?1:0),s=this.store.get(e);this.store.set(e,s===void 0?o:o&s)}entries(){return[...this.store.entries()].map(([e,t])=>[e,!!(t&2),!!(t&1)])}},xl=class{store=new Map;add(e,t){if(!e.canReaddir())return;let n=this.store.get(e);n?n.find(o=>o.globString()===t.globString())||n.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())}},Ro=class r{hasWalkedCache;matches=new Al;subwalks=new xl;patterns;follow;dot;opts;constructor(e,t){this.opts=e,this.follow=!!e.follow,this.dot=!!e.dot,this.hasWalkedCache=t?t.copy():new vl}processPatterns(e,t){this.patterns=t;let n=t.map(o=>[e,o]);for(let[o,s]of n){this.hasWalkedCache.storeWalked(o,s);let i=s.root(),a=s.isAbsolute()&&this.opts.absolute!==!1;if(i){o=o.resolve(i==="/"&&this.opts.root!==void 0?this.opts.root:i);let d=s.rest();if(d)s=d;else{this.matches.add(o,!0,!1);continue}}if(o.isENOENT())continue;let l,c,u=!1;for(;typeof(l=s.pattern())=="string"&&(c=s.rest());)o=o.resolve(l),s=c,u=!0;if(l=s.pattern(),c=s.rest(),u){if(this.hasWalkedCache.hasWalked(o,s))continue;this.hasWalkedCache.storeWalked(o,s)}if(typeof l=="string"){let d=l===".."||l===""||l===".";this.matches.add(o.resolve(l),a,d);continue}else if(l===ve){(!o.isSymbolicLink()||this.follow||s.checkFollowGlobstar())&&this.subwalks.add(o,s);let d=c?.pattern(),m=c?.rest();if(!c||(d===""||d===".")&&!m)this.matches.add(o,a,d===""||d===".");else if(d===".."){let p=o.parent||o;m?this.hasWalkedCache.hasWalked(p,m)||this.subwalks.add(p,m):this.matches.add(p,a,!0)}}else l instanceof RegExp&&this.subwalks.add(o,s)}return this}subwalkTargets(){return this.subwalks.keys()}child(){return new r(this.opts,this.hasWalkedCache)}filterEntries(e,t){let n=this.subwalks.get(e),o=this.child();for(let s of t)for(let i of n){let a=i.isAbsolute(),l=i.pattern(),c=i.rest();l===ve?o.testGlobstar(s,i,c,a):l instanceof RegExp?o.testRegExp(s,l,c,a):o.testString(s,l,c,a)}return o}testGlobstar(e,t,n,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()&&(n&&t.checkFollowGlobstar()?this.subwalks.add(e,n):t.markFollowGlobstar()&&this.subwalks.add(e,t)))),n){let s=n.pattern();if(typeof s=="string"&&s!==".."&&s!==""&&s!==".")this.testString(e,s,n.rest(),o);else if(s===".."){let i=e.parent||e;this.subwalks.add(i,n)}else s instanceof RegExp&&this.testRegExp(e,s,n.rest(),o)}}testRegExp(e,t,n,o){t.test(e.name)&&(n?this.subwalks.add(e,n):this.matches.add(e,o,!1))}testString(e,t,n,o){e.isNamed(t)&&(n?this.subwalks.add(e,n):this.matches.add(e,o,!1))}};var hC=(r,e)=>typeof r=="string"?new Tn([r],e):Array.isArray(r)?new Tn(r,e):r,Si=class{path;patterns;opts;seen=new Set;paused=!1;aborted=!1;#e=[];#t;#s;signal;maxDepth;includeChildMatches;constructor(e,t,n){if(this.patterns=e,this.path=t,this.opts=n,this.#s=!n.posix&&n.platform==="win32"?"\\":"/",this.includeChildMatches=n.includeChildMatches!==!1,(n.ignore||!this.includeChildMatches)&&(this.#t=hC(n.ignore??[],n),!this.includeChildMatches&&typeof this.#t.add!="function")){let o="cannot ignore child matches, ignore lacks add() method.";throw new Error(o)}this.maxDepth=n.maxDepth||1/0,n.signal&&(this.signal=n.signal,this.signal.addEventListener("abort",()=>{this.#e.length=0}))}#n(e){return this.seen.has(e)||!!this.#t?.ignored?.(e)}#i(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 n;if(this.opts.realpath){if(n=e.realpathCached()||await e.realpath(),!n)return;e=n}let s=e.isUnknown()||this.opts.stat?await e.lstat():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=await s.realpath();i&&(i.isUnknown()||this.opts.stat)&&await i.lstat()}return this.matchCheckTest(s,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.#n(e)?e:void 0}matchCheckSync(e,t){if(t&&this.opts.nodir)return;let n;if(this.opts.realpath){if(n=e.realpathCached()||e.realpathSync(),!n)return;e=n}let s=e.isUnknown()||this.opts.stat?e.lstatSync():e;if(this.opts.follow&&this.opts.nodir&&s?.isSymbolicLink()){let i=s.realpathSync();i&&(i?.isUnknown()||this.opts.stat)&&i.lstatSync()}return this.matchCheckTest(s,t)}matchFinish(e,t){if(this.#n(e))return;if(!this.includeChildMatches&&this.#t?.add){let s=`${e.relativePosix()}/**`;this.#t.add(s)}let n=this.opts.absolute===void 0?t:this.opts.absolute;this.seen.add(e);let o=this.opts.mark&&e.isDirectory()?this.#s:"";if(this.opts.withFileTypes)this.matchEmit(e);else if(n){let s=this.opts.posix?e.fullpathPosix():e.fullpath();this.matchEmit(s+o)}else{let s=this.opts.posix?e.relativePosix():e.relative(),i=this.opts.dotRelative&&!s.startsWith(".."+this.#s)?"."+this.#s:"";this.matchEmit(s?i+s+o:"."+o)}}async match(e,t,n){let o=await this.matchCheck(e,n);o&&this.matchFinish(o,t)}matchSync(e,t,n){let o=this.matchCheckSync(e,n);o&&this.matchFinish(o,t)}walkCB(e,t,n){this.signal?.aborted&&n(),this.walkCB2(e,t,new Ro(this.opts),n)}walkCB2(e,t,n,o){if(this.#i(e))return o();if(this.signal?.aborted&&o(),this.paused){this.onResume(()=>this.walkCB2(e,t,n,o));return}n.processPatterns(e,t);let s=1,i=()=>{--s===0&&o()};for(let[a,l,c]of n.matches.entries())this.#n(a)||(s++,this.match(a,l,c).then(()=>i()));for(let a of n.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;s++;let l=a.readdirCached();a.calledReaddir()?this.walkCB3(a,l,n,i):a.readdirCB((c,u)=>this.walkCB3(a,u,n,i),!0)}i()}walkCB3(e,t,n,o){n=n.filterEntries(e,t);let s=1,i=()=>{--s===0&&o()};for(let[a,l,c]of n.matches.entries())this.#n(a)||(s++,this.match(a,l,c).then(()=>i()));for(let[a,l]of n.subwalks.entries())s++,this.walkCB2(a,l,n.child(),i);i()}walkCBSync(e,t,n){this.signal?.aborted&&n(),this.walkCB2Sync(e,t,new Ro(this.opts),n)}walkCB2Sync(e,t,n,o){if(this.#i(e))return o();if(this.signal?.aborted&&o(),this.paused){this.onResume(()=>this.walkCB2Sync(e,t,n,o));return}n.processPatterns(e,t);let s=1,i=()=>{--s===0&&o()};for(let[a,l,c]of n.matches.entries())this.#n(a)||this.matchSync(a,l,c);for(let a of n.subwalkTargets()){if(this.maxDepth!==1/0&&a.depth()>=this.maxDepth)continue;s++;let l=a.readdirSync();this.walkCB3Sync(a,l,n,i)}i()}walkCB3Sync(e,t,n,o){n=n.filterEntries(e,t);let s=1,i=()=>{--s===0&&o()};for(let[a,l,c]of n.matches.entries())this.#n(a)||this.matchSync(a,l,c);for(let[a,l]of n.subwalks.entries())s++,this.walkCB2Sync(a,l,n.child(),i);i()}},Io=class extends Si{matches=new Set;constructor(e,t,n){super(e,t,n)}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}},Po=class extends Si{results;constructor(e,t,n){super(e,t,n),this.results=new dr({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 gC=typeof process=="object"&&process&&typeof process.platform=="string"?process.platform:"linux",Et=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=fC(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||gC,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"?Sn:t.platform==="darwin"?xo:t.platform?wn:fh;this.scurry=new l(this.cwd,{nocase:t.nocase,fs:t.fs})}this.nocase=this.scurry.nocase;let n=this.platform==="darwin"||this.platform==="win32",o={...t,dot:this.dot,matchBase:this.matchBase,nobrace:this.nobrace,nocase:this.nocase,nocaseMagicOnly:n,nocomment:!0,noext:this.noext,nonegate:!0,optimizationLevel:2,platform:this.platform,windowsPathsNoEscape:this.windowsPathsNoEscape,debug:!!this.opts.debug},s=this.pattern.map(l=>new Qe(l,o)),[i,a]=s.reduce((l,c)=>(l[0].push(...c.set),l[1].push(...c.globParts),l),[[],[]]);this.patterns=i.map((l,c)=>{let u=a[c];if(!u)throw new Error("invalid pattern object");return new bn(l,u,0,this.platform)})}async walk(){return[...await new Io(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 Io(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 Po(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 Po(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 Rl=(r,e={})=>{Array.isArray(r)||(r=[r]);for(let t of r)if(new Qe(t,e).hasMagic())return!0;return!1};function wi(r,e={}){return new Et(r,e).streamSync()}function Sh(r,e={}){return new Et(r,e).stream()}function En(r,e={}){return new Et(r,e).walkSync()}async function gh(r,e={}){return new Et(r,e).walk()}function bi(r,e={}){return new Et(r,e).iterateSync()}function wh(r,e={}){return new Et(r,e).iterate()}var yC=wi,SC=Object.assign(Sh,{sync:wi}),wC=bi,bC=Object.assign(wh,{sync:bi}),TC=Object.assign(En,{stream:wi,iterate:bi}),yh=Object.assign(gh,{glob:gh,globSync:En,sync:TC,globStream:Sh,stream:SC,globStreamSync:wi,streamSync:yC,globIterate:wh,iterate:bC,globIterateSync:bi,iterateSync:wC,Glob:Et,hasMagic:Rl,escape:pn,unescape:wt});yh.glob=yh;import PC from"os";import ur,{dirname as Eh}from"path";import{cwd as Ll}from"process";import Ch from"yaml";import{z as me}from"zod";import bh from"fs";import Ti from"path";import EC from"yaml";import{z as Il}from"zod";var Oo=[`**/*.${zt.TEST}`,`**/*.${zt.MODULE}`],Pl=Il.string().refine(r=>/^[a-zA-Z0-9-]+$/.test(r)),Ol=50,CC=Il.object({fileType:Il.nativeEnum(ne)});function Ct(r,e){let t={project:r,tests:{},modules:{}},n=r.config.include??Oo,o=Array.from(r.config.exclude??[]).concat(Md),s=En(n,{absolute:!1,cwd:r.rootDir,ignore:o,dotRelative:!1,maxDepth:Ol,nodir:!0});for(let i of s)vC(r.rootDir,i,t,e);return t}function vC(r,e,t,n){let o=Ti.join(r,e),s;try{s=bh.readFileSync(o,"utf-8")}catch(d){n.warn(`Could not read possible Momentic file at ${o}, skipping: ${d}`);return}let i;try{if(i=EC.parse(s),typeof i!="object"||i===null)throw new Error("The YAML document should parse as a map with key-value pairs")}catch(d){n.warn(`Could not parse possible Momentic file at ${o}, skipping: ${d}`);return}let a=CC.safeParse(i);if(a.error){n.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${a.error}`);return}let l=a.data.fileType,c;try{c=bh.statSync(o)}catch(d){n.warn(`Skipping path '${o}' because it could not be stat, skipping: ${d}`);return}let u={relativePath:e,fullFilePath:o,platformSep:Ti.sep,fullPathSegments:o.split(Ti.sep),fileName:Ti.basename(o),lastModified:c.mtime,createdAt:c.ctime};switch(l){case ne.TEST:try{let d=Ne.parse(i);t.tests[d.id]={type:ne.TEST,name:d.name,id:d.id,...u};return}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${d}`);return}case ne.MODULE:try{let d=st.parse(i);t.modules[d.moduleId]={type:ne.MODULE,name:d.name,id:d.moduleId,...u};return}catch(d){n.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${d}`);return}default:n.warn(`Unsupported file type ${l}, skipping...`);return}}var Cn="momentic.config.yaml",Th="momentic.workspace.yaml",OC=me.object({projects:me.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),LC=me.union([me.string(),me.object({fromFile:me.string(),json:me.boolean().optional()})]),MC=me.object({name:Pl,baseUrl:me.string(),envFile:me.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:me.record(me.string(),LC).optional(),inheritFromShell:me.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:aa.optional().transform(r=>r&&(r.localChromeExtensionPaths&&(r.localChromeExtensionPaths=r.localChromeExtensionPaths.map(e=>e.startsWith("~")?ur.join(PC.homedir(),e.slice(1)):e)),r))}),NC=me.object({name:Pl,include:me.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:me.string().array().optional().describe("opposite of include, takes precedence over include"),moduleCreationDir:me.string().optional(),testCreationDir:me.string().optional(),environments:me.array(MC).optional()});function vh(r,e){let t;try{t=xC(r,"utf-8")}catch(o){E.warn(`Could not read possible Momentic ${e} file at ${r}: ${o}`);return}let n;try{if(n=Ch.parse(t),typeof n!="object"||n===null)throw new Error(`The ${e} file should parse as a map with key-value pairs, but is type ${typeof n} instead`)}catch(o){E.warn(`Possible Momentic ${e} file at ${r} does not parse as valid YAML: ${o}`);return}return n}function Ml(r){let e=vh(r,"project configuration");if(e!==void 0)try{return NC.parse(e)}catch(t){E.warn(`Possible Momentic project configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function _C(r){let e=vh(r,"workspace configuration");if(e!==void 0)try{return OC.parse(e)}catch(t){E.warn(`Possible Momentic workspace configuration file at ${r} does not adhere to the required schema: ${t}`);return}}function kC(){let r=[],e=Ll(),t=ur.parse(e).root,n=15,o=0;for(;o<n;){o++;let s=ur.basename(e);if(eo.includes(s))return E.warn(`Stopping search for Momentic projects since the current directory name (${s}) is likely a system artifact folder.`),r;for(let i of RC(e))if(i.endsWith(Cn)){let a=ur.join(e,i),l=Ml(a);l&&r.push({configFilePath:a,config:l,rootDir:Eh(a)})}if(r.length)return r;if(e=ur.dirname(e),e===t)break}return r}function Mr(r={}){let{configFilePath:e,nameFilter:t}=r,n=Nl(e);if(t&&(n=n.filter(o=>o.config.name===t)),n.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
|
|
1981
|
-
${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return n[0]}function DC(r){let e=_C(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(s=>(s.endsWith("/")||(s+="/"),`${s}*${Cn}`)),n=En(t,{absolute:!1,cwd:Ll(),dotRelative:!1,maxDepth:Ol,nodir:!0}),o=[];for(let s of n){let i=ur.join(Ll(),s),a=Ml(i);a&&o.push({configFilePath:i,config:a,rootDir:Eh(i)})}return o}function Nl(r){if(r){r=ur.resolve(r);let t=Ml(r);if(!t)throw new Error("No valid Momentic project file available.");return[{config:t,configFilePath:r,rootDir:ur.dirname(r)}]}if(AC(Th)){let t=DC(Th);if(t)return t}return kC()}function vn(r,e){let t=Ch.stringify(r);IC(e,t)}var kl="https://api.momentic.ai",Ah,xh=r=>{kl=r},Lo=()=>kl,Rh=r=>{Ah=r},Te=()=>Ah,An,_l,Ih=async r=>{if(An)return An;let e=new Be({baseUrl:kl,apiKey:r});try{return An=await e.getOrgId(),_l=r,An}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Ei=()=>{if(!An)throw new Error("Your organization ID appears invalid. Please contact Momentic support.");return An},Ph=()=>{if(!_l)throw new Error("Your API key appears invalid. Please contact Momentic support.");return _l};import Oh,{multistream as FC}from"pino";import UC from"pino-pretty";var Dl=new Map,$C=!0,Fl=class r{consoleLogger;ddClientToken;hostname;bindingAttributes;excludeAttributesInConsoleLogs;excludeTimestamps;disableConsoleLogs;site="https://http-intake.logs.us5.datadoghq.com/api/v2/logs";constructor({bindings:e,clientToken:t,hostname:n,excludeAttributesInConsoleLogs:o,excludeTimestamps:s,disableConsoleLogs:i}){this.ddClientToken=t,this.hostname=n,this.excludeAttributesInConsoleLogs=o,this.excludeTimestamps=s,this.disableConsoleLogs=i,this.bindingAttributes={...e,env:"production"};let a={base:o?{}:this.bindingAttributes,errorKey:"err",level:"debug",timestamp:!s};this.consoleLogger=$C?Oh(a):Oh(a,FC([{stream:UC({colorize:!0})}]))}child(e){return new r({clientToken:this.ddClientToken,bindings:{...this.bindingAttributes,...e},hostname:this.hostname,excludeAttributesInConsoleLogs:this.excludeAttributesInConsoleLogs,disableConsoleLogs:this.disableConsoleLogs})}flush(e){this.disableConsoleLogs||this.consoleLogger.flush(e)}log(e,t,n,...o){if(t&&n===void 0&&(n=`${t}`,t={}),this.disableConsoleLogs||this.consoleLogger[e](e==="error"?t:{testId:t.testId,runId:t.runId},n,...o),typeof t=="object"&&t&&"err"in t&&t.err instanceof Error){let i={};for(let a of Object.getOwnPropertyNames(t.err))i[a]=t.err[a];i.name=t.err.name,t.err=i}let s=Object.assign({},this.bindingAttributes,t&&typeof t=="object"?t:{});o.length>0&&(s.args=o),(async()=>{try{let i=await fetch(this.site,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","DD-API-KEY":this.ddClientToken},body:JSON.stringify([{ddsource:this.bindingAttributes.app,hostname:this.hostname??"vercel",service:"momentic",message:{message:n||"",...s,level:e}}])});if(!i.ok)throw new Error(`Failed to log to Datadog: ${i.statusText})}`)}catch(i){this.disableConsoleLogs||this.consoleLogger.warn({obj:t,msg:n,args:o,err:i},"Failed to log to Datadog")}})()}debug(e,t,...n){this.log("debug",e,t,...n)}info(e,t,...n){this.log("info",e,t,...n)}warn(e,t,...n){this.log("warn",e,t,...n)}error(e,t,...n){this.log("error",e,t,...n)}bindings(){return this.bindingAttributes}addBinding(e,t){this.bindingAttributes[e]=t}setMinLevel(e){this.consoleLogger.level=e}enableConsoleLogs(){this.disableConsoleLogs=!1}},Ci=({app:r,clientToken:e,hostname:t,excludeAttributesInConsoleLogs:n,excludeTimestamps:o,disableConsoleLogs:s})=>{if(!process.env.DD_CLIENT_TOKEN&&!process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN&&!e)throw new Error("Missing DD_CLIENT_TOKEN");return Dl.has(r)||Dl.set(r,new Fl({bindings:{app:r},hostname:t,clientToken:e||process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN||process.env.DD_CLIENT_TOKEN,excludeAttributesInConsoleLogs:n,excludeTimestamps:o,disableConsoleLogs:s})),Dl.get(r)};import{hostname as BC}from"os";var pe=Ci({app:"desktop-server",clientToken:"pubcfd7516a5c0ba852b42675cd97bee027",hostname:BC(),excludeAttributesInConsoleLogs:!0,excludeTimestamps:!0,disableConsoleLogs:!0}),Lh=r=>{pe.addBinding("version",r)};function Ae(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Mh=zC();Mh.get("/",Ae((r,e)=>{let t=Ep(Te(),pe);e.status(200).json(t)}));var Nh=Mh;import{Router as WC}from"express";import _h from"fs";import kh from"path";var vi=WC();vi.get("/",Ae(async(r,e)=>{let t=Ct(Te(),E),o=(await wp(t,pe)).filter(s=>s.enabled??!0);e.status(200).json(o)}));vi.post("/",Ae(async(r,e)=>{let t;try{t=Pd.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}try{Vn(t.name)}catch(i){e.status(400).json({error:`Invalid module name: ${i}`});return}let n=Te(),o=kh.join(n.rootDir,n.config.moduleCreationDir??kh.dirname(t.testFilePath));if(!_h.existsSync(o)||!_h.statSync(o).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${o}' does not exist.`});return}let s=await Sp({...t,folder:o});e.status(201).json(s)}));vi.get("/:moduleId",Ae(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=Ct(Te(),E),n=t.modules[r.params.moduleId];if(!n){e.status(404).json({error:"Module not found."});return}try{let o=await il(n,t,E);e.json(o)}catch(o){e.status(400).json({err:o})}}));var Dh=vi;import{Router as jC}from"express";var Ai=jC();Ai.get("/",Ae((r,e)=>{let t=Nl().map(n=>({name:n.config.name,configFilePath:n.configFilePath}));e.status(200).json(t)}));Ai.get("/current",Ae((r,e)=>{let t=Te(),n={name:t.config.name,configFilePath:t.configFilePath};e.status(200).json(n)}));Ai.post("/set",Ae((r,e)=>{let t;try{t=Ld.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=Mr({configFilePath:t.configFilePath});Rh(n)}catch(n){e.status(400).json({error:`Error setting project: ${n}`});return}e.sendStatus(204)}));var Fh=Ai;import{Router as HC}from"express";import Ul from"path";import{v4 as GC}from"uuid";var Nr=HC();Nr.get("/",Ae((r,e)=>{let t=Te(),n=Ct(t,E),o=Array.from(Object.values(n.tests));e.status(200).json(o)}));Nr.post("/",Ae(async(r,e)=>{let t;try{t=Id.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{Vn(t.name)}catch(c){e.status(400).json({error:c.message});return}let o={id:GC(),name:t.name,baseUrl:t.baseUrl,schemaVersion:ct,advanced:{disableAICaching:!1,browserType:t.browserType??"Chromium",viewport:t.viewport??$t},retries:0,steps:[]};t.environment&&(o.envs=[{name:t.environment,default:!0}]);let s=Te(),i=Ul.join(s.rootDir,s.config.testCreationDir??""),a=await bp({test:o,name:t.name,folder:i}),l={...o,relativeFilePath:Ul.relative(s.rootDir,a)};e.status(201).json(l)}));Nr.get("/:testPath",Ae(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n=Te(),o=Ct(n,E),s;try{s=await ri(Ul.join(n.rootDir,t),pe,o),e.status(200).json(s)}catch(i){e.status(400).send({error:i.message});return}(async()=>{try{let{stepsToSave:i,moduleUpdates:a}=await gt({steps:s.steps});a.forEach(l=>{sl(l.moduleId,{...l,schemaVersion:ct},o)}),mo(t,{schemaVersion:ct,steps:i},n)}catch(i){pe.error({err:i},"Failed to save migrated test to disk after initial fetch")}})()}));Nr.patch("/:testPath/metadata",Ae(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=Rd.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}mo(r.params.testPath,t,Te()),e.status(201).json({message:"ok"})}));Nr.patch("/:testPath",Ae(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=xd.parse(r.body)}catch(d){e.status(400).json({error:`Invalid request body: ${d}`});return}let o=Te(),s=Ct(o,E),i;try{i=ti(t,o)}catch(d){e.status(400).json({error:`Existing test file on disk is invalid: ${d}`});return}let{stepsToSave:a,moduleUpdates:l,cachesToSave:c}=await gt({steps:n.steps,cacheCreationParams:{testId:i.id,orgId:Ei()}});await new Be({apiKey:Ph(),baseUrl:Lo()}).updateStepCaches({entries:c,testId:i.id}),l.forEach(d=>{sl(d.moduleId,{...d,schemaVersion:n.schemaVersion},s)}),mo(t,{steps:a,schemaVersion:n.schemaVersion},o),e.status(201).json({message:"ok"})}));Nr.patch("/:testPath/environments",Ae(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Od.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}mo(t,{envs:n.defaultEnv?[{name:n.defaultEnv,default:!0}]:[]},Te()),e.status(201).json({message:"ok"})}));var Uh=Nr;var xi=class extends tn{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async getOrgId(t){return this.orgId}async fetchTestMetadata(t,n,o){let s=Te(),a=Ct(s,o).tests[t];if(a)return ti(a.relativePath,s)}async fetchEnvironment(t,n,o){let s=Te();return po(n,s,o)}};async function Wh(r){let{momenticServerUrl:e,apiKey:t,serverPort:n,appPort:o,staticDir:s,devicePixelRatio:i,version:a}=r;Lh(a),e&&xh(e),pe.debug(r,"Initializing desktop server");let l=await Ih(t);pe.debug({orgId:l},"Checking API key successful");let u=`http://localhost:${n}`;o&&(u=`http://localhost:${o}`);let d=JC(s);await new Promise(y=>{d.listen(n,()=>{pe.info(`Server is running at http://localhost:${n}`),y()})});let p=new un({baseURL:Lo(),apiKey:t}),h={type:"API_KEY",baseUrl:Lo(),apiKey:t},f=new Be(h),g=new xi(f,Ei());yp({baseServer:d,generator:p,storage:g,logger:pe,devicePixelRatio:i,authorization:h}),await XC(u)}var zh="25mb";function JC(r){let e=Bh();e.use(VC()),e.use($h.json({limit:zh})),e.use($h.urlencoded({extended:!1,limit:zh}));let t=KC();if(t.use("/tests",Uh),t.use("/modules",Dh),t.use("/environments",Nh),t.use("/projects",Fh),e.use("/api",t),e.use((o,s,i)=>{o.path!=="/healthcheck"&&pe.debug({url:o.url,path:o.path,query:o.query,method:o.method,body:o.body,headers:o.rawHeaders,client:o.ip},"Received desktop-server request"),s.on("close",()=>{s.statusCode>=400&&pe.error({url:o.url,method:o.method,statusCode:s.statusCode},"Request completed in error")}),i()}),e.use((o,s,i,a)=>{if(o instanceof Error&&o.message.includes("BadRequestError: request aborted")){i.status(400).send("Client disconnected");return}pe.error({stack:o.stack,msg:o.message,err:o,url:s.url,method:s.method},"Unhandled exception leading to 500 on desktop-server"),E.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${o.message}`),i.status(500).send("Internal Server Error")}),r){let o=Bh.static(r);e.use("/",o),e.use("*",o)}return YC.createServer(e)}qC.setMaxListeners(50);process.on("warning",r=>{pe.warn({err:r},`Node warning received on desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{pe.error({err:r},"Uncaught exception leading to exit on desktop-server")});process.on("unhandledRejection",(r,e)=>{pe.error({reason:`${r}`,promise:`${e}`,stack:r?.stack},"Uncaught exception leading to exit on desktop-server (promise rejection)")});import qv from"events";import _f from"fs";import Wi from"path";import{fileURLToPath as Kv}from"url";import{existsSync as uv,mkdirSync as mv,statSync as pv}from"fs";import{dirname as hv}from"path";import Kh from"readline/promises";import{execSync as ZC}from"child_process";import{platform as QC}from"os";function $l(){return jh()?(E.info("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),E.info("If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations."),E.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),2):(E.info("Setting device pixel ratio to 1."),E.info("If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations"),E.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),1)}function jh(){return QC()==="darwin"&&ZC("system_profiler SPDisplaysDataType").toString().includes("Retina")}function Bl(r){jh()&&r===1&&(E.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),E.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import ev from"@actions/exec";import tv from"@actions/io";import rv from"quote";import nv from"string-argv";async function Hh(r,e=!0){let t=nv(r),n=await tv.which(t[0],!0),o=t.slice(1),s=ev.exec(rv(n),o,{delay:100});if(e)return s}import{existsSync as ov,statSync as sv}from"fs";var Gh=!!process.env.CI||!process.stdout.isTTY;function Mo(r){try{return ov(r)&&sv(r).isDirectory()}catch(e){return E.error({err:e},`Error reading path ${r} during directory existence check`),!1}}import iv from"csv-parser";import{createReadStream as av}from"fs";function zl(r){return new Promise((e,t)=>{let n=[];av(r).pipe(iv()).on("data",o=>n.push(o)).on("end",()=>e(n)).on("error",o=>t(o))})}import Ri from"semver";import{z as Ii}from"zod";var No="1.0.18",lv="https://registry.npmjs.org/momentic",cv=Ii.object({versions:Ii.record(Ii.string(),Ii.unknown()).optional()});async function Vh(r){if(!No){r.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let n=0;n<2;n++)try{let o=await J(fetch(lv),{milliseconds:2e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let s=await o.json();e=cv.parse(s).versions;break}catch(o){r.warn({err:o},"Failed to fetch npm registry data")}if(!e){r.warn("Failed to fetch npm registry data. Skipping version check.");return}let t;for(let n of Object.keys(e))Ri.valid(n)&&(!t||Ri.gt(n,t))&&Ri.gt(n,No)&&Ri.lt(n,"2.0.0")&&(t=n);t&&(E.warn(`Update available: v${No} -> v${t}`),E.warn("This version ay be missing critical fixes, features, and security updates."),E.warn(`Run "npx momentic@${t} -V" to update`))}import{hostname as dv}from"os";var $=Ci({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:dv(),excludeAttributesInConsoleLogs:!0,excludeTimestamps:!0,disableConsoleLogs:!0}).child({version:"1.0.18"});var Wl=!1,fv=(()=>{try{return pv("/.dockerenv"),!0}catch{return!1}})();async function tt(r,e){if(Gh||Wl||fv)return!0;$.flush(),await new Promise(i=>setTimeout(i,500));let t=Kh.createInterface({input:process.stdin,output:process.stdout}),n=r.split("."),o;if(n.length===1)o=r;else{let i=`${n.slice(0,n.length-1).join(".").trim()}.`;e?E.warn(i):E.log(i),o=n[n.length-1].trim()}let s=await t.question(`${o} ('y' for yes / n for no / 'A' to accept all) `);return t.close(),s==="A"?(Wl=!0,setTimeout(()=>{Wl=!1},3e3),!0):s.toLowerCase()==="y"}async function jl(r){let e=hv(r);return Mo(e)?uv(r)?tt(`File '${qh(r)}' already exists. Overwrite existing content?`,!0):!0:await tt(`Directory '${qh(e)}' doesn't exist. Create it now?`,!0)?(mv(e,{recursive:!0}),!0):!1}function qh(r){return r.replace(/(\s+)/g,"\\$1")}async function Yh(r){let e=Kh.createInterface({input:process.stdin,output:process.stdout}),t=await e.question(`${r} `);return e.close(),t.trim()}import{cloneDeep as gv}from"lodash-es";async function Pi({client:r,skipPrompts:e,project:t}){let n=await r.getAllEnvironments(),o=gv(t.config);o.environments||(o.environments=[]);for(let s of n){let i=o.environments?.find(a=>a.name===s.name);if(i)!e&&!await tt(`Environment ${s.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),i.baseUrl=s.variables[oe],delete s.variables[oe],i.envVariables=s.variables;else{let a=s.variables[oe];delete s.variables[oe],o.environments.push({name:s.name,baseUrl:a,envVariables:s.variables})}}vn(o,t.configFilePath),E.success(`Pulled ${n.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as Xh}from"crypto";import Jh from"fs";async function Qh({testsToFetch:r,client:e,all:t,yes:n}){let{tests:o,modules:s}=await e.getTestYAMLExport({paths:r,all:t}),i=0;for(let[l,c]of Object.entries(o)){let u=Zh(l,ne.TEST);!n&&!await jl(u)||(i+=1,Jh.writeFileSync(u,c,"utf-8"),$.info({checksum:Xh("md5").update(c).digest("hex")},`Wrote '${u}'`))}let a=0;for(let[l,c]of Object.entries(s)){let u=Zh(l,ne.MODULE);!n&&!await jl(u)||(a+=1,Jh.writeFileSync(u,c,"utf-8"),$.info({checksum:Xh("md5").update(c).digest("hex")},`Wrote '${u}'`))}i===0?E.success("Pulled 0 tests."):E.success(`Pulled ${i} test${i>1?"s":""}${a?` and ${a} module${a>1?"s":""}`:""}!`)}function Zh(r,e){switch(e){case ne.TEST:return`${ge(r)}.${zt.TEST}`;case ne.MODULE:return`${ge(r)}.${zt.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function ef(r){let{project:e,client:t,skipPrompts:n}=r;E.info("Welcome to the Momentic Cloud importer wizard! \u{1F636}\u200D\u{1F32B}\uFE0F"),E.info("Importing environments from Momentic Cloud."),E.info(`This command will overwrite all local environment configuration in ${e.configFilePath} with environments from Momentic Cloud.`),await tt("Are you sure you want to proceed?",!0)||(E.info("Aborting..."),process.exit(1)),await Pi({client:t,project:e,skipPrompts:n}),E.success(`Successfully imported environments from Momentic Cloud. We recommend pulling secrets out of ${e.configFilePath} into .env files or dynamically set environment variables for security.`),E.info("Importing tests and modules from Momentic Cloud."),await Qh({testsToFetch:[],client:t,all:!0,yes:n}),E.success("Successfully imported tests and modules from Momentic Cloud. You can move them to the desired location in your project. We recommend committing these files to version control so you can share them with team members and run Momentic tests in CI.")}import rt from"fs";import _r from"path";import yv from"yaml";function tf(){Mo("momentic")||(E.error(`The migration command should be ran from the v0 root Momentic directory, which should contain a folder called 'momentic'. No folder named 'momentic' was found in the current working directory (${process.cwd()}).`),process.exit(1));let r={name:"default",include:Oo,environments:[]};E.info("Migrating environments");let e=rf(["momentic/environments"],Sv);for(let n of e){let o=yv.parse(rt.readFileSync(n,"utf-8"));try{let s=Yo.parse(o),i=s.variables[oe]??"";delete s.variables[oe],r.environments?.push({name:s.name,baseUrl:i,envVariables:s.variables})}catch(s){E.error(`${n} failed to parse as a valid environment file.`),E.error(s),process.exit(1)}}E.info("Migrating tests");let t=al("./momentic",E);for(let n of t){let o=_r.join(...n.fullPathSegments),s=_r.join(_r.dirname(o),`${n.fileName.slice(0,-5)}.test.yaml`);E.debug(`Moving test ${o} to ${s}`),rt.renameSync(o,s)}if(Mo("momentic/modules")){E.info("Migrating modules");for(let n of rt.readdirSync("./momentic/modules")){if(!n.endsWith(".yaml"))continue;let o=_r.resolve(_r.join("./momentic/modules",n));if(!rt.readFileSync(o,"utf-8").includes("schemaVersion")){E.warn(`Skipping file ${o} since it does not have valid Momentic module contents`);continue}let i=`${o.slice(0,-5)}.module.yaml`;E.debug(`Moving module ${o} to ${i}`),rt.renameSync(o,i)}}return E.debug("Writing new project configuration file"),vn(r,"momentic.config.yaml"),rt.rmSync("./momentic/environments",{recursive:!0,force:!0}),rt.rmSync("./momentic/fixtures",{recursive:!0,force:!0}),E.success("Migration succeeded!"),E.info("Going forward:"),E.info(` - You can store test and module files anywhere under the project root (${process.cwd()})`),E.info(" - Environment details and other common options are tracked in the root momentic.config.yaml file"),r}function rf(r,e,t=new Set){for(let n of r){let o=_r.resolve(n),s=!1;try{s=rt.existsSync(o)&&rt.statSync(o).isDirectory()}catch(i){E.error({err:i},`Error reading path ${o} during collect paths`)}if(o&&s){let i=rt.readdirSync(o).map(a=>_r.join(o,a));rf(i,e,t);continue}if(o.endsWith(".yaml")){try{if(!rt.existsSync(o)||!rt.statSync(o).isFile()){E.warn(`File not found or unreadable: ${o}`);continue}}catch(i){E.error({err:i},`Error reading file ${o} during collect paths`);continue}if(!e(o))continue;t.add(o)}}return t}function Sv(r){return r.endsWith(".yaml")?rt.readFileSync(r,"utf8").includes("momentic/environment")?!0:(E.warn(`Skipping YAML that is not a Momentic environment: ${r}`),!1):!1}import{Argument as Oi,Option as ae}from"@commander-js/extra-typings";import{validateHeaderValue as wv}from"http";import{cpus as nf}from"os";import{parse as bv}from"yaml";import{z as _}from"zod";var Li=58888,Gl=30*60*1e3,kr=new ae("--api-key <key>","API key for authentication. If not supplied, attempts to read the MOMENTIC_API_KEY env var."),xn=new ae("--server <server>","Momentic server to use. Leave unchanged unless using Momentic on-premise."),Dr=new ae("-y, --yes","Skip all confirmation prompts."),Vl=new ae("-w, --wait","Wait for tests to finish running before exiting. Only applicable when running tests remotely").implies({remote:!0}),ql=new ae("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Only applicable when the --wait option is specified. Defaults to ${Gl/1e3} seconds.`),Mi=new ae("--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."),Kl=new ae("--no-report","Skip reporting test results to Momentic Cloud when running with the --local flag.").implies({local:!0}),of=new ae("--reporter <reporter>","Output report files in a standardized format to a local directory. See the --reporter-dir flag for information on the output directory.").choices(Object.values(ms)),sf=new ae("--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. Defaults to 'reports' if unset."),af=new ae("--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."),lf=new ae("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),Yl=new ae("--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."),cf=new ae("--port <port>",`Port to run the app on. Defaults to ${Li}.`),Xl=new ae("--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."),Ni=new ae("--env <env>","Name of the environment to use when running tests."),_i=new ae("--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."),df=new ae("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(r=>parseInt(r,10)),_o=new ae("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file (*.momentic.config.yaml)"),uf=new ae("-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."),mf=new ae("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(r=>parseInt(r,10)),pf=new Oi("<tests...>",`One or more test paths to queue on Momentic Cloud.
|
|
1981
|
+
${n.map(o=>o.configFilePath)}`);if(n.length===0)throw new Error("No valid Momentic project file available.");return n[0]}function DC(r){let e=_C(r);if(!e||!e.projects||!e.projects.length)return;let t=e.projects.map(s=>(s.endsWith("/")||(s+="/"),`${s}*${Cn}`)),n=En(t,{absolute:!1,cwd:Ll(),dotRelative:!1,maxDepth:Ol,nodir:!0}),o=[];for(let s of n){let i=ur.join(Ll(),s),a=Ml(i);a&&o.push({configFilePath:i,config:a,rootDir:Eh(i)})}return o}function Nl(r){if(r){r=ur.resolve(r);let t=Ml(r);if(!t)throw new Error("No valid Momentic project file available.");return[{config:t,configFilePath:r,rootDir:ur.dirname(r)}]}if(AC(Th)){let t=DC(Th);if(t)return t}return kC()}function vn(r,e){let t=Ch.stringify(r);IC(e,t)}var kl="https://api.momentic.ai",Ah,xh=r=>{kl=r},Lo=()=>kl,Rh=r=>{Ah=r},Te=()=>Ah,An,_l,Ih=async r=>{if(An)return An;let e=new Be({baseUrl:kl,apiKey:r});try{return An=await e.getOrgId(),_l=r,An}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Ei=()=>{if(!An)throw new Error("Your organization ID appears invalid. Please contact Momentic support.");return An},Ph=()=>{if(!_l)throw new Error("Your API key appears invalid. Please contact Momentic support.");return _l};import Oh,{multistream as FC}from"pino";import UC from"pino-pretty";var Dl=new Map,$C=!0,Fl=class r{consoleLogger;ddClientToken;hostname;bindingAttributes;excludeAttributesInConsoleLogs;excludeTimestamps;disableConsoleLogs;site="https://http-intake.logs.us5.datadoghq.com/api/v2/logs";constructor({bindings:e,clientToken:t,hostname:n,excludeAttributesInConsoleLogs:o,excludeTimestamps:s,disableConsoleLogs:i}){this.ddClientToken=t,this.hostname=n,this.excludeAttributesInConsoleLogs=o,this.excludeTimestamps=s,this.disableConsoleLogs=i,this.bindingAttributes={...e,env:"production"};let a={base:o?{}:this.bindingAttributes,errorKey:"err",level:"debug",timestamp:!s};this.consoleLogger=$C?Oh(a):Oh(a,FC([{stream:UC({colorize:!0})}]))}child(e){return new r({clientToken:this.ddClientToken,bindings:{...this.bindingAttributes,...e},hostname:this.hostname,excludeAttributesInConsoleLogs:this.excludeAttributesInConsoleLogs,disableConsoleLogs:this.disableConsoleLogs})}flush(e){this.disableConsoleLogs||this.consoleLogger.flush(e)}log(e,t,n,...o){if(t&&n===void 0&&(n=`${t}`,t={}),this.disableConsoleLogs||this.consoleLogger[e](e==="error"?t:{testId:t.testId,runId:t.runId},n,...o),typeof t=="object"&&t&&"err"in t&&t.err instanceof Error){let i={};for(let a of Object.getOwnPropertyNames(t.err))i[a]=t.err[a];i.name=t.err.name,t.err=i}let s=Object.assign({},this.bindingAttributes,t&&typeof t=="object"?t:{});o.length>0&&(s.args=o),(async()=>{try{let i=await fetch(this.site,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","DD-API-KEY":this.ddClientToken},body:JSON.stringify([{ddsource:this.bindingAttributes.app,hostname:this.hostname??"vercel",service:"momentic",message:{message:n||"",...s,level:e}}])});if(!i.ok)throw new Error(`Failed to log to Datadog: ${i.statusText})}`)}catch(i){this.disableConsoleLogs||this.consoleLogger.warn({obj:t,msg:n,args:o,err:i},"Failed to log to Datadog")}})()}debug(e,t,...n){this.log("debug",e,t,...n)}info(e,t,...n){this.log("info",e,t,...n)}warn(e,t,...n){this.log("warn",e,t,...n)}error(e,t,...n){this.log("error",e,t,...n)}bindings(){return this.bindingAttributes}addBinding(e,t){this.bindingAttributes[e]=t}setMinLevel(e){this.consoleLogger.level=e}enableConsoleLogs(){this.disableConsoleLogs=!1}},Ci=({app:r,clientToken:e,hostname:t,excludeAttributesInConsoleLogs:n,excludeTimestamps:o,disableConsoleLogs:s})=>{if(!process.env.DD_CLIENT_TOKEN&&!process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN&&!e)throw new Error("Missing DD_CLIENT_TOKEN");return Dl.has(r)||Dl.set(r,new Fl({bindings:{app:r},hostname:t,clientToken:e||process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN||process.env.DD_CLIENT_TOKEN,excludeAttributesInConsoleLogs:n,excludeTimestamps:o,disableConsoleLogs:s})),Dl.get(r)};import{hostname as BC}from"os";var pe=Ci({app:"desktop-server",clientToken:"pubcfd7516a5c0ba852b42675cd97bee027",hostname:BC(),excludeAttributesInConsoleLogs:!0,excludeTimestamps:!0,disableConsoleLogs:!0}),Lh=r=>{pe.addBinding("version",r)};function Ae(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Mh=zC();Mh.get("/",Ae((r,e)=>{let t=Ep(Te(),pe);e.status(200).json(t)}));var Nh=Mh;import{Router as WC}from"express";import _h from"fs";import kh from"path";var vi=WC();vi.get("/",Ae(async(r,e)=>{let t=Ct(Te(),E),o=(await wp(t,pe)).filter(s=>s.enabled??!0);e.status(200).json(o)}));vi.post("/",Ae(async(r,e)=>{let t;try{t=Pd.parse(r.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}try{Vn(t.name)}catch(i){e.status(400).json({error:`Invalid module name: ${i}`});return}let n=Te(),o=kh.join(n.rootDir,n.config.moduleCreationDir??kh.dirname(t.testFilePath));if(!_h.existsSync(o)||!_h.statSync(o).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${o}' does not exist.`});return}let s=await Sp({...t,folder:o});e.status(201).json(s)}));vi.get("/:moduleId",Ae(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=Ct(Te(),E),n=t.modules[r.params.moduleId];if(!n){e.status(404).json({error:"Module not found."});return}try{let o=await il(n,t,E);e.json(o)}catch(o){e.status(400).json({err:o})}}));var Dh=vi;import{Router as jC}from"express";var Ai=jC();Ai.get("/",Ae((r,e)=>{let t=Nl().map(n=>({name:n.config.name,configFilePath:n.configFilePath}));e.status(200).json(t)}));Ai.get("/current",Ae((r,e)=>{let t=Te(),n={name:t.config.name,configFilePath:t.configFilePath};e.status(200).json(n)}));Ai.post("/set",Ae((r,e)=>{let t;try{t=Ld.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}try{let n=Mr({configFilePath:t.configFilePath});Rh(n)}catch(n){e.status(400).json({error:`Error setting project: ${n}`});return}e.sendStatus(204)}));var Fh=Ai;import{Router as HC}from"express";import Ul from"path";import{v4 as GC}from"uuid";var Nr=HC();Nr.get("/",Ae((r,e)=>{let t=Te(),n=Ct(t,E),o=Array.from(Object.values(n.tests));e.status(200).json(o)}));Nr.post("/",Ae(async(r,e)=>{let t;try{t=Id.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}try{Vn(t.name)}catch(c){e.status(400).json({error:c.message});return}let o={id:GC(),name:t.name,baseUrl:t.baseUrl,schemaVersion:ct,advanced:{disableAICaching:!1,browserType:t.browserType??"Chromium",viewport:t.viewport??$t},retries:0,steps:[]};t.environment&&(o.envs=[{name:t.environment,default:!0}]);let s=Te(),i=Ul.join(s.rootDir,s.config.testCreationDir??""),a=await bp({test:o,name:t.name,folder:i}),l={...o,relativeFilePath:Ul.relative(s.rootDir,a)};e.status(201).json(l)}));Nr.get("/:testPath",Ae(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n=Te(),o=Ct(n,E),s;try{s=await ri(Ul.join(n.rootDir,t),pe,o),e.status(200).json(s)}catch(i){e.status(400).send({error:i.message});return}(async()=>{try{let{stepsToSave:i,moduleUpdates:a}=await gt({steps:s.steps});a.forEach(l=>{sl(l.moduleId,{...l,schemaVersion:ct},o)}),mo(t,{schemaVersion:ct,steps:i},n)}catch(i){pe.error({err:i},"Failed to save migrated test to disk after initial fetch")}})()}));Nr.patch("/:testPath/metadata",Ae(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=Rd.parse(r.body)}catch(n){e.status(400).json({error:`Invalid request body: ${n}`});return}mo(r.params.testPath,t,Te()),e.status(201).json({message:"ok"})}));Nr.patch("/:testPath",Ae(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=xd.parse(r.body)}catch(d){e.status(400).json({error:`Invalid request body: ${d}`});return}let o=Te(),s=Ct(o,E),i;try{i=ti(t,o)}catch(d){e.status(400).json({error:`Existing test file on disk is invalid: ${d}`});return}let{stepsToSave:a,moduleUpdates:l,cachesToSave:c}=await gt({steps:n.steps,cacheCreationParams:{testId:i.id,orgId:Ei()}});await new Be({apiKey:Ph(),baseUrl:Lo()}).updateStepCaches({entries:c,testId:i.id}),l.forEach(d=>{sl(d.moduleId,{...d,schemaVersion:n.schemaVersion},s)}),mo(t,{steps:a,schemaVersion:n.schemaVersion},o),e.status(201).json({message:"ok"})}));Nr.patch("/:testPath/environments",Ae(async(r,e)=>{let{testPath:t}=r.params;if(!t){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Od.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}mo(t,{envs:n.defaultEnv?[{name:n.defaultEnv,default:!0}]:[]},Te()),e.status(201).json({message:"ok"})}));var Uh=Nr;var xi=class extends tn{constructor(t,n){super(t,n);this.client=t;this.orgId=n}async getOrgId(t){return this.orgId}async fetchTestMetadata(t,n,o){let s=Te(),a=Ct(s,o).tests[t];if(a)return ti(a.relativePath,s)}async fetchEnvironment(t,n,o){let s=Te();return po(n,s,o)}};async function Wh(r){let{momenticServerUrl:e,apiKey:t,serverPort:n,appPort:o,staticDir:s,devicePixelRatio:i,version:a}=r;Lh(a),e&&xh(e),pe.debug(r,"Initializing desktop server");let l=await Ih(t);pe.debug({orgId:l},"Checking API key successful");let u=`http://localhost:${n}`;o&&(u=`http://localhost:${o}`);let d=JC(s);await new Promise(y=>{d.listen(n,()=>{pe.info(`Server is running at http://localhost:${n}`),y()})});let p=new un({baseURL:Lo(),apiKey:t}),h={type:"API_KEY",baseUrl:Lo(),apiKey:t},f=new Be(h),g=new xi(f,Ei());yp({baseServer:d,generator:p,storage:g,logger:pe,devicePixelRatio:i,authorization:h}),await XC(u)}var zh="25mb";function JC(r){let e=Bh();e.use(VC()),e.use($h.json({limit:zh})),e.use($h.urlencoded({extended:!1,limit:zh}));let t=KC();if(t.use("/tests",Uh),t.use("/modules",Dh),t.use("/environments",Nh),t.use("/projects",Fh),e.use("/api",t),e.use((o,s,i)=>{o.path!=="/healthcheck"&&pe.debug({url:o.url,path:o.path,query:o.query,method:o.method,body:o.body,headers:o.rawHeaders,client:o.ip},"Received desktop-server request"),s.on("close",()=>{s.statusCode>=400&&pe.error({url:o.url,method:o.method,statusCode:s.statusCode},"Request completed in error")}),i()}),e.use((o,s,i,a)=>{if(o instanceof Error&&o.message.includes("BadRequestError: request aborted")){i.status(400).send("Client disconnected");return}pe.error({stack:o.stack,msg:o.message,err:o,url:s.url,method:s.method},"Unhandled exception leading to 500 on desktop-server"),E.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${o.message}`),i.status(500).send("Internal Server Error")}),r){let o=Bh.static(r);e.use("/",o),e.use("*",o)}return YC.createServer(e)}qC.setMaxListeners(50);process.on("warning",r=>{pe.warn({err:r},`Node warning received on desktop-server: ${r.message}`)});process.on("uncaughtException",r=>{pe.error({err:r},"Uncaught exception leading to exit on desktop-server")});process.on("unhandledRejection",(r,e)=>{pe.error({reason:`${r}`,promise:`${e}`,stack:r?.stack},"Uncaught exception leading to exit on desktop-server (promise rejection)")});import qv from"events";import _f from"fs";import Wi from"path";import{fileURLToPath as Kv}from"url";import{existsSync as uv,mkdirSync as mv,statSync as pv}from"fs";import{dirname as hv}from"path";import Kh from"readline/promises";import{execSync as ZC}from"child_process";import{platform as QC}from"os";function $l(){return jh()?(E.info("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),E.info("If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations."),E.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),2):(E.info("Setting device pixel ratio to 1."),E.info("If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations"),E.info("Confirm your device's pixel-ratio at https://www.mydevice.io."),1)}function jh(){return QC()==="darwin"&&ZC("system_profiler SPDisplaysDataType").toString().includes("Retina")}function Bl(r){jh()&&r===1&&(E.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),E.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import ev from"@actions/exec";import tv from"@actions/io";import rv from"quote";import nv from"string-argv";async function Hh(r,e=!0){let t=nv(r),n=await tv.which(t[0],!0),o=t.slice(1),s=ev.exec(rv(n),o,{delay:100});if(e)return s}import{existsSync as ov,statSync as sv}from"fs";var Gh=!!process.env.CI||!process.stdout.isTTY;function Mo(r){try{return ov(r)&&sv(r).isDirectory()}catch(e){return E.error({err:e},`Error reading path ${r} during directory existence check`),!1}}import iv from"csv-parser";import{createReadStream as av}from"fs";function zl(r){return new Promise((e,t)=>{let n=[];av(r).pipe(iv()).on("data",o=>n.push(o)).on("end",()=>e(n)).on("error",o=>t(o))})}import Ri from"semver";import{z as Ii}from"zod";var No="1.0.19",lv="https://registry.npmjs.org/momentic",cv=Ii.object({versions:Ii.record(Ii.string(),Ii.unknown()).optional()});async function Vh(r){if(!No){r.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let n=0;n<2;n++)try{let o=await J(fetch(lv),{milliseconds:2e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let s=await o.json();e=cv.parse(s).versions;break}catch(o){r.warn({err:o},"Failed to fetch npm registry data")}if(!e){r.warn("Failed to fetch npm registry data. Skipping version check.");return}let t;for(let n of Object.keys(e))Ri.valid(n)&&(!t||Ri.gt(n,t))&&Ri.gt(n,No)&&Ri.lt(n,"2.0.0")&&(t=n);t&&(E.warn(`Update available: v${No} -> v${t}`),E.warn("This version ay be missing critical fixes, features, and security updates."),E.warn(`Run "npx momentic@${t} -V" to update`))}import{hostname as dv}from"os";var $=Ci({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:dv(),excludeAttributesInConsoleLogs:!0,excludeTimestamps:!0,disableConsoleLogs:!0}).child({version:"1.0.19"});var Wl=!1,fv=(()=>{try{return pv("/.dockerenv"),!0}catch{return!1}})();async function tt(r,e){if(Gh||Wl||fv)return!0;$.flush(),await new Promise(i=>setTimeout(i,500));let t=Kh.createInterface({input:process.stdin,output:process.stdout}),n=r.split("."),o;if(n.length===1)o=r;else{let i=`${n.slice(0,n.length-1).join(".").trim()}.`;e?E.warn(i):E.log(i),o=n[n.length-1].trim()}let s=await t.question(`${o} ('y' for yes / n for no / 'A' to accept all) `);return t.close(),s==="A"?(Wl=!0,setTimeout(()=>{Wl=!1},3e3),!0):s.toLowerCase()==="y"}async function jl(r){let e=hv(r);return Mo(e)?uv(r)?tt(`File '${qh(r)}' already exists. Overwrite existing content?`,!0):!0:await tt(`Directory '${qh(e)}' doesn't exist. Create it now?`,!0)?(mv(e,{recursive:!0}),!0):!1}function qh(r){return r.replace(/(\s+)/g,"\\$1")}async function Yh(r){let e=Kh.createInterface({input:process.stdin,output:process.stdout}),t=await e.question(`${r} `);return e.close(),t.trim()}import{cloneDeep as gv}from"lodash-es";async function Pi({client:r,skipPrompts:e,project:t}){let n=await r.getAllEnvironments(),o=gv(t.config);o.environments||(o.environments=[]);for(let s of n){let i=o.environments?.find(a=>a.name===s.name);if(i)!e&&!await tt(`Environment ${s.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),i.baseUrl=s.variables[oe],delete s.variables[oe],i.envVariables=s.variables;else{let a=s.variables[oe];delete s.variables[oe],o.environments.push({name:s.name,baseUrl:a,envVariables:s.variables})}}vn(o,t.configFilePath),E.success(`Pulled ${n.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as Xh}from"crypto";import Jh from"fs";async function Qh({testsToFetch:r,client:e,all:t,yes:n}){let{tests:o,modules:s}=await e.getTestYAMLExport({paths:r,all:t}),i=0;for(let[l,c]of Object.entries(o)){let u=Zh(l,ne.TEST);!n&&!await jl(u)||(i+=1,Jh.writeFileSync(u,c,"utf-8"),$.info({checksum:Xh("md5").update(c).digest("hex")},`Wrote '${u}'`))}let a=0;for(let[l,c]of Object.entries(s)){let u=Zh(l,ne.MODULE);!n&&!await jl(u)||(a+=1,Jh.writeFileSync(u,c,"utf-8"),$.info({checksum:Xh("md5").update(c).digest("hex")},`Wrote '${u}'`))}i===0?E.success("Pulled 0 tests."):E.success(`Pulled ${i} test${i>1?"s":""}${a?` and ${a} module${a>1?"s":""}`:""}!`)}function Zh(r,e){switch(e){case ne.TEST:return`${ge(r)}.${zt.TEST}`;case ne.MODULE:return`${ge(r)}.${zt.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function ef(r){let{project:e,client:t,skipPrompts:n}=r;E.info("Welcome to the Momentic Cloud importer wizard! \u{1F636}\u200D\u{1F32B}\uFE0F"),E.info("Importing environments from Momentic Cloud."),E.info(`This command will overwrite all local environment configuration in ${e.configFilePath} with environments from Momentic Cloud.`),await tt("Are you sure you want to proceed?",!0)||(E.info("Aborting..."),process.exit(1)),await Pi({client:t,project:e,skipPrompts:n}),E.success(`Successfully imported environments from Momentic Cloud. We recommend pulling secrets out of ${e.configFilePath} into .env files or dynamically set environment variables for security.`),E.info("Importing tests and modules from Momentic Cloud."),await Qh({testsToFetch:[],client:t,all:!0,yes:n}),E.success("Successfully imported tests and modules from Momentic Cloud. You can move them to the desired location in your project. We recommend committing these files to version control so you can share them with team members and run Momentic tests in CI.")}import rt from"fs";import _r from"path";import yv from"yaml";function tf(){Mo("momentic")||(E.error(`The migration command should be ran from the v0 root Momentic directory, which should contain a folder called 'momentic'. No folder named 'momentic' was found in the current working directory (${process.cwd()}).`),process.exit(1));let r={name:"default",include:Oo,environments:[]};E.info("Migrating environments");let e=rf(["momentic/environments"],Sv);for(let n of e){let o=yv.parse(rt.readFileSync(n,"utf-8"));try{let s=Yo.parse(o),i=s.variables[oe]??"";delete s.variables[oe],r.environments?.push({name:s.name,baseUrl:i,envVariables:s.variables})}catch(s){E.error(`${n} failed to parse as a valid environment file.`),E.error(s),process.exit(1)}}E.info("Migrating tests");let t=al("./momentic",E);for(let n of t){let o=_r.join(...n.fullPathSegments),s=_r.join(_r.dirname(o),`${n.fileName.slice(0,-5)}.test.yaml`);E.debug(`Moving test ${o} to ${s}`),rt.renameSync(o,s)}if(Mo("momentic/modules")){E.info("Migrating modules");for(let n of rt.readdirSync("./momentic/modules")){if(!n.endsWith(".yaml"))continue;let o=_r.resolve(_r.join("./momentic/modules",n));if(!rt.readFileSync(o,"utf-8").includes("schemaVersion")){E.warn(`Skipping file ${o} since it does not have valid Momentic module contents`);continue}let i=`${o.slice(0,-5)}.module.yaml`;E.debug(`Moving module ${o} to ${i}`),rt.renameSync(o,i)}}return E.debug("Writing new project configuration file"),vn(r,"momentic.config.yaml"),rt.rmSync("./momentic/environments",{recursive:!0,force:!0}),rt.rmSync("./momentic/fixtures",{recursive:!0,force:!0}),E.success("Migration succeeded!"),E.info("Going forward:"),E.info(` - You can store test and module files anywhere under the project root (${process.cwd()})`),E.info(" - Environment details and other common options are tracked in the root momentic.config.yaml file"),r}function rf(r,e,t=new Set){for(let n of r){let o=_r.resolve(n),s=!1;try{s=rt.existsSync(o)&&rt.statSync(o).isDirectory()}catch(i){E.error({err:i},`Error reading path ${o} during collect paths`)}if(o&&s){let i=rt.readdirSync(o).map(a=>_r.join(o,a));rf(i,e,t);continue}if(o.endsWith(".yaml")){try{if(!rt.existsSync(o)||!rt.statSync(o).isFile()){E.warn(`File not found or unreadable: ${o}`);continue}}catch(i){E.error({err:i},`Error reading file ${o} during collect paths`);continue}if(!e(o))continue;t.add(o)}}return t}function Sv(r){return r.endsWith(".yaml")?rt.readFileSync(r,"utf8").includes("momentic/environment")?!0:(E.warn(`Skipping YAML that is not a Momentic environment: ${r}`),!1):!1}import{Argument as Oi,Option as ae}from"@commander-js/extra-typings";import{validateHeaderValue as wv}from"http";import{cpus as nf}from"os";import{parse as bv}from"yaml";import{z as _}from"zod";var Li=58888,Gl=30*60*1e3,kr=new ae("--api-key <key>","API key for authentication. If not supplied, attempts to read the MOMENTIC_API_KEY env var."),xn=new ae("--server <server>","Momentic server to use. Leave unchanged unless using Momentic on-premise."),Dr=new ae("-y, --yes","Skip all confirmation prompts."),Vl=new ae("-w, --wait","Wait for tests to finish running before exiting. Only applicable when running tests remotely").implies({remote:!0}),ql=new ae("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Only applicable when the --wait option is specified. Defaults to ${Gl/1e3} seconds.`),Mi=new ae("--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."),Kl=new ae("--no-report","Skip reporting test results to Momentic Cloud when running with the --local flag.").implies({local:!0}),of=new ae("--reporter <reporter>","Output report files in a standardized format to a local directory. See the --reporter-dir flag for information on the output directory.").choices(Object.values(ms)),sf=new ae("--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. Defaults to 'reports' if unset."),af=new ae("--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."),lf=new ae("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),Yl=new ae("--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."),cf=new ae("--port <port>",`Port to run the app on. Defaults to ${Li}.`),Xl=new ae("--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."),Ni=new ae("--env <env>","Name of the environment to use when running tests."),_i=new ae("--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."),df=new ae("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(r=>parseInt(r,10)),_o=new ae("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file (*.momentic.config.yaml)"),uf=new ae("-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."),mf=new ae("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(r=>parseInt(r,10)),pf=new Oi("<tests...>",`One or more test paths to queue on Momentic Cloud.
|
|
1982
1982
|
|
|
1983
1983
|
A test path is a lowercased version of your test name where spaces are replaced with dashes: 'npx momentic@latest pull hello-world'.`),hf=new Oi("<tests...>","One or more test file path or folders that exist on the local machine: 'npx momentic@latest run hello-world.test.yaml'.").argOptional(),ff=new Oi("<suites...>",`One or more suite paths that exist on Momentic Cloud.
|
|
1984
1984
|
|
|
@@ -1994,4 +1994,4 @@ ${r.map(c=>` - ${c}`).join(`
|
|
|
1994
1994
|
`)}`),Object.values(e.tests).forEach(c=>{r.some(u=>c.relativePath.includes(u))&&i.add(c.fullFilePath)}))}else{!n&&!await tt("No test paths or substrings were provided. Do you want to run all tests?")&&(E.error("Cancelled by user."),process.exit(1));let a=Object.values(e.tests);E.info(`Reading all ${a.length} tests in the project from local disk.`),a.forEach(l=>{i.add(l.fullFilePath)})}for(let a of i){let l=If.relative(t.rootDir,a);o&&!o.some(c=>new RegExp(c).test(l))&&i.delete(a),s&&s.some(c=>new RegExp(c).test(l))&&i.delete(a)}return i}import{diff as Fv}from"deep-object-diff";import{cloneDeep as Of}from"lodash-es";import Uv from"semver";import{debounce as $v}from"ts-debounce";import{v4 as Lf}from"uuid";var zi=class extends ue{async runTemplateMatching(e){let t=await this.sendRequest(`/${ue.API_VERSION}/web-agent/template-matching`,e);return hs.parse(t)}};async function Mf(r){let e=new Date,{fullFilePath:t,momenticFiles:n}=r,o;try{o=await ri(t,$,n)}catch(s){E.error(`Failed to read and resolve test at '${t}': ${s}`),process.exit(1)}Uv.gt(o.schemaVersion,ct)&&E.warn(`Test ${t} has schema version ${o.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`);try{return await Bv(o,r)}catch(s){return E.error(`Fatal error running test: ${s.message}`),{parameters:r,failureReason:"UnknownError",failureDetails:{errorMessage:s.message,errorStack:s.stack},status:"FAILED",attempts:0,test:o,filePath:t,startedAt:e,finishedAt:new Date}}}async function Bv(r,{fullFilePath:e,project:t,apiClient:n,generator:o,orgId:s,retriesOverride:i,noReport:a,envName:l,urlOverride:c,devicePixelRatio:u,customHeaders:d,testInputs:m}){let p=new Date,h={envName:l,urlOverride:c,customHeaders:d,testInputs:m},f=new tn(n,s);try{await f.resolveStepCacheEntries({organizationId:s,testId:r.id,steps:r.steps,schemaVersion:r.schemaVersion,logger:$})}catch(x){throw $.error({err:x},"Failed to resolve step cache entries"),new Error(`Failed to resolve step cache entries. Please ensure you are running using a supported version of Momentic. If you believe this is an error, please contact Momentic Support with the following error: ${x}`)}if(!l){for(let x of r.envs??[])if(x.default){l=x.name;break}}let g,y={};if(l){try{g=po(l,t,$)}catch(x){let j=`Failed to resolve environment ${l} for test ${r.name}: ${x}`;throw new Error(j)}y=g.variables}let S=r.baseUrl;if(c)S=c;else if(!S){let x=y[oe];typeof x=="string"&&(S=x)}if(!S){let x=`Cannot run test with no base URL and no ${oe} variable defined in its environment`;throw new Error(x)}let w;if(a)w=Lf();else try{w=(await n.createRun({testId:r.id,testName:r.name,trigger:"CLI",resolvedBaseUrl:S,schemaVersion:r.schemaVersion})).id}catch(x){throw $.error({err:x,testId:r.id},"Error creating run on Momentic Cloud"),new Error(`Error creating run on Momentic Cloud. Please ensure Momentic is accessible from your environment.
|
|
1995
1995
|
If you believe this is an error, please contact Momentic Support with the following error message: ${x}`)}let T=$.child({testId:r.id,runId:w}),C=async x=>{if(!a)try{await n.updateRun(w,x)}catch(j){T.warn({err:j},`Failed to update run status for test ${w}. You may see stale data on the Momentic Cloud Server.`)}},A,I=Math.max(i??r.retries,0),O=[];for(let x=0;x<=I;x++){let j=Lf();if(!a)try{j=(await n.createRunAttempt(w)).id}catch(P){throw $.error({err:P,testId:r.id,runId:w},"Error creating run attempt on Momentic Cloud"),new Error("Error creating run attempt on Momentic Cloud. Please ensure Momentic is accessible from your environment or pass the --no-report flag.")}let H=async P=>{if(!a)try{await n.updateRunAttempt(w,j,P)}catch(xe){T.warn({err:xe},`Failed to update run attempt for attempt ${j}. You may see stale data on the Momentic Cloud Server.`)}};try{await C({status:"RUNNING",attempts:x+1});let{controller:P,context:xe}=await zv({baseUrl:S,envName:l,apiClient:n,devicePixelRatio:u,logger:T,storageClient:f,test:r,generator:o,orgId:s,variables:y,customHeaders:d,testInputs:m,localBrowserConfigFromEnv:g?.browser});if(A=await Wv({logger:T,storageClient:f,apiClient:n,test:r,orgId:s,runId:w,context:xe,controller:P,noReport:a}),await H({status:A.status,finishedAt:new Date}),O.unshift(A.status),A.status!=="FAILED")return await C({status:A.status,finishedAt:new Date,flake:od(O)}),{...A,parameters:h,runId:w,test:r,filePath:e,startedAt:p,finishedAt:new Date,attempts:x+1,baseUrl:S};let Re=A.failedStepResult,Ft=Re?.message||"Unknown failure";if(x<I){T.warn({errResult:Re},`Test '${r.name}' failed attempt ${x+1} of ${I+1}, retrying...`);continue}T.error({errResult:Re},`Test '${r.name}' failed after all exhausting ${I+1} attempts: ${Ft}
|
|
1996
1996
|
`),await C({status:"FAILED",failureReason:Re?.failureReason,finishedAt:new Date});let pr={errorMessage:Ft},L=Re?.failureReason??dd(Ft)??"UnknownError";return await C({status:"FAILED",finishedAt:new Date,failureDetails:pr,failureReason:L}),{...A,parameters:h,runId:w,failureDetails:pr,failureReason:L,test:r,filePath:e,startedAt:p,finishedAt:new Date,attempts:x+1,baseUrl:S}}catch(P){T.error({err:P},`Encountered fatal platform error while running test '${r.name}': ${P}`);let xe={errorMessage:P.message,errStack:P.stack},Re={status:"FAILED",failureDetails:xe,failureReason:"UnknownError",finishedAt:new Date};return await Promise.all([H(Re),C(Re)]),{...Re,parameters:h,runId:w,test:r,filePath:e,startedAt:p,finishedAt:new Date,attempts:x+1,baseUrl:S}}}throw new Error("This code should not be reachable")}async function zv({baseUrl:r,envName:e,devicePixelRatio:t,apiClient:n,test:o,storageClient:s,generator:i,orgId:a,variables:l,logger:c,customHeaders:u,testInputs:d,localBrowserConfigFromEnv:m}){let p={...m,...qn.parse(o.advanced)};u&&(p.extraHeaders={...p.extraHeaders??{},...u});let h=await Gt.init({baseUrl:r,logger:c,userBrowserSettings:p,storage:s,enricher:new zi({baseURL:n.baseUrl,apiKey:n.apiKey}),timeout:p.pageLoadTimeoutMs,contextArgs:{viewport:o.advanced.viewport??$t,deviceScaleFactor:t}}),f=new yt({httpClient:new Ze({baseUrl:n.baseUrl,apiKey:n.apiKey})}),g=new dn({browser:h,generator:i,config:Js,logger:c,orgId:a,storage:s,flagStore:await sn.init(a),localCodeEvalTools:f}),y=new Ve({baseUrl:r,currentUrl:g.browser.url(),variablesFromEnvironment:l,envName:e});return o.parameters&&await Promise.all(o.parameters.map(async S=>{let{name:w,defaultValue:T,required:C}=S,A=d?.[w];C&&A===void 0&&(E.error(`Required parameter '${w}' is required by test '${o.name}' but not provided`),process.exit(1));let I=await St({orgId:a,s:A??T,localTools:f,logger:c,context:Ve.dummyContext(y.getEnvName())});y.setMomenticSystemVariable(w,I)})),{controller:g,context:y}}async function Wv({storageClient:r,apiClient:e,test:t,orgId:n,runId:o,context:s,controller:i,noReport:a,logger:l}){$.info(`Running test '${t.name}' locally${a?"":` and reporting results to https://app.momentic.ai/runs/${o}`}`);let c=Of(t.steps),u=async w=>{try{if(w.results){let T=Of(w.results);Es(T,$),w.results=T}await e.updateRun(o,w)}catch(T){l.warn({err:T},"Failed to update run data. You may see stale data on the Momentic Cloud Server.")}},d,m=$v(async w=>{a||await u(w)},1e4,{maxWait:3e4}),p=new yt({httpClient:new Ze({baseUrl:e.baseUrl,apiKey:e.apiKey})}),h={controller:i,storage:r,context:s,logger:l,codeEvalTools:p},f={orgId:n,runId:o,testMetadata:t,steps:t.steps},S=await ks({fixtures:h,inputs:f,options:{takeScreenshots:!0,consumeDebuggingData:!0,reinitializeBrowser:!0},callbacks:{step:{},test:{onTestComplete:async()=>{await i.browser.cleanup()},onSaveScreenshot:async w=>{if(a)return"";let{key:T}=await e.uploadScreenshot({screenshot:w.toString("base64")});return T},onUpdateRun:w=>{d=Promise.resolve(m(w))},onProposedTestSteps:async w=>e.uploadProposedSteps(w,l),onTestSuccess:async w=>{let T=Fv(c,w);if(Object.keys(T).length===0){l.debug("No changes to test steps after success");return}l.debug({changes:T},"Updating steps post-run success in worker");try{let{cachesToSave:C}=await gt({steps:w,cacheCreationParams:{testId:t.id,orgId:n}});await e.updateStepCaches({testId:t.id,entries:C})}catch(C){l.error({err:C},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}}});return d&&(l.info("Waiting for last run update to finish"),await Promise.resolve(d)),S}async function Nf(r){let{tests:e,yes:t,start:n,waitOn:o,client:s,project:i,report:a,retriesOverride:l,urlOverride:c,envName:u,orgId:d,devicePixelRatio:m,customHeaders:p,testInputMatrix:h,reporter:f,include:g,exclude:y,reporterDir:S="reports",waitOnTimeout:w=60,parallel:T=1,shardIndex:C=1,shardCount:A=1}=r;n&&($.info({orgId:d},`Executing start command: ${n}`),await Hh(n,!1)),o&&($.info({orgId:d},`Waiting for url: ${o} with timeout: ${w} seconds.`),await jv({resources:[o],interval:2500,timeout:w*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let I=new un({baseURL:s.baseUrl,apiKey:s.apiKey}),O=Ct(i,E),x=await Pf({tests:e,momenticFiles:O,yes:t,project:i,include:g,exclude:y}),j=Array.from(x),H=[];j.forEach((L,Fe)=>{h?h.forEach((Ut,Ur)=>{H.push({path:L,testIndex:Fe,inputs:Ut,inputIndex:Ur})}):H.push({path:L,testIndex:Fe,inputs:void 0,inputIndex:void 0})}),A&&A>1&&(H=Hv(H,C,A)),$.info({allTestsToRunWithInputs:H,shardCount:A,shardIndex:C,orgId:d},`Running ${H.length} tests with ${T} workers`),E.dimmed(`Running ${H.length} tests with ${T} workers:`),H.forEach(L=>{E.dimmed(` ${L.path}${typeof L.inputIndex=="number"?` with input set ${L.inputIndex}`:""}`)}),E.log("");let P=[],xe=Date.now(),Re=new Set;for(let L=0;L<H.length;L+=T){let Fe=await Promise.all(H.slice(L,L+T).map(async({path:Ut,inputs:Ur})=>{Re.add({path:Ut,inputs:Ur});let k=()=>{E.log(`${Re.size}/${H.length} ${Ut}`)};k();let Df=setInterval(k,60*1e3);try{return await Mf({fullFilePath:Ut,momenticFiles:O,project:i,testInputs:Ur,orgId:d,devicePixelRatio:m,apiClient:s,generator:I,retriesOverride:l,urlOverride:c,envName:u,noReport:!a,customHeaders:p})}finally{clearInterval(Df)}}));P.push(...Fe)}let Ft=s.getAppUrl(),pr=Rn({results:P,startTime:xe,onFailed:L=>{$i(L,L.filePath)},getDisplayLine:L=>{let Fe=` ${L.filePath}`;return a&&L.runId&&(Fe+=` (${Ft}/runs/${L.runId})`),Fe},entity:"test"});return f&&await Rf(f,{suiteName:`on-demand-suite-${xe}`,startedAt:new Date(xe),finishedAt:new Date,runs:P},S??"reports"),pr}function Hv(r,e,t){if(t>r.length&&(E.warn(`Shard count ${t} is greater than the number of tests ${r.length}! Some workers won't have any tests to run.`),t=Math.max(t,r.length),e>t))return[];let n=Math.floor((e-1)*(r.length/t)),o=Math.floor(e*(r.length/t));return r.toSorted().filter((s,i)=>i>=n&&i<o)}await Vh($);var ht=new Gv;ht.name("momentic").description("Momentic CLI").version(No||"unknown");ht.command("install-browsers").action(async()=>{await Di()});ht.addOption(new mr("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",r=>{$.setMinLevel(r.toLowerCase()),E.setMinLevel(r.toLowerCase())});ht.addOption(new mr("--verbose","enable verbose logging")).on("option:verbose",()=>{$.enableConsoleLogs()});ht.command("check-config").addOption(_o).action(async r=>{Mr({configFilePath:r.config})});var Yv=ht.command("migrate").description("Migrate and upgrade tooling");Yv.command("v0-v1").addOption(Dr).addOption(kr).action(async r=>{let e=await Fr(r);if(!e.yes&&!await tt("This command will migrate and then delete your previous Momentic files. All members of your team should transition to the V1 CLI at the same time. Please backup your local directory for safety before proceeding. Continue?",!0)&&process.exit(1),!tf().environments?.length&&await tt("In the V1 CLI, all environment configuration should be committed to a central `momentic.config.yaml` file, which you should commit to your source control repository. Sensitive data can be managed through `.env` files or by injecting the secret into the environment and then referencing them in `envVariables` with ${VAR} syntax. Would you like to pull the latest environments from Momentic Cloud into your `momentic.config.yaml` file?",!0)){let{apiKey:n,server:o}=e,s=Mr({}),i=new Be({baseUrl:o,apiKey:n,logger:$});await Pi({client:i,project:s,skipPrompts:e.yes}),E.success("Successfully imported environments from Momentic Cloud.")}});ht.command("import-from-cloud").addOption(kr).addOption(xn).addOption(_o).addOption(Dr).action(async r=>{let e=await Fr(r),{apiKey:t,server:n,config:o,yes:s}=e,i=Mr({configFilePath:o}),a=new Be({baseUrl:n,apiKey:t,logger:$});await ef({client:a,project:i,skipPrompts:s}),process.exit(0)});ht.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new mr("--name <name>","Name of the project")).action(async r=>{E.info(`Welcome to the Momentic project setup wizard! \u{1F680}
|
|
1997
|
-
`),E.info("This wizard will help you bootstrap a new Momentic project. If need to import existing assets from Momentic Cloud, you can call the 'import-from-cloud' command after initialization."),_f.existsSync(Cn)&&(E.error("A momentic.config.yaml file already exists in this directory. Please rename or remove it to initialize a new project."),process.exit(1));let t={name:r.name??(await Yh("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):")||"app"),include:Oo};vn(t,Cn),E.success(`Initialized Momentic project file at ${Wi.resolve(Cn)}`)});ht.command("app").addOption(kr).addOption(xn).addOption(Dr).addOption(Yl).addOption(cf).addOption(_o).action(async r=>{let e=await Fr(r),{apiKey:t,port:n=Li,yes:o,server:s,pixelRatio:i}=e,a=new Be({baseUrl:s,apiKey:t,logger:$}),l=await Zl({client:a,skipPrompts:o,installBrowsers:!0});an.capture({event:"local app started",distinctId:l,properties:{organizationId:l}});let c=Kv(import.meta.url),u=Wi.dirname(c),d=Wi.resolve(u,"..","static"),m=Wi.resolve(u,"..","assets"),p=i??$l();Bl(p),await Wh({momenticServerUrl:s,apiKey:t,serverPort:n,appPort:n,staticDir:d,assetsDir:m,devicePixelRatio:p,version:"1.0.
|
|
1997
|
+
`),E.info("This wizard will help you bootstrap a new Momentic project. If need to import existing assets from Momentic Cloud, you can call the 'import-from-cloud' command after initialization."),_f.existsSync(Cn)&&(E.error("A momentic.config.yaml file already exists in this directory. Please rename or remove it to initialize a new project."),process.exit(1));let t={name:r.name??(await Yh("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):")||"app"),include:Oo};vn(t,Cn),E.success(`Initialized Momentic project file at ${Wi.resolve(Cn)}`)});ht.command("app").addOption(kr).addOption(xn).addOption(Dr).addOption(Yl).addOption(cf).addOption(_o).action(async r=>{let e=await Fr(r),{apiKey:t,port:n=Li,yes:o,server:s,pixelRatio:i}=e,a=new Be({baseUrl:s,apiKey:t,logger:$}),l=await Zl({client:a,skipPrompts:o,installBrowsers:!0});an.capture({event:"local app started",distinctId:l,properties:{organizationId:l}});let c=Kv(import.meta.url),u=Wi.dirname(c),d=Wi.resolve(u,"..","static"),m=Wi.resolve(u,"..","assets"),p=i??$l();Bl(p),await Wh({momenticServerUrl:s,apiKey:t,serverPort:n,appPort:n,staticDir:d,assetsDir:m,devicePixelRatio:p,version:"1.0.19"})});var kf=ht.command("queue").description("Queue tests or suites to run on Momentic Cloud");kf.command("suites").description("Run one or more suites on Momentic Cloud").addOption(kr).addOption(xn).addOption(Vl).addOption(ql).addOption(Dr).addArgument(ff).addOption(_i).addOption(Ni).addOption(Mi).action(async(r,e)=>{let{apiKey:t,server:n,wait:o,waitTimeout:s,env:i,urlOverride:a,customHeaders:l}=await Fr(e),c=new Be({baseUrl:n,apiKey:t,logger:$});(!r||!Array.isArray(r)||!r.length)&&(E.error("Must pass at least one suite to run."),process.exit(1));let u=await c.getOrgId();an.capture({event:"queue suites remotely",distinctId:u,properties:{organizationId:u,numSuites:r.length}}),await bf({client:c,orgId:u,wait:o,suitePaths:r,waitTimeout:s,env:i,urlOverride:a,customHeaders:ki(l)})});kf.command("tests").description("Run one or more tests on Momentic Cloud").addOption(kr).addOption(xn).addOption(Dr).addOption(Mi).addOption(Xl).addOption(_i).addOption(Ni).addOption(Vl).addOption(ql).addArgument(pf).action(async(r,e)=>{let t=await Fr(e),{all:n,apiKey:o,customHeaders:s,env:i,server:a,inputCsv:l,urlOverride:c,wait:u,waitTimeout:d,yes:m}=t,p=ki(s);for(let y of r)(y.endsWith(".yaml")||_f.existsSync(y))&&E.warn("Are you trying to run a test on your local machine? If so, please use the 'run' command instead of the 'queue' command");let h=new Be({baseUrl:a,apiKey:o,logger:$}),f=await h.getOrgId();an.capture({event:"queue tests remotely",distinctId:f,properties:{organizationId:f,numTests:r.length}});let g;l&&(g=await zl(l)),await Tf({client:h,orgId:f,tests:r,all:n,customHeaders:p,env:i,urlOverride:c,wait:u,waitTimeout:d,testInputMatrix:g,yes:m}),process.exit(0)});var Xv=ht.command("run").alias("test").description("Run tests on the local machine");Xv.addOption(kr).addOption(xn).addOption(_o).addOption(uf).addOption(Dr).addOption(Mi).addOption(Xl).addOption(Ni).addOption(_i).addOption(Kl).addOption(Yl).addOption(new mr("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new mr("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new mr("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.")).addOption(new mr("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.")).addOption(new mr("-p, --parallel <parallel>","When running with the --local flag, the number of tests to run in parallel. Defaults to 1.")).addOption(Kl).addOption(of).addOption(sf).addOption(df).addOption(mf).addOption(af).addOption(lf).addArgument(hf).action(async(r,e)=>{let t=await Fr(e),n=ki(t.customHeaders),o=Mr({configFilePath:t.config,nameFilter:t.filter}),s=new Be({baseUrl:t.server,apiKey:t.apiKey,logger:$}),i;t.inputCsv&&(i=await zl(t.inputCsv));let a=await Zl({client:s,skipPrompts:t.yes,installBrowsers:!0});an.capture({event:"run tests locally",distinctId:a,properties:{organizationId:a}});let l=t.pixelRatio??$l();Bl(l);try{(await Nf({...t,retriesOverride:t.retries,devicePixelRatio:l,tests:r,project:o,client:s,customHeaders:n,envName:t.env,orgId:a,testInputMatrix:i})).failed>0?process.exit(1):process.exit(0)}catch(c){E.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),E.error(c),process.exit(1)}});async function Jv(){try{await ht.parseAsync(process.argv)}catch(r){let e={};try{e.playwrightVersion=Vv("npx playwright --version").toString()}catch(t){$.error({err:t},"Error fetching debug information")}$.error({err:r,debugInfo:e},"Uncaught error in CLI"),$.flush(),E.error(r),process.exit(1)}}qv.setMaxListeners(50);process.on("warning",r=>{$.warn({err:r},`Node warning received on CLI: ${r.message}`)});Jv();
|