momentic 2.15.2 → 2.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -1,39 +1,39 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1d5113a9-8b0f-5942-99ae-c98bf948c708")}catch(e){}}();
4
- var bi=(t,e)=>{},Ql=!1;try{let t=await import("@sentry/node");bi=t.captureException,t.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",release:process.env.SENTRY_RELEASE_NAME,tracesSampleRate:0}),Ql=!0}catch{}import{Command as BO,Option as Ft}from"@commander-js/extra-typings";import{execSync as zO}from"child_process";var Ti=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;import{existsSync as ev,statSync as tv}from"fs";import{z as dm}from"zod";var ZO=dm.object({input:dm.string()});import{z as Ze}from"zod";var nN=Ze.object({srcs:Ze.array(Ze.string()),urls:Ze.array(Ze.string()),desiredSrc:Ze.string().optional(),desiredUrl:Ze.string().optional()}),um=Ze.object({srcRegex:Ze.string().optional(),urlRegex:Ze.string().optional()}),mm=Ze.object({x:Ze.number(),y:Ze.number(),correlation:Ze.number()}),rN=Ze.object({searchImageBase64String:Ze.string(),pageImageBase64String:Ze.string(),id:Ze.string().uuid(),timeoutMs:Ze.number().max(1e4).min(0).optional()});import{z as D}from"zod";import*as U from"zod";import{extendZodWithOpenApi as XT}from"zod-openapi";XT(U);var er=(s=>(s.AI="AI",s.AI_HEALED="AI_HEALED",s.CLICK_TO_FIND="CLICK_TO_FIND",s.XY_PERCENT="XY_PERCENT",s.RECORDING="RECORDING",s.USER_CSS_SELECTOR="USER_CSS_SELECTOR",s.HEURISTIC_HEALED="HEURISTIC_HEALED",s))(er||{}),JT=U.object({mPathSelectorTokens:U.string().array(),frameSrcRegex:U.string().optional(),frameUrlRegex:U.string().optional(),indices:U.number().array()}),Zl=U.object({result:U.number(),traceId:U.string()}).array(),To=U.object({type:U.literal("GCS_TRACES"),traces:Zl}),tr=U.object({id:U.number().int(),dataMomenticId:U.number().int().optional(),selector:U.string().optional(),hybridSelector:U.object({textContent:U.string().nullish(),attributes:U.record(U.string(),U.string()),tagName:U.string(),expandShadowRoot:U.boolean().optional(),classNames:U.string().array(),nthChild:U.number()}).array().optional(),generatedSelectors:U.string().array().optional(),role:U.string().optional(),name:U.string().optional(),numChildren:U.number().optional(),content:U.string().optional(),pathFromRoot:U.string().optional(),serializedHtml:U.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:U.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:U.string().url().optional(),boundingBox:U.object({x:U.number().optional(),y:U.number().optional(),width:U.number(),height:U.number()}).describe("css pixel bounding box").optional(),frameCache:JT.optional(),inputDescription:U.string().optional().describe("the description that generated this cache"),targetSource:U.nativeEnum(er).optional(),targetUpdateTime:U.string().optional(),targetUpdateLoggerTags:U.record(U.string(),U.string()).optional(),cacheResolutionUpdateSource:U.string().optional(),cacheResolutionUpdateTime:U.string().optional(),cacheResolutionUpdateLoggerTags:U.record(U.string(),U.string()).optional(),memory:To.optional()}).openapi({ref:"ElementTargetCache"});function pm(t){return!!(t.serializedHtml||t.screenshotUrl||t.generatedSelectors||t.hybridSelector)}var QT=U.object({type:U.literal("description"),elementDescriptor:U.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),ZT=U.object({x:U.number(),y:U.number()}),ew=U.object({type:U.literal("coordinates"),pixels:ZT}).openapi({ref:"CoordinatesTarget"});function nr(t){return t.type==="description"}function yn(t){return t.type==="coordinates"}var gt=U.discriminatedUnion("type",[QT,ew]).openapi({ref:"ElementTarget"});function ec(t){if(!t)return!1;switch(t.type){case"description":return!!t.elementDescriptor}return!0}function ht(t){if(!t)return"";switch(t.type){case"description":return t.elementDescriptor;case"coordinates":return`x: ${t.pixels.x}, y: ${t.pixels.y}`}}function La(t){return To.safeParse(t).success}import{v4 as Ee}from"uuid";import*as T from"zod";import{extendZodWithOpenApi as lw}from"zod-openapi";import{z as Z}from"zod";import{extendZodWithOpenApi as tw}from"zod-openapi";import{z as wo}from"zod";var tc=wo.object({result:wo.boolean(),traceId:wo.string()}).array(),nc=wo.object({type:wo.literal("GCS_TRACES"),traces:tc}),rc=wo.object({memory:nc.optional()});tw(Z);var gm=Z.object({plan:Z.string().optional(),evidence:Z.string().optional(),thoughts:Z.string(),result:Z.boolean(),relevantElements:Z.array(Z.number()).optional(),updatedMemory:tc.optional()}),rr=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(rr||{});var nw=Z.object({type:Z.literal("ELEMENT_NAME"),negated:Z.boolean().optional(),operation:Z.nativeEnum(rr),value:Z.string()}).openapi({ref:"ElementNameAssertion"}),rw=Z.object({type:Z.literal("ELEMENT_STYLE"),negated:Z.boolean().optional(),operation:Z.nativeEnum(rr),property:Z.string(),value:Z.string()}).openapi({ref:"ElementStyleAssertion"}),ow=Z.object({type:Z.literal("ELEMENT_CONTENT"),negated:Z.boolean().optional(),operation:Z.nativeEnum(rr),value:Z.string()}).openapi({ref:"ElementContentAssertion"}),iw=Z.object({type:Z.literal("ELEMENT_ATTRIBUTE"),negated:Z.boolean().optional(),operation:Z.nativeEnum(rr),attr:Z.string(),value:Z.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Eo=(i=>(i.EXISTS="EXISTS",i.VISIBLE="VISIBLE",i.ENABLED="ENABLED",i.EDITABLE="EDITABLE",i.FOCUSED="FOCUSED",i))(Eo||{}),aw=Z.object({type:Z.literal("ELEMENT_EXISTENCE"),negated:Z.boolean().optional(),condition:Z.nativeEnum(Eo).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),hm=Z.discriminatedUnion("type",[ow,iw,aw,nw,rw]).openapi({ref:"ManualElementAssertion"});var sw=Z.object({type:Z.literal("CONTENT"),negated:Z.boolean().optional(),value:Z.string()}).openapi({ref:"PageContentAssertion"}),fm=Z.discriminatedUnion("type",[sw]).openapi({ref:"ManualPageAssertion"});import{z as Se}from"zod";var Ma=Se.object({url:Se.string(),method:Se.union([Se.literal("GET"),Se.literal("POST"),Se.literal("PUT"),Se.literal("DELETE"),Se.literal("PATCH")]),headers:Se.record(Se.string(),Se.string()).optional(),params:Se.record(Se.string(),Se.string()).optional(),body:Se.string().optional(),timeout:Se.number().int().optional().describe("Max seconds to wait for the request to complete")}),Sm=Se.object({url:Se.string(),headers:Se.record(Se.string(),Se.string()).optional(),query:Se.string(),variables:Se.string().optional(),timeout:Se.number().int().optional().describe("Max seconds to wait for the request to complete")}),Oa=Se.object({code:Se.string(),fragment:Se.boolean().optional(),environment:Se.union([Se.literal("NODE"),Se.literal("BROWSER")]).optional().describe("default NODE"),timeout:Se.number().int().max(60).optional().describe("Max seconds for the code to complete")});var We=(H=>(H.AI_EXTRACT="AI_EXTRACT",H.AI_ASSERTION="AI_ASSERTION",H.AUTH_LOAD="AUTH_LOAD",H.AUTH_SAVE="AUTH_SAVE",H.BLUR="BLUR",H.CAPTCHA="CAPTCHA",H.CLICK="CLICK",H.COOKIE="COOKIE",H.COPY="COPY",H.DIALOG="DIALOG",H.DRAG="DRAG",H.ELEMENT_CHECK="ELEMENT_CHECK",H.FILE_UPLOAD="FILE_UPLOAD",H.FOCUS="FOCUS",H.GO_BACK="GO_BACK",H.GO_FORWARD="GO_FORWARD",H.HOVER="HOVER",H.JAVASCRIPT="JAVASCRIPT",H.LOCAL_STORAGE="LOCAL_STORAGE",H.MOUSE_DRAG="MOUSE_DRAG",H.NAVIGATE="NAVIGATE",H.NEW_TAB="NEW_TAB",H.PAGE_CHECK="PAGE_CHECK",H.PASTE="PASTE",H.PRESS="PRESS",H.KEY_DOWN="KEY_DOWN",H.KEY_UP="KEY_UP",H.REFRESH="REFRESH",H.REQUEST="REQUEST",H.GRAPHQL_REQUEST="GRAPHQL_REQUEST",H.SCROLL_DOWN="SCROLL_DOWN",H.SCROLL_UP="SCROLL_UP",H.SCROLL_LEFT="SCROLL_LEFT",H.SCROLL_RIGHT="SCROLL_RIGHT",H.SELECT_OPTION="SELECT_OPTION",H.SWITCH_TAB="TAB",H.TYPE="TYPE",H.VISUAL_DIFF="VISUAL_DIFF",H.WAIT="WAIT",H.WAIT_FOR_URL="WAIT_FOR_URL",H.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",H.AWAIT_LISTENER="AWAIT_LISTENER",H.RECORD_REQUESTS="RECORD_REQUESTS",H.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",H.SET_HEADER="SET_HEADER",H.OFFLINE_MODE="OFFLINE_MODE",H.SUCCESS="SUCCESS",H))(We||{});lw(T);var W=T.object({thoughts:T.string().optional(),id:T.string().uuid().describe("unique identifier to this step, used for step cache")}),Wt=T.object({useSelector:T.boolean().optional(),force:T.boolean().optional(),disableCache:T.boolean().optional().describe("disable element caching for this step"),iframeUrl:T.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),Bt=T.object({target:tr}).optional().openapi({ref:"SingleTargetCache"});function ym(t){return Bt.safeParse(t).success}var ka=T.object({loadTimeout:T.number().int().max(60).optional().describe("Max seconds for the page to load")}),ic=W.merge(ka).merge(T.object({type:T.literal("NAVIGATE"),url:T.string()})).openapi({ref:"NavigateCommand"}),_a=Wt.merge(T.object({cache:Bt})),or=W.merge(_a.merge(T.object({target:gt.optional(),type:T.literal("SCROLL_UP"),deltaY:T.number().optional()}))).openapi({ref:"ScrollUpCommand"}),ir=W.merge(_a.merge(T.object({target:gt.optional(),type:T.literal("SCROLL_DOWN"),deltaY:T.number().optional()}))).openapi({ref:"ScrollDownCommand"}),Co=W.merge(_a.merge(T.object({target:gt.optional(),type:T.literal("SCROLL_LEFT"),deltaX:T.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Ro=W.merge(_a.merge(T.object({target:gt.optional(),type:T.literal("SCROLL_RIGHT"),deltaX:T.number().optional()}))).openapi({ref:"ScrollRightCommand"}),vN=T.discriminatedUnion("type",[or,ir,Co,Ro]).openapi({ref:"AllScrollCommands"}),cw=W.merge(T.object({type:T.literal("DIALOG"),action:T.union([T.literal("ACCEPT"),T.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),dw=W.merge(T.object({type:T.literal("WAIT"),delay:T.number()})).openapi({ref:"WaitCommand"}),uw=T.discriminatedUnion("type",[T.object({type:T.literal("SUBSTRING"),url:T.string()}),T.object({type:T.literal("GLOB"),glob:T.string()}),T.object({type:T.literal("REGEX"),regex:T.string()})]),mw=T.object({caseInsensitive:T.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:T.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:T.number().int().optional().describe("Max seconds to wait for the URL to match")}),ac=W.extend({type:T.literal("WAIT_FOR_URL"),matcher:uw}).merge(mw).openapi({ref:"WaitUrlCommand"}),pw=W.merge(ka).merge(T.object({type:T.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),gw=W.merge(T.object({type:T.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),hw=W.merge(T.object({type:T.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),fw=W.extend({type:T.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),Sw=W.extend({type:T.literal("AUTH_LOAD"),storageState:T.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),sc=W.merge(Wt).extend({type:T.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),yw=W.extend({type:T.literal("COPY"),value:T.string()}).openapi({ref:"CopyCommand"}),bw=W.extend({type:T.literal("PASTE")}).openapi({ref:"PasteCommand"}),Tw=W.merge(Oa).extend({type:T.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Pr=W.merge(Wt).extend({type:T.literal("CLICK"),target:gt,doubleClick:T.boolean().optional(),rightClick:T.boolean().optional(),waitForDownload:T.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:T.number().optional(),downloadTimeoutMs:T.number().optional(),cache:Bt,relativePosition:T.object({x:T.number(),y:T.number()}).optional()}).openapi({ref:"ClickCommand"}),lc=T.object({fromTarget:tr.optional(),toTarget:tr.optional()}),wi=W.merge(Wt).merge(T.object({type:T.literal("DRAG"),fromTarget:gt,toTarget:gt,steps:T.number().optional(),hoverSeconds:T.number().optional().describe("Seconds to hover the object before dropping"),cache:lc.optional()})).openapi({ref:"DragCommand"}),Ei=W.merge(Wt).merge(T.object({type:T.literal("MOUSE_DRAG"),target:gt.optional(),deltaX:T.string().describe("pixels to move horizontally, can be template"),deltaY:T.string().describe("pixels to move vertically, can be template"),steps:T.number().optional(),cache:Bt})).openapi({ref:"MouseDragCommand"}),Lr=W.merge(Wt).merge(T.object({type:T.literal("HOVER"),target:gt,cache:Bt})).openapi({ref:"HoverCommand"}),Ci=W.merge(Wt).merge(T.object({type:T.literal("FOCUS"),target:gt,cache:Bt})).openapi({ref:"FocusCommand"}),Ri=W.merge(Wt).extend({type:T.literal("BLUR"),target:gt.optional(),cache:Bt}).openapi({ref:"BlurCommand"}),ww=T.object({type:T.literal("URL"),url:T.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),Ew=T.object({type:T.literal("USER_FILE"),name:T.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),Cw=W.extend({type:T.literal("FILE_UPLOAD"),fileSource:T.discriminatedUnion("type",[ww,Ew]),filename:T.string().optional()}).openapi({ref:"FileUploadCommand"}),Rw=T.discriminatedUnion("type",[T.object({type:T.literal("VALUE"),value:T.string()}),T.object({type:T.literal("LABEL"),label:T.string()}),T.object({type:T.literal("INDEX"),index:T.coerce.string()})]),Mr=W.merge(Wt).extend({type:T.literal("SELECT_OPTION"),target:gt,cache:Bt,choice:Rw.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),cc=T.union([T.literal("MULTIMODAL"),T.literal("VISION_ONLY")]),vo=W.merge(T.object({type:T.literal("AI_ASSERTION"),assertion:T.string(),disableCache:T.boolean().optional(),iframeUrl:T.string().optional(),contextChoice:cc.optional(),timeout:T.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:rc.optional()})).openapi({ref:"AIAssertionCommand"}),bn=5,dc=600,Or=W.merge(Wt).extend({type:T.literal("ELEMENT_CHECK"),target:gt,assertion:hm,cache:Bt.or(rc).optional(),timeout:T.number().int().min(0).max(dc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),uc=W.extend({type:T.literal("PAGE_CHECK"),assertion:fm,iframeUrl:T.string().optional().describe("url or url regex for the iframe"),timeout:T.number().int().min(0).max(dc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),vw=W.merge(T.object({type:T.literal("AI_EXTRACT"),goal:T.string(),schema:T.string().optional(),envKey:T.string().optional(),disableCache:T.boolean().optional(),iframeUrl:T.string().optional()})).openapi({ref:"AIExtractCommand"}),Aw=T.object({clearContent:T.boolean().optional(),forceClearContent:T.boolean().optional(),delay:T.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:T.boolean().optional(),pressEnter:T.boolean().optional()}),bm=25,Nr=W.merge(Wt).merge(Aw).extend({type:T.literal("TYPE"),target:gt.optional(),value:T.string(),cache:Bt}).openapi({ref:"TypeCommand"}),mc=W.merge(T.object({type:T.literal("PRESS"),value:T.string(),repeat:T.number().optional(),convertMeta:T.boolean().optional(),delayMs:T.number().optional()})).openapi({ref:"PressCommand"}),xw=W.merge(T.object({type:T.literal("KEY_DOWN"),value:T.string(),convertMeta:T.boolean().optional()})).openapi({ref:"KeyDownCommand"}),Iw=W.merge(T.object({type:T.literal("KEY_UP"),value:T.string(),convertMeta:T.boolean().optional()})).openapi({ref:"KeyUpCommand"}),Pw=T.object({type:T.literal("SUBSTRING"),substring:T.string()}),Lw=T.object({type:T.literal("REGEX"),pattern:T.string()}),Mw=T.object({type:T.literal("INDEX"),index:T.coerce.string()}),Ow=T.discriminatedUnion("type",[Pw,Lw,Mw]),Nw=W.merge(ka).merge(T.object({type:T.literal("TAB"),action:Ow})).openapi({ref:"TabCommand"}),pc=W.merge(ka).merge(T.object({type:T.literal("NEW_TAB"),url:T.string()})).openapi({ref:"NewTabCommand"}),kw=W.merge(T.object({type:T.literal("COOKIE"),value:T.string()})).openapi({ref:"CookieCommand"}),_w=W.merge(T.object({type:T.literal("LOCAL_STORAGE"),key:T.string(),value:T.string()})).openapi({ref:"LocalStorageCommand"}),Dw=W.extend({type:T.literal("REQUEST")}).merge(Ma).openapi({ref:"RequestCommand"}),Fw=W.extend({type:T.literal("GRAPHQL_REQUEST")}).merge(Sm).openapi({ref:"GraphQLRequestCommand"}),Uw=W.merge(T.object({type:T.literal("SUCCESS"),condition:vo.optional()})).openapi({ref:"SuccessCommand"}),Bw=W.merge(T.object({type:T.literal("FAILURE")})).openapi({ref:"FailureCommand"}),zw=T.object({data:T.string().describe("location at which to find a jpg"),width:T.number(),height:T.number()}),vi=W.merge(Wt).merge(T.object({type:T.literal("VISUAL_DIFF"),threshold:T.number().optional().describe("default 0.1"),target:gt.optional(),screenshot:zw.optional(),cache:Bt})).openapi({ref:"VisualDiffCommand"}),Hw=W.merge(T.object({type:T.literal("REGISTER_REQUEST_LISTENER"),pattern:T.string(),key:T.string()})).openapi({ref:"RegisterRequestListenerCommand"}),$w=W.merge(T.object({type:T.literal("AWAIT_LISTENER"),key:T.string(),timeout:T.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),jw=W.merge(T.object({type:T.literal("RECORD_REQUESTS"),pattern:T.string(),key:T.string()})).openapi({ref:"RecordRequestsCommand"}),Gw=W.merge(T.object({type:T.literal("GET_RECORDED_REQUESTS"),key:T.string()})).openapi({ref:"GetRecordedRequestsCommand"}),Ww=W.merge(T.object({type:T.literal("SET_HEADER"),name:T.string(),value:T.string(),urlPattern:T.string().optional().describe("URL pattern to match")})).openapi({ref:"SetHeaderCommand"}),Vw=W.merge(T.object({type:T.literal("OFFLINE_MODE"),enable:T.boolean()})).openapi({ref:"OfflineModeCommand"}),Tm=T.discriminatedUnion("type",[Pr,Nr,mc,xw,Iw,Mr,ic,ir,or,vo,Lr,dw,Uw]),qw=T.discriminatedUnion("type",[vw,Sw,fw,sc,kw,yw,cw,wi,Or,Cw,gw,hw,Tw,_w,Ei,pc,uc,bw,pw,Dw,Fw,Co,Ro,Nw,vi,Ci,Ri,ac,Hw,$w,jw,Gw,Ww,Vw]),Ao=T.discriminatedUnion("type",[...Tm.options,...qw.options]).openapi({ref:"Command"}),Da=T.discriminatedUnion("type",[...Tm.options,Bw]);function Fn(t){let e;switch(t){case"PASTE":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:Ee(),type:t};break;case"AUTH_LOAD":{e={id:Ee(),type:t,storageState:""};break}case"AI_EXTRACT":e={id:Ee(),type:t,goal:""};break;case"DIALOG":e={id:Ee(),type:t,action:"DISMISS"};break;case"DRAG":e={id:Ee(),type:t,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:Ee(),type:t,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:Ee(),type:t,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:Ee(),type:t,delay:1};break;case"BLUR":e={id:Ee(),type:t};break;case"HOVER":case"FOCUS":case"CLICK":e={id:Ee(),type:t,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:Ee(),type:t,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:Ee(),type:t,value:""};break;case"SELECT_OPTION":e={id:Ee(),type:t,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:Ee(),type:t,url:""};case"TAB":e={id:Ee(),type:t,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:Ee(),type:t,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:Ee(),type:t,url:"",query:""};break;case"LOCAL_STORAGE":e={id:Ee(),type:t,key:"",value:""};break;case"JAVASCRIPT":e={id:Ee(),type:t,code:""};break;case"AI_ASSERTION":e={id:Ee(),type:t,assertion:""};break;case"FILE_UPLOAD":{e={id:Ee(),type:t,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:Ee(),type:t,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:Ee(),type:t,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:Ee(),type:t,pattern:"",key:""};break}case"AWAIT_LISTENER":{e={id:Ee(),type:t,key:""};break}case"RECORD_REQUESTS":{e={id:Ee(),type:t,pattern:"",key:""};break}case"GET_RECORDED_REQUESTS":{e={id:Ee(),type:t,key:""};break}case"SET_HEADER":{e={id:Ee(),type:t,name:"",value:""};break}case"OFFLINE_MODE":{e={id:Ee(),type:t,enable:!0};break}default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function wm(t){switch(t.type){case"BLUR":case"CLICK":case"DRAG":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"TYPE":return!0;case"AUTH_LOAD":case"AUTH_SAVE":case"AWAIT_LISTENER":case"SUCCESS":case"AI_ASSERTION":case"AI_EXTRACT":case"CAPTCHA":case"COOKIE":case"COPY":case"DIALOG":case"ELEMENT_CHECK":case"FILE_UPLOAD":case"GET_RECORDED_REQUESTS":case"GO_BACK":case"GO_FORWARD":case"GRAPHQL_REQUEST":case"JAVASCRIPT":case"LOCAL_STORAGE":case"NAVIGATE":case"NEW_TAB":case"PASTE":case"PAGE_CHECK":case"RECORD_REQUESTS":case"REGISTER_REQUEST_LISTENER":case"REFRESH":case"REQUEST":case"SELECT_OPTION":case"SET_HEADER":case"TAB":case"VISUAL_DIFF":case"WAIT":case"WAIT_FOR_URL":case"OFFLINE_MODE":return!1;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}import{z as Kw}from"zod";var LN=Kw.discriminatedUnion("type",[Ri,sc,Pr,wi,Ci,Lr,Ei,or,ir,Co,Ro,Mr,Nr,vi,Or]);function Em(t){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(t)}import{z as Yw}from"zod";import{z as ar}from"zod";function Ai(t){return ar.object({key:ar.string(),testId:ar.string().optional(),moduleId:ar.string().optional(),organizationId:ar.string(),value:t})}function xi(t){return Ai(t).extend({uniqueKey:ar.string()})}function Fa(t){return ar.record(ar.string(),xi(t))}var Ct={type:!0,cache:!0},Un=Yw.discriminatedUnion("type",[vo.pick(Ct),Ri.pick(Ct),Pr.pick(Ct),wi.pick(Ct),Or.pick(Ct),Ci.pick(Ct),Lr.pick(Ct),Ei.pick(Ct),or.pick(Ct),ir.pick(Ct),Co.pick(Ct),Ro.pick(Ct),Mr.pick(Ct),Nr.pick(Ct),vi.pick(Ct)]),Ua=Object.values(We).filter(t=>Un.options.some(e=>e.shape.type.safeParse(t).success));Ao.options.forEach(t=>{if("target"in t.shape&&!Ua.includes(t.shape.type.value))throw new Error(`Command ${t.shape.type.value} has a target but no cache`)});function Cm(t){return Ua.includes(t.type)}var Rm=Ai(Un),vm=xi(Un),UN=Fa(Un);import{z as gc}from"zod";import{extendZodWithOpenApi as Qw}from"zod-openapi";import{z as Am}from"zod";import{extendZodWithOpenApi as Xw}from"zod-openapi";import{z as kr}from"zod";var Vt=kr.object({index:kr.number().optional().describe("global index within a test (in-order traversal)"),id:kr.string(),skipped:kr.boolean().optional(),envKey:kr.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:kr.boolean().optional(),retries:kr.number().optional()});Xw(Am);var Jw=Vt.extend({type:Am.literal("PRESET_ACTION")}),zt=Jw.extend({command:Ao}).openapi({ref:"PresetAction"});Qw(gc);var _r=Vt.extend({type:gc.literal("AI_ACTION"),text:gc.string(),steps:zt.array().optional()}).openapi({ref:"AIAction"});import{z as Rt}from"zod";import{z as Ba}from"zod";import{extendZodWithOpenApi as Zw}from"zod-openapi";Zw(Ba);var xo=Vt.extend({type:Ba.literal("AI_ACTION_DYNAMIC"),text:Ba.string(),retries:Ba.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as xm}from"zod";var hc=Vt.extend({type:xm.literal("CONDITIONAL"),skipped:xm.boolean().optional()});import{z as le}from"zod";var eE=le.object({cacheKey:le.string(),cacheExpiryMs:le.number()}),fc=Vt.extend({id:le.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:le.record(le.string()).optional(),cacheConfig:eE.optional()}),an=fc.extend({type:le.literal("MODULE"),moduleId:le.string().uuid()}),tE=le.union([an.pick({type:!0,moduleId:!0}),le.record(le.unknown())]),nE=le.object({type:le.literal("URL_REGEX"),regex:le.string()}),rE=le.object({type:le.literal("PAGE_CHECK"),substring:le.string()}),Sc=le.object({cacheInvalidation:le.discriminatedUnion("type",[rE,nE]).optional()}),Mt=le.object({moduleId:le.string().uuid(),name:le.string(),description:le.string().nullish(),enabled:le.boolean().nullish(),parameters:le.string().array().nullish(),defaultParameters:le.record(le.string(),le.string()).nullish(),parameterEnums:le.record(le.string(),le.string().array()).nullish(),defaultCacheKey:le.string().nullish(),defaultCacheTtl:le.number().nullish(),defaultCacheAllInvocations:le.boolean().nullish(),autoAuth:le.boolean().nullish(),advanced:Sc.nullish()});import{z as qt}from"zod";var yc=(r=>(r.ALWAYS="ALWAYS",r.ON_FAILURE="ON_FAILURE",r.ON_ACTION_FAILURE="ON_ACTION_FAILURE",r))(yc||{});var oE=qt.discriminatedUnion("type",[qt.object({type:qt.literal("NAVIGATE_URL"),url:qt.string().url()}),qt.object({type:qt.literal("GO_TO_SECTION_START")})]),iE=qt.object({trigger:qt.nativeEnum(yc).optional(),attempts:qt.number().int().optional(),restartBehavior:oE}),Ii=Vt.extend({type:qt.literal("SECTION"),description:qt.string().describe("user provided goal of what the section should accomplish"),plan:qt.string().array().optional(),autohealingConfig:iE.optional()});var Im=Mt.merge(fc).extend({type:Rt.literal("RESOLVED_MODULE"),steps:Rt.lazy(()=>$e.array())}),Pi=Mt.extend({steps:Rt.lazy(()=>$e.array())}),bc=Ii.extend({steps:Rt.lazy(()=>Le.array())}),aE=Ii.extend({steps:Rt.lazy(()=>$e.array())}),Dr=hc.extend({blocks:Rt.object({assertion:Rt.lazy(()=>zt),steps:Rt.lazy(()=>Le.array())}).array(),elseSteps:Rt.lazy(()=>Le.array().optional())}),sE=hc.extend({blocks:Rt.object({assertion:Rt.lazy(()=>zt),steps:Rt.lazy(()=>$e.array())}).array(),elseSteps:Rt.lazy(()=>$e.array().optional())}),Le=Rt.discriminatedUnion("type",[zt,_r,xo,an,Dr,bc]),$e=Rt.discriminatedUnion("type",[zt,_r,xo,Im,sE,aE]);import{z as Kt}from"zod";var lE=Kt.object({steps:Le.array(),beforeSteps:Le.array().nullish(),afterSteps:Le.array().nullish()}),Io=Kt.object({steps:$e.array(),beforeSteps:$e.array().nullish(),afterSteps:$e.array().nullish()}),Fr=Kt.object({steps:Kt.record(Kt.string(),Kt.unknown()).array(),beforeSteps:Kt.record(Kt.string(),Kt.unknown()).array().nullish(),afterSteps:Kt.record(Kt.string(),Kt.unknown()).array().nullish()});var ce="1.0.20";var Pm=D.object({phrase:D.string()}),Tc=D.object({thoughts:D.string().optional(),result:D.union([D.literal("NOT_FOUND"),D.string(),D.number(),D.array(D.unknown()),D.record(D.unknown(),D.unknown()),D.unknown()])}),E_=D.object({text:D.string()}),Lm=D.object({thoughts:D.string(),review:D.string().optional(),id:D.number().int(),updatedMemory:Zl.optional()});var za=(g=>(g.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",g.FEW_WORDS="FEW_WORDS",g.STYLE_TAG="STYLE_TAG",g.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",g.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",g.NONE="NONE",g.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",g.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",g.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",g.PREFER_ASSERTION="PREFER_ASSERTION",g.HTML_ELEMENTS="HTML_ELEMENTS",g.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",g.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",g))(za||{});var Mm=D.object({thoughts:D.string(),category:D.nativeEnum(za)}),cE=D.discriminatedUnion("op",[D.object({op:D.literal("replace"),path:D.string(),value:D.string()}),D.object({op:D.literal("add"),path:D.string(),value:D.string()}),D.object({op:D.literal("remove"),path:D.string()})]),C_=D.object({thoughts:D.string(),patches:cE.array()}),dE=[D.literal("add"),D.literal("replace"),D.literal("remove")],uE=D.object({op:D.union(dE),path:D.string(),value:$e.optional()}),Om=D.object({patches:uE.array(),thoughts:D.string()}),wc=(r=>(r.LEGITIMATE="LEGITIMATE",r.RECOVERABLE="RECOVERABLE",r.INELIGIBLE="INELIGIBLE",r))(wc||{}),Nm=D.object({thoughts:D.string(),scenario:D.nativeEnum(wc),instructions:D.string().nullish()}),km=D.object({reasoning:D.string(),scenario:D.string(),patch:D.null().optional()}),R_=D.object({thoughts:D.string(),evaluation:D.number().min(1).max(10)}),v_=D.object({observations:D.string(),reasoning:D.string(),command:Da});var Ec=D.object({summary:D.string(),reasoning:D.string(),evaluation:D.discriminatedUnion("type",[D.object({type:D.literal("DONE")}),D.object({type:D.literal("RIGHT_TRACK")}),D.object({type:D.literal("WRONG_TRACK"),feedback:D.string()}),D.object({type:D.literal("IMPOSSIBLE")})])});import{z as O}from"zod";import*as ee from"zod";var M_=ee.object({thoughts:ee.string().optional().describe("only provided if a description was provided"),target:tr.optional().describe("only provided if a description was provided"),pageState:ee.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:ee.object({label:ee.string(),value:ee.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:ee.object({data:ee.string(),height:ee.number().int(),width:ee.number().int()}).optional().describe("only provided if returnScreenshot is true")}),Ha=ee.union([ee.literal("ELEMENT_CHECK"),ee.literal("NEGATED_CHECK"),ee.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),ee.literal("SELECT_OPTION"),ee.literal("TYPE")]);function Ur(t){if(!("useSelector"in t&&t.useSelector)){if(t.type==="SELECT_OPTION")return"SELECT_OPTION";if(t.type==="TYPE")return"TYPE";if(t.type==="ELEMENT_CHECK"&&t.assertion.type==="ELEMENT_EXISTENCE"&&t.assertion.condition==="EXISTS"&&t.assertion.negated)return"NEGATED_CHECK";if(t.type==="ELEMENT_CHECK"&&t.assertion.type==="ELEMENT_EXISTENCE"&&t.assertion.condition==="VISIBLE"&&t.assertion.negated)return"NEGATED_ELEMENT_VISIBLE_CHECK";if(t.type==="ELEMENT_CHECK")return"ELEMENT_CHECK"}}var Li=(a=>(a.USER_SELECTOR="USER_SELECTOR",a.CSS_SELECTOR="CSS_SELECTOR",a.HYBRID_SELECTOR="HYBRID_SELECTOR",a.HTML_DISTANCE="HTML_DISTANCE",a.TEMPLATE_MATCHING="TEMPLATE_MATCHING",a.AUTO_FRAME="AUTO_FRAME",a))(Li||{}),Po=ee.object({matched:ee.boolean(),reason:ee.string().optional().describe("Human understandable description"),logs:ee.string().array().optional().describe("Logs for debugging")}),mE=Po.extend({type:ee.literal("USER_SELECTOR")}),pE=Po.extend({type:ee.literal("CSS_SELECTOR"),selectors:ee.string().array()}),gE=Po.extend({type:ee.literal("HYBRID_SELECTOR")}),hE=Po.extend({type:ee.literal("HTML_DISTANCE"),distance:ee.number().optional(),closestElement:ee.string().optional(),savedElement:ee.string().optional()}),fE=Po.extend({type:ee.literal("TEMPLATE_MATCHING"),elementImageUrl:ee.string().url()}),SE=Po.extend({type:ee.literal("AUTO_FRAME"),logs:ee.string().array().optional()}),_m=ee.discriminatedUnion("type",[mE,pE,gE,hE,fE,SE]);import{z as ki}from"zod";import{z as LE}from"zod";import*as $ from"zod";import{extendZodWithOpenApi as EE}from"zod-openapi";import{cloneDeep as Mi}from"lodash-es";import Hm from"truncate-json";import*as Hr from"zod";import{extendZodWithOpenApi as yE}from"zod-openapi";import{z as ft}from"zod";import{z as je}from"zod";var Cc=je.object({autoFollowNewTabs:je.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:je.union([je.boolean(),je.literal("inputs-only")]).optional(),ignoreHrefForCaching:je.boolean().optional(),disableSecondaryCacheResolution:je.boolean().optional(),hybridSelectorMode:je.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:je.boolean().optional(),visualActions:je.boolean().optional(),autoExpandIframes:je.boolean().optional()});var Dm=1e4,Fm=6e4,Br=Cc.extend({pageLoadTimeoutMs:je.number().optional().refine(t=>t===void 0||t<=Fm&&t>=-1,{message:`Page load timeout must be between 0 and ${Fm/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:je.number().optional().refine(t=>t===void 0||t<=Dm&&t>=-1,{message:`Smart waiting timeout must be between 0 and ${Dm/1e3} seconds`}),localChromeExtensionPaths:je.string().array().optional(),extraHeaders:je.record(je.string(),je.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:je.string().optional(),disableGpu:je.boolean().optional(),bustCacheOnBoundingBoxChange:je.boolean().optional().describe("Bust the cache if no elements are matched that have the same bounding box and location as the original element. This will improve accuracy on sites that use many same components, at the expense of stability and speed."),allowPartialAccessibilityTree:je.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:je.boolean().optional().describe("Ignore HTTPS errors, such as self-signed certificates and certificate errors. This can be useful for testing sites that use self-signed certificates or certificate errors.")});var it="BASE_URL",$a="CURRENT_URL",zr="ENV_NAME",Lo="TEST_NAME",F_={[it]:"https://www.google.com"},Um=ft.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),Bm=ft.object({name:ft.string(),variables:ft.record(ft.string().describe("variable name"),ft.string().describe("variable value"))}),zm=ft.object({name:ft.string(),variables:ft.record(ft.string().describe("variable name"),ft.unknown().describe("variable value")),browser:Br.optional()});var U_=ft.object({name:ft.string(),variables:ft.record(ft.string().describe("variable name"),ft.unknown().describe("variable value"))});yE(Hr);var Rc=Hr.object({env:Hr.record(Hr.unknown())}).openapi({ref:"TestContextSnapshot"}),bE="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",TE=[it,zr,Lo],$m=[$a,it,zr,Lo],Yt=class t{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,n=void 0,r={}){return new t({baseUrl:"about:blank",currentUrl:"about:blank",testName:e,envName:n,variablesFromEnvironment:r})}static fromSnapshot({snapshot:e,environmentVariables:n}){let r=e.env[it]??"about:blank",o=e.env[$a]??"about:blank",i=e.env[zr],a=e.env[Lo],s={};for(let[c,d]of Object.entries(e.env))$m.includes(c)||(n??{})[c]===void 0&&(s[c]=d);return new t({baseUrl:r,currentUrl:o,dynamicVariables:s,envName:i,testName:a,variablesFromEnvironment:n??{}})}setEnvVariables(e){let n=Mi(e);this.env=Object.assign(this.env,n)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,n){this.varsFromMomenticEnvironment[e]=n}getVariable(e){return this.env[e]}setVariable(e,n){TE.includes(e)||(this.env[e]=n)}getEnvName(){return this.env[zr]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return Mi(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([r,o])=>$m.includes(r)||this.varsFromMomenticEnvironment[r]===void 0?[r,o]:[r,bE]));for(let[r,o]of Object.entries(e.env)){if(!o){e.env[r]=o;continue}let{jsonString:i}=Hm(JSON.stringify(o),1e3);try{e.env[r]=JSON.parse(i)}catch{e.env[r]=void 0}}let{jsonString:n}=Hm(JSON.stringify(e.env),5e3);try{e.env=JSON.parse(n)}catch{e.env={}}return e}setCurrentUrl(e){this.env[$a]=e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=Mi(e.variablesFromEnvironment),this.setMomenticSystemVariable(it,e.baseUrl),e.envName&&this.setMomenticSystemVariable(zr,e.envName),e.testName&&this.setMomenticSystemVariable(Lo,e.testName)}getDynamicVariablesCopy(){return Mi(this.env)}getVariablesFromEnvironmentCopy(){return Mi(this.varsFromMomenticEnvironment)}};var Ce=(i=>(i.SUCCESS="SUCCESS",i.FAILED="FAILED",i.RUNNING="RUNNING",i.IDLE="IDLE",i.CANCELLED="CANCELLED",i))(Ce||{}),ja=(r=>(r.SUCCESS="SUCCESS",r.FAILED="FAILED",r.CANCELLED="CANCELLED",r))(ja||{});import{z as Tn}from"zod";import{extendZodWithOpenApi as wE}from"zod-openapi";wE(Tn);var he=(d=>(d.AI_PROVIDER="AIProviderError",d.USER_INFRA="UserInfrastructureError",d.ACTION_FAILURE="ActionFailureError",d.ASSERTION_FAILURE="AssertionFailureError",d.CONFIG_ERROR="UserConfigurationError",d.WEB_AGENT_PLATFORM="InternalWebAgentError",d.UNKNOWN_PLATFORM="InternalPlatformError",d.JOB_TIMEOUT="JobTimeoutError",d.CONCURRENCY_ERROR="ConcurrencyError",d.UNKNOWN="UnknownError",d))(he||{});var jm=["JobTimeoutError","UserConfigurationError","UserInfrastructureError"],Ga={ActionFailureError:"Action failure",AssertionFailureError:"Assertion failure",UserInfrastructureError:"Infrastructure failure",UserConfigurationError:"Configuration error",AIProviderError:"AI provider error",InternalWebAgentError:"Momentic AI agent error",JobTimeoutError:"Job timeout",InternalPlatformError:"Unknown Momentic platform error",UnknownError:"Unknown error",ConcurrencyError:"Concurrency error"},Mo={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 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).",AIProviderError:"The AI provider failed to return a response or returned a malformed response.",UserInfrastructureError:"The user's web application exhibited an infrastructure failure, such as a page load timeout, a 5XX status code, maintenance page, or session crash.",UserConfigurationError:"The error message suggests a user-caused misconfiguration in the test, such as an undefined variable, a missing base URL, an empty test/module input parameter, or an invalid step option",JobTimeoutError:"The test took too long to complete, suggesting a problem with the test itself.",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.",ConcurrencyError:"The AI test executed correctly, but the application state did not match expectations because another process modified the same resource concurrently. This failure is due to a concurrency error, such as a race condition or deadlock. Commonly caused by tests running simultaneously when using constants rather than random values, or underlying operations that allow for race conditions. For example, in Notion, if multiple tests are running at the same time where one creates a page and enters text to check if it renders, but another test deletes all pages before it can validate the render, this would be a concurrency error.",UnknownError:"An unknown error occurred. Please refer to the failure details in the run for more information or reach out to Momentic Support for assistance.",InternalPlatformError:"An unknown error occurred with the Momentic platform."},vc=Tn.object({reason:Tn.nativeEnum(he),previousStepsDescription:Tn.array(Tn.string()).optional(),summary:Tn.string(),rootCause:Tn.string().optional()}).openapi({ref:"TestResultClassification"}),Wa=Tn.object({errorMessage:Tn.string(),errorStack:Tn.string().optional(),classification:vc.optional()}).openapi({ref:"TestFailureDetails"});EE($);var Ac=$.object({beforeUrl:$.string().optional(),afterUrl:$.string().optional(),message:$.string().optional(),beforeSnapshot:$.string().optional(),afterSnapshot:$.string().optional(),startedAt:$.coerce.date(),finishedAt:$.coerce.date()}),CE=Ac.extend({viewport:$.object({height:$.number(),width:$.number()}).nullish(),status:$.nativeEnum(ja),message:$.string().optional(),elementInteracted:$.string().optional()}),$r=Ac.extend({status:$.nativeEnum(Ce),message:$.string().optional(),data:$.unknown().optional(),beforeTestContext:Rc.optional(),afterTestContext:Rc.optional(),failureReason:$.nativeEnum(he).optional(),details:$.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"}),xc=(n=>(n.NOT_ELIGIBLE="NOT_ELIGIBLE",n.ATTEMPTED="ATTEMPTED",n))(xc||{}),Va=$r.merge(zt).extend({results:CE.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:$.lazy(()=>et.array()).optional(),failureRecoveryStatus:$.object({type:$.nativeEnum(xc),message:$.string()}).optional()}),RE=$r.merge(_r).extend({results:$.lazy(()=>Va.array()),previousAttempts:$.lazy(()=>et.array()).optional()}),vE=$r.merge(xo).extend({results:$.lazy(()=>Va.array()),previousAttempts:$.lazy(()=>et.array()).optional()}),AE=$r.merge(an).extend({moduleName:$.string().optional(),results:$.lazy(()=>et.array()),previousAttempts:$.lazy(()=>et.array()).optional()}),xE=$r.merge(Dr).extend({assertion:Va.optional(),results:$.lazy(()=>et.array()).describe("results for the block actually executed"),previousAttempts:$.lazy(()=>et.array()).optional()}),IE=$r.merge(Ii).extend({results:$.lazy(()=>et.array()),healingAttempts:$.lazy(()=>et.array().array()).optional(),previousAttempts:$.lazy(()=>et.array()).optional()}),et=$.discriminatedUnion("type",[RE,vE,Va,AE,xE,IE]),qa=$r.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),PE=Ac.extend({index:$.number().optional(),description:$.string(),pageState:$.string().optional(),elementInteracted:$.string().optional(),startedAt:$.coerce.date().or($.string()).optional().catch(void 0),finishedAt:$.coerce.date().or($.string()).optional().catch(void 0)}),Ka=PE.extend({beforeScreenshot:$.string().optional(),afterScreenshot:$.string().optional()});var Ic=LE.object({results:et.array().describe("main results"),beforeResults:et.array().optional(),afterResults:et.array().optional()}),Oi=Ic.partial();import{z as F}from"zod";import{extendZodWithOpenApi as UE}from"zod-openapi";var Oo=(n=>(n.WEB="WEB",n.ANDROID="ANDROID",n))(Oo||{});import{z as Ge}from"zod";var Pc=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(Pc||{});var ME=Ge.object({type:Ge.literal("DESCRIPTION_UPDATE"),thoughts:Ge.string()}),Ya=Ge.discriminatedUnion("type",[ME]),OE=Ge.object({testId:Ge.string(),name:Ge.string(),orgId:Ge.string(),runId:Ge.string(),steps:$e.array(),purpose:Ge.nativeEnum(Pc),details:Ya.or(Ya.array()).optional()});var pD=OE.pick({name:!0,orgId:!0}),Lc=Ge.object({id:Ge.string(),name:Ge.string().nullish(),createdAt:Ge.string().pipe(Ge.coerce.date()).or(Ge.date()),organizationId:Ge.string(),schemaVersion:Ge.string(),runId:Ge.string().nullish(),purpose:Ge.nativeEnum(Pc),details:Ya.or(Ya.array()).optional(),applied:Ge.boolean().nullish(),appliedAt:Ge.coerce.date().nullish()}),Gm=Lc.extend({steps:$e.array()});import{isValidCron as NE}from"cron-validator";import{z as oe}from"zod";import{z as Mc}from"zod";var Bn=(r=>(r.CHROMIUM="Chromium",r.GOOGLE_CHROME="Google Chrome",r.CHROME_FOR_TESTING="Chrome for Testing",r))(Bn||{});var Xa=Mc.object({width:Mc.number().min(200).max(1e4),height:Mc.number().min(200).max(1e4)}),Wm={"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}},fD=Object.keys(Wm);var Ot=Wm["Desktop Large"],No="en-us",ko="America/Los_Angeles";var _o={latitude:37.7749,longitude:-122.4194};var Vm=["Africa/Abidjan","Africa/Accra","Africa/Algiers","Africa/Bissau","Africa/Cairo","Africa/Casablanca","Africa/Ceuta","Africa/El_Aaiun","Africa/Johannesburg","Africa/Juba","Africa/Khartoum","Africa/Lagos","Africa/Maputo","Africa/Monrovia","Africa/Nairobi","Africa/Ndjamena","Africa/Sao_Tome","Africa/Tripoli","Africa/Tunis","Africa/Windhoek","America/Adak","America/Anchorage","America/Argentina/Buenos_Aires","America/Argentina/Catamarca","America/Argentina/Cordoba","America/Argentina/Jujuy","America/Argentina/La_Rioja","America/Argentina/Mendoza","America/Argentina/Rio_Gallegos","America/Argentina/Salta","America/Argentina/San_Juan","America/Argentina/San_Luis","America/Argentina/Tucuman","America/Argentina/Ushuaia","America/Araguaina","America/Asuncion","America/Atikokan","America/Bahia","America/Bahia_Banderas","America/Barbados","America/Belem","America/Belize","America/Blanc-Sablon","America/Boa_Vista","America/Bogota","America/Boise","America/Cambridge_Bay","America/Campo_Grande","America/Cancun","America/Caracas","America/Cayenne","America/Chicago","America/Chihuahua","America/Costa_Rica","America/Creston","America/Cuiaba","America/Curacao","America/Danmarkshavn","America/Dawson","America/Dawson_Creek","America/Denver","America/Detroit","America/Dominica","America/Edmonton","America/Eirunepe","America/El_Salvador","America/Fort_Nelson","America/Fortaleza","America/Glace_Bay","America/Goose_Bay","America/Grand_Turk","America/Grenada","America/Guadeloupe","America/Guatemala","America/Guayaquil","America/Guyana","America/Halifax","America/Havana","America/Hermosillo","America/Indiana/Indianapolis","America/Indiana/Knox","America/Indiana/Marengo","America/Indiana/Petersburg","America/Indiana/Tell_City","America/Indiana/Vevay","America/Indiana/Vincennes","America/Indiana/Winamac","America/Inuvik","America/Iqaluit","America/Jamaica","America/Juneau","America/Kentucky/Louisville","America/Kentucky/Monticello","America/La_Paz","America/Lima","America/Los_Angeles","America/Maceio","America/Managua","America/Manaus","America/Marigot","America/Martinique","America/Matamoros","America/Mazatlan","America/Menominee","America/Merida","America/Metlakatla","America/Mexico_City","America/Miquelon","America/Moncton","America/Monterrey","America/Montevideo","America/Montserrat","America/Nassau","America/New_York","America/Nipigon","America/Nome","America/Noronha","America/North_Dakota/Beulah","America/North_Dakota/Center","America/North_Dakota/New_Salem","America/Ojinaga","America/Panama","America/Pangnirtung","America/Paramaribo","America/Phoenix","America/Port-au-Prince","America/Port_of_Spain","America/Porto_Velho","America/Puerto_Rico","America/Punta_Arenas","America/Rainy_River","America/Rankin_Inlet","America/Recife","America/Regina","America/Resolute","America/Rio_Branco","America/Santarem","America/Santiago","America/Santo_Domingo","America/Sao_Paulo","America/Scoresbysund","America/Sitka","America/St_Barthelemy","America/St_Johns","America/St_Kitts","America/St_Lucia","America/St_Thomas","America/St_Vincent","America/Swift_Current","America/Tegucigalpa","America/Thule","America/Thunder_Bay","America/Tijuana","America/Toronto","America/Tortola","America/Vancouver","America/Whitehorse","America/Winnipeg","America/Yakutat","America/Yellowknife","Antarctica/Casey","Antarctica/Davis","Antarctica/DumontDUrville","Antarctica/Macquarie","Antarctica/Mawson","Antarctica/Palmer","Antarctica/Rothera","Antarctica/Syowa","Antarctica/Troll","Antarctica/Vostok","Arctic/Longyearbyen","Asia/Aden","Asia/Almaty","Asia/Amman","Asia/Anadyr","Asia/Aqtau","Asia/Aqtobe","Asia/Ashgabat","Asia/Atyrau","Asia/Baghdad","Asia/Bahrain","Asia/Baku","Asia/Bangkok","Asia/Barnaul","Asia/Beirut","Asia/Bishkek","Asia/Brunei","Asia/Chita","Asia/Choibalsan","Asia/Colombo","Asia/Damascus","Asia/Dhaka","Asia/Dili","Asia/Dubai","Asia/Dushanbe","Asia/Famagusta","Asia/Gaza","Asia/Hebron","Asia/Ho_Chi_Minh","Asia/Hong_Kong","Asia/Hovd","Asia/Irkutsk","Asia/Jakarta","Asia/Jayapura","Asia/Jerusalem","Asia/Kabul","Asia/Kamchatka","Asia/Karachi","Asia/Kathmandu","Asia/Khandyga","Asia/Kolkata","Asia/Krasnoyarsk","Asia/Kuala_Lumpur","Asia/Kuching","Asia/Kuwait","Asia/Macau","Asia/Magadan","Asia/Makassar","Asia/Manila","Asia/Muscat","Asia/Nicosia","Asia/Novokuznetsk","Asia/Novosibirsk","Asia/Omsk","Asia/Oral","Asia/Phnom_Penh","Asia/Pontianak","Asia/Pyongyang","Asia/Qatar","Asia/Qostanay","Asia/Qyzylorda","Asia/Riyadh","Asia/Sakhalin","Asia/Samarkand","Asia/Seoul","Asia/Shanghai","Asia/Singapore","Asia/Srednekolymsk","Asia/Taipei","Asia/Tashkent","Asia/Tbilisi","Asia/Tehran","Asia/Thimphu","Asia/Tokyo","Asia/Tomsk","Asia/Ulaanbaatar","Asia/Urumqi","Asia/Ust-Nera","Asia/Vientiane","Asia/Vladivostok","Asia/Yakutsk","Asia/Yangon","Asia/Yekaterinburg","Asia/Yerevan","Atlantic/Azores","Atlantic/Bermuda","Atlantic/Canary","Atlantic/Cape_Verde","Atlantic/Faroe","Atlantic/Madeira","Atlantic/Reykjavik","Atlantic/South_Georgia","Atlantic/Stanley","Australia/Adelaide","Australia/Brisbane","Australia/Broken_Hill","Australia/Currie","Australia/Darwin","Australia/Eucla","Australia/Hobart","Australia/Lindeman","Australia/Lord_Howe","Australia/Melbourne","Australia/Perth","Australia/Sydney","Europe/Amsterdam","Europe/Andorra","Europe/Astrakhan","Europe/Athens","Europe/Belgrade","Europe/Berlin","Europe/Bratislava","Europe/Brussels","Europe/Bucharest","Europe/Budapest","Europe/Busingen","Europe/Chisinau","Europe/Copenhagen","Europe/Dublin","Europe/Gibraltar","Europe/Guernsey","Europe/Helsinki","Europe/Isle_of_Man","Europe/Istanbul","Europe/Jersey","Europe/Kaliningrad","Europe/Kiev","Europe/Kirov","Europe/Lisbon","Europe/Ljubljana","Europe/London","Europe/Luxembourg","Europe/Madrid","Europe/Malta","Europe/Mariehamn","Europe/Minsk","Europe/Monaco","Europe/Moscow","Europe/Oslo","Europe/Paris","Europe/Podgorica","Europe/Prague","Europe/Riga","Europe/Rome","Europe/Samara","Europe/San_Marino","Europe/Sarajevo","Europe/Saratov","Europe/Simferopol","Europe/Skopje","Europe/Sofia","Europe/Stockholm","Europe/Tallinn","Europe/Tirane","Europe/Ulyanovsk","Europe/Uzhgorod","Europe/Vaduz","Europe/Vatican","Europe/Vienna","Europe/Vilnius","Europe/Volgograd","Europe/Warsaw","Europe/Zagreb","Europe/Zaporozhye","Europe/Zurich","Indian/Antananarivo","Indian/Chagos","Indian/Christmas","Indian/Cocos","Indian/Comoro","Indian/Kerguelen","Indian/Mahe","Indian/Maldives","Indian/Mauritius","Indian/Mayotte","Indian/Reunion","Pacific/Apia","Pacific/Auckland","Pacific/Bougainville","Pacific/Chatham","Pacific/Chuuk","Pacific/Easter","Pacific/Efate","Pacific/Enderbury","Pacific/Fakaofo","Pacific/Fiji","Pacific/Funafuti","Pacific/Galapagos","Pacific/Gambier","Pacific/Guadalcanal","Pacific/Guam","Pacific/Honolulu","Pacific/Kiritimati","Pacific/Kosrae","Pacific/Kwajalein","Pacific/Majuro","Pacific/Marquesas","Pacific/Midway","Pacific/Nauru","Pacific/Niue","Pacific/Norfolk","Pacific/Noumea","Pacific/Pago_Pago","Pacific/Palau","Pacific/Pitcairn","Pacific/Pohnpei","Pacific/Port_Moresby","Pacific/Rarotonga","Pacific/Saipan","Pacific/Tahiti","Pacific/Tarawa","Pacific/Tongatapu","Pacific/Wake","Pacific/Wallis"];var qm=2e3,Ja=Br.extend({browserType:oe.nativeEnum(Bn).optional(),slowMoMs:oe.number().optional().refine(t=>t===void 0||t<=qm&&t>=-1,{message:`Slow motion must be between 0 and ${qm} milliseconds`}),basicAuthorization:oe.object({username:oe.string().optional(),password:oe.string().optional()}).optional(),geolocation:oe.object({latitude:oe.coerce.number().refine(t=>t>=-90&&t<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:oe.coerce.number().refine(t=>t>=-180&&t<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:oe.boolean().optional(),locale:oe.string().optional(),timezone:oe.enum(Vm).optional(),colorScheme:oe.enum(["light","dark"]).optional()}),Km=["extraHeaders","basicAuthorization","localChromeExtensionPaths"],Oc=oe.object({useMemory:oe.boolean().optional(),failureRecovery:oe.boolean().optional().describe("undefined means inherit org settings")}),kE=Oc.extend({disableAICaching:oe.boolean().optional(),failureRecoveryInstructions:oe.string().optional()}),_E=oe.object({viewport:Xa.optional()}),jr=_E.merge(kE).merge(Ja),Do=oe.object({cron:oe.string().refine(t=>NE(t),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:oe.boolean().default(!1),env:oe.string().optional(),timeZone:oe.string().default("America/Los_Angeles"),jobKey:oe.string().optional()}),Fo=oe.object({onSuccess:oe.boolean().default(!1),failureMessage:oe.string().optional(),onFailure:oe.boolean().default(!0),successMessage:oe.string().optional()}),DE=oe.object({name:oe.string(),required:oe.boolean().optional(),defaultValue:oe.string().describe("this is not optional because we need a value when the editor is first loaded")}),Qa=DE.array(),FE=oe.object({name:oe.string(),value:oe.string()}),Ym=FE.array(),Za=oe.object({name:oe.string(),default:oe.boolean().optional(),fixtures:Um.array().optional()});UE(F);var Xt={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},ue=(s=>(s.PENDING="PENDING",s.RUNNING="RUNNING",s.PASSED="PASSED",s.FAILED="FAILED",s.CANCELLED="CANCELLED",s.RETRYING="RETRYING",s.WAITING_FOR_USER="WAITING_FOR_USER",s))(ue||{}),es=(n=>(n.BEFORE_ALL="BEFORE_ALL",n.AFTER_ALL="AFTER_ALL",n))(es||{});var Ye=F.string().pipe(F.coerce.date()).or(F.date()),Ni=F.object({id:F.string(),runKey:F.string(),organizationId:F.string(),executionType:F.nativeEnum(Oo).optional().default("WEB"),createdAt:Ye,createdBy:F.string(),flake:F.boolean().nullish(),scheduledAt:Ye.or(F.null()),startedAt:Ye.or(F.null()),updatedAt:Ye.nullish(),finishedAt:Ye.or(F.null()),resolvedBaseUrl:F.string().nullish(),environmentName:F.string().nullish(),gitBranchName:F.string().nullish(),githubRepository:F.string().nullish(),gitlabProjectPath:F.string().nullish(),labels:F.array(F.string()).optional(),gitOriginUrl:F.string().nullish(),gitCommitSha:F.string().nullish(),gitCommitShaShort:F.string().nullish(),gitCommitAuthorName:F.string().nullish(),cliVersion:F.string().nullish(),section:F.nativeEnum(es).nullish(),status:F.nativeEnum(ue),trigger:F.nativeEnum(Xt),attempts:F.number(),runAttempts:F.array(F.object({id:F.string(),status:F.nativeEnum(ue),startedAt:Ye.or(F.null()),finishedAt:Ye.or(F.null())})).optional(),videos:F.array(F.string()).optional(),failureReason:F.nativeEnum(he).nullish(),failureDetails:Wa.nullish(),failureRecoveryDetails:F.record(F.string(),F.unknown()).nullish(),pipelineId:F.string().nullish(),testFragments:F.array(Lc).nullish(),resolvedInputs:F.record(F.string(),F.string()).nullish(),quarantined:F.boolean().nullish().default(!1),quarantinedReason:F.string().nullish(),localTestId:F.string().nullish(),testId:F.string().nullish(),testName:F.string().nullish(),description:F.string().nullish(),test:F.object({name:F.string(),id:F.string()}).nullish().default(null),suiteId:F.string().nullish()}).openapi({ref:"RunMetadata"}),BE={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},ts=Ni.pick({...BE,test:!0}),Xm=Ni.omit({failureReason:!0,failureDetails:!0,test:!0}),Nc=Ni.extend({stepsSnapshot:F.array(F.record(F.unknown())).nullish(),resolvedInputs:F.record(F.string(),F.string()).nullish(),test:F.object({name:F.string(),id:F.string(),description:F.string().nullish(),baseUrl:F.string().nullish(),advanced:jr.nullish()}).nullish()}).merge(Ic),Jm=t=>t.includes("PASSED")&&t.includes("FAILED");var zE=ki.object({id:ki.string().uuid(),startedAt:Ye.or(ki.null()),finishedAt:Ye.or(ki.null()),status:ki.nativeEnum(ue)}).merge(Oi),BD=zE.array();var ns=(o=>(o.JUNIT="junit",o.ALLURE="allure",o.ALLURE_JSON="allure-json",o.PLAYWRIGHT_JSON="playwright-json",o))(ns||{});import{z as Xe}from"zod";var HE=Xe.object({id:Xe.string(),status:Xe.nativeEnum(ue),trigger:Xe.nativeEnum(Xt),createdAt:Ye,startedAt:Ye.nullish(),finishedAt:Ye.nullish(),gitCommitSha:Xe.string().nullish(),gitCommitShaShort:Xe.string().nullish(),gitCommitTimestamp:Ye.nullish(),gitBranchName:Xe.string().nullish(),gitOriginUrl:Xe.string().nullish(),gitCommitMessage:Xe.string().nullish(),gitCommitAuthorName:Xe.string().nullish(),githubRepository:Xe.string().nullish(),gitlabProjectPath:Xe.string().nullish(),pipelineId:Xe.string().nullish(),cliVersion:Xe.string().nullish(),labels:Xe.string().array().optional(),suite:Xe.object({id:Xe.string(),name:Xe.string()}).nullish(),runs:Xe.object({status:Xe.nativeEnum(ue)}).array()}).openapi({ref:"RunGroup"}),Qm=HE.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:ts.array()});import{z as at}from"zod";var $E=at.object({type:at.literal("TARGETING"),name:at.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:_m.array(),pageState:at.string().optional(),targetSource:at.nativeEnum(er).optional(),targetUpdateTime:at.string().optional()}),jE=at.object({type:at.literal("AI_LOCATION"),matched:at.boolean(),pageState:at.string().optional(),ragUsed:at.boolean().optional(),thoughts:at.string().optional()}),GE=at.object({type:at.literal("ASSERTION"),relevantElementsSerialized:at.string().array().optional(),pageState:at.string().optional(),ragUsed:at.boolean().optional()}),Zm=at.discriminatedUnion("type",[$E,jE,GE]);function rs(){return{details:[]}}import{z as Ve}from"zod";var WE=Ve.object({id:Ve.string(),name:Ve.string()}),ZD=WE.merge(Ve.object({createdAt:Ye,createdBy:Ve.string(),schedule:Do,notification:Fo,environment:Ve.object({name:Ve.string()}).nullish(),beforeTests:Ve.object({id:Ve.string()}).array().nullish(),afterTests:Ve.object({id:Ve.string()}).array().nullish()})),ep=Ve.object({id:Ve.string().uuid(),orgId:Ve.string(),createdAt:Ye,startedAt:Ye.or(Ve.null()),finishedAt:Ye.or(Ve.null()),status:Ve.nativeEnum(ue),trigger:Ve.nativeEnum(Xt),suite:Ve.object({id:Ve.string(),name:Ve.string()}).nullish(),runs:Ni.array()}),eF=ep.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),tp=ep.extend({runs:ts.array()});import{z as Jt}from"zod";import{cloneDeep as rF}from"lodash-es";import{z as ye}from"zod";var cF=ye.object({thoughts:ye.string(),subGoals:ye.object({instruction:ye.string()}).array()}),dF=ye.object({thoughts:ye.string(),newPlanMarkdown:ye.string()}),uF=ye.object({thoughts:ye.string(),correct:ye.boolean(),failedActionIndex:ye.number().optional()}),VE=ye.object({type:ye.literal("PLANNING"),beforePlan:ye.string(),goalDecision:ye.string(),thoughts:ye.string()}),qE=ye.object({type:ye.literal("RUNNING"),stepDisplayName:ye.string(),status:ye.nativeEnum(Ce),results:et.array()}),KE=ye.object({type:ye.literal("REVISING"),beforePlan:ye.string(),afterPlan:ye.string(),errString:ye.string(),diffs:ye.string(),thoughts:ye.string()}),YE=ye.object({type:ye.literal("SYSTEM"),message:ye.string()}),XE=ye.discriminatedUnion("type",[VE,qE,KE,YE]),np=XE.array();var fF=Jt.object({id:Jt.string(),scheduledAt:Jt.coerce.date().nullable(),startedAt:Jt.coerce.date().nullable(),finishedAt:Jt.coerce.date().nullable(),status:Jt.nativeEnum(ue),history:np.nullable(),testPlan:Jt.object({id:Jt.string(),name:Jt.string()}).nullable(),test:Jt.object({id:Jt.string(),name:Jt.string()}).nullable()});import{z as vt}from"zod";var kc=vt.object({content:vt.string(),ids:vt.string().array(),tokenLength:vt.number()}),JE=vt.object({chunks:kc.array()}),NF=vt.object({ids:vt.string().array(),score:vt.number(),tokenLength:vt.number()}),kF=JE.extend({description:vt.string().describe("Input to pass to RAG engine"),tokenLimit:vt.number()}),rp=vt.object({ids:vt.number().array()}),op=vt.object({indices:vt.number().array()});var Nt=O.object({disableCache:O.boolean().optional(),useMemory:O.boolean().optional(),loggerTags:O.record(O.string(),O.string()).optional(),langfuseSessionId:O.string().optional(),agentConfigVersion:O.string().optional()}),$F=Nt.extend({chunks:kc.array(),description:O.string().describe("Input to pass to AI"),type:O.union([O.literal("locator"),O.literal("assertion"),O.literal("ai-action")]),softTokenLimit:O.number(),hardTokenLimit:O.number()}),QE=O.object({screenshotBase64AfterCommand:O.string(),urlAfterCommand:O.string(),serializedCommand:O.string(),elementInteracted:O.string().optional(),thoughts:O.string().optional()}),ip=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string(),source:Ha.optional().catch(void 0),memory:O.discriminatedUnion("type",[To,O.object({type:O.literal("RESOLVED_TRACES"),traces:O.unknown().array()})]).optional()}),ap=O.object({target:O.string().or(O.number()),browserState:O.string().optional(),screenshot:O.string().optional(),boundingBox:O.object({x:O.number(),y:O.number(),height:O.number(),width:O.number()}).optional()}),sp=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string().optional(),returnSchema:O.string().optional()}),ZE=O.literal("NEGATED_CHECK"),lp=O.object({goal:O.string(),browserState:O.string(),screenshot:O.string(),url:O.string(),contextChoice:cc.optional(),memory:O.discriminatedUnion("type",[nc,O.object({type:O.literal("RESOLVED_TRACES"),traces:O.unknown().array()})]).optional(),source:ZE.optional()}),cp=O.object({command:Ao}),_c=O.object({goal:O.string(),browserState:O.string(),startingScreenshot:O.string().optional(),screenshot:O.string(),url:O.string(),history:QE.array(),actionHint:O.string().optional(),lastError:O.string().optional()}),dp=O.object({results:Ka.array(),errorMessage:O.string(),errorStack:O.string().optional()}),up=O.object({results:Ka.array(),goal:O.string(),errorMessage:O.string()}),mp=O.object({failedResults:Ka.array(),nextStepsSerialized:O.string().array(),currentUrl:O.string(),currentPageState:O.string(),currentScreenshot:O.string(),customInstructions:O.string().optional(),testDescription:O.string().optional()}),jF=O.object({description:O.string(),type:O.union([O.literal("locator"),O.literal("assertion"),O.literal("ai-action")]),excerpt:O.string()});import{z as _i}from"zod";var VF=_i.object({goal:_i.string()}),pp=_i.object({keywords:_i.array(_i.string())});import{z as Dc}from"zod";var os=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(os||{}),YF=Dc.nativeEnum(os),eC=Dc.enum(["v1","v2"]),XF=eC.or(Dc.string().describe("for people with special configurations"));import{z as Fe}from"zod";var gp=Fe.object({attributesRequired:Fe.array(Fe.string()).optional(),textRequired:Fe.boolean().optional(),boundsRequired:Fe.boolean().optional()}),tC=Fe.object({id:Fe.number(),thoughts:Fe.string(),requirements:gp.optional(),additionalElements:Fe.object({id:Fe.number(),requirements:gp}).array().optional()}),hp=Fe.object({description:Fe.string(),screenXml:Fe.string(),screenshot:Fe.string()}),fp=Fe.object({assertion:Fe.string(),screenXml:Fe.string(),screenshot:Fe.string()}),nC=Fe.object({thoughts:Fe.string(),result:Fe.boolean(),relevantElements:Fe.array(Fe.number()).optional()});var Sp=t=>!(!t.org_id||!t.user_id||!t.platform);import{z as Gr}from"zod";var yp=Gr.object({id:Gr.string().uuid(),skipped:Gr.boolean().optional(),envKey:Gr.string().optional().describe("key in the environment to save the result of this step to")}),Fc=yp.merge(Ma).extend({type:Gr.literal("REQUEST")}),Uc=yp.merge(Oa).extend({type:Gr.literal("JAVASCRIPT")}),Bc=Gr.discriminatedUnion("type",[Uc,Fc]);import{z as Qt}from"zod";import{z as Wr}from"zod";var rC=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,ve=t=>{let e=t.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 is=Wr.string().min(1).max(255).superRefine((t,e)=>{try{Vr(t)}catch(n){return e.addIssue({code:Wr.ZodIssueCode.custom,message:n.message,fatal:!0}),Wr.NEVER}});function Vr(t){if(t=t.toLowerCase().trim(),t.length===0||t.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(t))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(t.endsWith("-")||t.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(t.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(t))throw new Error(`"${t}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(t)||/^\s|\s$/.test(t))throw new Error("Name cannot start or end with a space or dot.");if(t.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(t==="none")throw new Error("Name cannot be 'none'.");if(t.match(rC))throw new Error("Name cannot be a UUID. Please choose a different name.")}var as=Wr.preprocess(t=>t===null?"":t,Wr.union([Wr.string().url(),Wr.literal("")])).optional();var bp=Qt.object({id:Qt.string(),name:is,description:Qt.string().optional().nullish(),baseUrl:as.nullish(),schemaVersion:Qt.string(),advanced:Qt.unknown().optional(),retries:Qt.number(),envs:Qt.array(Za).nullish(),parameters:Qa.nullish()}),oC=Qt.object({createdAt:Qt.coerce.date(),updatedAt:Qt.coerce.date(),schedule:Do.nullish(),notification:Fo.nullish(),createdBy:Qt.string(),organizationId:Qt.string()}),iC=bp.merge(oC),E0=iC.extend({steps:Bc.array()}),C0=bp.extend({steps:Bc.array()});import{z as kt}from"zod";var Tp=kt.object({startedAt:kt.coerce.date(),finishedAt:kt.coerce.date(),status:kt.nativeEnum(Ce),message:kt.string().optional(),data:kt.unknown().optional()}),aC=Tp.merge(Uc).extend({type:kt.literal("JAVASCRIPT")}),sC=Tp.merge(Fc).extend({type:kt.literal("REQUEST")}),lC=kt.discriminatedUnion("type",[aC,sC]),wp=kt.object({startedAt:kt.coerce.date(),finishedAt:kt.coerce.date().nullish(),status:kt.nativeEnum(ue),results:lC.array(),failureReason:kt.string().nullish(),failureDetails:Wa.nullish()});import{z as _t}from"zod";var cC=_t.object({id:_t.string(),organizationId:_t.string(),createdAt:_t.coerce.date(),updatedAt:_t.coerce.date(),createdBy:_t.string(),scheduledAt:_t.coerce.date().nullish(),startedAt:_t.coerce.date().nullish(),finishedAt:_t.coerce.date().nullish(),status:_t.nativeEnum(ue),trigger:_t.nativeEnum(Xt),results:wp.array().nullish(),apiTestName:_t.string().nullish(),apiTestPath:_t.string().nullish(),apiTestId:_t.string().nullish()}),N0=cC.pick({status:!0,startedAt:!0,finishedAt:!0});var Di=(n=>(n.TestRun="test-run",n.CreditsUsed="credits-used",n))(Di||{}),Ep=3;function dC(t){return t==="MODULE"||t==="CONDITIONAL"||t==="SECTION"||t==="RESOLVED_MODULE"}function zc(t){if(!dC(t))switch(t){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function Hc(t){switch(t.type){case"AI_EXTRACT":case"AI_ASSERTION":return Ep;case"CAPTCHA":return 3;case"CLICK":case"TYPE":case"SELECT_OPTION":case"HOVER":case"ELEMENT_CHECK":case"FOCUS":case"BLUR":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_UP":case"MOUSE_DRAG":return t.useSelector||!t.target||t.target.type!=="description"?0:1;case"DRAG":return t.useSelector?0:1;case"VISUAL_DIFF":case"TAB":case"JAVASCRIPT":case"NAVIGATE":case"WAIT":case"SUCCESS":case"AUTH_LOAD":case"AUTH_SAVE":case"COOKIE":case"DIALOG":case"FILE_UPLOAD":case"GO_BACK":case"GO_FORWARD":case"LOCAL_STORAGE":case"NEW_TAB":case"PAGE_CHECK":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"COPY":case"PASTE":case"REFRESH":case"REQUEST":case"GRAPHQL_REQUEST":case"WAIT_FOR_URL":case"REGISTER_REQUEST_LISTENER":case"AWAIT_LISTENER":case"RECORD_REQUESTS":case"GET_RECORDED_REQUESTS":case"SET_HEADER":case"OFFLINE_MODE":return 0;default:(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}var Uo=class{async reportBillableEvent(e,n,r){}async reportCreditsUsed(e,n,r,o){}};function $c(t,e){return{...t,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}import{parseString as uC,splitCookiesString as mC}from"set-cookie-parser";import{z as we}from"zod";var jc=we.object({name:we.string(),value:we.string(),url:we.string().optional(),domain:we.string().optional(),path:we.string().optional(),expires:we.number().default(Date.now()/1e3+60*60*24*365),httpOnly:we.boolean().optional(),secure:we.boolean().default(!0),sameSite:we.union([we.literal("Strict"),we.literal("Lax"),we.literal("None")]).default("None")});function ss(t,e){let n=[],r=mC(t);for(let o of r){let i=uC(o,{decodeValues:!1});if(!i.name)throw new Error("Name missing from cookie");if(!i.value)continue;let a;if(i.sameSite){let d=i.sameSite.trim().toLowerCase();if(d==="strict")a="Strict";else if(d==="lax")a="Lax";else if(d==="none")a="None";else throw new Error(`Invalid sameSite setting in cookie: ${d}`)}i.httpOnly===void 0&&(i.httpOnly=!1),!i.path&&i.domain&&(i.path="/"),!i.domain&&e&&(i.domain=e);let s=jc.parse({...i,expires:i.expires?i.expires.getTime()/1e3:void 0,sameSite:a});n.push(s);let l=[s.name,...Object.keys(s)].map(d=>d.toLowerCase()),c=o.match(/\b(\S+)=([^;]*)/g);if(c)for(let d of c){let[u,m]=d.split("=");if(!u||!m)throw new Error(`Invalid key-value pair in cookie: ${d}`);l.includes(u.toLowerCase())||n.push({...s,name:u,value:m})}}return n}var pC=we.object({origin:we.string(),localStorage:we.array(we.object({name:we.string(),value:we.string()}))}),gC=we.object({entries:we.record(we.string(),we.array(we.tuple([we.unknown(),we.unknown()]))),version:we.number().optional()}),ls=we.object({cookies:jc.array().optional(),origins:pC.array().optional(),idb:we.record(we.string(),gC).optional().describe("key is db name")});function Cp(t,e){let n=[];return t.cloneSync()?.serializeSync()?.cookies.forEach(r=>{let o=jc.safeParse({name:r.key,...r});if(!o.success)return;let i=o.data;!i.domain&&!i.url&&(i.domain=e),n.push(i)}),n}import vC from"zod";import{v4 as tU}from"uuid";import{z as be}from"zod";import*as Me from"zod";var Rp=Me.object({requiredText:Me.string().optional(),requiredAttributes:Me.record(Me.string(),Me.string()).optional(),requiredBounds:Me.boolean().optional()}),hC=Me.object({xPath:Me.string(),requirements:Rp.optional()}),fC=Me.object({type:Me.literal("NATIVE"),bounds:Me.number().array(),resolvedDescription:Me.string(),xPath:Me.string(),elementOnlySerializedXml:Me.string(),requirements:Rp.optional(),requiredRelatedElements:hC.array().optional()}),SC=Me.object({type:Me.literal("WEBVIEW"),resolvedDescription:Me.string(),xPath:Me.string(),browserCache:tr.optional()}),vp=Me.discriminatedUnion("type",[fC,SC]);var Bo=(c=>(c.AI_CHECK="AI_CHECK",c.TAP="TAP",c.TYPE="TYPE",c.PRESS="PRESS",c.OPEN_APP="OPEN_APP",c.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",c.JAVASCRIPT="JAVASCRIPT",c.ADB="ADB",c.STATE="STATE",c))(Bo||{}),Ap=(l=>(l.BACK="BACK",l.HOME="HOME",l.APP_SWITCHER="APP_SWITCHER",l.POWER="POWER",l.SEARCH="SEARCH",l.VOLUME_UP="VOLUME_UP",l.VOLUME_DOWN="VOLUME_DOWN",l.VOLUME_MUTE="VOLUME_MUTE",l))(Ap||{}),xp=be.discriminatedUnion("type",[be.object({type:be.literal("description"),description:be.string()}),be.object({type:be.literal("coordinates"),xPercent:be.number(),yPercent:be.number()})]),zn=be.object({id:be.string().uuid(),disableCache:be.boolean().optional()}),yC=zn.extend({type:be.literal("STATE")}),Ip=be.object({target:vp}),Gc=zn.extend({type:be.literal("TAP"),target:xp,cache:Ip.optional()}),Wc=zn.extend({type:be.literal("TYPE"),target:xp.optional(),cache:Ip.optional(),text:be.string()}),bC=zn.extend({type:be.literal("OPEN_NOTIFICATION_DRAWER")}),TC=zn.extend({type:be.literal("PRESS"),key:be.nativeEnum(Ap)}),wC=zn.extend({type:be.literal("OPEN_APP"),packageName:be.string(),activityName:be.string().optional()}),EC=zn.extend({type:be.literal("AI_CHECK"),assertion:be.string(),timeoutSecs:be.number().optional()}),CC=zn.extend({type:be.literal("JAVASCRIPT"),code:be.string(),timeout:be.number().int().max(60).optional().describe("Max seconds for the code to complete")}),RC=zn.extend({type:be.literal("ADB"),command:be.string()}),Pp=be.discriminatedUnion("type",[Gc,Wc,TC,wC,bC,EC,CC,RC,yC]);var Lp={type:!0,cache:!0},zo=vC.discriminatedUnion("type",[Gc.pick(Lp),Wc.pick(Lp)]),cU=Object.values(Bo).filter(t=>zo.options.some(e=>e.shape.type.safeParse(t).success));var Mp=Ai(zo),Op=xi(zo),dU=Fa(zo);import{cloneDeep as pU}from"lodash-es";import hU from"truncate-json";import sr from"zod";import Fi from"zod";var AC=Fi.object({id:Fi.string().uuid(),envKey:Fi.string().optional()}),Hn=AC.extend({type:Fi.literal("MOBILE_PRESET_STEP"),command:Pp}),TU=Fi.discriminatedUnion("type",[Hn]);import Ue from"zod";var Ho=Ue.object({startTime:Ue.number(),endTime:Ue.number().optional(),error:Ue.string().optional()});var Vc=Ho.extend({type:Ue.literal("SECTION"),name:Ue.string(),subSpans:Ue.lazy(()=>OC.array())}),xC=Ho.extend({type:Ue.literal("AI_LOCATOR_CALL"),result:Ue.object({serializedElement:Ue.string(),id:Ue.number(),thoughts:Ue.string()}).optional()}),IC=Ho.extend({type:Ue.literal("AI_ASSERTION_CALL"),result:Ue.object({thoughts:Ue.string(),result:Ue.boolean()}).optional()}),PC=Ho.extend({type:Ue.literal("WAIT_FOR_STABILITY"),reason:Ue.string().optional()}),LC=Ho.extend({type:Ue.literal("RESOLVE_TARGET_CACHE"),result:Ue.object({serializedElement:Ue.string()}).optional()}),MC=Ho.extend({type:Ue.literal("GET_EMULATOR_STATE")}),OC=Ue.discriminatedUnion("type",[Vc,xC,IC,PC,LC,MC]);var NC=sr.object({message:sr.string().optional(),startTime:sr.number(),endTime:sr.number(),status:sr.nativeEnum(Ce),trace:Vc.optional().catch(void 0),beforeSnapshot:sr.string().optional(),afterSnapshot:sr.string().optional()}),kC=Hn.merge(NC).extend({data:sr.unknown().optional().describe("output data from the step")}),cs=kC;import tt from"zod";import{z as sn}from"zod";import{z as _e}from"zod";var St=_e.object({id:_e.string(),name:is,baseUrl:as,description:_e.string().optional().nullish(),schemaVersion:_e.string(),advanced:jr,retries:_e.number(),envs:_e.array(Za).nullish(),parameters:Qa.nullish(),disabled:_e.boolean().optional(),labels:_e.array(_e.string()).optional().catch([])}),NU=_e.enum(["INHERIT","ENABLED","DISABLED"]);var _C=jr.extend({failureRecovery:_e.boolean().or(_e.string()).optional().transform(t=>typeof t=="string"?t:t===void 0?"INHERIT":t?"ENABLED":"DISABLED"),useMemory:_e.boolean().or(_e.string()).optional().transform(t=>typeof t=="string"?t:t===void 0?"INHERIT":t?"ENABLED":"DISABLED")});var kU=St.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:_C}),_U=St.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),DC=_e.object({labels:_e.array(_e.string()).optional(),outputs:Ym.nullish()}),Zt=St.merge(DC),FC=_e.object({createdAt:_e.coerce.date(),updatedAt:_e.coerce.date(),updatedBy:_e.string().nullable(),schedule:Do,notification:Fo,createdBy:_e.string(),organizationId:_e.string(),folderId:_e.string().nullable().optional()}),UC=St.merge(FC),DU=UC.merge(Io),ds=St.merge(Io),FU=St.merge(Fr);var Np="test",kp="module",BC="mobile-test",st=(n=>(n.TEST=`${Np}.yaml`,n.MODULE=`${kp}.yaml`,n))(st||{}),fe=(r=>(r.TEST=`momentic/${Np}`,r.MODULE=`momentic/${kp}`,r.MOBILE_TEST=`momentic/${BC}`,r))(fe||{}),GU=St.merge(Fr),qc=Mt.extend({steps:sn.array(sn.record(sn.string(),sn.unknown())),schemaVersion:sn.string()}),WU=qc.extend({fileType:sn.literal(fe.MODULE)}),VU=sn.object({test:sn.string().describe("YAML for the test, including metadata and steps"),modules:sn.record(sn.string(),sn.string()).describe("Map of module name to YAML for the module")});var zC=tt.object({disableDefaultWebviewAccessibilityTree:tt.boolean().optional(),autoGrantPermissions:tt.boolean().optional()}),HC=zC,Ui=tt.object({retries:tt.number().optional().describe("number of retries to run"),defaultChannel:tt.string().optional().describe("default channel to use"),defaultTag:tt.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:tt.string().optional(),emulator:HC.optional()}),Kc=tt.object({id:tt.string().uuid(),description:tt.string(),schemaVersion:tt.string(),settings:Ui}),$C=Kc.merge(tt.object({steps:tt.array(Hn)})),_p=tt.object({fileType:tt.literal(fe.MOBILE_TEST)}).merge($C),JU=tt.object({name:tt.string(),steps:tt.array(Hn).optional(),settings:Ui.optional()});var gB=new Set(Object.values(We));var jC={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",KEY_DOWN:"Key down",KEY_UP:"Key up",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:"localStorage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL 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",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",RECORD_REQUESTS:"Record requests",GET_RECORDED_REQUESTS:"Get recorded requests",SET_HEADER:"Set header",OFFLINE_MODE:"Offline mode",SUCCESS:"Done"},hB={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],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"],KEY_DOWN:["keyboard","type","key","down","press"],KEY_UP:["keyboard","type","key","up","press"],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:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],RECORD_REQUESTS:[],GET_RECORDED_REQUESTS:[],SET_HEADER:[],OFFLINE_MODE:[],SUCCESS:[]},fB={AI_ACTION:"Ask AI achieve a specific goal. Saves the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",HOVER:"Hover over an element on the page.",FILE_UPLOAD:"Automatically upload a file when the native file upload dialog is activated.",FOCUS:"Focus an element on the page.",BLUR:"Remove focus from an element on the page.",SELECT_OPTION:"Select an option from an HTML Select <select> element.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",KEY_DOWN:"Hold down the specified keys on the keyboard. (e.g. Control+A)",KEY_UP:"Release the specified keys on the keyboard. (e.g. Control+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 localStorage 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.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",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 or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",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 contents using pre-built conditions.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",RECORD_REQUESTS:"Record network requests that match a given pattern.",GET_RECORDED_REQUESTS:"Get recorded requests that matched the pattern.",SET_HEADER:"Set a header.",OFFLINE_MODE:"Configure offline mode.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."},SB={AI_CHECK:"AI check",TAP:"Tap",TYPE:"Type",PRESS:"Press",OPEN_APP:"Open app",JAVASCRIPT:"JavaScript",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",ADB:"ADB command",STATE:"Debug state"},yB={AI_CHECK:"Ask AI to verify whether something is true on the screen.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a button on the device or on the screen.",OPEN_APP:"Open an app on the device.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",ADB:"Execute an ADB command on the device.",STATE:"Get the debug state of the device."};import GC from"semver";import{z as WC}from"zod";var EB=WC.string().refine(t=>GC.valid(t),{message:"must be a valid semver string"});import{Faker as vB,en as AB}from"@faker-js/faker";import{z as j}from"zod";var us=55555,IB=j.object({body:j.string(),to:j.string(),from:j.string()}),PB=j.object({from:j.string().optional(),to:j.string(),timeout:j.number().optional(),beforeDate:j.string().pipe(j.coerce.date()).or(j.date()).optional(),afterDate:j.string().pipe(j.coerce.date()).or(j.date()).optional()}),LB=j.object({to:j.string().email(),from:j.string(),subject:j.string(),body:j.string(),html:j.string().optional()}),MB=j.object({inbox:j.string().transform(t=>t.toLowerCase()),afterDate:j.string().pipe(j.coerce.date()).or(j.date()).optional(),timeout:j.number().optional(),trimWhitespace:j.boolean().optional()}),OB=j.object({inbox:j.string(),limit:j.number().optional(),afterDate:j.string().pipe(j.coerce.date()).or(j.date()).optional(),trimWhitespace:j.boolean().optional()});var Dp=j.object({result:j.unknown(),variableUpdates:j.record(j.string(),j.unknown()).optional(),persistentVariableUpdates:j.record(j.string(),j.unknown()).optional(),error:j.string().optional(),success:j.boolean()}),NB=j.object({id:j.string().optional(),orgId:j.string(),momenticLambdaAuthHash:j.string(),code:j.string(),fragment:j.boolean(),state:j.object({env:j.record(j.string(),j.unknown())}),timeoutMs:j.number().optional()}),lr=15e3;import*as yt from"zod";import{extendZodWithOpenApi as VC}from"zod-openapi";VC(yt);var qC=yt.object({url:yt.string(),lineNumber:yt.number(),columnNumber:yt.number()}).openapi({ref:"CodeLocation"}),ms=yt.object({timestamp:yt.number(),text:yt.string(),type:yt.string(),tabIndex:yt.number(),args:yt.unknown().array().optional(),url:yt.string().optional(),location:qC.optional()}).openapi({ref:"ConsoleLog"}),Fp=ms.array(),KC=Fp.array();import*as Xc from"zod";import{extendZodWithOpenApi as gR}from"zod-openapi";import{z as I}from"zod";var YC=I.object({name:I.string(),version:I.string(),comment:I.string().optional()}),XC=I.object({name:I.string(),version:I.string(),comment:I.string().optional()}),JC=I.object({onContentLoad:I.number().optional(),onLoad:I.number().optional(),comment:I.string().optional()}),Bp=I.object({startedDateTime:I.string(),id:I.string(),title:I.string().optional(),pageTimings:JC,comment:I.string().optional()}),QC=I.array(Bp),ZC=I.object({name:I.string(),value:I.string(),path:I.string().optional(),domain:I.string().optional(),expires:I.string().optional(),httpOnly:I.boolean().optional(),secure:I.boolean().optional(),comment:I.string().optional()}),zp=I.array(ZC),eR=I.object({name:I.string(),value:I.string(),comment:I.string().optional()}),Hp=I.array(eR),tR=I.object({name:I.string(),value:I.string(),comment:I.string().optional()}),nR=I.array(tR),rR=I.object({name:I.string(),value:I.string().optional(),fileName:I.string().optional(),contentType:I.string().optional(),comment:I.string().optional()}),oR=I.array(rR),iR=I.object({mimeType:I.string(),params:oR,text:I.string(),comment:I.string().optional()}),aR=I.object({method:I.string(),url:I.string(),httpVersion:I.string().optional(),cookies:zp,headers:Hp,queryString:nR,postData:iR.optional(),headersSize:I.number().optional(),bodySize:I.number().optional(),comment:I.string().optional()}),sR=I.object({size:I.number().optional(),compression:I.number().optional(),mimeType:I.string().optional(),text:I.string().optional(),encoding:I.string().optional(),comment:I.string().optional()}),lR=I.object({status:I.number(),statusText:I.string(),httpVersion:I.string().optional(),cookies:zp,headers:Hp,content:sR,redirectURL:I.string().optional(),headersSize:I.number().optional(),bodySize:I.number().optional(),comment:I.string().optional()}),Up=I.object({expires:I.string().optional(),lastAccess:I.string(),eTag:I.string(),hitCount:I.number(),comment:I.string().optional()}),cR=I.object({beforeRequest:Up.optional(),afterRequest:Up.optional(),comment:I.string().optional()}),dR=I.object({blocked:I.number().optional(),dns:I.number().optional(),connect:I.number().optional(),send:I.number(),wait:I.number(),receive:I.number(),ssl:I.number().optional(),comment:I.string().optional()}),$p=I.object({pageref:I.string().optional(),startedDateTime:I.string(),time:I.number().optional(),request:aR,response:lR.optional(),cache:cR.optional(),timings:dR,serverIPAddress:I.string().optional(),connection:I.string().optional(),comment:I.string().optional(),_resourceType:I.string().optional()}),uR=I.array($p),mR=I.object({version:I.string().default("1.1"),creator:YC.optional(),browser:XC.optional(),pages:QC.optional(),entries:uR,comment:I.string().optional()}),pR=I.object({log:mR}),jp=I.record(I.string(),Bp),Gp=I.record(I.string(),$p);function Yc(t,e){return{log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(t).sort((n,r)=>new Date(n.startedDateTime).getTime()-new Date(r.startedDateTime).getTime()),entries:Object.values(e).sort((n,r)=>new Date(n.startedDateTime).getTime()-new Date(r.startedDateTime).getTime())}}}gR(Xc);var hR=Xc.object({logsPerPage:ms.array().array(),harPages:jp.optional(),harEntries:Gp.optional()}).openapi({ref:"DebugData"});var Bi=class{async getConsoleLogsForRunAttempt(e,n,r){}async getNetworkLogsForRunAttempt(e,n,r){}async getHtmlSnapshot(e,n){}async getA11yTreeSnapshot(e,n){}async getScreenshot(e,n){}async storeConsoleLogsForRunAttempt(e,n,r,o){}async storeNetworkLogsForRunAttempt(e,n,r,o){}async storeScreenshot(e,n,r){}async storeHtmlSnapshot(e,n,r){}};var ps=class extends Error{constructor(e,n,r,o={}){super(`The ${r} with id ${n} is invalid: ${e}`,o),this.name="InvalidEntityError"}};function Wp(t){for(let e of Object.values(he))if(t.includes(e))return e}var A=class extends Error{reason;constructor(e,n,r){let o=!1;for(let i of Object.values(he))if(n.startsWith(i)){o=!0,e=i;break}if(r?.errOptions?.cause)super(o?n:`${e}: ${n}`,r?.errOptions);else{let i=o?n:`${e}${n?`: ${n}`:""}`;super(i,r?.errOptions)}this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message}}},$o=class extends Error{updatedLocatorMemory;constructor(e,n,r={}){super(e,r),this.updatedLocatorMemory=n,this.name="NoElementsFoundUsingAIError"}},wn=class extends Error{decisions;constructor(e,n,r={}){super(e,r),this.decisions=n,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
3
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="5ae4a21c-85ec-580b-8627-11d5337ee5e5")}catch(e){}}();
4
+ var wa=(t,e)=>{},ic=!1;try{let t=await import("@sentry/node");wa=t.captureException,t.init({dsn:"https://89e980855f7b9c6e56fc6c7e7143888b@o4506426201800704.ingest.us.sentry.io/4508343221354497",environment:"production",release:process.env.SENTRY_RELEASE_NAME,tracesSampleRate:0}),ic=!0}catch{}import{Command as eN,Option as Ut}from"@commander-js/extra-typings";import{execSync as tN}from"child_process";var Ea=!!process.env.CI||!!process.env.GITHUB_ACTIONS||!!process.env.GITHUB_RUN_ID||!!process.env.GITLAB_CI||!!process.env.CI_COMMIT_SHA||!!process.env.JENKINS_URL||!!process.env.BUILD_NUMBER||!!process.env.JENKINS_HOME||!!process.env.CIRCLECI||!!process.env.CIRCLE_BUILD_NUM||!!process.env.TRAVIS||!!process.env.TRAVIS_BUILD_NUMBER||!!process.env.BITBUCKET_BUILD_NUMBER||!!process.env.BITBUCKET_COMMIT||!!process.env.CODEBUILD_BUILD_ID||!!process.env.TF_BUILD||!!process.env.BUILD_BUILDID||!!process.env.AGENT_ID||!!process.env.BUILDER_SA_EMAIL||!!process.env.HEROKU_TEST_RUN_ID||!!process.env.CI_NODE_INDEX||!!process.env.TEAMCITY_VERSION||!!process.env.BUILD_VCS_NUMBER||!!process.env.BUILDKITE||!!process.env.BUILDKITE_BUILD_NUMBER||!!process.env.APPVEYOR||!!process.env.APPVEYOR_BUILD_NUMBER||!!process.env.DRONE||!!process.env.DRONE_BUILD_NUMBER||!!process.env.SHIPPABLE||!!process.env.BUILD_URL||!!process.env.SEMAPHORE||!!process.env.SEMAPHORE_EXECUTABLE_UUID||!!process.env.WOODPECKER||!!process.env.CI_BUILD_NUMBER||!!process.env.WERCKER_MAIN_PIPELINE_STARTED||!!process.env.BUDDY_EXECUTION_ID;import{existsSync as mv,statSync as pv}from"fs";import{z as bm}from"zod";var gN=bm.object({input:bm.string()});import{z as Ze}from"zod";var SN=Ze.object({srcs:Ze.array(Ze.string()),urls:Ze.array(Ze.string()),desiredSrc:Ze.string().optional(),desiredUrl:Ze.string().optional()}),Tm=Ze.object({srcRegex:Ze.string().optional(),urlRegex:Ze.string().optional()}),wm=Ze.object({x:Ze.number(),y:Ze.number(),correlation:Ze.number()}),yN=Ze.object({searchImageBase64String:Ze.string(),pageImageBase64String:Ze.string(),id:Ze.string().uuid(),timeoutMs:Ze.number().max(1e4).min(0).optional()});import{z as F}from"zod";import*as B from"zod";import{extendZodWithOpenApi as ow}from"zod-openapi";ow(B);var tr=(s=>(s.AI="AI",s.AI_HEALED="AI_HEALED",s.CLICK_TO_FIND="CLICK_TO_FIND",s.XY_PERCENT="XY_PERCENT",s.RECORDING="RECORDING",s.USER_CSS_SELECTOR="USER_CSS_SELECTOR",s.HEURISTIC_HEALED="HEURISTIC_HEALED",s))(tr||{}),aw=B.object({mPathSelectorTokens:B.string().array(),frameSrcRegex:B.string().optional(),frameUrlRegex:B.string().optional(),indices:B.number().array()}),sc=B.object({result:B.number(),traceId:B.string()}).array(),Eo=B.object({type:B.literal("GCS_TRACES"),traces:sc}),nr=B.object({id:B.number().int(),dataMomenticId:B.number().int().optional(),selector:B.string().optional(),hybridSelector:B.object({textContent:B.string().nullish(),attributes:B.record(B.string(),B.string()),tagName:B.string(),expandShadowRoot:B.boolean().optional(),classNames:B.string().array(),nthChild:B.number()}).array().optional(),generatedSelectors:B.string().array().optional(),role:B.string().optional(),name:B.string().optional(),numChildren:B.number().optional(),content:B.string().optional(),pathFromRoot:B.string().optional(),serializedHtml:B.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:B.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:B.string().url().optional(),boundingBox:B.object({x:B.number().optional(),y:B.number().optional(),width:B.number(),height:B.number()}).describe("css pixel bounding box").optional(),frameCache:aw.optional(),inputDescription:B.string().optional().describe("the description that generated this cache"),targetSource:B.nativeEnum(tr).optional(),targetUpdateTime:B.string().optional(),targetUpdateLoggerTags:B.record(B.string(),B.string()).optional(),cacheResolutionUpdateSource:B.string().optional(),cacheResolutionUpdateTime:B.string().optional(),cacheResolutionUpdateLoggerTags:B.record(B.string(),B.string()).optional(),memory:Eo.optional()}).openapi({ref:"ElementTargetCache"});function Em(t){return!!(t.serializedHtml||t.screenshotUrl||t.generatedSelectors||t.hybridSelector)}var iw=B.object({type:B.literal("description"),elementDescriptor:B.string().describe("Description of the element.")}).openapi({ref:"DescriptionTarget"}),sw=B.object({x:B.number(),y:B.number()}),lw=B.object({type:B.literal("coordinates"),pixels:sw}).openapi({ref:"CoordinatesTarget"});function rr(t){return t.type==="description"}function bn(t){return t.type==="coordinates"}var gt=B.discriminatedUnion("type",[iw,lw]).openapi({ref:"ElementTarget"});function lc(t){if(!t)return!1;switch(t.type){case"description":return!!t.elementDescriptor}return!0}function ht(t){if(!t)return"";switch(t.type){case"description":return t.elementDescriptor;case"coordinates":return`x: ${t.pixels.x}, y: ${t.pixels.y}`}}function ki(t){return Eo.safeParse(t).success}import{v4 as he}from"uuid";import*as E from"zod";import{extendZodWithOpenApi as fw}from"zod-openapi";import{z as Z}from"zod";import{extendZodWithOpenApi as cw}from"zod-openapi";import{z as Ro}from"zod";var cc=Ro.object({result:Ro.boolean(),traceId:Ro.string()}).array(),dc=Ro.object({type:Ro.literal("GCS_TRACES"),traces:cc}),uc=Ro.object({memory:dc.optional()});cw(Z);var Rm=Z.object({plan:Z.string().optional(),evidence:Z.string().optional(),thoughts:Z.string(),result:Z.boolean(),relevantElements:Z.array(Z.number()).optional(),updatedMemory:cc.optional()}),or=(o=>(o.CONTAINS="CONTAINS",o.STARTS_WITH="STARTS_WITH",o.EQUALS="EQUALS",o.EXISTS="EXISTS",o))(or||{});var dw=Z.object({type:Z.literal("ELEMENT_NAME"),negated:Z.boolean().optional(),operation:Z.nativeEnum(or),value:Z.string()}).openapi({ref:"ElementNameAssertion"}),uw=Z.object({type:Z.literal("ELEMENT_STYLE"),negated:Z.boolean().optional(),operation:Z.nativeEnum(or),property:Z.string(),value:Z.string()}).openapi({ref:"ElementStyleAssertion"}),mw=Z.object({type:Z.literal("ELEMENT_CONTENT"),negated:Z.boolean().optional(),operation:Z.nativeEnum(or),value:Z.string()}).openapi({ref:"ElementContentAssertion"}),pw=Z.object({type:Z.literal("ELEMENT_ATTRIBUTE"),negated:Z.boolean().optional(),operation:Z.nativeEnum(or),attr:Z.string(),value:Z.string()}).openapi({ref:"ElementAttributeValueAssertion"}),Co=(a=>(a.EXISTS="EXISTS",a.VISIBLE="VISIBLE",a.ENABLED="ENABLED",a.EDITABLE="EDITABLE",a.FOCUSED="FOCUSED",a))(Co||{}),gw=Z.object({type:Z.literal("ELEMENT_EXISTENCE"),negated:Z.boolean().optional(),condition:Z.nativeEnum(Co).describe("Treated as the element exists AND is also ...")}).openapi({ref:"ElementExistenceAssertion"}),Cm=Z.discriminatedUnion("type",[mw,pw,gw,dw,uw]).openapi({ref:"ManualElementAssertion"});var hw=Z.object({type:Z.literal("CONTENT"),negated:Z.boolean().optional(),value:Z.string()}).openapi({ref:"PageContentAssertion"}),vm=Z.discriminatedUnion("type",[hw]).openapi({ref:"ManualPageAssertion"});import Rt from"zod";var mc=Rt.discriminatedUnion("type",[Rt.object({type:Rt.literal("SUBSTRING"),url:Rt.string()}),Rt.object({type:Rt.literal("GLOB"),glob:Rt.string()}),Rt.object({type:Rt.literal("REGEX"),regex:Rt.string()}),Rt.object({type:Rt.literal("DOMAIN"),domain:Rt.string()})]),Ra=Rt.object({urlMatcher:mc,method:Rt.string().optional()});import{z as ge}from"zod";var _i=ge.object({url:ge.string(),method:ge.union([ge.literal("GET"),ge.literal("POST"),ge.literal("PUT"),ge.literal("DELETE"),ge.literal("PATCH")]),headers:ge.record(ge.string(),ge.string()).optional(),params:ge.record(ge.string(),ge.string()).optional(),body:ge.string().optional(),timeout:ge.number().int().optional().describe("Max seconds to wait for the request to complete")}),Am=ge.object({url:ge.string(),headers:ge.record(ge.string(),ge.string()).optional(),query:ge.string(),variables:ge.string().optional(),timeout:ge.number().int().optional().describe("Max seconds to wait for the request to complete")}),Di=ge.object({code:ge.string(),fragment:ge.boolean().optional(),environment:ge.union([ge.literal("NODE"),ge.literal("BROWSER")]).optional().describe("default NODE"),timeout:ge.number().int().max(60).optional().describe("Max seconds for the code to complete")});var je=($=>($.AI_EXTRACT="AI_EXTRACT",$.AI_ASSERTION="AI_ASSERTION",$.AUTH_LOAD="AUTH_LOAD",$.AUTH_SAVE="AUTH_SAVE",$.BLUR="BLUR",$.CAPTCHA="CAPTCHA",$.CLICK="CLICK",$.COOKIE="COOKIE",$.COPY="COPY",$.DIALOG="DIALOG",$.DRAG="DRAG",$.ELEMENT_CHECK="ELEMENT_CHECK",$.FILE_UPLOAD="FILE_UPLOAD",$.FOCUS="FOCUS",$.GO_BACK="GO_BACK",$.GO_FORWARD="GO_FORWARD",$.HOVER="HOVER",$.JAVASCRIPT="JAVASCRIPT",$.LOCAL_STORAGE="LOCAL_STORAGE",$.MOUSE_DRAG="MOUSE_DRAG",$.NAVIGATE="NAVIGATE",$.NEW_TAB="NEW_TAB",$.PAGE_CHECK="PAGE_CHECK",$.PASTE="PASTE",$.PRESS="PRESS",$.KEY_DOWN="KEY_DOWN",$.KEY_UP="KEY_UP",$.REFRESH="REFRESH",$.REQUEST="REQUEST",$.GRAPHQL_REQUEST="GRAPHQL_REQUEST",$.SCROLL_DOWN="SCROLL_DOWN",$.SCROLL_UP="SCROLL_UP",$.SCROLL_LEFT="SCROLL_LEFT",$.SCROLL_RIGHT="SCROLL_RIGHT",$.SELECT_OPTION="SELECT_OPTION",$.SWITCH_TAB="TAB",$.TYPE="TYPE",$.VISUAL_DIFF="VISUAL_DIFF",$.WAIT="WAIT",$.WAIT_FOR_URL="WAIT_FOR_URL",$.REGISTER_REQUEST_LISTENER="REGISTER_REQUEST_LISTENER",$.AWAIT_LISTENER="AWAIT_LISTENER",$.RECORD_REQUESTS="RECORD_REQUESTS",$.GET_RECORDED_REQUESTS="GET_RECORDED_REQUESTS",$.SET_HEADER="SET_HEADER",$.MOCK_ROUTE="MOCK_ROUTE",$.REMOVE_ROUTE_MOCK="REMOVE_ROUTE_MOCK",$.OFFLINE_MODE="OFFLINE_MODE",$.SUCCESS="SUCCESS",$))(je||{});fw(E);var V=E.object({thoughts:E.string().optional(),id:E.string().uuid().describe("unique identifier to this step, used for step cache")}),Vt=E.object({useSelector:E.boolean().optional(),force:E.boolean().optional(),disableCache:E.boolean().optional().describe("disable element caching for this step"),iframeUrl:E.string().optional().describe("url or url regex for the iframe")}).openapi({ref:"CommonTargetingOptions"}),zt=E.object({target:nr}).optional().openapi({ref:"SingleTargetCache"});function xm(t){return zt.safeParse(t).success}var Ui=E.object({loadTimeout:E.number().int().max(60).optional().describe("Max seconds for the page to load")}),gc=V.merge(Ui).merge(E.object({type:E.literal("NAVIGATE"),url:E.string()})).openapi({ref:"NavigateCommand"}),Bi=Vt.merge(E.object({cache:zt})),ar=V.merge(Bi.merge(E.object({target:gt.optional(),type:E.literal("SCROLL_UP"),deltaY:E.number().optional()}))).openapi({ref:"ScrollUpCommand"}),ir=V.merge(Bi.merge(E.object({target:gt.optional(),type:E.literal("SCROLL_DOWN"),deltaY:E.number().optional()}))).openapi({ref:"ScrollDownCommand"}),vo=V.merge(Bi.merge(E.object({target:gt.optional(),type:E.literal("SCROLL_LEFT"),deltaX:E.number().optional()}))).openapi({ref:"ScrollLeftCommand"}),Ao=V.merge(Bi.merge(E.object({target:gt.optional(),type:E.literal("SCROLL_RIGHT"),deltaX:E.number().optional()}))).openapi({ref:"ScrollRightCommand"}),jN=E.discriminatedUnion("type",[ar,ir,vo,Ao]).openapi({ref:"AllScrollCommands"}),Sw=V.merge(E.object({type:E.literal("DIALOG"),action:E.union([E.literal("ACCEPT"),E.literal("DISMISS")])})).openapi({ref:"DialogCommand"}),yw=V.merge(E.object({type:E.literal("WAIT"),delay:E.number()})).openapi({ref:"WaitCommand"}),bw=E.object({caseInsensitive:E.boolean().optional().describe("Whether to ignore case when matching the URL"),negated:E.boolean().optional().describe("Wait for the URL to NOT match the provided matcher instead."),timeout:E.number().int().optional().describe("Max seconds to wait for the URL to match")}),hc=V.extend({type:E.literal("WAIT_FOR_URL"),matcher:mc}).merge(bw).openapi({ref:"WaitUrlCommand"}),Tw=V.merge(Ui).merge(E.object({type:E.literal("REFRESH")})).openapi({ref:"RefreshCommand"}),ww=V.merge(E.object({type:E.literal("GO_BACK")})).openapi({ref:"GoBackCommand"}),Ew=V.merge(E.object({type:E.literal("GO_FORWARD")})).openapi({ref:"GoForwardCommand"}),Rw=V.extend({type:E.literal("AUTH_SAVE")}).openapi({ref:"AuthSaveCommand"}),Cw=V.extend({type:E.literal("AUTH_LOAD"),storageState:E.string().describe("JSON string auth state. Leave blank or set to the empty string to clear all existing authentication.")}).openapi({ref:"AuthLoadCommand"}),fc=V.merge(Vt).extend({type:E.literal("CAPTCHA")}).openapi({ref:"CaptchaCommand"}),vw=V.extend({type:E.literal("COPY"),value:E.string()}).openapi({ref:"CopyCommand"}),Aw=V.extend({type:E.literal("PASTE")}).openapi({ref:"PasteCommand"}),xw=V.merge(Di).extend({type:E.literal("JAVASCRIPT")}).openapi({ref:"JavaScriptCommand"}),Or=V.merge(Vt).extend({type:E.literal("CLICK"),target:gt,doubleClick:E.boolean().optional(),rightClick:E.boolean().optional(),waitForDownload:E.boolean().optional().describe("Wait for the click to trigger a file download and for the file download to complete."),delayMs:E.number().optional(),downloadTimeoutMs:E.number().optional(),cache:zt,relativePosition:E.object({x:E.number(),y:E.number()}).optional()}).openapi({ref:"ClickCommand"}),Sc=E.object({fromTarget:nr.optional(),toTarget:nr.optional()}),Ca=V.merge(Vt).merge(E.object({type:E.literal("DRAG"),fromTarget:gt,toTarget:gt,steps:E.number().optional(),hoverSeconds:E.number().optional().describe("Seconds to hover the object before dropping"),cache:Sc.optional()})).openapi({ref:"DragCommand"}),va=V.merge(Vt).merge(E.object({type:E.literal("MOUSE_DRAG"),target:gt.optional(),deltaX:E.string().describe("pixels to move horizontally, can be template"),deltaY:E.string().describe("pixels to move vertically, can be template"),steps:E.number().optional(),cache:zt})).openapi({ref:"MouseDragCommand"}),Nr=V.merge(Vt).merge(E.object({type:E.literal("HOVER"),target:gt,cache:zt})).openapi({ref:"HoverCommand"}),Aa=V.merge(Vt).merge(E.object({type:E.literal("FOCUS"),target:gt,cache:zt})).openapi({ref:"FocusCommand"}),xa=V.merge(Vt).extend({type:E.literal("BLUR"),target:gt.optional(),cache:zt}).openapi({ref:"BlurCommand"}),Iw=E.object({type:E.literal("URL"),url:E.string()}).describe("Accessible link to the file, either public http or local file://").openapi({ref:"UrlSource"}),Pw=E.object({type:E.literal("USER_FILE"),name:E.string()}).describe("Accessible link to the file, references the google cloud file").openapi({ref:"UploadedFileSource"}),Mw=V.extend({type:E.literal("FILE_UPLOAD"),fileSource:E.discriminatedUnion("type",[Iw,Pw]),filename:E.string().optional()}).openapi({ref:"FileUploadCommand"}),Lw=E.discriminatedUnion("type",[E.object({type:E.literal("VALUE"),value:E.string()}),E.object({type:E.literal("LABEL"),label:E.string()}),E.object({type:E.literal("INDEX"),index:E.coerce.string()})]),kr=V.merge(Vt).extend({type:E.literal("SELECT_OPTION"),target:gt,cache:zt,choice:Lw.describe("new field for selecting options, optional for backcompat")}).openapi({ref:"SelectOptionCommand"}),yc=E.union([E.literal("MULTIMODAL"),E.literal("VISION_ONLY")]),xo=V.merge(E.object({type:E.literal("AI_ASSERTION"),assertion:E.string(),disableCache:E.boolean().optional(),iframeUrl:E.string().optional(),contextChoice:yc.optional(),timeout:E.number().int().optional().describe("Max seconds to wait for assertion to be true"),cache:uc.optional()})).openapi({ref:"AIAssertionCommand"}),Tn=5,bc=600,_r=V.merge(Vt).extend({type:E.literal("ELEMENT_CHECK"),target:gt,assertion:Cm,cache:zt.or(uc).optional(),timeout:E.number().int().min(0).max(bc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"ElementAssertionCommand"}),Tc=V.extend({type:E.literal("PAGE_CHECK"),assertion:vm,iframeUrl:E.string().optional().describe("url or url regex for the iframe"),timeout:E.number().int().min(0).max(bc).optional().describe("max seconds to wait for the assertion to be true")}).openapi({ref:"PageAssertionCommand"}),Ow=V.merge(E.object({type:E.literal("AI_EXTRACT"),goal:E.string(),schema:E.string().optional(),envKey:E.string().optional(),disableCache:E.boolean().optional(),iframeUrl:E.string().optional()})).openapi({ref:"AIExtractCommand"}),Nw=E.object({clearContent:E.boolean().optional(),forceClearContent:E.boolean().optional(),delay:E.number().min(0).max(1e3).optional().describe("Delay between each press in milliseconds."),force:E.boolean().optional(),pressEnter:E.boolean().optional()}),Im=25,Dr=V.merge(Vt).merge(Nw).extend({type:E.literal("TYPE"),target:gt.optional(),value:E.string(),cache:zt}).openapi({ref:"TypeCommand"}),wc=V.merge(E.object({type:E.literal("PRESS"),value:E.string(),repeat:E.number().optional(),convertMeta:E.boolean().optional(),delayMs:E.number().optional()})).openapi({ref:"PressCommand"}),kw=V.merge(E.object({type:E.literal("KEY_DOWN"),value:E.string(),convertMeta:E.boolean().optional()})).openapi({ref:"KeyDownCommand"}),_w=V.merge(E.object({type:E.literal("KEY_UP"),value:E.string(),convertMeta:E.boolean().optional()})).openapi({ref:"KeyUpCommand"}),Dw=E.object({type:E.literal("SUBSTRING"),substring:E.string()}),Fw=E.object({type:E.literal("REGEX"),pattern:E.string()}),Uw=E.object({type:E.literal("INDEX"),index:E.coerce.string()}),Bw=E.discriminatedUnion("type",[Dw,Fw,Uw]),zw=V.merge(Ui).merge(E.object({type:E.literal("TAB"),action:Bw})).openapi({ref:"TabCommand"}),Ec=V.merge(Ui).merge(E.object({type:E.literal("NEW_TAB"),url:E.string()})).openapi({ref:"NewTabCommand"}),Hw=V.merge(E.object({type:E.literal("COOKIE"),value:E.string()})).openapi({ref:"CookieCommand"}),$w=V.merge(E.object({type:E.literal("LOCAL_STORAGE"),key:E.string(),value:E.string()})).openapi({ref:"LocalStorageCommand"}),jw=V.extend({type:E.literal("REQUEST")}).merge(_i).openapi({ref:"RequestCommand"}),Gw=V.extend({type:E.literal("GRAPHQL_REQUEST")}).merge(Am).openapi({ref:"GraphQLRequestCommand"}),Ww=V.merge(E.object({type:E.literal("SUCCESS"),condition:xo.optional()})).openapi({ref:"SuccessCommand"}),Vw=V.merge(E.object({type:E.literal("FAILURE")})).openapi({ref:"FailureCommand"}),qw=E.object({data:E.string().describe("location at which to find a jpg"),width:E.number(),height:E.number()}),Ia=V.merge(Vt).merge(E.object({type:E.literal("VISUAL_DIFF"),threshold:E.number().optional().describe("default 0.1"),target:gt.optional(),screenshot:qw.optional(),cache:zt})).openapi({ref:"VisualDiffCommand"}),Kw=V.merge(E.object({type:E.literal("REGISTER_REQUEST_LISTENER"),requestMatcher:Ra,key:E.string()})).openapi({ref:"RegisterRequestListenerCommand"}),Yw=V.merge(E.object({type:E.literal("AWAIT_LISTENER"),key:E.string(),timeout:E.number().optional().describe("timeout")})).openapi({ref:"WaitForListenerCommand"}),Xw=V.merge(E.object({type:E.literal("RECORD_REQUESTS"),requestMatcher:Ra,key:E.string()})).openapi({ref:"RecordRequestsCommand"}),Jw=V.merge(E.object({type:E.literal("GET_RECORDED_REQUESTS"),key:E.string()})).openapi({ref:"GetRecordedRequestsCommand"}),Qw=V.merge(E.object({type:E.literal("SET_HEADER"),name:E.string(),value:E.string(),requestMatcher:Ra.optional()})).openapi({ref:"SetHeaderCommand"}),Zw=V.merge(E.object({type:E.literal("MOCK_ROUTE"),requestMatcher:Ra,responseGenerator:E.string().describe("JavaScript code to generate a response"),fetchOriginalResponse:E.boolean().optional().describe("Whether to fetch the real response and pass it to the response generator. If enabled, the original response will be available as `response` in the code."),key:E.string().optional().describe("Key to reference this mock. This only needs to be set if you plan to remove the mock later in the test.")}).openapi({ref:"MockRouteCommandOptions"})),eE=V.merge(E.object({type:E.literal("REMOVE_ROUTE_MOCK"),key:E.string().optional().describe("Key of the mock to remove. If not set, all route mocks will be removed.")}).openapi({ref:"RemoveRouteMockCommandOptions"})),tE=V.merge(E.object({type:E.literal("OFFLINE_MODE"),enable:E.boolean()})).openapi({ref:"OfflineModeCommand"}),Pm=E.discriminatedUnion("type",[Or,Dr,wc,kw,_w,kr,gc,ir,ar,xo,Nr,yw,Ww]),nE=E.discriminatedUnion("type",[Ow,Cw,Rw,fc,Hw,vw,Sw,Ca,_r,Mw,ww,Ew,xw,$w,va,Ec,Tc,Aw,Tw,jw,Gw,vo,Ao,zw,Ia,Aa,xa,hc,Kw,Yw,Xw,Jw,Qw,Zw,eE,tE]),Io=E.discriminatedUnion("type",[...Pm.options,...nE.options]).openapi({ref:"Command"}),zi=E.discriminatedUnion("type",[...Pm.options,Vw]);function Un(t){let e;switch(t){case"PASTE":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:he(),type:t};break;case"AUTH_LOAD":{e={id:he(),type:t,storageState:""};break}case"AI_EXTRACT":e={id:he(),type:t,goal:""};break;case"DIALOG":e={id:he(),type:t,action:"DISMISS"};break;case"DRAG":e={id:he(),type:t,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:he(),type:t,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:he(),type:t,matcher:{type:"SUBSTRING",url:""}};break;case"WAIT":e={id:he(),type:t,delay:1};break;case"BLUR":e={id:he(),type:t};break;case"HOVER":case"FOCUS":case"CLICK":e={id:he(),type:t,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"COPY":case"TYPE":e={id:he(),type:t,value:"",clearContent:!0};break;case"KEY_DOWN":case"KEY_UP":e={id:he(),type:t,value:""};break;case"SELECT_OPTION":e={id:he(),type:t,target:{type:"description",elementDescriptor:""},choice:{type:"VALUE",value:""}};break;case"NAVIGATE":case"NEW_TAB":return{id:he(),type:t,url:""};case"TAB":e={id:he(),type:t,action:{type:"SUBSTRING",substring:""}};break;case"REQUEST":e={id:he(),type:t,url:"",method:"GET"};break;case"GRAPHQL_REQUEST":e={id:he(),type:t,url:"",query:""};break;case"LOCAL_STORAGE":e={id:he(),type:t,key:"",value:""};break;case"JAVASCRIPT":e={id:he(),type:t,code:""};break;case"AI_ASSERTION":e={id:he(),type:t,assertion:""};break;case"FILE_UPLOAD":{e={id:he(),type:t,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:he(),type:t,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:he(),type:t,assertion:{type:"CONTENT",value:""}};break}case"REGISTER_REQUEST_LISTENER":{e={id:he(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"AWAIT_LISTENER":{e={id:he(),type:t,key:""};break}case"RECORD_REQUESTS":{e={id:he(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},key:""};break}case"GET_RECORDED_REQUESTS":{e={id:he(),type:t,key:""};break}case"SET_HEADER":{e={id:he(),type:t,name:"",value:""};break}case"MOCK_ROUTE":{e={id:he(),type:t,requestMatcher:{urlMatcher:{type:"REGEX",regex:""}},responseGenerator:""};break}case"REMOVE_ROUTE_MOCK":{e={id:he(),type:t};break}case"OFFLINE_MODE":{e={id:he(),type:t,enable:!0};break}default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return e}function Mm(t){switch(t.type){case"BLUR":case"CLICK":case"DRAG":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"TYPE":return!0;case"AUTH_LOAD":case"AUTH_SAVE":case"AWAIT_LISTENER":case"SUCCESS":case"AI_ASSERTION":case"AI_EXTRACT":case"CAPTCHA":case"COOKIE":case"COPY":case"DIALOG":case"ELEMENT_CHECK":case"FILE_UPLOAD":case"GET_RECORDED_REQUESTS":case"GO_BACK":case"GO_FORWARD":case"GRAPHQL_REQUEST":case"JAVASCRIPT":case"LOCAL_STORAGE":case"NAVIGATE":case"NEW_TAB":case"PASTE":case"PAGE_CHECK":case"RECORD_REQUESTS":case"REGISTER_REQUEST_LISTENER":case"REFRESH":case"REQUEST":case"SELECT_OPTION":case"SET_HEADER":case"TAB":case"VISUAL_DIFF":case"WAIT":case"WAIT_FOR_URL":case"OFFLINE_MODE":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":return!1;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}import{z as rE}from"zod";var KN=rE.discriminatedUnion("type",[xa,fc,Or,Ca,Aa,Nr,va,ar,ir,vo,Ao,kr,Dr,Ia,_r]);function Lm(t){return["AI_ASSERTION","ELEMENT_CHECK","PAGE_CHECK"].includes(t)}import{z as oE}from"zod";import{z as sr}from"zod";function Pa(t){return sr.object({key:sr.string(),testId:sr.string().optional(),moduleId:sr.string().optional(),organizationId:sr.string(),value:t})}function Ma(t){return Pa(t).extend({uniqueKey:sr.string()})}function Hi(t){return sr.record(sr.string(),Ma(t))}var Ct={type:!0,cache:!0},Bn=oE.discriminatedUnion("type",[xo.pick(Ct),xa.pick(Ct),Or.pick(Ct),Ca.pick(Ct),_r.pick(Ct),Aa.pick(Ct),Nr.pick(Ct),va.pick(Ct),ar.pick(Ct),ir.pick(Ct),vo.pick(Ct),Ao.pick(Ct),kr.pick(Ct),Dr.pick(Ct),Ia.pick(Ct)]),$i=Object.values(je).filter(t=>Bn.options.some(e=>e.shape.type.safeParse(t).success));Io.options.forEach(t=>{if("target"in t.shape&&!$i.includes(t.shape.type.value))throw new Error(`Command ${t.shape.type.value} has a target but no cache`)});function Om(t){return $i.includes(t.type)}var Nm=Pa(Bn),km=Ma(Bn),nk=Hi(Bn);import{z as Rc}from"zod";import{extendZodWithOpenApi as sE}from"zod-openapi";import{z as _m}from"zod";import{extendZodWithOpenApi as aE}from"zod-openapi";import{z as Fr}from"zod";var qt=Fr.object({index:Fr.number().optional().describe("global index within a test (in-order traversal)"),id:Fr.string(),skipped:Fr.boolean().optional(),envKey:Fr.string().optional().describe("key in the environment to save the result of this step to"),aiSuggested:Fr.boolean().optional(),retries:Fr.number().optional()});aE(_m);var iE=qt.extend({type:_m.literal("PRESET_ACTION")}),Ht=iE.extend({command:Io}).openapi({ref:"PresetAction"});sE(Rc);var Ur=qt.extend({type:Rc.literal("AI_ACTION"),text:Rc.string(),steps:Ht.array().optional()}).openapi({ref:"AIAction"});import{z as vt}from"zod";import{z as ji}from"zod";import{extendZodWithOpenApi as lE}from"zod-openapi";lE(ji);var Po=qt.extend({type:ji.literal("AI_ACTION_DYNAMIC"),text:ji.string(),retries:ji.number().optional()}).openapi({ref:"AIActionDynamic"});import{z as Dm}from"zod";var Cc=qt.extend({type:Dm.literal("CONDITIONAL"),skipped:Dm.boolean().optional()});import{z as ie}from"zod";var cE=ie.object({cacheKey:ie.string(),cacheExpiryMs:ie.number()}),vc=qt.extend({id:ie.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:ie.record(ie.string()).optional(),cacheConfig:cE.optional()}),sn=vc.extend({type:ie.literal("MODULE"),moduleId:ie.string().uuid()}),dE=ie.union([sn.pick({type:!0,moduleId:!0}),ie.record(ie.unknown())]),uE=ie.object({type:ie.literal("URL_REGEX"),regex:ie.string()}),mE=ie.object({type:ie.literal("PAGE_CHECK"),substring:ie.string()}),Ac=ie.object({cacheInvalidation:ie.discriminatedUnion("type",[mE,uE]).optional()}),Ot=ie.object({moduleId:ie.string().uuid(),name:ie.string(),description:ie.string().nullish(),enabled:ie.boolean().nullish(),parameters:ie.string().array().nullish(),defaultParameters:ie.record(ie.string(),ie.string()).nullish(),parameterEnums:ie.record(ie.string(),ie.string().array()).nullish(),defaultCacheKey:ie.string().nullish(),defaultCacheTtl:ie.number().nullish(),defaultCacheAllInvocations:ie.boolean().nullish(),autoAuth:ie.boolean().nullish(),advanced:Ac.nullish()});import{z as Kt}from"zod";var xc=(r=>(r.ALWAYS="ALWAYS",r.ON_FAILURE="ON_FAILURE",r.ON_ACTION_FAILURE="ON_ACTION_FAILURE",r))(xc||{});var pE=Kt.discriminatedUnion("type",[Kt.object({type:Kt.literal("NAVIGATE_URL"),url:Kt.string().url()}),Kt.object({type:Kt.literal("GO_TO_SECTION_START")})]),gE=Kt.object({trigger:Kt.nativeEnum(xc).optional(),attempts:Kt.number().int().optional(),restartBehavior:pE}),La=qt.extend({type:Kt.literal("SECTION"),description:Kt.string().describe("user provided goal of what the section should accomplish"),plan:Kt.string().array().optional(),autohealingConfig:gE.optional()});var Fm=Ot.merge(vc).extend({type:vt.literal("RESOLVED_MODULE"),steps:vt.lazy(()=>Ge.array())}),Oa=Ot.extend({steps:vt.lazy(()=>Ge.array())}),Ic=La.extend({steps:vt.lazy(()=>Me.array())}),hE=La.extend({steps:vt.lazy(()=>Ge.array())}),Br=Cc.extend({blocks:vt.object({assertion:vt.lazy(()=>Ht),steps:vt.lazy(()=>Me.array())}).array(),elseSteps:vt.lazy(()=>Me.array().optional())}),fE=Cc.extend({blocks:vt.object({assertion:vt.lazy(()=>Ht),steps:vt.lazy(()=>Ge.array())}).array(),elseSteps:vt.lazy(()=>Ge.array().optional())}),Me=vt.discriminatedUnion("type",[Ht,Ur,Po,sn,Br,Ic]),Ge=vt.discriminatedUnion("type",[Ht,Ur,Po,Fm,fE,hE]);import{z as Yt}from"zod";var SE=Yt.object({steps:Me.array(),beforeSteps:Me.array().nullish(),afterSteps:Me.array().nullish()}),Mo=Yt.object({steps:Ge.array(),beforeSteps:Ge.array().nullish(),afterSteps:Ge.array().nullish()}),zr=Yt.object({steps:Yt.record(Yt.string(),Yt.unknown()).array(),beforeSteps:Yt.record(Yt.string(),Yt.unknown()).array().nullish(),afterSteps:Yt.record(Yt.string(),Yt.unknown()).array().nullish()});var se="1.0.21";var Um=F.object({phrase:F.string()}),Pc=F.object({thoughts:F.string().optional(),result:F.union([F.literal("NOT_FOUND"),F.string(),F.number(),F.array(F.unknown()),F.record(F.unknown(),F.unknown()),F.unknown()])}),H_=F.object({text:F.string()}),Bm=F.object({thoughts:F.string(),review:F.string().optional(),id:F.number().int(),updatedMemory:sc.optional()});var Gi=(p=>(p.NO_DESCRIPTION_PROVIDED="NO_DESCRIPTION_PROVIDED",p.FEW_WORDS="FEW_WORDS",p.STYLE_TAG="STYLE_TAG",p.TYPE_IN_DESCRIPTION="TYPE_IN_DESCRIPTION",p.HARDCODED_ATTRIBUTE="HARDCODED_ATTRIBUTE",p.NONE="NONE",p.AMBIGUOUS_DESCRIPTION="AMBIGUOUS_DESCRIPTION",p.AMBIGUOUS_ASSERTION="AMBIGUOUS_ASSERTION",p.PREFER_PAGE_CHECK="PREFER_PAGE_CHECK",p.PREFER_ASSERTION="PREFER_ASSERTION",p.HTML_ELEMENTS="HTML_ELEMENTS",p.MULTIPLE_ELEMENTS_DESCRIPTION="MULTIPLE_ELEMENTS_DESCRIPTION",p.NEEDS_DATE_VARIABLE="NEEDS_DATE_VARIABLE",p))(Gi||{});var zm=F.object({thoughts:F.string(),category:F.nativeEnum(Gi)}),yE=F.discriminatedUnion("op",[F.object({op:F.literal("replace"),path:F.string(),value:F.string()}),F.object({op:F.literal("add"),path:F.string(),value:F.string()}),F.object({op:F.literal("remove"),path:F.string()})]),$_=F.object({thoughts:F.string(),patches:yE.array()}),bE=[F.literal("add"),F.literal("replace"),F.literal("remove")],TE=F.object({op:F.union(bE),path:F.string(),value:Ge.optional()}),Hm=F.object({patches:TE.array(),thoughts:F.string()}),Mc=(r=>(r.LEGITIMATE="LEGITIMATE",r.RECOVERABLE="RECOVERABLE",r.INELIGIBLE="INELIGIBLE",r))(Mc||{}),$m=F.object({thoughts:F.string(),scenario:F.nativeEnum(Mc),instructions:F.string().nullish()}),jm=F.object({reasoning:F.string(),scenario:F.string(),patch:F.null().optional()}),j_=F.object({thoughts:F.string(),evaluation:F.number().min(1).max(10)}),G_=F.object({observations:F.string(),reasoning:F.string(),command:zi});var Lc=F.object({summary:F.string(),reasoning:F.string(),evaluation:F.discriminatedUnion("type",[F.object({type:F.literal("DONE")}),F.object({type:F.literal("RIGHT_TRACK")}),F.object({type:F.literal("WRONG_TRACK"),feedback:F.string()}),F.object({type:F.literal("IMPOSSIBLE")})])});import{z as N}from"zod";import*as ee from"zod";var X_=ee.object({thoughts:ee.string().optional().describe("only provided if a description was provided"),target:nr.optional().describe("only provided if a description was provided"),pageState:ee.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:ee.object({label:ee.string(),value:ee.string()}).array().optional().describe("list of options, provided for <select> elements only"),screenshot:ee.object({data:ee.string(),height:ee.number().int(),width:ee.number().int()}).optional().describe("only provided if returnScreenshot is true")}),Wi=ee.union([ee.literal("ELEMENT_CHECK"),ee.literal("NEGATED_CHECK"),ee.literal("NEGATED_ELEMENT_VISIBLE_CHECK"),ee.literal("SELECT_OPTION"),ee.literal("TYPE")]);function Hr(t){if(!("useSelector"in t&&t.useSelector)){if(t.type==="SELECT_OPTION")return"SELECT_OPTION";if(t.type==="TYPE")return"TYPE";if(t.type==="ELEMENT_CHECK"&&t.assertion.type==="ELEMENT_EXISTENCE"&&t.assertion.condition==="EXISTS"&&t.assertion.negated)return"NEGATED_CHECK";if(t.type==="ELEMENT_CHECK"&&t.assertion.type==="ELEMENT_EXISTENCE"&&t.assertion.condition==="VISIBLE"&&t.assertion.negated)return"NEGATED_ELEMENT_VISIBLE_CHECK";if(t.type==="ELEMENT_CHECK")return"ELEMENT_CHECK"}}var Na=(i=>(i.USER_SELECTOR="USER_SELECTOR",i.CSS_SELECTOR="CSS_SELECTOR",i.HYBRID_SELECTOR="HYBRID_SELECTOR",i.HTML_DISTANCE="HTML_DISTANCE",i.TEMPLATE_MATCHING="TEMPLATE_MATCHING",i.AUTO_FRAME="AUTO_FRAME",i))(Na||{}),Lo=ee.object({matched:ee.boolean(),reason:ee.string().optional().describe("Human understandable description"),logs:ee.string().array().optional().describe("Logs for debugging")}),wE=Lo.extend({type:ee.literal("USER_SELECTOR")}),EE=Lo.extend({type:ee.literal("CSS_SELECTOR"),selectors:ee.string().array()}),RE=Lo.extend({type:ee.literal("HYBRID_SELECTOR")}),CE=Lo.extend({type:ee.literal("HTML_DISTANCE"),distance:ee.number().optional(),closestElement:ee.string().optional(),savedElement:ee.string().optional()}),vE=Lo.extend({type:ee.literal("TEMPLATE_MATCHING"),elementImageUrl:ee.string().url()}),AE=Lo.extend({type:ee.literal("AUTO_FRAME"),logs:ee.string().array().optional()}),Gm=ee.discriminatedUnion("type",[wE,EE,RE,CE,vE,AE]);import{z as Fa}from"zod";import{z as BE}from"zod";import*as j from"zod";import{extendZodWithOpenApi as LE}from"zod-openapi";import{cloneDeep as ka}from"lodash-es";import Xm from"truncate-json";import*as Gr from"zod";import{extendZodWithOpenApi as xE}from"zod-openapi";import{z as ft}from"zod";import{z as Fe}from"zod";var Oc=Fe.object({autoFollowNewTabs:Fe.boolean().optional().describe("Deprecated: Auto-follow new tabs that are opened."),showZeroOpacityElements:Fe.union([Fe.boolean(),Fe.literal("inputs-only")]).optional(),ignoreHrefForCaching:Fe.boolean().optional(),disableSecondaryCacheResolution:Fe.boolean().optional(),hybridSelectorMode:Fe.enum(["off","test","prefer"]).optional(),globalLocatorRedirect:Fe.boolean().optional(),visualActions:Fe.boolean().optional(),autoExpandIframes:Fe.boolean().optional(),disableHtmlSnapshots:Fe.boolean().optional()});var Wm=1e4,Vm=6e4,$r=Oc.extend({pageLoadTimeoutMs:Fe.number().optional().refine(t=>t===void 0||t<=Vm&&t>=-1,{message:`Page load timeout must be between 0 and ${Vm/1e3} seconds`}).describe("global page load timeout default for all tests in ms, can still be overridden by individual tests"),smartWaitingTimeoutMs:Fe.number().optional().refine(t=>t===void 0||t<=Wm&&t>=-1,{message:`Smart waiting timeout must be between 0 and ${Wm/1e3} seconds`}),localChromeExtensionPaths:Fe.string().array().optional(),extraHeaders:Fe.record(Fe.string(),Fe.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:Fe.string().optional(),disableGpu:Fe.boolean().optional(),bustCacheOnBoundingBoxChange:Fe.boolean().optional().describe("Bust the cache if no elements are matched that have the same bounding box and location as the original element. This will improve accuracy on sites that use many same components, at the expense of stability and speed."),allowPartialAccessibilityTree:Fe.boolean().optional().describe("Allow fetching the partial accessibility tree if fetching the full tree takes too long."),ignoreHttpsErrors:Fe.boolean().optional().describe("Ignore HTTPS errors, such as self-signed certificates and certificate errors. This can be useful for testing sites that use self-signed certificates or certificate errors.")});var at="BASE_URL",Vi="CURRENT_URL",jr="ENV_NAME",Oo="TEST_NAME",nD={[at]:"https://www.google.com"},qm=ft.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),Km=ft.object({name:ft.string(),variables:ft.record(ft.string().describe("variable name"),ft.string().describe("variable value"))}),Ym=ft.object({name:ft.string(),variables:ft.record(ft.string().describe("variable name"),ft.unknown().describe("variable value")),browser:$r.optional()});var rD=ft.object({name:ft.string(),variables:ft.record(ft.string().describe("variable name"),ft.unknown().describe("variable value"))});xE(Gr);var Nc=Gr.object({env:Gr.record(Gr.unknown())}).openapi({ref:"TestContextSnapshot"}),IE="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",PE=[at,jr,Oo],Jm=[Vi,at,jr,Oo],Xt=class t{env={};varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static dummyContext(e=void 0,n=void 0,r={}){return new t({baseUrl:"about:blank",currentUrl:"about:blank",testName:e,envName:n,variablesFromEnvironment:r})}static fromSnapshot({snapshot:e,environmentVariables:n}){let r=e.env[at]??"about:blank",o=e.env[Vi]??"about:blank",a=e.env[jr],i=e.env[Oo],s={};for(let[c,d]of Object.entries(e.env))Jm.includes(c)||(n??{})[c]===void 0&&(s[c]=d);return new t({baseUrl:r,currentUrl:o,dynamicVariables:s,envName:a,testName:i,variablesFromEnvironment:n??{}})}setEnvVariables(e){let n=ka(e);this.env=Object.assign(this.env,n)}setInputs(e){e&&this.setEnvVariables(e)}setMomenticSystemVariable(e,n){this.varsFromMomenticEnvironment[e]=n}getVariable(e){return this.env[e]}setVariable(e,n){PE.includes(e)||(this.env[e]=n)}getEnvName(){return this.env[jr]}toObjectCopy(){let e={env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return ka(e)}toEditorDisplayCopy(){return this.toObjectCopy()}toRedactedDisplayCopy(){let e=this.toObjectCopy();e.env=Object.fromEntries(Object.entries(e.env).map(([r,o])=>Jm.includes(r)||this.varsFromMomenticEnvironment[r]===void 0?[r,o]:[r,IE]));for(let[r,o]of Object.entries(e.env)){if(!o){e.env[r]=o;continue}let{jsonString:a}=Xm(JSON.stringify(o),1e3);try{e.env[r]=JSON.parse(a)}catch{e.env[r]=void 0}}let{jsonString:n}=Xm(JSON.stringify(e.env),5e3);try{e.env=JSON.parse(n)}catch{e.env={}}return e}setCurrentUrl(e){this.env[Vi]=e}reset(e){this.env={},this.varsFromMomenticEnvironment={},this.setEnvVariables(e.dynamicVariables??{}),this.setCurrentUrl(e.currentUrl),this.varsFromMomenticEnvironment=ka(e.variablesFromEnvironment),this.setMomenticSystemVariable(at,e.baseUrl),e.envName&&this.setMomenticSystemVariable(jr,e.envName),e.testName&&this.setMomenticSystemVariable(Oo,e.testName)}getDynamicVariablesCopy(){return ka(this.env)}getVariablesFromEnvironmentCopy(){return ka(this.varsFromMomenticEnvironment)}};var Ee=(a=>(a.SUCCESS="SUCCESS",a.FAILED="FAILED",a.RUNNING="RUNNING",a.IDLE="IDLE",a.CANCELLED="CANCELLED",a))(Ee||{}),qi=(r=>(r.SUCCESS="SUCCESS",r.FAILED="FAILED",r.CANCELLED="CANCELLED",r))(qi||{});import{z as wn}from"zod";import{extendZodWithOpenApi as ME}from"zod-openapi";ME(wn);var me=(d=>(d.AI_PROVIDER="AIProviderError",d.USER_INFRA="UserInfrastructureError",d.ACTION_FAILURE="ActionFailureError",d.ASSERTION_FAILURE="AssertionFailureError",d.CONFIG_ERROR="UserConfigurationError",d.WEB_AGENT_PLATFORM="InternalWebAgentError",d.UNKNOWN_PLATFORM="InternalPlatformError",d.JOB_TIMEOUT="JobTimeoutError",d.CONCURRENCY_ERROR="ConcurrencyError",d.UNKNOWN="UnknownError",d))(me||{});var Qm=["JobTimeoutError","UserConfigurationError","UserInfrastructureError"],Ki={ActionFailureError:"Action failure",AssertionFailureError:"Assertion failure",UserInfrastructureError:"Infrastructure failure",UserConfigurationError:"Configuration error",AIProviderError:"AI provider error",InternalWebAgentError:"Momentic AI agent error",JobTimeoutError:"Job timeout",InternalPlatformError:"Unknown Momentic platform error",UnknownError:"Unknown error",ConcurrencyError:"Concurrency error"},No={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 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).",AIProviderError:"The AI provider failed to return a response or returned a malformed response.",UserInfrastructureError:"The user's web application exhibited an infrastructure failure, such as a page load timeout, a 5XX status code, maintenance page, or session crash.",UserConfigurationError:"The error message suggests a user-caused misconfiguration in the test, such as an undefined variable, a missing base URL, an empty test/module input parameter, or an invalid step option",JobTimeoutError:"The test took too long to complete, suggesting a problem with the test itself.",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.",ConcurrencyError:"The AI test executed correctly, but the application state did not match expectations because another process modified the same resource concurrently. This failure is due to a concurrency error, such as a race condition or deadlock. Commonly caused by tests running simultaneously when using constants rather than random values, or underlying operations that allow for race conditions. For example, in Notion, if multiple tests are running at the same time where one creates a page and enters text to check if it renders, but another test deletes all pages before it can validate the render, this would be a concurrency error.",UnknownError:"An unknown error occurred. Please refer to the failure details in the run for more information or reach out to Momentic Support for assistance.",InternalPlatformError:"An unknown error occurred with the Momentic platform."},kc=wn.object({reason:wn.nativeEnum(me),previousStepsDescription:wn.array(wn.string()).optional(),summary:wn.string(),rootCause:wn.string().optional()}).openapi({ref:"TestResultClassification"}),Yi=wn.object({errorMessage:wn.string(),errorStack:wn.string().optional(),classification:kc.optional()}).openapi({ref:"TestFailureDetails"});LE(j);var _c=j.object({beforeUrl:j.string().optional(),afterUrl:j.string().optional(),message:j.string().optional(),beforeSnapshot:j.string().optional(),afterSnapshot:j.string().optional(),startedAt:j.coerce.date(),finishedAt:j.coerce.date()}),OE=_c.extend({viewport:j.object({height:j.number(),width:j.number()}).nullish(),status:j.nativeEnum(qi),message:j.string().optional(),elementInteracted:j.string().optional()}),Wr=_c.extend({status:j.nativeEnum(Ee),message:j.string().optional(),data:j.unknown().optional(),beforeTestContext:Nc.optional(),afterTestContext:Nc.optional(),failureReason:j.nativeEnum(me).optional(),details:j.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"}),Dc=(n=>(n.NOT_ELIGIBLE="NOT_ELIGIBLE",n.ATTEMPTED="ATTEMPTED",n))(Dc||{}),Xi=Wr.merge(Ht).extend({results:OE.array().describe("Command that was executed. Array is just for consistency with other result types. There should only ever be one item."),previousAttempts:j.lazy(()=>et.array()).optional(),failureRecoveryStatus:j.object({type:j.nativeEnum(Dc),message:j.string()}).optional()}),NE=Wr.merge(Ur).extend({results:j.lazy(()=>Xi.array()),previousAttempts:j.lazy(()=>et.array()).optional()}),kE=Wr.merge(Po).extend({results:j.lazy(()=>Xi.array()),previousAttempts:j.lazy(()=>et.array()).optional()}),_E=Wr.merge(sn).extend({moduleName:j.string().optional(),results:j.lazy(()=>et.array()),previousAttempts:j.lazy(()=>et.array()).optional()}),DE=Wr.merge(Br).extend({assertion:Xi.optional(),results:j.lazy(()=>et.array()).describe("results for the block actually executed"),previousAttempts:j.lazy(()=>et.array()).optional()}),FE=Wr.merge(La).extend({results:j.lazy(()=>et.array()),healingAttempts:j.lazy(()=>et.array().array()).optional(),previousAttempts:j.lazy(()=>et.array()).optional()}),et=j.discriminatedUnion("type",[NE,kE,Xi,_E,DE,FE]),Ji=Wr.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),UE=_c.extend({index:j.number().optional(),description:j.string(),pageState:j.string().optional(),elementInteracted:j.string().optional(),startedAt:j.coerce.date().or(j.string()).optional().catch(void 0),finishedAt:j.coerce.date().or(j.string()).optional().catch(void 0)}),Qi=UE.extend({beforeScreenshot:j.string().optional(),afterScreenshot:j.string().optional()});var Fc=BE.object({results:et.array().describe("main results"),beforeResults:et.array().optional(),afterResults:et.array().optional()}),_a=Fc.partial();import{z as U}from"zod";import{extendZodWithOpenApi as WE}from"zod-openapi";var ko=(n=>(n.WEB="WEB",n.ANDROID="ANDROID",n))(ko||{});import{isValidCron as zE}from"cron-validator";import{z as re}from"zod";import{z as Uc}from"zod";var zn=(r=>(r.CHROMIUM="Chromium",r.GOOGLE_CHROME="Google Chrome",r.CHROME_FOR_TESTING="Chrome for Testing",r))(zn||{});var Zi=Uc.object({width:Uc.number().min(200).max(1e4),height:Uc.number().min(200).max(1e4)}),Zm={"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}},LD=Object.keys(Zm);var Nt=Zm["Desktop Large"],_o="en-us",Do="America/Los_Angeles";var Fo={latitude:37.7749,longitude:-122.4194};var ep=["Africa/Abidjan","Africa/Accra","Africa/Algiers","Africa/Bissau","Africa/Cairo","Africa/Casablanca","Africa/Ceuta","Africa/El_Aaiun","Africa/Johannesburg","Africa/Juba","Africa/Khartoum","Africa/Lagos","Africa/Maputo","Africa/Monrovia","Africa/Nairobi","Africa/Ndjamena","Africa/Sao_Tome","Africa/Tripoli","Africa/Tunis","Africa/Windhoek","America/Adak","America/Anchorage","America/Argentina/Buenos_Aires","America/Argentina/Catamarca","America/Argentina/Cordoba","America/Argentina/Jujuy","America/Argentina/La_Rioja","America/Argentina/Mendoza","America/Argentina/Rio_Gallegos","America/Argentina/Salta","America/Argentina/San_Juan","America/Argentina/San_Luis","America/Argentina/Tucuman","America/Argentina/Ushuaia","America/Araguaina","America/Asuncion","America/Atikokan","America/Bahia","America/Bahia_Banderas","America/Barbados","America/Belem","America/Belize","America/Blanc-Sablon","America/Boa_Vista","America/Bogota","America/Boise","America/Cambridge_Bay","America/Campo_Grande","America/Cancun","America/Caracas","America/Cayenne","America/Chicago","America/Chihuahua","America/Costa_Rica","America/Creston","America/Cuiaba","America/Curacao","America/Danmarkshavn","America/Dawson","America/Dawson_Creek","America/Denver","America/Detroit","America/Dominica","America/Edmonton","America/Eirunepe","America/El_Salvador","America/Fort_Nelson","America/Fortaleza","America/Glace_Bay","America/Goose_Bay","America/Grand_Turk","America/Grenada","America/Guadeloupe","America/Guatemala","America/Guayaquil","America/Guyana","America/Halifax","America/Havana","America/Hermosillo","America/Indiana/Indianapolis","America/Indiana/Knox","America/Indiana/Marengo","America/Indiana/Petersburg","America/Indiana/Tell_City","America/Indiana/Vevay","America/Indiana/Vincennes","America/Indiana/Winamac","America/Inuvik","America/Iqaluit","America/Jamaica","America/Juneau","America/Kentucky/Louisville","America/Kentucky/Monticello","America/La_Paz","America/Lima","America/Los_Angeles","America/Maceio","America/Managua","America/Manaus","America/Marigot","America/Martinique","America/Matamoros","America/Mazatlan","America/Menominee","America/Merida","America/Metlakatla","America/Mexico_City","America/Miquelon","America/Moncton","America/Monterrey","America/Montevideo","America/Montserrat","America/Nassau","America/New_York","America/Nipigon","America/Nome","America/Noronha","America/North_Dakota/Beulah","America/North_Dakota/Center","America/North_Dakota/New_Salem","America/Ojinaga","America/Panama","America/Pangnirtung","America/Paramaribo","America/Phoenix","America/Port-au-Prince","America/Port_of_Spain","America/Porto_Velho","America/Puerto_Rico","America/Punta_Arenas","America/Rainy_River","America/Rankin_Inlet","America/Recife","America/Regina","America/Resolute","America/Rio_Branco","America/Santarem","America/Santiago","America/Santo_Domingo","America/Sao_Paulo","America/Scoresbysund","America/Sitka","America/St_Barthelemy","America/St_Johns","America/St_Kitts","America/St_Lucia","America/St_Thomas","America/St_Vincent","America/Swift_Current","America/Tegucigalpa","America/Thule","America/Thunder_Bay","America/Tijuana","America/Toronto","America/Tortola","America/Vancouver","America/Whitehorse","America/Winnipeg","America/Yakutat","America/Yellowknife","Antarctica/Casey","Antarctica/Davis","Antarctica/DumontDUrville","Antarctica/Macquarie","Antarctica/Mawson","Antarctica/Palmer","Antarctica/Rothera","Antarctica/Syowa","Antarctica/Troll","Antarctica/Vostok","Arctic/Longyearbyen","Asia/Aden","Asia/Almaty","Asia/Amman","Asia/Anadyr","Asia/Aqtau","Asia/Aqtobe","Asia/Ashgabat","Asia/Atyrau","Asia/Baghdad","Asia/Bahrain","Asia/Baku","Asia/Bangkok","Asia/Barnaul","Asia/Beirut","Asia/Bishkek","Asia/Brunei","Asia/Chita","Asia/Choibalsan","Asia/Colombo","Asia/Damascus","Asia/Dhaka","Asia/Dili","Asia/Dubai","Asia/Dushanbe","Asia/Famagusta","Asia/Gaza","Asia/Hebron","Asia/Ho_Chi_Minh","Asia/Hong_Kong","Asia/Hovd","Asia/Irkutsk","Asia/Jakarta","Asia/Jayapura","Asia/Jerusalem","Asia/Kabul","Asia/Kamchatka","Asia/Karachi","Asia/Kathmandu","Asia/Khandyga","Asia/Kolkata","Asia/Krasnoyarsk","Asia/Kuala_Lumpur","Asia/Kuching","Asia/Kuwait","Asia/Macau","Asia/Magadan","Asia/Makassar","Asia/Manila","Asia/Muscat","Asia/Nicosia","Asia/Novokuznetsk","Asia/Novosibirsk","Asia/Omsk","Asia/Oral","Asia/Phnom_Penh","Asia/Pontianak","Asia/Pyongyang","Asia/Qatar","Asia/Qostanay","Asia/Qyzylorda","Asia/Riyadh","Asia/Sakhalin","Asia/Samarkand","Asia/Seoul","Asia/Shanghai","Asia/Singapore","Asia/Srednekolymsk","Asia/Taipei","Asia/Tashkent","Asia/Tbilisi","Asia/Tehran","Asia/Thimphu","Asia/Tokyo","Asia/Tomsk","Asia/Ulaanbaatar","Asia/Urumqi","Asia/Ust-Nera","Asia/Vientiane","Asia/Vladivostok","Asia/Yakutsk","Asia/Yangon","Asia/Yekaterinburg","Asia/Yerevan","Atlantic/Azores","Atlantic/Bermuda","Atlantic/Canary","Atlantic/Cape_Verde","Atlantic/Faroe","Atlantic/Madeira","Atlantic/Reykjavik","Atlantic/South_Georgia","Atlantic/Stanley","Australia/Adelaide","Australia/Brisbane","Australia/Broken_Hill","Australia/Currie","Australia/Darwin","Australia/Eucla","Australia/Hobart","Australia/Lindeman","Australia/Lord_Howe","Australia/Melbourne","Australia/Perth","Australia/Sydney","Europe/Amsterdam","Europe/Andorra","Europe/Astrakhan","Europe/Athens","Europe/Belgrade","Europe/Berlin","Europe/Bratislava","Europe/Brussels","Europe/Bucharest","Europe/Budapest","Europe/Busingen","Europe/Chisinau","Europe/Copenhagen","Europe/Dublin","Europe/Gibraltar","Europe/Guernsey","Europe/Helsinki","Europe/Isle_of_Man","Europe/Istanbul","Europe/Jersey","Europe/Kaliningrad","Europe/Kiev","Europe/Kirov","Europe/Lisbon","Europe/Ljubljana","Europe/London","Europe/Luxembourg","Europe/Madrid","Europe/Malta","Europe/Mariehamn","Europe/Minsk","Europe/Monaco","Europe/Moscow","Europe/Oslo","Europe/Paris","Europe/Podgorica","Europe/Prague","Europe/Riga","Europe/Rome","Europe/Samara","Europe/San_Marino","Europe/Sarajevo","Europe/Saratov","Europe/Simferopol","Europe/Skopje","Europe/Sofia","Europe/Stockholm","Europe/Tallinn","Europe/Tirane","Europe/Ulyanovsk","Europe/Uzhgorod","Europe/Vaduz","Europe/Vatican","Europe/Vienna","Europe/Vilnius","Europe/Volgograd","Europe/Warsaw","Europe/Zagreb","Europe/Zaporozhye","Europe/Zurich","Indian/Antananarivo","Indian/Chagos","Indian/Christmas","Indian/Cocos","Indian/Comoro","Indian/Kerguelen","Indian/Mahe","Indian/Maldives","Indian/Mauritius","Indian/Mayotte","Indian/Reunion","Pacific/Apia","Pacific/Auckland","Pacific/Bougainville","Pacific/Chatham","Pacific/Chuuk","Pacific/Easter","Pacific/Efate","Pacific/Enderbury","Pacific/Fakaofo","Pacific/Fiji","Pacific/Funafuti","Pacific/Galapagos","Pacific/Gambier","Pacific/Guadalcanal","Pacific/Guam","Pacific/Honolulu","Pacific/Kiritimati","Pacific/Kosrae","Pacific/Kwajalein","Pacific/Majuro","Pacific/Marquesas","Pacific/Midway","Pacific/Nauru","Pacific/Niue","Pacific/Norfolk","Pacific/Noumea","Pacific/Pago_Pago","Pacific/Palau","Pacific/Pitcairn","Pacific/Pohnpei","Pacific/Port_Moresby","Pacific/Rarotonga","Pacific/Saipan","Pacific/Tahiti","Pacific/Tarawa","Pacific/Tongatapu","Pacific/Wake","Pacific/Wallis"];var tp=2e3,es=$r.extend({browserType:re.nativeEnum(zn).optional(),slowMoMs:re.number().optional().refine(t=>t===void 0||t<=tp&&t>=-1,{message:`Slow motion must be between 0 and ${tp} milliseconds`}),basicAuthorization:re.object({username:re.string().optional(),password:re.string().optional()}).optional(),geolocation:re.object({latitude:re.coerce.number().refine(t=>t>=-90&&t<=90,{message:"Latitude must be between -90 and 90 degrees"}),longitude:re.coerce.number().refine(t=>t>=-180&&t<=180,{message:"Longitude must be between -180 and 180 degrees"})}).optional(),disableJavaScript:re.boolean().optional(),locale:re.string().optional(),timezone:re.enum(ep).optional(),colorScheme:re.enum(["light","dark"]).optional()}),np=["extraHeaders","basicAuthorization","localChromeExtensionPaths"],Bc=re.object({useMemory:re.boolean().optional(),failureRecovery:re.boolean().optional().describe("undefined means inherit org settings")}),HE=Bc.extend({disableAICaching:re.boolean().optional(),failureRecoveryInstructions:re.string().optional()}),$E=re.object({viewport:Zi.optional()}),Vr=$E.merge(HE).merge(es),Uo=re.object({cron:re.string().refine(t=>zE(t),{message:"Invalid cron expression."}).default("0 0 */1 * *"),enabled:re.boolean().default(!1),env:re.string().optional(),timeZone:re.string().default("America/Los_Angeles"),jobKey:re.string().optional()}),Bo=re.object({onSuccess:re.boolean().default(!1),failureMessage:re.string().optional(),onFailure:re.boolean().default(!0),successMessage:re.string().optional()}),jE=re.object({name:re.string(),required:re.boolean().optional(),defaultValue:re.string().describe("this is not optional because we need a value when the editor is first loaded")}),ts=jE.array(),GE=re.object({name:re.string(),value:re.string()}),rp=GE.array(),ns=re.object({name:re.string(),default:re.boolean().optional(),fixtures:qm.array().optional()});WE(U);var Jt={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},le=(s=>(s.PENDING="PENDING",s.RUNNING="RUNNING",s.PASSED="PASSED",s.FAILED="FAILED",s.CANCELLED="CANCELLED",s.RETRYING="RETRYING",s.WAITING_FOR_USER="WAITING_FOR_USER",s))(le||{}),rs=(n=>(n.BEFORE_ALL="BEFORE_ALL",n.AFTER_ALL="AFTER_ALL",n))(rs||{});var Ye=U.string().pipe(U.coerce.date()).or(U.date()),Da=U.object({id:U.string(),runKey:U.string(),organizationId:U.string(),executionType:U.nativeEnum(ko).optional().default("WEB"),createdAt:Ye,createdBy:U.string(),flake:U.boolean().nullish(),scheduledAt:Ye.or(U.null()),startedAt:Ye.or(U.null()),updatedAt:Ye.nullish(),finishedAt:Ye.or(U.null()),resolvedBaseUrl:U.string().nullish(),environmentName:U.string().nullish(),gitBranchName:U.string().nullish(),githubRepository:U.string().nullish(),gitlabProjectPath:U.string().nullish(),labels:U.array(U.string()).optional(),gitOriginUrl:U.string().nullish(),gitCommitSha:U.string().nullish(),gitCommitShaShort:U.string().nullish(),gitCommitAuthorName:U.string().nullish(),cliVersion:U.string().nullish(),section:U.nativeEnum(rs).nullish(),status:U.nativeEnum(le),trigger:U.nativeEnum(Jt),attempts:U.number(),runAttempts:U.array(U.object({id:U.string(),status:U.nativeEnum(le),startedAt:Ye.or(U.null()),finishedAt:Ye.or(U.null())})).optional(),videos:U.array(U.string()).optional(),failureReason:U.nativeEnum(me).nullish(),failureDetails:Yi.nullish(),failureRecoveryDetails:U.record(U.string(),U.unknown()).nullish(),pipelineId:U.string().nullish(),resolvedInputs:U.record(U.string(),U.string()).nullish(),quarantined:U.boolean().nullish().default(!1),quarantinedReason:U.string().nullish(),localTestId:U.string().nullish(),testId:U.string().nullish(),testName:U.string().nullish(),description:U.string().nullish(),test:U.object({name:U.string(),id:U.string()}).nullish().default(null),suiteId:U.string().nullish()}).openapi({ref:"RunMetadata"}),VE={id:!0,status:!0,testName:!0,localTestId:!0,testId:!0,test:{select:{name:!0,id:!0}},finishedAt:!0,failureReason:!0,failureDetails:!0},os=Da.pick({...VE,test:!0}),op=Da.omit({failureReason:!0,failureDetails:!0,test:!0}),zc=Da.extend({stepsSnapshot:U.array(U.record(U.unknown())).nullish(),resolvedInputs:U.record(U.string(),U.string()).nullish(),test:U.object({name:U.string(),id:U.string(),description:U.string().nullish(),baseUrl:U.string().nullish(),advanced:Vr.nullish()}).nullish()}).merge(Fc),ap=t=>t.includes("PASSED")&&t.includes("FAILED");var qE=Fa.object({id:Fa.string().uuid(),startedAt:Ye.or(Fa.null()),finishedAt:Ye.or(Fa.null()),status:Fa.nativeEnum(le)}).merge(_a),ZD=qE.array();var as=(o=>(o.JUNIT="junit",o.ALLURE="allure",o.ALLURE_JSON="allure-json",o.PLAYWRIGHT_JSON="playwright-json",o))(as||{});import{z as Xe}from"zod";var KE=Xe.object({id:Xe.string(),status:Xe.nativeEnum(le),trigger:Xe.nativeEnum(Jt),createdAt:Ye,startedAt:Ye.nullish(),finishedAt:Ye.nullish(),gitCommitSha:Xe.string().nullish(),gitCommitShaShort:Xe.string().nullish(),gitCommitTimestamp:Ye.nullish(),gitBranchName:Xe.string().nullish(),gitOriginUrl:Xe.string().nullish(),gitCommitMessage:Xe.string().nullish(),gitCommitAuthorName:Xe.string().nullish(),githubRepository:Xe.string().nullish(),gitlabProjectPath:Xe.string().nullish(),pipelineId:Xe.string().nullish(),cliVersion:Xe.string().nullish(),labels:Xe.string().array().optional(),suite:Xe.object({id:Xe.string(),name:Xe.string()}).nullish(),runs:Xe.object({status:Xe.nativeEnum(le)}).array()}).openapi({ref:"RunGroup"}),ip=KE.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}).extend({runs:os.array()});import{z as it}from"zod";var YE=it.object({type:it.literal("TARGETING"),name:it.string().optional().describe("Target name to disambiguate for steps with multiple targets"),elementLocationDecisions:Gm.array(),pageState:it.string().optional(),targetSource:it.nativeEnum(tr).optional(),targetUpdateTime:it.string().optional()}),XE=it.object({type:it.literal("AI_LOCATION"),matched:it.boolean(),pageState:it.string().optional(),ragUsed:it.boolean().optional(),thoughts:it.string().optional()}),JE=it.object({type:it.literal("ASSERTION"),relevantElementsSerialized:it.string().array().optional(),pageState:it.string().optional(),ragUsed:it.boolean().optional()}),sp=it.discriminatedUnion("type",[YE,XE,JE]);function is(){return{details:[]}}import{z as Ve}from"zod";var QE=Ve.object({id:Ve.string(),name:Ve.string()}),pF=QE.merge(Ve.object({createdAt:Ye,createdBy:Ve.string(),schedule:Uo,notification:Bo,environment:Ve.object({name:Ve.string()}).nullish(),beforeTests:Ve.object({id:Ve.string()}).array().nullish(),afterTests:Ve.object({id:Ve.string()}).array().nullish()})),lp=Ve.object({id:Ve.string().uuid(),orgId:Ve.string(),createdAt:Ye,startedAt:Ye.or(Ve.null()),finishedAt:Ye.or(Ve.null()),status:Ve.nativeEnum(le),trigger:Ve.nativeEnum(Jt),suite:Ve.object({id:Ve.string(),name:Ve.string()}).nullish(),runs:Da.array()}),gF=lp.pick({id:!0,createdAt:!0,startedAt:!0,finishedAt:!0,status:!0,trigger:!0,suite:!0}),cp=lp.extend({runs:os.array()});import{z as Qt}from"zod";import{cloneDeep as SF}from"lodash-es";import{z as fe}from"zod";var RF=fe.object({thoughts:fe.string(),subGoals:fe.object({instruction:fe.string()}).array()}),CF=fe.object({thoughts:fe.string(),newPlanMarkdown:fe.string()}),vF=fe.object({thoughts:fe.string(),correct:fe.boolean(),failedActionIndex:fe.number().optional()}),ZE=fe.object({type:fe.literal("PLANNING"),beforePlan:fe.string(),goalDecision:fe.string(),thoughts:fe.string()}),eR=fe.object({type:fe.literal("RUNNING"),stepDisplayName:fe.string(),status:fe.nativeEnum(Ee),results:et.array()}),tR=fe.object({type:fe.literal("REVISING"),beforePlan:fe.string(),afterPlan:fe.string(),errString:fe.string(),diffs:fe.string(),thoughts:fe.string()}),nR=fe.object({type:fe.literal("SYSTEM"),message:fe.string()}),rR=fe.discriminatedUnion("type",[ZE,eR,tR,nR]),dp=rR.array();var MF=Qt.object({id:Qt.string(),scheduledAt:Qt.coerce.date().nullable(),startedAt:Qt.coerce.date().nullable(),finishedAt:Qt.coerce.date().nullable(),status:Qt.nativeEnum(le),history:dp.nullable(),testPlan:Qt.object({id:Qt.string(),name:Qt.string()}).nullable(),test:Qt.object({id:Qt.string(),name:Qt.string()}).nullable()});import{z as At}from"zod";var Hc=At.object({content:At.string(),ids:At.string().array(),tokenLength:At.number()}),oR=At.object({chunks:Hc.array()}),qF=At.object({ids:At.string().array(),score:At.number(),tokenLength:At.number()}),KF=oR.extend({description:At.string().describe("Input to pass to RAG engine"),tokenLimit:At.number()}),up=At.object({ids:At.number().array()}),mp=At.object({indices:At.number().array()});var kt=N.object({disableCache:N.boolean().optional(),useMemory:N.boolean().optional(),loggerTags:N.record(N.string(),N.string()).optional(),langfuseSessionId:N.string().optional(),agentConfigVersion:N.string().optional()}),n0=kt.extend({chunks:Hc.array(),description:N.string().describe("Input to pass to AI"),type:N.union([N.literal("locator"),N.literal("assertion"),N.literal("ai-action")]),softTokenLimit:N.number(),hardTokenLimit:N.number()}),aR=N.object({screenshotBase64AfterCommand:N.string(),urlAfterCommand:N.string(),serializedCommand:N.string(),elementInteracted:N.string().optional(),thoughts:N.string().optional()}),pp=N.object({goal:N.string(),browserState:N.string(),screenshot:N.string(),source:Wi.optional().catch(void 0),memory:N.discriminatedUnion("type",[Eo,N.object({type:N.literal("RESOLVED_TRACES"),traces:N.unknown().array()})]).optional()}),gp=N.object({target:N.string().or(N.number()),browserState:N.string().optional(),screenshot:N.string().optional(),boundingBox:N.object({x:N.number(),y:N.number(),height:N.number(),width:N.number()}).optional()}),hp=N.object({goal:N.string(),browserState:N.string(),screenshot:N.string().optional(),returnSchema:N.string().optional()}),iR=N.literal("NEGATED_CHECK"),fp=N.object({goal:N.string(),browserState:N.string(),screenshot:N.string(),url:N.string(),contextChoice:yc.optional(),memory:N.discriminatedUnion("type",[dc,N.object({type:N.literal("RESOLVED_TRACES"),traces:N.unknown().array()})]).optional(),source:iR.optional()}),Sp=N.object({command:Io}),$c=N.object({goal:N.string(),browserState:N.string(),startingScreenshot:N.string().optional(),screenshot:N.string(),url:N.string(),history:aR.array(),actionHint:N.string().optional(),lastError:N.string().optional()}),yp=N.object({results:Qi.array(),errorMessage:N.string(),errorStack:N.string().optional()}),bp=N.object({results:Qi.array(),goal:N.string(),errorMessage:N.string()}),Tp=N.object({failedResults:Qi.array(),nextStepsSerialized:N.string().array(),currentUrl:N.string(),currentPageState:N.string(),currentScreenshot:N.string(),customInstructions:N.string().optional(),testDescription:N.string().optional()}),r0=N.object({description:N.string(),type:N.union([N.literal("locator"),N.literal("assertion"),N.literal("ai-action")]),excerpt:N.string()});import{z as Ua}from"zod";var i0=Ua.object({goal:Ua.string()}),wp=Ua.object({keywords:Ua.array(Ua.string())});import{z as jc}from"zod";var ss=(o=>(o.LOCATOR="locator",o.ASSERTION="assertion",o.VISUAL_ASSERTION="visual-assertion",o.TEXT_EXTRACTION="text-extraction",o))(ss||{}),c0=jc.nativeEnum(ss),sR=jc.enum(["v1","v2"]),d0=sR.or(jc.string().describe("for people with special configurations"));import{z as Ue}from"zod";var Ep=Ue.object({attributesRequired:Ue.array(Ue.string()).optional(),textRequired:Ue.boolean().optional(),boundsRequired:Ue.boolean().optional()}),lR=Ue.object({id:Ue.number(),thoughts:Ue.string(),requirements:Ep.optional(),additionalElements:Ue.object({id:Ue.number(),requirements:Ep}).array().optional()}),Rp=Ue.object({description:Ue.string(),screenXml:Ue.string(),screenshot:Ue.string()}),Cp=Ue.object({assertion:Ue.string(),screenXml:Ue.string(),screenshot:Ue.string()}),cR=Ue.object({thoughts:Ue.string(),result:Ue.boolean(),relevantElements:Ue.array(Ue.number()).optional()});var vp=t=>!(!t.org_id||!t.user_id||!t.platform);import{z as qr}from"zod";var Ap=qr.object({id:qr.string().uuid(),skipped:qr.boolean().optional(),envKey:qr.string().optional().describe("key in the environment to save the result of this step to")}),Gc=Ap.merge(_i).extend({type:qr.literal("REQUEST")}),Wc=Ap.merge(Di).extend({type:qr.literal("JAVASCRIPT")}),Vc=qr.discriminatedUnion("type",[Wc,Gc]);import{z as Zt}from"zod";import{z as Kr}from"zod";var dR=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/,ve=t=>{let e=t.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 ls=Kr.string().min(1).max(255).superRefine((t,e)=>{try{Yr(t)}catch(n){return e.addIssue({code:Kr.ZodIssueCode.custom,message:n.message,fatal:!0}),Kr.NEVER}});function Yr(t){if(t=t.toLowerCase().trim(),t.length===0||t.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"/\\|?*]/.test(t))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(t.endsWith("-")||t.startsWith("-"))throw new Error("Name cannot start or end with a dash.");if(t.includes("\0"))throw new Error("Name cannot contain null characters");if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(t))throw new Error(`"${t}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(t)||/^\s|\s$/.test(t))throw new Error("Name cannot start or end with a space or dot.");if(t.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(t==="none")throw new Error("Name cannot be 'none'.");if(t.match(dR))throw new Error("Name cannot be a UUID. Please choose a different name.")}var cs=Kr.preprocess(t=>t===null?"":t,Kr.union([Kr.string().url(),Kr.literal("")])).optional();var xp=Zt.object({id:Zt.string(),name:ls,description:Zt.string().optional().nullish(),baseUrl:cs.nullish(),schemaVersion:Zt.string(),advanced:Zt.unknown().optional(),retries:Zt.number(),envs:Zt.array(ns).nullish(),parameters:ts.nullish()}),uR=Zt.object({createdAt:Zt.coerce.date(),updatedAt:Zt.coerce.date(),schedule:Uo.nullish(),notification:Bo.nullish(),createdBy:Zt.string(),organizationId:Zt.string()}),mR=xp.merge(uR),D0=mR.extend({steps:Vc.array()}),F0=xp.extend({steps:Vc.array()});import{z as _t}from"zod";var Ip=_t.object({startedAt:_t.coerce.date(),finishedAt:_t.coerce.date(),status:_t.nativeEnum(Ee),message:_t.string().optional(),data:_t.unknown().optional()}),pR=Ip.merge(Wc).extend({type:_t.literal("JAVASCRIPT")}),gR=Ip.merge(Gc).extend({type:_t.literal("REQUEST")}),hR=_t.discriminatedUnion("type",[pR,gR]),Pp=_t.object({startedAt:_t.coerce.date(),finishedAt:_t.coerce.date().nullish(),status:_t.nativeEnum(le),results:hR.array(),failureReason:_t.string().nullish(),failureDetails:Yi.nullish()});import{z as Dt}from"zod";var fR=Dt.object({id:Dt.string(),organizationId:Dt.string(),createdAt:Dt.coerce.date(),updatedAt:Dt.coerce.date(),createdBy:Dt.string(),scheduledAt:Dt.coerce.date().nullish(),startedAt:Dt.coerce.date().nullish(),finishedAt:Dt.coerce.date().nullish(),status:Dt.nativeEnum(le),trigger:Dt.nativeEnum(Jt),results:Pp.array().nullish(),apiTestName:Dt.string().nullish(),apiTestPath:Dt.string().nullish(),apiTestId:Dt.string().nullish()}),q0=fR.pick({status:!0,startedAt:!0,finishedAt:!0});var Ba=(n=>(n.TestRun="test-run",n.CreditsUsed="credits-used",n))(Ba||{}),Mp=3;function SR(t){return t==="MODULE"||t==="CONDITIONAL"||t==="SECTION"||t==="RESOLVED_MODULE"}function qc(t){if(!SR(t))switch(t){case"PRESET_ACTION":return 0;case"AI_ACTION":return 3;case"AI_ACTION_DYNAMIC":return 5;default:(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function Kc(t){switch(t.type){case"AI_EXTRACT":case"AI_ASSERTION":return Mp;case"CAPTCHA":return 3;case"CLICK":case"TYPE":case"SELECT_OPTION":case"HOVER":case"ELEMENT_CHECK":case"FOCUS":case"BLUR":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_UP":case"MOUSE_DRAG":return t.useSelector||!t.target||t.target.type!=="description"?0:1;case"DRAG":return t.useSelector?0:1;case"VISUAL_DIFF":case"TAB":case"JAVASCRIPT":case"NAVIGATE":case"WAIT":case"SUCCESS":case"AUTH_LOAD":case"AUTH_SAVE":case"COOKIE":case"DIALOG":case"FILE_UPLOAD":case"GO_BACK":case"GO_FORWARD":case"LOCAL_STORAGE":case"NEW_TAB":case"PAGE_CHECK":case"PRESS":case"KEY_DOWN":case"KEY_UP":case"COPY":case"PASTE":case"REFRESH":case"REQUEST":case"GRAPHQL_REQUEST":case"WAIT_FOR_URL":case"REGISTER_REQUEST_LISTENER":case"AWAIT_LISTENER":case"RECORD_REQUESTS":case"GET_RECORDED_REQUESTS":case"SET_HEADER":case"MOCK_ROUTE":case"REMOVE_ROUTE_MOCK":case"OFFLINE_MODE":return 0;default:(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}var zo=class{async reportBillableEvent(e,n,r){}async reportCreditsUsed(e,n,r,o){}};function Yc(t,e){return{...t,testId:e?.testId??"",testName:e?.testName??"",suiteId:e?.suiteId??"",suiteName:e?.suiteName??""}}import{parseString as yR,splitCookiesString as bR}from"set-cookie-parser";import{z as Te}from"zod";var Xc=Te.object({name:Te.string(),value:Te.string(),url:Te.string().optional(),domain:Te.string().optional(),path:Te.string().optional(),expires:Te.number().default(Date.now()/1e3+60*60*24*365),httpOnly:Te.boolean().optional(),secure:Te.boolean().default(!0),sameSite:Te.union([Te.literal("Strict"),Te.literal("Lax"),Te.literal("None")]).default("None")});function ds(t,e){let n=[],r=bR(t);for(let o of r){let a=yR(o,{decodeValues:!1});if(!a.name)throw new Error("Name missing from cookie");if(!a.value)continue;let i;if(a.sameSite){let d=a.sameSite.trim().toLowerCase();if(d==="strict")i="Strict";else if(d==="lax")i="Lax";else if(d==="none")i="None";else throw new Error(`Invalid sameSite setting in cookie: ${d}`)}a.httpOnly===void 0&&(a.httpOnly=!1),!a.path&&a.domain&&(a.path="/"),!a.domain&&e&&(a.domain=e);let s=Xc.parse({...a,expires:a.expires?a.expires.getTime()/1e3:void 0,sameSite:i});n.push(s);let l=[s.name,...Object.keys(s)].map(d=>d.toLowerCase()),c=o.match(/\b(\S+)=([^;]*)/g);if(c)for(let d of c){let[u,m]=d.split("=");if(!u||!m)throw new Error(`Invalid key-value pair in cookie: ${d}`);l.includes(u.toLowerCase())||n.push({...s,name:u,value:m})}}return n}var TR=Te.object({origin:Te.string(),localStorage:Te.array(Te.object({name:Te.string(),value:Te.string()}))}),wR=Te.object({entries:Te.record(Te.string(),Te.array(Te.tuple([Te.unknown(),Te.unknown()]))),version:Te.number().optional()}),us=Te.object({cookies:Xc.array().optional(),origins:TR.array().optional(),idb:Te.record(Te.string(),wR).optional().describe("key is db name")});function Lp(t,e){let n=[];return t.cloneSync()?.serializeSync()?.cookies.forEach(r=>{let o=Xc.safeParse({name:r.key,...r});if(!o.success)return;let a=o.data;!a.domain&&!a.url&&(a.domain=e),n.push(a)}),n}import OR from"zod";import{v4 as hU}from"uuid";import{z as Se}from"zod";import*as Le from"zod";var Op=Le.object({requiredText:Le.string().optional(),requiredAttributes:Le.record(Le.string(),Le.string()).optional(),requiredBounds:Le.boolean().optional()}),ER=Le.object({xPath:Le.string(),requirements:Op.optional()}),RR=Le.object({type:Le.literal("NATIVE"),bounds:Le.number().array(),resolvedDescription:Le.string(),xPath:Le.string(),elementOnlySerializedXml:Le.string(),requirements:Op.optional(),requiredRelatedElements:ER.array().optional()}),CR=Le.object({type:Le.literal("WEBVIEW"),resolvedDescription:Le.string(),xPath:Le.string(),browserCache:nr.optional()}),Np=Le.discriminatedUnion("type",[RR,CR]);var Ho=(c=>(c.AI_CHECK="AI_CHECK",c.TAP="TAP",c.TYPE="TYPE",c.PRESS="PRESS",c.OPEN_APP="OPEN_APP",c.OPEN_NOTIFICATION_DRAWER="OPEN_NOTIFICATION_DRAWER",c.JAVASCRIPT="JAVASCRIPT",c.ADB="ADB",c.STATE="STATE",c))(Ho||{}),kp=(l=>(l.BACK="BACK",l.HOME="HOME",l.APP_SWITCHER="APP_SWITCHER",l.POWER="POWER",l.SEARCH="SEARCH",l.VOLUME_UP="VOLUME_UP",l.VOLUME_DOWN="VOLUME_DOWN",l.VOLUME_MUTE="VOLUME_MUTE",l))(kp||{}),_p=Se.discriminatedUnion("type",[Se.object({type:Se.literal("description"),description:Se.string()}),Se.object({type:Se.literal("coordinates"),xPercent:Se.number(),yPercent:Se.number()})]),Hn=Se.object({id:Se.string().uuid(),disableCache:Se.boolean().optional()}),vR=Hn.extend({type:Se.literal("STATE")}),Dp=Se.object({target:Np}),Jc=Hn.extend({type:Se.literal("TAP"),target:_p,cache:Dp.optional()}),Qc=Hn.extend({type:Se.literal("TYPE"),target:_p.optional(),cache:Dp.optional(),text:Se.string()}),AR=Hn.extend({type:Se.literal("OPEN_NOTIFICATION_DRAWER")}),xR=Hn.extend({type:Se.literal("PRESS"),key:Se.nativeEnum(kp)}),IR=Hn.extend({type:Se.literal("OPEN_APP"),packageName:Se.string(),activityName:Se.string().optional()}),PR=Hn.extend({type:Se.literal("AI_CHECK"),assertion:Se.string(),timeoutSecs:Se.number().optional()}),MR=Hn.extend({type:Se.literal("JAVASCRIPT"),code:Se.string(),timeout:Se.number().int().max(60).optional().describe("Max seconds for the code to complete")}),LR=Hn.extend({type:Se.literal("ADB"),command:Se.string()}),Fp=Se.discriminatedUnion("type",[Jc,Qc,xR,IR,AR,PR,MR,LR,vR]);var Up={type:!0,cache:!0},$o=OR.discriminatedUnion("type",[Jc.pick(Up),Qc.pick(Up)]),RU=Object.values(Ho).filter(t=>$o.options.some(e=>e.shape.type.safeParse(t).success));var Bp=Pa($o),zp=Ma($o),CU=Hi($o);import{cloneDeep as xU}from"lodash-es";import PU from"truncate-json";import lr from"zod";import za from"zod";var NR=za.object({id:za.string().uuid(),envKey:za.string().optional()}),$n=NR.extend({type:za.literal("MOBILE_PRESET_STEP"),command:Fp}),kU=za.discriminatedUnion("type",[$n]);import Be from"zod";var jo=Be.object({startTime:Be.number(),endTime:Be.number().optional(),error:Be.string().optional()});var Zc=jo.extend({type:Be.literal("SECTION"),name:Be.string(),subSpans:Be.lazy(()=>BR.array())}),kR=jo.extend({type:Be.literal("AI_LOCATOR_CALL"),result:Be.object({serializedElement:Be.string(),id:Be.number(),thoughts:Be.string()}).optional()}),_R=jo.extend({type:Be.literal("AI_ASSERTION_CALL"),result:Be.object({thoughts:Be.string(),result:Be.boolean()}).optional()}),DR=jo.extend({type:Be.literal("WAIT_FOR_STABILITY"),reason:Be.string().optional()}),FR=jo.extend({type:Be.literal("RESOLVE_TARGET_CACHE"),result:Be.object({serializedElement:Be.string()}).optional()}),UR=jo.extend({type:Be.literal("GET_EMULATOR_STATE")}),BR=Be.discriminatedUnion("type",[Zc,kR,_R,DR,FR,UR]);var zR=lr.object({message:lr.string().optional(),startTime:lr.number(),endTime:lr.number(),status:lr.nativeEnum(Ee),trace:Zc.optional().catch(void 0),beforeSnapshot:lr.string().optional(),afterSnapshot:lr.string().optional()}),HR=$n.merge(zR).extend({data:lr.unknown().optional().describe("output data from the step")}),ms=HR;import tt from"zod";import{z as ln}from"zod";import{z as _e}from"zod";var St=_e.object({id:_e.string(),name:ls,baseUrl:cs,description:_e.string().optional().nullish(),schemaVersion:_e.string(),advanced:Vr,retries:_e.number(),envs:_e.array(ns).nullish(),parameters:ts.nullish(),disabled:_e.boolean().optional(),labels:_e.array(_e.string()).optional().catch([])}),qU=_e.enum(["INHERIT","ENABLED","DISABLED"]);var $R=Vr.extend({failureRecovery:_e.boolean().or(_e.string()).optional().transform(t=>typeof t=="string"?t:t===void 0?"INHERIT":t?"ENABLED":"DISABLED"),useMemory:_e.boolean().or(_e.string()).optional().transform(t=>typeof t=="string"?t:t===void 0?"INHERIT":t?"ENABLED":"DISABLED")});var KU=St.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,parameters:!0}).extend({advanced:$R}),YU=St.pick({name:!0,description:!0,baseUrl:!0,retries:!0,disabled:!0,advanced:!0,parameters:!0}),jR=_e.object({labels:_e.array(_e.string()).optional(),outputs:rp.nullish()}),en=St.merge(jR),GR=_e.object({createdAt:_e.coerce.date(),updatedAt:_e.coerce.date(),updatedBy:_e.string().nullable(),schedule:Uo,notification:Bo,createdBy:_e.string(),organizationId:_e.string(),folderId:_e.string().nullable().optional()}),WR=St.merge(GR),XU=WR.merge(Mo),ps=St.merge(Mo),JU=St.merge(zr);var Hp="test",$p="module",VR="mobile-test",st=(n=>(n.TEST=`${Hp}.yaml`,n.MODULE=`${$p}.yaml`,n))(st||{}),pe=(r=>(r.TEST=`momentic/${Hp}`,r.MODULE=`momentic/${$p}`,r.MOBILE_TEST=`momentic/${VR}`,r))(pe||{}),oB=St.merge(zr),ed=Ot.extend({steps:ln.array(ln.record(ln.string(),ln.unknown())),schemaVersion:ln.string()}),aB=ed.extend({fileType:ln.literal(pe.MODULE)}),iB=ln.object({test:ln.string().describe("YAML for the test, including metadata and steps"),modules:ln.record(ln.string(),ln.string()).describe("Map of module name to YAML for the module")});var qR=tt.object({disableDefaultWebviewAccessibilityTree:tt.boolean().optional(),autoGrantPermissions:tt.boolean().optional()}),KR=qR,Ha=tt.object({retries:tt.number().optional().describe("number of retries to run"),defaultChannel:tt.string().optional().describe("default channel to use"),defaultTag:tt.string().optional().describe("default tag to use, if not set uses latest"),defaultEnv:tt.string().optional(),emulator:KR.optional()}),td=tt.object({id:tt.string().uuid(),description:tt.string(),schemaVersion:tt.string(),settings:Ha}),YR=td.merge(tt.object({steps:tt.array($n)})),jp=tt.object({fileType:tt.literal(pe.MOBILE_TEST)}).merge(YR),uB=tt.object({name:tt.string(),steps:tt.array($n).optional(),settings:Ha.optional()});var IB=new Set(Object.values(je));var XR={AI_ACTION:"AI action",AI_ACTION_DYNAMIC:"AI action",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",KEY_DOWN:"Key down",KEY_UP:"Key up",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:"localStorage",REQUEST:"API request",GRAPHQL_REQUEST:"GraphQL 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",COPY:"Copy",PASTE:"Paste",REGISTER_REQUEST_LISTENER:"Register request listener",AWAIT_LISTENER:"Await listener",RECORD_REQUESTS:"Record requests",GET_RECORDED_REQUESTS:"Get recorded requests",SET_HEADER:"Set header",MOCK_ROUTE:"Mock route",REMOVE_ROUTE_MOCK:"Remove route mock",OFFLINE_MODE:"Offline mode",SUCCESS:"Done"},PB={AI_ACTION:["ai","action","agent"],AI_ACTION_DYNAMIC:["ai","action","dynamic","agent"],RESOLVED_MODULE:[],AI_ASSERTION:["ai","check","assert","make sure","ensure"],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"],KEY_DOWN:["keyboard","type","key","down","press"],KEY_UP:["keyboard","type","key","up","press"],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:[],GRAPHQL_REQUEST:[],CAPTCHA:[],DRAG:[],VISUAL_DIFF:[],DIALOG:[],MOUSE_DRAG:[],AUTH_LOAD:[],AUTH_SAVE:[],ELEMENT_CHECK:[],PAGE_CHECK:[],WAIT_FOR_URL:[],COPY:[],PASTE:[],REGISTER_REQUEST_LISTENER:[],AWAIT_LISTENER:[],RECORD_REQUESTS:[],GET_RECORDED_REQUESTS:[],SET_HEADER:[],MOCK_ROUTE:[],REMOVE_ROUTE_MOCK:[],OFFLINE_MODE:[],SUCCESS:[]},MB={AI_ACTION:"Ask AI achieve a specific goal. Saves the steps for reuse. Please use Dynamic AI action instead.",AI_ACTION_DYNAMIC:"Ask AI achieve a specific goal. Fully dynamic and does not save the steps for reuse. Our most capable AI agent.",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI to verify whether something is true on the page.",CLICK:"Click on an element on the page.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page.",HOVER:"Hover over an element on the page.",FILE_UPLOAD:"Automatically upload a file when the native file upload dialog is activated.",FOCUS:"Focus an element on the page.",BLUR:"Remove focus from an element on the page.",SELECT_OPTION:"Select an option from an HTML Select <select> element.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Control+A)",KEY_DOWN:"Hold down the specified keys on the keyboard. (e.g. Control+A)",KEY_UP:"Release the specified keys on the keyboard. (e.g. Control+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 localStorage 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.",GRAPHQL_REQUEST:"Make a GraphQL request to a URL.",JAVASCRIPT:"Run JavaScript code in the browser or a Node.js environment.",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 or clear session state using a JavaScript object including cookies, localStorage, and IndexDB entries.",AUTH_SAVE:"Save authentication state (cookies, localStorage) into a JavaScript object.",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 contents using pre-built conditions.",WAIT_FOR_URL:"Wait for the active page's URL to match a target value or pattern.",COPY:"Copy the specified value to the browser clipboard.",PASTE:"Paste the browser clipboard contents.",REGISTER_REQUEST_LISTENER:"Register a listener for network requests.",AWAIT_LISTENER:"Wait for a listener to fire, and return the response data.",RECORD_REQUESTS:"Record network requests that match a given pattern.",GET_RECORDED_REQUESTS:"Get recorded requests that matched the pattern.",SET_HEADER:"Set a header.",MOCK_ROUTE:"Mock network requests to a specific URL.",REMOVE_ROUTE_MOCK:"Remove a previously set route mock.",OFFLINE_MODE:"Configure offline mode.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."},LB={AI_CHECK:"AI check",TAP:"Tap",TYPE:"Type",PRESS:"Press",OPEN_APP:"Open app",JAVASCRIPT:"JavaScript",OPEN_NOTIFICATION_DRAWER:"Open notification drawer",ADB:"ADB command",STATE:"Debug state"},OB={AI_CHECK:"Ask AI to verify whether something is true on the screen.",TAP:"Tap on an element on the screen.",TYPE:"Type the specified text into an element.",PRESS:"Press a button on the device or on the screen.",OPEN_APP:"Open an app on the device.",JAVASCRIPT:"Execute JavaScript code in a NodeJS context.",OPEN_NOTIFICATION_DRAWER:"Open the notification drawer.",ADB:"Execute an ADB command on the device.",STATE:"Get the debug state of the device."};import JR from"semver";import{z as QR}from"zod";var DB=QR.string().refine(t=>JR.valid(t),{message:"must be a valid semver string"});import{Faker as BB,en as zB}from"@faker-js/faker";import{z as O}from"zod";var gs=55555,$B=O.object({body:O.string(),to:O.string(),from:O.string()}),jB=O.object({from:O.string().optional(),to:O.string(),timeout:O.number().optional(),beforeDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional()}),GB=O.object({to:O.string().email(),from:O.string(),subject:O.string(),body:O.string(),html:O.string().optional()}),WB=O.object({inbox:O.string().transform(t=>t.toLowerCase()),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),timeout:O.number().optional(),trimWhitespace:O.boolean().optional()}),VB=O.object({inbox:O.string(),limit:O.number().optional(),afterDate:O.string().pipe(O.coerce.date()).or(O.date()).optional(),trimWhitespace:O.boolean().optional()});var hs=(n=>(n.RAW="RAW",n.RESPONSE="RESPONSE",n))(hs||{}),Gp=O.object({body:O.string().nullish(),status:O.number().optional(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}),ZR=O.object({url:O.string(),options:O.object({method:O.string(),body:O.string().nullish(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}).optional()}).optional(),eC=O.object({body:O.string().nullish(),options:O.object({status:O.number(),statusText:O.string().optional(),headers:O.array(O.tuple([O.string(),O.string()])).optional()}).optional()}).optional(),Wp=O.object({result:O.unknown(),variableUpdates:O.record(O.string(),O.unknown()).optional(),persistentVariableUpdates:O.record(O.string(),O.unknown()).optional(),error:O.string().optional(),success:O.boolean()}),qB=O.object({id:O.string().optional(),orgId:O.string(),momenticLambdaAuthHash:O.string(),code:O.string(),fragment:O.boolean(),state:O.object({env:O.record(O.string(),O.unknown()),request:ZR,response:eC,additionalBindings:O.record(O.string(),O.unknown()).optional()}),timeoutMs:O.number().optional(),disallowVariableUpdates:O.boolean().optional(),responseSerialization:O.nativeEnum(hs).optional()}),cr=15e3;import*as yt from"zod";import{extendZodWithOpenApi as tC}from"zod-openapi";tC(yt);var nC=yt.object({url:yt.string(),lineNumber:yt.number(),columnNumber:yt.number()}).openapi({ref:"CodeLocation"}),fs=yt.object({timestamp:yt.number(),text:yt.string(),type:yt.string(),tabIndex:yt.number(),args:yt.unknown().array().optional(),url:yt.string().optional(),location:nC.optional()}).openapi({ref:"ConsoleLog"}),Vp=fs.array(),rC=Vp.array();import*as rd from"zod";import{extendZodWithOpenApi as RC}from"zod-openapi";import{z as I}from"zod";var oC=I.object({name:I.string(),version:I.string(),comment:I.string().optional()}),aC=I.object({name:I.string(),version:I.string(),comment:I.string().optional()}),iC=I.object({onContentLoad:I.number().optional(),onLoad:I.number().optional(),comment:I.string().optional()}),Kp=I.object({startedDateTime:I.string(),id:I.string(),title:I.string().optional(),pageTimings:iC,comment:I.string().optional()}),sC=I.array(Kp),lC=I.object({name:I.string(),value:I.string(),path:I.string().optional(),domain:I.string().optional(),expires:I.string().optional(),httpOnly:I.boolean().optional(),secure:I.boolean().optional(),comment:I.string().optional()}),Yp=I.array(lC),cC=I.object({name:I.string(),value:I.string(),comment:I.string().optional()}),Xp=I.array(cC),dC=I.object({name:I.string(),value:I.string(),comment:I.string().optional()}),uC=I.array(dC),mC=I.object({name:I.string(),value:I.string().optional(),fileName:I.string().optional(),contentType:I.string().optional(),comment:I.string().optional()}),pC=I.array(mC),gC=I.object({mimeType:I.string(),params:pC,text:I.string(),comment:I.string().optional()}),hC=I.object({method:I.string(),url:I.string(),httpVersion:I.string().optional(),cookies:Yp,headers:Xp,queryString:uC,postData:gC.optional(),headersSize:I.number().optional(),bodySize:I.number().optional(),comment:I.string().optional()}),fC=I.object({size:I.number().optional(),compression:I.number().optional(),mimeType:I.string().optional(),text:I.string().optional(),encoding:I.string().optional(),comment:I.string().optional()}),SC=I.object({status:I.number(),statusText:I.string(),httpVersion:I.string().optional(),cookies:Yp,headers:Xp,content:fC,redirectURL:I.string().optional(),headersSize:I.number().optional(),bodySize:I.number().optional(),comment:I.string().optional()}),qp=I.object({expires:I.string().optional(),lastAccess:I.string(),eTag:I.string(),hitCount:I.number(),comment:I.string().optional()}),yC=I.object({beforeRequest:qp.optional(),afterRequest:qp.optional(),comment:I.string().optional()}),bC=I.object({blocked:I.number().optional(),dns:I.number().optional(),connect:I.number().optional(),send:I.number(),wait:I.number(),receive:I.number(),ssl:I.number().optional(),comment:I.string().optional()}),Jp=I.object({pageref:I.string().optional(),startedDateTime:I.string(),time:I.number().optional(),request:hC,response:SC.optional(),cache:yC.optional(),timings:bC,serverIPAddress:I.string().optional(),connection:I.string().optional(),comment:I.string().optional(),_resourceType:I.string().optional()}),TC=I.array(Jp),wC=I.object({version:I.string().default("1.1"),creator:oC.optional(),browser:aC.optional(),pages:sC.optional(),entries:TC,comment:I.string().optional()}),EC=I.object({log:wC}),Qp=I.record(I.string(),Kp),Zp=I.record(I.string(),Jp);function nd(t,e){return{log:{version:"1.2",creator:{name:"Momentic, Inc.",version:"1.0.0"},pages:Object.values(t).sort((n,r)=>new Date(n.startedDateTime).getTime()-new Date(r.startedDateTime).getTime()),entries:Object.values(e).sort((n,r)=>new Date(n.startedDateTime).getTime()-new Date(r.startedDateTime).getTime())}}}RC(rd);var CC=rd.object({logsPerPage:fs.array().array(),harPages:Qp.optional(),harEntries:Zp.optional()}).openapi({ref:"DebugData"});var $a=class{async getConsoleLogsForRunAttempt(e,n,r){}async getNetworkLogsForRunAttempt(e,n,r){}async getHtmlSnapshot(e,n){}async getA11yTreeSnapshot(e,n){}async getScreenshot(e,n){}async storeConsoleLogsForRunAttempt(e,n,r,o){}async storeNetworkLogsForRunAttempt(e,n,r,o){}async storeScreenshot(e,n,r){}async storeHtmlSnapshot(e,n,r){}};var Ss=class extends Error{constructor(e,n,r,o={}){super(`The ${r} with id ${n} is invalid: ${e}`,o),this.name="InvalidEntityError"}};function eg(t){for(let e of Object.values(me))if(t.includes(e))return e}var A=class extends Error{reason;constructor(e,n,r){let o=!1;for(let a of Object.values(me))if(n.startsWith(a)){o=!0,e=a;break}if(r?.errOptions?.cause)super(o?n:`${e}: ${n}`,r?.errOptions);else{let a=o?n:`${e}${n?`: ${n}`:""}`;super(a,r?.errOptions)}this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e}toString(){return this.message}toJSON(){return{message:this.message}}},Go=class extends Error{updatedLocatorMemory;constructor(e,n,r={}){super(e,r),this.updatedLocatorMemory=n,this.name="NoElementsFoundUsingAIError"}},En=class extends Error{decisions;constructor(e,n,r={}){super(e,r),this.decisions=n,this.name="NoElementsFoundUsingCacheError"}toString(){return`${this.message}
5
5
  Decisions:
6
6
  ${this.decisions.map(e=>e.toString()).join(`
7
- `)}`}};function Vp(t){return t instanceof Error?t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("waiting for locator"):!1}function Jc(t){return!(t instanceof Error)||t.message.includes("locator resolved to visible")?!1:!!(t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("body >")||t.message.includes("Element is not attached to the DOM"))}var En=class extends Error{retryableWithAI;constructor(e,n,r={}){super(e,r),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=n}},gs=class extends En{constructor(e,n={}){super(e,!0,n),this.name="BoundingBoxMovedError"}},hs=class extends En{constructor(e,n={}){super(e,!1,n),this.name="ZeroOpacityError"}};function qp(t){return t instanceof Error?t.message.includes("Could not find attribute data-momentic-id for object"):!1}function Hi(t){return t instanceof Error?t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("waiting for locator")&&t.message.includes("data-momentic-id")&&!t.message.includes("locator resolved")&&!t.message.includes("waiting for element to be"):!1}function Qc(t){return t instanceof Error?t.message.includes("Protocol error (DOM.resolveNode): No node with given id found")||t.message.includes("Could not resolve backend node"):!1}var zi=class extends Error{constructor(e,n={}){super(e,n),this.name="InsufficientCacheDataError"}};import{cloneDeep as fR}from"lodash-es";import{z as Cn}from"zod";var cr=(g=>(g.DisableClickhouseCaches="disable_clickhouse_caches",g.DisableClickHouseLastUpdatedEndpoint="disable_clickhouse_last_updated_endpoint",g.IconKnowledgeBase="icon_knowledge_base",g.MiniModelInitialAssertion="mini_model_initial_assertion",g.MiniModelInitialLocator="mini_model_initial_locator",g.ShowTestPlans="show_test_plans",g.ShowZeroOpacityElements="show_zero_opacity_elements",g.VisualActions="visual_actions",g.RagV2="rag_v2",g.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",g.GlobalLocatorRedirect="global_locator_redirect",g.FakerConstantSeed="faker_constant_seed",g.AutoExpandIframes="auto_expand_iframes",g))(cr||{});var Kp=Cn.union([Cn.string(),Cn.number(),Cn.boolean(),Cn.null(),Cn.record(Cn.string(),Cn.lazy(()=>Kp)),Cn.array(Cn.lazy(()=>Kp))]),$i=class{flags;payloads;constructor(e,n){this.flags=e,this.payloads=n}isBooleanFlagEnabled(e){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="true"?!0:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="false"?!1:this.flags[e]===!0}getAllFlags(){let e=fR(this.flags);return Object.entries(e).forEach(([n,r])=>{typeof r=="boolean"&&Object.values(cr).includes(n)&&(e[n]=this.isBooleanFlagEnabled(n))}),e}getFlagPayload(e){let n=this.payloads[e];if(n!==void 0){if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}}refresh(){throw new Error("Not implemented")}},Ez=new $i({},{});var Zc={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},Yp=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],Rz=Object.keys(Zc);import*as Xp from"zod";var Az=Xp.custom().refine(t=>t&&t.length>0).refine(t=>t&&t[0]instanceof File,{message:"Please upload a valid file."});import{z as dr}from"zod";var Pz=dr.object({id:dr.string(),name:dr.string(),createdAt:dr.coerce.date(),createdBy:dr.string(),updatedAt:dr.coerce.date(),updatedBy:dr.string().nullable(),organizationId:dr.string()});import{z as M}from"zod";import ur from"zod";var jo=ur.object({platformSep:ur.string(),fullPathSegments:ur.string().array(),relativePathSegments:ur.string().array(),relativePath:ur.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:ur.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:ur.coerce.date(),createdAt:ur.coerce.date()});var SR=M.array(jo.extend({id:M.string(),name:M.string(),description:M.string().optional(),labels:M.string().array().optional()})),yR=M.array(jo.extend({id:M.string(),name:M.string(),description:M.string().optional(),content:Pi})),$z=M.object({tests:SR,modules:yR,labels:M.string().array()}),jz=ds.merge(Zt),Jp=M.object({schemaVersion:M.string(),stepLists:Io}),Qp=Zt.partial().merge(St.pick({id:!0})),Zp=M.object({name:M.string(),description:M.string().optional(),baseUrl:M.string().url().optional(),environment:M.string().optional(),browserType:M.nativeEnum(Bn).optional(),viewport:Xa.optional(),pathSegments:M.string().array().optional()}),Gz=ds.merge(M.object({relativeFilePath:M.string().describe("relative to project root")})),eg=M.object({name:M.string()}),Wz=M.object({relativeFilePath:M.string()}),tg=M.object({name:M.string()}),Vz=M.object({relativeFilePath:M.string()}),ng=M.object({name:M.string(),description:M.string(),enabled:M.boolean(),steps:M.lazy(()=>$e.array()),testFilePath:M.string().describe("relative to the project root"),folderPath:M.string().optional().describe("user selected folder path")}),rg=M.object({name:M.string(),description:M.string(),enabled:M.boolean()}).partial();var qz=M.array(zm),og=M.object({defaultEnv:M.string().optional().describe("name of the default env, or undefined to unset")}),ig=M.object({configFilePath:M.string().describe("full path on disk")}),Kz=M.string().array(),Yz=M.object({message:M.string(),newRelativeTestPath:M.string().optional()}),ed=M.object({name:M.string(),absolutePath:M.string(),relativePath:M.string(),pathSegments:M.array(M.string()),isDirectory:M.boolean(),size:M.number(),createdAt:M.coerce.date(),modifiedAt:M.coerce.date(),accessedAt:M.coerce.date()}),ag=M.object({pathSegments:M.array(M.string())}),Xz=M.object({absolutePath:M.string(),pathSegments:M.array(M.string()),contents:M.array(ed)}),sg=M.object({pathSegments:M.array(M.string())}),lg=M.object({pathSegments:M.array(M.string()),newPathSegments:M.array(M.string())}),cg=M.object({pathSegments:M.array(M.string()),recursive:M.boolean().optional()}),Jz=M.object({success:M.boolean(),message:M.string(),pathSegments:M.array(M.string()).optional()});var fs=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],Ss=fs.map(t=>`**/${t}/**`);import Rn from"chalk";import bR from"safe-stable-stringify";import TR from"truncate-json";import wR from"zod";var ji=bR.configure({deterministic:!1});function dg(t){let e=ji(t),{jsonString:n}=TR(e,1e4);return n}var ER=["app","version","env","namespace","host"];function Oe(t){let e=t.bindings()??{},n={};for(let r of Object.keys(e)){let o=e[r];!ER.includes(r)&&typeof o=="string"&&(n[r]=o)}return n}var td=wR.enum(["debug","info","warn","error"]);var Gi={debug:20,info:30,warn:40,error:50},bs={20:"debug",30:"info",40:"warn",50:"error"},Wi=class t{minLogLevel;logBindings;constructor(e,n){typeof e=="string"?this.minLogLevel=Gi[e]:this.minLogLevel=e,this.logBindings=n}logWithLevel(e,n,...r){try{this.logWithLevelHelper(e,n,...r)}catch(o){console.error(`Failed to log to console: ${o}`)}}logWithLevelHelper(e,n,...r){if(e<this.minLogLevel)return;let o;Array.isArray(r[0])?(o=r[0],r=r.slice(1)):typeof r[0]=="object"&&!(r[0]instanceof Error)&&Object.entries(r[0]).length&&(o={...r[0],...this.logBindings},r=r.slice(1));let i=[];if(i.push(...r),console.log(n(...i)),o&&!Array.isArray(o)){let a=Object.entries(o);for(let[s,l]of a){let c=l;l instanceof Error?c=l.message:typeof l=="object"&&(c=ji(l,void 0,2),c=c.split(`
7
+ `)}`}};function tg(t){return t instanceof Error?t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("waiting for locator"):!1}function od(t){return!(t instanceof Error)||t.message.includes("locator resolved to visible")?!1:!!(t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("body >")||t.message.includes("Element is not attached to the DOM"))}var Rn=class extends Error{retryableWithAI;constructor(e,n,r={}){super(e,r),this.name="CacheAttributesDisqualifyElementError",this.retryableWithAI=n}},ys=class extends Rn{constructor(e,n={}){super(e,!0,n),this.name="BoundingBoxMovedError"}},bs=class extends Rn{constructor(e,n={}){super(e,!1,n),this.name="ZeroOpacityError"}};function ng(t){return t instanceof Error?t.message.includes("Could not find attribute data-momentic-id for object"):!1}function Ga(t){return t instanceof Error?t.message.includes("Timeout")&&t.message.includes("exceeded")&&t.message.includes("waiting for locator")&&t.message.includes("data-momentic-id")&&!t.message.includes("locator resolved")&&!t.message.includes("waiting for element to be"):!1}function ad(t){return t instanceof Error?t.message.includes("Protocol error (DOM.resolveNode): No node with given id found")||t.message.includes("Could not resolve backend node"):!1}var ja=class extends Error{constructor(e,n={}){super(e,n),this.name="InsufficientCacheDataError"}};import{cloneDeep as vC}from"lodash-es";import{z as Cn}from"zod";var dr=(p=>(p.DisableClickhouseCaches="disable_clickhouse_caches",p.DisableClickHouseLastUpdatedEndpoint="disable_clickhouse_last_updated_endpoint",p.IconKnowledgeBase="icon_knowledge_base",p.MiniModelInitialAssertion="mini_model_initial_assertion",p.MiniModelInitialLocator="mini_model_initial_locator",p.ShowTestPlans="show_test_plans",p.ShowZeroOpacityElements="show_zero_opacity_elements",p.VisualActions="visual_actions",p.RagV2="rag_v2",p.DisableSecondaryCacheResolution="disable_secondary_cache_resolution",p.GlobalLocatorRedirect="global_locator_redirect",p.FakerConstantSeed="faker_constant_seed",p.AutoExpandIframes="auto_expand_iframes",p))(dr||{});var rg=Cn.union([Cn.string(),Cn.number(),Cn.boolean(),Cn.null(),Cn.record(Cn.string(),Cn.lazy(()=>rg)),Cn.array(Cn.lazy(()=>rg))]),Wa=class{flags;payloads;constructor(e,n){this.flags=e,this.payloads=n}isBooleanFlagEnabled(e){return process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="true"?!0:process.env&&process.env[`MOMENTIC_FLAG_OVERRIDE_${e.toUpperCase()}`]==="false"?!1:this.flags[e]===!0}getAllFlags(){let e=vC(this.flags);return Object.entries(e).forEach(([n,r])=>{typeof r=="boolean"&&Object.values(dr).includes(n)&&(e[n]=this.isBooleanFlagEnabled(n))}),e}getFlagPayload(e){let n=this.payloads[e];if(n!==void 0){if(typeof n=="string")try{return JSON.parse(n)}catch{return n}return n}}refresh(){throw new Error("Not implemented")}},Dz=new Wa({},{});var id={".123":"application/vnd.lotus-1-2-3",".3dml":"text/vnd.in3d.3dml",".3g2":"video/3gpp2",".3gp":"video/3gpp",".a":"application/octet-stream",".aab":"application/x-authorware-bin",".aac":"audio/x-aac",".aam":"application/x-authorware-map",".aas":"application/x-authorware-seg",".abw":"application/x-abiword",".acc":"application/vnd.americandynamics.acc",".ace":"application/x-ace-compressed",".acu":"application/vnd.acucobol",".acutc":"application/vnd.acucorp",".adp":"audio/adpcm",".aep":"application/vnd.audiograph",".afm":"application/x-font-type1",".afp":"application/vnd.ibm.modcap",".ai":"application/postscript",".aif":"audio/x-aiff",".aifc":"audio/x-aiff",".aiff":"audio/x-aiff",".air":"application/vnd.adobe.air-application-installer-package+zip",".ami":"application/vnd.amiga.ami",".apk":"application/vnd.android.package-archive",".application":"application/x-ms-application",".apr":"application/vnd.lotus-approach",".asc":"application/pgp-signature",".asf":"video/x-ms-asf",".asm":"text/x-asm",".aso":"application/vnd.accpac.simply.aso",".asx":"video/x-ms-asf",".atc":"application/vnd.acucorp",".atom":"application/atom+xml",".atomcat":"application/atomcat+xml",".atomsvc":"application/atomsvc+xml",".atx":"application/vnd.antix.game-component",".au":"audio/basic",".avi":"video/x-msvideo",".aw":"application/applixware",".azf":"application/vnd.airzip.filesecure.azf",".azs":"application/vnd.airzip.filesecure.azs",".azw":"application/vnd.amazon.ebook",".bat":"application/x-msdownload",".bcpio":"application/x-bcpio",".bdf":"application/x-font-bdf",".bdm":"application/vnd.syncml.dm+wbxml",".bh2":"application/vnd.fujitsu.oasysprs",".bin":"application/octet-stream",".bmi":"application/vnd.bmi",".bmp":"image/bmp",".book":"application/vnd.framemaker",".box":"application/vnd.previewsystems.box",".boz":"application/x-bzip2",".bpk":"application/octet-stream",".btif":"image/prs.btif",".bz":"application/x-bzip",".bz2":"application/x-bzip2",".c":"text/x-c",".c4d":"application/vnd.clonk.c4group",".c4f":"application/vnd.clonk.c4group",".c4g":"application/vnd.clonk.c4group",".c4p":"application/vnd.clonk.c4group",".c4u":"application/vnd.clonk.c4group",".cab":"application/vnd.ms-cab-compressed",".car":"application/vnd.curl.car",".cat":"application/vnd.ms-pki.seccat",".cc":"text/x-c",".cct":"application/x-director",".ccxml":"application/ccxml+xml",".cdbcmsg":"application/vnd.contact.cmsg",".cdf":"application/x-netcdf",".cdkey":"application/vnd.mediastation.cdkey",".cdx":"chemical/x-cdx",".cdxml":"application/vnd.chemdraw+xml",".cdy":"application/vnd.cinderella",".cer":"application/pkix-cert",".cgm":"image/cgm",".chat":"application/x-chat",".chm":"application/vnd.ms-htmlhelp",".chrt":"application/vnd.kde.kchart",".cif":"chemical/x-cif",".cii":"application/vnd.anser-web-certificate-issue-initiation",".cil":"application/vnd.ms-artgalry",".cla":"application/vnd.claymore",".class":"application/java-vm",".clkk":"application/vnd.crick.clicker.keyboard",".clkp":"application/vnd.crick.clicker.palette",".clkt":"application/vnd.crick.clicker.template",".clkw":"application/vnd.crick.clicker.wordbank",".clkx":"application/vnd.crick.clicker",".clp":"application/x-msclip",".cmc":"application/vnd.cosmocaller",".cmdf":"chemical/x-cmdf",".cml":"chemical/x-cml",".cmp":"application/vnd.yellowriver-custom-menu",".cmx":"image/x-cmx",".cod":"application/vnd.rim.cod",".com":"application/x-msdownload",".conf":"text/plain",".cpio":"application/x-cpio",".cpp":"text/x-c",".cpt":"application/mac-compactpro",".crd":"application/x-mscardfile",".crl":"application/pkix-crl",".crt":"application/x-x509-ca-cert",".csh":"application/x-csh",".csml":"chemical/x-csml",".csp":"application/vnd.commonspace",".css":"text/css",".cst":"application/x-director",".csv":"text/csv",".cu":"application/cu-seeme",".curl":"text/vnd.curl",".cww":"application/prs.cww",".cxt":"application/x-director",".cxx":"text/x-c",".daf":"application/vnd.mobius.daf",".dataless":"application/vnd.fdsn.seed",".davmount":"application/davmount+xml",".dcr":"application/x-director",".dcurl":"text/vnd.curl.dcurl",".dd2":"application/vnd.oma.dd2+xml",".ddd":"application/vnd.fujixerox.ddd",".deb":"application/x-debian-package",".def":"text/plain",".deploy":"application/octet-stream",".der":"application/x-x509-ca-cert",".dfac":"application/vnd.dreamfactory",".dic":"text/x-c",".diff":"text/plain",".dir":"application/x-director",".dis":"application/vnd.mobius.dis",".dist":"application/octet-stream",".distz":"application/octet-stream",".djv":"image/vnd.djvu",".djvu":"image/vnd.djvu",".dll":"application/x-msdownload",".dmg":"application/octet-stream",".dms":"application/octet-stream",".dna":"application/vnd.dna",".doc":"application/msword",".docm":"application/vnd.ms-word.document.macroenabled.12",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".dot":"application/msword",".dotm":"application/vnd.ms-word.template.macroenabled.12",".dotx":"application/vnd.openxmlformats-officedocument.wordprocessingml.template",".dp":"application/vnd.osgi.dp",".dpg":"application/vnd.dpgraph",".dsc":"text/prs.lines.tag",".dtb":"application/x-dtbook+xml",".dtd":"application/xml-dtd",".dts":"audio/vnd.dts",".dtshd":"audio/vnd.dts.hd",".dump":"application/octet-stream",".dvi":"application/x-dvi",".dwf":"model/vnd.dwf",".dwg":"image/vnd.dwg",".dxf":"image/vnd.dxf",".dxp":"application/vnd.spotfire.dxp",".dxr":"application/x-director",".ecelp4800":"audio/vnd.nuera.ecelp4800",".ecelp7470":"audio/vnd.nuera.ecelp7470",".ecelp9600":"audio/vnd.nuera.ecelp9600",".ecma":"application/ecmascript",".edm":"application/vnd.novadigm.edm",".edx":"application/vnd.novadigm.edx",".efif":"application/vnd.picsel",".ei6":"application/vnd.pg.osasli",".elc":"application/octet-stream",".eml":"message/rfc822",".emma":"application/emma+xml",".eol":"audio/vnd.digital-winds",".eot":"application/vnd.ms-fontobject",".eps":"application/postscript",".epub":"application/epub+zip",".es3":"application/vnd.eszigno3+xml",".esf":"application/vnd.epson.esf",".et3":"application/vnd.eszigno3+xml",".etx":"text/x-setext",".exe":"application/x-msdownload",".ext":"application/vnd.novadigm.ext",".ez":"application/andrew-inset",".ez2":"application/vnd.ezpix-album",".ez3":"application/vnd.ezpix-package",".f":"text/x-fortran",".f4v":"video/x-f4v",".f77":"text/x-fortran",".f90":"text/x-fortran",".fbs":"image/vnd.fastbidsheet",".fdf":"application/vnd.fdf",".fe_launch":"application/vnd.denovo.fcselayout-link",".fg5":"application/vnd.fujitsu.oasysgp",".fgd":"application/x-director",".fh":"image/x-freehand",".fh4":"image/x-freehand",".fh5":"image/x-freehand",".fh7":"image/x-freehand",".fhc":"image/x-freehand",".fig":"application/x-xfig",".fli":"video/x-fli",".flo":"application/vnd.micrografx.flo",".flv":"video/x-flv",".flw":"application/vnd.kde.kivio",".flx":"text/vnd.fmi.flexstor",".fly":"text/vnd.fly",".fm":"application/vnd.framemaker",".fnc":"application/vnd.frogans.fnc",".for":"text/x-fortran",".fpx":"image/vnd.fpx",".frame":"application/vnd.framemaker",".fsc":"application/vnd.fsc.weblaunch",".fst":"image/vnd.fst",".ftc":"application/vnd.fluxtime.clip",".fti":"application/vnd.anser-web-funds-transfer-initiation",".fvt":"video/vnd.fvt",".fzs":"application/vnd.fuzzysheet",".g3":"image/g3fax",".gac":"application/vnd.groove-account",".gdl":"model/vnd.gdl",".geo":"application/vnd.dynageo",".gex":"application/vnd.geometry-explorer",".ggb":"application/vnd.geogebra.file",".ggt":"application/vnd.geogebra.tool",".ghf":"application/vnd.groove-help",".gif":"image/gif",".gim":"application/vnd.groove-identity-message",".gmx":"application/vnd.gmx",".gnumeric":"application/x-gnumeric",".gph":"application/vnd.flographit",".gqf":"application/vnd.grafeq",".gqs":"application/vnd.grafeq",".gram":"application/srgs",".gre":"application/vnd.geometry-explorer",".grv":"application/vnd.groove-injector",".grxml":"application/srgs+xml",".gsf":"application/x-font-ghostscript",".gtar":"application/x-gtar",".gtm":"application/vnd.groove-tool-message",".gtw":"model/vnd.gtw",".gv":"text/vnd.graphviz",".gz":"application/x-gzip",".h":"text/x-c",".h261":"video/h261",".h263":"video/h263",".h264":"video/h264",".hbci":"application/vnd.hbci",".hdf":"application/x-hdf",".hh":"text/x-c",".hlp":"application/winhlp",".hpgl":"application/vnd.hp-hpgl",".hpid":"application/vnd.hp-hpid",".hps":"application/vnd.hp-hps",".hqx":"application/mac-binhex40",".htke":"application/vnd.kenameaapp",".htm":"text/html",".html":"text/html",".hvd":"application/vnd.yamaha.hv-dic",".hvp":"application/vnd.yamaha.hv-voice",".hvs":"application/vnd.yamaha.hv-script",".icc":"application/vnd.iccprofile",".ice":"x-conference/x-cooltalk",".icm":"application/vnd.iccprofile",".ico":"image/x-icon",".ics":"text/calendar",".ief":"image/ief",".ifb":"text/calendar",".ifm":"application/vnd.shana.informed.formdata",".iges":"model/iges",".igl":"application/vnd.igloader",".igs":"model/iges",".igx":"application/vnd.micrografx.igx",".iif":"application/vnd.shana.informed.interchange",".imp":"application/vnd.accpac.simply.imp",".ims":"application/vnd.ms-ims",".in":"text/plain",".ipk":"application/vnd.shana.informed.package",".irm":"application/vnd.ibm.rights-management",".irp":"application/vnd.irepository.package+xml",".iso":"application/octet-stream",".itp":"application/vnd.shana.informed.formtemplate",".ivp":"application/vnd.immervision-ivp",".ivu":"application/vnd.immervision-ivu",".jad":"text/vnd.sun.j2me.app-descriptor",".jam":"application/vnd.jam",".jar":"application/java-archive",".java":"text/x-java-source",".jisp":"application/vnd.jisp",".jlt":"application/vnd.hp-jlyt",".jnlp":"application/x-java-jnlp-file",".joda":"application/vnd.joost.joda-archive",".jpe":"image/jpeg",".jpeg":"image/jpeg",".jpg":"image/jpeg",".jpgm":"video/jpm",".jpgv":"video/jpeg",".jpm":"video/jpm",".js":"application/javascript",".json":"application/json",".kar":"audio/midi",".karbon":"application/vnd.kde.karbon",".kfo":"application/vnd.kde.kformula",".kia":"application/vnd.kidspiration",".kil":"application/x-killustrator",".kml":"application/vnd.google-earth.kml+xml",".kmz":"application/vnd.google-earth.kmz",".kne":"application/vnd.kinar",".knp":"application/vnd.kinar",".kon":"application/vnd.kde.kontour",".kpr":"application/vnd.kde.kpresenter",".kpt":"application/vnd.kde.kpresenter",".ksh":"text/plain",".ksp":"application/vnd.kde.kspread",".ktr":"application/vnd.kahootz",".ktz":"application/vnd.kahootz",".kwd":"application/vnd.kde.kword",".kwt":"application/vnd.kde.kword",".latex":"application/x-latex",".lbd":"application/vnd.llamagraphics.life-balance.desktop",".lbe":"application/vnd.llamagraphics.life-balance.exchange+xml",".les":"application/vnd.hhe.lesson-player",".lha":"application/octet-stream",".link66":"application/vnd.route66.link66+xml",".list":"text/plain",".list3820":"application/vnd.ibm.modcap",".listafp":"application/vnd.ibm.modcap",".log":"text/plain",".lostxml":"application/lost+xml",".lrf":"application/octet-stream",".lrm":"application/vnd.ms-lrm",".ltf":"application/vnd.frogans.ltf",".lvp":"audio/vnd.lucent.voice",".lwp":"application/vnd.lotus-wordpro",".lzh":"application/octet-stream",".m13":"application/x-msmediaview",".m14":"application/x-msmediaview",".m1v":"video/mpeg",".m2a":"audio/mpeg",".m2v":"video/mpeg",".m3a":"audio/mpeg",".m3u":"audio/x-mpegurl",".m4u":"video/vnd.mpegurl",".m4v":"video/x-m4v",".ma":"application/mathematica",".mag":"application/vnd.ecowin.chart",".maker":"application/vnd.framemaker",".man":"text/troff",".mathml":"application/mathml+xml",".mb":"application/mathematica",".mbk":"application/vnd.mobius.mbk",".mbox":"application/mbox",".mc1":"application/vnd.medcalcdata",".mcd":"application/vnd.mcd",".mcurl":"text/vnd.curl.mcurl",".mdb":"application/x-msaccess",".mdi":"image/vnd.ms-modi",".me":"text/troff",".mesh":"model/mesh",".mfm":"application/vnd.mfmp",".mgz":"application/vnd.proteus.magazine",".mht":"message/rfc822",".mhtml":"message/rfc822",".mid":"audio/midi",".midi":"audio/midi",".mif":"application/vnd.mif",".mime":"message/rfc822",".mj2":"video/mj2",".mjp2":"video/mj2",".mkv":"video/x-matroska",".mlp":"application/vnd.dolby.mlp",".mmd":"application/vnd.chipnuts.karaoke-mmd",".mmf":"application/vnd.smaf",".mmr":"image/vnd.fujixerox.edmics-mmr",".mny":"application/x-msmoney",".mobi":"application/x-mobipocket-ebook",".mov":"video/quicktime",".movie":"video/x-sgi-movie",".mp2":"audio/mpeg",".mp2a":"audio/mpeg",".mp3":"audio/mpeg",".mp4":"video/mp4",".mp4a":"audio/mp4",".mp4s":"application/mp4",".mp4v":"video/mp4",".mpa":"video/mpeg",".mpc":"application/vnd.mophun.certificate",".mpe":"video/mpeg",".mpeg":"video/mpeg",".mpg":"video/mpeg",".mpg4":"video/mp4",".mpga":"audio/mpeg",".mpkg":"application/vnd.apple.installer+xml",".mpm":"application/vnd.blueice.multipass",".mpn":"application/vnd.mophun.application",".mpp":"application/vnd.ms-project",".mpt":"application/vnd.ms-project",".mpy":"application/vnd.ibm.minipay",".mqy":"application/vnd.mobius.mqy",".mrc":"application/marc",".ms":"text/troff",".mscml":"application/mediaservercontrol+xml",".mseed":"application/vnd.fdsn.mseed",".mseq":"application/vnd.mseq",".msf":"application/vnd.epson.msf",".msh":"model/mesh",".msi":"application/x-msdownload",".msl":"application/vnd.mobius.msl",".msty":"application/vnd.muvee.style",".mts":"model/vnd.mts",".mus":"application/vnd.musician",".musicxml":"application/vnd.recordare.musicxml+xml",".mvb":"application/x-msmediaview",".mwf":"application/vnd.mfer",".mxf":"application/mxf",".mxl":"application/vnd.recordare.musicxml",".mxml":"application/xv+xml",".mxs":"application/vnd.triscape.mxs",".mxu":"video/vnd.mpegurl",".n-gage":"application/vnd.nokia.n-gage.symbian.install",".nb":"application/mathematica",".nc":"application/x-netcdf",".ncx":"application/x-dtbncx+xml",".ngdat":"application/vnd.nokia.n-gage.data",".nlu":"application/vnd.neurolanguage.nlu",".nml":"application/vnd.enliven",".nnd":"application/vnd.noblenet-directory",".nns":"application/vnd.noblenet-sealer",".nnw":"application/vnd.noblenet-web",".npx":"image/vnd.net-fpx",".nsf":"application/vnd.lotus-notes",".nws":"message/rfc822",".o":"application/octet-stream",".oa2":"application/vnd.fujitsu.oasys2",".oa3":"application/vnd.fujitsu.oasys3",".oas":"application/vnd.fujitsu.oasys",".obd":"application/x-msbinder",".obj":"application/octet-stream",".oda":"application/oda",".odb":"application/vnd.oasis.opendocument.database",".odc":"application/vnd.oasis.opendocument.chart",".odf":"application/vnd.oasis.opendocument.formula",".odft":"application/vnd.oasis.opendocument.formula-template",".odg":"application/vnd.oasis.opendocument.graphics",".odi":"application/vnd.oasis.opendocument.image",".odp":"application/vnd.oasis.opendocument.presentation",".ods":"application/vnd.oasis.opendocument.spreadsheet",".odt":"application/vnd.oasis.opendocument.text",".oga":"audio/ogg",".ogg":"audio/ogg",".ogv":"video/ogg",".ogx":"application/ogg",".onepkg":"application/onenote",".onetmp":"application/onenote",".onetoc":"application/onenote",".onetoc2":"application/onenote",".opf":"application/oebps-package+xml",".oprc":"application/vnd.palm",".org":"application/vnd.lotus-organizer",".osf":"application/vnd.yamaha.openscoreformat",".osfpvg":"application/vnd.yamaha.openscoreformat.osfpvg+xml",".otc":"application/vnd.oasis.opendocument.chart-template",".otf":"application/x-font-otf",".otg":"application/vnd.oasis.opendocument.graphics-template",".oth":"application/vnd.oasis.opendocument.text-web",".oti":"application/vnd.oasis.opendocument.image-template",".otm":"application/vnd.oasis.opendocument.text-master",".otp":"application/vnd.oasis.opendocument.presentation-template",".ots":"application/vnd.oasis.opendocument.spreadsheet-template",".ott":"application/vnd.oasis.opendocument.text-template",".oxt":"application/vnd.openofficeorg.extension",".p":"text/x-pascal",".p10":"application/pkcs10",".p12":"application/x-pkcs12",".p7b":"application/x-pkcs7-certificates",".p7c":"application/pkcs7-mime",".p7m":"application/pkcs7-mime",".p7r":"application/x-pkcs7-certreqresp",".p7s":"application/pkcs7-signature",".pas":"text/x-pascal",".pbd":"application/vnd.powerbuilder6",".pbm":"image/x-portable-bitmap",".pcf":"application/x-font-pcf",".pcl":"application/vnd.hp-pcl",".pclxl":"application/vnd.hp-pclxl",".pct":"image/x-pict",".pcurl":"application/vnd.curl.pcurl",".pcx":"image/x-pcx",".pdb":"application/vnd.palm",".pdf":"application/pdf",".pfa":"application/x-font-type1",".pfb":"application/x-font-type1",".pfm":"application/x-font-type1",".pfr":"application/font-tdpfr",".pfx":"application/x-pkcs12",".pgm":"image/x-portable-graymap",".pgn":"application/x-chess-pgn",".pgp":"application/pgp-encrypted",".pic":"image/x-pict",".pkg":"application/octet-stream",".pki":"application/pkixcmp",".pkipath":"application/pkix-pkipath",".pl":"text/plain",".plb":"application/vnd.3gpp.pic-bw-large",".plc":"application/vnd.mobius.plc",".plf":"application/vnd.pocketlearn",".pls":"application/pls+xml",".pml":"application/vnd.ctc-posml",".png":"image/png",".pnm":"image/x-portable-anymap",".portpkg":"application/vnd.macports.portpkg",".pot":"application/vnd.ms-powerpoint",".potm":"application/vnd.ms-powerpoint.template.macroenabled.12",".potx":"application/vnd.openxmlformats-officedocument.presentationml.template",".ppa":"application/vnd.ms-powerpoint",".ppam":"application/vnd.ms-powerpoint.addin.macroenabled.12",".ppd":"application/vnd.cups-ppd",".ppm":"image/x-portable-pixmap",".pps":"application/vnd.ms-powerpoint",".ppsm":"application/vnd.ms-powerpoint.slideshow.macroenabled.12",".ppsx":"application/vnd.openxmlformats-officedocument.presentationml.slideshow",".ppt":"application/vnd.ms-powerpoint",".pptm":"application/vnd.ms-powerpoint.presentation.macroenabled.12",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".pqa":"application/vnd.palm",".prc":"application/x-mobipocket-ebook",".pre":"application/vnd.lotus-freelance",".prf":"application/pics-rules",".ps":"application/postscript",".psb":"application/vnd.3gpp.pic-bw-small",".psd":"image/vnd.adobe.photoshop",".psf":"application/x-font-linux-psf",".ptid":"application/vnd.pvi.ptid1",".pub":"application/x-mspublisher",".pvb":"application/vnd.3gpp.pic-bw-var",".pwn":"application/vnd.3m.post-it-notes",".pwz":"application/vnd.ms-powerpoint",".py":"text/x-python",".pya":"audio/vnd.ms-playready.media.pya",".pyc":"application/x-python-code",".pyo":"application/x-python-code",".pyv":"video/vnd.ms-playready.media.pyv",".qam":"application/vnd.epson.quickanime",".qbo":"application/vnd.intu.qbo",".qfx":"application/vnd.intu.qfx",".qps":"application/vnd.publishare-delta-tree",".qt":"video/quicktime",".qwd":"application/vnd.quark.quarkxpress",".qwt":"application/vnd.quark.quarkxpress",".qxb":"application/vnd.quark.quarkxpress",".qxd":"application/vnd.quark.quarkxpress",".qxl":"application/vnd.quark.quarkxpress",".qxt":"application/vnd.quark.quarkxpress",".ra":"audio/x-pn-realaudio",".ram":"audio/x-pn-realaudio",".rar":"application/x-rar-compressed",".ras":"image/x-cmu-raster",".rcprofile":"application/vnd.ipunplugged.rcprofile",".rdf":"application/rdf+xml",".rdz":"application/vnd.data-vision.rdz",".rep":"application/vnd.businessobjects",".res":"application/x-dtbresource+xml",".rgb":"image/x-rgb",".rif":"application/reginfo+xml",".rl":"application/resource-lists+xml",".rlc":"image/vnd.fujixerox.edmics-rlc",".rld":"application/resource-lists-diff+xml",".rm":"application/vnd.rn-realmedia",".rmi":"audio/midi",".rmp":"audio/x-pn-realaudio-plugin",".rms":"application/vnd.jcp.javame.midlet-rms",".rnc":"application/relax-ng-compact-syntax",".roff":"text/troff",".rpm":"application/x-rpm",".rpss":"application/vnd.nokia.radio-presets",".rpst":"application/vnd.nokia.radio-preset",".rq":"application/sparql-query",".rs":"application/rls-services+xml",".rsd":"application/rsd+xml",".rss":"application/rss+xml",".rtf":"application/rtf",".rtx":"text/richtext",".s":"text/x-asm",".saf":"application/vnd.yamaha.smaf-audio",".sbml":"application/sbml+xml",".sc":"application/vnd.ibm.secure-container",".scd":"application/x-msschedule",".scm":"application/vnd.lotus-screencam",".scq":"application/scvp-cv-request",".scs":"application/scvp-cv-response",".scurl":"text/vnd.curl.scurl",".sda":"application/vnd.stardivision.draw",".sdc":"application/vnd.stardivision.calc",".sdd":"application/vnd.stardivision.impress",".sdkd":"application/vnd.solent.sdkm+xml",".sdkm":"application/vnd.solent.sdkm+xml",".sdp":"application/sdp",".sdw":"application/vnd.stardivision.writer",".see":"application/vnd.seemail",".seed":"application/vnd.fdsn.seed",".sema":"application/vnd.sema",".semd":"application/vnd.semd",".semf":"application/vnd.semf",".ser":"application/java-serialized-object",".setpay":"application/set-payment-initiation",".setreg":"application/set-registration-initiation",".sfd-hdstx":"application/vnd.hydrostatix.sof-data",".sfs":"application/vnd.spotfire.sfs",".sgl":"application/vnd.stardivision.writer-global",".sgm":"text/sgml",".sgml":"text/sgml",".sh":"application/x-sh",".shar":"application/x-shar",".shf":"application/shf+xml",".si":"text/vnd.wap.si",".sic":"application/vnd.wap.sic",".sig":"application/pgp-signature",".silo":"model/mesh",".sis":"application/vnd.symbian.install",".sisx":"application/vnd.symbian.install",".sit":"application/x-stuffit",".sitx":"application/x-stuffitx",".skd":"application/vnd.koan",".skm":"application/vnd.koan",".skp":"application/vnd.koan",".skt":"application/vnd.koan",".sl":"text/vnd.wap.sl",".slc":"application/vnd.wap.slc",".sldm":"application/vnd.ms-powerpoint.slide.macroenabled.12",".sldx":"application/vnd.openxmlformats-officedocument.presentationml.slide",".slt":"application/vnd.epson.salt",".smf":"application/vnd.stardivision.math",".smi":"application/smil+xml",".smil":"application/smil+xml",".snd":"audio/basic",".snf":"application/x-font-snf",".so":"application/octet-stream",".spc":"application/x-pkcs7-certificates",".spf":"application/vnd.yamaha.smaf-phrase",".spl":"application/x-futuresplash",".spot":"text/vnd.in3d.spot",".spp":"application/scvp-vp-response",".spq":"application/scvp-vp-request",".spx":"audio/ogg",".src":"application/x-wais-source",".srx":"application/sparql-results+xml",".sse":"application/vnd.kodak-descriptor",".ssf":"application/vnd.epson.ssf",".ssml":"application/ssml+xml",".stc":"application/vnd.sun.xml.calc.template",".std":"application/vnd.sun.xml.draw.template",".stf":"application/vnd.wt.stf",".sti":"application/vnd.sun.xml.impress.template",".stk":"application/hyperstudio",".stl":"application/vnd.ms-pki.stl",".str":"application/vnd.pg.format",".stw":"application/vnd.sun.xml.writer.template",".sus":"application/vnd.sus-calendar",".susp":"application/vnd.sus-calendar",".sv4cpio":"application/x-sv4cpio",".sv4crc":"application/x-sv4crc",".svd":"application/vnd.svd",".svg":"image/svg+xml",".svgz":"image/svg+xml",".swa":"application/x-director",".swf":"application/x-shockwave-flash",".swi":"application/vnd.arastra.swi",".sxc":"application/vnd.sun.xml.calc",".sxd":"application/vnd.sun.xml.draw",".sxg":"application/vnd.sun.xml.writer.global",".sxi":"application/vnd.sun.xml.impress",".sxm":"application/vnd.sun.xml.math",".sxw":"application/vnd.sun.xml.writer",".t":"text/troff",".tao":"application/vnd.tao.intent-module-archive",".tar":"application/x-tar",".tcap":"application/vnd.3gpp2.tcap",".tcl":"application/x-tcl",".teacher":"application/vnd.smart.teacher",".tex":"application/x-tex",".texi":"application/x-texinfo",".texinfo":"application/x-texinfo",".text":"text/plain",".tfm":"application/x-tex-tfm",".tgz":"application/x-gzip",".tif":"image/tiff",".tiff":"image/tiff",".tmo":"application/vnd.tmobile-livetv",".torrent":"application/x-bittorrent",".tpl":"application/vnd.groove-tool-template",".tpt":"application/vnd.trid.tpt",".tr":"text/troff",".tra":"application/vnd.trueapp",".trm":"application/x-msterminal",".tsv":"text/tab-separated-values",".ttc":"application/x-font-ttf",".ttf":"application/x-font-ttf",".twd":"application/vnd.simtech-mindmapper",".twds":"application/vnd.simtech-mindmapper",".txd":"application/vnd.genomatix.tuxedo",".txf":"application/vnd.mobius.txf",".txt":"text/plain",".u32":"application/x-authorware-bin",".udeb":"application/x-debian-package",".ufd":"application/vnd.ufdl",".ufdl":"application/vnd.ufdl",".umj":"application/vnd.umajin",".unityweb":"application/vnd.unity",".uoml":"application/vnd.uoml+xml",".uri":"text/uri-list",".uris":"text/uri-list",".urls":"text/uri-list",".ustar":"application/x-ustar",".utz":"application/vnd.uiq.theme",".uu":"text/x-uuencode",".vcd":"application/x-cdlink",".vcf":"text/x-vcard",".vcg":"application/vnd.groove-vcard",".vcs":"text/x-vcalendar",".vcx":"application/vnd.vcx",".vis":"application/vnd.visionary",".viv":"video/vnd.vivo",".vor":"application/vnd.stardivision.writer",".vox":"application/x-authorware-bin",".vrml":"model/vrml",".vsd":"application/vnd.visio",".vsf":"application/vnd.vsf",".vss":"application/vnd.visio",".vst":"application/vnd.visio",".vsw":"application/vnd.visio",".vtu":"model/vnd.vtu",".vxml":"application/voicexml+xml",".w3d":"application/x-director",".webm":"video/webm",".wad":"application/x-doom",".wav":"audio/x-wav",".wax":"audio/x-ms-wax",".wbmp":"image/vnd.wap.wbmp",".wbs":"application/vnd.criticaltools.wbs+xml",".wbxml":"application/vnd.wap.wbxml",".wcm":"application/vnd.ms-works",".wdb":"application/vnd.ms-works",".wiz":"application/msword",".wks":"application/vnd.ms-works",".wm":"video/x-ms-wm",".wma":"audio/x-ms-wma",".wmd":"application/x-ms-wmd",".wmf":"application/x-msmetafile",".wml":"text/vnd.wap.wml",".wmlc":"application/vnd.wap.wmlc",".wmls":"text/vnd.wap.wmlscript",".wmlsc":"application/vnd.wap.wmlscriptc",".wmv":"video/x-ms-wmv",".wmx":"video/x-ms-wmx",".wmz":"application/x-ms-wmz",".wpd":"application/vnd.wordperfect",".wpl":"application/vnd.ms-wpl",".wps":"application/vnd.ms-works",".wqd":"application/vnd.wqd",".wri":"application/x-mswrite",".wrl":"model/vrml",".wsdl":"application/wsdl+xml",".wspolicy":"application/wspolicy+xml",".wtb":"application/vnd.webturbo",".wvx":"video/x-ms-wvx",".x32":"application/x-authorware-bin",".x3d":"application/vnd.hzn-3d-crossword",".xap":"application/x-silverlight-app",".xar":"application/vnd.xara",".xbap":"application/x-ms-xbap",".xbd":"application/vnd.fujixerox.docuworks.binder",".xbm":"image/x-xbitmap",".xdm":"application/vnd.syncml.dm+xml",".xdp":"application/vnd.adobe.xdp+xml",".xdw":"application/vnd.fujixerox.docuworks",".xenc":"application/xenc+xml",".xer":"application/patch-ops-error+xml",".xfdf":"application/vnd.adobe.xfdf",".xfdl":"application/vnd.xfdl",".xht":"application/xhtml+xml",".xhtml":"application/xhtml+xml",".xhvml":"application/xv+xml",".xif":"image/vnd.xiff",".xla":"application/vnd.ms-excel",".xlam":"application/vnd.ms-excel.addin.macroenabled.12",".xlb":"application/vnd.ms-excel",".xlc":"application/vnd.ms-excel",".xlm":"application/vnd.ms-excel",".xls":"application/vnd.ms-excel",".xlsb":"application/vnd.ms-excel.sheet.binary.macroenabled.12",".xlsm":"application/vnd.ms-excel.sheet.macroenabled.12",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xlt":"application/vnd.ms-excel",".xltm":"application/vnd.ms-excel.template.macroenabled.12",".xltx":"application/vnd.openxmlformats-officedocument.spreadsheetml.template",".xlw":"application/vnd.ms-excel",".xml":"application/xml",".xo":"application/vnd.olpc-sugar",".xop":"application/xop+xml",".xpdl":"application/xml",".xpi":"application/x-xpinstall",".xpm":"image/x-xpixmap",".xpr":"application/vnd.is-xpr",".xps":"application/vnd.ms-xpsdocument",".xpw":"application/vnd.intercon.formnet",".xpx":"application/vnd.intercon.formnet",".xsl":"application/xml",".xslt":"application/xslt+xml",".xsm":"application/vnd.syncml+xml",".xspf":"application/xspf+xml",".xul":"application/vnd.mozilla.xul+xml",".xvm":"application/xv+xml",".xvml":"application/xv+xml",".xwd":"image/x-xwindowdump",".xyz":"chemical/x-xyz",".zaz":"application/vnd.zzazz.deck+xml",".zip":"application/zip",".zir":"application/vnd.zul",".zirz":"application/vnd.zul",".zmm":"application/vnd.handheld-entertainment+xml"},og=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"],Uz=Object.keys(id);import*as ag from"zod";var zz=ag.custom().refine(t=>t&&t.length>0).refine(t=>t&&t[0]instanceof File,{message:"Please upload a valid file."});import{z as ur}from"zod";var jz=ur.object({id:ur.string(),name:ur.string(),createdAt:ur.coerce.date(),createdBy:ur.string(),updatedAt:ur.coerce.date(),updatedBy:ur.string().nullable(),organizationId:ur.string()});import{z as L}from"zod";import mr from"zod";var Wo=mr.object({platformSep:mr.string(),fullPathSegments:mr.string().array(),relativePathSegments:mr.string().array(),relativePath:mr.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:mr.string().describe("base name of the file including the extension, e.g. my-module.module.yaml"),lastModified:mr.coerce.date(),createdAt:mr.coerce.date()});var AC=L.array(Wo.extend({id:L.string(),name:L.string(),description:L.string().optional(),labels:L.string().array().optional()})),xC=L.array(Wo.extend({id:L.string(),name:L.string(),description:L.string().optional(),content:Oa})),nH=L.object({tests:AC,modules:xC,labels:L.string().array()}),rH=ps.merge(en),ig=L.object({schemaVersion:L.string(),stepLists:Mo}),sg=en.partial().merge(St.pick({id:!0})),lg=L.object({name:L.string(),description:L.string().optional(),baseUrl:L.string().url().optional(),environment:L.string().optional(),browserType:L.nativeEnum(zn).optional(),viewport:Zi.optional(),pathSegments:L.string().array().optional()}),oH=ps.merge(L.object({relativeFilePath:L.string().describe("relative to project root")})),cg=L.object({name:L.string()}),aH=L.object({relativeFilePath:L.string()}),dg=L.object({name:L.string()}),iH=L.object({relativeFilePath:L.string()}),ug=L.object({name:L.string(),description:L.string(),enabled:L.boolean(),steps:L.lazy(()=>Ge.array()),testFilePath:L.string().describe("relative to the project root"),folderPath:L.string().optional().describe("user selected folder path")}),mg=L.object({name:L.string(),description:L.string(),enabled:L.boolean()}).partial();var sH=L.array(Ym),pg=L.object({defaultEnv:L.string().optional().describe("name of the default env, or undefined to unset")}),gg=L.object({configFilePath:L.string().describe("full path on disk")}),lH=L.string().array(),cH=L.object({message:L.string(),newRelativeTestPath:L.string().optional()}),sd=L.object({name:L.string(),absolutePath:L.string(),relativePath:L.string(),pathSegments:L.array(L.string()),isDirectory:L.boolean(),size:L.number(),createdAt:L.coerce.date(),modifiedAt:L.coerce.date(),accessedAt:L.coerce.date()}),hg=L.object({pathSegments:L.array(L.string())}),dH=L.object({absolutePath:L.string(),pathSegments:L.array(L.string()),contents:L.array(sd)}),fg=L.object({pathSegments:L.array(L.string())}),Sg=L.object({pathSegments:L.array(L.string()),newPathSegments:L.array(L.string())}),yg=L.object({pathSegments:L.array(L.string()),recursive:L.boolean().optional()}),uH=L.object({success:L.boolean(),message:L.string(),pathSegments:L.array(L.string()).optional()});var Ts=["node_modules","dist","bin",".git",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"],ws=Ts.map(t=>`**/${t}/**`);import vn from"chalk";import IC from"safe-stable-stringify";import PC from"truncate-json";import MC from"zod";var Va=IC.configure({deterministic:!1});function bg(t){let e=Va(t),{jsonString:n}=PC(e,1e4);return n}var LC=["app","version","env","namespace","host"];function Oe(t){let e=t.bindings()??{},n={};for(let r of Object.keys(e)){let o=e[r];!LC.includes(r)&&typeof o=="string"&&(n[r]=o)}return n}var ld=MC.enum(["debug","info","warn","error"]);var qa={debug:20,info:30,warn:40,error:50},Rs={20:"debug",30:"info",40:"warn",50:"error"},Ka=class t{minLogLevel;logBindings;constructor(e,n){typeof e=="string"?this.minLogLevel=qa[e]:this.minLogLevel=e,this.logBindings=n}logWithLevel(e,n,...r){try{this.logWithLevelHelper(e,n,...r)}catch(o){console.error(`Failed to log to console: ${o}`)}}logWithLevelHelper(e,n,...r){if(e<this.minLogLevel)return;let o;Array.isArray(r[0])?(o=r[0],r=r.slice(1)):typeof r[0]=="object"&&!(r[0]instanceof Error)&&Object.entries(r[0]).length&&(o={...r[0],...this.logBindings},r=r.slice(1));let a=[];if(a.push(...r),console.log(n(...a)),o&&!Array.isArray(o)){let i=Object.entries(o);for(let[s,l]of i){let c=l;l instanceof Error?c=l.message:typeof l=="object"&&(c=Va(l,void 0,2),c=c.split(`
8
8
  `).map((d,u)=>u>0?` ${d}`:d).join(`
9
- `)),console.log(n(` ${s}:`,c))}}else if(o)for(let a of o){let s=a;typeof a=="object"&&(s=ji(a,void 0,2),s=s.split(`
9
+ `)),console.log(n(` ${s}:`,c))}}else if(o)for(let i of o){let s=i;typeof i=="object"&&(s=Va(i,void 0,2),s=s.split(`
10
10
  `).map((l,c)=>c>0?` ${l}`:l).join(`
11
- `)),console.log(" ",n(s))}}getLevel(){return bs[this.minLogLevel]}setMinLevel(e){typeof e=="string"?this.minLogLevel=Gi[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,Rn.reset,...e)}info(...e){this.logWithLevel(30,Rn.white,...e)}debug(...e){this.logWithLevel(20,Rn.dim,...e)}warn(...e){this.logWithLevel(40,Rn.yellow,...e)}error(...e){this.logWithLevel(50,Rn.red,...e)}success(...e){this.logWithLevel(1/0,Rn.green,...e)}dimmed(...e){this.logWithLevel(30,Rn.dim,...e)}underline(...e){this.logWithLevel(40,Rn.underline,...e)}bold(...e){this.logWithLevel(40,Rn.bold,...e)}grey(...e){this.logWithLevel(20,Rn.grey,...e)}child(e){return new t(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},nd=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}getLevel(){return"error"}flush(){}bindings(){return{}}},iH=new nd,CR=typeof window>"u"&&typeof process<"u"&&td.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?td.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,y=new Wi(CR,{}),qr={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>qr,flush:()=>{},bindings:()=>({}),getLevel:()=>"error"},ys={},Ts=({logger:t,logKey:e,maxCount:n,intervalMs:r},o,i,...a)=>{let s=ys[e];s?clearTimeout(s.timer):(s={count:0,totalCount:0},ys[e]=s),s.totalCount++,s.count<n&&(s.count++,t.debug(o,i,...a)),s.timer=setTimeout(()=>{let l=ys[e];l?.totalCount!==l?.count&&t.debug({logKey:e,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${e}`),delete ys[e]},r)};import{z as Re}from"zod";var RR=Re.array(jo.extend({id:Re.string(),name:Re.string(),description:Re.string().optional(),labels:Re.string().array().optional()})),vR=Re.array(jo.extend({id:Re.string(),name:Re.string(),description:Re.string().optional(),content:Pi})),uH=Re.object({name:Re.string(),description:Re.string().optional(),steps:Re.array(Hn).optional(),settings:Ui.optional(),pathSegments:Re.string().array()}),mH=Re.object({id:Re.string(),fileName:Re.string(),fullPath:Re.string(),relativeFilePath:Re.string().describe("relative to project root")});var pH=Re.object({steps:Re.array(Hn).optional(),settings:Ui.optional()}),gH=Re.object({message:Re.literal("ok")}),hH=Re.object({tag:Re.string(),channel:Re.string(),filePath:Re.string()}),fH=Re.object({tests:RR,modules:vR,labels:Re.string().array()});import{z as qe}from"zod";var ug=qe.object({id:qe.string(),createdAt:qe.coerce.date(),createdBy:qe.string(),organizationId:qe.string(),name:qe.string(),description:qe.string().nullish(),enabled:qe.boolean(),schemaVersion:qe.string().describe("Schema version for steps"),parameters:qe.string().array().nullish().describe("Parameter list"),parameterEnums:qe.record(qe.string(),qe.string().array()).nullish(),defaultParameters:qe.record(qe.string(),qe.string()).nullish(),defaultCacheKey:qe.string().nullish(),defaultCacheTtl:qe.number().nullish(),defaultCacheAllInvocations:qe.boolean().nullish(),autoAuth:qe.boolean().nullish(),advanced:Sc.nullish()}),vH=ug.extend({steps:qe.lazy(()=>Le.array())}),mg=5*60*1e3,rd=Mt.merge(ug.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as IH}from"date-fns-tz";import{z as Ne}from"zod";var od=Oc.extend({aiAction:Ne.boolean().optional(),stepLintSuggestions:Ne.boolean().optional(),agentConfig:Ne.record(Ne.string(),Ne.string()).optional(),aiFailureAnalysis:Ne.boolean().optional(),aiPageFiltering:Ne.boolean().optional().describe("rag v2 feature flag")}),id=Ne.object({fakerConstantSeed:Ne.boolean().optional()}),kH=Ne.object({ai:od.optional(),githubAppInstallationId:Ne.number().nullish(),githubAppSummaryMessageEnabled:Ne.boolean().nullish(),githubReleaseAppInstallationId:Ne.number().nullish(),gitlabAppAccessToken:Ne.string().nullish(),gitlabAppBaseUrl:Ne.string().nullish(),qaseAccessToken:Ne.string().nullish(),testSuggestionsEnabled:Ne.boolean().nullish(),browser:Cc.optional(),advanced:id.optional()}),_H=Ne.object({globalOverrides:Ne.record(Ne.string()).optional(),agentConfig:Ne.record(Ne.string(),Ne.string()).optional()}),DH=Ne.record(Ne.string(),Ne.string()).nullish();import*as w from"zod";var pg="x-momentic-cli-version",AR="x-momentic-main-branch-name",xR="x-momentic-branch-name",IR="x-momentic-commit-timestamp",PR="x-momentic-last-commit-on-main",LR="x-momentic-last-commit-on-main-timestamp",QH=w.object({error:w.boolean(),reason:w.string(),message:w.string()}),ZH=Nt.merge(_c),gg=Da,e1=Nt.merge(_c);var t1=Nt.merge(lp).extend({useConsensus:w.boolean().optional(),attemptNumber:w.number().optional()}),ad=gm,n1=Nt.merge(cp),hg=Mm,r1=Nt.merge(ip),fg=Lm,o1=Nt.merge(ap),Sg=Pm,i1=Nt.merge(sp);var a1=w.object({testPaths:w.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:w.string().optional(),all:w.boolean().optional(),urlOverride:w.string().optional(),customHeaders:w.record(w.string(),w.string()).optional(),testInputMatrix:w.record(w.string(),w.string()).array().optional()}),yg=w.object({queuedTests:w.unknown().array(),runIds:w.string().uuid().array(),runGroupId:w.string().optional()});var s1=w.string().array(),l1=w.union([w.object({paths:w.string().array().describe("run specific test paths (e.g. todo-test)"),all:w.boolean().describe("run all tests").optional()}),w.object({path:w.string().describe("deprecated; present for backcompat")})]),bg=w.object({tests:w.record(w.string().describe("Test name"),w.string().describe("Test YAML")),modules:w.record(w.string().describe("Module name"),w.string().describe("Module YAML"))}),MR=w.object({test:w.string().describe("test YAML"),modules:w.record(w.string().describe("moduleId"),w.string().describe("module YAML"))}),c1=MR.array(),d1=w.object({testId:w.string(),schemaVersion:w.string()}).merge(Fr);function sd(t){let{gitMainBranch:e,gitBranchName:n,gitCommitTimestamp:r,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:i}=t,a={};return e&&(a[AR]=encodeURIComponent(e)),n&&(a[xR]=encodeURIComponent(n)),r&&(a[IR]=r.toISOString()),o&&(a[PR]=encodeURIComponent(o)),i&&(a[LR]=i.toISOString()),a}var u1=w.object({entries:w.array(Rm),testId:w.string()}),m1=w.object({entries:w.array(Mp),testId:w.string()}),p1=w.object({testId:w.string()});function Tg(t){return w.record(w.unknown()).transform(e=>{let n={};for(let[r,o]of Object.entries(e)){let i=t.safeParse(o);i.success&&(n[r]=i.data)}return n})}var wg=Tg(vm),Eg=Tg(Op),Cg=w.object({trigger:w.nativeEnum(Xt),status:w.nativeEnum(ue),startedAt:w.coerce.date().optional(),gitCommitSha:w.string().optional(),gitCommitShaShort:w.string().optional(),gitCommitTimestamp:w.coerce.date().optional(),gitBranchName:w.string().optional(),gitOriginUrl:w.string().optional(),gitCommitMessage:w.string().optional(),gitCommitAuthorName:w.string().optional(),githubRepository:w.string().optional(),gitlabProjectPath:w.string().optional(),pipelineId:w.string().optional(),cliVersion:w.string().optional()}),g1=w.object({id:w.string()}),Rg=w.object({status:w.nativeEnum(ue),updatedAt:w.coerce.date().optional(),finishedAt:w.coerce.date().optional()}),vg=w.object({stepsSnapshot:w.array(w.record(w.unknown())).optional(),runGroupId:w.string().optional(),testId:w.string(),testName:w.string(),resolvedBaseUrl:w.string().optional(),environmentName:w.string().optional(),labels:w.array(w.string()).optional(),cliVersion:w.string().optional(),trigger:w.nativeEnum(Xt),schemaVersion:w.string().optional(),section:w.nativeEnum(es).optional(),resolvedInputs:w.record(w.string(),w.string()).optional(),quarantined:w.boolean().optional().default(!1),quarantinedReason:w.string().optional()}),h1=w.object({id:w.string()}),OR=Nc.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Ag=OR.array(),xg=Nc.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,resolvedBaseUrl:!0,environmentName:!0,labels:!0,cliVersion:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),f1=w.object({id:w.string()}),Ig=w.object({status:w.nativeEnum(ue),finishedAt:w.coerce.date().optional(),schemaVersion:w.string().optional().default("1.0.19"),results:w.record(w.string(),w.unknown()).array().optional(),beforeResults:w.record(w.string(),w.unknown()).array().optional(),afterResults:w.record(w.string(),w.unknown()).array().optional()}),S1=w.object({screenshot:w.string()}),Pg=w.object({key:w.string()}),Lg=w.object({orgId:w.string(),userId:w.string()}),Mg=w.array(Bm),y1=w.record(w.string(),w.union([w.string(),w.boolean()])),b1=w.object({paths:w.string().array(),env:w.string().optional(),urlOverride:w.string().optional(),customHeaders:w.record(w.string(),w.string()).optional()}),Og=w.object({suiteRunIds:w.string().array(),runGroupIds:w.string().array()}),T1=w.object({suiteRunIds:w.string().array()}),w1=tp.array(),E1=w.object({runGroupIds:w.string().array()}),NR=w.object({uploadUrl:w.string()}),C1=Nt.merge(dp),R1=Nt.merge(mp),v1=Nt.merge(up),kR=w.object({testId:w.string().optional().default(""),testName:w.string().optional().default(""),suiteId:w.string().optional().default(""),suiteName:w.string().optional().default(""),creditsUsed:w.number().optional(),usedBy:w.string().optional()}),_R=w.object({transactionId:w.string(),timestamp:w.string(),event:w.nativeEnum(Di),properties:kR}),A1=_R.array(),Ng=Gm.omit({steps:!0}).extend({steps:w.array(w.record(w.string(),w.unknown())).describe("unparsed ResolvedStep[]")}),x1=w.object({limit:w.number().max(10).optional(),afterTime:w.number().optional()}),kg=Xm.array(),I1=w.object({applied:w.boolean().optional(),appliedAt:w.coerce.date().optional()}),_g=NR.extend({id:w.string()}),P1=w.object({runGroupId:w.string().uuid().optional()}),Dg=w.object({runGroupId:w.string().uuid()}),Fg=w.object({quarantined:w.object({testId:w.string().uuid(),quarantinedAt:w.coerce.date(),quarantinedBy:w.string().optional(),quarantinedReason:w.string()}).array()}),L1=w.object({testId:w.string().uuid(),testName:w.string().optional(),reason:w.string(),gitLocalUsername:w.string().optional(),gitLocalEmail:w.string().optional(),gitLocalName:w.string().optional()}),M1=w.object({testName:w.string().optional(),reason:w.string().optional(),gitLocalUsername:w.string().optional(),gitLocalEmail:w.string().optional(),gitLocalName:w.string().optional()}),O1=Nt.merge(hp),N1=Nt.merge(fp),k1=w.object({apkToInstall:w.object({channel:w.string(),tag:w.string().optional()}).optional(),hostname:w.string().optional()}),Ug=w.object({name:w.string(),webRtcUrl:w.string(),adbUrl:w.string(),token:w.string(),apkDownloadUrl:w.string().optional(),region:w.string().optional()}),_1=w.object({channel:w.string(),tag:w.string(),md5:w.string()}),Bg=w.object({id:w.string(),uploadUrl:w.string().optional(),downloadUrl:w.string(),md5:w.string().optional()}),zg=w.object({assets:w.array(w.object({channel:w.string(),tag:w.string(),md5:w.string(),createdAt:w.number().describe("Unix timestamp in milliseconds")}))});import{z as Y}from"zod";var U1=Y.object({localTestId:Y.string(),quarantinedAt:Y.date(),quarantinedBy:Y.string().optional(),quarantinedReason:Y.string(),quarantinedByGitEmail:Y.string().optional(),quarantinedByGitName:Y.string().optional(),quarantinedByGitUsername:Y.string().optional()}).or(Y.object({cloudTestId:Y.string(),quarantinedAt:Y.date(),quarantinedBy:Y.string().optional(),quarantinedReason:Y.string(),quarantinedByGitEmail:Y.string().optional(),quarantinedByGitName:Y.string().optional(),quarantinedByGitUsername:Y.string().optional()})),Hg=(n=>(n.QUARANTINE="QUARANTINE",n.UNQUARANTINE="UNQUARANTINE",n))(Hg||{});var ld=Y.object({name:Y.string(),description:Y.string().nullish(),effect:Y.nativeEnum(Hg),labels:Y.array(Y.string()),githubRepository:Y.string().nullish(),gitlabProjectPath:Y.string().nullish(),gitBranchName:Y.string().nullish()}),DR=Y.object({type:Y.literal("LAST_N_RUNS"),lastN:Y.number().min(1).max(10)}),FR=Y.object({type:Y.literal("LAST_N_HOURS"),lastN:Y.number().min(1).max(24)}),UR=Y.object({type:Y.literal("LAST_N_DAYS"),lastN:Y.number().min(1).max(7)}),cd=Y.discriminatedUnion("type",[DR,FR,UR]),BR=Y.object({flakeRateThreshold:Y.number().min(1).max(100),evaluationWindow:cd}),zR=ld.extend({type:Y.literal("FLAKE_RATE"),config:BR}),HR=Y.object({passRateThreshold:Y.number().min(1).max(100),evaluationWindow:cd}),$R=ld.extend({type:Y.literal("PASS_RATE"),config:HR}),jR=Y.object({failureCountThreshold:Y.number().min(0),evaluationWindow:cd}),GR=ld.extend({type:Y.literal("FAILURE_COUNT"),config:jR}),B1=Y.discriminatedUnion("type",[zR,$R,GR]);import{z as nt}from"zod";var $1=nt.object({repositoriesIndexed:nt.boolean(),indexingInProgress:nt.boolean(),indexesOutdated:nt.boolean()}),$g=(a=>(a.Queued="queued",a.InProgress="in_progress",a.Completed="completed",a.Waiting="waiting",a.Requested="requested",a.Pending="pending",a))($g||{}),jg=(s=>(s.Success="success",s.Failure="failure",s.Neutral="neutral",s.Cancelled="cancelled",s.Skipped="skipped",s.TimedOut="timed_out",s.ActionRequired="action_required",s))(jg||{}),j1=nt.object({name:nt.string(),status:nt.nativeEnum($g),conclusion:nt.nativeEnum(jg).nullable()}),Vi=nt.object({sha:nt.string(),message:nt.string(),author:nt.object({name:nt.string().optional(),email:nt.string().optional(),date:nt.coerce.date().optional()}),committer:nt.object({name:nt.string().optional(),email:nt.string().optional(),date:nt.coerce.date().optional()})});import{z as De}from"zod";var Gg=De.object({orgId:De.string(),cacheKeys:De.string().array()}),V1=De.object({keyParams:Gg,clientMetadata:De.string(),lockAcquisitionTimeoutMs:De.number().optional()}),Wg=De.object({acquired:De.boolean(),acquiredByMetadata:De.string(),keyPrefix:De.string()}),q1=De.object({keyPrefix:De.string(),result:De.string(),ttlMs:De.number()}),K1=De.union([De.object({keyPrefix:De.string()}),Gg]),WR=De.object({remainingTtlMs:De.number(),value:De.string().nullish()}),Y1=De.object({results:De.record(De.string(),WR),activeLocks:De.string().array()}),Vg=0,qg=5*60*1e3;var Z1=90*24*60*60*1e3,e$=7*24*60*60*1e3;import{z as Kg}from"zod";var r$=Kg.object({quarantineNotifications:Kg.string().nullish()});import{z as dt}from"zod";var VR=dt.object({version:dt.string(),json:dt.record(dt.unknown()),hash:dt.string()}),Yg=dt.record(dt.unknown()),s$=dt.object({newSvgs:dt.array(VR),metadata:Yg.optional()}),qR=dt.object({version:dt.string(),json:dt.record(dt.unknown()).nullish(),hash:dt.string(),description:dt.string().nullish(),metadata:Yg.nullish()}),Xg=dt.record(dt.string().describe("icon hash"),qR);import{z as Be}from"zod";var dd=Be.object({assertion:Be.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),KR=Be.object({instruction:Be.string().describe("Human readable instruction to execute the step. Instructions should only describe concrete actions that need to be taken. Any checks or assertions should be described in the preConditions, postConditions, or expectedResults."),expectedResults:dd.array().optional().describe("Human readable description of the expected results after the step is executed. Each expected result should contain a single assertion that evaluates to true or false.")}),Jg=KR.extend({subSteps:Be.lazy(()=>Jg.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),Qg=Be.object({name:Be.string().describe("Short name describing the test plan"),description:Be.string().nullish().transform(t=>t??void 0).describe("Longer form description of the high level goal of the test plan")}),Zg=Qg.extend({id:Be.string(),createdAt:Be.coerce.date(),updatedAt:Be.coerce.date(),updatedBy:Be.string(),createdBy:Be.string(),test:Be.object({id:Be.string(),name:Be.string()}).nullish().transform(t=>t??void 0)}),u$=Zg.extend({testGenRuns:Be.tuple([]).or(Be.tuple([Be.object({id:Be.string(),startedAt:Be.coerce.date(),status:Be.nativeEnum(ue)})]))}),eh=Be.object({preConditions:dd.array().nullish().transform(t=>t??[]),postConditions:dd.array().nullish().transform(t=>t??[]),steps:Jg.array().nullish().transform(t=>t??[])}),m$=Zg.extend({plan:eh.nullish().transform(t=>t??{preConditions:[],postConditions:[],steps:[]})}),YR=Qg.extend({plan:eh.nullish().transform(t=>t??{preConditions:[],postConditions:[],steps:[]})}),p$=YR.array().nullish().transform(t=>t??[]);import{validator as XR}from"@exodus/schemasafe";function th(t){let e;try{e=JSON.parse(t)}catch(n){return`The schema is not valid JSON. ${n}`}try{XR(e)}catch(n){return`The schema is not a valid JSON schema. ${n}`}}var nh=t=>{t.extraHeaders&&(t.extraHeaders=Object.fromEntries(Object.entries(t.extraHeaders).filter(([e,n])=>e.trim()&&n.trim())))};import{z as L$}from"zod";var ws=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}};import{z as K}from"zod";var JR=K.object({step:$e,status:K.nativeEnum(Ce),startedAt:K.coerce.date(),finishedAt:K.coerce.date().optional(),healMetadata:K.object({healType:K.nativeEnum(Li).or(K.literal("AI")),healedAt:K.coerce.date()}).optional(),beforeSnapshotId:K.string().uuid().optional(),afterSnapshotId:K.string().uuid().optional(),message:K.string().optional()}),K$=JR.extend({finishedAt:K.coerce.date().optional().transform(t=>t??new Date)}),rh="1.0.0",ud=Ig.extend({id:K.string().uuid().optional(),startedAt:K.coerce.date(),runAttemptSchemaVersion:K.string().optional(),schemaVersion:K.string().optional().default("1.0.19"),results:K.record(K.string(),K.unknown()).array().optional(),beforeResults:K.record(K.string(),K.unknown()).array().optional(),afterResults:K.record(K.string(),K.unknown()).array().optional()}),oh=ud.extend({finishedAt:K.coerce.date().optional().transform(t=>t??new Date)}),Y$=ud.merge(Oi),X$=oh.merge(Oi),ih=K.object({results:K.array(cs),beforeResults:K.array(cs).optional(),afterResults:K.array(cs).optional()}),J$=ud.merge(ih),Q$=oh.merge(ih),QR=xg.merge(vg).extend({executionType:K.nativeEnum(Oo).optional().default("WEB"),testId:K.string().uuid(),testDescription:K.string().optional(),runGroupId:K.string().uuid(),status:K.nativeEnum(ue),startedAt:K.coerce.date(),attempts:K.number(),failureRecoveryDetails:K.record(K.unknown()).optional()}),Z$=QR.extend({finishedAt:K.coerce.date().optional().transform(t=>t??new Date)}),ZR=Cg.merge(Rg).extend({id:K.string().uuid().optional(),startedAt:K.coerce.date(),cliVersion:K.string(),labels:K.string().array().optional().default([])}),qi=ZR.extend({updatedAt:K.coerce.date().optional().transform(t=>t??new Date),finishedAt:K.coerce.date().optional().transform(t=>t??new Date)});function ah(t){try{return ev(t)&&tv(t).isDirectory()}catch(e){return y.error({err:e},`Error reading path ${t} during directory existence check`),!1}}import{confirm as pv,input as gv}from"@inquirer/prompts";import{existsSync as hv,mkdirSync as fv,statSync as Sv}from"fs";import{dirname as yv}from"path";import vn,{supportsColor as uv}from"chalk";import{Console as sh}from"console";import{format as Ki}from"util";var md=class extends Error{constructor(e,n,r){let o=Error.stackTraceLimit;r&&(Error.stackTraceLimit=Math.max(r,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,n),Error.stackTraceLimit=o}},Es=class t extends sh{_buffer=[];_groupDepth=0;Console=sh;constructor(){super({write:e=>(t.write(this._buffer,"log",e),!0)})}static write(e,n,r,o=2){let i=new md(void 0,t.write).stack;if(!i)return e;let a=i.split(`
11
+ `)),console.log(" ",n(s))}}getLevel(){return Rs[this.minLogLevel]}setMinLevel(e){typeof e=="string"?this.minLogLevel=qa[e]:this.minLogLevel=e}log(...e){this.logWithLevel(30,vn.reset,...e)}info(...e){this.logWithLevel(30,vn.white,...e)}debug(...e){this.logWithLevel(20,vn.dim,...e)}warn(...e){this.logWithLevel(40,vn.yellow,...e)}error(...e){this.logWithLevel(50,vn.red,...e)}success(...e){this.logWithLevel(1/0,vn.green,...e)}dimmed(...e){this.logWithLevel(30,vn.dim,...e)}underline(...e){this.logWithLevel(40,vn.underline,...e)}bold(...e){this.logWithLevel(40,vn.bold,...e)}grey(...e){this.logWithLevel(20,vn.grey,...e)}child(e){return new t(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},cd=class{debug(){}info(){}warn(){}error(){}success(){}dimmed(){}underline(){}bold(){}grey(){}child(){return this}getLevel(){return"error"}flush(){}bindings(){return{}}},bH=new cd,OC=typeof window>"u"&&typeof process<"u"&&ld.safeParse(process?.env?.MOMENTIC_DEV_LOG_LEVEL).success?ld.parse(process.env.MOMENTIC_DEV_LOG_LEVEL):30,S=new Ka(OC,{}),Xr={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Xr,flush:()=>{},bindings:()=>({}),getLevel:()=>"error"},Es={},Cs=({logger:t,logKey:e,maxCount:n,intervalMs:r},o,a,...i)=>{let s=Es[e];s?clearTimeout(s.timer):(s={count:0,totalCount:0},Es[e]=s),s.totalCount++,s.count<n&&(s.count++,t.debug(o,a,...i)),s.timer=setTimeout(()=>{let l=Es[e];l?.totalCount!==l?.count&&t.debug({logKey:e,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${e}`),delete Es[e]},r)};import{z as Re}from"zod";var NC=Re.array(Wo.extend({id:Re.string(),name:Re.string(),description:Re.string().optional(),labels:Re.string().array().optional()})),kC=Re.array(Wo.extend({id:Re.string(),name:Re.string(),description:Re.string().optional(),content:Oa})),vH=Re.object({name:Re.string(),description:Re.string().optional(),steps:Re.array($n).optional(),settings:Ha.optional(),pathSegments:Re.string().array()}),AH=Re.object({id:Re.string(),fileName:Re.string(),fullPath:Re.string(),relativeFilePath:Re.string().describe("relative to project root")});var xH=Re.object({steps:Re.array($n).optional(),settings:Ha.optional()}),IH=Re.object({message:Re.literal("ok")}),PH=Re.object({tag:Re.string(),channel:Re.string(),filePath:Re.string()}),MH=Re.object({tests:NC,modules:kC,labels:Re.string().array()});import{z as qe}from"zod";var Tg=qe.object({id:qe.string(),createdAt:qe.coerce.date(),createdBy:qe.string(),organizationId:qe.string(),name:qe.string(),description:qe.string().nullish(),enabled:qe.boolean(),schemaVersion:qe.string().describe("Schema version for steps"),parameters:qe.string().array().nullish().describe("Parameter list"),parameterEnums:qe.record(qe.string(),qe.string().array()).nullish(),defaultParameters:qe.record(qe.string(),qe.string()).nullish(),defaultCacheKey:qe.string().nullish(),defaultCacheTtl:qe.number().nullish(),defaultCacheAllInvocations:qe.boolean().nullish(),autoAuth:qe.boolean().nullish(),advanced:Ac.nullish()}),BH=Tg.extend({steps:qe.lazy(()=>Me.array())}),wg=5*60*1e3,dd=Ot.merge(Tg.omit({id:!0,createdAt:!0,createdBy:!0,organizationId:!0,enabled:!0}));import{formatInTimeZone as $H}from"date-fns-tz";import{z as Ne}from"zod";var ud=Bc.extend({aiAction:Ne.boolean().optional(),stepLintSuggestions:Ne.boolean().optional(),agentConfig:Ne.record(Ne.string(),Ne.string()).optional(),aiFailureAnalysis:Ne.boolean().optional(),aiPageFiltering:Ne.boolean().optional().describe("rag v2 feature flag")}),md=Ne.object({fakerConstantSeed:Ne.boolean().optional()}),KH=Ne.object({ai:ud.optional(),githubAppInstallationId:Ne.number().nullish(),githubAppSummaryMessageEnabled:Ne.boolean().nullish(),githubReleaseAppInstallationId:Ne.number().nullish(),gitlabAppAccessToken:Ne.string().nullish(),gitlabAppBaseUrl:Ne.string().nullish(),qaseAccessToken:Ne.string().nullish(),testSuggestionsEnabled:Ne.boolean().nullish(),browser:Oc.optional(),advanced:md.optional()}),YH=Ne.object({globalOverrides:Ne.record(Ne.string()).optional(),agentConfig:Ne.record(Ne.string(),Ne.string()).optional()}),XH=Ne.record(Ne.string(),Ne.string()).nullish();import*as T from"zod";import{z as We}from"zod";var pd=(e=>(e.TEST_REVIEW="TEST_REVIEW",e))(pd||{});var _C=We.object({type:We.literal("DESCRIPTION_UPDATE"),thoughts:We.string()}),vs=We.discriminatedUnion("type",[_C]),DC=We.object({testId:We.string(),name:We.string(),orgId:We.string(),runId:We.string(),steps:Ge.array(),purpose:We.nativeEnum(pd),details:vs.or(vs.array()).optional()});var e1=DC.pick({name:!0,orgId:!0}),FC=We.object({id:We.string(),name:We.string().nullish(),createdAt:We.string().pipe(We.coerce.date()).or(We.date()),organizationId:We.string(),schemaVersion:We.string(),runId:We.string().nullish(),purpose:We.nativeEnum(pd),details:vs.or(vs.array()).optional(),applied:We.boolean().nullish(),appliedAt:We.coerce.date().nullish()}),Eg=FC.extend({steps:Ge.array()});var Rg="x-momentic-cli-version",UC="x-momentic-main-branch-name",BC="x-momentic-branch-name",zC="x-momentic-commit-timestamp",HC="x-momentic-last-commit-on-main",$C="x-momentic-last-commit-on-main-timestamp",f1=T.object({error:T.boolean(),reason:T.string(),message:T.string()}),S1=kt.merge($c),Cg=zi,y1=kt.merge($c);var b1=kt.merge(fp).extend({useConsensus:T.boolean().optional(),attemptNumber:T.number().optional()}),gd=Rm,T1=kt.merge(Sp),vg=zm,w1=kt.merge(pp),Ag=Bm,E1=kt.merge(gp),xg=Um,R1=kt.merge(hp);var C1=T.object({testPaths:T.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:T.string().optional(),all:T.boolean().optional(),urlOverride:T.string().optional(),customHeaders:T.record(T.string(),T.string()).optional(),testInputMatrix:T.record(T.string(),T.string()).array().optional()}),Ig=T.object({queuedTests:T.unknown().array(),runIds:T.string().uuid().array(),runGroupId:T.string().optional()});var v1=T.string().array(),A1=T.union([T.object({paths:T.string().array().describe("run specific test paths (e.g. todo-test)"),all:T.boolean().describe("run all tests").optional()}),T.object({path:T.string().describe("deprecated; present for backcompat")})]),Pg=T.object({tests:T.record(T.string().describe("Test name"),T.string().describe("Test YAML")),modules:T.record(T.string().describe("Module name"),T.string().describe("Module YAML"))}),jC=T.object({test:T.string().describe("test YAML"),modules:T.record(T.string().describe("moduleId"),T.string().describe("module YAML"))}),x1=jC.array(),I1=T.object({testId:T.string(),schemaVersion:T.string()}).merge(zr);function hd(t){let{gitMainBranch:e,gitBranchName:n,gitCommitTimestamp:r,lastCommitOnMainSha:o,lastCommitOnMainTimestamp:a}=t,i={};return e&&(i[UC]=encodeURIComponent(e)),n&&(i[BC]=encodeURIComponent(n)),r&&(i[zC]=r.toISOString()),o&&(i[HC]=encodeURIComponent(o)),a&&(i[$C]=a.toISOString()),i}var P1=T.object({entries:T.array(Nm),testId:T.string()}),M1=T.object({entries:T.array(Bp),testId:T.string()}),L1=T.object({testId:T.string()});function Mg(t){return T.record(T.unknown()).transform(e=>{let n={};for(let[r,o]of Object.entries(e)){let a=t.safeParse(o);a.success&&(n[r]=a.data)}return n})}var Lg=Mg(km),Og=Mg(zp),Ng=T.object({trigger:T.nativeEnum(Jt),status:T.nativeEnum(le),startedAt:T.coerce.date().optional(),gitCommitSha:T.string().optional(),gitCommitShaShort:T.string().optional(),gitCommitTimestamp:T.coerce.date().optional(),gitBranchName:T.string().optional(),gitOriginUrl:T.string().optional(),gitCommitMessage:T.string().optional(),gitCommitAuthorName:T.string().optional(),githubRepository:T.string().optional(),gitlabProjectPath:T.string().optional(),pipelineId:T.string().optional(),cliVersion:T.string().optional()}),O1=T.object({id:T.string()}),kg=T.object({status:T.nativeEnum(le),updatedAt:T.coerce.date().optional(),finishedAt:T.coerce.date().optional()}),_g=T.object({stepsSnapshot:T.array(T.record(T.unknown())).optional(),runGroupId:T.string().optional(),testId:T.string(),testName:T.string(),resolvedBaseUrl:T.string().optional(),environmentName:T.string().optional(),labels:T.array(T.string()).optional(),cliVersion:T.string().optional(),trigger:T.nativeEnum(Jt),schemaVersion:T.string().optional(),section:T.nativeEnum(rs).optional(),resolvedInputs:T.record(T.string(),T.string()).optional(),quarantined:T.boolean().optional().default(!1),quarantinedReason:T.string().optional()}),N1=T.object({id:T.string()}),GC=zc.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Dg=GC.array(),Fg=zc.pick({startedAt:!0,finishedAt:!0,updatedAt:!0,results:!0,beforeResults:!0,afterResults:!0,status:!0,failureDetails:!0,failureReason:!0,resolvedBaseUrl:!0,environmentName:!0,labels:!0,cliVersion:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),k1=T.object({id:T.string()}),Ug=T.object({status:T.nativeEnum(le),finishedAt:T.coerce.date().optional(),schemaVersion:T.string().optional().default("1.0.19"),results:T.record(T.string(),T.unknown()).array().optional(),beforeResults:T.record(T.string(),T.unknown()).array().optional(),afterResults:T.record(T.string(),T.unknown()).array().optional()}),_1=T.object({screenshot:T.string()}),Bg=T.object({key:T.string()}),zg=T.object({orgId:T.string(),userId:T.string()}),Hg=T.array(Km),D1=T.record(T.string(),T.union([T.string(),T.boolean()])),F1=T.object({paths:T.string().array(),env:T.string().optional(),urlOverride:T.string().optional(),customHeaders:T.record(T.string(),T.string()).optional()}),$g=T.object({suiteRunIds:T.string().array(),runGroupIds:T.string().array()}),U1=T.object({suiteRunIds:T.string().array()}),B1=cp.array(),z1=T.object({runGroupIds:T.string().array()}),WC=T.object({uploadUrl:T.string()}),H1=kt.merge(yp),$1=kt.merge(Tp),j1=kt.merge(bp),VC=T.object({testId:T.string().optional().default(""),testName:T.string().optional().default(""),suiteId:T.string().optional().default(""),suiteName:T.string().optional().default(""),creditsUsed:T.number().optional(),usedBy:T.string().optional()}),qC=T.object({transactionId:T.string(),timestamp:T.string(),event:T.nativeEnum(Ba),properties:VC}),G1=qC.array(),jg=Eg.omit({steps:!0}).extend({steps:T.array(T.record(T.string(),T.unknown())).describe("unparsed ResolvedStep[]")}),W1=T.object({limit:T.number().max(10).optional(),afterTime:T.number().optional()}),Gg=op.array(),V1=T.object({applied:T.boolean().optional(),appliedAt:T.coerce.date().optional()}),Wg=WC.extend({id:T.string()}),q1=T.object({runGroupId:T.string().uuid().optional()}),Vg=T.object({runGroupId:T.string().uuid()}),qg=T.object({quarantined:T.object({testId:T.string().uuid(),quarantinedAt:T.coerce.date(),quarantinedBy:T.string().optional(),quarantinedReason:T.string()}).array()}),K1=T.object({testId:T.string().uuid(),testName:T.string().optional(),reason:T.string(),gitLocalUsername:T.string().optional(),gitLocalEmail:T.string().optional(),gitLocalName:T.string().optional()}),Y1=T.object({testName:T.string().optional(),reason:T.string().optional(),gitLocalUsername:T.string().optional(),gitLocalEmail:T.string().optional(),gitLocalName:T.string().optional()}),X1=kt.merge(Rp),J1=kt.merge(Cp),Q1=T.object({apkToInstall:T.object({channel:T.string(),tag:T.string().optional()}).optional(),hostname:T.string().optional()}),Kg=T.object({name:T.string(),webRtcUrl:T.string(),adbUrl:T.string(),token:T.string(),apkDownloadUrl:T.string().optional(),region:T.string().optional()}),Z1=T.object({channel:T.string(),tag:T.string(),md5:T.string()}),Yg=T.object({id:T.string(),uploadUrl:T.string().optional(),downloadUrl:T.string(),md5:T.string().optional()}),Xg=T.object({assets:T.array(T.object({channel:T.string(),tag:T.string(),md5:T.string(),createdAt:T.number().describe("Unix timestamp in milliseconds")}))});import{z as Y}from"zod";var n$=Y.object({localTestId:Y.string(),quarantinedAt:Y.date(),quarantinedBy:Y.string().optional(),quarantinedReason:Y.string(),quarantinedByGitEmail:Y.string().optional(),quarantinedByGitName:Y.string().optional(),quarantinedByGitUsername:Y.string().optional()}).or(Y.object({cloudTestId:Y.string(),quarantinedAt:Y.date(),quarantinedBy:Y.string().optional(),quarantinedReason:Y.string(),quarantinedByGitEmail:Y.string().optional(),quarantinedByGitName:Y.string().optional(),quarantinedByGitUsername:Y.string().optional()})),Jg=(n=>(n.QUARANTINE="QUARANTINE",n.UNQUARANTINE="UNQUARANTINE",n))(Jg||{});var fd=Y.object({name:Y.string(),description:Y.string().nullish(),effect:Y.nativeEnum(Jg),labels:Y.array(Y.string()),githubRepository:Y.string().nullish(),gitlabProjectPath:Y.string().nullish(),gitBranchName:Y.string().nullish()}),KC=Y.object({type:Y.literal("LAST_N_RUNS"),lastN:Y.number().min(1).max(10)}),YC=Y.object({type:Y.literal("LAST_N_HOURS"),lastN:Y.number().min(1).max(24)}),XC=Y.object({type:Y.literal("LAST_N_DAYS"),lastN:Y.number().min(1).max(7)}),Sd=Y.discriminatedUnion("type",[KC,YC,XC]),JC=Y.object({flakeRateThreshold:Y.number().min(1).max(100),evaluationWindow:Sd}),QC=fd.extend({type:Y.literal("FLAKE_RATE"),config:JC}),ZC=Y.object({passRateThreshold:Y.number().min(1).max(100),evaluationWindow:Sd}),ev=fd.extend({type:Y.literal("PASS_RATE"),config:ZC}),tv=Y.object({failureCountThreshold:Y.number().min(0),evaluationWindow:Sd}),nv=fd.extend({type:Y.literal("FAILURE_COUNT"),config:tv}),r$=Y.discriminatedUnion("type",[QC,ev,nv]);import{z as nt}from"zod";var i$=nt.object({repositoriesIndexed:nt.boolean(),indexingInProgress:nt.boolean(),indexesOutdated:nt.boolean()}),Qg=(i=>(i.Queued="queued",i.InProgress="in_progress",i.Completed="completed",i.Waiting="waiting",i.Requested="requested",i.Pending="pending",i))(Qg||{}),Zg=(s=>(s.Success="success",s.Failure="failure",s.Neutral="neutral",s.Cancelled="cancelled",s.Skipped="skipped",s.TimedOut="timed_out",s.ActionRequired="action_required",s))(Zg||{}),s$=nt.object({name:nt.string(),status:nt.nativeEnum(Qg),conclusion:nt.nativeEnum(Zg).nullable()}),Ya=nt.object({sha:nt.string(),message:nt.string(),author:nt.object({name:nt.string().optional(),email:nt.string().optional(),date:nt.coerce.date().optional()}),committer:nt.object({name:nt.string().optional(),email:nt.string().optional(),date:nt.coerce.date().optional()})});import{z as De}from"zod";var eh=De.object({orgId:De.string(),cacheKeys:De.string().array()}),d$=De.object({keyParams:eh,clientMetadata:De.string(),lockAcquisitionTimeoutMs:De.number().optional()}),th=De.object({acquired:De.boolean(),acquiredByMetadata:De.string(),keyPrefix:De.string()}),u$=De.object({keyPrefix:De.string(),result:De.string(),ttlMs:De.number()}),m$=De.union([De.object({keyPrefix:De.string()}),eh]),rv=De.object({remainingTtlMs:De.number(),value:De.string().nullish()}),p$=De.object({results:De.record(De.string(),rv),activeLocks:De.string().array()}),nh=0,rh=5*60*1e3;var S$=90*24*60*60*1e3,y$=7*24*60*60*1e3;import{z as oh}from"zod";var w$=oh.object({quarantineNotifications:oh.string().nullish()});import{z as dt}from"zod";var ov=dt.object({version:dt.string(),json:dt.record(dt.unknown()),hash:dt.string()}),ah=dt.record(dt.unknown()),v$=dt.object({newSvgs:dt.array(ov),metadata:ah.optional()}),av=dt.object({version:dt.string(),json:dt.record(dt.unknown()).nullish(),hash:dt.string(),description:dt.string().nullish(),metadata:ah.nullish()}),ih=dt.record(dt.string().describe("icon hash"),av);import{z as ze}from"zod";var yd=ze.object({assertion:ze.string().describe("A human readable assertion that evaluates to either true or false depending on the state of the system.")}),iv=ze.object({instruction:ze.string().describe("Human readable instruction to execute the step. Instructions should only describe concrete actions that need to be taken. Any checks or assertions should be described in the preConditions, postConditions, or expectedResults."),expectedResults:yd.array().optional().describe("Human readable description of the expected results after the step is executed. Each expected result should contain a single assertion that evaluates to true or false.")}),sh=iv.extend({subSteps:ze.lazy(()=>sh.array().optional()).describe("More granular steps to be take to achieve the current step's higher level objective.")}),lh=ze.object({name:ze.string().describe("Short name describing the test plan"),description:ze.string().nullish().transform(t=>t??void 0).describe("Longer form description of the high level goal of the test plan")}),ch=lh.extend({id:ze.string(),createdAt:ze.coerce.date(),updatedAt:ze.coerce.date(),updatedBy:ze.string(),createdBy:ze.string(),test:ze.object({id:ze.string(),name:ze.string()}).nullish().transform(t=>t??void 0)}),P$=ch.extend({testGenRuns:ze.tuple([]).or(ze.tuple([ze.object({id:ze.string(),startedAt:ze.coerce.date(),status:ze.nativeEnum(le)})]))}),dh=ze.object({preConditions:yd.array().nullish().transform(t=>t??[]),postConditions:yd.array().nullish().transform(t=>t??[]),steps:sh.array().nullish().transform(t=>t??[])}),M$=ch.extend({plan:dh.nullish().transform(t=>t??{preConditions:[],postConditions:[],steps:[]})}),sv=lh.extend({plan:dh.nullish().transform(t=>t??{preConditions:[],postConditions:[],steps:[]})}),L$=sv.array().nullish().transform(t=>t??[]);import{validator as lv}from"@exodus/schemasafe";function uh(t){let e;try{e=JSON.parse(t)}catch(n){return`The schema is not valid JSON. ${n}`}try{lv(e)}catch(n){return`The schema is not a valid JSON schema. ${n}`}}var mh=t=>{t.extraHeaders&&(t.extraHeaders=Object.fromEntries(Object.entries(t.extraHeaders).filter(([e,n])=>e.trim()&&n.trim())))};import{z as K$}from"zod";var As=class{async resolveStepCacheEntries(){}async saveStepCacheEntries(){}};import{z as q}from"zod";var cv=q.object({step:Ge,status:q.nativeEnum(Ee),startedAt:q.coerce.date(),finishedAt:q.coerce.date().optional(),healMetadata:q.object({healType:q.nativeEnum(Na).or(q.literal("AI")),healedAt:q.coerce.date()}).optional(),beforeSnapshotId:q.string().uuid().optional(),afterSnapshotId:q.string().uuid().optional(),message:q.string().optional()}),mj=cv.extend({finishedAt:q.coerce.date().optional().transform(t=>t??new Date)}),ph="1.0.0",bd=Ug.extend({id:q.string().uuid().optional(),startedAt:q.coerce.date(),runAttemptSchemaVersion:q.string().optional(),schemaVersion:q.string().optional().default("1.0.19"),results:q.record(q.string(),q.unknown()).array().optional(),beforeResults:q.record(q.string(),q.unknown()).array().optional(),afterResults:q.record(q.string(),q.unknown()).array().optional()}),gh=bd.extend({finishedAt:q.coerce.date().optional().transform(t=>t??new Date)}),pj=bd.merge(_a),gj=gh.merge(_a),hh=q.object({results:q.array(ms),beforeResults:q.array(ms).optional(),afterResults:q.array(ms).optional()}),hj=bd.merge(hh),fj=gh.merge(hh),dv=Fg.merge(_g).extend({executionType:q.nativeEnum(ko).optional().default("WEB"),testId:q.string().uuid(),testDescription:q.string().optional(),runGroupId:q.string().uuid(),status:q.nativeEnum(le),startedAt:q.coerce.date(),attempts:q.number(),failureRecoveryDetails:q.record(q.unknown()).optional()}),Sj=dv.extend({finishedAt:q.coerce.date().optional().transform(t=>t??new Date)}),uv=Ng.merge(kg).extend({id:q.string().uuid().optional(),startedAt:q.coerce.date(),cliVersion:q.string(),labels:q.string().array().optional().default([])}),Xa=uv.extend({updatedAt:q.coerce.date().optional().transform(t=>t??new Date),finishedAt:q.coerce.date().optional().transform(t=>t??new Date)});function fh(t){try{return mv(t)&&pv(t).isDirectory()}catch(e){return S.error({err:e},`Error reading path ${t} during directory existence check`),!1}}import{confirm as vv,input as Av}from"@inquirer/prompts";import{existsSync as xv,mkdirSync as Iv,statSync as Pv}from"fs";import{dirname as Mv}from"path";import An,{supportsColor as Rv}from"chalk";import{Console as Sh}from"console";import{format as Ja}from"util";var Td=class extends Error{constructor(e,n,r){let o=Error.stackTraceLimit;r&&(Error.stackTraceLimit=Math.max(r,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,n),Error.stackTraceLimit=o}},xs=class t extends Sh{_buffer=[];_groupDepth=0;Console=Sh;constructor(){super({write:e=>(t.write(this._buffer,"log",e),!0)})}static write(e,n,r,o=2){let a=new Td(void 0,t.write).stack;if(!a)return e;let i=a.split(`
12
12
  `).slice(o).filter(Boolean).join(`
13
- `);return e.push({message:r,origin:a,type:n}),e}_log(e,n){t.write(this._buffer,e," ".repeat(this._groupDepth)+n,3)}debug(e,...n){this._log("debug",Ki(e,...n))}error(e,...n){this._log("error",Ki(e,...n))}info(e,...n){this._log("info",Ki(e,...n))}log(e,...n){this._log("log",Ki(e,...n))}warn(e,...n){this._log("warn",Ki(e,...n))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function lh(t){let e=globalThis.console,n=new Es;globalThis.console=n;try{t()}finally{let o=n.getBuffer()?.map(i=>i.message).join(`
13
+ `);return e.push({message:r,origin:i,type:n}),e}_log(e,n){t.write(this._buffer,e," ".repeat(this._groupDepth)+n,3)}debug(e,...n){this._log("debug",Ja(e,...n))}error(e,...n){this._log("error",Ja(e,...n))}info(e,...n){this._log("info",Ja(e,...n))}log(e,...n){this._log("log",Ja(e,...n))}warn(e,...n){this._log("warn",Ja(e,...n))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function yh(t){let e=globalThis.console,n=new xs;globalThis.console=n;try{t()}finally{let o=n.getBuffer()?.map(a=>a.message).join(`
14
14
  `);process.stderr.write(`${o}
15
- `),globalThis.console=e}}var Ke=" ".repeat(6);function ch(t,e="",n=!1){let r=process.stdout?.columns||process.stderr?.columns||80,o=Math.max(r-e.length,20),i=t.split(`
16
- `),a=[];for(let s of i)if(n){let l=s;for(;l.length>o;){let d=l.slice(0,o+1).lastIndexOf(" "),u=d>-1?d:o;a.push(e+l.slice(0,u)),l=l.slice(u).trimStart()}a.push(e+l)}else{let l=s.split(" "),c="";for(let d of l){if(!c.length){c=d;continue}let u=`${c} ${d}`;u.length<=o?c=u:(a.push(e+c),c=d)}a.push(e+c)}return a.join(`
17
- `)}import rv from"os";import dh,{multistream as ov}from"pino";import iv from"pino-pretty";import av from"pino-std-serializers";var Yi=new Map,sv=!0,uh="Log throttle exceeded",lv=100,cv=5e3,pd=class t{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=!1;lastWindowStart=Date.now();site="https://ingest.us.signoz.cloud:443/logs/json";flushIntervalMs;maxBatchSize;buffer=[];flushTimer;constructor({bindings:e,hostname:n,disableConsoleLogs:r,flushIntervalMs:o,maxBatchSize:i}){this.hostname=n??rv.hostname(),this.disableConsoleLogs=r,this.bindingAttributes={...e,env:"production"},this.flushIntervalMs=o??5e3,this.maxBatchSize=i??10;let a={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=sv?dh(a):dh(a,ov([{stream:iv({colorize:!0})}]))}getLevel(){return bs[this.minLevelValue]}child(e){return new t({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}flush(e){this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush(e)}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushBuffer()},this.flushIntervalMs))}async flushBuffer(){if(this.buffer.length===0)return;let e=this.buffer;this.buffer=[];try{let n=await fetch(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:ji(e)});if(!n.ok)throw new Error(`Got error status (${n.statusText}) from SigNoz`)}catch(n){this.consoleLogger.warn({err:n},"Failed to log to SigNoz")}}shouldAllowLog(e){if(e===uh)return!0;let n=Date.now();return n-this.lastWindowStart>cv&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,uh),this.droppedLogsInWindow=!1,this.lastWindowStart=n),this.logsInCurrentWindow<lv?(this.logsInCurrentWindow++,!0):(this.droppedLogsInWindow=!0,!1)}log(e,n,r,...o){try{this.logHelper(e,n,r,...o)}catch(i){this.consoleLogger.warn(`Failed to log to Signoz: ${i}`)}}logHelper(e,n,r,...o){if(Gi[e]<this.minLevelValue||!this.shouldAllowLog(r))return;typeof n=="string"&&!r&&(n={message:n}),typeof n=="object"&&n&&"err"in n&&n.err instanceof Error&&(n.err=av.err(n.err));let i={...this.bindingAttributes,...n&&typeof n=="object"?n:{},...o.length>0?{args:o}:{}},a={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](i,r,...o);let s={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:a,attributes:{},body:dg({message:r||"",...i})};this.buffer.push(s),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let n=this.bindingAttributes.app;this.bindingAttributes.app=e,Yi.set("app",this),Yi.delete(n)}debug(e,n,...r){this.log("debug",e,n,...r)}info(e,n,...r){this.log("info",e,n,...r)}warn(e,n,...r){this.log("warn",e,n,...r)}error(e,n,...r){this.log("error",e,n,...r)}bindings(){return this.bindingAttributes}addBinding(e,n){this.bindingAttributes[e]=n}setMinLevel(e){typeof e=="number"?(this.minLevelValue=e,this.consoleLogger.level=bs[e]):(this.minLevelValue=Gi[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Cs=({app:t,hostname:e,disableConsoleLogs:n})=>(Yi.has(t)||Yi.set(t,new pd({bindings:{app:t},hostname:e,disableConsoleLogs:n})),Yi.get(t));import{hostname as dv}from"os";var X=Cs({app:"cli",hostname:dv(),disableConsoleLogs:!0}).child({cliVersion:"2.15.2"});var mv=5;async function vs({getResults:t,checkDone:e,name:n,timeoutMs:r=18e5}){let o=Date.now(),i=0;for(;Date.now()-o<r;){let a;i>mv&&(y.error(`Failed to fetch ${n} status too many times.`),process.exit(1));try{a=await t(),i=0}catch(c){i++,X.warn({err:c},"Failed to fetch run status, retrying..."),y.warn({err:c},"Failed to fetch run status, retrying..."),await new Promise(d=>setTimeout(d,1500*i));continue}if(e(a))return a;let l=Math.max(1e4,Math.floor(r/100));await new Promise(c=>setTimeout(c,l))}y.error(`Timeout elapsed waiting for ${n} to complete (${Math.floor(r/1e3)}s).`),process.exit(1)}function Go({results:t,startTime:e,entity:n,getDisplayLine:r,onFailed:o}){let i=t.filter(d=>d.status==="PASSED"&&d.quarantined),a=t.filter(d=>d.status==="PASSED"&&!d.quarantined),s=t.filter(d=>d.status==="FAILED"&&d.quarantined),l=t.filter(d=>d.status==="FAILED"&&!d.quarantined),c=t.filter(d=>d.status==="CANCELLED");return lh(()=>{if(l.forEach(d=>{y.log(""),o(d)}),l.length){y.log("");let d=l.length===1?"":"s";y.error(`${l.length} ${n}${d} failed:`),l.forEach(u=>{y.dimmed(r(u))})}if(c.length){y.log("");let d=c.length===1?"":"s";y.warn(`${c.length} ${n}${d} cancelled:`),c.forEach(u=>{y.dimmed(r(u))})}if(a.length){y.log("");let d=a.length===1?"":"s";y.success(`${a.length} ${n}${d} passed:`),a.forEach(u=>{y.dimmed(r(u))})}if(s.length){y.log("");let d=s.length===1?"":"s";y.warn(`${s.length} quarantined ${n}${d} failed:`),s.forEach(u=>{y.dimmed(r(u))})}if(i.length){y.log("");let d=i.length===1?"":"s";y.warn(`${i.length} quarantined ${n}${d} passed:`),i.forEach(u=>{y.dimmed(r(u))})}y.log(""),y.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:i.length,passed:a.length,quarantinedFailed:s.length,failed:l.length,cancelled:c.length}}var As=(t,e)=>{if(!t.failureDetails||!t.failureReason)return;let n=Ga[t.failureDetails?.classification?.reason||t.failureReason],r=t.failureDetails?.classification?.summary||Mo[t.failureReason],o=t.failureDetails.classification?.rootCause;if(y.error(e),o){y.log(`${Ke}- Error type: ${vn.dim(n)}`);let i="- Root cause analysis:",a=ch(`${i} ${o}`,`${Ke} `,!1),s=a.indexOf(":");y.log(`${Ke}${i} ${vn.dim(a.slice(s+1))}`)}else y.log(`${Ke}Reason: ${vn.red(n)}`),y.log(`${Ke}Description: ${vn.red(r)}`)},Xi=({status:t,testLogRef:e,getRunningTestsCount:n,getTotalTestsCount:r,additionalText:o})=>{t=t.toUpperCase();let i=t,a;t.includes("FAIL")?(i=vn.bgRed.white("FAIL"),a=3):t.includes("PASS")?(i=vn.bgGreen.white("PASS"),a=3):t.includes("START")?(i=vn.bgBlue.white("START"),a=2):t.includes("CANCEL")?(i=vn.bgRgb(191,68,11).white("CANCEL"),a=1):t.includes("RETRY")?(i=vn.bgRgb(191,68,11).white("RETRY"),a=2):t.includes("RUN")||t.includes("PROG")?(i=vn.bgMagenta.white("RUNNING"),a=0):(y.warn(`Unknown status tried to be logged in run test locally: ${t}`),a=0),uv||(i=`${i}`),y.log(`${i}${" ".repeat(a)} ${e} ${o?`${o} `:""}(${n()}/${r()})`)};var bv=!1,ph=(()=>{try{return Sv("/.dockerenv"),!0}catch{return!1}})();async function bt(t,e){return Ti||bv||ph?!0:(y.flush(),X.flush(),await new Promise(r=>setTimeout(r,500)),await pv({message:t}))}async function gd(t){let e=yv(t);return ah(e)?hv(t)?bt(`File '${mh(t)}' already exists. Overwrite existing content?`,!0):!0:await bt(`Directory '${mh(e)}' doesn't exist. Create it now?`,!0)?(fv(e,{recursive:!0}),!0):!1}function mh(t){return t.replace(/(\s+)/g,"\\$1")}async function gh(t,e){return Ti||ph?e:(await gv({message:t,default:e})).trim()||e}import Tv from"fs";import{tmpdir as wv}from"os";import Ev from"path";import{registry as Ji}from"playwright-core/lib/server";import hh from"proper-lockfile";var fh=Ev.join(wv(),"momenticBrowserInstallation");var hd=["chrome","chromium","chrome-for-testing"],Cv={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},Sh={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function yh(t){let e=Sh[Cv[t]??""]??"",n=Ji.findExecutable(e);return!n||n.installType==="none"?!1:fd(n)}function fd(t){let e=t.executablePath();return Tv.existsSync(e)}function Rv(t,e){let n=Sh[t];if(!n)throw new Error(`Requested install of unknown browser type ${t}`);let r=Ji.findExecutable(n);if(!r||r.installType==="none")throw new Error(`Requested install of unknown browser type ${t}`);if(!(!e&&fd(r)))return r}async function vv({browser:t,force:e}){let n=Rv(t,e);if(!n){y.info(`Browser '${t}' is already installed, skipping...`);return}y.info(`Installing browser '${t}'...`);try{await Ji.installDeps([n],!1),await Ji.install([n],!1)}catch(r){if(r.message.includes("Lock file is already being held")){y.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=Ji.findExecutable(t),i=5*60*1e3,a=Date.now();for(;Date.now()-a<i&&!fd(o);)y.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw r}}async function bh({rawBrowsers:t,force:e=!1,all:n=!1}){let r=n?hd:Array.from(new Set(t));try{await hh.lock(fh,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(i){y.warn(`Failed to acquire lock to install browsers. Please ensure that any other process installing browsers completes within 5 minutes: ${i}. Continuing without installation...`);return}let o;try{for(let i of r)try{await vv({browser:i,force:e})}catch(a){o=a,y.error(`Failed to install the ${i} browser: ${a}`)}}finally{await hh.unlock(fh,{realpath:!1})}if(o)throw o}import{randomUUID as HO}from"crypto";import _b from"body-parser";import MM from"cors";import OM from"dedent";import{Router as gA}from"express";import xt from"fs";import{globSync as hA}from"glob";import lt from"path";import Md from"fs";import{z as yd}from"zod";var B="v1",Qi="2.15.2";var mr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Th=t=>{let e=t.reason===void 0?new DOMException("This operation was aborted.","AbortError"):t.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function z(t,e){let{milliseconds:n,fallback:r,message:o,customTimers:i={setTimeout,clearTimeout}}=e,a,s;if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);return new Promise((l,c)=>{if(e.signal){let{signal:u}=e;if(u.aborted)return c(Th(u));s=()=>c(Th(u)),u.addEventListener("abort",s)}let d=()=>{if(r)try{l(r())}catch(u){c(u)}else{typeof t.cancel=="function"&&Promise.resolve().then(()=>t.cancel()).catch(()=>{});let u=o instanceof Error?o:new mr(o??`Promise timed out after ${n}ms`);c(u)}};a=i.setTimeout(d,n),Promise.resolve(t).then(u=>l(u)).catch(u=>c(u))}).finally(()=>{i.clearTimeout(a),e.signal&&s&&e.signal.removeEventListener("abort",s)})}var xs=class{limit;windowMs;userActions;constructor(e,n){this.limit=e,this.windowMs=n,this.userActions=new Map}_cleanup(e,n="DEFAULT_USER"){let r=Date.now(),o=`${n}:${e}`;if(this.userActions.has(o)){let a=this.userActions.get(o)?.filter(s=>r-s<=this.windowMs)??[];a.length>0?this.userActions.set(o,a):this.userActions.delete(o)}}increment(e,n="DEFAULT_USER"){let r=Date.now(),o=`${n}:${e}`;this._cleanup(n,e),this.userActions.has(o)||this.userActions.set(o,[]);let i=this.userActions.get(o);return i.length>=this.limit?!0:(i.push(r),!1)}};var Av=9e4,xv=3,Iv=1500,Pv=15e3,ln=class extends Error{status;rawError;constructor(e,n,r,o={}){super(r,o),this.status=e,this.rawError=n}};async function Lv(t){return t.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var Sd=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return Qi&&(e[pg]=Qi),e}async sendRequest(e,n){let{retries:r=xv,requestTimeoutMs:o=Av,initialRetryDelayMs:i=Iv,maxRetryDelayMs:a=Pv}=n,s=r,l=r,c,d={path:e,baseUrl:this.baseUrl,method:n.method};for(;s>0;)try{return s--,await this.sendSingleRequestHelper(e,n,o)}catch(u){if(c=u,u instanceof ln&&u.status>=400&&u.status<500)throw u;if(u instanceof Error&&u.name==="AbortError"&&(c=new mr),s===0)throw c;let m=l-s,g=Math.min(i*Math.pow(2,m-1),a);await new Promise(p=>setTimeout(p,g))}throw this.logger.warn({...d,err:c},"Got fatal error response from Momentic server"),c}async sendSingleRequestHelper(e,n,r){let o={path:e,baseUrl:this.baseUrl,method:n.method},i=new AbortController,a=setTimeout(()=>i.abort(),r),s=()=>i.abort();n.signal&&n.signal.addEventListener("abort",s);let l={...this.getHeaders(),...n.extraHeaders};try{let c=await fetch(`${this.baseUrl}${e}`,{method:n.method,body:n.body?JSON.stringify(n.body):void 0,headers:l,signal:i.signal});if(!c.ok){let u=await Lv(c);throw new ln(c.status,u,`Request to ${n.method} ${e} failed with status ${c.status}: ${u}`)}let d;if(c.status===204)d={};else{let u=await c.text();try{d=JSON.parse(u)}catch{d=u}}return this.logger&&n.logResponse===!0&&d&&this.logger.debug({result:d,status:c.status,...o},"Got response from Momentic server"),d}finally{clearTimeout(a),n.signal&&n.signal.removeEventListener("abort",s)}}},At=class extends Sd{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var Je=class extends At{constructor(e){super(e)}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${B}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});return Lg.parse(e)}async bulkGetRunStatus(e){let n=await this.sendRequest(`/${B}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Ag.parse(n)}async getTestYAMLExport(e){let n=await this.sendRequest(`/${B}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return bg.parse(n)}async updateStepCaches(e,n){await this.sendRequest(`/${B}/cache`,{method:"PATCH",body:e,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,n){let r=await this.sendRequest(`/${B}/cache`,{method:"POST",body:e,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return wg.parse(r)}async updateMobileStepCaches(e,n){await this.sendRequest(`/${B}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,n){let r=await this.sendRequest(`/${B}/mobile-cache`,{method:"POST",body:e,extraHeaders:n,retries:10,logResponse:!0,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Eg.parse(r)}async queueTests(e){let n=await this.sendRequest(`/${B}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return yg.parse(n)}async uploadScreenshot(e){let n=await this.sendRequest(`/${B}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Pg.parse(n)}async getAllEnvironments(){let e=await this.sendRequest(`/${B}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Mg.parse(e)}async acquireCacheLock(e,n){let r=await this.sendRequest(`/${B}/result-cache/lock`,{method:"POST",body:e,signal:n,retries:3,requestTimeoutMs:3e4});return Wg.parse(r)}async releaseCacheLock(e){await this.sendRequest(`/${B}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${B}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${B}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${B}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(n){if(n instanceof Error&&n.message.includes("404"))return null;throw n}}async queueSuiteRuns(e){let n=await this.sendRequest(`/${B}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Og.parse(n)}async bulkGetRunGroupStatus(e){let n={runGroupIds:e},r=await this.sendRequest(`/${B}/run-groups/status`,{method:"POST",body:n,retries:3,requestTimeoutMs:5e3});return Qm.array().parse(r)}async uploadProposedSteps(e,n){try{await this.sendRequest(`/${B}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(r){n.error({err:r},"Failed to upload proposed steps")}}async reportBillableEvents(e,n){try{await this.sendRequest(`/${B}/billing/events`,{method:"POST",body:n,retries:10,requestTimeoutMs:1e4})}catch(r){e.error({err:r},"Failed to report billable event")}}async fetchTestFragment(e){let n=await this.sendRequest(`/${B}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ng.parse(n)}async patchTestFragment(e,n){await this.sendRequest(`/${B}/test-fragments/${e}`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,n){let r=await this.sendRequest(`/${B}/results/tests/${e}`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return kg.parse(r)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${B}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return _g.parse(e)}async startProcessingResultsUpload(e,n){let r=await this.sendRequest(`/${B}/results/uploads/${e}/process`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return Dg.parse(r)}async fetchIconKnowledgeBase(e){try{let n=await this.sendRequest(`/${B}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Xg.parse(n)}catch(n){return e.error({err:n},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,n){try{await this.sendRequest(`/${B}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(r){n.error({err:r},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,n,r,o){let i=new URLSearchParams;i.set("base",r),i.set("head",o);let a=await this.sendRequest(`/${B}/git/github/${e}/${n}/merge-base-commit?${i.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Vi.parse(a)}async getCommitFromGithub(e,n,r){let o=await this.sendRequest(`/${B}/git/github/${e}/${n}/commits/${r}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Vi.parse(o)}async getMergeBaseCommitFromGitlab(e,n,r){let o=new URLSearchParams;o.set("base",n),o.set("head",r);let i=await this.sendRequest(`/${B}/git/gitlab/${e}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Vi.parse(i)}async getCommitFromGitlab(e,n){let r=await this.sendRequest(`/${B}/git/gitlab/${e}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Vi.parse(r)}async getAgentConfig(){let e=await this.sendRequest(`/${B}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return yd.record(yd.string(),yd.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${B}/quarantine`,{method:"GET"});return Fg.parse(e)}async quarantineTest(e,n,r){await this.sendRequest(`/${B}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:n,...r??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,n,r){await this.sendRequest(`/${B}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:n,...r??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let n=await this.sendRequest(`/${B}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Ug.parse(n)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${B}/limbar/android/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAndroidAssetUrls({channel:e,tag:n,md5:r}){let o={channel:e,tag:n,md5:r},i=await this.sendRequest(`/${B}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return Bg.parse(i)}async deleteAndroidEmulator(e){await this.sendRequest(`/${B}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${B}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return zg.parse(e)}async deleteAndroidAsset(e,n){await this.sendRequest(`/${B}/limbar/assets/${e}/${n}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function bd(t){let e=process.versions.node,n=parseInt(e.split(".")[0]);(isNaN(n)||n<18)&&(y.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),y.debug(`Identified node version ${e}`);let r=await t.client.getAuthInfo();return y.debug("Got auth info from API"),r}import{randomUUID as wh}from"crypto";var Is=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvent(e,n,r){try{return await this.apiClient.reportBillableEvents(e,[{event:n,timestamp:new Date().toISOString(),transactionId:r?.eventId??wh(),properties:$c({},r)}])}catch(o){e.error({err:o},"Failed to report billable event")}}async reportCreditsUsed(e,n,r,o){if(r)try{return await this.apiClient.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:o?.eventId??wh(),properties:$c({creditsUsed:r,usedBy:n},o)}])}catch(i){e.error({err:i},"Failed to report credits used")}}};var Wo=class{constructor(e,n){this.client=e;this.orgId=n}async acquireCacheLock(e,n){return this.client.acquireCacheLock(e,n)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}fetchIconKnowledgeBase(e){return this.client.fetchIconKnowledgeBase(e)}saveNewIcons(e,n){return this.client.saveNewIcons(e,n)}};import{Faker as Mv,en as Ov}from"@faker-js/faker";var Vo="v1",pr=class{httpClient;fakerInstance;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this)};ai={generate:this.sendAiGenerate.bind(this)};constructor(e){this.httpClient=e.httpClient,e.fakerSeed&&(this.fakerInstance=new Mv({locale:Ov}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let n=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Vo}/tools/ai/generate`,{method:"POST",body:n}).catch(r=>{throw r instanceof ln?new Error(r.rawError):new Error(`Failed to send AI generation: ${r.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Vo}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(n=>{throw n instanceof ln?new Error(n.rawError):new Error(`Failed to send sms: ${n.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Vo}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(n=>{throw n instanceof ln?new Error(n.rawError):n})}async sendEmail(e){return this.httpClient.sendRequest(`/${Vo}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(n=>{throw n instanceof ln?new Error(n.rawError):new Error(`Failed to send email: ${n.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Vo}/tools/email/fetchAll`,{method:"POST",body:e}).catch(n=>{throw n instanceof ln?new Error(n.rawError):new Error(`Failed to fetch all emails: ${n.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Vo}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(n=>{throw n instanceof ln?new Error(n.rawError):new Error(`Failed to fetch latest emails: ${n.message}`)})}};import{z as Nv}from"zod";var qo=class extends At{agentConfig;constructor(e,n){super(n),this.agentConfig=e}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,n){let r={...e,loggerTags:n.loggerTags},o=await this.sendRequest(`/${B}/web-agent/recommend-chunks-ai`,{method:"POST",body:r,signal:n.abortSignal});return op.parse(o)}async rankChunksWithRag(e,n){let r=await this.sendRequest(`/${B}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:Qi,...e},signal:n.abortSignal});return rp.parse(r)}async getScreenshotFromS3(e){let n=await this.sendRequest(`/${B}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return Nv.string().parse(n)}async getElementLocation(e,n){let r={...e,disableCache:n.disableCache,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${B}/web-agent/locate-element`,{method:"POST",body:r,signal:n.abortSignal});return fg.parse(o)}async getAssertionResult(e,n){let r={...e,disableCache:!!n.disableCache,useConsensus:!!n.useConsensus,attemptNumber:n.attemptNumber,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${B}/web-agent/assertion`,{method:"POST",body:r,signal:n.abortSignal});return ad.parse(o)}async getLintStepResult(e,n){let r={...e,disableCache:!!n.disableCache,loggerTags:n.loggerTags},o=await this.sendRequest(`/${B}/web-agent/lint/step`,{method:"POST",body:r,signal:n.abortSignal});return hg.parse(o)}async getVisualAssertionResult(e,n){let r={...e,disableCache:!!n.disableCache,useConsensus:!!n.useConsensus,attemptNumber:n.attemptNumber,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${B}/web-agent/visual-assertion`,{method:"POST",body:r,signal:n.abortSignal});return ad.parse(o)}async getAiActionCommand(e,n){let r=await this.sendRequest(`/${B}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return gg.parse(r)}async getMultiturnAiActionCommand(e,n){return await this.sendRequest(`/${B}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal})}async getMultiturnAiActionEvaluation(e,n){let r=await this.sendRequest(`/${B}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return Ec.parse(r)}async getReverseMappedDescription(e,n){let r=await this.sendRequest(`/${B}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return Sg.parse(r)}async getTextExtraction(e,n){let r={...e,disableCache:n.disableCache,loggerTags:n.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${B}/web-agent/text-extraction`,{method:"POST",body:r,signal:n.abortSignal});return Tc.parse(o)}async getTestResultClassification(e,n){let r=await this.sendRequest(`/${B}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:n.loggerTags},signal:n.abortSignal});return vc.parse(r)}async getExtractedKeywords(e,n){let r=await this.sendRequest(`/${B}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:n.disableCache,context:e},signal:n.abortSignal});return pp.parse(r)}async getAutohealingProposal(e,n){let r=await this.sendRequest(`/${B}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:n.loggerTags},signal:n.abortSignal});return Om.parse(r)}async getFailureRecoveryProposal(e,n){let r=await this.sendRequest(`/${B}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:n.loggerTags},signal:n.abortSignal});return km.parse(r)}async getFailureRecoveryPlan(e,n){let r=await this.sendRequest(`/${B}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:n.loggerTags},signal:n.abortSignal});return Nm.parse(r)}async getIframeRegex(e,n){let r=await this.sendRequest(`/${B}/web-agent/iframe-regex`,{method:"POST",body:e,signal:n.abortSignal});return um.parse(r)}};var Ko=class extends At{generator;constructor(e,n){super(e),this.generator=n}async runTemplateMatching(e,n={}){let r=await this.sendRequest(`/${B}/web-agent/template-matching`,{method:"POST",body:e,signal:n?.signal});return mm.parse(r)}async constructIframeRegex(e,n={}){return this.generator.getIframeRegex(e,{abortSignal:n.signal})}};function Eh(t,e,n){return fetch(t,{method:"PUT",body:n,headers:{"Content-Type":e}})}var Ps=class{constructor(e){this.client=e}async uploadResultsArchive(e,n){let{uploadUrl:r,id:o}=await this.client.generateTestResultsUploadUrl(),i=await Eh(r,"application/zip",n);if(!i.ok)throw new Error(`Failed to upload test results: ${await i.text()}`);let{runGroupId:a}=await this.client.startProcessingResultsUpload(o,{runGroupId:e});return a}};import{diff as Ah}from"deep-object-diff";function Zi(t){let e={parentChain:[]};return Ls(t,e),e}function Ls(t,e){let{onPresetAction:n,onSimpleStepContainer:r,onConditional:o,earlyStop:i}=t;for(let a of t.steps)switch(a.type){case"PRESET_ACTION":if(n(a,e)&&i)return!0;break;case"CONDITIONAL":if(o?.(a,e)&&i)return!0;e.parentChain.push(a);for(let l of a.blocks)if(n(l.assertion,e)&&i||Ls({...t,steps:l.steps},e)&&i)return!0;if(Ls({...t,steps:a.elseSteps??[]},e)&&i)return!0;e.parentChain.pop();break;case"RESOLVED_MODULE":case"SECTION":case"AI_ACTION":if(r?.(a,e)&&i)return!0;if(a.steps){if(e.parentChain.push(a),Ls({...t,steps:a.steps},e)&&i)return!0;e.parentChain.pop()}break;case"AI_ACTION_DYNAMIC":{if(r?.(a,e)&&i)return!0;break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(a)}}function Ch(t,e,n,r){let o=Array.from(e),i=Array.from(r);for(let s=0;s<o.length;s++){if(o[s]!==i[s])return!1;i.shift()}return!!kv([t],n,i).result}function kv(t,e,n=[]){let r,o=[],i=(a,s)=>{let l=JSON.stringify(s.parentChain.map(d=>d.id)),c=n.length===0?!0:JSON.stringify(n)===l;return a.id===e&&c?(r=a,o=s.parentChain,!0):!1};return Zi({steps:t,earlyStop:!0,onPresetAction:i,onConditional:i,onSimpleStepContainer:i}),{result:r,parentChain:o}}function Rh(t,e){e(t);for(let n in t){let r=t[n];r&&(Array.isArray(r)?Os(r,e):typeof r=="object"&&Rh(r,e))}}function Os(t,e){for(let n of t)n&&(Array.isArray(n)?Os(n,e):typeof n=="object"&&Rh(n,e))}function Td(t,e){if(t.length>e.length)return Td(e,t);for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function Ms(t){for(let e of t.results)switch(e.type){case"PRESET_ACTION":t.onPresetAction(e);break;case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":t.onSimpleStepContainer?.(e),Ms({...t,results:e.results});break;case"CONDITIONAL":t.onConditional?.(e),e.assertionResult&&t.onPresetAction(e.assertionResult),Ms({...t,results:e.results});break;default:throw new Error(`Unsupported result type: ${e.type}`)}}import{cloneDeep as vh}from"lodash-es";import{v4 as wd}from"uuid";async function ze(t){let e=new Map,n=new Set,r=vh(t.stepLists.steps),o=await Kr({...t,steps:r,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:n}),i={stepsToSave:{steps:o.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates};for(let a of["beforeSteps","afterSteps"]){let s=vh(t.stepLists[a]);if(!s)continue;let l=await Kr({...t,steps:s,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:n});i.cachesToSave.push(...l.cachesToSave),i.moduleUpdates.push(...l.moduleUpdates),i.stepsToSave[a]=l.stepsToSave}return i}async function Kr({steps:t,...e}){let{seenModules:n,cacheCreationParams:r,moduleIdParents:o,moduleStepParents:i,moduleIdReplacements:a,shouldCreateNewModuleId:s,createNewCacheIds:l}=e,c={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let d of t)switch(delete d.index,delete d.aiSuggested,d.id=l?wd():d.id,d.type){case"PRESET_ACTION":{let m=d.command;m.id=l?wd():m.id,"cache"in m&&m.cache&&(r&&(c.cachesToSave=c.cachesToSave.concat(Ed({id:m.id,orgId:r.orgId,testId:r.testId,value:Un.parse(m),moduleIdParents:o,moduleStepParents:i}))),delete m.cache),m.thoughts&&delete m.thoughts,c.stepsToSave.push({...d,command:m});break}case"RESOLVED_MODULE":{let m=l?wd():d.id,g=d.moduleId;a.has(g)?g=a.get(g):s!==void 0&&(g=await s(d),a.set(d.moduleId,g));let{cachesToSave:p,stepsToSave:h,moduleUpdates:f}=await Kr({...e,steps:d.steps,cacheCreationParams:r?{...r}:void 0,createNewCacheIds:!1,moduleStepParents:[...i,m],moduleIdParents:[...o,g],skipCacheIntermediateEntries:l});c.moduleUpdates=c.moduleUpdates.concat(f),c.cachesToSave=c.cachesToSave.concat(p),n.has(g)||(n.add(g),c.moduleUpdates.push({...Mt.parse(d),steps:Le.array().parse(h),moduleId:g}));let S=an.parse({...d,type:"MODULE",moduleId:g,inputs:d.inputs,id:m,skipped:d.skipped,cacheConfig:d.cacheConfig,envKey:d.envKey});c.stepsToSave.push(S);break}case"AI_ACTION":{if(!d.steps){c.stepsToSave.push(d);break}let{stepsToSave:m,cachesToSave:g}=await Kr({...e,steps:d.steps});try{d.steps=zt.array().parse(m)}catch(p){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${p}`)}c.stepsToSave.push(d),c.cachesToSave=c.cachesToSave.concat(g);break}case"AI_ACTION_DYNAMIC":{c.stepsToSave.push(d);break}case"CONDITIONAL":{let m=[];for(let p of d.blocks){let{stepsToSave:h,cachesToSave:f,moduleUpdates:S}=await Kr({...e,steps:p.steps});m.push({...p,steps:h}),c.cachesToSave=c.cachesToSave.concat(f),c.moduleUpdates=c.moduleUpdates.concat(S)}let g={...d,elseSteps:void 0,blocks:m};if(d.elseSteps){let{stepsToSave:p,cachesToSave:h,moduleUpdates:f}=await Kr({...e,steps:d.elseSteps});g.elseSteps=p,c.cachesToSave=c.cachesToSave.concat(h),c.moduleUpdates=c.moduleUpdates.concat(f)}c.stepsToSave.push(g);break}case"SECTION":{let{stepsToSave:m,cachesToSave:g,moduleUpdates:p}=await Kr({...e,steps:d.steps}),h={...d,steps:m};c.moduleUpdates=c.moduleUpdates.concat(p),c.stepsToSave.push(h),c.cachesToSave=c.cachesToSave.concat(g);break}default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(d)}return c}function Yo({steps:t,topLevel:e=!0,...n}){let{stepCacheEntries:r,logger:o,keyPrefix:i}=n,a=[],s=[],l=[],c=0,d=(m,g)=>{try{let p=Un.parse(g.value);if(p.type!==m.type){o.warn({parsedCacheEntry:p,command:m},"Not using step cache due to type mismatch"),s.push(g.key);return}m.cache=p.cache,a.push(g.key),l.push(g.uniqueKey)}catch(p){s.push(g.key),o.error({err:p,cacheEntry:g},"Not using step cache due to parsing error")}},u=(m,g)=>{let p=Dv(m.id,g),h=p.find(f=>!!r[f]);if(h)d(m,r[h]);else{if(m.type==="AI_ASSERTION")return;s.push(p[0])}};for(let m of t)switch(m.type){case"RESOLVED_MODULE":{c+=m.steps.length;let{cacheKeysHit:g,cacheKeysMissed:p,uniqueKeysHit:h}=Yo({...n,steps:m.steps,keyPrefix:i?`${i}:${m.id}`:m.id,topLevel:!1});a.push(...g),s.push(...p),l.push(...h);break}case"SECTION":case"AI_ACTION":{if(c+=m.steps?.length??0,!m.steps?.length)break;let{cacheKeysHit:g,cacheKeysMissed:p,uniqueKeysHit:h}=Yo({...n,steps:m.steps,topLevel:!1});a.push(...g),s.push(...p),l.push(...h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!Ua.includes(m.command.type)||(m.command.type==="TYPE"||m.command.type==="MOUSE_DRAG"||m.command.type==="VISUAL_DIFF"||m.command.type==="SCROLL_DOWN"||m.command.type==="SCROLL_UP"||m.command.type==="SCROLL_LEFT"||m.command.type==="SCROLL_RIGHT")&&!m.command.target||"cache"in m.command&&m.command.cache)continue;c++,u(m.command,i);break}case"CONDITIONAL":{for(let g of m.blocks){c++,u(g.assertion.command,i),c+=g.steps.length;let{cacheKeysHit:p,cacheKeysMissed:h,uniqueKeysHit:f}=Yo({...n,steps:g.steps,topLevel:!1});a.push(...p),s.push(...h),l.push(...f)}if(m.elseSteps){c+=m.elseSteps.length;let{cacheKeysHit:g,cacheKeysMissed:p,uniqueKeysHit:h}=Yo({...n,steps:m.elseSteps,topLevel:!1});a.push(...g),s.push(...p),l.push(...h)}break}default:return(p=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(m)}return e&&c&&s.length>0&&o.warn({totalSteps:c,cacheKeysMissed:s,cacheKeysHit:a,uniqueKeysHit:l,cacheEntries:r.length},"Step cache did not fully resolve"),{cacheKeysHit:a,cacheKeysMissed:s,uniqueKeysHit:l}}function xh(t,e){return e?`${e}:${t}`:t}function Dv(t,e){let n=[],r=e?.split(":")??[];for(let o=r.length;o>=0;o--){let i=[...r.slice(o),t];n.push(i.join(":"))}return n.reverse(),n}function Ed(t){let{moduleStepParents:e=[],moduleIdParents:n=[]}=t;if(e.length!==n.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
18
- ${JSON.stringify(n)}`);let r=[];return r.push({key:xh(t.id,e.join(":")),organizationId:t.orgId,value:t.value,testId:t.testId}),r}function Ih(t){let e=new Set;return Os(t,n=>{if("type"in n&&n.type==="RESOLVED_MODULE"&&"moduleId"in n){let r=n.moduleId;typeof r=="string"&&!e.has(r)&&e.add(r)}}),e}function Ns({cmd:t,newTarget:e,key:n,logger:r}){t.type==="DRAG"?n!=="fromTarget"&&n!=="toTarget"?r.error({cmd:t,newTarget:e,key:n},"Attempted to apply invalid cache to DRAG command"):t.cache={...t.cache,[n]:e}:n==="target"&&Cm(t)?t.cache={...t.cache,target:e}:r.error({cmd:t,newTarget:e,key:n},"Invalid target cache application")}function ks(t,e){t.cache={...t.cache,memory:{type:"GCS_TRACES",traces:e}}}async function _s({logger:t,cacheStorage:e,orgId:n,testId:r,originalSteps:o,updatedSteps:i}){let a=Ah(o,i);if(Object.keys(a).length!==0){t.debug({changes:a},"Updating steps caches post-run success");try{let{cachesToSave:s}=await ze({stepLists:i,cacheCreationParams:{testId:r,orgId:n}});await e.saveStepCacheEntries({logger:t,testId:r,entries:s})}catch(s){t.error({err:s},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async function Ds({logger:t,cacheStorage:e,orgId:n,testId:r,originalSteps:o,updatedSteps:i}){let a=Ah(o,i);if(Object.keys(a).length===0)return;t.debug({changes:a},"Updating memory post-run failure");let s={};for(let d of["steps","beforeSteps","afterSteps"]){let u=o[d];if(!u||!u.length)continue;let m=Fv({steps:u});for(let[g,p]of Object.entries(m))s[g]=p}let{cachesToSave:l}=await ze({stepLists:i,cacheCreationParams:{testId:r,orgId:n}}),c=Uv({newEntries:l,originalCachesMap:s,logger:t});if(c.length){t.debug({prunedCaches:c},"Saving pruned memory post-failure");try{await e.saveStepCacheEntries({logger:t,testId:r,entries:l})}catch(d){t.error({err:d},"Failed to save memory after successful execution. This is not critical, but can impact future performance.")}}}function Fv({steps:t}){let e={};return Zi({steps:t,onPresetAction:(n,r)=>{let o=n.command;if(!("cache"in o)||!o.cache)return;let i=r.parentChain.filter(l=>l.type==="RESOLVED_MODULE").map(l=>l.id).join(":"),a=xh(n.id,i),s=Un.parse(o);e[a]=s},onSimpleStepContainer:(n,r)=>{},onConditional:(n,r)=>{}}),e}function Uv({newEntries:t,originalCachesMap:e,logger:n}){let r=[];for(let o of t){let i=e[o.key];if(!i||!i.cache||o.value.type!==i.type)continue;let a=o.value.cache;if(o.value={...i},!a){r.push(o);continue}if("memory"in a&&a.memory)n.debug({cacheKey:o.key,newCacheMemory:a.memory,originalCache:i},"Overwriting assertion cache memory"),o.value.cache={...o.value.cache,memory:a.memory};else if("target"in a&&a.target.memory){let s=Bt.parse(o.value.cache);if(!s)continue;n.debug({cacheKey:o.key,newCacheMemory:a.target.memory,originalCache:i},"Overwriting target cache memory"),s.target.memory=a.target.memory,o.value.cache=s}else if("fromTarget"in a||"toTarget"in a){let s=lc.optional().parse(o.value.cache);if(!s)continue;s.fromTarget&&a.fromTarget&&(s.fromTarget.memory=a.fromTarget.memory),s.toTarget&&a.toTarget&&(s.toTarget.memory=a.toTarget.memory),n.debug({cacheKey:o.key,fromTargetMemory:a.fromTarget?.memory,toTargetMemory:a.toTarget?.memory,originalCache:i},"Overwriting drag cache memory"),o.value.cache=s}r.push(o)}return r}function He(t,e,n=!1){return t.length<e?t:t.slice(0,e-3)+(n?"...TRUNCATED...":"[...]")}var en={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},tn={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},Cd={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},Rd={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};function Bv(t){switch(t.type){case"ELEMENT_CONTENT":return`content ${t.negated?tn[t.operation]:en[t.operation]} '${t.value}'`;case"ELEMENT_ATTRIBUTE":{let n=t.negated?tn[t.operation]:en[t.operation];return t.operation==="EXISTS"?`attribute '${t.attr}' ${n}`:`attribute '${t.attr}' ${n} '${t.value}'`}case"ELEMENT_NAME":{let n=t.negated?tn[t.operation]:en[t.operation];return t.operation==="EXISTS"?`tag name ${n}`:`tag name ${n} '${t.value}'`}case"ELEMENT_STYLE":{let n=t.negated?tn[t.operation]:en[t.operation];return t.operation==="EXISTS"?`style property '${t.property}' ${n}`:`style property '${t.property}' ${n} '${t.value}'`}case"ELEMENT_EXISTENCE":return t.negated?Rd[t.condition]:Cd[t.condition];default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}var T2={CONTENT:"The page"};function zv(t){switch(t.type){case"VALUE":return`the option with value ${t.value}`;case"LABEL":return`the option with label ${t.label}`;case"INDEX":return`the option at index ${t.index}`;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function vd(t){switch(t.type){case"SUBSTRING":return`match substring '${t.url}'`;case"REGEX":return`match regex '${t.regex}'`;case"GLOB":return`match glob '${t.glob}'`;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function Hv(t){switch(t.type){case"CONTENT":return`${t.negated?tn.CONTAINS:en.CONTAINS} '${t.value}'`;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t.type)}}function $n(t,e=!0){switch(t.type){case"SUCCESS":return t.condition?.assertion?`Check success condition: ${t.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${t.goal}`;case"NAVIGATE":return`Go to URL: ${e?He(t.url,30):t.url}`;case"DIALOG":return`Automatically ${t.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 ${t.deltaY?`${t.deltaY}px`:"1 page height"}${t.target?` in the container of: ${ht(t.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${t.deltaY?`${t.deltaY}px`:"1 page height"}${t.target?` in the container of: ${ht(t.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${t.deltaX?`${t.deltaX}px`:"1 page width"}${t.target?` in the container of: ${ht(t.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${t.deltaX?`${t.deltaX}px`:"1 page width"}${t.target?` in the container of: ${ht(t.target)}`:""}`;case"WAIT":return`Wait for ${t.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(t.target?.type==="coordinates")return`Click at coordinates: ${ht(t.target)}`;let r="";return t.target?.elementDescriptor.length?r=` on element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(r=` on element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Click${r}`}case"FOCUS":return`Focus ${ht(t.target)}`;case"BLUR":return`Focus ${ht(t.target)}`;case"DRAG":return`Drag ${ht(t.fromTarget)} onto ${ht(t.toTarget)}`;case"MOUSE_DRAG":return t.target?.type==="description"&&t.target.elementDescriptor?`Click and drag ${ht(t.target)} by ${t.deltaX}px horizontally, ${t.deltaY}px vertically`:`Click and drag mouse by ${t.deltaX}px horizontally, ${t.deltaY}px vertically`;case"TYPE":{let r="";return t.target?.type==="coordinates"?r=` in element at coordinates: ${ht(t.target)}`:t.target?.elementDescriptor.length?r=` in element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(r=` in element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Type '${t.value}'${r||""}`}case"HOVER":{let r="";return t.target.type==="coordinates"?r=` over coordinates: ${ht(t.target)}`:t.target.elementDescriptor.length>0?r=` over element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(r=` over element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Hover${r}`}case"PRESS":return`Press ${t.value}`;case"KEY_DOWN":return`Hold down ${t.value} on the keyboard`;case"KEY_UP":return`Release ${t.value} on the keyboard`;case"SELECT_OPTION":{let r="",o=zv(t.choice);return t.target.type==="coordinates"?r=` from element at coordinates: ${ht(t.target)}`:t.target.elementDescriptor.length>0?r=` from: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(r=` from: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${o}'${r}`}case"TAB":switch(t.action.type){case"SUBSTRING":return`Switch to tab with substring: ${t.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${t.action.pattern}`;case"INDEX":return`Switch to tab at index: ${t.action.index}`;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${t.url}`;case"REQUEST":return`Send ${t.method} request to ${t.url}`;case"GRAPHQL_REQUEST":return`Send GraphQL request to ${t.url}`;case"COOKIE":return`Set cookie: ${t.value}`;case"LOCAL_STORAGE":return`Set local storage: ${t.key}: ${t.value}`;case"JAVASCRIPT":return`Run JavaScript: ${e?He(t.code,30):t.code}`;case"AI_ASSERTION":return`Assertion: '${t.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${t.target?`for element: ${ht(t.target)}`:"for entire page"}`;case"FILE_UPLOAD":return t.fileSource.type==="URL"?`Upload file: ${t.fileSource.url}`:`Upload file: ${t.fileSource.name}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Check the element ${ht(t.target)} ${Bv(t.assertion)}`;case"PAGE_CHECK":return`Check the page ${Hv(t.assertion)}`;case"WAIT_FOR_URL":return`Wait for page URL to ${vd(t.matcher)}`;case"COPY":return"Copy to clipboard";case"PASTE":return"Paste clipboard contents";case"REGISTER_REQUEST_LISTENER":return t.pattern?`Register a listener for network requests that match ${t.pattern}`:"Register a listener for network requests";case"AWAIT_LISTENER":return t.key?`Wait for the listener ${t.key} to resolve`:"Wait for a listener to resolve";case"RECORD_REQUESTS":return t.pattern?`Start recording requests that match ${t.pattern}`:"Start recording network requests";case"GET_RECORDED_REQUESTS":return t.key?`Get the requests that were recorded for ${t.key}`:"Get the requests that were recorded";case"SET_HEADER":return t.name?t.urlPattern?`Set a ${t.name} header for requests that match ${t.urlPattern}`:`Set a ${t.name} header for all requests`:"Set a header";case"OFFLINE_MODE":return t.enable?"Enable offline mode":"Disable offline mode";default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function Ph(t){let e=[];for(let n of t){n.sort((a,s)=>a.timestamp-s.timestamp);let r=[],o,i=1;for(let a of n)o&&o.text===a.text&&o.type===a.type&&JSON.stringify(o.args??null)===JSON.stringify(a.args??null)?i++:(o&&(i>1?o.args&&o.args.length?o.args.push(`(repeated ${i} times)`):o.text+=` (repeated ${i} times)`:r.push(o)),o=a,i=1);o&&r.push(o),e.push(r)}return e}import{cloneDeep as R2}from"lodash-es";import{v4 as L2}from"uuid";import{cloneDeep as $v}from"lodash-es";import _h from"truncate-json";import{cloneDeep as k2,unset as _2}from"lodash-es";function gr(t){switch(t.type){case"AI_ACTION":return`AI action: ${He(t.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${He(t.text,100)}`;case"PRESET_ACTION":return $n(t.command);case"MODULE":return`Module: ${t.id}`;case"RESOLVED_MODULE":return`Module: ${t.name}`;case"CONDITIONAL":return"Conditional step";case"SECTION":return`Section${t.description?`with goal: ${He(t.description,100)}`:""}`;default:return(n=>{throw new Error("You missed a case in the switch above")})(t)}}function Yr(t,e){return t.split(`
15
+ `),globalThis.console=e}}var Ke=" ".repeat(6);function bh(t,e="",n=!1){let r=process.stdout?.columns||process.stderr?.columns||80,o=Math.max(r-e.length,20),a=t.split(`
16
+ `),i=[];for(let s of a)if(n){let l=s;for(;l.length>o;){let d=l.slice(0,o+1).lastIndexOf(" "),u=d>-1?d:o;i.push(e+l.slice(0,u)),l=l.slice(u).trimStart()}i.push(e+l)}else{let l=s.split(" "),c="";for(let d of l){if(!c.length){c=d;continue}let u=`${c} ${d}`;u.length<=o?c=u:(i.push(e+c),c=d)}i.push(e+c)}return i.join(`
17
+ `)}import hv from"os";import Th,{multistream as fv}from"pino";import Sv from"pino-pretty";import yv from"pino-std-serializers";var Qa=new Map,bv=!0,wh="Log throttle exceeded",Tv=100,wv=5e3,wd=class t{consoleLogger;hostname;bindingAttributes;disableConsoleLogs;minLevelValue=20;logsInCurrentWindow=0;droppedLogsInWindow=!1;lastWindowStart=Date.now();site="https://ingest.us.signoz.cloud:443/logs/json";flushIntervalMs;maxBatchSize;buffer=[];flushTimer;constructor({bindings:e,hostname:n,disableConsoleLogs:r,flushIntervalMs:o,maxBatchSize:a}){this.hostname=n??hv.hostname(),this.disableConsoleLogs=r,this.bindingAttributes={...e,env:"production"},this.flushIntervalMs=o??5e3,this.maxBatchSize=a??10;let i={base:this.bindingAttributes,errorKey:"err",level:"debug"};this.consoleLogger=bv?Th(i):Th(i,fv([{stream:Sv({colorize:!0})}]))}getLevel(){return Rs[this.minLevelValue]}child(e){return new t({bindings:{...this.bindingAttributes,...e},hostname:this.hostname,disableConsoleLogs:this.disableConsoleLogs,flushIntervalMs:this.flushIntervalMs,maxBatchSize:this.maxBatchSize})}flush(e){this.flushBuffer(),this.disableConsoleLogs||this.consoleLogger.flush(e)}scheduleFlush(){this.flushTimer||(this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushBuffer()},this.flushIntervalMs))}async flushBuffer(){if(this.buffer.length===0)return;let e=this.buffer;this.buffer=[];try{let n=await fetch(this.site,{method:"POST",headers:{"Content-Type":"application/json","signoz-access-token":"CumAaTMUcwjt05OddAmefKgshbhfRmWxzxih"},body:Va(e)});if(!n.ok)throw new Error(`Got error status (${n.statusText}) from SigNoz`)}catch(n){this.consoleLogger.warn({err:n},"Failed to log to SigNoz")}}shouldAllowLog(e){if(e===wh)return!0;let n=Date.now();return n-this.lastWindowStart>wv&&(this.logsInCurrentWindow=0,this.droppedLogsInWindow&&this.log("error",void 0,wh),this.droppedLogsInWindow=!1,this.lastWindowStart=n),this.logsInCurrentWindow<Tv?(this.logsInCurrentWindow++,!0):(this.droppedLogsInWindow=!0,!1)}log(e,n,r,...o){try{this.logHelper(e,n,r,...o)}catch(a){this.consoleLogger.warn(`Failed to log to Signoz: ${a}`)}}logHelper(e,n,r,...o){if(qa[e]<this.minLevelValue||!this.shouldAllowLog(r))return;typeof n=="string"&&!r&&(n={message:n}),typeof n=="object"&&n&&"err"in n&&n.err instanceof Error&&(n.err=yv.err(n.err));let a={...this.bindingAttributes,...n&&typeof n=="object"?n:{},...o.length>0?{args:o}:{}},i={host:this.hostname,env:this.bindingAttributes.env};this.disableConsoleLogs||this.consoleLogger[e](a,r,...o);let s={timestamp:Math.round(Date.now()*1e6),severity_text:e.toUpperCase(),resources:i,attributes:{},body:bg({message:r||"",...a})};this.buffer.push(s),this.buffer.length>=this.maxBatchSize?(this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=void 0),this.flushBuffer()):this.scheduleFlush()}setApp(e){let n=this.bindingAttributes.app;this.bindingAttributes.app=e,Qa.set("app",this),Qa.delete(n)}debug(e,n,...r){this.log("debug",e,n,...r)}info(e,n,...r){this.log("info",e,n,...r)}warn(e,n,...r){this.log("warn",e,n,...r)}error(e,n,...r){this.log("error",e,n,...r)}bindings(){return this.bindingAttributes}addBinding(e,n){this.bindingAttributes[e]=n}setMinLevel(e){typeof e=="number"?(this.minLevelValue=e,this.consoleLogger.level=Rs[e]):(this.minLevelValue=qa[e],this.consoleLogger.level=e)}enableConsoleLogs(){this.disableConsoleLogs=!1}},Is=({app:t,hostname:e,disableConsoleLogs:n})=>(Qa.has(t)||Qa.set(t,new wd({bindings:{app:t},hostname:e,disableConsoleLogs:n})),Qa.get(t));import{hostname as Ev}from"os";var X=Is({app:"cli",hostname:Ev(),disableConsoleLogs:!0}).child({cliVersion:"2.16.0"});var Cv=5;async function Ms({getResults:t,checkDone:e,name:n,timeoutMs:r=18e5}){let o=Date.now(),a=0;for(;Date.now()-o<r;){let i;a>Cv&&(S.error(`Failed to fetch ${n} status too many times.`),process.exit(1));try{i=await t(),a=0}catch(c){a++,X.warn({err:c},"Failed to fetch run status, retrying..."),S.warn({err:c},"Failed to fetch run status, retrying..."),await new Promise(d=>setTimeout(d,1500*a));continue}if(e(i))return i;let l=Math.max(1e4,Math.floor(r/100));await new Promise(c=>setTimeout(c,l))}S.error(`Timeout elapsed waiting for ${n} to complete (${Math.floor(r/1e3)}s).`),process.exit(1)}function Vo({results:t,startTime:e,entity:n,getDisplayLine:r,onFailed:o}){let a=t.filter(d=>d.status==="PASSED"&&d.quarantined),i=t.filter(d=>d.status==="PASSED"&&!d.quarantined),s=t.filter(d=>d.status==="FAILED"&&d.quarantined),l=t.filter(d=>d.status==="FAILED"&&!d.quarantined),c=t.filter(d=>d.status==="CANCELLED");return yh(()=>{if(l.forEach(d=>{S.log(""),o(d)}),l.length){S.log("");let d=l.length===1?"":"s";S.error(`${l.length} ${n}${d} failed:`),l.forEach(u=>{S.dimmed(r(u))})}if(c.length){S.log("");let d=c.length===1?"":"s";S.warn(`${c.length} ${n}${d} cancelled:`),c.forEach(u=>{S.dimmed(r(u))})}if(i.length){S.log("");let d=i.length===1?"":"s";S.success(`${i.length} ${n}${d} passed:`),i.forEach(u=>{S.dimmed(r(u))})}if(s.length){S.log("");let d=s.length===1?"":"s";S.warn(`${s.length} quarantined ${n}${d} failed:`),s.forEach(u=>{S.dimmed(r(u))})}if(a.length){S.log("");let d=a.length===1?"":"s";S.warn(`${a.length} quarantined ${n}${d} passed:`),a.forEach(u=>{S.dimmed(r(u))})}S.log(""),S.dimmed(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{quarantinedPassed:a.length,passed:i.length,quarantinedFailed:s.length,failed:l.length,cancelled:c.length}}var Ls=(t,e)=>{if(!t.failureDetails||!t.failureReason)return;let n=Ki[t.failureDetails?.classification?.reason||t.failureReason],r=t.failureDetails?.classification?.summary||No[t.failureReason],o=t.failureDetails.classification?.rootCause;if(S.error(e),o){S.log(`${Ke}- Error type: ${An.dim(n)}`);let a="- Root cause analysis:",i=bh(`${a} ${o}`,`${Ke} `,!1),s=i.indexOf(":");S.log(`${Ke}${a} ${An.dim(i.slice(s+1))}`)}else S.log(`${Ke}Reason: ${An.red(n)}`),S.log(`${Ke}Description: ${An.red(r)}`)},Za=({status:t,testLogRef:e,getRunningTestsCount:n,getTotalTestsCount:r,additionalText:o})=>{t=t.toUpperCase();let a=t,i;t.includes("FAIL")?(a=An.bgRed.white("FAIL"),i=3):t.includes("PASS")?(a=An.bgGreen.white("PASS"),i=3):t.includes("START")?(a=An.bgBlue.white("START"),i=2):t.includes("CANCEL")?(a=An.bgRgb(191,68,11).white("CANCEL"),i=1):t.includes("RETRY")?(a=An.bgRgb(191,68,11).white("RETRY"),i=2):t.includes("RUN")||t.includes("PROG")?(a=An.bgMagenta.white("RUNNING"),i=0):(S.warn(`Unknown status tried to be logged in run test locally: ${t}`),i=0),Rv||(a=`${a}`),S.log(`${a}${" ".repeat(i)} ${e} ${o?`${o} `:""}(${n()}/${r()})`)};var Lv=!1,Rh=(()=>{try{return Pv("/.dockerenv"),!0}catch{return!1}})();async function bt(t,e){return Ea||Lv||Rh?!0:(S.flush(),X.flush(),await new Promise(r=>setTimeout(r,500)),await vv({message:t}))}async function Ed(t){let e=Mv(t);return fh(e)?xv(t)?bt(`File '${Eh(t)}' already exists. Overwrite existing content?`,!0):!0:await bt(`Directory '${Eh(e)}' doesn't exist. Create it now?`,!0)?(Iv(e,{recursive:!0}),!0):!1}function Eh(t){return t.replace(/(\s+)/g,"\\$1")}async function Ch(t,e){return Ea||Rh?e:(await Av({message:t,default:e})).trim()||e}import Ov from"fs";import{tmpdir as Nv}from"os";import kv from"path";import{registry as ei}from"playwright-core/lib/server";import vh from"proper-lockfile";var Ah=kv.join(Nv(),"momenticBrowserInstallation");var Rd=["chrome","chromium","chrome-for-testing"],_v={Chromium:"chromium","Google Chrome":"chrome","Chrome for Testing":"chrome-for-testing"},xh={chrome:"chrome",chromium:"chromium","chrome-for-testing":"chromium-headless-shell"};function Ih(t){let e=xh[_v[t]??""]??"",n=ei.findExecutable(e);return!n||n.installType==="none"?!1:Cd(n)}function Cd(t){let e=t.executablePath();return Ov.existsSync(e)}function Dv(t,e){let n=xh[t];if(!n)throw new Error(`Requested install of unknown browser type ${t}`);let r=ei.findExecutable(n);if(!r||r.installType==="none")throw new Error(`Requested install of unknown browser type ${t}`);if(!(!e&&Cd(r)))return r}async function Fv({browser:t,force:e}){let n=Dv(t,e);if(!n){S.info(`Browser '${t}' is already installed, skipping...`);return}S.info(`Installing browser '${t}'...`);try{await ei.installDeps([n],!1),await ei.install([n],!1)}catch(r){if(r.message.includes("Lock file is already being held")){S.warn("Another process is installing Playwright browsers. Waiting for completion before proceeding..");let o=ei.findExecutable(t),a=5*60*1e3,i=Date.now();for(;Date.now()-i<a&&!Cd(o);)S.info("Waiting for browser to finish installing..."),await new Promise(s=>setTimeout(s,5e3))}else throw r}}async function Ph({rawBrowsers:t,force:e=!1,all:n=!1}){let r=n?Rd:Array.from(new Set(t));try{await vh.lock(Ah,{stale:1e3*60*5,update:1e3*60,realpath:!1,retries:{retries:30,factor:2,maxTimeout:15e3,minTimeout:500}})}catch(a){S.warn(`Failed to acquire lock to install browsers. Please ensure that any other process installing browsers completes within 5 minutes: ${a}. Continuing without installation...`);return}let o;try{for(let a of r)try{await Fv({browser:a,force:e})}catch(i){o=i,S.error(`Failed to install the ${a} browser: ${i}`)}}finally{await vh.unlock(Ah,{realpath:!1})}if(o)throw o}import{randomUUID as nN}from"crypto";import jb from"body-parser";import VL from"cors";import qL from"dedent";import{Router as AA}from"express";import It from"fs";import{globSync as xA}from"glob";import lt from"path";import Ud from"fs";import{z as Ad}from"zod";var z="v1",ti="2.16.0";var pr=class extends Error{constructor(e){super(e),this.name="TimeoutError"}};var Mh=t=>{let e=t.reason===void 0?new DOMException("This operation was aborted.","AbortError"):t.reason;return e instanceof Error?e:new DOMException(e,"AbortError")};function H(t,e){let{milliseconds:n,fallback:r,message:o,customTimers:a={setTimeout,clearTimeout}}=e,i,s;if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);return new Promise((l,c)=>{if(e.signal){let{signal:u}=e;if(u.aborted)return c(Mh(u));s=()=>c(Mh(u)),u.addEventListener("abort",s)}let d=()=>{if(r)try{l(r())}catch(u){c(u)}else{typeof t.cancel=="function"&&Promise.resolve().then(()=>t.cancel()).catch(()=>{});let u=o instanceof Error?o:new pr(o??`Promise timed out after ${n}ms`);c(u)}};i=a.setTimeout(d,n),Promise.resolve(t).then(u=>l(u)).catch(u=>c(u))}).finally(()=>{a.clearTimeout(i),e.signal&&s&&e.signal.removeEventListener("abort",s)})}var Os=class{limit;windowMs;userActions;constructor(e,n){this.limit=e,this.windowMs=n,this.userActions=new Map}_cleanup(e,n="DEFAULT_USER"){let r=Date.now(),o=`${n}:${e}`;if(this.userActions.has(o)){let i=this.userActions.get(o)?.filter(s=>r-s<=this.windowMs)??[];i.length>0?this.userActions.set(o,i):this.userActions.delete(o)}}increment(e,n="DEFAULT_USER"){let r=Date.now(),o=`${n}:${e}`;this._cleanup(n,e),this.userActions.has(o)||this.userActions.set(o,[]);let a=this.userActions.get(o);return a.length>=this.limit?!0:(a.push(r),!1)}};var Uv=9e4,Bv=3,zv=1500,Hv=15e3,cn=class extends Error{status;rawError;constructor(e,n,r,o={}){super(r,o),this.status=e,this.rawError=n}};async function $v(t){return t.text().then(e=>{try{return JSON.parse(e).error}catch{return e}})}var vd=class{baseUrl;logger;constructor(e){this.baseUrl=e.baseUrl,this.logger=e.logger}getHeaders(){let e={"Content-Type":"application/json"};return ti&&(e[Rg]=ti),e}async sendRequest(e,n){let{retries:r=Bv,requestTimeoutMs:o=Uv,initialRetryDelayMs:a=zv,maxRetryDelayMs:i=Hv}=n,s=r,l=r,c,d={path:e,baseUrl:this.baseUrl,method:n.method};for(;s>0;)try{return s--,await this.sendSingleRequestHelper(e,n,o)}catch(u){if(c=u,u instanceof cn&&u.status>=400&&u.status<500)throw u;if(u instanceof Error&&u.name==="AbortError"&&(c=new pr),s===0)throw c;let m=l-s,p=Math.min(a*Math.pow(2,m-1),i);await new Promise(g=>setTimeout(g,p))}throw this.logger.warn({...d,err:c},"Got fatal error response from Momentic server"),c}async sendSingleRequestHelper(e,n,r){let o={path:e,baseUrl:this.baseUrl,method:n.method},a=new AbortController,i=setTimeout(()=>a.abort(),r),s=()=>a.abort();n.signal&&n.signal.addEventListener("abort",s);let l={...this.getHeaders(),...n.extraHeaders};try{let c=await fetch(`${this.baseUrl}${e}`,{method:n.method,body:n.body?JSON.stringify(n.body):void 0,headers:l,signal:a.signal});if(!c.ok){let u=await $v(c);throw new cn(c.status,u,`Request to ${n.method} ${e} failed with status ${c.status}: ${u}`)}let d;if(c.status===204)d={};else{let u=await c.text();try{d=JSON.parse(u)}catch{d=u}}return this.logger&&n.logResponse===!0&&d&&this.logger.debug({result:d,status:c.status,...o},"Got response from Momentic server"),d}finally{clearTimeout(i),n.signal&&n.signal.removeEventListener("abort",s)}}},xt=class extends vd{apiKey;constructor(e){super(e),this.apiKey=e.apiKey}getHeaders(){return{...super.getHeaders(),Authorization:`Bearer ${this.apiKey}`}}};var Je=class extends xt{constructor(e){super(e)}getAppUrl(){return this.baseUrl==="http://localhost:8000"?"http://localhost:3000":this.baseUrl.replace(/\/\/api/,"//app")}async getAuthInfo(){let e=await this.sendRequest(`/${z}/auth/check`,{method:"GET",retries:10,requestTimeoutMs:5e3});return zg.parse(e)}async bulkGetRunStatus(e){let n=await this.sendRequest(`/${z}/runs/status`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Dg.parse(n)}async getTestYAMLExport(e){let n=await this.sendRequest(`/${z}/tests/export`,{method:"POST",body:e,retries:3,requestTimeoutMs:3e4});return Pg.parse(n)}async updateStepCaches(e,n){await this.sendRequest(`/${z}/cache`,{method:"PATCH",body:e,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getStepCacheForTest(e,n){let r=await this.sendRequest(`/${z}/cache`,{method:"POST",body:e,extraHeaders:n,retries:10,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Lg.parse(r)}async updateMobileStepCaches(e,n){await this.sendRequest(`/${z}/mobile-cache`,{method:"PATCH",body:e,extraHeaders:n,retries:3,requestTimeoutMs:1e4,initialRetryDelayMs:3e3})}async getMobileStepCacheForTest(e,n){let r=await this.sendRequest(`/${z}/mobile-cache`,{method:"POST",body:e,extraHeaders:n,retries:10,logResponse:!0,requestTimeoutMs:3e4,initialRetryDelayMs:3e3});return Og.parse(r)}async queueTests(e){let n=await this.sendRequest(`/${z}/tests/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4});return Ig.parse(n)}async uploadScreenshot(e){let n=await this.sendRequest(`/${z}/screenshots`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return Bg.parse(n)}async getAllEnvironments(){let e=await this.sendRequest(`/${z}/environments`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Hg.parse(e)}async acquireCacheLock(e,n){let r=await this.sendRequest(`/${z}/result-cache/lock`,{method:"POST",body:e,signal:n,retries:3,requestTimeoutMs:3e4});return th.parse(r)}async releaseCacheLock(e){await this.sendRequest(`/${z}/result-cache/lock`,{method:"DELETE",body:{key:e},retries:3,requestTimeoutMs:5e3})}async deleteCacheResult(e){await this.sendRequest(`/${z}/result-cache/entry`,{method:"DELETE",body:e,retries:3,requestTimeoutMs:5e3})}async setCacheResult(e){await this.sendRequest(`/${z}/result-cache/entry`,{method:"PATCH",body:e,retries:3,requestTimeoutMs:5e3})}async getCacheResult(e){try{return await this.sendRequest(`/${z}/result-cache/entry`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(n){if(n instanceof Error&&n.message.includes("404"))return null;throw n}}async queueSuiteRuns(e){let n=await this.sendRequest(`/${z}/suites/queue`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3});return $g.parse(n)}async bulkGetRunGroupStatus(e){let n={runGroupIds:e},r=await this.sendRequest(`/${z}/run-groups/status`,{method:"POST",body:n,retries:3,requestTimeoutMs:5e3});return ip.array().parse(r)}async uploadProposedSteps(e,n){try{await this.sendRequest(`/${z}/test-fragments/`,{method:"POST",body:e,retries:3,requestTimeoutMs:1e4})}catch(r){n.error({err:r},"Failed to upload proposed steps")}}async reportBillableEvents(e,n){try{await this.sendRequest(`/${z}/billing/events`,{method:"POST",body:n,retries:10,requestTimeoutMs:1e4})}catch(r){e.error({err:r},"Failed to report billable event")}}async fetchTestFragment(e){let n=await this.sendRequest(`/${z}/test-fragments/${e}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return jg.parse(n)}async patchTestFragment(e,n){await this.sendRequest(`/${z}/test-fragments/${e}`,{method:"PATCH",body:n,retries:3,requestTimeoutMs:1e4})}async getPastTestResults(e,n){let r=await this.sendRequest(`/${z}/results/tests/${e}`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return Gg.parse(r)}async generateTestResultsUploadUrl(){let e=await this.sendRequest(`/${z}/results/uploads`,{method:"POST",retries:3,requestTimeoutMs:1e4});return Wg.parse(e)}async startProcessingResultsUpload(e,n){let r=await this.sendRequest(`/${z}/results/uploads/${e}/process`,{method:"POST",body:n,retries:3,requestTimeoutMs:1e4});return Vg.parse(r)}async fetchIconKnowledgeBase(e){try{let n=await this.sendRequest(`/${z}/knowledge-base/icons`,{method:"GET",retries:3,requestTimeoutMs:5e3});return ih.parse(n)}catch(n){return e.error({err:n},"Failed to fetch icon knowledge base"),null}}async saveNewIcons(e,n){try{await this.sendRequest(`/${z}/knowledge-base/icons`,{method:"POST",body:e,retries:3,requestTimeoutMs:5e3})}catch(r){n.error({err:r},"Failed to save new icons to icon knowledge base")}}async getMergeBaseCommitFromGithub(e,n,r,o){let a=new URLSearchParams;a.set("base",r),a.set("head",o);let i=await this.sendRequest(`/${z}/git/github/${e}/${n}/merge-base-commit?${a.toString()}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ya.parse(i)}async getCommitFromGithub(e,n,r){let o=await this.sendRequest(`/${z}/git/github/${e}/${n}/commits/${r}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ya.parse(o)}async getMergeBaseCommitFromGitlab(e,n,r){let o=new URLSearchParams;o.set("base",n),o.set("head",r);let a=await this.sendRequest(`/${z}/git/gitlab/${e}/merge-base-commit?${o.toString()}`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Ya.parse(a)}async getCommitFromGitlab(e,n){let r=await this.sendRequest(`/${z}/git/gitlab/${e}/commits/${n}`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Ya.parse(r)}async getAgentConfig(){let e=await this.sendRequest(`/${z}/web-agent/agent-config`,{method:"GET",retries:3,requestTimeoutMs:5e3});return Ad.record(Ad.string(),Ad.string()).parse(e)}async getQuarantinedTests(){let e=await this.sendRequest(`/${z}/quarantine`,{method:"GET"});return qg.parse(e)}async quarantineTest(e,n,r){await this.sendRequest(`/${z}/quarantine`,{method:"POST",body:{testId:e.id,testName:e.name,reason:n,...r??{}},retries:3,requestTimeoutMs:1e4})}async unquarantineTest(e,n,r){await this.sendRequest(`/${z}/quarantine/${e.id}`,{method:"DELETE",body:{testName:e.name,reason:n,...r??{}},retries:3,requestTimeoutMs:1e4})}async createAndroidEmulator(e){let n=await this.sendRequest(`/${z}/limbar/android`,{method:"POST",retries:3,body:e,requestTimeoutMs:9e4,initialRetryDelayMs:5e3,maxRetryDelayMs:15e3});return Kg.parse(n)}async extendAndroidEmulatorTtl(e){try{await this.sendRequest(`/${z}/limbar/android/${e}/keepalive`,{method:"POST",retries:3,requestTimeoutMs:15e3})}catch{}}async generateAndroidAssetUrls({channel:e,tag:n,md5:r}){let o={channel:e,tag:n,md5:r},a=await this.sendRequest(`/${z}/limbar/android/upload-url`,{method:"POST",retries:3,body:o,requestTimeoutMs:15e3,logResponse:!0});return Yg.parse(a)}async deleteAndroidEmulator(e){await this.sendRequest(`/${z}/limbar/android/${e}`,{method:"DELETE",retries:3,requestTimeoutMs:3e4})}async getAndroidAssets(){let e=await this.sendRequest(`/${z}/limbar/assets`,{method:"GET",retries:3,requestTimeoutMs:1e4});return Xg.parse(e)}async deleteAndroidAsset(e,n){await this.sendRequest(`/${z}/limbar/assets/${e}/${n}`,{method:"DELETE",retries:3,requestTimeoutMs:1e4})}};async function xd(t){let e=process.versions.node,n=parseInt(e.split(".")[0]);(isNaN(n)||n<18)&&(S.error(`Node.js version 20 or higher is required to run the CLI. Detected: ${process.versions.node}.`),process.exit(1)),S.debug(`Identified node version ${e}`);let r=await t.client.getAuthInfo();return S.debug("Got auth info from API"),r}import{randomUUID as Lh}from"crypto";var Ns=class{apiClient;constructor(e){this.apiClient=e}async reportBillableEvent(e,n,r){try{return await this.apiClient.reportBillableEvents(e,[{event:n,timestamp:new Date().toISOString(),transactionId:r?.eventId??Lh(),properties:Yc({},r)}])}catch(o){e.error({err:o},"Failed to report billable event")}}async reportCreditsUsed(e,n,r,o){if(r)try{return await this.apiClient.reportBillableEvents(e,[{event:"credits-used",timestamp:new Date().toISOString(),transactionId:o?.eventId??Lh(),properties:Yc({creditsUsed:r,usedBy:n},o)}])}catch(a){e.error({err:a},"Failed to report credits used")}}};var qo=class{constructor(e,n){this.client=e;this.orgId=n}async acquireCacheLock(e,n){return this.client.acquireCacheLock(e,n)}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async deleteCacheResult(e){return this.client.deleteCacheResult(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}fetchIconKnowledgeBase(e){return this.client.fetchIconKnowledgeBase(e)}saveNewIcons(e,n){return this.client.saveNewIcons(e,n)}};import{Faker as jv,en as Gv}from"@faker-js/faker";var Ko="v1",gr=class{httpClient;fakerInstance;type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this)};email={send:this.sendEmail.bind(this),fetchLatest:this.fetchLatestEmail.bind(this),fetchAll:this.fetchAllEmails.bind(this)};ai={generate:this.sendAiGenerate.bind(this)};constructor(e){this.httpClient=e.httpClient,e.fakerSeed&&(this.fakerInstance=new jv({locale:Gv}),this.fakerInstance.seed(e.fakerSeed))}async sendAiGenerate(e){let n=typeof e=="string"?{input:e}:e;return this.httpClient.sendRequest(`/${Ko}/tools/ai/generate`,{method:"POST",body:n}).catch(r=>{throw r instanceof cn?new Error(r.rawError):new Error(`Failed to send AI generation: ${r.message}`)})}async sendSms(e){return this.httpClient.sendRequest(`/${Ko}/tools/sms/send`,{method:"POST",body:e}).then(()=>{}).catch(n=>{throw n instanceof cn?new Error(n.rawError):new Error(`Failed to send sms: ${n.message}`)})}async fetchLatestSms(e){return this.httpClient.sendRequest(`/${Ko}/tools/sms/fetchLatest`,{method:"POST",body:e}).catch(n=>{throw n instanceof cn?new Error(n.rawError):n})}async sendEmail(e){return this.httpClient.sendRequest(`/${Ko}/tools/email/send`,{method:"POST",body:e}).then(()=>{}).catch(n=>{throw n instanceof cn?new Error(n.rawError):new Error(`Failed to send email: ${n.message}`)})}async fetchAllEmails(e){return this.httpClient.sendRequest(`/${Ko}/tools/email/fetchAll`,{method:"POST",body:e}).catch(n=>{throw n instanceof cn?new Error(n.rawError):new Error(`Failed to fetch all emails: ${n.message}`)})}async fetchLatestEmail(e){return this.httpClient.sendRequest(`/${Ko}/tools/email/fetchLatest`,{method:"POST",body:e}).catch(n=>{throw n instanceof cn?new Error(n.rawError):new Error(`Failed to fetch latest emails: ${n.message}`)})}};import{z as Wv}from"zod";var Yo=class extends xt{agentConfig;constructor(e,n){super(n),this.agentConfig=e}getAgentConfig(){return this.agentConfig}async rankChunksWithAi(e,n){let r={...e,loggerTags:n.loggerTags},o=await this.sendRequest(`/${z}/web-agent/recommend-chunks-ai`,{method:"POST",body:r,signal:n.abortSignal});return mp.parse(o)}async rankChunksWithRag(e,n){let r=await this.sendRequest(`/${z}/web-agent/recommend-chunks`,{method:"POST",body:{cliVersion:ti,...e},signal:n.abortSignal});return up.parse(r)}async getScreenshotFromS3(e){let n=await this.sendRequest(`/${z}/s3/visual-diff-screenshot`,{method:"POST",body:{url:e}});return Wv.string().parse(n)}async getElementLocation(e,n){let r={...e,disableCache:n.disableCache,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.locator},o=await this.sendRequest(`/${z}/web-agent/locate-element`,{method:"POST",body:r,signal:n.abortSignal});return Ag.parse(o)}async getAssertionResult(e,n){let r={...e,disableCache:!!n.disableCache,useConsensus:!!n.useConsensus,attemptNumber:n.attemptNumber,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.assertion},o=await this.sendRequest(`/${z}/web-agent/assertion`,{method:"POST",body:r,signal:n.abortSignal});return gd.parse(o)}async getLintStepResult(e,n){let r={...e,disableCache:!!n.disableCache,loggerTags:n.loggerTags},o=await this.sendRequest(`/${z}/web-agent/lint/step`,{method:"POST",body:r,signal:n.abortSignal});return vg.parse(o)}async getVisualAssertionResult(e,n){let r={...e,disableCache:!!n.disableCache,useConsensus:!!n.useConsensus,attemptNumber:n.attemptNumber,loggerTags:n.loggerTags,useMemory:n.useMemory,agentConfigVersion:this.agentConfig?.["visual-assertion"]},o=await this.sendRequest(`/${z}/web-agent/visual-assertion`,{method:"POST",body:r,signal:n.abortSignal});return gd.parse(o)}async getAiActionCommand(e,n){let r=await this.sendRequest(`/${z}/web-agent/next-command-dynamic`,{method:"POST",body:{...e,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return Cg.parse(r)}async getMultiturnAiActionCommand(e,n){return await this.sendRequest(`/${z}/web-agent/ai-action/next-command`,{method:"POST",body:{...e,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal})}async getMultiturnAiActionEvaluation(e,n){let r=await this.sendRequest(`/${z}/web-agent/ai-action/evaluate`,{method:"POST",body:{...e,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return Lc.parse(r)}async getReverseMappedDescription(e,n){let r=await this.sendRequest(`/${z}/web-agent/reverse-mapped-description`,{method:"POST",body:{...e,disableCache:n.disableCache,loggerTags:n.loggerTags},signal:n.abortSignal});return xg.parse(r)}async getTextExtraction(e,n){let r={...e,disableCache:n.disableCache,loggerTags:n.loggerTags,agentConfigVersion:this.agentConfig?.["text-extraction"]},o=await this.sendRequest(`/${z}/web-agent/text-extraction`,{method:"POST",body:r,signal:n.abortSignal});return Pc.parse(o)}async getTestResultClassification(e,n){let r=await this.sendRequest(`/${z}/web-agent/result-classification`,{method:"POST",body:{...e,loggerTags:n.loggerTags},signal:n.abortSignal});return kc.parse(r)}async getExtractedKeywords(e,n){let r=await this.sendRequest(`/${z}/web-agent/extract-keywords`,{method:"POST",body:{goal:e,disableCache:n.disableCache,context:e},signal:n.abortSignal});return wp.parse(r)}async getAutohealingProposal(e,n){let r=await this.sendRequest(`/${z}/web-agent/autoheal-section`,{method:"POST",body:{...e,loggerTags:n.loggerTags},signal:n.abortSignal});return Hm.parse(r)}async getFailureRecoveryProposal(e,n){let r=await this.sendRequest(`/${z}/web-agent/failure-recovery`,{method:"POST",body:{...e,loggerTags:n.loggerTags},signal:n.abortSignal});return jm.parse(r)}async getFailureRecoveryPlan(e,n){let r=await this.sendRequest(`/${z}/web-agent/failure-recovery-plan`,{method:"POST",body:{...e,loggerTags:n.loggerTags},signal:n.abortSignal});return $m.parse(r)}async getIframeRegex(e,n){let r=await this.sendRequest(`/${z}/web-agent/iframe-regex`,{method:"POST",body:e,signal:n.abortSignal});return Tm.parse(r)}};var Xo=class extends xt{generator;constructor(e,n){super(e),this.generator=n}async runTemplateMatching(e,n={}){let r=await this.sendRequest(`/${z}/web-agent/template-matching`,{method:"POST",body:e,signal:n?.signal});return wm.parse(r)}async constructIframeRegex(e,n={}){return this.generator.getIframeRegex(e,{abortSignal:n.signal})}};function Oh(t,e,n){return fetch(t,{method:"PUT",body:n,headers:{"Content-Type":e}})}var ks=class{constructor(e){this.client=e}async uploadResultsArchive(e,n){let{uploadUrl:r,id:o}=await this.client.generateTestResultsUploadUrl(),a=await Oh(r,"application/zip",n);if(!a.ok)throw new Error(`Failed to upload test results: ${await a.text()}`);let{runGroupId:i}=await this.client.startProcessingResultsUpload(o,{runGroupId:e});return i}};import{diff as Dh}from"deep-object-diff";function ni(t){let e={parentChain:[]};return _s(t,e),e}function _s(t,e){let{onPresetAction:n,onSimpleStepContainer:r,onConditional:o,earlyStop:a}=t;for(let i of t.steps)switch(i.type){case"PRESET_ACTION":if(n(i,e)&&a)return!0;break;case"CONDITIONAL":if(o?.(i,e)&&a)return!0;e.parentChain.push(i);for(let l of i.blocks)if(n(l.assertion,e)&&a||_s({...t,steps:l.steps},e)&&a)return!0;if(_s({...t,steps:i.elseSteps??[]},e)&&a)return!0;e.parentChain.pop();break;case"RESOLVED_MODULE":case"SECTION":case"AI_ACTION":if(r?.(i,e)&&a)return!0;if(i.steps){if(e.parentChain.push(i),_s({...t,steps:i.steps},e)&&a)return!0;e.parentChain.pop()}break;case"AI_ACTION_DYNAMIC":{if(r?.(i,e)&&a)return!0;break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(i)}}function Nh(t,e,n,r){let o=Array.from(e),a=Array.from(r);for(let s=0;s<o.length;s++){if(o[s]!==a[s])return!1;a.shift()}return!!Vv([t],n,a).result}function Vv(t,e,n=[]){let r,o=[],a=(i,s)=>{let l=JSON.stringify(s.parentChain.map(d=>d.id)),c=n.length===0?!0:JSON.stringify(n)===l;return i.id===e&&c?(r=i,o=s.parentChain,!0):!1};return ni({steps:t,earlyStop:!0,onPresetAction:a,onConditional:a,onSimpleStepContainer:a}),{result:r,parentChain:o}}function kh(t,e){e(t);for(let n in t){let r=t[n];r&&(Array.isArray(r)?Fs(r,e):typeof r=="object"&&kh(r,e))}}function Fs(t,e){for(let n of t)n&&(Array.isArray(n)?Fs(n,e):typeof n=="object"&&kh(n,e))}function Id(t,e){if(t.length>e.length)return Id(e,t);for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function Ds(t){for(let e of t.results)switch(e.type){case"PRESET_ACTION":t.onPresetAction(e);break;case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":t.onSimpleStepContainer?.(e),Ds({...t,results:e.results});break;case"CONDITIONAL":t.onConditional?.(e),e.assertionResult&&t.onPresetAction(e.assertionResult),Ds({...t,results:e.results});break;default:throw new Error(`Unsupported result type: ${e.type}`)}}import{cloneDeep as _h}from"lodash-es";import{v4 as Pd}from"uuid";async function He(t){let e=new Map,n=new Set,r=_h(t.stepLists.steps),o=await Jr({...t,steps:r,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:n}),a={stepsToSave:{steps:o.stepsToSave,beforeSteps:void 0,afterSteps:void 0},cachesToSave:o.cachesToSave,moduleUpdates:o.moduleUpdates};for(let i of["beforeSteps","afterSteps"]){let s=_h(t.stepLists[i]);if(!s)continue;let l=await Jr({...t,steps:s,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:e,seenModules:n});a.cachesToSave.push(...l.cachesToSave),a.moduleUpdates.push(...l.moduleUpdates),a.stepsToSave[i]=l.stepsToSave}return a}async function Jr({steps:t,...e}){let{seenModules:n,cacheCreationParams:r,moduleIdParents:o,moduleStepParents:a,moduleIdReplacements:i,shouldCreateNewModuleId:s,createNewCacheIds:l}=e,c={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let d of t)switch(delete d.index,delete d.aiSuggested,d.id=l?Pd():d.id,d.type){case"PRESET_ACTION":{let m=d.command;m.id=l?Pd():m.id,"cache"in m&&m.cache&&(r&&(c.cachesToSave=c.cachesToSave.concat(Md({id:m.id,orgId:r.orgId,testId:r.testId,value:Bn.parse(m),moduleIdParents:o,moduleStepParents:a}))),delete m.cache),m.thoughts&&delete m.thoughts,c.stepsToSave.push({...d,command:m});break}case"RESOLVED_MODULE":{let m=l?Pd():d.id,p=d.moduleId;i.has(p)?p=i.get(p):s!==void 0&&(p=await s(d),i.set(d.moduleId,p));let{cachesToSave:g,stepsToSave:h,moduleUpdates:f}=await Jr({...e,steps:d.steps,cacheCreationParams:r?{...r}:void 0,createNewCacheIds:!1,moduleStepParents:[...a,m],moduleIdParents:[...o,p],skipCacheIntermediateEntries:l});c.moduleUpdates=c.moduleUpdates.concat(f),c.cachesToSave=c.cachesToSave.concat(g),n.has(p)||(n.add(p),c.moduleUpdates.push({...Ot.parse(d),steps:Me.array().parse(h),moduleId:p}));let y=sn.parse({...d,type:"MODULE",moduleId:p,inputs:d.inputs,id:m,skipped:d.skipped,cacheConfig:d.cacheConfig,envKey:d.envKey});c.stepsToSave.push(y);break}case"AI_ACTION":{if(!d.steps){c.stepsToSave.push(d);break}let{stepsToSave:m,cachesToSave:p}=await Jr({...e,steps:d.steps});try{d.steps=Ht.array().parse(m)}catch(g){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${g}`)}c.stepsToSave.push(d),c.cachesToSave=c.cachesToSave.concat(p);break}case"AI_ACTION_DYNAMIC":{c.stepsToSave.push(d);break}case"CONDITIONAL":{let m=[];for(let g of d.blocks){let{stepsToSave:h,cachesToSave:f,moduleUpdates:y}=await Jr({...e,steps:g.steps});m.push({...g,steps:h}),c.cachesToSave=c.cachesToSave.concat(f),c.moduleUpdates=c.moduleUpdates.concat(y)}let p={...d,elseSteps:void 0,blocks:m};if(d.elseSteps){let{stepsToSave:g,cachesToSave:h,moduleUpdates:f}=await Jr({...e,steps:d.elseSteps});p.elseSteps=g,c.cachesToSave=c.cachesToSave.concat(h),c.moduleUpdates=c.moduleUpdates.concat(f)}c.stepsToSave.push(p);break}case"SECTION":{let{stepsToSave:m,cachesToSave:p,moduleUpdates:g}=await Jr({...e,steps:d.steps}),h={...d,steps:m};c.moduleUpdates=c.moduleUpdates.concat(g),c.stepsToSave.push(h),c.cachesToSave=c.cachesToSave.concat(p);break}default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(d)}return c}function Jo({steps:t,topLevel:e=!0,...n}){let{stepCacheEntries:r,logger:o,keyPrefix:a}=n,i=[],s=[],l=[],c=0,d=(m,p)=>{try{let g=Bn.parse(p.value);if(g.type!==m.type){o.warn({parsedCacheEntry:g,command:m},"Not using step cache due to type mismatch"),s.push(p.key);return}m.cache=g.cache,i.push(p.key),l.push(p.uniqueKey)}catch(g){s.push(p.key),o.error({err:g,cacheEntry:p},"Not using step cache due to parsing error")}},u=(m,p)=>{let g=Kv(m.id,p),h=g.find(f=>!!r[f]);if(h)d(m,r[h]);else{if(m.type==="AI_ASSERTION")return;s.push(g[0])}};for(let m of t)switch(m.type){case"RESOLVED_MODULE":{c+=m.steps.length;let{cacheKeysHit:p,cacheKeysMissed:g,uniqueKeysHit:h}=Jo({...n,steps:m.steps,keyPrefix:a?`${a}:${m.id}`:m.id,topLevel:!1});i.push(...p),s.push(...g),l.push(...h);break}case"SECTION":case"AI_ACTION":{if(c+=m.steps?.length??0,!m.steps?.length)break;let{cacheKeysHit:p,cacheKeysMissed:g,uniqueKeysHit:h}=Jo({...n,steps:m.steps,topLevel:!1});i.push(...p),s.push(...g),l.push(...h);break}case"AI_ACTION_DYNAMIC":continue;case"PRESET_ACTION":{if(!$i.includes(m.command.type)||(m.command.type==="TYPE"||m.command.type==="MOUSE_DRAG"||m.command.type==="VISUAL_DIFF"||m.command.type==="SCROLL_DOWN"||m.command.type==="SCROLL_UP"||m.command.type==="SCROLL_LEFT"||m.command.type==="SCROLL_RIGHT")&&!m.command.target||"cache"in m.command&&m.command.cache)continue;c++,u(m.command,a);break}case"CONDITIONAL":{for(let p of m.blocks){c++,u(p.assertion.command,a),c+=p.steps.length;let{cacheKeysHit:g,cacheKeysMissed:h,uniqueKeysHit:f}=Jo({...n,steps:p.steps,topLevel:!1});i.push(...g),s.push(...h),l.push(...f)}if(m.elseSteps){c+=m.elseSteps.length;let{cacheKeysHit:p,cacheKeysMissed:g,uniqueKeysHit:h}=Jo({...n,steps:m.elseSteps,topLevel:!1});i.push(...p),s.push(...g),l.push(...h)}break}default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(m)}return e&&c&&s.length>0&&o.warn({totalSteps:c,cacheKeysMissed:s,cacheKeysHit:i,uniqueKeysHit:l,cacheEntries:r.length},"Step cache did not fully resolve"),{cacheKeysHit:i,cacheKeysMissed:s,uniqueKeysHit:l}}function Fh(t,e){return e?`${e}:${t}`:t}function Kv(t,e){let n=[],r=e?.split(":")??[];for(let o=r.length;o>=0;o--){let a=[...r.slice(o),t];n.push(a.join(":"))}return n.reverse(),n}function Md(t){let{moduleStepParents:e=[],moduleIdParents:n=[]}=t;if(e.length!==n.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
18
+ ${JSON.stringify(n)}`);let r=[];return r.push({key:Fh(t.id,e.join(":")),organizationId:t.orgId,value:t.value,testId:t.testId}),r}function Uh(t){let e=new Set;return Fs(t,n=>{if("type"in n&&n.type==="RESOLVED_MODULE"&&"moduleId"in n){let r=n.moduleId;typeof r=="string"&&!e.has(r)&&e.add(r)}}),e}function Us({cmd:t,newTarget:e,key:n,logger:r}){t.type==="DRAG"?n!=="fromTarget"&&n!=="toTarget"?r.error({cmd:t,newTarget:e,key:n},"Attempted to apply invalid cache to DRAG command"):t.cache={...t.cache,[n]:e}:n==="target"&&Om(t)?t.cache={...t.cache,target:e}:r.error({cmd:t,newTarget:e,key:n},"Invalid target cache application")}function Bs(t,e){t.cache={...t.cache,memory:{type:"GCS_TRACES",traces:e}}}async function zs({logger:t,cacheStorage:e,orgId:n,testId:r,originalSteps:o,updatedSteps:a}){let i=Dh(o,a);if(Object.keys(i).length!==0){t.debug({changes:i},"Updating steps caches post-run success");try{let{cachesToSave:s}=await He({stepLists:a,cacheCreationParams:{testId:r,orgId:n}});await e.saveStepCacheEntries({logger:t,testId:r,entries:s})}catch(s){t.error({err:s},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}async function Hs({logger:t,cacheStorage:e,orgId:n,testId:r,originalSteps:o,updatedSteps:a}){let i=Dh(o,a);if(Object.keys(i).length===0)return;t.debug({changes:i},"Updating memory post-run failure");let s={};for(let d of["steps","beforeSteps","afterSteps"]){let u=o[d];if(!u||!u.length)continue;let m=Yv({steps:u});for(let[p,g]of Object.entries(m))s[p]=g}let{cachesToSave:l}=await He({stepLists:a,cacheCreationParams:{testId:r,orgId:n}}),c=Xv({newEntries:l,originalCachesMap:s,logger:t});if(c.length){t.debug({prunedCaches:c},"Saving pruned memory post-failure");try{await e.saveStepCacheEntries({logger:t,testId:r,entries:l})}catch(d){t.error({err:d},"Failed to save memory after successful execution. This is not critical, but can impact future performance.")}}}function Yv({steps:t}){let e={};return ni({steps:t,onPresetAction:(n,r)=>{let o=n.command;if(!("cache"in o)||!o.cache)return;let a=r.parentChain.filter(l=>l.type==="RESOLVED_MODULE").map(l=>l.id).join(":"),i=Fh(n.id,a),s=Bn.parse(o);e[i]=s},onSimpleStepContainer:(n,r)=>{},onConditional:(n,r)=>{}}),e}function Xv({newEntries:t,originalCachesMap:e,logger:n}){let r=[];for(let o of t){let a=e[o.key];if(!a||!a.cache||o.value.type!==a.type)continue;let i=o.value.cache;if(o.value={...a},!i){r.push(o);continue}if("memory"in i&&i.memory)n.debug({cacheKey:o.key,newCacheMemory:i.memory,originalCache:a},"Overwriting assertion cache memory"),o.value.cache={...o.value.cache,memory:i.memory};else if("target"in i&&i.target.memory){let s=zt.parse(o.value.cache);if(!s)continue;n.debug({cacheKey:o.key,newCacheMemory:i.target.memory,originalCache:a},"Overwriting target cache memory"),s.target.memory=i.target.memory,o.value.cache=s}else if("fromTarget"in i||"toTarget"in i){let s=Sc.optional().parse(o.value.cache);if(!s)continue;s.fromTarget&&i.fromTarget&&(s.fromTarget.memory=i.fromTarget.memory),s.toTarget&&i.toTarget&&(s.toTarget.memory=i.toTarget.memory),n.debug({cacheKey:o.key,fromTargetMemory:i.fromTarget?.memory,toTargetMemory:i.toTarget?.memory,originalCache:a},"Overwriting drag cache memory"),o.value.cache=s}r.push(o)}return r}function $e(t,e,n=!1){return t.length<e?t:t.slice(0,e-3)+(n?"...TRUNCATED...":"[...]")}var tn={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with",EXISTS:"exists"},nn={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with",EXISTS:"does not exist"},Ld={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable",FOCUSED:"is focused"},Od={EXISTS:"does not exist",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable",FOCUSED:"is not focused"};function Jv(t){switch(t.type){case"ELEMENT_CONTENT":return`content ${t.negated?nn[t.operation]:tn[t.operation]} '${t.value}'`;case"ELEMENT_ATTRIBUTE":{let n=t.negated?nn[t.operation]:tn[t.operation];return t.operation==="EXISTS"?`attribute '${t.attr}' ${n}`:`attribute '${t.attr}' ${n} '${t.value}'`}case"ELEMENT_NAME":{let n=t.negated?nn[t.operation]:tn[t.operation];return t.operation==="EXISTS"?`tag name ${n}`:`tag name ${n} '${t.value}'`}case"ELEMENT_STYLE":{let n=t.negated?nn[t.operation]:tn[t.operation];return t.operation==="EXISTS"?`style property '${t.property}' ${n}`:`style property '${t.property}' ${n} '${t.value}'`}case"ELEMENT_EXISTENCE":return t.negated?Od[t.condition]:Ld[t.condition];default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}var U2={CONTENT:"The page"};function Qv(t){switch(t.type){case"VALUE":return`the option with value ${t.value}`;case"LABEL":return`the option with label ${t.label}`;case"INDEX":return`the option at index ${t.index}`;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function js(t){switch(t.type){case"SUBSTRING":return`match substring '${t.url}'`;case"REGEX":return`match regex '${t.regex}'`;case"GLOB":return`match glob '${t.glob}'`;case"DOMAIN":return`match domain '${t.domain}'`;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function $s(t){let e="";return t.method&&(e=` with method ${t.method}`),`${js(t.urlMatcher)}${e}`}function Zv(t){switch(t.type){case"CONTENT":return`${t.negated?nn.CONTAINS:tn.CONTAINS} '${t.value}'`;default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t.type)}}function jn(t,e=!0){switch(t.type){case"SUCCESS":return t.condition?.assertion?`Check success condition: ${t.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${t.goal}`;case"NAVIGATE":return`Go to URL: ${e?$e(t.url,30):t.url}`;case"DIALOG":return`Automatically ${t.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 ${t.deltaY?`${t.deltaY}px`:"1 page height"}${t.target?` in the container of: ${ht(t.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${t.deltaY?`${t.deltaY}px`:"1 page height"}${t.target?` in the container of: ${ht(t.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${t.deltaX?`${t.deltaX}px`:"1 page width"}${t.target?` in the container of: ${ht(t.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${t.deltaX?`${t.deltaX}px`:"1 page width"}${t.target?` in the container of: ${ht(t.target)}`:""}`;case"WAIT":return`Wait for ${t.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(t.target?.type==="coordinates")return`Click at coordinates: ${ht(t.target)}`;let r="";return t.target?.elementDescriptor.length?r=` on element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(r=` on element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Click${r}`}case"FOCUS":return`Focus ${ht(t.target)}`;case"BLUR":return`Focus ${ht(t.target)}`;case"DRAG":return`Drag ${ht(t.fromTarget)} onto ${ht(t.toTarget)}`;case"MOUSE_DRAG":return t.target?.type==="description"&&t.target.elementDescriptor?`Click and drag ${ht(t.target)} by ${t.deltaX}px horizontally, ${t.deltaY}px vertically`:`Click and drag mouse by ${t.deltaX}px horizontally, ${t.deltaY}px vertically`;case"TYPE":{let r="";return t.target?.type==="coordinates"?r=` in element at coordinates: ${ht(t.target)}`:t.target?.elementDescriptor.length?r=` in element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(r=` in element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Type '${t.value}'${r||""}`}case"HOVER":{let r="";return t.target.type==="coordinates"?r=` over coordinates: ${ht(t.target)}`:t.target.elementDescriptor.length>0?r=` over element: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(r=` over element: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Hover${r}`}case"PRESS":return`Press ${t.value}`;case"KEY_DOWN":return`Hold down ${t.value} on the keyboard`;case"KEY_UP":return`Release ${t.value} on the keyboard`;case"SELECT_OPTION":{let r="",o=Qv(t.choice);return t.target.type==="coordinates"?r=` from element at coordinates: ${ht(t.target)}`:t.target.elementDescriptor.length>0?r=` from: '${t.target.elementDescriptor}'`:t.cache?.target.nodeOnlySerializedHtml&&(r=` from: '${t.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${o}'${r}`}case"TAB":switch(t.action.type){case"SUBSTRING":return`Switch to tab with substring: ${t.action.substring}`;case"REGEX":return`Switch to tab matching regex: ${t.action.pattern}`;case"INDEX":return`Switch to tab at index: ${t.action.index}`;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t.action)}return"Switch to unknown tab";case"NEW_TAB":return`Open new tab to: ${t.url}`;case"REQUEST":return`Send ${t.method} request to ${t.url}`;case"GRAPHQL_REQUEST":return`Send GraphQL request to ${t.url}`;case"COOKIE":return`Set cookie: ${t.value}`;case"LOCAL_STORAGE":return`Set local storage: ${t.key}: ${t.value}`;case"JAVASCRIPT":return`Run JavaScript: ${e?$e(t.code,30):t.code}`;case"AI_ASSERTION":return`Assertion: '${t.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${t.target?`for element: ${ht(t.target)}`:"for entire page"}`;case"FILE_UPLOAD":return t.fileSource.type==="URL"?`Upload file: ${t.fileSource.url}`:`Upload file: ${t.fileSource.name}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Check the element ${ht(t.target)} ${Jv(t.assertion)}`;case"PAGE_CHECK":return`Check the page ${Zv(t.assertion)}`;case"WAIT_FOR_URL":return`Wait for page URL to ${js(t.matcher)}`;case"COPY":return"Copy to clipboard";case"PASTE":return"Paste clipboard contents";case"REGISTER_REQUEST_LISTENER":return t.requestMatcher?`Register a listener for network requests that ${$s(t.requestMatcher)}`:"Register a listener for network requests";case"AWAIT_LISTENER":return t.key?`Wait for the listener ${t.key} to resolve`:"Wait for a listener to resolve";case"RECORD_REQUESTS":return t.requestMatcher?`Start recording requests that match ${$s(t.requestMatcher)}`:"Start recording network requests";case"GET_RECORDED_REQUESTS":return t.key?`Get the requests that were recorded for ${t.key}`:"Get the requests that were recorded";case"SET_HEADER":return t.name?t.requestMatcher?`Set a ${t.name} header for requests that match ${$s(t.requestMatcher)}`:`Set a ${t.name} header for all requests`:"Set a header";case"MOCK_ROUTE":return t.requestMatcher?`Mock requests that ${$s(t.requestMatcher)}`:"Mock a network route";case"REMOVE_ROUTE_MOCK":return t.key?`Remove the mock with key ${t.key}`:"Remove all route mocks";case"OFFLINE_MODE":return t.enable?"Enable offline mode":"Disable offline mode";default:return(r=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function Bh(t){let e=[];for(let n of t){n.sort((i,s)=>i.timestamp-s.timestamp);let r=[],o,a=1;for(let i of n)o&&o.text===i.text&&o.type===i.type&&JSON.stringify(o.args??null)===JSON.stringify(i.args??null)?a++:(o&&(a>1?o.args&&o.args.length?o.args.push(`(repeated ${a} times)`):o.text+=` (repeated ${a} times)`:r.push(o)),o=i,a=1);o&&r.push(o),e.push(r)}return e}import{cloneDeep as $2}from"lodash-es";import{v4 as K2}from"uuid";import{cloneDeep as eA}from"lodash-es";import Wh from"truncate-json";import{cloneDeep as Q2,unset as Z2}from"lodash-es";function hr(t){switch(t.type){case"AI_ACTION":return`AI action: ${$e(t.text,100)}`;case"AI_ACTION_DYNAMIC":return`AI action: ${$e(t.text,100)}`;case"PRESET_ACTION":return jn(t.command);case"MODULE":return`Module: ${t.id}`;case"RESOLVED_MODULE":return`Module: ${t.name}`;case"CONDITIONAL":return"Conditional step";case"SECTION":return`Section${t.description?`with goal: ${$e(t.description,100)}`:""}`;default:return(n=>{throw new Error("You missed a case in the switch above")})(t)}}function Qr(t,e){return t.split(`
19
19
  `).map(n=>" ".repeat(e)+n).join(`
20
- `)}function Ad(t){switch(t.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":{let e="results"in t&&Array.isArray(t.results)?t.results.length:0;return`AI action: ${t.text}
21
- ${Yr(`Sub-steps: ${e}`,2)}`}case"PRESET_ACTION":return $n(t.command,!1);case"MODULE":{let e="results"in t&&Array.isArray(t.results)?t.results.length:0;if("moduleName"in t){let n=t.moduleName;return`Module: ${t.id} ModuleName: ${n}
22
- ${Yr(`Sub-steps: ${e}`,2)}`}return`Module: ${t.id}
23
- ${Yr(`Sub-steps: ${e}`,2)}`}case"RESOLVED_MODULE":return`Module: ${t.name}`;case"CONDITIONAL":{let e=["Conditional step"];if("assertionResult"in t&&t.assertionResult&&(e.push(Yr("Conditional check:",2)),e.push(Yr(Ad(t.assertionResult),2))),"results"in t&&Array.isArray(t.results)){let n=t.results.length,r="assertionResult"in t&&t.assertionResult?"Branch steps":"Else branch steps";e.push(Yr(`${r}: ${n}`,2))}return e.join(`
20
+ `)}function Nd(t){switch(t.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":{let e="results"in t&&Array.isArray(t.results)?t.results.length:0;return`AI action: ${t.text}
21
+ ${Qr(`Sub-steps: ${e}`,2)}`}case"PRESET_ACTION":return jn(t.command,!1);case"MODULE":{let e="results"in t&&Array.isArray(t.results)?t.results.length:0;if("moduleName"in t){let n=t.moduleName;return`Module: ${t.id} ModuleName: ${n}
22
+ ${Qr(`Sub-steps: ${e}`,2)}`}return`Module: ${t.id}
23
+ ${Qr(`Sub-steps: ${e}`,2)}`}case"RESOLVED_MODULE":return`Module: ${t.name}`;case"CONDITIONAL":{let e=["Conditional step"];if("assertionResult"in t&&t.assertionResult&&(e.push(Qr("Conditional check:",2)),e.push(Qr(Nd(t.assertionResult),2))),"results"in t&&Array.isArray(t.results)){let n=t.results.length,r="assertionResult"in t&&t.assertionResult?"Branch steps":"Else branch steps";e.push(Qr(`${r}: ${n}`,2))}return e.join(`
24
24
  `)}case"SECTION":{let e="results"in t&&Array.isArray(t.results)?t.results.length:0;return`Section${t.description?`with goal: ${t.description}`:""}
25
- ${Yr(`Sub-steps: ${e}`,2)}`}default:return(n=>{throw new Error("You missed a case in the switch above")})(t)}}var Lh=1e3,Mh=3e6,jv="[FAILED]";async function Oh(t,e,n){if(n){let r=await e.getScreenshot(t,n);if(r)return`data:image/jpeg;base64,${Buffer.from(r).toString("base64")}`}}function Gv(t,e){let n=(()=>{switch(t.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":return"AI action";case"PRESET_ACTION":return"Preset action";case"MODULE":return"Module";case"CONDITIONAL":return"Conditional step";case"SECTION":return"Section";default:return(i=>{throw new Error("You missed a case in the switch above")})(t)}})();return(o=>e?`${e==="start"?"Start":"End"} of ${n}
26
- ${o}`:o)(Ad(t))}function Fs(t,e={}){let{index:n,includeDomState:r=!1,header:o}=e,i=Gv(t,o),a;t.type==="PRESET_ACTION"&&(a=t.results?.[0]?.elementInteracted);let s=t.message!=="Successfully executed preset action."?t.message:void 0,l=i;t.status==="FAILED"&&(l=`${jv} ${l}`);let c={description:l,startedAt:t.startedAt.toISOString(),finishedAt:t.finishedAt.toISOString(),beforeUrl:t.beforeUrl,afterUrl:t.afterUrl,beforeSnapshot:t.beforeSnapshot,afterSnapshot:t.afterSnapshot,elementInteracted:a,message:s,index:n};if(t.status==="FAILED"&&r)try{let d=Zm.array().parse(t.details);for(let u of d)"pageState"in u&&(c.pageState=u.pageState)}catch{}return c}async function Dh(t,e,n,{addIndices:r=!0,includeDomState:o=!1,flatten:i=!0,maxItemsFromEnd:a=15,indexOffset:s=0}){let l,c=[];for(let d=0;d<n.length;d++){let u=n[d],m=r?d+s:void 0;switch(u.type){case"PRESET_ACTION":{c.push(Fs(u,{index:m,includeDomState:o,header:void 0})),u.status==="FAILED"&&(l=m);break}case"CONDITIONAL":case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":case"SECTION":{if(i){c.push(Fs(u,{index:r?m:void 0,includeDomState:o,header:"start"})),s+=1;let{failureIndex:g,results:p}=await Dh(t,e,u.results,{addIndices:r,includeDomState:o,flatten:i,maxItemsFromEnd:a,indexOffset:s+d});if(c.push(...p),g!==void 0){l=g;break}s+=p.length,c.push(Fs(u,{index:r?s+d:void 0,includeDomState:o,header:"end"})),s+=1}else c.push(Fs(u,{index:r?s+d:void 0,includeDomState:o,header:void 0}));break}default:return(p=>{throw new Error("You missed a case in the switch above")})(u)}if(l!==void 0)break}return{results:c,failureIndex:l}}async function Xo(t,e,n,{numStepsWithScreenshots:r=5,addIndices:o=!0,includeBeforeScreenshots:i=!1,includeDomState:a=!1,flatten:s=!0,maxItemsFromEnd:l=20}){let{results:c,failureIndex:d}=await Dh(t,e,n,{addIndices:o,includeDomState:a,flatten:s,maxItemsFromEnd:l,indexOffset:0}),u=[],m=0;if(l!==void 0&&c.length>l&&(m=c.length-l),d!==void 0&&d<c.length-1&&t.warn("PROCESS_RESULTS_FOR_LLM: Failure index check - should not be possible",{failureIndex:d,flattenedResultsLength:c.length,lastIndex:c.length-1,isLastIndex:d===c.length-1,offset:m}),d!==void 0&&m>d)throw new Error("Failure index is out of bounds");for(let g=m;g<c.length;g++){let p=c[g],h={description:p.description,startedAt:p.startedAt,finishedAt:p.finishedAt,beforeUrl:p.beforeUrl,afterUrl:p.afterUrl,elementInteracted:p.elementInteracted,message:p.message,pageState:p.pageState,index:p.index},f,S;(r===void 0||r>0&&g>=c.length-r)&&(p.afterSnapshot&&(S=await Oh(t,e,p.afterSnapshot)),i&&p.beforeSnapshot&&(f=await Oh(t,e,p.beforeSnapshot))),h.beforeScreenshot=f,h.afterScreenshot=S,u.push(h)}return{results:u,failureIndex:d!==void 0?d-m:void 0}}function Id({json:t,keysToRedact:e,maxJsonStringSize:n}){try{if(!t)return t;if(typeof t=="string")return He(t,n??2e4);if(typeof t=="object"){let{jsonString:r}=_h(JSON.stringify(t,(o,i)=>e?.includes(o)||typeof i=="string"&&i.length>3e4?"REDACTED":i),n??2e4);return JSON.parse(r)}return t}catch{return t}}function xd(t,e){for(let n=0;n<t.length;n++){let r=t[n];try{if(r.data){let{jsonString:o}=_h(JSON.stringify(r.data),1e3);r.data=JSON.parse(o)}}catch(o){e.error({err:o},"Failed to serialize individual result output data"),r.data=`Result output data could not be serialized: ${o}`}switch(r.details&&(r.details=void 0),r.type){case"PRESET_ACTION":Nh(r);break;case"CONDITIONAL":r.assertionResult&&Nh(r.assertionResult),xd(r.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":{xd(r.results,e);break}default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}}function Nh(t){let e=t.command;"cache"in e&&e.cache&&(e.cache=void 0)}function kh(t,e){let n=JSON.stringify(t),r=n.replaceAll("\\u0000","");if(n.length!==r.length){let o=n.indexOf("\\u0000");e.warn({input:n.slice(Math.max(0,o-500),Math.min(n.length,o+500))},"Database content violation: stripped unicode character from input")}return r}function Us(t,e){let n=$v(t);if(xd(n,e),n.length>Lh)return e.error("Database content violation: results too long, truncating before insertion"),n.slice(0,Lh);let r=kh(n,e);if(r.length>Mh)for(e.error({serializedLength:r.length,resultsArrayLength:n.length},"Database content violation: results too large, truncating before insertion");r.length>Mh;)n.pop(),r=kh(n,e);try{return et.array().parse(JSON.parse(r))}catch(o){throw e.error({serialized:r,err:o},"Could not parse serialized results into JSON structure after processing"),o}}import{cloneDeep as tY}from"lodash-es";var Wv=/^(?!.*\S+\s+\S+).*$/,Vv=/^[a-zA-Z0-9\s.,;:'"!?()\- \u00C0-\u00FF]+$/,qv=/style="([^"]*)/g,Kv=/data-[\w-]+/g,Yv=t=>{switch(t.type){case"AI_ASSERTION":return{type:t.type,assertion:t.assertion};case"DRAG":if(t.fromTarget.type==="description")return{type:t.type,description:t.fromTarget.elementDescriptor};break;case"CLICK":case"BLUR":case"TYPE":case"SELECT_OPTION":case"ELEMENT_CHECK":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"VISUAL_DIFF":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":if(t.target?.type==="description")return{type:t.type,description:t.target.elementDescriptor};break}return{type:"NONE",description:"NONE"}};function Fh(t){let e=Yv(t),n=e.type==="AI_ASSERTION"?e.assertion:e.description;return!n||n==="NONE"?{thoughts:"NONE",category:"NO_DESCRIPTION_PROVIDED"}:Wv.test(n)&&Vv.test(n)?{thoughts:"The target description is too short. Please provide more details.",category:"FEW_WORDS"}:qv.test(n)?{thoughts:"Style tags are not recommended in the command description as they change frequently. Please remove them and describe the target in a different way.",category:"STYLE_TAG"}:Kv.test(n)?{thoughts:"Hardcoded data attributes are not recommended in the command description as they change frequently.",category:"HARDCODED_ATTRIBUTE"}:new RegExp(`\\b${e.type}\\b`,"gi").test(n)?{thoughts:`The element description you provided starts with the command type (${e.type}). This can confuse our AI agents since the element itself is unrelated to the desired action.`,category:"TYPE_IN_DESCRIPTION"}:{thoughts:"NONE",category:"NONE"}}function Uh(t,e){if(!(!t.envs||!t.envs.length)){for(let n of t.envs){let r=n;e in n&&(r[e]&&(n.default=!0),delete r.defaultOnCloud,delete r.defaultOnLocal)}t.envs.some(n=>n.default)||(t.envs[0].default=!0)}}import{cloneDeep as uf}from"lodash-es";import eA from"diff-lines";import zs,{gte as tA}from"semver";var Bh={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async t=>(t=t.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),t=t.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),t)};var zh={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 t=>t.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let n=e.commands,r=n[n.length-1];return r&&r.type!=="SUCCESS"&&n.push({type:"SUCCESS"}),e})};var Xv=["target","fromTarget","toTarget"];function Hh(t){for(let e of Xv){if(t[e]===void 0)continue;let n=t[e];n.elementDescriptor!==void 0?n.type="description":t[e]={type:"description",elementDescriptor:""}}}var $h={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":return Hh(e.command),e;case"AI_ACTION":{let n=e.commands;for(let r of n??[])Hh(r);return e}default:return e}})};import{v4 as Jv}from"uuid";var jh={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=Jv()),e;default:return e}})};import{v4 as Gh}from"uuid";var Wh={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let n=e.command;return n.id=n.id??Gh(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(n=>({type:"PRESET_ACTION",command:{...n,id:n.id??Gh()}})),delete e.commands),e;default:return e}})};var Vh={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 t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let n=e.command;return typeof n.type!="string"||n.type!=="AI_WAIT"||(n.type="AI_ASSERTION",n.timeout||(n.timeout=10)),e}default:return e}})};import{v4 as Qv}from"uuid";var qh={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 t=>t.map(e=>("id"in e&&typeof e.id=="string"||(e.id=Qv()),e))};import{v4 as Kh}from"uuid";var Yh={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 t=>t.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let n=e.condition;n.id||(n.id=Kh())}return e.id=Kh(),e})};var Xh={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 t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||typeof n.envKey!="string"||(e.envKey=n.envKey,delete n.envKey),e})};import{v4 as Zv}from"uuid";var Jh={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=Zv()),e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||typeof n.envKey!="string"||(e.envKey=n.envKey,delete n.envKey),e})};var Qh={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:n.option},e.option=void 0),e})};var Zh={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return n&&ef(n),e})};function ef(t){t&&Object.keys(t).forEach(e=>{if(typeof t[e]=="object"&&t[e]){ef(t[e]);return}if(typeof t[e]!="string")return;let n=t[e];e==="code"?t[e]=n.replace(/inputs\./g,"env."):n.includes("{{")&&n.includes("}}")&&(t[e]=n.replace(/inputs\./g,"env."))})}var tf={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="TAB"||n.url===void 0||(n.action={type:"SUBSTRING",substring:n.url},n.url=void 0),e})};var nf={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="TYPE"?e:n.pressKeysSequentially===void 0?(n.delay=0,e):(n.pressKeysSequentially&&(n.pressKeysSequentially=void 0,n.delay=50),e)})};var rf={name:"Migrate wait for URL to matcher",fromVersion:"1.0.18",toVersion:"1.0.19",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="WAIT_FOR_URL"||n.url===void 0||(n.matcher={type:"GLOB",glob:n.url},n.url=void 0),e})};var of={name:"Migrate select choice round 2",fromVersion:"1.0.19",toVersion:"1.0.20",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;if(!n)return e;if(n.type==="SELECT_OPTION"){if(n.option===void 0)return e;n.choice={type:"VALUE",value:n.option},n.option=void 0}else if(n.type==="TAB"){if(n.url===void 0)return e;n.action={type:"SUBSTRING",substring:n.url},n.url=void 0}else if(n.type==="WAIT_FOR_URL"){if(n.url===void 0)return e;n.matcher={type:"GLOB",glob:n.url},n.url=void 0}else n.type==="AI_WAIT"&&(n.type="AI_ASSERTION",n.timeout||(n.timeout=10));return e})};var af={name:"Migrate AI checks to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async t=>t.map(e=>{if(e.type!=="AI_ASSERTION")return e;let r={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...r};return delete o.text,o}),stopOnFailure:!0};var Bs=new Set(["CLICK","TYPE","SELECT_OPTION"]),sf={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async t=>t.map(e=>{let n=e.command,r=n?.type,o=n?.elementDescriptor;return(o!==void 0||Bs.has(r))&&(n.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let s=a?.elementDescriptor,l=a?.type;(s!==void 0||Bs.has(l))&&(a.target={elementDescriptor:s??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let s=a.command,l=s?.elementDescriptor,c=s?.type;(l!==void 0||Bs.has(c))&&(s.target={elementDescriptor:l??""}),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(u=>{let m=u?.elementDescriptor,g=u?.type;(m!==void 0||Bs.has(g))&&(u.target={elementDescriptor:m??""})})}),e}),stopOnFailure:!0};var lf={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async t=>t.map(e=>{let n=e;return n.status==="FAILURE"&&(n.status="FAILED"),typeof n.commands=="object"&&Array.isArray(n.commands)&&n.commands.forEach(r=>{if(r&&typeof r=="object"){let o=r;o?.status==="FAILURE"&&(o.status="FAILED")}}),n}),stopOnFailure:!0};var cf={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async t=>t.map(e=>{let n=e.command,r=n?.type;return r?.startsWith("PRESET_")&&(n.type=r.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let a=i.type;a?.startsWith("PRESET_")&&(i.type=a.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let a=i.command,s=a?.type;s?.startsWith("PRESET_")&&(a.type=s.slice(7)),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(c=>{let d=c.type;d?.startsWith("PRESET_")&&(c.type=d.slice(7))})}),e}),stopOnFailure:!0};var Xr=[af,lf,cf,sf,Bh,zh,$h,jh,Wh,Vh,qh,Yh,Xh,Jh,Qh,Zh,tf,nf,rf,of];if(ce!==Xr[Xr.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");Xr.forEach((t,e)=>{if(!zs.valid(t.toVersion)||!zs.valid(t.fromVersion))throw new Error(`Migration '${t.name}' has invalid version`);if(!zs.gt(t.toVersion,t.fromVersion))throw new Error(`Migration '${t.name}' has toVersion <= fromVersion`);if(e===0)return;if(Xr[e-1].toVersion!==t.fromVersion)throw new Error(`Migration '${t.name}' at index ${e} is not contiguous with previous migration`)});function nA(t){return t.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var ea=async({metadata:t,steps:e,logger:n,toVersion:r})=>{let o=e,{schemaVersion:i,id:a}=t,s=Xr.findIndex(d=>zs.gt(d.toVersion,i));if(s===-1)return{steps:o,newVersion:i};let l=i;for(let d=s;d<Xr.length;d++){if(r&&tA(l,r)){n.debug("Stopping migration early because toVersion was reached");break}let u=Xr[d],m={id:a,migration:u.name,toVersion:u.toVersion};try{o=await df(o,u),l=u.toVersion}catch(g){throw n.error({err:g,...m},"Migration failed"),new Error(`Step migration ${u.name} failed: ${g}`)}}let c=eA(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return c.trim()&&n.debug({diffs:c,id:a},"Migration diffs"),{newVersion:l,steps:o}};async function df(t,e){let n=await e.execute(t);for(let r of n)for(let o of Object.keys(r)){if(!e.recursiveKeys.has(o))continue;let i=r[o];!i||!Array.isArray(i)||nA(i)&&(r[o]=await df(i,e))}return n}async function mf({rawSteps:t,metadata:e,logger:n,callbacks:r}){Uh(e,"defaultOnCloud");let o={},{resolvedSteps:i,newSchemaVersion:a}=await Hs({rawSteps:t.steps,migrationMetadata:e,logger:n,callbacks:r,resolvedModuleCache:o}),s={...e,steps:i,schemaVersion:a};for(let l of["beforeSteps","afterSteps"]){let c=t[l];if(!c)continue;let{resolvedSteps:d}=await Hs({rawSteps:c,migrationMetadata:e,logger:n,callbacks:r,resolvedModuleCache:o});s[l]=d}return{resolvedTest:s,moduleIds:Array.from(Object.keys(o))}}async function Jr(t,e,n){let{newVersion:r,steps:o}=await ea({metadata:t,steps:e,logger:n});try{return{steps:Le.array().parse(o),newVersion:r}}catch(i){throw n.error({type:"zod",err:i,newVersion:r,id:t.id,steps:o},"Failed to parse test steps while migrating test"),new ps(`Failed to parse test steps while migrating test: ${i}`,t.id,"entity",{cause:i})}}async function Hs({rawSteps:t,migrationMetadata:e,logger:n,callbacks:r,resolvedModuleCache:o={}}){let{newVersion:i,steps:a}=await Jr(e,t,n),s=[];for(let l of a)s.push(await ta({step:l,callbacks:r,logger:n,resolvedModuleCache:o}));return{resolvedSteps:s,newSchemaVersion:i}}async function ta({step:t,callbacks:e,logger:n,resolvedModuleCache:r}){switch(t.type){case"AI_ACTION":return t;case"AI_ACTION_DYNAMIC":return t;case"PRESET_ACTION":return t;case"MODULE":{let l=t.moduleId,c=r[l];if(c)return{...uf(c),...t,type:"RESOLVED_MODULE"};let d=await e.onFetchModule({id:l,logger:n});if(!d)throw new Error(`Could not find module with id ${l}`);let{newVersion:u,steps:m}=await ea({metadata:{id:l,schemaVersion:d.schemaVersion},steps:d.steps,logger:n}),g;try{g=Le.array().parse(m)}catch(f){throw n.error({type:"zod",err:f,steps:m,newVersion:u,id:l},"Module failed to parse"),f}let p;try{p=await Promise.all(g.map(f=>ta({step:f,callbacks:e,logger:n,resolvedModuleCache:r})))}catch(f){throw n.error({err:f,...t},`Failed to recursively resolve module '${d.name}': ${f}`),f}let h={...d,steps:p};return r[l]=uf(h),{...h,...t,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let l of t.blocks){let c=[];for(let d of l.steps)c.push(await ta({step:d,callbacks:e,logger:n,resolvedModuleCache:r}));o.push({...l,steps:c})}let i;if(t.elseSteps){i=[];for(let l of t.elseSteps)i.push(await ta({step:l,callbacks:e,logger:n,resolvedModuleCache:r}))}return{...t,blocks:o,elseSteps:i};case"SECTION":let a=[];for(let l of t.steps)a.push(await ta({step:l,callbacks:e,logger:n,resolvedModuleCache:r}));return{...t,steps:a};default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function rA(t){return typeof t=="object"&&t!==null}function jn(t){if(Array.isArray(t))return t.map(jn);if(rA(t)){let e={};return Object.entries(t).forEach(([n,r])=>{r!==void 0&&(e[n]=jn(r))}),e}return t}import{cloneDeep as oA}from"lodash-es";import{stringify as pf}from"yaml";async function gf({test:t,processedModuleNames:e=new Set,createNewCacheIds:n=!1}){let r={id:t.id,name:t.name,description:t.description,baseUrl:t.baseUrl,schemaVersion:t.schemaVersion,advanced:t.advanced,retries:t.retries,envs:t.envs,disabled:t.disabled,labels:t.labels},o={},i=await iA({originalStepLists:{steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps},modules:o,processedModuleNames:e,createNewCacheIds:n}),a={fileType:fe.TEST,...r,beforeSteps:i.beforeSteps&&i.beforeSteps.length>0?i.beforeSteps:void 0,steps:i.steps,afterSteps:i.afterSteps&&i.afterSteps.length>0?i.afterSteps:void 0};return{test:pf(a),modules:o}}async function iA({originalStepLists:t,modules:e,processedModuleNames:n,createNewCacheIds:r}){let o=oA(t);Object.values(o).forEach(s=>{aA(s??[])});let{stepsToSave:i,moduleUpdates:a}=await ze({stepLists:o,createNewCacheIds:r});for(let s of a)n.has(s.name)||(e[s.name]=sA(s),n.add(s.name));return i}function aA(t){Zi({steps:t,onPresetAction:e=>{e.aiSuggested=void 0,e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.aiSuggested=void 0,e.index=void 0},onSimpleStepContainer:e=>{e.aiSuggested=void 0,e.index=void 0}})}function sA(t){let e=Mt.parse(t),n={fileType:fe.MODULE,...e,schemaVersion:ce,steps:t.steps};return pf(n)}async function J(t,e){if(!(t<=0))return new Promise((n,r)=>{if(e?.aborted){r(e.reason);return}e?.addEventListener("abort",i);let o=setTimeout(()=>{e?.removeEventListener("abort",i),n()},t);function i(){clearTimeout(o),e?.removeEventListener("abort",i),r(e?.reason)}})}async function na({promiseGenerator:t,signal:e,codePath:n,logger:r}){let i=Date.now(),a=setInterval(()=>{if(e?.aborted){clearInterval(a);return}r?.warn({codePath:n,startTime:i,elapsedMilliseconds:Date.now()-i},`Asynchronous operation is taking a long time (${n})`)},5e3);return new Promise((s,l)=>{function c(){clearInterval(a),e?.removeEventListener("abort",c),l(e?.reason)}if(e?.aborted){l(e?.reason),clearInterval(a);return}e?.addEventListener("abort",c),(async()=>{try{s(await t())}catch(d){l(d)}finally{clearInterval(a),e?.removeEventListener("abort",c)}})()})}async function Qr({promiseGenerator:t,timeoutMs:e,codePath:n,logger:r,signal:o}){let i=!1,a=new AbortController,s=()=>{a.abort()},l=setTimeout(()=>{i||a.abort()},e);o?.addEventListener("abort",s);try{return await na({promiseGenerator:t,signal:a.signal,codePath:n,logger:r})}finally{i=!0,o?.removeEventListener("abort",s),clearTimeout(l)}}function hf(t){let e;return t>10*60*1e3?e=2*60*1e3:t>60*1e3?e=20*1e3:t>10*1e3?e=2*1e3:e=1e3,e}function $s(t){let e=[];for(let n of t)switch(n.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(n);break;case"RESOLVED_MODULE":{let r={...n,type:"MODULE"};e.push(an.parse(r));break}case"SECTION":{let r={...n,steps:$s(n.steps)};e.push(Le.parse(r));break}case"CONDITIONAL":{let r={...n,blocks:n.blocks.map(o=>({assertion:o.assertion,steps:$s(o.steps)})),elseSteps:n.elseSteps?$s(n.elseSteps):void 0};e.push(Dr.parse(r));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return e}function js(t){return $s([t])[0]}import lA from"picomatch";var ff=(t,e,n)=>{n?.caseInsensitive&&(t=t.toLowerCase());let r;switch(e.type){case"SUBSTRING":{let o=n?.caseInsensitive?e.url.toLowerCase():e.url;r=t.includes(o);break}case"GLOB":{let o=n?.caseInsensitive?e.glob.toLowerCase():e.glob;r=t===e.glob||lA(o)(t);break}case"REGEX":{r=new RegExp(e.regex).test(t);break}}return n?.negated?!r:r},Gs=(t,e)=>{try{let{hostname:n,pathname:r}=new URL(t),{hostname:o,pathname:i}=new URL(e);return n!==o||r!==i}catch{return!1}},Jo=t=>{try{return new URL(t),!0}catch{return!1}},Sf=t=>!t.toLowerCase().startsWith("http"),Qo=(t,e)=>{try{return new URL(t,e),!0}catch{return!1}};function Zr(t,e){try{return!!new URL(t).origin.trim()}catch(n){return e?.error({url:t,err:n},"Invalid URL in check"),!1}}async function cA(t){let{logger:e,browserStateStorage:n,generator:r,results:o,error:i,maxItemsFromEnd:a,numStepsWithScreenshots:s,disableCache:l}=t,c=[];if(o.length>0){let{results:u}=await Xo(e,n,o,{numStepsWithScreenshots:s,maxItemsFromEnd:a,includeBeforeScreenshots:!0,includeContainerTagsInDescription:!0});c=u}return await r.getTestResultClassification({results:c,errorMessage:i.message,errorStack:i.stack},{disableCache:l??!1})}async function yf(t){let{logger:e,browserStateStorage:n,generator:r,results:o,error:i,maxItemsFromEnd:a,numStepsWithScreenshots:s,disableCache:l}=t;if(!n||!o||o.length===0)return{};try{let c=await cA({logger:e,browserStateStorage:n,generator:r,results:o,error:i,maxItemsFromEnd:a,numStepsWithScreenshots:s,disableCache:l});return{classification:c,aiFailureReason:c.reason}}catch(c){return e.error({err:c},"Failed to classify test result"),{}}}function Zo({orgId:t,client:e,gitMetadata:n,alwaysSaveCache:r,noCache:o}){return o?new ws:new Pd(t,e,n,r)}var Pd=class{constructor(e,n,r,o){this.orgId=e;this.client=n;let{gitBranchName:i,gitProtectedBranches:a}=r;this.cacheHeaders=sd(r),o?this.writeCaches=!0:i?this.writeCaches=!a.includes(i):this.writeCaches=!0}cacheHeaders;writeCaches;async saveStepCacheEntries({entries:e,testId:n,logger:r}){if(!this.writeCaches){r.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:e,testId:n},this.cacheHeaders)}catch(o){r.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let{steps:n,beforeSteps:r,afterSteps:o}=e.stepLists,i=await this.client.getStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping cache last used at update because branch is protected");return}for(let s of[n,r,o])s&&Yo({steps:s,stepCacheEntries:i,logger:e.logger});let{cachesToSave:a}=await ze({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:a,testId:e.testId},this.cacheHeaders)}};import uA from"path";var mA=new xs(30,60*1e3),Nd="https://api.momentic.ai",bf,Tf=t=>{Nd=t},ra=()=>Nd;var ei,Od,Ws,wf=async t=>{if(bf&&ei&&Ws)return ei;let e=new Je({baseUrl:Nd,apiKey:t,logger:y});bf=e;try{let n=await e.getAuthInfo();return ei=n.orgId,Od=n.userId,Ws=t,ei}catch(n){throw new Error(`Error checking API key against server: ${n}`)}},nn=()=>{if(!ei)throw new Error("Your organization ID is invalid.");return ei},Vs=()=>{if(!Od)throw new Error("Your user ID is invalid.");return Od},kd=()=>{if(!Ws)throw new Error("Your API key is invalid.");return Ws},_d,Ld,qs=(t,e)=>{_d=t,Ld?.abort(),Ld=new AbortController;let n=Ld.signal,r=[t.configFilePath];t.config.environments?.forEach(o=>{if(!o.envFile)return;let i=uA.resolve(t.rootDir,o.envFile);try{if(Md.lstatSync(i).isSymbolicLink())return;Md.existsSync(i)&&r.push(i)}catch(a){y.warn({err:a},`Failed to check if env file ${i} exists`)}});try{pA({filesToWatch:r,revalidator:e,signal:n,project:t})}catch(o){y.error({err:o},"Failed to start config file watchers")}},ae=()=>_d;function pA({filesToWatch:t,revalidator:e,signal:n,project:r}){t.forEach(o=>{Md.watch(o,{signal:n,persistent:!1,recursive:!1},(i,a)=>{a&&(mA.increment("setLocalProject")&&y.warn(`A file change under the ${r.rootDir} directory has caused Momentic to reload its configuration more than 30 times in the last minute. Rapid changes to files may indicate your momentic.config.yaml 'include' glob is incorrect. Please ensure temporary, library, and auto-generated files are not included in Momentic's context.`),_d=e(r.configFilePath))})})}function me(t){return function(...e){let n=e[e.length-1],r=t(...e);Promise.resolve(r).catch(n)}}var ia=gA();function oa(t){let e=ae(),n=lt.dirname(e.configFilePath);return lt.join(n,...t)}function fA(t){let e=ae(),n=lt.dirname(e.configFilePath),r=lt.relative(n,t);return r?r.split(lt.sep):[]}function SA(t,e){let n=xt.statSync(t),r=fA(t);return ed.parse({name:e,absolutePath:t,relativePath:r.join(lt.sep),pathSegments:r,isDirectory:n.isDirectory(),size:n.size,createdAt:n.birthtime,modifiedAt:n.mtime,accessedAt:n.atime})}ia.post("/",me(async(t,e,n)=>{let r;try{r=ag.parse(t.body).pathSegments}catch(u){e.status(400).json({error:`Failed to parse folder read body: ${u}`});return}let o=oa(r);if(!xt.existsSync(o)){e.status(404).json({error:`Path not found: ${r.join(lt.sep)}`});return}if(!xt.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${r.join(lt.sep)}`});return}let a=ae(),s=Array.from(a.config.exclude??[]).concat(Ss),c=hA("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(u=>{let m=lt.join(o,u);return SA(m,u)}),d={absolutePath:o,pathSegments:r,contents:c};e.status(200).json(d)}));ia.put("/",me(async(t,e,n)=>{let r;try{r=sg.parse(t.body).pathSegments}catch(a){e.status(400).json({error:`Failed to parse folder create body: ${a}`});return}let o=oa(r);if(xt.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${r.join(lt.sep)}`,pathSegments:r});return}xt.mkdirSync(o,{recursive:!0});let i={success:!0,message:`Folder created: ${r.join(lt.sep)}`,pathSegments:r};e.status(201).json(i)}));ia.patch("/",me(async(t,e,n)=>{let r,o;try{let c=lg.parse(t.body);r=c.pathSegments,o=c.newPathSegments}catch(c){e.status(400).json({error:`Failed to parse folder update body: ${c}`});return}let i=oa(r),a=oa(o);if(!xt.existsSync(i)){e.status(400).json({error:`Folder not found: ${r.join(lt.sep)}`});return}if(xt.existsSync(a)){e.status(400).json({error:`Destination already exists: ${o.join(lt.sep)}`});return}let s=lt.dirname(a);xt.existsSync(s)||xt.mkdirSync(s,{recursive:!0}),xt.renameSync(i,a);let l={success:!0,message:`Folder moved from ${r.join(lt.sep)} to ${o.join(lt.sep)}`,pathSegments:o};e.status(200).json(l)}));ia.delete("/",me(async(t,e,n)=>{let r,o=!0;try{let l=cg.parse(t.body);r=l.pathSegments,o=l.recursive??!0}catch(l){e.status(400).json({error:`Failed to parse folder delete body: ${l}`});return}let i=oa(r);if(!xt.existsSync(i)){e.status(200).json({success:!0,message:`Folder not found: ${r.join(lt.sep)}`,pathSegments:r});return}if(!xt.statSync(i).isDirectory()){e.status(400).json({error:`Path is not a directory: ${r.join(lt.sep)}`});return}if(o)xt.rmSync(i,{recursive:!0,force:!0});else{if(xt.readdirSync(i).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${r.join("/")}`});return}xt.rmdirSync(i)}let s={success:!0,message:`Folder deleted: ${r.join("/")}`,pathSegments:r};e.status(200).json(s)}));var Dd=ia;import NM from"events";import Db,{Router as kM}from"express";import{diff as wA}from"deep-object-diff";import cn from"fs";import to from"path";import ti from"yaml";import{z as vf}from"zod";import{execSync as yA}from"child_process";function eo(t,e){let n=e.hooks?.postSave;if(!n)return;let r;n.includes("$1")?r=n.replaceAll("$1",t):r=`${n} ${t}`,y.debug({postSaveCommand:r},"Executing post-save hook command");try{yA(r,{encoding:"utf-8"})}catch(o){y.warn({err:o,postSaveCommand:r},"Failed to execute post-save hook command, continuing...")}}import{diff as Ef}from"deep-object-diff";import An from"fs";import{cloneDeep as bA}from"lodash-es";import aa from"path";import{v4 as TA}from"uuid";import sa from"yaml";function Ht({content:t,schemaVersion:e,momenticFiles:n,project:r,forceSaveOnNoDiffs:o}){let i=n.modules[t.moduleId]?.fullFilePath;if(!i||!An.existsSync(i))throw new Error(`Tried to update module ${t.moduleId} that could not be found on disk`);let a=An.readFileSync(i,"utf-8"),s=sa.parse(a),l;if(t.name&&t.name!==s.name){let g=`${ve(t.name)}.${st.MODULE}`;if(l=aa.join(aa.dirname(i),g),An.existsSync(l))throw new Error(`Module with name '${t.name}' already exists at path '${l}'`)}let c={...t,schemaVersion:e},d=jn({fileType:fe.MODULE,...rd.parse(c),steps:Le.array().parse(t.steps)}),u=Ef(d,s);if(u&&Object.keys(u).length===0&&!o){y.debug(`Skipping save for module ${t.moduleId} since there are no changes`);return}let m=sa.stringify(d);An.writeFileSync(i,m,"utf-8"),l&&An.renameSync(i,l),eo(l||i,r.config)}function Cf({moduleId:t,content:e,momenticFiles:n,project:r,logger:o}){let i=n.modules[t]?.fullFilePath;if(!i)throw new Error(`Tried to update module ${t} that could not be found on disk`);let a=Gn(i,o),s={...a,...e},l=jn({fileType:fe.MODULE,...rd.parse(s),steps:a.steps}),c=Ef(l,a);if(c&&Object.keys(c).length===0){y.debug(`Skipping save for module ${t} since there are no changes`);return}let d=sa.stringify(l);An.writeFileSync(i,d,"utf-8");let u;if(e.name){let m=`${ve(e.name)}.${st.MODULE}`;if(u=aa.join(aa.dirname(i),m),An.existsSync(u))throw new Error(`Module with name '${e.name}' already exists at path '${u}'`);An.renameSync(i,u)}eo(u||i,r.config)}async function Rf({name:t,description:e,enabled:n,steps:r,folder:o,project:i}){let a=ve(t),s=aa.join(o,`${a}.module.yaml`),l=TA(),{stepsToSave:c}=await ze({stepLists:{steps:r}}),d={fileType:fe.MODULE,schemaVersion:ce,moduleId:l,name:t,description:e,enabled:n,steps:c.steps},u=sa.stringify(d);return An.writeFileSync(s,u,"utf-8"),eo(s,i.config),{moduleId:l,name:t,description:e,enabled:n,steps:r}}function Gn(t,e){let n=An.readFileSync(t,"utf-8"),r=sa.parse(n);try{return qc.parse(r)}catch(o){throw e.error({err:o,moduleFilePath:t,moduleContents:n},`${t} does not parse as a valid Momentic module`),o}}async function Ks(t,e,n,r){let o=Gn(t.fullFilePath,n),{resolvedSteps:i}=await Hs({rawSteps:o.steps,migrationMetadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:r,logger:n,callbacks:{onFetchModule:async({id:s})=>{let l=e.modules[s]?.fullFilePath;if(l)return Gn(l,n)}}}),a={...o,steps:i};return r&&(r[t.id]=bA(a)),a}async function Ys(t,e){let n={};return await Promise.all(Object.values(t.modules).map(async r=>{await Ks(r,t,e,n)})),Array.from(Object.values(n))}async function Af({test:t,name:e,folder:n}){let r=await gf({test:t});if(Object.keys(r.modules).length)throw new Error("A brand new test should not contain any modules in it");let i=`${ve(e)}.${st.TEST}`,a=to.join(n,i);return cn.writeFileSync(a,r.test,"utf-8"),a}function Fd(t,e,n){let r=to.join(n.rootDir,t);if(!cn.existsSync(r))throw new Error(`Test not found at path '${t}' in project '${n.rootDir}'`);let o=cn.readFileSync(r,"utf-8"),i=ti.parse(o),a,s;if(e.name&&e.name!==i.name){let m=`${ve(e.name)}.${st.TEST}`;if(a=to.join(to.dirname(t),m),s=to.join(n.rootDir,a),cn.existsSync(s))throw new Error(`Test with name '${e.name}' already exists at path '${s}'`)}let l={...i,...e},c=Zt.parse(l),d={fileType:fe.TEST,...Zt.parse(c),beforeSteps:i.beforeSteps??void 0,steps:i.steps,afterSteps:i.afterSteps??void 0},u=ti.stringify(d);return cn.writeFileSync(r,u,"utf-8"),s&&cn.renameSync(r,s),eo(r,n.config),{newRelativeTestPath:a}}function It({relativeTestPath:t,steps:e,schemaVersion:n,project:r,forceSaveOnNoDiffs:o}){let i=to.join(r.rootDir,t);if(!cn.existsSync(i))throw new Error(`Test not found at path '${t}' in project '${r.rootDir}'`);let a=cn.readFileSync(i,"utf-8"),s=ti.parse(a),l=Zt.parse({...s,schemaVersion:n}),c=Le.array().or(vf.undefined()).parse(e.beforeSteps),d=Le.array().parse(e.steps),u=Le.array().or(vf.undefined()).parse(e.afterSteps),m=jn({fileType:fe.TEST,...l,beforeSteps:c&&c.length>0?c:void 0,steps:d,afterSteps:u&&u.length>0?u:void 0}),g=wA(m,s);if(g&&Object.keys(g).length===0&&!o){y.debug(`Skipping save for test ${l.name} since there are no changes`);return}let p=ti.stringify(m);cn.writeFileSync(i,p,"utf-8"),y.debug(`Saving test ${l.name} to ${i}`),eo(i,r.config)}function Xs(t,e){let n=to.join(e.rootDir,t);if(!n)throw new Error(`Could not find test with path ${t} in Momentic project (${e.rootDir})`);let r;try{r=cn.readFileSync(n,"utf8"),r=r.replace(/\r\n|\r/g,`
27
- `)}catch(i){throw new Error(`Could not read test file ${n}: ${i}`)}let o;try{o=ti.parse(r)}catch(i){throw new Error(`Could not parse test file ${n} as YAML: ${i}`)}return St.parse(o)}function no(t,e,n){let r=n.project.rootDir,o;try{o=cn.readFileSync(t,"utf-8")}catch(a){throw e.error({err:a,projectRoot:r},a.message),new Error(a.message)}let i=ti.parse(o);if(!i.steps||!Array.isArray(i.steps))throw new Error(`Test ${t} is missing steps`);return i}async function Pt(t,e,n){let r=no(t,e,n),o;try{o=Zt.parse(r)}catch(a){throw new Error(`Test ${t} is missing metadata or has invalid metadata: ${a}`)}let{resolvedTest:i}=await mf({rawSteps:{steps:r.steps,beforeSteps:r.beforeSteps,afterSteps:r.afterSteps},metadata:o,logger:e,callbacks:{onFetchModule:async({id:a,logger:s})=>{let l=n.modules[a]?.fullFilePath;if(l)return Gn(l,s)}}});return i}import EA from"@dotenvx/dotenvx";import CA from"fs";import xf from"path";function If(t,e){return(t.config.environments??[]).map(n=>la(n.name,t,e))}function Pf(t){return t.includes("${")?t.replace(/\$\{([^}]+)\}/g,(e,n)=>{let[r,o]=n.split(/:-|-/,2),i=process.env[r];return n.includes(":-")?i&&i!==""?i:o||"":n.includes("-")?i!==void 0?i:o||"":i||""}):t}function RA(t){let{envVariables:e,project:n}=t;if(!e)return{};let r={};for(let[o,i]of Object.entries(e)){if(typeof i=="string"){let s=Pf(i);s&&(r[o]=s);continue}let a;try{a=CA.readFileSync(xf.resolve(n.rootDir,i.fromFile),"utf-8")}catch(s){throw new Error(`Failed to read environment variable '${o}' from file '${i.fromFile}': ${s}`)}if(i.json)try{r[o]=JSON.parse(a)}catch(s){throw new Error(`Failed to parse environment variable '${o}' from file '${i.fromFile}' as JSON: ${s}`)}else r[o]=a}return Object.keys(r).length>0&&y.debug(r,"Set environment variables with interpolation from project configuration"),r}function vA(t){let{project:e,envFile:n,logger:r}=t,o={};if(!n)return o;let i=EA.config({path:xf.resolve(e.rootDir,n),processEnv:o,logLevel:"error",quiet:!0});if(i.error)throw new Error(`Failed to load .env file: ${i.error.message}`);return r.debug(o,"Set environment variables from .env file"),o}function la(t,e,n){let r=(e.config.environments??[]).find(l=>l.name===t);if(!r)throw new Error(`Environment ${t} not found in local project configuration file`);if(!r.baseUrl)throw new Error(`Browser environment ${t} does not have a baseUrl configured`);let o={[it]:Pf(r.baseUrl)},i=RA({envVariables:r.envVariables,project:e});Object.assign(o,i);let a=vA({project:e,envFile:r.envFile,logger:n});return Object.assign(o,a),r.inheritFromShell&&(n.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:t,variables:o,browser:r.browser}}import{existsSync as FA,readFileSync as UA,readdirSync as BA,writeFileSync as zA}from"fs";import{globSync as HA}from"glob";import ro,{dirname as Nf}from"path";import{cwd as $d}from"process";import kf from"yaml";import{z as ke}from"zod";import Lf from"fs";import{globSync as AA}from"glob";import ca from"path";import xA from"yaml";import{z as Ud}from"zod";var Mf=!1,Bd=[`**/*.${st.TEST}`,`**/*.${st.MODULE}`],zd=Ud.string().refine(t=>/^[a-zA-Z0-9-]+$/.test(t)),Hd=50,IA=Ud.object({fileType:Ud.nativeEnum(fe)});function te(t,e){let n={project:t,tests:{},modules:{},mobileTests:{},duplicateEntities:{}},r=t.config.include??Bd,o=Array.from(t.config.exclude??[]).concat(Ss),i=AA(r,{absolute:!1,cwd:t.rootDir,ignore:o,dotRelative:!1,maxDepth:Hd,nodir:!0});for(let a of i){let s=PA(t.rootDir,a,n,e);s&&(n.duplicateEntities[s.id]=s.paths)}return Mf=!0,n}function PA(t,e,n,r){let o=ca.join(t,e),i=LA(o,r);if(!i)return;let a=MA(i,o,r);if(!a)return;let s=IA.safeParse(a);if(s.success===!1){r.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${s.error}`);return}let l=s.data.fileType,c=OA(o,r);if(!c)return;let d=NA(e,o,c);switch(l){case fe.TEST:try{return kA(a,n,d,o,r)}catch(u){r.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${u}`);return}case fe.MODULE:try{return _A(a,n,d,o,r)}catch(u){r.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${u}`);return}case fe.MOBILE_TEST:try{return DA(a,n,d,o,r)}catch(u){r.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${u}`);return}default:{let u=l;return}}}function LA(t,e){try{return Lf.readFileSync(t,"utf-8")}catch(n){e.warn(`Could not read possible Momentic file at ${t}, skipping: ${n}`);return}}function MA(t,e,n){try{let r=xA.parse(t);if(typeof r!="object"||r===null)throw new Error("The YAML document should parse as a map with key-value pairs");return r}catch(r){n.warn(`Could not parse possible Momentic file at ${e}, skipping: ${r}`);return}}function OA(t,e){try{return Lf.statSync(t)}catch(n){e.warn(`Skipping path '${t}' because it could not be stat, skipping: ${n}`);return}}function NA(t,e,n){return{relativePath:t,fullFilePath:e,platformSep:ca.sep,fullPathSegments:e.split(ca.sep),relativePathSegments:t.split(ca.sep),fileName:ca.basename(e),lastModified:n.mtime,createdAt:n.birthtime}}function kA(t,e,n,r,o){let i=Zt.parse(t),a;if(e.tests[i.id]){let s=e.tests[i.id].fullFilePath;a={id:i.id,paths:[s,r]}}return e.tests[i.id]={type:fe.TEST,name:i.name,id:i.id,description:i.description??void 0,labels:i.labels,...n},a}function _A(t,e,n,r,o){let i=Mt.parse(t),a;if(e.modules[i.moduleId]){let l=e.modules[i.moduleId].fullFilePath;a={id:i.moduleId,paths:[l,r]}}e.modules[i.moduleId]={type:fe.MODULE,name:i.name,id:i.moduleId,description:i.description??void 0,...n};let s=n.fileName.replace(`.${st.MODULE}`,"");return!Mf&&ve(i.name)!==s&&o.warn(`The module with ID ${i.moduleId} has a name (${i.name}) that does not match its file name (${s}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),a}function DA(t,e,n,r,o){let i=Kc.parse(t),a;if(e.mobileTests[i.id]){let l=e.mobileTests[i.id].fullFilePath;a={id:i.id,paths:[l,r]}}let s=n.fileName.replace(`.${st.TEST}`,"");return e.mobileTests[i.id]={type:fe.MOBILE_TEST,name:s,id:i.id,description:i.description??void 0,...n},a}var ni="momentic.config.yaml",Of="momentic.workspace.yaml",$A=ke.object({projects:ke.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),jA=ke.union([ke.string(),ke.object({fromFile:ke.string(),json:ke.boolean().optional()})]),GA=ke.object({name:zd,baseUrl:ke.string().optional().describe("Optional for mobile tests"),envFile:ke.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:ke.record(ke.string(),jA).optional(),inheritFromShell:ke.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:Br.optional().describe("deprecated: use project-level configuration only")}),WA=ke.object({postSave:ke.string().optional()}),VA=ke.object({name:zd,include:ke.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:ke.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:ke.string().optional(),reporterDir:ke.string().optional(),outputDir:ke.string().optional(),retries:ke.number().optional().describe("number of retries per test"),parallel:ke.number().optional().describe("degree of parallelism"),environments:ke.array(GA).optional(),gitMainBranch:ke.string().optional(),gitProtectedBranches:ke.string().array().optional(),ai:od.optional(),browser:Br.optional(),advanced:id.optional(),hooks:WA.optional()});function _f(t,e){let n;try{n=UA(t,"utf-8")}catch(o){y.warn(`Could not read possible Momentic ${e} file at ${t}: ${o}`);return}let r;try{if(r=kf.parse(n),typeof r!="object"||r===null)throw new Error(`The ${e} file should parse as a map with key-value pairs, but is type ${typeof r} instead`)}catch(o){y.warn(`Possible Momentic ${e} file at ${t} does not parse as valid YAML: ${o}`);return}return r}function jd(t){let e=_f(t,"project configuration");if(e!==void 0)try{return VA.parse(e)}catch(n){y.warn(`Possible Momentic project configuration file at ${t} does not adhere to the required schema: ${n}`);return}}function qA(t){let e=_f(t,"workspace configuration");if(e!==void 0)try{return $A.parse(e)}catch(n){y.warn(`Possible Momentic workspace configuration file at ${t} does not adhere to the required schema: ${n}`);return}}function KA(){let t=[],e=$d(),n=ro.parse(e).root,r=15,o=0;for(;o<r;){o++;let i=ro.basename(e);if(fs.includes(i))return y.warn(`Stopping search for Momentic projects since the current directory name (${i}) is likely a system artifact folder.`),t;for(let a of BA(e))if(a.endsWith(ni)){let s=ro.join(e,a),l=jd(s);l&&t.push({configFilePath:s,config:l,rootDir:Nf(s)})}if(t.length)return t;if(e=ro.dirname(e),e===n)break}return t}function ct(t={}){let{configFilePath:e,nameFilter:n}=t,r=Gd(e);if(n&&(r=r.filter(o=>o.config.name===n)),r.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
28
- ${r.map(o=>o.configFilePath)}`);if(r.length===0)throw new Error("No valid Momentic project file available.");return y.debug(`Found valid project configuration at ${r[0].configFilePath}`),r[0]}function YA(t){let e=qA(t);if(!e||!e.projects||!e.projects.length)return;let n=e.projects.map(i=>(i.endsWith("/")||(i+="/"),`${i}*${ni}`)),r=HA(n,{absolute:!1,cwd:$d(),dotRelative:!1,maxDepth:Hd,nodir:!0}),o=[];for(let i of r){let a=ro.join($d(),i),s=jd(a);s&&o.push({configFilePath:a,config:s,rootDir:Nf(a)})}return o}function Gd(t){if(t){t=ro.resolve(t);let n=jd(t);return n||(console.error(`No valid Momentic project file found at ${t}.`),process.exit(1)),[{config:n,configFilePath:t,rootDir:ro.dirname(t)}]}if(FA(Of)){let n=YA(Of);if(n)return n}return KA()}function ri(t,e){let n=kf.stringify(t);zA(e,n)}import oi from"fs";import Wd from"path";import{z as Vd}from"zod";var Df="golden/visual-diff",Ff="reports",Uf="test-results";var XA=Vd.object({width:Vd.number(),height:Vd.number()}),ii=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,n){let r=Wd.join(e.rootDir,e.config.goldenFileDir??Df);this.defaultGoldenScreenshotDir=r,this.regenerateGoldenFiles=n}async prepareGoldenScreenshotForComparison(e,n,r){if(n.screenshot?.data?.startsWith("https://")){let a=await fetch(n.screenshot.data);return{buffer:Buffer.from(await a.arrayBuffer()),width:n.screenshot.width,height:n.screenshot.height}}let o=n.screenshot?.data;o||(o=Wd.join(this.defaultGoldenScreenshotDir,`${n.id}.jpg`));let i=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return oi.mkdirSync(Wd.dirname(o),{recursive:!0}),oi.writeFileSync(o,r.buffer),oi.writeFileSync(i,JSON.stringify({width:r.width,height:r.height})),{buffer:Buffer.from(r.buffer),width:r.width,height:r.height};if(oi.existsSync(o)){let a=oi.readFileSync(o),s=XA.parse(JSON.parse(oi.readFileSync(i,"utf-8")));return{buffer:a,width:s.width,height:s.height}}else throw new A("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};var hr=class{flags;constructor(e){this.flags={auto_expand_iframes:e.browser?.autoExpandIframes??!1,rag_v2:e.ai?.aiPageFiltering??!1,faker_constant_seed:e.advanced?.fakerConstantSeed??!1,disable_secondary_cache_resolution:e.browser?.disableSecondaryCacheResolution??!1,global_locator_redirect:e.browser?.globalLocatorRedirect??!0,visual_actions:e.browser?.visualActions??!1,mini_model_initial_assertion:!1,mini_model_initial_locator:!1,show_test_plans:!1,icon_knowledge_base:!1,disable_clickhouse_caches:!1,disable_clickhouse_last_updated_endpoint:!1}}isBooleanFlagEnabled(e){return this.flags[e]??!1}getAllFlags(){return{...this.flags}}getFlagPayload(e){}async refresh(){}};import{execFile as JA}from"node:child_process";import{promisify as QA}from"node:util";import ZA from"simple-git";var Ae=ZA(),Bf=QA(JA);async function ex(t){let e=await xe(t,Ae.raw(["config","--list"])),n={};if(!e)return n;for(let r of e.split(`
29
- `)){let o=r.indexOf("=");if(o===-1)continue;let i=r.slice(0,o),a=r.slice(o+1).trim();n[i]=a}return n}async function tx(t,e,n){try{let o=n["github.user"]||void 0;if(o)return o}catch{}let r;try{if(e?.startsWith("http://")||e?.startsWith("https://"))r=new URL(e).host;else if(e?.startsWith("git@")){let o=e.indexOf("@"),i=e.indexOf(":",o+1);o!==-1&&i!==-1&&(r=e.slice(o+1,i))}}catch{}if(r=r?.toLowerCase(),!!r){try{if(e?.startsWith("git@")&&r?.includes("github")){let{stdout:o,stderr:i}=await Bf("ssh",["-T","-o","BatchMode=yes",`git@${r}`],{timeout:5e3}),s=`${o??""}${i??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(s?.[1])return s[1]}}catch{}try{let o=r&&r!=="github.com"?["api","--hostname",r,"user","-q",".login"]:["api","user","-q",".login"],{stdout:i}=await Bf("gh",o,{timeout:5e3}),a=i?.toString().trim();if(a)return a}catch{}}}async function nx(t,e,n){let r=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(r)return tx(t,e,n);if(o)return}catch{}}function Js(t){if(t.startsWith("git@")){let e=t.split(":");if(e.length===2){let n=e[1].replace(".git","").split("/");if(n.length===2){let r=n[0],o=n[1];return`${r}/${o}`}}}else if(t.startsWith("http")||t.startsWith("https")){let n=new URL(t).pathname.split("/").filter(Boolean);if(n.length>=2){let r=n[0],o=n[1].replace(".git","");return`${r}/${o}`}}}async function xe(t,e){try{return(await e).trim()}catch(n){t.error({err:n},"Failed to run git command");return}}function rx(){if(process.env.GITHUB_ACTION)return"GithubActions";if(process.env.GITLAB_CI)return"GitlabCI";if(process.env.CIRCLECI)return"CircleCI";if(process.env.BUILDKITE)return"Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return"AzureDevOps";if(process.env.PROJECT_ID&&process.env.BUILD_ID)return"GCPCloudBuild"}async function ox(t){let[e,n,r,o]=await Promise.all([xe(t,Ae.show(["--no-patch","--format=%ci"])),xe(t,Ae.listRemote(["--get-url","origin"])),xe(t,Ae.show(["-s","--pretty=%B"])),xe(t,Ae.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:n,gitCommitMessage:r,gitCommitAuthorName:o,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function ix(t){let[e,n,r]=await Promise.all([xe(t,Ae.listRemote(["--get-url","origin"])),xe(t,Ae.show(["-s","--pretty=%B"])),xe(t,Ae.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:n,gitCommitAuthorName:r,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function ax(t){let[e,n,r,o]=await Promise.all([xe(t,Ae.show(["--no-patch","--format=%ci"])),xe(t,Ae.listRemote(["--get-url","origin"])),xe(t,Ae.show(["-s","--pretty=%B"])),xe(t,Ae.show(["-s","--pretty=%an"]))]),i=n?.includes("github.com"),a=n?.includes("gitlab.com"),s=n?Js(n):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:r,gitCommitAuthorName:o,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function sx(t){let[e,n,r]=await Promise.all([xe(t,Ae.show(["--no-patch","--format=%ci"])),xe(t,Ae.show(["-s","--pretty=%B"])),xe(t,Ae.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Js(o):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:n,gitCommitAuthorName:r,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function lx(t){let[e,n,r]=await Promise.all([xe(t,Ae.show(["--no-patch","--format=%ci"])),xe(t,Ae.show(["-s","--pretty=%B"])),xe(t,Ae.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],i=o?.includes("github.com"),a=o?.includes("gitlab.com"),s=o?Js(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:n,gitCommitAuthorName:r,githubRepository:i?s:void 0,gitlabProjectPath:a?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function cx(t,e){let[n,r,o,i,a,s,l,c,d]=await Promise.all([xe(t,Ae.revparse(["HEAD"])),xe(t,Ae.revparse(["--short","HEAD"])),xe(t,Ae.revparse(["--abbrev-ref","HEAD"])),xe(t,Ae.listRemote(["--get-url","origin"])),xe(t,Ae.show(["--no-patch","--format=%ci"])),xe(t,Ae.show(["-s","--pretty=%B"])),xe(t,Ae.show(["-s","--pretty=%an"])),e?xe(t,Ae.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),ex(t)]),u=c?await xe(t,Ae.show(["--no-patch","--format=%ci",c])):void 0,m=i?.includes("github.com"),g=i?.includes("gitlab.com"),p=i?Js(i):void 0,h=d["user.email"]||void 0,f=d["user.name"]||void 0,S=d["user.username"]||void 0,b=await nx(t,i,d)??S??void 0;return t.debug({userUsername:b,gitLocalUserLogin:S,gitLocalUserEmail:h,gitLocalUserName:f},"Resolved local git identity"),{gitCommitSha:n,gitCommitShaShort:r,gitBranchName:o,gitOriginUrl:i,gitCommitTimestamp:a?new Date(a):void 0,gitCommitMessage:s,gitCommitAuthorName:l,gitLocalUsername:b,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:c,lastCommitOnMainTimestamp:u?new Date(u):void 0,githubRepository:m?p:void 0,gitlabProjectPath:g?p:void 0,pipelineId:void 0}}async function dx(){let t=process.env._HEAD_REPO_URL;return{gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:t?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:t?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function ux(t){let e=t.config.gitProtectedBranches??[];return t.config.gitMainBranch&&e.push(t.config.gitMainBranch),{gitMainBranch:t.config.gitMainBranch,gitProtectedBranches:e}}async function qd(t,e){let n=rx();if(!n)return cx(t,e);switch(n){case"GithubActions":return ox(t);case"GitlabCI":return ix(t);case"CircleCI":return ax(t);case"Buildkite":return sx(t);case"AzureDevOps":return lx(t);case"GCPCloudBuild":return dx()}}async function mx(t,e,n,r){let o=r;if(!r.gitCommitSha)return o;if(r.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp)){let i=await e.getMergeBaseCommitFromGitlab(n,r.gitMainBranch,r.gitCommitSha);o={...o,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName){let i=await e.getCommitFromGitlab(n,r.gitCommitSha);i&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??i.author.name,gitCommitMessage:o.gitCommitMessage??i.message})}return o}async function px(t,e,n,r,o){let i=o;if(!o.gitCommitSha)return i;if(o.gitMainBranch&&(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)){let a=await e.getMergeBaseCommitFromGithub(n,r,o.gitMainBranch,o.gitCommitSha);i={...i,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}if(!i.gitCommitTimestamp||!i.gitCommitAuthorName||!i.gitCommitMessage||!i.gitCommitAuthorName){let a=await e.getCommitFromGithub(n,r,o.gitCommitSha);a&&(i={...i,gitCommitTimestamp:i.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:i.gitCommitAuthorName??a.author.name,gitCommitMessage:i.gitCommitMessage??a.message})}return i}async function gx(t,e,n){try{if(n.githubRepository){let[r,o]=n.githubRepository.split("/");return await px(t,e,r,o,n)}else if(n.gitlabProjectPath)return await mx(t,e,n.gitlabProjectPath,n)}catch(r){t.warn({err:r},"Failed to get remote git metadata")}return n}async function fr(t,e,n){let r=await ux(n),o=await qd(t,r.gitMainBranch),i={...r,...o};(!i.lastCommitOnMainSha||!i.lastCommitOnMainTimestamp)&&i.gitBranchName===r.gitMainBranch&&(i.lastCommitOnMainSha=i.gitCommitSha,i.lastCommitOnMainTimestamp=i.gitCommitTimestamp);let a=await gx(t,e,i);return{...r,...o,...a}}import SJ from"yaml";import{randomUUID as hx}from"crypto";import Wn from"fs";import oo from"path";var zf={status:(t,e)=>{if(t.status===e.status)return t.status;if(t.status==="FAILED"||e.status==="FAILED")return"FAILED";if(t.status==="CANCELLED"||e.status==="CANCELLED")return"CANCELLED";if(t.status==="RETRYING"||e.status==="RETRYING")return"RETRYING";if(t.status==="RUNNING"||e.status==="RUNNING")return"RUNNING";if(t.status==="PENDING"||e.status==="PENDING")return"PENDING";throw new Error(`Invalid run status merge: ${t.status} and ${e.status}`)},startedAt:(t,e)=>t.startedAt<e.startedAt?t.startedAt:e.startedAt,updatedAt:(t,e)=>t.updatedAt>e.updatedAt?t.updatedAt:e.updatedAt,finishedAt:(t,e)=>!t.finishedAt||!e.finishedAt?new Date:t.finishedAt>e.finishedAt?t.finishedAt:e.finishedAt,gitCommitTimestamp:(t,e)=>{if(!(!t&&!e)){if(!t.gitCommitTimestamp||!e.gitCommitTimestamp||t.gitCommitTimestamp.getTime()!==e.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${t.gitCommitTimestamp} and ${e.gitCommitTimestamp}`);return t.gitCommitTimestamp}},pipelineId:(t,e)=>t.pipelineId===e.pipelineId?t.pipelineId:!t.pipelineId&&e.pipelineId?e.pipelineId:!e.pipelineId&&t.pipelineId?t.pipelineId:t.startedAt<e.startedAt?e.pipelineId:t.pipelineId,labels:(t,e)=>{let n=new Set([...t.labels??[],...e.labels??[]]);return Array.from(n)}};function fx(t,e,n){if(zf[n]){let i=zf[n];return i(t,e)}let r=t[n],o=e[n];if(r!==o)throw new Error(`Metadata values for key "${n}" do not match: "${r}" vs "${o}"`);return r}var Hf=new Set([".DS_Store","__MACOSX"]);function $f(t,e,n){let r=hx(),o=t.child({runGroupId:r});Wn.rmSync(e,{recursive:!0,force:!0});let i=Wn.readdirSync(n).filter(c=>!Hf.has(c)).map(c=>oo.join(n,c));if(i.length===0)throw new Error(`No run groups found in results path: ${n}`);Wn.mkdirSync(e,{recursive:!0});let a=oo.join(i[0],"metadata.json"),s={...qi.parse(JSON.parse(Wn.readFileSync(a,"utf-8"))),id:r};for(let c of i){let d=oo.join(c,"runs");if(!Wn.existsSync(d))continue;let u=Wn.readdirSync(d);for(let p of u){if(Hf.has(p))continue;let h=oo.join(d,p),f=oo.join(e,"runs",p);Wn.cpSync(h,f,{recursive:!0})}let m=oo.join(c,"metadata.json"),g=qi.parse(JSON.parse(Wn.readFileSync(m,"utf-8")));o.info({oldRunGroupId:g.id},"Merging metadata from run groups");for(let p in g){if(p==="id")continue;let h=p;s[h]=fx(s,g,h)}}let l=oo.join(e,"metadata.json");Wn.writeFileSync(l,JSON.stringify(s,null,2))}import jf from"adm-zip";import Kd from"fs";import Qs from"path";function Sx(t){let e=new jf,n=Qs.join(t,"metadata.json"),r=qi.parse(JSON.parse(Kd.readFileSync(n,"utf-8")));e.addLocalFile(n);for(let o of Kd.readdirSync(Qs.join(t,"runs"))){if(!o.endsWith(".zip"))continue;let i=o.replace(/\.zip$/,""),a=new jf(Qs.join(t,"runs",o));for(let s of a.getEntries())s.isDirectory||e.addFile(Qs.join("runs",i,s.entryName),s.getData())}return{runGroupId:r.id,buffer:e.toBuffer()}}async function Zs(t){let{client:e,consoleLogger:n,resultsPath:r}=t;if(!Kd.existsSync(r)){n.warn("Results path does not exist, skipping upload.");return}let o=new Ps(e);try{let{runGroupId:i,buffer:a}=Sx(r),s=await o.uploadResultsArchive(i,a),l=`${e.getAppUrl()}/run-groups/${s}`;n.success(`Successfully uploaded test results. Once processed, your results can be found at ${l}`);return}catch(i){let a;i instanceof Error?a=i.message:typeof i=="string"?a=i:a="Unknown error",n.error(`Failed to upload test results: ${a}.`);return}}import yx from"adm-zip";import Lt from"fs";import dn from"path";var da=class t{constructor(e){this.filePath=e;Lt.rmSync(this.filePath,{recursive:!0,force:!0}),Lt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new t(dn.join(this.filePath,e))}mkdir(e){Lt.mkdirSync(dn.join(this.filePath,e),{recursive:!0})}readFile(e){let n=dn.join(this.filePath,e);if(Lt.existsSync(n))return Lt.readFileSync(n)}storeFile(e){let{name:n,contents:r}=e,o=dn.join(this.filePath,n);try{Lt.writeFileSync(o,r)}catch{}}createRunArchive(e){return new Yd(dn.join(this.filePath,"runs"),e)}},Yd=class{constructor(e,n){this.filePath=e;this.tempPath=dn.join(e,`.${n}`),this.finalPath=dn.join(e,`${n}.zip`),Lt.rmSync(this.tempPath,{recursive:!0,force:!0}),Lt.rmSync(this.finalPath,{recursive:!0,force:!0}),Lt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let n=dn.join(this.tempPath,e);if(Lt.existsSync(n))return Lt.readFileSync(n)}mkdir(e){Lt.mkdirSync(dn.join(this.tempPath,e),{recursive:!0})}cd(e){return new da(dn.join(this.tempPath,e))}storeFile(e){let{name:n,contents:r}=e,o=dn.join(this.tempPath,n);Lt.writeFileSync(o,r)}close(){let e=new yx;e.addLocalFolder(this.tempPath,void 0,r=>r!==".DS_Store");let n=e.toBuffer();Lt.writeFileSync(this.finalPath,n),Lt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import _M from"http";import DM from"path";import{Server as GL}from"socket.io";var bx=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async()=>{e.info({sessionId:r},"Cancel event received");let o=n.getSession(r);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},Gf={event:"cancel",createHandler:bx};var Tx=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async(o,i)=>{let a=n.getSession(r);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let c=(await s.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:c},"Fetched a11y tree from the browser"),i({a11yTree:c})}catch(l){e.error({err:l},"Error fetching a11y tree from the browser"),i({err:l.message})}}},Wf={event:"fetchA11yTree",createHandler:Tx};var wx=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async(o,i)=>{let a=n.getSession(r);if(!a)throw new Error("No active session found");a.controller.setOpen();let s=a.controller.browser;try{let l=await s.html();i({html:l})}catch(l){e.error({err:l},"Error fetching DOM from the browser"),l.name==="TimeoutError"?i({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):i({err:l.message})}}},Vf={event:"fetchDom",createHandler:wx};var Ex=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return o=>{e.info({sessionId:r,reason:o},`Disconnect event received (${o})`),n.removeSession(r,e)}},qf={event:"disconnect",createHandler:Ex};function xn(t){let{result:e,nestedResults:n}=t;if(!t.nestedResults.length)return;let{firstMetadata:r,lastMetadata:o}=Cx(n);Rx(e,r,o);let i=[...t.asyncTasks];t.asyncTasks.push((async()=>{try{await vx(i,e,r,o)}catch(a){t.logger.error({result:t.result,err:a},"Error hoisting scalar result metadata")}})())}function Cx(t){let e=t[0],n;for(;;){switch(e.type){case"PRESET_ACTION":{n=e;break}case"CONDITIONAL":if(e.assertionResult){n=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){n=e;break}e=e.results[e.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(n)break}let r=t[t.length-1],o;for(;;){switch(r.type){case"PRESET_ACTION":{o=r;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":if(!r.results.length){o=r;break}r=r.results[r.results.length-1];break;default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}if(o)break}return{firstMetadata:n,lastMetadata:o}}function Rx(t,e,n){e&&(t.beforeUrl=e.beforeUrl),n&&(t.afterUrl=n.afterUrl,t.data=n.data,n.status!=="SUCCESS"&&(t.message=n.message))}async function vx(t,e,n,r){await Promise.allSettled(t),n&&(e.beforeSnapshot=n.beforeSnapshot),r&&(e.afterSnapshot=r.afterSnapshot)}import ua from"os";import Ax from"v8";var Kf,In,xx=ua.platform(),Ix=ua.cpus().map(t=>({model:t.model,speed:t.speed})).reduce((t,e)=>(t[e.model]={speed:e.speed},t.totalCores=(t.totalCores??0)+1,t),{});function Yf(t){let e=()=>{try{let n=!1,r=Px(),o=Lx();r.freeMemory<1e6&&(n=!0);let i=Ax.getHeapStatistics(),a=i.used_heap_size,s=i.heap_size_limit;a/s>.9&&(n=!0),n?t.warn({memory:r,cpu:o,heapStats:i},"Critical resource usage metrics detected"):t.debug({memory:r,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,2e4),cpuMetadata:Ix,platform:xx}}function Px(){let t=ua.totalmem(),e=ua.freemem(),n=t-e;return{totalMemory:t,freeMemory:e,usedMemory:n}}function Lx(){let t=ua.cpus(),e=Date.now(),n={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of t)n.user+=o.times.user,n.nice+=o.times.nice,n.sys+=o.times.sys,n.idle+=o.times.idle,n.irq+=o.times.irq;if(n.total=n.user+n.nice+n.sys+n.idle+n.irq,!In)return In=n,null;let r={user:n.user-In.user,nice:n.nice-In.nice,sys:n.sys-In.sys,idle:n.idle-In.idle,irq:n.irq-In.irq,total:n.total-In.total};return Kf={measurementTime:e,intervalMs:e-In.measurementTime,user:r.user/r.total*100,nice:r.nice/r.total*100,sys:r.sys/r.total*100,idle:r.idle/r.total*100,irq:r.irq/r.total*100,total:100-r.idle/r.total*100},In=n,Kf}import{randomUUID as Bx}from"crypto";import{faker as Mx}from"@faker-js/faker";import Ox from"assert";import Nx from"axios";import*as kx from"child_process";import _x from"moment";import*as Dx from"otpauth";import Fx from"pg";async function Xf(t){let e;try{e=new URL(t.url).hostname}catch{}let n=[];return t.headers.getSetCookie()?.forEach(r=>{let o=ss(r,e);n.push(...o)}),n}var Ux=Object.getPrototypeOf(async function(){}).constructor;async function Jf(t,e,n){let r=e.code;e.options.fragment&&(r=`return ${e.code}`);let{env:o}=e.bindings,i=e.tools,a={},s=(f,S)=>{o[f]=S,a[f]=S},l={},c=(f,S)=>{o[f]=S,l[f]=S},d;r.includes("Octokit")&&(d=(await import("@octokit/rest")).Octokit);let u;r.includes("createAppAuth")&&(u=(await import("@octokit/auth-app")).createAppAuth);let m=async()=>await Promise.resolve(new Ux("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai",r)(Nx,_x,i.fakerInstance??Mx,Ox,Fx,d,u,Dx,kx,Xf,o,s,c,S=>i.sms.send(S),S=>i.sms.fetchLatest(S),i.email,i.sms,i.ai)),g=!0,p,h;try{p=await z(m(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal})}catch(f){n.error({err:f,env:o,evalCode:r},`[${t}] Error executing code: ${f}`),g=!1,f instanceof mr?h=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:h=f instanceof Error?f.message:`${f}`}return{result:p,variableUpdates:a,persistentVariableUpdates:l,success:g,error:h}}async function Qf({code:t,fragment:e,context:n,localTools:r,logger:o,signal:i,timeoutMs:a=lr}){let s=Bx(),l=await Jf(s,{code:t,options:{fragment:e,timeoutMs:a},bindings:n.toObjectCopy(),tools:r,signal:i},o);return y.debug(`[${s}] Got execution result: ${JSON.stringify(l)}`),l}import{createHmac as zx,randomUUID as Hx}from"crypto";import $x from"fetch-retry";var jx=$x(global.fetch,{retries:3,retryOn:function(t,e,n){return!!(e!==null||n&&n.status>=500)},retryDelay:function(t){return Math.pow(2,t)*500}}),Zf=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,eS=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function tS({orgId:t,code:e,fragment:n,context:r,timeoutMs:o=lr,retries:i=2,signal:a,logger:s}){if(!Zf)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let l,c,d=0;if(!eS)throw new Error("Missing lambda auth secret.");let u=zx("sha256",eS).update(t).digest("hex");for(;d<=i;){d++,a?.throwIfAborted();let g={id:Hx(),orgId:t,momenticLambdaAuthHash:u,code:e,fragment:n,state:r.toObjectCopy(),timeoutMs:o};try{if(l=await z(jx(Zf,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:a}),!l)throw new Error("Got empty response from code evaluation server");if(!l.ok)throw new Error(`Code evaluation server returned error code ${l.status}`);c=void 0;break}catch(p){c=p}}if(c)throw s.error({err:c},"Failed to evaluate code remotely"),c;if(!l)throw new Error(`An unexpected code evaluation error occurred${c?`: ${c}`:""}`);let m;try{m=Dp.parse(await l.json())}catch(g){throw new Error(`Code evaluation server returned invalid response: ${g}`)}if(m.error)throw new Error(`Code evaluation error: ${m.error}`);return m}async function io(t){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await tS(t);else if(t.localTools)e=await Qf({...t,localTools:t.localTools});else throw new Error("No code evaluation environment available");if(e.error){let n=`Failed to evaluate code:
25
+ ${Qr(`Sub-steps: ${e}`,2)}`}default:return(n=>{throw new Error("You missed a case in the switch above")})(t)}}var zh=1e3,Hh=3e6,tA="[FAILED]";async function $h(t,e,n){if(n){let r=await e.getScreenshot(t,n);if(r)return`data:image/jpeg;base64,${Buffer.from(r).toString("base64")}`}}function nA(t,e){let n=(()=>{switch(t.type){case"AI_ACTION":case"AI_ACTION_DYNAMIC":return"AI action";case"PRESET_ACTION":return"Preset action";case"MODULE":return"Module";case"CONDITIONAL":return"Conditional step";case"SECTION":return"Section";default:return(a=>{throw new Error("You missed a case in the switch above")})(t)}})();return(o=>e?`${e==="start"?"Start":"End"} of ${n}
26
+ ${o}`:o)(Nd(t))}function Gs(t,e={}){let{index:n,includeDomState:r=!1,header:o}=e,a=nA(t,o),i;t.type==="PRESET_ACTION"&&(i=t.results?.[0]?.elementInteracted);let s=t.message!=="Successfully executed preset action."?t.message:void 0,l=a;t.status==="FAILED"&&(l=`${tA} ${l}`);let c={description:l,startedAt:t.startedAt.toISOString(),finishedAt:t.finishedAt.toISOString(),beforeUrl:t.beforeUrl,afterUrl:t.afterUrl,beforeSnapshot:t.beforeSnapshot,afterSnapshot:t.afterSnapshot,elementInteracted:i,message:s,index:n};if(t.status==="FAILED"&&r)try{let d=sp.array().parse(t.details);for(let u of d)"pageState"in u&&(c.pageState=u.pageState)}catch{}return c}async function Vh(t,e,n,{addIndices:r=!0,includeDomState:o=!1,flatten:a=!0,maxItemsFromEnd:i=15,indexOffset:s=0}){let l,c=[];for(let d=0;d<n.length;d++){let u=n[d],m=r?d+s:void 0;switch(u.type){case"PRESET_ACTION":{c.push(Gs(u,{index:m,includeDomState:o,header:void 0})),u.status==="FAILED"&&(l=m);break}case"CONDITIONAL":case"AI_ACTION":case"AI_ACTION_DYNAMIC":case"MODULE":case"SECTION":{if(a){c.push(Gs(u,{index:r?m:void 0,includeDomState:o,header:"start"})),s+=1;let{failureIndex:p,results:g}=await Vh(t,e,u.results,{addIndices:r,includeDomState:o,flatten:a,maxItemsFromEnd:i,indexOffset:s+d});if(c.push(...g),p!==void 0){l=p;break}s+=g.length,c.push(Gs(u,{index:r?s+d:void 0,includeDomState:o,header:"end"})),s+=1}else c.push(Gs(u,{index:r?s+d:void 0,includeDomState:o,header:void 0}));break}default:return(g=>{throw new Error("You missed a case in the switch above")})(u)}if(l!==void 0)break}return{results:c,failureIndex:l}}async function Qo(t,e,n,{numStepsWithScreenshots:r=5,addIndices:o=!0,includeBeforeScreenshots:a=!1,includeDomState:i=!1,flatten:s=!0,maxItemsFromEnd:l=20}){let{results:c,failureIndex:d}=await Vh(t,e,n,{addIndices:o,includeDomState:i,flatten:s,maxItemsFromEnd:l,indexOffset:0}),u=[],m=0;if(l!==void 0&&c.length>l&&(m=c.length-l),d!==void 0&&d<c.length-1&&t.warn("PROCESS_RESULTS_FOR_LLM: Failure index check - should not be possible",{failureIndex:d,flattenedResultsLength:c.length,lastIndex:c.length-1,isLastIndex:d===c.length-1,offset:m}),d!==void 0&&m>d)throw new Error("Failure index is out of bounds");for(let p=m;p<c.length;p++){let g=c[p],h={description:g.description,startedAt:g.startedAt,finishedAt:g.finishedAt,beforeUrl:g.beforeUrl,afterUrl:g.afterUrl,elementInteracted:g.elementInteracted,message:g.message,pageState:g.pageState,index:g.index},f,y;(r===void 0||r>0&&p>=c.length-r)&&(g.afterSnapshot&&(y=await $h(t,e,g.afterSnapshot)),a&&g.beforeSnapshot&&(f=await $h(t,e,g.beforeSnapshot))),h.beforeScreenshot=f,h.afterScreenshot=y,u.push(h)}return{results:u,failureIndex:d!==void 0?d-m:void 0}}function _d({json:t,keysToRedact:e,maxJsonStringSize:n}){try{if(!t)return t;if(typeof t=="string")return $e(t,n??2e4);if(typeof t=="object"){let{jsonString:r}=Wh(JSON.stringify(t,(o,a)=>e?.includes(o)||typeof a=="string"&&a.length>3e4?"REDACTED":a),n??2e4);return JSON.parse(r)}return t}catch{return t}}function kd(t,e){for(let n=0;n<t.length;n++){let r=t[n];try{if(r.data){let{jsonString:o}=Wh(JSON.stringify(r.data),1e3);r.data=JSON.parse(o)}}catch(o){e.error({err:o},"Failed to serialize individual result output data"),r.data=`Result output data could not be serialized: ${o}`}switch(r.details&&(r.details=void 0),r.type){case"PRESET_ACTION":jh(r);break;case"CONDITIONAL":r.assertionResult&&jh(r.assertionResult),kd(r.results,e);break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":{kd(r.results,e);break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}}function jh(t){let e=t.command;"cache"in e&&e.cache&&(e.cache=void 0)}function Gh(t,e){let n=JSON.stringify(t),r=n.replaceAll("\\u0000","");if(n.length!==r.length){let o=n.indexOf("\\u0000");e.warn({input:n.slice(Math.max(0,o-500),Math.min(n.length,o+500))},"Database content violation: stripped unicode character from input")}return r}function Ws(t,e){let n=eA(t);if(kd(n,e),n.length>zh)return e.error("Database content violation: results too long, truncating before insertion"),n.slice(0,zh);let r=Gh(n,e);if(r.length>Hh)for(e.error({serializedLength:r.length,resultsArrayLength:n.length},"Database content violation: results too large, truncating before insertion");r.length>Hh;)n.pop(),r=Gh(n,e);try{return et.array().parse(JSON.parse(r))}catch(o){throw e.error({serialized:r,err:o},"Could not parse serialized results into JSON structure after processing"),o}}import{cloneDeep as bY}from"lodash-es";var rA=/^(?!.*\S+\s+\S+).*$/,oA=/^[a-zA-Z0-9\s.,;:'"!?()\- \u00C0-\u00FF]+$/,aA=/style="([^"]*)/g,iA=/data-[\w-]+/g,sA=t=>{switch(t.type){case"AI_ASSERTION":return{type:t.type,assertion:t.assertion};case"DRAG":if(t.fromTarget.type==="description")return{type:t.type,description:t.fromTarget.elementDescriptor};break;case"CLICK":case"BLUR":case"TYPE":case"SELECT_OPTION":case"ELEMENT_CHECK":case"FOCUS":case"HOVER":case"MOUSE_DRAG":case"VISUAL_DIFF":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":if(t.target?.type==="description")return{type:t.type,description:t.target.elementDescriptor};break}return{type:"NONE",description:"NONE"}};function qh(t){let e=sA(t),n=e.type==="AI_ASSERTION"?e.assertion:e.description;return!n||n==="NONE"?{thoughts:"NONE",category:"NO_DESCRIPTION_PROVIDED"}:rA.test(n)&&oA.test(n)?{thoughts:"The target description is too short. Please provide more details.",category:"FEW_WORDS"}:aA.test(n)?{thoughts:"Style tags are not recommended in the command description as they change frequently. Please remove them and describe the target in a different way.",category:"STYLE_TAG"}:iA.test(n)?{thoughts:"Hardcoded data attributes are not recommended in the command description as they change frequently.",category:"HARDCODED_ATTRIBUTE"}:new RegExp(`\\b${e.type}\\b`,"gi").test(n)?{thoughts:`The element description you provided starts with the command type (${e.type}). This can confuse our AI agents since the element itself is unrelated to the desired action.`,category:"TYPE_IN_DESCRIPTION"}:{thoughts:"NONE",category:"NONE"}}function Kh(t,e){if(!(!t.envs||!t.envs.length)){for(let n of t.envs){let r=n;e in n&&(r[e]&&(n.default=!0),delete r.defaultOnCloud,delete r.defaultOnLocal)}t.envs.some(n=>n.default)||(t.envs[0].default=!0)}}import{cloneDeep as Ef}from"lodash-es";import mA from"diff-lines";import qs,{gte as pA}from"semver";var Yh={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async t=>(t=t.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),t=t.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),t)};var Xh={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 t=>t.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let n=e.commands,r=n[n.length-1];return r&&r.type!=="SUCCESS"&&n.push({type:"SUCCESS"}),e})};var lA=["target","fromTarget","toTarget"];function Jh(t){for(let e of lA){if(t[e]===void 0)continue;let n=t[e];n.elementDescriptor!==void 0?n.type="description":t[e]={type:"description",elementDescriptor:""}}}var Qh={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":return Jh(e.command),e;case"AI_ACTION":{let n=e.commands;for(let r of n??[])Jh(r);return e}default:return e}})};import{v4 as cA}from"uuid";var Zh={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=cA()),e;default:return e}})};import{v4 as ef}from"uuid";var tf={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let n=e.command;return n.id=n.id??ef(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(n=>({type:"PRESET_ACTION",command:{...n,id:n.id??ef()}})),delete e.commands),e;default:return e}})};var nf={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 t=>t.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let n=e.command;return typeof n.type!="string"||n.type!=="AI_WAIT"||(n.type="AI_ASSERTION",n.timeout||(n.timeout=10)),e}default:return e}})};import{v4 as dA}from"uuid";var rf={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 t=>t.map(e=>("id"in e&&typeof e.id=="string"||(e.id=dA()),e))};import{v4 as of}from"uuid";var af={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 t=>t.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let n=e.condition;n.id||(n.id=of())}return e.id=of(),e})};var sf={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 t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||typeof n.envKey!="string"||(e.envKey=n.envKey,delete n.envKey),e})};import{v4 as uA}from"uuid";var lf={name:"Redo last two migrations",fromVersion:"1.0.13",toVersion:"1.0.14",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if((!("id"in e)||typeof e.id!="string")&&(e.id=uA()),e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||typeof n.envKey!="string"||(e.envKey=n.envKey,delete n.envKey),e})};var cf={name:"Migrate select choice",fromVersion:"1.0.14",toVersion:"1.0.15",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="SELECT_OPTION"||e.option===void 0||(e.choice={type:"VALUE",value:n.option},e.option=void 0),e})};var df={name:"Migrate select choice",fromVersion:"1.0.15",toVersion:"1.0.16",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return n&&uf(n),e})};function uf(t){t&&Object.keys(t).forEach(e=>{if(typeof t[e]=="object"&&t[e]){uf(t[e]);return}if(typeof t[e]!="string")return;let n=t[e];e==="code"?t[e]=n.replace(/inputs\./g,"env."):n.includes("{{")&&n.includes("}}")&&(t[e]=n.replace(/inputs\./g,"env."))})}var mf={name:"Migrate switch tab choice",fromVersion:"1.0.16",toVersion:"1.0.17",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="TAB"||n.url===void 0||(n.action={type:"SUBSTRING",substring:n.url},n.url=void 0),e})};var pf={name:"Remove press keys sequentially",fromVersion:"1.0.17",toVersion:"1.0.18",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="TYPE"?e:n.pressKeysSequentially===void 0?(n.delay=0,e):(n.pressKeysSequentially&&(n.pressKeysSequentially=void 0,n.delay=50),e)})};var gf={name:"Migrate wait for URL to matcher",fromVersion:"1.0.18",toVersion:"1.0.19",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="WAIT_FOR_URL"||n.url===void 0||(n.matcher={type:"GLOB",glob:n.url},n.url=void 0),e})};var hf={name:"Migrate select choice round 2",fromVersion:"1.0.19",toVersion:"1.0.20",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;if(!n)return e;if(n.type==="SELECT_OPTION"){if(n.option===void 0)return e;n.choice={type:"VALUE",value:n.option},n.option=void 0}else if(n.type==="TAB"){if(n.url===void 0)return e;n.action={type:"SUBSTRING",substring:n.url},n.url=void 0}else if(n.type==="WAIT_FOR_URL"){if(n.url===void 0)return e;n.matcher={type:"GLOB",glob:n.url},n.url=void 0}else n.type==="AI_WAIT"&&(n.type="AI_ASSERTION",n.timeout||(n.timeout=10));return e})};var ff={name:"Migrate ",fromVersion:"1.0.20",toVersion:"1.0.21",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!1,execute:async t=>t.map(e=>{if(e.type!=="PRESET_ACTION")return e;let n=e.command;return!n||n.type!=="MOCK_ROUTE"&&n.type!=="SET_HEADER"&&n.type!=="RECORD_REQUESTS"&&n.type!=="REGISTER_REQUEST_LISTENER"||(n.type==="REGISTER_REQUEST_LISTENER"||n.type==="RECORD_REQUESTS"?n.requestMatcher={urlMatcher:{type:"REGEX",regex:n.pattern}}:(n.type==="SET_HEADER"||n.type==="MOCK_ROUTE")&&n.urlPattern&&(n.requestMatcher={urlMatcher:{type:"REGEX",regex:n.urlPattern}})),e})};var Sf={name:"Migrate AI checks to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async t=>t.map(e=>{if(e.type!=="AI_ASSERTION")return e;let r={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...r};return delete o.text,o}),stopOnFailure:!0};var Vs=new Set(["CLICK","TYPE","SELECT_OPTION"]),yf={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async t=>t.map(e=>{let n=e.command,r=n?.type,o=n?.elementDescriptor;return(o!==void 0||Vs.has(r))&&(n.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let s=i?.elementDescriptor,l=i?.type;(s!==void 0||Vs.has(l))&&(i.target={elementDescriptor:s??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let s=i.command,l=s?.elementDescriptor,c=s?.type;(l!==void 0||Vs.has(c))&&(s.target={elementDescriptor:l??""}),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(u=>{let m=u?.elementDescriptor,p=u?.type;(m!==void 0||Vs.has(p))&&(u.target={elementDescriptor:m??""})})}),e}),stopOnFailure:!0};var bf={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async t=>t.map(e=>{let n=e;return n.status==="FAILURE"&&(n.status="FAILED"),typeof n.commands=="object"&&Array.isArray(n.commands)&&n.commands.forEach(r=>{if(r&&typeof r=="object"){let o=r;o?.status==="FAILURE"&&(o.status="FAILED")}}),n}),stopOnFailure:!0};var Tf={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async t=>t.map(e=>{let n=e.command,r=n?.type;return r?.startsWith("PRESET_")&&(n.type=r.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(a=>{let i=a.type;i?.startsWith("PRESET_")&&(a.type=i.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(a=>{let i=a.command,s=i?.type;s?.startsWith("PRESET_")&&(i.type=s.slice(7)),a.commands&&Array.isArray(a.commands)&&a.commands.forEach(c=>{let d=c.type;d?.startsWith("PRESET_")&&(c.type=d.slice(7))})}),e}),stopOnFailure:!0};var Zr=[Sf,bf,Tf,yf,Yh,Xh,Qh,Zh,tf,nf,rf,af,sf,lf,cf,df,mf,pf,gf,hf,ff];if(se!==Zr[Zr.length-1].toVersion)throw new Error("Please bump LATEST_SCHEMA_VERSION in types package after adding a migration");Zr.forEach((t,e)=>{if(!qs.valid(t.toVersion)||!qs.valid(t.fromVersion))throw new Error(`Migration '${t.name}' has invalid version`);if(!qs.gt(t.toVersion,t.fromVersion))throw new Error(`Migration '${t.name}' has toVersion <= fromVersion`);if(e===0)return;if(Zr[e-1].toVersion!==t.fromVersion)throw new Error(`Migration '${t.name}' at index ${e} is not contiguous with previous migration`)});function gA(t){return t.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var ri=async({metadata:t,steps:e,logger:n,toVersion:r})=>{let o=e,{schemaVersion:a,id:i}=t,s=Zr.findIndex(d=>qs.gt(d.toVersion,a));if(s===-1)return{steps:o,newVersion:a};let l=a;for(let d=s;d<Zr.length;d++){if(r&&pA(l,r)){n.debug("Stopping migration early because toVersion was reached");break}let u=Zr[d],m={id:i,migration:u.name,toVersion:u.toVersion};try{o=await wf(o,u),l=u.toVersion}catch(p){throw n.error({err:p,...m},"Migration failed"),new Error(`Step migration ${u.name} failed: ${p}`)}}let c=mA(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return c.trim()&&n.debug({diffs:c,id:i},"Migration diffs"),{newVersion:l,steps:o}};async function wf(t,e){let n=await e.execute(t);for(let r of n)for(let o of Object.keys(r)){if(!e.recursiveKeys.has(o))continue;let a=r[o];!a||!Array.isArray(a)||gA(a)&&(r[o]=await wf(a,e))}return n}async function Rf({rawSteps:t,metadata:e,logger:n,callbacks:r}){Kh(e,"defaultOnCloud");let o={},{resolvedSteps:a,newSchemaVersion:i}=await Ks({rawSteps:t.steps,migrationMetadata:e,logger:n,callbacks:r,resolvedModuleCache:o}),s={...e,steps:a,schemaVersion:i};for(let l of["beforeSteps","afterSteps"]){let c=t[l];if(!c)continue;let{resolvedSteps:d}=await Ks({rawSteps:c,migrationMetadata:e,logger:n,callbacks:r,resolvedModuleCache:o});s[l]=d}return{resolvedTest:s,moduleIds:Array.from(Object.keys(o))}}async function eo(t,e,n){let{newVersion:r,steps:o}=await ri({metadata:t,steps:e,logger:n});try{return{steps:Me.array().parse(o),newVersion:r}}catch(a){throw n.error({type:"zod",err:a,newVersion:r,id:t.id,steps:o},"Failed to parse test steps while migrating test"),new Ss(`Failed to parse test steps while migrating test: ${a}`,t.id,"entity",{cause:a})}}async function Ks({rawSteps:t,migrationMetadata:e,logger:n,callbacks:r,resolvedModuleCache:o={}}){let{newVersion:a,steps:i}=await eo(e,t,n),s=[];for(let l of i)s.push(await oi({step:l,callbacks:r,logger:n,resolvedModuleCache:o}));return{resolvedSteps:s,newSchemaVersion:a}}async function oi({step:t,callbacks:e,logger:n,resolvedModuleCache:r}){switch(t.type){case"AI_ACTION":return t;case"AI_ACTION_DYNAMIC":return t;case"PRESET_ACTION":return t;case"MODULE":{let l=t.moduleId,c=r[l];if(c)return{...Ef(c),...t,type:"RESOLVED_MODULE"};let d=await e.onFetchModule({id:l,logger:n});if(!d)throw new Error(`Could not find module with id ${l}`);let{newVersion:u,steps:m}=await ri({metadata:{id:l,schemaVersion:d.schemaVersion},steps:d.steps,logger:n}),p;try{p=Me.array().parse(m)}catch(f){throw n.error({type:"zod",err:f,steps:m,newVersion:u,id:l},"Module failed to parse"),f}let g;try{g=await Promise.all(p.map(f=>oi({step:f,callbacks:e,logger:n,resolvedModuleCache:r})))}catch(f){throw n.error({err:f,...t},`Failed to recursively resolve module '${d.name}': ${f}`),f}let h={...d,steps:g};return r[l]=Ef(h),{...h,...t,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let l of t.blocks){let c=[];for(let d of l.steps)c.push(await oi({step:d,callbacks:e,logger:n,resolvedModuleCache:r}));o.push({...l,steps:c})}let a;if(t.elseSteps){a=[];for(let l of t.elseSteps)a.push(await oi({step:l,callbacks:e,logger:n,resolvedModuleCache:r}))}return{...t,blocks:o,elseSteps:a};case"SECTION":let i=[];for(let l of t.steps)i.push(await oi({step:l,callbacks:e,logger:n,resolvedModuleCache:r}));return{...t,steps:i};default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}}function hA(t){return typeof t=="object"&&t!==null}function Gn(t){if(Array.isArray(t))return t.map(Gn);if(hA(t)){let e={};return Object.entries(t).forEach(([n,r])=>{r!==void 0&&(e[n]=Gn(r))}),e}return t}import{cloneDeep as fA}from"lodash-es";import{stringify as Cf}from"yaml";async function vf({test:t,processedModuleNames:e=new Set,createNewCacheIds:n=!1}){let r={id:t.id,name:t.name,description:t.description,baseUrl:t.baseUrl,schemaVersion:t.schemaVersion,advanced:t.advanced,retries:t.retries,envs:t.envs,disabled:t.disabled,labels:t.labels},o={},a=await SA({originalStepLists:{steps:t.steps,beforeSteps:t.beforeSteps,afterSteps:t.afterSteps},modules:o,processedModuleNames:e,createNewCacheIds:n}),i={fileType:pe.TEST,...r,beforeSteps:a.beforeSteps&&a.beforeSteps.length>0?a.beforeSteps:void 0,steps:a.steps,afterSteps:a.afterSteps&&a.afterSteps.length>0?a.afterSteps:void 0};return{test:Cf(i),modules:o}}async function SA({originalStepLists:t,modules:e,processedModuleNames:n,createNewCacheIds:r}){let o=fA(t);Object.values(o).forEach(s=>{yA(s??[])});let{stepsToSave:a,moduleUpdates:i}=await He({stepLists:o,createNewCacheIds:r});for(let s of i)n.has(s.name)||(e[s.name]=bA(s),n.add(s.name));return a}function yA(t){ni({steps:t,onPresetAction:e=>{e.aiSuggested=void 0,e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.aiSuggested=void 0,e.index=void 0},onSimpleStepContainer:e=>{e.aiSuggested=void 0,e.index=void 0}})}function bA(t){let e=Ot.parse(t),n={fileType:pe.MODULE,...e,schemaVersion:se,steps:t.steps};return Cf(n)}async function J(t,e){if(!(t<=0))return new Promise((n,r)=>{if(e?.aborted){r(e.reason);return}e?.addEventListener("abort",a);let o=setTimeout(()=>{e?.removeEventListener("abort",a),n()},t);function a(){clearTimeout(o),e?.removeEventListener("abort",a),r(e?.reason)}})}async function ai({promiseGenerator:t,signal:e,codePath:n,logger:r}){let a=Date.now(),i=setInterval(()=>{if(e?.aborted){clearInterval(i);return}r?.warn({codePath:n,startTime:a,elapsedMilliseconds:Date.now()-a},`Asynchronous operation is taking a long time (${n})`)},5e3);return new Promise((s,l)=>{function c(){clearInterval(i),e?.removeEventListener("abort",c),l(e?.reason)}if(e?.aborted){l(e?.reason),clearInterval(i);return}e?.addEventListener("abort",c),(async()=>{try{s(await t())}catch(d){l(d)}finally{clearInterval(i),e?.removeEventListener("abort",c)}})()})}async function to({promiseGenerator:t,timeoutMs:e,codePath:n,logger:r,signal:o}){let a=!1,i=new AbortController,s=()=>{i.abort()},l=setTimeout(()=>{a||i.abort()},e);o?.addEventListener("abort",s);try{return await ai({promiseGenerator:t,signal:i.signal,codePath:n,logger:r})}finally{a=!0,o?.removeEventListener("abort",s),clearTimeout(l)}}function Af(t){let e;return t>10*60*1e3?e=2*60*1e3:t>60*1e3?e=20*1e3:t>10*1e3?e=2*1e3:e=1e3,e}function Ys(t){let e=[];for(let n of t)switch(n.type){case"PRESET_ACTION":case"AI_ACTION":case"AI_ACTION_DYNAMIC":e.push(n);break;case"RESOLVED_MODULE":{let r={...n,type:"MODULE"};e.push(sn.parse(r));break}case"SECTION":{let r={...n,steps:Ys(n.steps)};e.push(Me.parse(r));break}case"CONDITIONAL":{let r={...n,blocks:n.blocks.map(o=>({assertion:o.assertion,steps:Ys(o.steps)})),elseSteps:n.elseSteps?Ys(n.elseSteps):void 0};e.push(Br.parse(r));break}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return e}function Xs(t){return Ys([t])[0]}import TA from"picomatch";var Js=(t,e,n)=>{n?.caseInsensitive&&(t=t.toLowerCase());let r;switch(e.type){case"SUBSTRING":{let o=n?.caseInsensitive?e.url.toLowerCase():e.url;r=t.includes(o);break}case"GLOB":{let o=n?.caseInsensitive?e.glob.toLowerCase():e.glob;r=t===e.glob||TA(o)(t);break}case"REGEX":{r=new RegExp(e.regex).test(t);break}case"DOMAIN":{let o=n?.caseInsensitive?e.domain.toLowerCase():e.domain;r=new URL(t).hostname===o;break}}return n?.negated?!r:r},Qs=(t,e)=>{try{let{hostname:n,pathname:r}=new URL(t),{hostname:o,pathname:a}=new URL(e);return n!==o||r!==a}catch{return!1}},Zo=t=>{try{return new URL(t),!0}catch{return!1}},xf=t=>!t.toLowerCase().startsWith("http"),ea=(t,e)=>{try{return new URL(t,e),!0}catch{return!1}};function no(t,e){try{return!!new URL(t).origin.trim()}catch(n){return e?.error({url:t,err:n},"Invalid URL in check"),!1}}async function wA(t){let{logger:e,browserStateStorage:n,generator:r,results:o,error:a,maxItemsFromEnd:i,numStepsWithScreenshots:s,disableCache:l}=t,c=[];if(o.length>0){let{results:u}=await Qo(e,n,o,{numStepsWithScreenshots:s,maxItemsFromEnd:i,includeBeforeScreenshots:!0,includeContainerTagsInDescription:!0});c=u}return await r.getTestResultClassification({results:c,errorMessage:a.message,errorStack:a.stack},{disableCache:l??!1})}async function If(t){let{logger:e,browserStateStorage:n,generator:r,results:o,error:a,maxItemsFromEnd:i,numStepsWithScreenshots:s,disableCache:l}=t;if(!n||!o||o.length===0)return{};try{let c=await wA({logger:e,browserStateStorage:n,generator:r,results:o,error:a,maxItemsFromEnd:i,numStepsWithScreenshots:s,disableCache:l});return{classification:c,aiFailureReason:c.reason}}catch(c){return e.error({err:c},"Failed to classify test result"),{}}}function ta({orgId:t,client:e,gitMetadata:n,alwaysSaveCache:r,noCache:o}){return o?new As:new Dd(t,e,n,r)}var Dd=class{constructor(e,n,r,o){this.orgId=e;this.client=n;let{gitBranchName:a,gitProtectedBranches:i}=r;this.cacheHeaders=hd(r),o?this.writeCaches=!0:a?this.writeCaches=!i.includes(a):this.writeCaches=!0}cacheHeaders;writeCaches;async saveStepCacheEntries({entries:e,testId:n,logger:r}){if(!this.writeCaches){r.debug("Skipping cache storage because branch is protected");return}try{await this.client.updateStepCaches({entries:e,testId:n},this.cacheHeaders)}catch(o){r.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let{steps:n,beforeSteps:r,afterSteps:o}=e.stepLists,a=await this.client.getStepCacheForTest({testId:e.testId},this.cacheHeaders);if(!this.writeCaches){e.logger.debug("Skipping cache last used at update because branch is protected");return}for(let s of[n,r,o])s&&Jo({steps:s,stepCacheEntries:a,logger:e.logger});let{cachesToSave:i}=await He({stepLists:e.stepLists,cacheCreationParams:{testId:e.testId,orgId:this.orgId}});this.client.updateStepCaches({entries:i,testId:e.testId},this.cacheHeaders)}};import RA from"path";var CA=new Os(30,60*1e3),zd="https://api.momentic.ai",Pf,Mf=t=>{zd=t},ii=()=>zd;var na,Bd,Zs,Lf=async t=>{if(Pf&&na&&Zs)return na;let e=new Je({baseUrl:zd,apiKey:t,logger:S});Pf=e;try{let n=await e.getAuthInfo();return na=n.orgId,Bd=n.userId,Zs=t,na}catch(n){throw new Error(`Error checking API key against server: ${n}`)}},rn=()=>{if(!na)throw new Error("Your organization ID is invalid.");return na},el=()=>{if(!Bd)throw new Error("Your user ID is invalid.");return Bd},Hd=()=>{if(!Zs)throw new Error("Your API key is invalid.");return Zs},$d,Fd,tl=(t,e)=>{$d=t,Fd?.abort(),Fd=new AbortController;let n=Fd.signal,r=[t.configFilePath];t.config.environments?.forEach(o=>{if(!o.envFile)return;let a=RA.resolve(t.rootDir,o.envFile);try{if(Ud.lstatSync(a).isSymbolicLink())return;Ud.existsSync(a)&&r.push(a)}catch(i){S.warn({err:i},`Failed to check if env file ${a} exists`)}});try{vA({filesToWatch:r,revalidator:e,signal:n,project:t})}catch(o){S.error({err:o},"Failed to start config file watchers")}},ae=()=>$d;function vA({filesToWatch:t,revalidator:e,signal:n,project:r}){t.forEach(o=>{Ud.watch(o,{signal:n,persistent:!1,recursive:!1},(a,i)=>{i&&(CA.increment("setLocalProject")&&S.warn(`A file change under the ${r.rootDir} directory has caused Momentic to reload its configuration more than 30 times in the last minute. Rapid changes to files may indicate your momentic.config.yaml 'include' glob is incorrect. Please ensure temporary, library, and auto-generated files are not included in Momentic's context.`),$d=e(r.configFilePath))})})}function ce(t){return function(...e){let n=e[e.length-1],r=t(...e);Promise.resolve(r).catch(n)}}var li=AA();function si(t){let e=ae(),n=lt.dirname(e.configFilePath);return lt.join(n,...t)}function IA(t){let e=ae(),n=lt.dirname(e.configFilePath),r=lt.relative(n,t);return r?r.split(lt.sep):[]}function PA(t,e){let n=It.statSync(t),r=IA(t);return sd.parse({name:e,absolutePath:t,relativePath:r.join(lt.sep),pathSegments:r,isDirectory:n.isDirectory(),size:n.size,createdAt:n.birthtime,modifiedAt:n.mtime,accessedAt:n.atime})}li.post("/",ce(async(t,e,n)=>{let r;try{r=hg.parse(t.body).pathSegments}catch(u){e.status(400).json({error:`Failed to parse folder read body: ${u}`});return}let o=si(r);if(!It.existsSync(o)){e.status(404).json({error:`Path not found: ${r.join(lt.sep)}`});return}if(!It.statSync(o).isDirectory()){e.status(400).json({error:`Path is not a directory: ${r.join(lt.sep)}`});return}let i=ae(),s=Array.from(i.config.exclude??[]).concat(ws),c=xA("*",{absolute:!1,cwd:o,ignore:s,dotRelative:!1,maxDepth:1,nodir:!1}).map(u=>{let m=lt.join(o,u);return PA(m,u)}),d={absolutePath:o,pathSegments:r,contents:c};e.status(200).json(d)}));li.put("/",ce(async(t,e,n)=>{let r;try{r=fg.parse(t.body).pathSegments}catch(i){e.status(400).json({error:`Failed to parse folder create body: ${i}`});return}let o=si(r);if(It.existsSync(o)){e.status(200).json({success:!0,message:`Folder already exists: ${r.join(lt.sep)}`,pathSegments:r});return}It.mkdirSync(o,{recursive:!0});let a={success:!0,message:`Folder created: ${r.join(lt.sep)}`,pathSegments:r};e.status(201).json(a)}));li.patch("/",ce(async(t,e,n)=>{let r,o;try{let c=Sg.parse(t.body);r=c.pathSegments,o=c.newPathSegments}catch(c){e.status(400).json({error:`Failed to parse folder update body: ${c}`});return}let a=si(r),i=si(o);if(!It.existsSync(a)){e.status(400).json({error:`Folder not found: ${r.join(lt.sep)}`});return}if(It.existsSync(i)){e.status(400).json({error:`Destination already exists: ${o.join(lt.sep)}`});return}let s=lt.dirname(i);It.existsSync(s)||It.mkdirSync(s,{recursive:!0}),It.renameSync(a,i);let l={success:!0,message:`Folder moved from ${r.join(lt.sep)} to ${o.join(lt.sep)}`,pathSegments:o};e.status(200).json(l)}));li.delete("/",ce(async(t,e,n)=>{let r,o=!0;try{let l=yg.parse(t.body);r=l.pathSegments,o=l.recursive??!0}catch(l){e.status(400).json({error:`Failed to parse folder delete body: ${l}`});return}let a=si(r);if(!It.existsSync(a)){e.status(200).json({success:!0,message:`Folder not found: ${r.join(lt.sep)}`,pathSegments:r});return}if(!It.statSync(a).isDirectory()){e.status(400).json({error:`Path is not a directory: ${r.join(lt.sep)}`});return}if(o)It.rmSync(a,{recursive:!0,force:!0});else{if(It.readdirSync(a).length>0){e.status(409).json({error:`Cannot delete non-empty directory without recursive flag: ${r.join("/")}`});return}It.rmdirSync(a)}let s={success:!0,message:`Folder deleted: ${r.join("/")}`,pathSegments:r};e.status(200).json(s)}));var jd=li;import KL from"events";import Gb,{Router as YL}from"express";import{diff as NA}from"deep-object-diff";import dn from"fs";import oo from"path";import ra from"yaml";import{z as _f}from"zod";import{execSync as MA}from"child_process";function ro(t,e){let n=e.hooks?.postSave;if(!n)return;let r;n.includes("$1")?r=n.replaceAll("$1",t):r=`${n} ${t}`,S.debug({postSaveCommand:r},"Executing post-save hook command");try{MA(r,{encoding:"utf-8"})}catch(o){S.warn({err:o,postSaveCommand:r},"Failed to execute post-save hook command, continuing...")}}import{diff as Of}from"deep-object-diff";import xn from"fs";import{cloneDeep as LA}from"lodash-es";import ci from"path";import{v4 as OA}from"uuid";import di from"yaml";function $t({content:t,schemaVersion:e,momenticFiles:n,project:r,forceSaveOnNoDiffs:o}){let a=n.modules[t.moduleId]?.fullFilePath;if(!a||!xn.existsSync(a))throw new Error(`Tried to update module ${t.moduleId} that could not be found on disk`);let i=xn.readFileSync(a,"utf-8"),s=di.parse(i),l;if(t.name&&t.name!==s.name){let p=`${ve(t.name)}.${st.MODULE}`;if(l=ci.join(ci.dirname(a),p),xn.existsSync(l))throw new Error(`Module with name '${t.name}' already exists at path '${l}'`)}let c={...t,schemaVersion:e},d=Gn({fileType:pe.MODULE,...dd.parse(c),steps:Me.array().parse(t.steps)}),u=Of(d,s);if(u&&Object.keys(u).length===0&&!o){S.debug(`Skipping save for module ${t.moduleId} since there are no changes`);return}let m=di.stringify(d);xn.writeFileSync(a,m,"utf-8"),l&&xn.renameSync(a,l),ro(l||a,r.config)}function Nf({moduleId:t,content:e,momenticFiles:n,project:r,logger:o}){let a=n.modules[t]?.fullFilePath;if(!a)throw new Error(`Tried to update module ${t} that could not be found on disk`);let i=Wn(a,o),s={...i,...e},l=Gn({fileType:pe.MODULE,...dd.parse(s),steps:i.steps}),c=Of(l,i);if(c&&Object.keys(c).length===0){S.debug(`Skipping save for module ${t} since there are no changes`);return}let d=di.stringify(l);xn.writeFileSync(a,d,"utf-8");let u;if(e.name){let m=`${ve(e.name)}.${st.MODULE}`;if(u=ci.join(ci.dirname(a),m),xn.existsSync(u))throw new Error(`Module with name '${e.name}' already exists at path '${u}'`);xn.renameSync(a,u)}ro(u||a,r.config)}async function kf({name:t,description:e,enabled:n,steps:r,folder:o,project:a}){let i=ve(t),s=ci.join(o,`${i}.module.yaml`),l=OA(),{stepsToSave:c}=await He({stepLists:{steps:r}}),d={fileType:pe.MODULE,schemaVersion:se,moduleId:l,name:t,description:e,enabled:n,steps:c.steps},u=di.stringify(d);return xn.writeFileSync(s,u,"utf-8"),ro(s,a.config),{moduleId:l,name:t,description:e,enabled:n,steps:r}}function Wn(t,e){let n=xn.readFileSync(t,"utf-8"),r=di.parse(n);try{return ed.parse(r)}catch(o){throw e.error({err:o,moduleFilePath:t,moduleContents:n},`${t} does not parse as a valid Momentic module`),o}}async function nl(t,e,n,r){let o=Wn(t.fullFilePath,n),{resolvedSteps:a}=await Ks({rawSteps:o.steps,migrationMetadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:r,logger:n,callbacks:{onFetchModule:async({id:s})=>{let l=e.modules[s]?.fullFilePath;if(l)return Wn(l,n)}}}),i={...o,steps:a};return r&&(r[t.id]=LA(i)),i}async function rl(t,e){let n={};return await Promise.all(Object.values(t.modules).map(async r=>{await nl(r,t,e,n)})),Array.from(Object.values(n))}async function Df({test:t,name:e,folder:n}){let r=await vf({test:t});if(Object.keys(r.modules).length)throw new Error("A brand new test should not contain any modules in it");let a=`${ve(e)}.${st.TEST}`,i=oo.join(n,a);return dn.writeFileSync(i,r.test,"utf-8"),i}function Gd(t,e,n){let r=oo.join(n.rootDir,t);if(!dn.existsSync(r))throw new Error(`Test not found at path '${t}' in project '${n.rootDir}'`);let o=dn.readFileSync(r,"utf-8"),a=ra.parse(o),i,s;if(e.name&&e.name!==a.name){let m=`${ve(e.name)}.${st.TEST}`;if(i=oo.join(oo.dirname(t),m),s=oo.join(n.rootDir,i),dn.existsSync(s))throw new Error(`Test with name '${e.name}' already exists at path '${s}'`)}let l={...a,...e},c=en.parse(l),d={fileType:pe.TEST,...en.parse(c),beforeSteps:a.beforeSteps??void 0,steps:a.steps,afterSteps:a.afterSteps??void 0},u=ra.stringify(d);return dn.writeFileSync(r,u,"utf-8"),s&&dn.renameSync(r,s),ro(r,n.config),{newRelativeTestPath:i}}function Pt({relativeTestPath:t,steps:e,schemaVersion:n,project:r,forceSaveOnNoDiffs:o}){let a=oo.join(r.rootDir,t);if(!dn.existsSync(a))throw new Error(`Test not found at path '${t}' in project '${r.rootDir}'`);let i=dn.readFileSync(a,"utf-8"),s=ra.parse(i),l=en.parse({...s,schemaVersion:n}),c=Me.array().or(_f.undefined()).parse(e.beforeSteps),d=Me.array().parse(e.steps),u=Me.array().or(_f.undefined()).parse(e.afterSteps),m=Gn({fileType:pe.TEST,...l,beforeSteps:c&&c.length>0?c:void 0,steps:d,afterSteps:u&&u.length>0?u:void 0}),p=NA(m,s);if(p&&Object.keys(p).length===0&&!o){S.debug(`Skipping save for test ${l.name} since there are no changes`);return}let g=ra.stringify(m);dn.writeFileSync(a,g,"utf-8"),S.debug(`Saving test ${l.name} to ${a}`),ro(a,r.config)}function ol(t,e){let n=oo.join(e.rootDir,t);if(!n)throw new Error(`Could not find test with path ${t} in Momentic project (${e.rootDir})`);let r;try{r=dn.readFileSync(n,"utf8"),r=r.replace(/\r\n|\r/g,`
27
+ `)}catch(a){throw new Error(`Could not read test file ${n}: ${a}`)}let o;try{o=ra.parse(r)}catch(a){throw new Error(`Could not parse test file ${n} as YAML: ${a}`)}return St.parse(o)}function ao(t,e,n){let r=n.project.rootDir,o;try{o=dn.readFileSync(t,"utf-8")}catch(i){throw e.error({err:i,projectRoot:r},i.message),new Error(i.message)}let a=ra.parse(o);if(!a.steps||!Array.isArray(a.steps))throw new Error(`Test ${t} is missing steps`);return a}async function Mt(t,e,n){let r=ao(t,e,n),o;try{o=en.parse(r)}catch(i){throw new Error(`Test ${t} is missing metadata or has invalid metadata: ${i}`)}let{resolvedTest:a}=await Rf({rawSteps:{steps:r.steps,beforeSteps:r.beforeSteps,afterSteps:r.afterSteps},metadata:o,logger:e,callbacks:{onFetchModule:async({id:i,logger:s})=>{let l=n.modules[i]?.fullFilePath;if(l)return Wn(l,s)}}});return a}import kA from"@dotenvx/dotenvx";import _A from"fs";import Ff from"path";function Uf(t,e){return(t.config.environments??[]).map(n=>ui(n.name,t,e))}function Bf(t){return t.includes("${")?t.replace(/\$\{([^}]+)\}/g,(e,n)=>{let[r,o]=n.split(/:-|-/,2),a=process.env[r];return n.includes(":-")?a&&a!==""?a:o||"":n.includes("-")?a!==void 0?a:o||"":a||""}):t}function DA(t){let{envVariables:e,project:n}=t;if(!e)return{};let r={};for(let[o,a]of Object.entries(e)){if(typeof a=="string"){let s=Bf(a);s&&(r[o]=s);continue}let i;try{i=_A.readFileSync(Ff.resolve(n.rootDir,a.fromFile),"utf-8")}catch(s){throw new Error(`Failed to read environment variable '${o}' from file '${a.fromFile}': ${s}`)}if(a.json)try{r[o]=JSON.parse(i)}catch(s){throw new Error(`Failed to parse environment variable '${o}' from file '${a.fromFile}' as JSON: ${s}`)}else r[o]=i}return Object.keys(r).length>0&&S.debug(r,"Set environment variables with interpolation from project configuration"),r}function FA(t){let{project:e,envFile:n,logger:r}=t,o={};if(!n)return o;let a=kA.config({path:Ff.resolve(e.rootDir,n),processEnv:o,logLevel:"error",quiet:!0});if(a.error)throw new Error(`Failed to load .env file: ${a.error.message}`);return r.debug(o,"Set environment variables from .env file"),o}function ui(t,e,n){let r=(e.config.environments??[]).find(l=>l.name===t);if(!r)throw new Error(`Environment ${t} not found in local project configuration file`);if(!r.baseUrl)throw new Error(`Browser environment ${t} does not have a baseUrl configured`);let o={[at]:Bf(r.baseUrl)},a=DA({envVariables:r.envVariables,project:e});Object.assign(o,a);let i=FA({project:e,envFile:r.envFile,logger:n});return Object.assign(o,i),r.inheritFromShell&&(n.debug(process.env,"Inheriting environment variables from shell"),Object.assign(o,process.env)),{name:t,variables:o,browser:r.browser}}import{existsSync as YA,readFileSync as XA,readdirSync as JA,writeFileSync as QA}from"fs";import{globSync as ZA}from"glob";import io,{dirname as jf}from"path";import{cwd as Yd}from"process";import Gf from"yaml";import{z as ke}from"zod";import zf from"fs";import{globSync as UA}from"glob";import mi from"path";import BA from"yaml";import{z as Wd}from"zod";var Hf=!1,Vd=[`**/*.${st.TEST}`,`**/*.${st.MODULE}`],qd=Wd.string().refine(t=>/^[a-zA-Z0-9-]+$/.test(t)),Kd=50,zA=Wd.object({fileType:Wd.nativeEnum(pe)});function te(t,e){let n={project:t,tests:{},modules:{},mobileTests:{},duplicateEntities:{}},r=t.config.include??Vd,o=Array.from(t.config.exclude??[]).concat(ws),a=UA(r,{absolute:!1,cwd:t.rootDir,ignore:o,dotRelative:!1,maxDepth:Kd,nodir:!0});for(let i of a){let s=HA(t.rootDir,i,n,e);s&&(n.duplicateEntities[s.id]=s.paths)}return Hf=!0,n}function HA(t,e,n,r){let o=mi.join(t,e),a=$A(o,r);if(!a)return;let i=jA(a,o,r);if(!i)return;let s=zA.safeParse(i);if(s.success===!1){r.warn(`Possible Momentic file at ${o} does not have a 'fileType', skipping: ${s.error}`);return}let l=s.data.fileType,c=GA(o,r);if(!c)return;let d=WA(e,o,c);switch(l){case pe.TEST:try{return VA(i,n,d,o,r)}catch(u){r.warn(`Skipping file '${o}' because it is missing Momentic test metadata: ${u}`);return}case pe.MODULE:try{return qA(i,n,d,o,r)}catch(u){r.warn(`Skipping file '${o}' because it is missing Momentic module metadata: ${u}`);return}case pe.MOBILE_TEST:try{return KA(i,n,d,o,r)}catch(u){r.warn(`Skipping file '${o}' because it is missing Momentic mobile test metadata: ${u}`);return}default:{let u=l;return}}}function $A(t,e){try{return zf.readFileSync(t,"utf-8")}catch(n){e.warn(`Could not read possible Momentic file at ${t}, skipping: ${n}`);return}}function jA(t,e,n){try{let r=BA.parse(t);if(typeof r!="object"||r===null)throw new Error("The YAML document should parse as a map with key-value pairs");return r}catch(r){n.warn(`Could not parse possible Momentic file at ${e}, skipping: ${r}`);return}}function GA(t,e){try{return zf.statSync(t)}catch(n){e.warn(`Skipping path '${t}' because it could not be stat, skipping: ${n}`);return}}function WA(t,e,n){return{relativePath:t,fullFilePath:e,platformSep:mi.sep,fullPathSegments:e.split(mi.sep),relativePathSegments:t.split(mi.sep),fileName:mi.basename(e),lastModified:n.mtime,createdAt:n.birthtime}}function VA(t,e,n,r,o){let a=en.parse(t),i;if(e.tests[a.id]){let s=e.tests[a.id].fullFilePath;i={id:a.id,paths:[s,r]}}return e.tests[a.id]={type:pe.TEST,name:a.name,id:a.id,description:a.description??void 0,labels:a.labels,...n},i}function qA(t,e,n,r,o){let a=Ot.parse(t),i;if(e.modules[a.moduleId]){let l=e.modules[a.moduleId].fullFilePath;i={id:a.moduleId,paths:[l,r]}}e.modules[a.moduleId]={type:pe.MODULE,name:a.name,id:a.moduleId,description:a.description??void 0,...n};let s=n.fileName.replace(`.${st.MODULE}`,"");return!Hf&&ve(a.name)!==s&&o.warn(`The module with ID ${a.moduleId} has a name (${a.name}) that does not match its file name (${s}). We recommend renaming the module or the file to be consistent to avoid confusion and issues with module resolution.`),i}function KA(t,e,n,r,o){let a=td.parse(t),i;if(e.mobileTests[a.id]){let l=e.mobileTests[a.id].fullFilePath;i={id:a.id,paths:[l,r]}}let s=n.fileName.replace(`.${st.TEST}`,"");return e.mobileTests[a.id]={type:pe.MOBILE_TEST,name:s,id:a.id,description:a.description??void 0,...n},i}var oa="momentic.config.yaml",$f="momentic.workspace.yaml",ex=ke.object({projects:ke.string().array().describe("list of glob patterns to find project (momentic.config.yaml) files")}),tx=ke.union([ke.string(),ke.object({fromFile:ke.string(),json:ke.boolean().optional()})]),nx=ke.object({name:qd,baseUrl:ke.string().optional().describe("Optional for mobile tests"),envFile:ke.string().optional().describe("path to a file on disk to read environment variables from. can be relative to project root or absolute."),envVariables:ke.record(ke.string(),tx).optional(),inheritFromShell:ke.boolean().optional().describe("inherit all environment variables from the shell - might be noisy"),browser:$r.optional().describe("deprecated: use project-level configuration only")}),rx=ke.object({postSave:ke.string().optional()}),ox=ke.object({name:qd,include:ke.string().array().optional().describe("list of glob patterns that match momentic files (optional)"),exclude:ke.string().array().optional().describe("opposite of include, takes precedence over include"),goldenFileDir:ke.string().optional(),reporterDir:ke.string().optional(),outputDir:ke.string().optional(),retries:ke.number().optional().describe("number of retries per test"),parallel:ke.number().optional().describe("degree of parallelism"),environments:ke.array(nx).optional(),gitMainBranch:ke.string().optional(),gitProtectedBranches:ke.string().array().optional(),ai:ud.optional(),browser:$r.optional(),advanced:md.optional(),hooks:rx.optional()});function Wf(t,e){let n;try{n=XA(t,"utf-8")}catch(o){S.warn(`Could not read possible Momentic ${e} file at ${t}: ${o}`);return}let r;try{if(r=Gf.parse(n),typeof r!="object"||r===null)throw new Error(`The ${e} file should parse as a map with key-value pairs, but is type ${typeof r} instead`)}catch(o){S.warn(`Possible Momentic ${e} file at ${t} does not parse as valid YAML: ${o}`);return}return r}function Xd(t){let e=Wf(t,"project configuration");if(e!==void 0)try{return ox.parse(e)}catch(n){S.warn(`Possible Momentic project configuration file at ${t} does not adhere to the required schema: ${n}`);return}}function ax(t){let e=Wf(t,"workspace configuration");if(e!==void 0)try{return ex.parse(e)}catch(n){S.warn(`Possible Momentic workspace configuration file at ${t} does not adhere to the required schema: ${n}`);return}}function ix(){let t=[],e=Yd(),n=io.parse(e).root,r=15,o=0;for(;o<r;){o++;let a=io.basename(e);if(Ts.includes(a))return S.warn(`Stopping search for Momentic projects since the current directory name (${a}) is likely a system artifact folder.`),t;for(let i of JA(e))if(i.endsWith(oa)){let s=io.join(e,i),l=Xd(s);l&&t.push({configFilePath:s,config:l,rootDir:jf(s)})}if(t.length)return t;if(e=io.dirname(e),e===n)break}return t}function ct(t={}){let{configFilePath:e,nameFilter:n}=t,r=Jd(e);if(n&&(r=r.filter(o=>o.config.name===n)),r.length>1)throw new Error(`Multiple valid projects were found in the same directory. Please use the '-c / --config' flag to disambiguate:
28
+ ${r.map(o=>o.configFilePath)}`);if(r.length===0)throw new Error("No valid Momentic project file available.");return S.debug(`Found valid project configuration at ${r[0].configFilePath}`),r[0]}function sx(t){let e=ax(t);if(!e||!e.projects||!e.projects.length)return;let n=e.projects.map(a=>(a.endsWith("/")||(a+="/"),`${a}*${oa}`)),r=ZA(n,{absolute:!1,cwd:Yd(),dotRelative:!1,maxDepth:Kd,nodir:!0}),o=[];for(let a of r){let i=io.join(Yd(),a),s=Xd(i);s&&o.push({configFilePath:i,config:s,rootDir:jf(i)})}return o}function Jd(t){if(t){t=io.resolve(t);let n=Xd(t);return n||(console.error(`No valid Momentic project file found at ${t}.`),process.exit(1)),[{config:n,configFilePath:t,rootDir:io.dirname(t)}]}if(YA($f)){let n=sx($f);if(n)return n}return ix()}function aa(t,e){let n=Gf.stringify(t);QA(e,n)}import ia from"fs";import Qd from"path";import{z as Zd}from"zod";var Vf="golden/visual-diff",qf="reports",Kf="test-results";var lx=Zd.object({width:Zd.number(),height:Zd.number()}),sa=class{defaultGoldenScreenshotDir;regenerateGoldenFiles;constructor(e,n){let r=Qd.join(e.rootDir,e.config.goldenFileDir??Vf);this.defaultGoldenScreenshotDir=r,this.regenerateGoldenFiles=n}async prepareGoldenScreenshotForComparison(e,n,r){if(n.screenshot?.data?.startsWith("https://")){let i=await fetch(n.screenshot.data);return{buffer:Buffer.from(await i.arrayBuffer()),width:n.screenshot.width,height:n.screenshot.height}}let o=n.screenshot?.data;o||(o=Qd.join(this.defaultGoldenScreenshotDir,`${n.id}.jpg`));let a=`${o}.metadata.json`;if(this.regenerateGoldenFiles)return ia.mkdirSync(Qd.dirname(o),{recursive:!0}),ia.writeFileSync(o,r.buffer),ia.writeFileSync(a,JSON.stringify({width:r.width,height:r.height})),{buffer:Buffer.from(r.buffer),width:r.width,height:r.height};if(ia.existsSync(o)){let i=ia.readFileSync(o),s=lx.parse(JSON.parse(ia.readFileSync(a,"utf-8")));return{buffer:i,width:s.width,height:s.height}}else throw new A("UserConfigurationError",`Cannot execute visual diff without a saved baseline screenshot at ${o}`)}};var fr=class{flags;constructor(e){this.flags={auto_expand_iframes:e.browser?.autoExpandIframes??!1,rag_v2:e.ai?.aiPageFiltering??!1,faker_constant_seed:e.advanced?.fakerConstantSeed??!1,disable_secondary_cache_resolution:e.browser?.disableSecondaryCacheResolution??!1,global_locator_redirect:e.browser?.globalLocatorRedirect??!0,visual_actions:e.browser?.visualActions??!1,mini_model_initial_assertion:!1,mini_model_initial_locator:!1,show_test_plans:!1,icon_knowledge_base:!1,disable_clickhouse_caches:!1,disable_clickhouse_last_updated_endpoint:!1}}isBooleanFlagEnabled(e){return this.flags[e]??!1}getAllFlags(){return{...this.flags}}getFlagPayload(e){}async refresh(){}};import{execFile as cx}from"node:child_process";import{promisify as dx}from"node:util";import ux from"simple-git";var Ae=ux(),Yf=dx(cx);async function mx(t){let e=await xe(t,Ae.raw(["config","--list"])),n={};if(!e)return n;for(let r of e.split(`
29
+ `)){let o=r.indexOf("=");if(o===-1)continue;let a=r.slice(0,o),i=r.slice(o+1).trim();n[a]=i}return n}async function px(t,e,n){try{let o=n["github.user"]||void 0;if(o)return o}catch{}let r;try{if(e?.startsWith("http://")||e?.startsWith("https://"))r=new URL(e).host;else if(e?.startsWith("git@")){let o=e.indexOf("@"),a=e.indexOf(":",o+1);o!==-1&&a!==-1&&(r=e.slice(o+1,a))}}catch{}if(r=r?.toLowerCase(),!!r){try{if(e?.startsWith("git@")&&r?.includes("github")){let{stdout:o,stderr:a}=await Yf("ssh",["-T","-o","BatchMode=yes",`git@${r}`],{timeout:5e3}),s=`${o??""}${a??""}`.trim().match(/Hi\s+([A-Za-z0-9_-]+)!/);if(s?.[1])return s[1]}}catch{}try{let o=r&&r!=="github.com"?["api","--hostname",r,"user","-q",".login"]:["api","user","-q",".login"],{stdout:a}=await Yf("gh",o,{timeout:5e3}),i=a?.toString().trim();if(i)return i}catch{}}}async function gx(t,e,n){let r=e?.includes("github.com"),o=e?.includes("gitlab.com");try{if(r)return px(t,e,n);if(o)return}catch{}}function al(t){if(t.startsWith("git@")){let e=t.split(":");if(e.length===2){let n=e[1].replace(".git","").split("/");if(n.length===2){let r=n[0],o=n[1];return`${r}/${o}`}}}else if(t.startsWith("http")||t.startsWith("https")){let n=new URL(t).pathname.split("/").filter(Boolean);if(n.length>=2){let r=n[0],o=n[1].replace(".git","");return`${r}/${o}`}}}async function xe(t,e){try{return(await e).trim()}catch(n){t.error({err:n},"Failed to run git command");return}}function hx(){if(process.env.GITHUB_ACTION)return"GithubActions";if(process.env.GITLAB_CI)return"GitlabCI";if(process.env.CIRCLECI)return"CircleCI";if(process.env.BUILDKITE)return"Buildkite";if(process.env["System.CollectionUri"]?.includes("azure"))return"AzureDevOps";if(process.env.PROJECT_ID&&process.env.BUILD_ID)return"GCPCloudBuild"}async function fx(t){let[e,n,r,o]=await Promise.all([xe(t,Ae.show(["--no-patch","--format=%ci"])),xe(t,Ae.listRemote(["--get-url","origin"])),xe(t,Ae.show(["-s","--pretty=%B"])),xe(t,Ae.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.GITHUB_SHA,gitCommitShaShort:process.env.GITHUB_SHA?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME,gitOriginUrl:n,gitCommitMessage:r,gitCommitAuthorName:o,githubRepository:process.env.GITHUB_REPOSITORY,pipelineId:process.env.GITHUB_RUN_ID}}async function Sx(t){let[e,n,r]=await Promise.all([xe(t,Ae.listRemote(["--get-url","origin"])),xe(t,Ae.show(["-s","--pretty=%B"])),xe(t,Ae.show(["-s","--pretty=%an"]))]);return{gitCommitSha:process.env.CI_COMMIT_SHA,gitCommitShaShort:process.env.CI_COMMIT_SHORT_SHA,gitCommitTimestamp:process.env.CI_COMMIT_TIMESTAMP?new Date(process.env.CI_COMMIT_TIMESTAMP):void 0,gitBranchName:process.env.CI_COMMIT_BRANCH||process.env.CI_COMMIT_REF_NAME,gitOriginUrl:e,gitCommitMessage:n,gitCommitAuthorName:r,gitlabProjectPath:process.env.CI_PROJECT_PATH,pipelineId:`${process.env.CI_PIPELINE_ID}:${process.env.CI_JOB_ID}`}}async function yx(t){let[e,n,r,o]=await Promise.all([xe(t,Ae.show(["--no-patch","--format=%ci"])),xe(t,Ae.listRemote(["--get-url","origin"])),xe(t,Ae.show(["-s","--pretty=%B"])),xe(t,Ae.show(["-s","--pretty=%an"]))]),a=n?.includes("github.com"),i=n?.includes("gitlab.com"),s=n?al(n):void 0;return{gitCommitSha:process.env.CIRCLE_SHA1,gitCommitShaShort:process.env.CIRCLE_SHA1?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.CIRCLE_BRANCH,gitOriginUrl:process.env.CIRCLE_REPOSITORY_URL,gitCommitMessage:r,gitCommitAuthorName:o,githubRepository:a?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:process.env.CIRCLE_PIPELINE_ID}}async function bx(t){let[e,n,r]=await Promise.all([xe(t,Ae.show(["--no-patch","--format=%ci"])),xe(t,Ae.show(["-s","--pretty=%B"])),xe(t,Ae.show(["-s","--pretty=%an"]))]),o=process.env.BUILDKITE_REPO,a=o?.includes("github.com"),i=o?.includes("gitlab.com"),s=o?al(o):void 0;return{gitCommitSha:process.env.BUILDKITE_COMMIT,gitCommitShaShort:process.env.BUILDKITE_COMMIT?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env.BUILDKITE_BRANCH,gitOriginUrl:o,gitCommitMessage:n,gitCommitAuthorName:r,githubRepository:a?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:`${process.env.BUILDKITE_PIPELINE_ID}:${process.env.BUILDKITE_BUILD_ID}:${process.env.BUILDKITE_JOB_ID}`}}async function Tx(t){let[e,n,r]=await Promise.all([xe(t,Ae.show(["--no-patch","--format=%ci"])),xe(t,Ae.show(["-s","--pretty=%B"])),xe(t,Ae.show(["-s","--pretty=%an"]))]),o=process.env["Build.Repository.Uri"],a=o?.includes("github.com"),i=o?.includes("gitlab.com"),s=o?al(o):void 0;return{gitCommitSha:process.env["Build.SourceVersion"],gitCommitShaShort:process.env["Build.SourceVersion"]?.slice(0,6),gitCommitTimestamp:e?new Date(e):void 0,gitBranchName:process.env["Build.SourceBranchName"],gitOriginUrl:o,gitCommitMessage:n,gitCommitAuthorName:r,githubRepository:a?s:void 0,gitlabProjectPath:i?s:void 0,pipelineId:`${process.env["System.JobId"]}:${process.env["System.JobAttempt"]}`}}async function wx(t,e){let[n,r,o,a,i,s,l,c,d]=await Promise.all([xe(t,Ae.revparse(["HEAD"])),xe(t,Ae.revparse(["--short","HEAD"])),xe(t,Ae.revparse(["--abbrev-ref","HEAD"])),xe(t,Ae.listRemote(["--get-url","origin"])),xe(t,Ae.show(["--no-patch","--format=%ci"])),xe(t,Ae.show(["-s","--pretty=%B"])),xe(t,Ae.show(["-s","--pretty=%an"])),e?xe(t,Ae.raw(["merge-base","--fork-point",e])):Promise.resolve(void 0),mx(t)]),u=c?await xe(t,Ae.show(["--no-patch","--format=%ci",c])):void 0,m=a?.includes("github.com"),p=a?.includes("gitlab.com"),g=a?al(a):void 0,h=d["user.email"]||void 0,f=d["user.name"]||void 0,y=d["user.username"]||void 0,b=await gx(t,a,d)??y??void 0;return t.debug({userUsername:b,gitLocalUserLogin:y,gitLocalUserEmail:h,gitLocalUserName:f},"Resolved local git identity"),{gitCommitSha:n,gitCommitShaShort:r,gitBranchName:o,gitOriginUrl:a,gitCommitTimestamp:i?new Date(i):void 0,gitCommitMessage:s,gitCommitAuthorName:l,gitLocalUsername:b,gitLocalEmail:h,gitLocalName:f,lastCommitOnMainSha:c,lastCommitOnMainTimestamp:u?new Date(u):void 0,githubRepository:m?g:void 0,gitlabProjectPath:p?g:void 0,pipelineId:void 0}}async function Ex(){let t=process.env._HEAD_REPO_URL;return{gitCommitSha:process.env.COMMIT_SHA,gitCommitShaShort:process.env.COMMIT_SHA?.slice(0,6),gitBranchName:process.env.BRANCH_NAME,gitOriginUrl:t?process.env._HEAD_REPO_URL:void 0,gitCommitTimestamp:void 0,gitCommitMessage:void 0,gitCommitAuthorName:void 0,githubRepository:t?process.env.REPO_FULL_NAME:void 0,pipelineId:`${process.env.PROJECT_ID}:${process.env.BUILD_ID}`}}async function Rx(t){let e=t.config.gitProtectedBranches??[];return t.config.gitMainBranch&&e.push(t.config.gitMainBranch),{gitMainBranch:t.config.gitMainBranch,gitProtectedBranches:e}}async function eu(t,e){let n=hx();if(!n)return wx(t,e);switch(n){case"GithubActions":return fx(t);case"GitlabCI":return Sx(t);case"CircleCI":return yx(t);case"Buildkite":return bx(t);case"AzureDevOps":return Tx(t);case"GCPCloudBuild":return Ex()}}async function Cx(t,e,n,r){let o=r;if(!r.gitCommitSha)return o;if(r.gitMainBranch&&(!o.lastCommitOnMainSha||!o.lastCommitOnMainTimestamp)){let a=await e.getMergeBaseCommitFromGitlab(n,r.gitMainBranch,r.gitCommitSha);o={...o,lastCommitOnMainSha:a.sha,lastCommitOnMainTimestamp:a.committer.date}}if(!o.gitCommitTimestamp||!o.gitCommitAuthorName||!o.gitCommitMessage||!o.gitCommitAuthorName){let a=await e.getCommitFromGitlab(n,r.gitCommitSha);a&&(o={...o,gitCommitTimestamp:o.gitCommitTimestamp??a.committer.date,gitCommitAuthorName:o.gitCommitAuthorName??a.author.name,gitCommitMessage:o.gitCommitMessage??a.message})}return o}async function vx(t,e,n,r,o){let a=o;if(!o.gitCommitSha)return a;if(o.gitMainBranch&&(!a.lastCommitOnMainSha||!a.lastCommitOnMainTimestamp)){let i=await e.getMergeBaseCommitFromGithub(n,r,o.gitMainBranch,o.gitCommitSha);a={...a,lastCommitOnMainSha:i.sha,lastCommitOnMainTimestamp:i.committer.date}}if(!a.gitCommitTimestamp||!a.gitCommitAuthorName||!a.gitCommitMessage||!a.gitCommitAuthorName){let i=await e.getCommitFromGithub(n,r,o.gitCommitSha);i&&(a={...a,gitCommitTimestamp:a.gitCommitTimestamp??i.committer.date,gitCommitAuthorName:a.gitCommitAuthorName??i.author.name,gitCommitMessage:a.gitCommitMessage??i.message})}return a}async function Ax(t,e,n){try{if(n.githubRepository){let[r,o]=n.githubRepository.split("/");return await vx(t,e,r,o,n)}else if(n.gitlabProjectPath)return await Cx(t,e,n.gitlabProjectPath,n)}catch(r){t.warn({err:r},"Failed to get remote git metadata")}return n}async function Sr(t,e,n){let r=await Rx(n),o=await eu(t,r.gitMainBranch),a={...r,...o};(!a.lastCommitOnMainSha||!a.lastCommitOnMainTimestamp)&&a.gitBranchName===r.gitMainBranch&&(a.lastCommitOnMainSha=a.gitCommitSha,a.lastCommitOnMainTimestamp=a.gitCommitTimestamp);let i=await Ax(t,e,a);return{...r,...o,...i}}import UJ from"yaml";import{randomUUID as xx}from"crypto";import Vn from"fs";import so from"path";var Xf={status:(t,e)=>{if(t.status===e.status)return t.status;if(t.status==="FAILED"||e.status==="FAILED")return"FAILED";if(t.status==="CANCELLED"||e.status==="CANCELLED")return"CANCELLED";if(t.status==="RETRYING"||e.status==="RETRYING")return"RETRYING";if(t.status==="RUNNING"||e.status==="RUNNING")return"RUNNING";if(t.status==="PENDING"||e.status==="PENDING")return"PENDING";throw new Error(`Invalid run status merge: ${t.status} and ${e.status}`)},startedAt:(t,e)=>t.startedAt<e.startedAt?t.startedAt:e.startedAt,updatedAt:(t,e)=>t.updatedAt>e.updatedAt?t.updatedAt:e.updatedAt,finishedAt:(t,e)=>!t.finishedAt||!e.finishedAt?new Date:t.finishedAt>e.finishedAt?t.finishedAt:e.finishedAt,gitCommitTimestamp:(t,e)=>{if(!(!t&&!e)){if(!t.gitCommitTimestamp||!e.gitCommitTimestamp||t.gitCommitTimestamp.getTime()!==e.gitCommitTimestamp.getTime())throw new Error(`Git commit timestamps must match to be merged: ${t.gitCommitTimestamp} and ${e.gitCommitTimestamp}`);return t.gitCommitTimestamp}},pipelineId:(t,e)=>t.pipelineId===e.pipelineId?t.pipelineId:!t.pipelineId&&e.pipelineId?e.pipelineId:!e.pipelineId&&t.pipelineId?t.pipelineId:t.startedAt<e.startedAt?e.pipelineId:t.pipelineId,labels:(t,e)=>{let n=new Set([...t.labels??[],...e.labels??[]]);return Array.from(n)}};function Ix(t,e,n){if(Xf[n]){let a=Xf[n];return a(t,e)}let r=t[n],o=e[n];if(r!==o)throw new Error(`Metadata values for key "${n}" do not match: "${r}" vs "${o}"`);return r}var Jf=new Set([".DS_Store","__MACOSX"]);function Qf(t,e,n){let r=xx(),o=t.child({runGroupId:r});Vn.rmSync(e,{recursive:!0,force:!0});let a=Vn.readdirSync(n).filter(c=>!Jf.has(c)).map(c=>so.join(n,c));if(a.length===0)throw new Error(`No run groups found in results path: ${n}`);Vn.mkdirSync(e,{recursive:!0});let i=so.join(a[0],"metadata.json"),s={...Xa.parse(JSON.parse(Vn.readFileSync(i,"utf-8"))),id:r};for(let c of a){let d=so.join(c,"runs");if(!Vn.existsSync(d))continue;let u=Vn.readdirSync(d);for(let g of u){if(Jf.has(g))continue;let h=so.join(d,g),f=so.join(e,"runs",g);Vn.cpSync(h,f,{recursive:!0})}let m=so.join(c,"metadata.json"),p=Xa.parse(JSON.parse(Vn.readFileSync(m,"utf-8")));o.info({oldRunGroupId:p.id},"Merging metadata from run groups");for(let g in p){if(g==="id")continue;let h=g;s[h]=Ix(s,p,h)}}let l=so.join(e,"metadata.json");Vn.writeFileSync(l,JSON.stringify(s,null,2))}import Zf from"adm-zip";import tu from"fs";import il from"path";function Px(t){let e=new Zf,n=il.join(t,"metadata.json"),r=Xa.parse(JSON.parse(tu.readFileSync(n,"utf-8")));e.addLocalFile(n);for(let o of tu.readdirSync(il.join(t,"runs"))){if(!o.endsWith(".zip"))continue;let a=o.replace(/\.zip$/,""),i=new Zf(il.join(t,"runs",o));for(let s of i.getEntries())s.isDirectory||e.addFile(il.join("runs",a,s.entryName),s.getData())}return{runGroupId:r.id,buffer:e.toBuffer()}}async function sl(t){let{client:e,consoleLogger:n,resultsPath:r}=t;if(!tu.existsSync(r)){n.warn("Results path does not exist, skipping upload.");return}let o=new ks(e);try{let{runGroupId:a,buffer:i}=Px(r),s=await o.uploadResultsArchive(a,i),l=`${e.getAppUrl()}/run-groups/${s}`;n.success(`Successfully uploaded test results. Once processed, your results can be found at ${l}`);return}catch(a){let i;a instanceof Error?i=a.message:typeof a=="string"?i=a:i="Unknown error",n.error(`Failed to upload test results: ${i}.`);return}}import Mx from"adm-zip";import Lt from"fs";import un from"path";var pi=class t{constructor(e){this.filePath=e;Lt.rmSync(this.filePath,{recursive:!0,force:!0}),Lt.mkdirSync(this.filePath,{recursive:!0})}cd(e){return new t(un.join(this.filePath,e))}mkdir(e){Lt.mkdirSync(un.join(this.filePath,e),{recursive:!0})}readFile(e){let n=un.join(this.filePath,e);if(Lt.existsSync(n))return Lt.readFileSync(n)}storeFile(e){let{name:n,contents:r}=e,o=un.join(this.filePath,n);try{Lt.writeFileSync(o,r)}catch{}}createRunArchive(e){return new nu(un.join(this.filePath,"runs"),e)}},nu=class{constructor(e,n){this.filePath=e;this.tempPath=un.join(e,`.${n}`),this.finalPath=un.join(e,`${n}.zip`),Lt.rmSync(this.tempPath,{recursive:!0,force:!0}),Lt.rmSync(this.finalPath,{recursive:!0,force:!0}),Lt.mkdirSync(this.tempPath,{recursive:!0})}tempPath;finalPath;readFile(e){let n=un.join(this.tempPath,e);if(Lt.existsSync(n))return Lt.readFileSync(n)}mkdir(e){Lt.mkdirSync(un.join(this.tempPath,e),{recursive:!0})}cd(e){return new pi(un.join(this.tempPath,e))}storeFile(e){let{name:n,contents:r}=e,o=un.join(this.tempPath,n);Lt.writeFileSync(o,r)}close(){let e=new Mx;e.addLocalFolder(this.tempPath,void 0,r=>r!==".DS_Store");let n=e.toBuffer();Lt.writeFileSync(this.finalPath,n),Lt.rmSync(this.tempPath,{recursive:!0,force:!0})}};import XL from"http";import JL from"path";import{Server as aL}from"socket.io";var Lx=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async()=>{e.info({sessionId:r},"Cancel event received");let o=n.getSession(r);if(!o)throw new Error("No active session found");try{o.controller.setClosed()}catch{}}},eS={event:"cancel",createHandler:Lx};var Ox=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async(o,a)=>{let i=n.getSession(r);if(!i)throw new Error("No active session found");i.controller.setOpen();let s=i.controller.browser;try{let c=(await s.getBrowserState({skipWait:!0})).serialize();e.debug({a11yTree:c},"Fetched a11y tree from the browser"),a({a11yTree:c})}catch(l){e.error({err:l},"Error fetching a11y tree from the browser"),a({err:l.message})}}},tS={event:"fetchA11yTree",createHandler:Ox};var Nx=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async(o,a)=>{let i=n.getSession(r);if(!i)throw new Error("No active session found");i.controller.setOpen();let s=i.controller.browser;try{let l=await s.html();a({html:l})}catch(l){e.error({err:l},"Error fetching DOM from the browser"),l.name==="TimeoutError"?a({err:"Timed out fetching DOM tree. This page may be too large for Momentic to process."}):a({err:l.message})}}},nS={event:"fetchDom",createHandler:Nx};var kx=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return o=>{e.info({sessionId:r,reason:o},`Disconnect event received (${o})`),n.removeSession(r,e)}},rS={event:"disconnect",createHandler:kx};function In(t){let{result:e,nestedResults:n}=t;if(!t.nestedResults.length)return;let{firstMetadata:r,lastMetadata:o}=_x(n);Dx(e,r,o);let a=[...t.asyncTasks];t.asyncTasks.push((async()=>{try{await Fx(a,e,r,o)}catch(i){t.logger.error({result:t.result,err:i},"Error hoisting scalar result metadata")}})())}function _x(t){let e=t[0],n;for(;;){switch(e.type){case"PRESET_ACTION":{n=e;break}case"CONDITIONAL":if(e.assertionResult){n=e;break}break;case"AI_ACTION_DYNAMIC":case"AI_ACTION":case"MODULE":case"SECTION":if(!e.results.length){n=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(n)break}let r=t[t.length-1],o;for(;;){switch(r.type){case"PRESET_ACTION":{o=r;break}case"AI_ACTION_DYNAMIC":case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":if(!r.results.length){o=r;break}r=r.results[r.results.length-1];break;default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}if(o)break}return{firstMetadata:n,lastMetadata:o}}function Dx(t,e,n){e&&(t.beforeUrl=e.beforeUrl),n&&(t.afterUrl=n.afterUrl,t.data=n.data,n.status!=="SUCCESS"&&(t.message=n.message))}async function Fx(t,e,n,r){await Promise.allSettled(t),n&&(e.beforeSnapshot=n.beforeSnapshot),r&&(e.afterSnapshot=r.afterSnapshot)}import gi from"os";import Ux from"v8";var oS,Pn,Bx=gi.platform(),zx=gi.cpus().map(t=>({model:t.model,speed:t.speed})).reduce((t,e)=>(t[e.model]={speed:e.speed},t.totalCores=(t.totalCores??0)+1,t),{});function aS(t){let e=()=>{try{let n=!1,r=Hx(),o=$x();r.freeMemory<1e6&&(n=!0);let a=Ux.getHeapStatistics(),i=a.used_heap_size,s=a.heap_size_limit;i/s>.9&&(n=!0),n?t.warn({memory:r,cpu:o,heapStats:a},"Critical resource usage metrics detected"):t.debug({memory:r,cpu:o},"Got machine resource usage metrics")}catch{}};return e(),{interval:setInterval(e,2e4),cpuMetadata:zx,platform:Bx}}function Hx(){let t=gi.totalmem(),e=gi.freemem(),n=t-e;return{totalMemory:t,freeMemory:e,usedMemory:n}}function $x(){let t=gi.cpus(),e=Date.now(),n={measurementTime:e,user:0,nice:0,sys:0,idle:0,irq:0,total:0};for(let o of t)n.user+=o.times.user,n.nice+=o.times.nice,n.sys+=o.times.sys,n.idle+=o.times.idle,n.irq+=o.times.irq;if(n.total=n.user+n.nice+n.sys+n.idle+n.irq,!Pn)return Pn=n,null;let r={user:n.user-Pn.user,nice:n.nice-Pn.nice,sys:n.sys-Pn.sys,idle:n.idle-Pn.idle,irq:n.irq-Pn.irq,total:n.total-Pn.total};return oS={measurementTime:e,intervalMs:e-Pn.measurementTime,user:r.user/r.total*100,nice:r.nice/r.total*100,sys:r.sys/r.total*100,idle:r.idle/r.total*100,irq:r.irq/r.total*100,total:100-r.idle/r.total*100},Pn=n,oS}import{randomUUID as Zx}from"crypto";import{faker as jx}from"@faker-js/faker";import Gx from"assert";import Wx from"axios";import*as Vx from"child_process";import qx from"moment";import*as Kx from"otpauth";import Yx from"pg";async function iS(t){let e;try{e=new URL(t.url).hostname}catch{}let n=[];return t.headers.getSetCookie()?.forEach(r=>{let o=ds(r,e);n.push(...o)}),n}function Xx(t,e){if(!t&&!e)return;let n;if(t){let{url:o,options:a}=t;n=new Request(o,a)}let r;if(e){let{body:o,options:a}=e;r=new Response(o??null,a)}return{request:n,response:r}}async function Jx(t,e){switch(t){case"RAW":return e;case"RESPONSE":if(e instanceof Response){let n=[];return e.headers.forEach((o,a)=>{n.push([a,o])}),{status:e.status,headers:n,body:await e.text()}}else throw new Error("Result is not a Response object")}}var Qx=Object.getPrototypeOf(async function(){}).constructor;async function sS(t,e,n){let r=e.code;e.options.fragment&&(r=`return ${e.code}`);let{env:o,additionalBindings:a,request:i,response:s}=e.bindings,l=e.tools,c={},d=(w,C)=>{o[w]=C,c[w]=C},u={},m=(w,C)=>{o[w]=C,u[w]=C},p;r.includes("Octokit")&&(p=(await import("@octokit/rest")).Octokit);let g;r.includes("createAppAuth")&&(g=(await import("@octokit/auth-app")).createAppAuth);let h=async()=>await Promise.resolve(new Qx("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","child_process","extractCookiesFromResponse","env","setVariable","setPersistentVariable","sendSms","waitForLatestSms","email","sms","ai","mock",...Object.keys(a??{}),r)(Wx,qx,l.fakerInstance??jx,Gx,Yx,p,g,Kx,Vx,iS,o,e.options.disallowVariableUpdates?void 0:d,e.options.disallowVariableUpdates?void 0:m,C=>l.sms.send(C),C=>l.sms.fetchLatest(C),l.email,l.sms,l.ai,Xx(i,s),...Object.values(a??{}))),f=!0,y,b;try{let w=await H(h(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`,signal:e.signal});y=await Jx(e.options.responseSerialization??"RAW",w)}catch(w){n.error({err:w,env:o,evalCode:r},`[${t}] Error executing code: ${w}`),f=!1,w instanceof pr?b=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:b=w instanceof Error?w.message:`${w}`}return{result:y,variableUpdates:c,persistentVariableUpdates:u,success:f,error:b}}async function lS({code:t,fragment:e,context:n,localTools:r,logger:o,signal:a,timeoutMs:i=cr,disallowVariableUpdates:s,additionalBindings:l,responseSerialization:c,mock:d}){let u=Zx(),m=await sS(u,{code:t,options:{fragment:e,timeoutMs:i,disallowVariableUpdates:s,responseSerialization:c},bindings:{...n.toObjectCopy(),...d,additionalBindings:l},tools:r,signal:a},o);return S.debug(`[${u}] Got execution result: ${JSON.stringify(m)}`),m}import{createHmac as eI,randomUUID as tI}from"crypto";import nI from"fetch-retry";var rI=nI(global.fetch,{retries:3,retryOn:function(t,e,n){return!!(e!==null||n&&n.status>=500)},retryDelay:function(t){return Math.pow(2,t)*500}}),cS=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT,dS=process.env.MOMENTIC_LAMBDA_AUTH_SECRET;async function uS({orgId:t,code:e,fragment:n,context:r,timeoutMs:o=cr,retries:a=2,signal:i,logger:s,additionalBindings:l,disallowVariableUpdates:c,responseSerialization:d,mock:u}){if(!cS)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let m,p,g=0;if(!dS)throw new Error("Missing lambda auth secret.");let h=eI("sha256",dS).update(t).digest("hex");for(;g<=a;){g++,i?.throwIfAborted();let y={id:tI(),orgId:t,momenticLambdaAuthHash:h,code:e,fragment:n,state:{...r.toObjectCopy(),...u,additionalBindings:l},timeoutMs:o,disallowVariableUpdates:c,responseSerialization:d};try{if(m=await H(rI(cS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`,signal:i}),!m)throw new Error("Got empty response from code evaluation server");if(!m.ok)throw new Error(`Code evaluation server returned error code ${m.status}`);p=void 0;break}catch(b){p=b}}if(p)throw s.error({err:p},"Failed to evaluate code remotely"),p;if(!m)throw new Error(`An unexpected code evaluation error occurred${p?`: ${p}`:""}`);let f;try{f=Wp.parse(await m.json())}catch(y){throw new Error(`Code evaluation server returned invalid response: ${y}`)}if(f.error)throw new Error(`Code evaluation error: ${f.error}`);return f}async function yr(t){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await uS(t);else if(t.localTools)e=await lS({...t,localTools:t.localTools});else throw new Error("No code evaluation environment available");if(e.error){let n=`Failed to evaluate code:
30
30
  ${e.error}
31
31
  Code received:
32
- ${t.code}`;throw t.logger.error({err:e.error,code:t.code,env:t.context.toObjectCopy()},n),new Error(n)}if(e.variableUpdates)for(let[n,r]of Object.entries(e.variableUpdates))t.context.setVariable(n,r);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await t.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[n,r]of Object.entries(e.persistentVariableUpdates))t.context.setVariable(n,r)}return e.result}import{set as Gx}from"lodash-es";async function $t(t){let{orgId:e,s:n,context:r,logger:o,signal:i,retries:a=2,timeoutMs:s=lr,allowUndefined:l=!1}=t,c=/{{(.*?)}}/g,d=n.matchAll(c),u=n;for(let m of d){if(m.length<2)continue;let g=m[1].trim(),p;try{p=await io({orgId:e,code:g,fragment:!0,context:r,timeoutMs:s,logger:o,retries:a,localTools:t.localTools,signal:i})}catch(f){throw o.error({err:f,value:n},"Error evaluating template string"),f}if(p===void 0&&!l)throw new A("UserConfigurationError",`Template fragment '${g}' 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.replaceAll(/\$/g,"$$$$"),u=u.replace(m[0],h)}return u}async function el(t){return nS(t)}async function nS({obj:t,bannedKeys:e,allowList:n,context:r,prefixPath:o=[],replacements:i=[],...a}){for(let s in t){if(e.includes(s))continue;let l=!1;if(n)if(n.includes(s))l=!0;else continue;let c=t[s],d=[...o,s];if(typeof c=="string"&&c.includes("{{")){let u=await $t({s:c,context:r,...a});if(c===u)continue;i.push({path:d,original:c}),t[s]=u}else typeof c=="object"&&c!==null&&!Array.isArray(c)&&await nS({obj:c,bannedKeys:e,context:r,prefixPath:d,replacements:i,allowList:l?void 0:n,...a})}return i}function rS(t,e){for(let{path:n,original:r}of e)Gx(t,n,r)}import Wx from"fetch-retry";var t6=process.env.MAILINATOR_API_KEY,n6=Wx(global.fetch,{retryOn:function(t,e,n){return t>3?!1:!!(e!==null||n&&n.status>=400)},retryDelay:function(t){return 500}});import{hostname as Qx}from"os";async function oS(t){let{command:e,tracer:n,timeoutMs:r,targetingWrapper:o,disableCache:i,fixtures:a}=t,{logger:s,abortSignal:l}=a;if(e.target&&!nr(e.target))throw new Error("Element assertion with x/y is not supported yet");let c=qx(e.assertion),d=ym(e.cache)?e.cache:void 0,u=Date.now(),m=0,g,p=500;for(;m<2||Date.now()-u<r;){m++,m>1&&await J(p,l),l?.throwIfAborted();try{let{elementInteractedDisplayString:h,result:f}=await o({ctx:a.ctx,tracer:n,command:e,target:e.target,cache:d?.target,action:async S=>Vx(S.locator,t),options:{...e,disableCache:i,disableGlobalLocatorRedirect:!0,source:Ur(e),allowZeroOpacityOverride:!0,targetName:"target"}});if(g={success:f.success,data:f.data,err:f.err,elementInteractedDisplayString:h},!f.success){g=f,p=Math.min(p*2,1e4);continue}return g}catch(h){if(l?.throwIfAborted(),c)return{success:!0,thoughts:`The element described does not exist on the page: ${h.message}`};if(s.warn({err:h},"Element assertion ended in error, retrying..."),!(h instanceof A)||h.reason!="ActionFailureError")throw h;g={success:!1,err:h}}}if(!g)throw new Error(`Failed to evaluate manual element assertion in ${r}ms.`);return g}async function Vx(t,{command:e,fixtures:n}){let r=e.assertion;await n.browser.highlight(t);let o=!0,i,a;switch(r.type){case"ELEMENT_CONTENT":{let l=await t.textContent()??"";if(a={elementTextContent:He(l,500,!0)},!tl(l,r.value,r.operation,!!r.negated)){let c=r.negated?en[r.operation]:tn[r.operation];o=!1,i=new A("AssertionFailureError",`The content ${c} '${r.value}': ${l}`)}break}case"ELEMENT_ATTRIBUTE":{a={elementOuterHtml:He(await t.evaluate(c=>c.cloneNode(!1).outerHTML),500,!0)};let l;try{l=await t.getAttribute(r.attr,{timeout:3e3})??""}catch(c){i=new A("AssertionFailureError",`The element does not have an attribute named ${r.attr}: ${c}`),o=!1;break}if(!tl(l,r.value,r.operation,!!r.negated)){let c=r.negated?en[r.operation]:tn[r.operation];o=!1,r.operation==="EXISTS"?i=new A("AssertionFailureError",`The attribute ${r.attr} ${c}`):i=new A("AssertionFailureError",`The attribute ${r.attr} ${c} '${r.value}': ${l}`)}break}case"ELEMENT_EXISTENCE":{switch(r.condition){case"VISIBLE":{o=await t.evaluate(async(c,d)=>{let u=Date.now();for(;Date.now()-u<d;){await new Promise(g=>setTimeout(g,250));let m=c.getBoundingClientRect();if(!(m.width===0||m.height===0)&&window.getComputedStyle(c).visibility!=="hidden"&&window.getComputedStyle(c).display!=="none")return!0}return!1},bn*1e3);break}case"EDITABLE":{o=await t.isEditable({timeout:bn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await t.isEnabled({timeout:bn*1e3});break}case"FOCUSED":{o=await t.evaluate(c=>c===document.activeElement);break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.condition)}if(o=r.negated?!o:o,!o){let l=r.negated?Cd[r.condition]:Rd[r.condition];i=new A("AssertionFailureError",`The element ${l}`)}break}case"ELEMENT_NAME":{let l=await t.evaluate(c=>c.tagName);if(!tl(l,r.value,r.operation,!!r.negated)){let c=r.negated?en[r.operation]:tn[r.operation];o=!1,i=new A("AssertionFailureError",`The element tag name ${c} '${r.value}': ${l}`)}break}case"ELEMENT_STYLE":{let l=await t.evaluate((c,d)=>window.getComputedStyle(c).getPropertyValue(d),r.property);if(!tl(l,r.value,r.operation,!!r.negated)){let c=r.negated?en[r.operation]:tn[r.operation];o=!1,r.operation==="EXISTS"?i=new A("AssertionFailureError",`The style property ${r.property} ${c}`):i=new A("AssertionFailureError",`The style property ${r.property} ${c} '${r.value}': ${l}`)}break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return{success:o,data:a,err:i}}function tl(t,e,n,r){let o;switch(n){case"CONTAINS":{o=t.includes(e);break}case"EQUALS":{o=t.trim()===e.trim();break}case"STARTS_WITH":{o=t.trim().startsWith(e);break}case"EXISTS":{o=t.trim().length>0;break}default:return(a=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return r?!o:o}function qx(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&(t.condition==="EXISTS"||t.condition==="VISIBLE")}function iS(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&t.condition==="EXISTS"}import{Jimp as Kx}from"jimp";async function ma(t,e){let n=await t.screenshot(e),r=await Kx.fromBuffer(n);return{buffer:n,width:Math.ceil(r.bitmap.width??0),height:Math.ceil(r.bitmap.height??0)}}import{Jimp as aS}from"jimp";import Xd from"jpeg-js";import Yx from"pixelmatch";async function sS({ctx:t,tracer:e,command:n,disableCache:r,browser:o,targetingWrapper:i,logger:a,screenshotStorage:s}){if(n.target&&!nr(n.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:a});let l={clearHighlights:!0,hideCaret:!0},c;n.target?.elementDescriptor?c=(await i({ctx:t,tracer:e,command:n,target:n.target,cache:n.cache?.target,action:async V=>ma(o,{locator:V.locator,...l}),options:{...n,disableCache:r,disableGlobalLocatorRedirect:!0,targetName:"target"}})).result:c=await ma(o,l);let d=await s.prepareGoldenScreenshotForComparison(a,n,c);if((c.height!==d.height||c.width!==d.width)&&a.warn({currHeight:c.height,currWidth:c.width,savedHeight:d.height,savedWidth:d.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(c.height-d.height)>10||Math.abs(c.width-d.width)>10){let N=`${c.width}x${c.height}`,V=`${d.width}x${d.height}`;return{fail:!0,thoughts:`Current screenshot (${N}) does not match saved screenshot dimensions (${V}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:d.buffer,afterScreenshotOverride:c.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let u=await aS.fromBuffer(c.buffer),m={width:c.width,height:c.height},g=await aS.fromBuffer(d.buffer),p={width:d.width,height:d.height},h,f=m.width*m.height,S=p.width*p.height,b=Math.abs(m.height-p.height),E=Math.abs(m.width-p.width);if(f>S){let N=u.cover({w:p.width,h:p.height});c.buffer=await N.getBuffer("image/jpeg"),h="current",c.width=p.width,c.height=p.height}else if(S>f){let N=g.cover({w:m.width,h:m.height});d.buffer=await N.getBuffer("image/jpeg"),h="saved"}let v={data:Buffer.alloc(c.width*c.height*4),width:c.width,height:c.height},R=n.threshold??.1,x=Yx(Xd.decode(d.buffer).data,Xd.decode(c.buffer).data,v.data,c.width,c.height,{threshold:R,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,L=x>R*100,k=`Visual diff of ${x.toFixed(2)}% detected, which is ${L?"over":"under"} the threshold of ${R*100}%.`;if(h&&(k+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${E} pixels.`),L)throw new A("ActionFailureError",k);return{fail:L,thoughts:k,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:Xd.encode(v,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var Xx=3e4;async function lS({command:t,logger:e,baseUrl:n,fetchImplementation:r=fetch}){let o=t.timeout??Xx/1e3,i=Object.fromEntries(Object.entries(t.headers||{}).filter(([g,p])=>g&&p)),a=new URLSearchParams;Object.entries(t.params||{}).filter(([g,p])=>g&&p).forEach(([g,p])=>{a.append(g,p)});let s=a.toString(),l;if(Jo(t.url)&&(l=t.url),n&&Qo(t.url,n)&&(l=new URL(t.url,n).toString()),!l)throw new A("ActionFailureError",`Invalid URL: ${t.url}`);e.info({url:l,searchParams:s,headers:i,body:t.body,method:t.method},"Making HTTP request");let d=await z((async()=>{let g=s?`${l}?${s}`:l;try{return await r(g,{headers:i,method:t.method,body:t.body})}catch(p){throw e.error({err:p},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${p}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new A("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok){let g;try{g=await d.text()}catch(p){g=`Failed to read response body: ${p}`}throw new A("ActionFailureError",`Fetch request failed with status ${d.status}: ${g}`)}let u={};d.headers.forEach((g,p)=>{u[p]=g});let m={status:d.status,headers:u};if(d.headers.get("content-type")?.includes("json"))try{m.json=await d.json()}catch{}else d.headers.get("content-type")?.includes("text")&&(m.text=await d.text());return m}var Jx=5e3;async function nl({timeout:t=bn,...e}){let n=Date.now(),r=t*1e3,o=r+1e4,i,a=0,s=500;for(;a-n<r;){if(Date.now()-n>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let l=Date.now();i=await cS(e),a=Date.now();let c=a-l;if(c>1e3&&e.logger.warn({pageAssertDuration:c},"Page assertion took longer than expected"),!i.success)await J(s,e.signal),s=Math.min(Math.floor(s*1.5),Jx);else return i}return i=await cS(e),i}async function cS({assertion:t,browser:e,autoExpandIframes:n}){switch(t.type){case"CONTENT":{let o,i=!1,a;try{let s;if(n){let l=await e.evaluateFunctionInAllFrames(dS,{value:t.value,negated:!!t.negated,returnHtml:!1});i=t.negated?l.every(c=>c.evaluation):l.some(c=>c.evaluation),s=l.find(c=>c.pageHtml)?.pageHtml}else({evaluation:i,pageHtml:s}=await e.evaluateFunctionInPage(dS,{value:t.value,negated:!!t.negated,returnHtml:!0},"checking page content"));if(!i){let l=t.negated?en.CONTAINS:tn.CONTAINS;a=new A("AssertionFailureError",`The page ${l} '${t.value}'.`),o=s}}catch(s){a=new A("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}return{success:i,err:a,data:i||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t.type)}}function dS({value:t,negated:e,returnHtml:n}){let r=document.documentElement.outerHTML,o=r.includes(t)===!e;return r.length>1e4&&(r=r.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&n?r:void 0}}var Jd=async t=>{let{step:e,resolvedInputs:n}=t.moduleParams,{logger:r,context:o,storage:i,codeEvalTools:a,controller:s}=t.fixtures,l=s.browser,{orgId:c,runId:d}=t.inputs,u=s.executeAbortController.signal;Object.keys(n).length>0&&(o.setInputs(n),r.info(Id({json:{inputs:n,moduleId:e.moduleId},maxJsonStringSize:1e3}),"Set module inputs"));let m,g=!1,p,h;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",S=await $t({orgId:c,s:f,context:o,logger:r,localTools:a,signal:u});h={orgId:c,cacheKeys:[S,...Object.entries(n).map(([E,v])=>`${E}:${v}`)]},r.info({original:f,keyParams:h},"Module cache key params");let b=Date.now();for(;Date.now()-b<mg;){u?.throwIfAborted();let E=await i.getCacheResult(h);if(E){r.info({cacheResult:He(E,1e3,!0)},"Got result from module execution cache"),m=rl(e,n,"SUCCESS"),m.message="Used cached module result.",m.data=JSON.parse(E),g=!0;break}else r.info({cacheKey:f,keyParams:h},"No cache result found, continuing with lock acquisition");let v=await i.acquireCacheLock({keyParams:h,clientMetadata:`hostName:${Qx()};runId:${d}`},u);if(v.acquired){p=v.keyPrefix,r.info({cacheKeyPrefixIfLockAcquired:p,cacheKey:f,keyParams:h},"Acquired cache lock and proceeding with module execution");break}else r.debug({cacheKeyPrefixIfLockAcquired:p,cacheKey:f,keyParams:h},"Failed to acquire cache lock, retrying...");await J(2500+Math.random()*1e4,u)}}try{if(!m)m=await Zx(t);else if(e.autoAuth){let f=ls.safeParse(m.data);if(!f.success)throw new A("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${f.error.message}`);r.debug("Automatically loading auth state after cached module result"),await l.loadAuthState(f.data);let S=!1,b=e.advanced?.cacheInvalidation;if(b&&b.type==="PAGE_CHECK"){let E={type:"CONTENT",value:b.substring},v=await nl({timeout:bn,assertion:E,browser:l,logger:r,signal:u,autoExpandIframes:!!l.userBrowserSettings.autoExpandIframes});v.success?r.debug({invalResult:v},"Cached result still valid after page check, continuing..."):(r.info({invalResult:v},"Invalidating cached result due to page check failure"),S=!0)}if(h&&S)return await i.deleteCacheResult(h),Jd(t)}}finally{try{p!==void 0&&!g&&m?.status==="SUCCESS"&&await eI({step:e,result:m,browser:s.browser,cacheKeyPrefix:p,logger:r,storage:i})}finally{p!==void 0&&await i.releaseCacheLock(p)}}return m},Zx=async t=>{let{step:e,tracer:n}=t.moduleParams,r=rl(e,t.moduleParams.resolvedInputs,"SUCCESS"),o=await n.startSubSteps(),{status:i,results:a}=await t.executeStepList({...t,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}});return r.results=a,r.status=i,r.finishedAt=new Date,xn({asyncTasks:t.work.asyncTasks,nestedResults:a,result:r,logger:t.fixtures.logger}),r};function rl(t,e,n){let r={};return Object.entries(e).forEach(([i,a])=>{r[i]=JSON.stringify(a)}),{type:"MODULE",id:t.id,moduleId:t.moduleId,moduleName:t.name,startedAt:new Date,cacheConfig:t.cacheConfig,inputs:r,results:[],finishedAt:new Date,status:n}}async function uS({orgId:t,step:e,context:n,logger:r,flagStore:o,codeEvalTools:i,signal:a}){let s={};try{for(let l of e.parameters??[]){let c=e.inputs?.[l]??e.defaultParameters?.[l];if(!c){r.warn(`No value or default found for parameter '${l}' that is required by module '${e.name}'`);continue}s[l]=await io({orgId:t,code:c,fragment:!0,context:n,logger:r,localTools:i,signal:a})}return s}catch(l){throw a?.throwIfAborted(),new A("UserConfigurationError",`Failed to evaluate module inputs: ${l}`)}}async function eI({step:t,result:e,browser:n,cacheKeyPrefix:r,logger:o,storage:i}){let a=t.cacheConfig?.cacheExpiryMs;(!a||a===Vg)&&(a=t.defaultCacheTtl??qg);let s;t.autoAuth?s=JSON.stringify(await n.saveAuthState()):e.data!==void 0?s=JSON.stringify(e.data):s='""',o.debug({cacheKeyPrefix:r,ttlMs:a,truncatedCacheResultJson:Id({json:s,maxJsonStringSize:1e4})},"Setting module cache result"),await i.setCacheResult({result:s,keyPrefix:r,ttlMs:a})}async function ao(t,e,n){return tI(t,e,n)}async function tI(t,e,n){let r=new Date;try{return n.throwIfAborted(),await e()}catch(o){let i=new Date,a="FAILED",s;if(n.aborted||o instanceof DOMException&&o.name==="AbortError"?(s="Step aborted by user.",a="CANCELLED"):o instanceof A?s=`${o}`:s=`An unexpected error occurred: ${o.message}`,t.type==="RESOLVED_MODULE"){let l=rl(t,{},"FAILED");return l.message=s,l.startedAt=r,l.finishedAt=i,l}return{...js(t),startedAt:r,finishedAt:i,status:a,data:null,message:s,results:[]}}}async function ai(t,e){let n=!1;try{return t&&!t.state.failureRecoveryDisabled&&(t.state.failureRecoveryDisabled=!0,n=!0),await e()}finally{t&&n&&(t.state.failureRecoveryDisabled=void 0)}}import{randomUUID as mS}from"crypto";var ol=async t=>{let{step:e,tracer:n}=t.presetParams,{logger:r,controller:o,context:i,billingReporter:a}=t.fixtures,{collectDebugData:s}=t.options,{testMetadata:l,suiteMetadata:c}=t.inputs,d=e.command.type,u=r.child({commandType:d,stepId:e.id,commandId:e.command.id}),m=Hc(e.command);t.work.asyncTasks.push(a.reportCreditsUsed(u,d,m,{testId:l?.id,testName:l?.name,suiteId:c?.id,suiteName:c?.name}));let g=o.browser.url(),p=new Date,h,f=mS(),S=mS();if(s)try{h=await o.browser.screenshot({retries:1,clearHighlights:!0,quality:75});let C=await o.browser.getRawCondensedHtml();n.attachBeforeHtmlSnapshot({logger:u,snapshotId:f,html:C})}catch(C){u.debug({err:C},"Failed to take before screenshot, continuing...")}let b,E,v,R=rs();try{let C=await o.executePresetCommand(R,n,e.command,i,l?.advanced.disableAICaching??!1);C.beforeScreenshotOverride&&(h=C.beforeScreenshotOverride),v=C.afterScreenshotOverride;let x=new Date,L=o.browser.url();E={beforeUrl:g,afterUrl:L,startedAt:p,finishedAt:x,viewport:o.browser.getViewport(),status:C.fail?"FAILED":"SUCCESS",elementInteracted:C.elementInteracted},b={...e,message:C.thoughts??"Successfully executed preset action.",beforeUrl:g,afterUrl:L,finishedAt:x,startedAt:p,status:C.fail?"FAILED":"SUCCESS",data:C.data,results:[E],details:R.details},"assertion"in e.command&&(b.message=C.thoughts||"Assertion passed.")}catch(C){u.error({message:C.message,stack:C.stack},`Failed executing preset step ${$n(e.command)}`);let x=o.browser.url(),L=new Date,k=C instanceof Error?C.message:`${C}`;E={beforeUrl:g,afterUrl:x,startedAt:p,finishedAt:L,viewport:o.browser.getViewport(),status:C instanceof DOMException&&C.name==="AbortError"?"CANCELLED":"FAILED",message:k},b={...e,startedAt:p,finishedAt:L,beforeUrl:g,afterUrl:x,status:C instanceof DOMException&&C.name==="AbortError"?"CANCELLED":"FAILED",message:k,failureReason:C instanceof A?C.reason:void 0,results:[E],details:R.details}}if(s)try{v||(v=await o.browser.screenshot({retries:1,quality:75}));let C=await o.browser.getRawCondensedHtml();n.attachAfterHtmlSnapshot({logger:u,snapshotId:S,html:C})}catch(C){u.debug({err:C},"Failed store debug data after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return E.beforeSnapshot=f,b.beforeSnapshot=f,E.afterSnapshot=S,b.afterSnapshot=S,h&&n.attachBeforeScreenshot({logger:u,snapshotId:f,screenshot:h}),v&&n.attachAfterScreenshot({logger:u,snapshotId:S,screenshot:v}),b};async function pS({codePath:t,screenshotBuff:e,storage:n,logger:r}){if(e)try{let o=await n.uploadScreenshot(e);return r.info({screenshotUrl:o,codePath:t},"Saved screenshot for debugging"),o}catch(o){r.error({err:o,codePath:t},"Failed to save screenshot for debugging")}}async function Pn({frameConfig:t,action:e,browser:n}){let r=n.getActiveFrameConfig();t?n.setActiveFrameConfig(t):r?.type==="auto"&&n.setActiveFrameConfig(void 0);try{return await e()}finally{n.setActiveFrameConfig(r)}}var nI=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function gS({beforeUrl:t,beforePages:e,browser:n,command:r,logger:o}){if(nI.includes(r.type))return;let s=("cache"in r&&r.cache&&"target"in r.cache?r.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,l=Date.now(),c=0;for(;c===0||Date.now()-l<s;){await J(250),c++;let d=(await n.getOpenPages()).map(m=>m.url),u=n.url();if(d.length!==e.length)for(let m=d.length-1;m>=e.length;m--){let g=d[m];if(Zr(g,o)&&g!==t&&g!==u){o.info({beforePages:e,afterPages:d,beforeUrl:t},"Auto-following new tab after preset action"),await n.switchToPage({type:"INDEX",index:String(m)});break}}}}var hS="MOMENTIC_RUN_ID",fS="FINAL_SCREENSHOT_URL";import{cloneDeep as pI}from"lodash-es";async function SS(t){let{step:e,tracer:n}=t.conditionalParams,{logger:r,controller:o}=t.fixtures,i=new Date,a=js(e),s=e.elseSteps,l=!0,c=[],d,u=rs();for(let f=0;f<e.blocks.length;f++){r.info(`Evaluating condition ${f} in conditional step`);let S=e.blocks[f];try{let b=await ol({...t,presetParams:{tracer:n,step:S.assertion}});c.push(b),r.info(`Condition ${f} resolved to true, executing the corresponding ${S.steps.length} steps`),l=!1,s=S.steps,d=b}catch(b){r.info({err:b},`Condition ${f} resolved to false`)}finally{o.throwIfClosed()}}if(s)l&&r.info("No conditions resolved to true, executing the else block steps");else return r.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped"),{...a,status:"SUCCESS",startedAt:i,data:c[c.length-1]?.data,message:c[c.length-1]?.message,results:[],finishedAt:new Date,details:u.details};r.info(`Executing ${s.length} steps in the selected conditional block`);let m=await t.conditionalParams.tracer.startSubSteps(),g=await t.executeStepList({...t,listParams:{steps:s,containerName:"conditional block",tracer:m}}),h={...a,assertionResult:d,...g,startedAt:i,finishedAt:new Date};return xn({asyncTasks:t.work.asyncTasks,nestedResults:[...c,...g.results],result:h,logger:r}),h}import{randomUUID as yS}from"crypto";var bS=async t=>{let{tracer:e}=t.aiStepParams,{controller:n,logger:r}=t.fixtures;await n.browser.waitForDOMStability();let o=await n.browser.screenshot({}),i=await rI(t);i.finishedAt=new Date,xn({asyncTasks:t.work.asyncTasks,result:i,nestedResults:i.results,logger:t.fixtures.logger});let a=await n.browser.screenshot({}),s=yS();i.beforeSnapshot=s,e.attachBeforeScreenshot({logger:r,snapshotId:s,screenshot:o});let l=yS();return i.afterSnapshot=l,e.attachAfterScreenshot({logger:r,snapshotId:l,screenshot:a}),i},rI=async t=>{let{step:e,tracer:n}=t.aiStepParams,{controller:r,context:o,logger:i}=t.fixtures,a={...e,startedAt:new Date,beforeTestContext:o.toRedactedDisplayCopy(),finishedAt:new Date,results:[],status:"SUCCESS"};if(!("steps"in e&&e.steps&&e.steps.length>0&&e.steps[e.steps.length-1]?.command.type==="SUCCESS"))throw new A("UserConfigurationError","AI action has been fully deprecated. Please delete this step and transition to Dynamic AI Action.");try{let l=await n.startSubSteps(),{status:c}=await t.executeStepList({...t,listParams:{steps:e.steps,containerName:"AI action",results:a.results,tracer:l}});return a.finishedAt=new Date,a.status=c,a}catch(l){i.warn({err:l},"Failed executing saved deprecated AI action steps");let c=r.executeAbortController.signal.aborted;a.message=l instanceof Error?l.message:`${l}`,a.status=c?"CANCELLED":"FAILED"}return a};import{randomUUID as Qd}from"crypto";var TS=15,oI=7,wS=async t=>{let{tracer:e}=t.aiStepParams,{logger:n,controller:r}=t.fixtures;await r.browser.waitForDOMStability();let o=await r.browser.screenshot({quality:75}),i=await iI(t);i.finishedAt=new Date,xn({asyncTasks:t.work.asyncTasks,result:i,nestedResults:i.results,logger:t.fixtures.logger});let a=await r.browser.screenshot({quality:75}),s=Qd();i.beforeSnapshot=s,e.attachBeforeScreenshot({logger:n,snapshotId:s,screenshot:o});let l=Qd();return i.afterSnapshot=l,e.attachAfterScreenshot({logger:n,snapshotId:l,screenshot:a}),i},iI=async t=>{let{step:e,tracer:n}=t.aiStepParams,{testMetadata:r,orgId:o}=t.inputs,{controller:i,context:a,logger:s,codeEvalTools:l}=t.fixtures,{step:c}=t.callbacks,d=`${e.id}-${Date.now()}`,u=s.child({stepId:e.id,langfuseSessionId:d}),m={...e,startedAt:new Date,beforeTestContext:a.toRedactedDisplayCopy(),results:[],finishedAt:new Date,status:"SUCCESS"},g=await $t({orgId:o,s:e.text,context:a,logger:u,localTools:l});await i.browser.waitForDOMStability({logger:u});let h=`data:image/jpeg;base64,${(await i.browser.screenshot({clearHighlights:!0,retries:2})).toString("base64")}`,f=[],S=0,b=0,E,v;for(;;){if(S>TS)return m.message=`Exceeded the maximum number of commands allowed per AI step (${TS})`,m.status="FAILED",m;if(i.executeAbortController.signal.aborted)return m.message="Test execution was cancelled",m.status="CANCELLED",m;c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Evaluating current state..."});let R=await i.evaluateAiAction({goal:g,startingScreenshot:S===0?void 0:h,history:f,logger:u,langfuseSessionId:d,lastError:v}),{evaluation:C,reasoning:x,summary:L}=R;u.info(R,"Got AI evaluation");let k=m.results[S-1]?.id;switch(C.type){case"DONE":return m.message=`Our AI evaluator confirmed all tasks are complete: ${x}`,m.status="SUCCESS",k&&c.onDynamicAIActionEvaluatingEvent?.({stepId:k,status:"SUCCESS",message:`${L}
33
- ${x}`}),m;case"RIGHT_TRACK":{E=void 0,S===0?c.onDynamicAIActionEvaluatingEvent?.({stepId:e.id,status:"RUNNING",message:x}):k&&c.onDynamicAIActionEvaluatingEvent?.({stepId:k,status:"SUCCESS",message:x});break}case"WRONG_TRACK":{if(E=`${x}
34
- ${C.feedback}`,b++,b>=oI)return m.message=`Our AI agent requires additional information to achieve this goal:
32
+ ${t.code}`;throw t.logger.error({err:e.error,code:t.code,env:t.context.toObjectCopy()},n),new Error(n)}if(e.variableUpdates)for(let[n,r]of Object.entries(e.variableUpdates))t.context.setVariable(n,r);if(e.persistentVariableUpdates&&Object.keys(e.persistentVariableUpdates).length>0){await t.callbacks?.onPersistentVariableUpdates?.(e.persistentVariableUpdates);for(let[n,r]of Object.entries(e.persistentVariableUpdates))t.context.setVariable(n,r)}return e.result}import{set as oI}from"lodash-es";async function jt(t){let{orgId:e,s:n,context:r,logger:o,signal:a,retries:i=2,timeoutMs:s=cr,allowUndefined:l=!1}=t,c=/{{(.*?)}}/g,d=n.matchAll(c),u=n;for(let m of d){if(m.length<2)continue;let p=m[1].trim(),g;try{g=await yr({orgId:e,code:p,fragment:!0,context:r,timeoutMs:s,logger:o,retries:i,localTools:t.localTools,signal:a})}catch(f){throw o.error({err:f,value:n},"Error evaluating template string"),f}if(g===void 0&&!l)throw new A("UserConfigurationError",`Template fragment '${p}' 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 g=="string"?g:`${g}`;h=h.replaceAll(/\$/g,"$$$$"),u=u.replace(m[0],h)}return u}async function ll(t){return mS(t)}async function mS({obj:t,bannedKeys:e,allowList:n,context:r,prefixPath:o=[],replacements:a=[],...i}){for(let s in t){if(e.includes(s))continue;let l=!1;if(n)if(n.includes(s))l=!0;else continue;let c=t[s],d=[...o,s];if(typeof c=="string"&&c.includes("{{")){let u=await jt({s:c,context:r,...i});if(c===u)continue;a.push({path:d,original:c}),t[s]=u}else typeof c=="object"&&c!==null&&!Array.isArray(c)&&await mS({obj:c,bannedKeys:e,context:r,prefixPath:d,replacements:a,allowList:l?void 0:n,...i})}return a}function pS(t,e){for(let{path:n,original:r}of e)oI(t,n,r)}import aI from"fetch-retry";var L6=process.env.MAILINATOR_API_KEY,O6=aI(global.fetch,{retryOn:function(t,e,n){return t>3?!1:!!(e!==null||n&&n.status>=400)},retryDelay:function(t){return 500}});import{hostname as mI}from"os";async function gS(t){let{command:e,tracer:n,timeoutMs:r,targetingWrapper:o,disableCache:a,fixtures:i}=t,{logger:s,abortSignal:l}=i;if(e.target&&!rr(e.target))throw new Error("Element assertion with x/y is not supported yet");let c=sI(e.assertion),d=xm(e.cache)?e.cache:void 0,u=Date.now(),m=0,p,g=500;for(;m<2||Date.now()-u<r;){m++,m>1&&await J(g,l),l?.throwIfAborted();try{let{elementInteractedDisplayString:h,result:f}=await o({ctx:i.ctx,tracer:n,command:e,target:e.target,cache:d?.target,action:async y=>iI(y.locator,t),options:{...e,disableCache:a,disableGlobalLocatorRedirect:!0,source:Hr(e),allowZeroOpacityOverride:!0,targetName:"target"}});if(p={success:f.success,data:f.data,err:f.err,elementInteractedDisplayString:h},!f.success){p=f,g=Math.min(g*2,1e4);continue}return p}catch(h){if(l?.throwIfAborted(),c)return{success:!0,thoughts:`The element described does not exist on the page: ${h.message}`};if(s.warn({err:h},"Element assertion ended in error, retrying..."),!(h instanceof A)||h.reason!="ActionFailureError")throw h;p={success:!1,err:h}}}if(!p)throw new Error(`Failed to evaluate manual element assertion in ${r}ms.`);return p}async function iI(t,{command:e,fixtures:n}){let r=e.assertion;await n.browser.highlight(t);let o=!0,a,i;switch(r.type){case"ELEMENT_CONTENT":{let l=await t.textContent()??"";if(i={elementTextContent:$e(l,500,!0)},!cl(l,r.value,r.operation,!!r.negated)){let c=r.negated?tn[r.operation]:nn[r.operation];o=!1,a=new A("AssertionFailureError",`The content ${c} '${r.value}': ${l}`)}break}case"ELEMENT_ATTRIBUTE":{i={elementOuterHtml:$e(await t.evaluate(c=>c.cloneNode(!1).outerHTML),500,!0)};let l;try{l=await t.getAttribute(r.attr,{timeout:3e3})??""}catch(c){a=new A("AssertionFailureError",`The element does not have an attribute named ${r.attr}: ${c}`),o=!1;break}if(!cl(l,r.value,r.operation,!!r.negated)){let c=r.negated?tn[r.operation]:nn[r.operation];o=!1,r.operation==="EXISTS"?a=new A("AssertionFailureError",`The attribute ${r.attr} ${c}`):a=new A("AssertionFailureError",`The attribute ${r.attr} ${c} '${r.value}': ${l}`)}break}case"ELEMENT_EXISTENCE":{switch(r.condition){case"VISIBLE":{o=await t.evaluate(async(c,d)=>{let u=Date.now();for(;Date.now()-u<d;){await new Promise(p=>setTimeout(p,250));let m=c.getBoundingClientRect();if(!(m.width===0||m.height===0)&&window.getComputedStyle(c).visibility!=="hidden"&&window.getComputedStyle(c).display!=="none")return!0}return!1},Tn*1e3);break}case"EDITABLE":{o=await t.isEditable({timeout:Tn*1e3});break}case"EXISTS":{o=!0;break}case"ENABLED":{o=await t.isEnabled({timeout:Tn*1e3});break}case"FOCUSED":{o=await t.evaluate(c=>c===document.activeElement);break}default:return(c=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.condition)}if(o=r.negated?!o:o,!o){let l=r.negated?Ld[r.condition]:Od[r.condition];a=new A("AssertionFailureError",`The element ${l}`)}break}case"ELEMENT_NAME":{let l=await t.evaluate(c=>c.tagName);if(!cl(l,r.value,r.operation,!!r.negated)){let c=r.negated?tn[r.operation]:nn[r.operation];o=!1,a=new A("AssertionFailureError",`The element tag name ${c} '${r.value}': ${l}`)}break}case"ELEMENT_STYLE":{let l=await t.evaluate((c,d)=>window.getComputedStyle(c).getPropertyValue(d),r.property);if(!cl(l,r.value,r.operation,!!r.negated)){let c=r.negated?tn[r.operation]:nn[r.operation];o=!1,r.operation==="EXISTS"?a=new A("AssertionFailureError",`The style property ${r.property} ${c}`):a=new A("AssertionFailureError",`The style property ${r.property} ${c} '${r.value}': ${l}`)}break}default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return{success:o,data:i,err:a}}function cl(t,e,n,r){let o;switch(n){case"CONTAINS":{o=t.includes(e);break}case"EQUALS":{o=t.trim()===e.trim();break}case"STARTS_WITH":{o=t.trim().startsWith(e);break}case"EXISTS":{o=t.trim().length>0;break}default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}return r?!o:o}function sI(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&(t.condition==="EXISTS"||t.condition==="VISIBLE")}function hS(t){return t.type==="ELEMENT_EXISTENCE"&&t.negated&&t.condition==="EXISTS"}import{Jimp as lI}from"jimp";async function hi(t,e){let n=await t.screenshot(e),r=await lI.fromBuffer(n);return{buffer:n,width:Math.ceil(r.bitmap.width??0),height:Math.ceil(r.bitmap.height??0)}}import{Jimp as fS}from"jimp";import ru from"jpeg-js";import cI from"pixelmatch";async function SS({ctx:t,tracer:e,command:n,disableCache:r,browser:o,targetingWrapper:a,logger:i,screenshotStorage:s}){if(n.target&&!rr(n.target))throw new Error("Visual Diff with x/y is not supported yet");await o.waitForDOMStability({logger:i});let l={clearHighlights:!0,hideCaret:!0},c;n.target?.elementDescriptor?c=(await a({ctx:t,tracer:e,command:n,target:n.target,cache:n.cache?.target,action:async K=>hi(o,{locator:K.locator,...l}),options:{...n,disableCache:r,disableGlobalLocatorRedirect:!0,targetName:"target"}})).result:c=await hi(o,l);let d=await s.prepareGoldenScreenshotForComparison(i,n,c);if((c.height!==d.height||c.width!==d.width)&&i.warn({currHeight:c.height,currWidth:c.width,savedHeight:d.height,savedWidth:d.width},"Mismatched before and after visual diff screenshot sizes"),Math.abs(c.height-d.height)>10||Math.abs(c.width-d.width)>10){let _=`${c.width}x${c.height}`,K=`${d.width}x${d.height}`;return{fail:!0,thoughts:`Current screenshot (${_}) does not match saved screenshot dimensions (${K}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:d.buffer,afterScreenshotOverride:c.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let u=await fS.fromBuffer(c.buffer),m={width:c.width,height:c.height},p=await fS.fromBuffer(d.buffer),g={width:d.width,height:d.height},h,f=m.width*m.height,y=g.width*g.height,b=Math.abs(m.height-g.height),w=Math.abs(m.width-g.width);if(f>y){let _=u.cover({w:g.width,h:g.height});c.buffer=await _.getBuffer("image/jpeg"),h="current",c.width=g.width,c.height=g.height}else if(y>f){let _=p.cover({w:m.width,h:m.height});d.buffer=await _.getBuffer("image/jpeg"),h="saved"}let C={data:Buffer.alloc(c.width*c.height*4),width:c.width,height:c.height},v=n.threshold??.1,x=cI(ru.decode(d.buffer).data,ru.decode(c.buffer).data,C.data,c.width,c.height,{threshold:v,diffColorAlt:[0,255,0]})/(c.width*c.height)*100,M=x>v*100,D=`Visual diff of ${x.toFixed(2)}% detected, which is ${M?"over":"under"} the threshold of ${v*100}%.`;if(h&&(D+=` The ${h} screenshot was cropped since it was taller by ${b} pixels and wider by ${w} pixels.`),M)throw new A("ActionFailureError",D);return{fail:M,thoughts:D,beforeScreenshotOverride:c.buffer,afterScreenshotOverride:ru.encode(C,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}var dI=3e4;async function yS({command:t,logger:e,baseUrl:n,fetchImplementation:r=fetch}){let o=t.timeout??dI/1e3,a=Object.fromEntries(Object.entries(t.headers||{}).filter(([p,g])=>p&&g)),i=new URLSearchParams;Object.entries(t.params||{}).filter(([p,g])=>p&&g).forEach(([p,g])=>{i.append(p,g)});let s=i.toString(),l;if(Zo(t.url)&&(l=t.url),n&&ea(t.url,n)&&(l=new URL(t.url,n).toString()),!l)throw new A("ActionFailureError",`Invalid URL: ${t.url}`);e.info({url:l,searchParams:s,headers:a,body:t.body,method:t.method},"Making HTTP request");let d=await H((async()=>{let p=s?`${l}?${s}`:l;try{return await r(p,{headers:a,method:t.method,body:t.body})}catch(g){throw e.error({err:g},"Failed to make HTTP request"),new Error(`Failed to make HTTP request: ${g}`)}})(),{milliseconds:o*1e3,fallback:()=>{throw new A("ActionFailureError",`Fetch request timed out after ${o} seconds`)}});if(!d.ok){let p;try{p=await d.text()}catch(g){p=`Failed to read response body: ${g}`}throw new A("ActionFailureError",`Fetch request failed with status ${d.status}: ${p}`)}let u={};d.headers.forEach((p,g)=>{u[g]=p});let m={status:d.status,headers:u};if(d.headers.get("content-type")?.includes("json"))try{m.json=await d.json()}catch{}else d.headers.get("content-type")?.includes("text")&&(m.text=await d.text());return m}var uI=5e3;async function dl({timeout:t=Tn,...e}){let n=Date.now(),r=t*1e3,o=r+1e4,a,i=0,s=500;for(;i-n<r;){if(Date.now()-n>o){e.logger.warn("Exceeded max system timeout for page assertion, exiting...");break}e.signal.throwIfAborted();let l=Date.now();a=await bS(e),i=Date.now();let c=i-l;if(c>1e3&&e.logger.warn({pageAssertDuration:c},"Page assertion took longer than expected"),!a.success)await J(s,e.signal),s=Math.min(Math.floor(s*1.5),uI);else return a}return a=await bS(e),a}async function bS({assertion:t,browser:e,autoExpandIframes:n}){switch(t.type){case"CONTENT":{let o,a=!1,i;try{let s;if(n){let l=await e.evaluateFunctionInAllFrames(TS,{value:t.value,negated:!!t.negated,returnHtml:!1});a=t.negated?l.every(c=>c.evaluation):l.some(c=>c.evaluation),s=l.find(c=>c.pageHtml)?.pageHtml}else({evaluation:a,pageHtml:s}=await e.evaluateFunctionInPage(TS,{value:t.value,negated:!!t.negated,returnHtml:!0},"checking page content"));if(!a){let l=t.negated?tn.CONTAINS:nn.CONTAINS;i=new A("AssertionFailureError",`The page ${l} '${t.value}'.`),o=s}}catch(s){i=new A("AssertionFailureError",`Failed to evaluate page content assertion: ${s instanceof Error?s.message:`${s}`}`)}return{success:a,err:i,data:a||!o?void 0:{pageContent:o}}}default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t.type)}}function TS({value:t,negated:e,returnHtml:n}){let r=document.documentElement.outerHTML,o=r.includes(t)===!e;return r.length>1e4&&(r=r.slice(0,1e4)+"...TRUNCATED"),{evaluation:o,pageHtml:!o&&n?r:void 0}}var ou=async t=>{let{step:e,resolvedInputs:n}=t.moduleParams,{logger:r,context:o,storage:a,codeEvalTools:i,controller:s}=t.fixtures,l=s.browser,{orgId:c,runId:d}=t.inputs,u=s.executeAbortController.signal;Object.keys(n).length>0&&(o.setInputs(n),r.info(_d({json:{inputs:n,moduleId:e.moduleId},maxJsonStringSize:1e3}),"Set module inputs"));let m,p=!1,g,h;if(e.cacheConfig||e.defaultCacheAllInvocations){let f=e.cacheConfig?.cacheKey||e.defaultCacheKey||"",y=await jt({orgId:c,s:f,context:o,logger:r,localTools:i,signal:u});h={orgId:c,cacheKeys:[y,...Object.entries(n).map(([w,C])=>`${w}:${C}`)]},r.info({original:f,keyParams:h},"Module cache key params");let b=Date.now();for(;Date.now()-b<wg;){u?.throwIfAborted();let w=await a.getCacheResult(h);if(w){r.info({cacheResult:$e(w,1e3,!0)},"Got result from module execution cache"),m=ul(e,n,"SUCCESS"),m.message="Used cached module result.",m.data=JSON.parse(w),p=!0;break}else r.info({cacheKey:f,keyParams:h},"No cache result found, continuing with lock acquisition");let C=await a.acquireCacheLock({keyParams:h,clientMetadata:`hostName:${mI()};runId:${d}`},u);if(C.acquired){g=C.keyPrefix,r.info({cacheKeyPrefixIfLockAcquired:g,cacheKey:f,keyParams:h},"Acquired cache lock and proceeding with module execution");break}else r.debug({cacheKeyPrefixIfLockAcquired:g,cacheKey:f,keyParams:h},"Failed to acquire cache lock, retrying...");await J(2500+Math.random()*1e4,u)}}try{if(!m)m=await pI(t);else if(e.autoAuth){let f=us.safeParse(m.data);if(!f.success)throw new A("UserConfigurationError",`Cached authentication module result is not a valid storage state: ${f.error.message}`);r.debug("Automatically loading auth state after cached module result"),await l.loadAuthState(f.data);let y=!1,b=e.advanced?.cacheInvalidation;if(b&&b.type==="PAGE_CHECK"){let w={type:"CONTENT",value:b.substring},C=await dl({timeout:Tn,assertion:w,browser:l,logger:r,signal:u,autoExpandIframes:!!l.userBrowserSettings.autoExpandIframes});C.success?r.debug({invalResult:C},"Cached result still valid after page check, continuing..."):(r.info({invalResult:C},"Invalidating cached result due to page check failure"),y=!0)}if(h&&y)return await a.deleteCacheResult(h),ou(t)}}finally{try{g!==void 0&&!p&&m?.status==="SUCCESS"&&await gI({step:e,result:m,browser:s.browser,cacheKeyPrefix:g,logger:r,storage:a})}finally{g!==void 0&&await a.releaseCacheLock(g)}}return m},pI=async t=>{let{step:e,tracer:n}=t.moduleParams,r=ul(e,t.moduleParams.resolvedInputs,"SUCCESS"),o=await n.startSubSteps(),{status:a,results:i}=await t.executeStepList({...t,listParams:{steps:e.steps,containerName:`module ('${e.name}')`,tracer:o}});return r.results=i,r.status=a,r.finishedAt=new Date,In({asyncTasks:t.work.asyncTasks,nestedResults:i,result:r,logger:t.fixtures.logger}),r};function ul(t,e,n){let r={};return Object.entries(e).forEach(([a,i])=>{r[a]=JSON.stringify(i)}),{type:"MODULE",id:t.id,moduleId:t.moduleId,moduleName:t.name,startedAt:new Date,cacheConfig:t.cacheConfig,inputs:r,results:[],finishedAt:new Date,status:n}}async function wS({orgId:t,step:e,context:n,logger:r,flagStore:o,codeEvalTools:a,signal:i}){let s={};try{for(let l of e.parameters??[]){let c=e.inputs?.[l]??e.defaultParameters?.[l];if(!c){r.warn(`No value or default found for parameter '${l}' that is required by module '${e.name}'`);continue}s[l]=await yr({orgId:t,code:c,fragment:!0,context:n,logger:r,localTools:a,signal:i})}return s}catch(l){throw i?.throwIfAborted(),new A("UserConfigurationError",`Failed to evaluate module inputs: ${l}`)}}async function gI({step:t,result:e,browser:n,cacheKeyPrefix:r,logger:o,storage:a}){let i=t.cacheConfig?.cacheExpiryMs;(!i||i===nh)&&(i=t.defaultCacheTtl??rh);let s;t.autoAuth?s=JSON.stringify(await n.saveAuthState()):e.data!==void 0?s=JSON.stringify(e.data):s='""',o.debug({cacheKeyPrefix:r,ttlMs:i,truncatedCacheResultJson:_d({json:s,maxJsonStringSize:1e4})},"Setting module cache result"),await a.setCacheResult({result:s,keyPrefix:r,ttlMs:i})}async function lo(t,e,n){return hI(t,e,n)}async function hI(t,e,n){let r=new Date;try{return n.throwIfAborted(),await e()}catch(o){let a=new Date,i="FAILED",s;if(n.aborted||o instanceof DOMException&&o.name==="AbortError"?(s="Step aborted by user.",i="CANCELLED"):o instanceof A?s=`${o}`:s=`An unexpected error occurred: ${o.message}`,t.type==="RESOLVED_MODULE"){let l=ul(t,{},"FAILED");return l.message=s,l.startedAt=r,l.finishedAt=a,l}return{...Xs(t),startedAt:r,finishedAt:a,status:i,data:null,message:s,results:[]}}}async function la(t,e){let n=!1;try{return t&&!t.state.failureRecoveryDisabled&&(t.state.failureRecoveryDisabled=!0,n=!0),await e()}finally{t&&n&&(t.state.failureRecoveryDisabled=void 0)}}import{randomUUID as ES}from"crypto";var ml=async t=>{let{step:e,tracer:n}=t.presetParams,{logger:r,controller:o,context:a,billingReporter:i}=t.fixtures,{collectDebugData:s}=t.options,{testMetadata:l,suiteMetadata:c}=t.inputs,d=e.command.type,u=r.child({commandType:d,stepId:e.id,commandId:e.command.id}),m=Kc(e.command);t.work.asyncTasks.push(i.reportCreditsUsed(u,d,m,{testId:l?.id,testName:l?.name,suiteId:c?.id,suiteName:c?.name}));let p=o.browser.url(),g=new Date,h,f=ES(),y=ES();if(s)try{if(h=await o.browser.screenshot({retries:1,clearHighlights:!0,quality:75}),!o.browser.userBrowserSettings.disableHtmlSnapshots){let R=await o.browser.getRawCondensedHtml();n.attachBeforeHtmlSnapshot({logger:u,snapshotId:f,html:R})}}catch(R){u.debug({err:R},"Failed to take before screenshot, continuing...")}let b,w,C,v=is();try{let R=await o.executePresetCommand(v,n,e.command,a,l?.advanced.disableAICaching??!1);R.beforeScreenshotOverride&&(h=R.beforeScreenshotOverride),C=R.afterScreenshotOverride;let x=new Date,M=o.browser.url();w={beforeUrl:p,afterUrl:M,startedAt:g,finishedAt:x,viewport:o.browser.getViewport(),status:R.fail?"FAILED":"SUCCESS",elementInteracted:R.elementInteracted},b={...e,message:R.thoughts??"Successfully executed preset action.",beforeUrl:p,afterUrl:M,finishedAt:x,startedAt:g,status:R.fail?"FAILED":"SUCCESS",data:R.data,results:[w],details:v.details},"assertion"in e.command&&(b.message=R.thoughts||"Assertion passed.")}catch(R){u.error({message:R.message,stack:R.stack},`Failed executing preset step ${jn(e.command)}`);let x=o.browser.url(),M=new Date,D=R instanceof Error?R.message:`${R}`;w={beforeUrl:p,afterUrl:x,startedAt:g,finishedAt:M,viewport:o.browser.getViewport(),status:R instanceof DOMException&&R.name==="AbortError"?"CANCELLED":"FAILED",message:D},b={...e,startedAt:g,finishedAt:M,beforeUrl:p,afterUrl:x,status:R instanceof DOMException&&R.name==="AbortError"?"CANCELLED":"FAILED",message:D,failureReason:R instanceof A?R.reason:void 0,results:[w],details:v.details}}if(s)try{if(C||(C=await o.browser.screenshot({retries:1,quality:75})),!o.browser.userBrowserSettings.disableHtmlSnapshots){let R=await o.browser.getRawCondensedHtml();n.attachAfterHtmlSnapshot({logger:u,snapshotId:y,html:R})}}catch(R){u.debug({err:R},"Failed to store debug data after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return w.beforeSnapshot=f,b.beforeSnapshot=f,w.afterSnapshot=y,b.afterSnapshot=y,h&&n.attachBeforeScreenshot({logger:u,snapshotId:f,screenshot:h}),C&&n.attachAfterScreenshot({logger:u,snapshotId:y,screenshot:C}),b};async function RS({codePath:t,screenshotBuff:e,storage:n,logger:r}){if(e)try{let o=await n.uploadScreenshot(e);return r.info({screenshotUrl:o,codePath:t},"Saved screenshot for debugging"),o}catch(o){r.error({err:o,codePath:t},"Failed to save screenshot for debugging")}}async function Mn({frameConfig:t,action:e,browser:n}){let r=n.getActiveFrameConfig();t?n.setActiveFrameConfig(t):r?.type==="auto"&&n.setActiveFrameConfig(void 0);try{return await e()}finally{n.setActiveFrameConfig(r)}}var fI=["NAVIGATE","NEW_TAB","TAB","REFRESH","WAIT_FOR_URL"];async function CS({beforeUrl:t,beforePages:e,browser:n,command:r,logger:o}){if(fI.includes(r.type))return;let s=("cache"in r&&r.cache&&"target"in r.cache?r.cache.target:void 0)?.nodeOnlySerializedHtml?.includes("<a")??!1?300:3e3,l=Date.now(),c=0;for(;c===0||Date.now()-l<s;){await J(250),c++;let d=(await n.getOpenPages()).map(m=>m.url),u=n.url();if(d.length!==e.length)for(let m=d.length-1;m>=e.length;m--){let p=d[m];if(no(p,o)&&p!==t&&p!==u){o.info({beforePages:e,afterPages:d,beforeUrl:t},"Auto-following new tab after preset action"),await n.switchToPage({type:"INDEX",index:String(m)});break}}}}var vS="MOMENTIC_RUN_ID",AS="FINAL_SCREENSHOT_URL";import{cloneDeep as xI}from"lodash-es";async function xS(t){let{step:e,tracer:n}=t.conditionalParams,{logger:r,controller:o}=t.fixtures,a=new Date,i=Xs(e),s=e.elseSteps,l=!0,c=[],d,u=is();for(let f=0;f<e.blocks.length;f++){r.info(`Evaluating condition ${f} in conditional step`);let y=e.blocks[f];try{let b=await ml({...t,presetParams:{tracer:n,step:y.assertion}});c.push(b),r.info(`Condition ${f} resolved to true, executing the corresponding ${y.steps.length} steps`),l=!1,s=y.steps,d=b}catch(b){r.info({err:b},`Condition ${f} resolved to false`)}finally{o.throwIfClosed()}}if(s)l&&r.info("No conditions resolved to true, executing the else block steps");else return r.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped"),{...i,status:"SUCCESS",startedAt:a,data:c[c.length-1]?.data,message:c[c.length-1]?.message,results:[],finishedAt:new Date,details:u.details};r.info(`Executing ${s.length} steps in the selected conditional block`);let m=await t.conditionalParams.tracer.startSubSteps(),p=await t.executeStepList({...t,listParams:{steps:s,containerName:"conditional block",tracer:m}}),h={...i,assertionResult:d,...p,startedAt:a,finishedAt:new Date};return In({asyncTasks:t.work.asyncTasks,nestedResults:[...c,...p.results],result:h,logger:r}),h}import{randomUUID as IS}from"crypto";var PS=async t=>{let{tracer:e}=t.aiStepParams,{controller:n,logger:r}=t.fixtures;await n.browser.waitForDOMStability();let o=await n.browser.screenshot({}),a=await SI(t);a.finishedAt=new Date,In({asyncTasks:t.work.asyncTasks,result:a,nestedResults:a.results,logger:t.fixtures.logger});let i=await n.browser.screenshot({}),s=IS();a.beforeSnapshot=s,e.attachBeforeScreenshot({logger:r,snapshotId:s,screenshot:o});let l=IS();return a.afterSnapshot=l,e.attachAfterScreenshot({logger:r,snapshotId:l,screenshot:i}),a},SI=async t=>{let{step:e,tracer:n}=t.aiStepParams,{controller:r,context:o,logger:a}=t.fixtures,i={...e,startedAt:new Date,beforeTestContext:o.toRedactedDisplayCopy(),finishedAt:new Date,results:[],status:"SUCCESS"};if(!("steps"in e&&e.steps&&e.steps.length>0&&e.steps[e.steps.length-1]?.command.type==="SUCCESS"))throw new A("UserConfigurationError","AI action has been fully deprecated. Please delete this step and transition to Dynamic AI Action.");try{let l=await n.startSubSteps(),{status:c}=await t.executeStepList({...t,listParams:{steps:e.steps,containerName:"AI action",results:i.results,tracer:l}});return i.finishedAt=new Date,i.status=c,i}catch(l){a.warn({err:l},"Failed executing saved deprecated AI action steps");let c=r.executeAbortController.signal.aborted;i.message=l instanceof Error?l.message:`${l}`,i.status=c?"CANCELLED":"FAILED"}return i};import{randomUUID as au}from"crypto";var MS=15,yI=7,LS=async t=>{let{tracer:e}=t.aiStepParams,{logger:n,controller:r}=t.fixtures;await r.browser.waitForDOMStability();let o=await r.browser.screenshot({quality:75}),a=await bI(t);a.finishedAt=new Date,In({asyncTasks:t.work.asyncTasks,result:a,nestedResults:a.results,logger:t.fixtures.logger});let i=await r.browser.screenshot({quality:75}),s=au();a.beforeSnapshot=s,e.attachBeforeScreenshot({logger:n,snapshotId:s,screenshot:o});let l=au();return a.afterSnapshot=l,e.attachAfterScreenshot({logger:n,snapshotId:l,screenshot:i}),a},bI=async t=>{let{step:e,tracer:n}=t.aiStepParams,{testMetadata:r,orgId:o}=t.inputs,{controller:a,context:i,logger:s,codeEvalTools:l}=t.fixtures,{step:c}=t.callbacks,d=`${e.id}-${Date.now()}`,u=s.child({stepId:e.id,langfuseSessionId:d}),m={...e,startedAt:new Date,beforeTestContext:i.toRedactedDisplayCopy(),results:[],finishedAt:new Date,status:"SUCCESS"},p=await jt({orgId:o,s:e.text,context:i,logger:u,localTools:l});await a.browser.waitForDOMStability({logger:u});let h=`data:image/jpeg;base64,${(await a.browser.screenshot({clearHighlights:!0,retries:2})).toString("base64")}`,f=[],y=0,b=0,w,C;for(;;){if(y>MS)return m.message=`Exceeded the maximum number of commands allowed per AI step (${MS})`,m.status="FAILED",m;if(a.executeAbortController.signal.aborted)return m.message="Test execution was cancelled",m.status="CANCELLED",m;c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Evaluating current state..."});let v=await a.evaluateAiAction({goal:p,startingScreenshot:y===0?void 0:h,history:f,logger:u,langfuseSessionId:d,lastError:C}),{evaluation:R,reasoning:x,summary:M}=v;u.info(v,"Got AI evaluation");let D=m.results[y-1]?.id;switch(R.type){case"DONE":return m.message=`Our AI evaluator confirmed all tasks are complete: ${x}`,m.status="SUCCESS",D&&c.onDynamicAIActionEvaluatingEvent?.({stepId:D,status:"SUCCESS",message:`${M}
33
+ ${x}`}),m;case"RIGHT_TRACK":{w=void 0,y===0?c.onDynamicAIActionEvaluatingEvent?.({stepId:e.id,status:"RUNNING",message:x}):D&&c.onDynamicAIActionEvaluatingEvent?.({stepId:D,status:"SUCCESS",message:x});break}case"WRONG_TRACK":{if(w=`${x}
34
+ ${R.feedback}`,b++,b>=yI)return m.message=`Our AI agent requires additional information to achieve this goal:
35
35
  ${x}
36
- ${C.feedback}`,m.status="FAILED",c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,status:"FAILED",message:m.message}),m;k&&c.onDynamicAIActionEvaluatingEvent?.({stepId:k,status:"FAILED",message:C.feedback});break}case"IMPOSSIBLE":return m.message=`Our AI evaluator determined this task cannot be achieved: ${x}`,m.status="FAILED",c.onDynamicAIActionEvaluatingEvent?.({stepId:k??e.id,status:"FAILED",message:m.message}),m}let N=setTimeout(()=>{c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Deciding what to do next..."})},1500);u.info({commandIndex:S,lastActionHint:E},`Generating new sub-command ${S} within AI action`);let V,P;try{({command:V,reasoning:P}=await i.promptToCommand({goal:g,history:f,startingScreenshot:h,disableCache:r?.advanced.disableAICaching??!1,logger:u,actionHint:E,langfuseSessionId:d})),u.info({command:V,reasoning:P},"Got proposed command")}finally{clearTimeout(N)}if(V.type==="FAILURE")return clearTimeout(N),m.status="FAILED",m.message=`Our AI agent determined that no supported actions can fulfill the goals: ${P}`,m;let G={id:Qd(),type:"PRESET_ACTION",command:V},_={substepIndex:S+1,message:P||"Generated new command."};c.onDynamicCommandGenerated?.({..._,step:G,parentStepId:e.id}),u.info({commandId:V.id},`Executing sub-command ${S} within AI step: ${$n(V)}`);let q=await n.startSubSteps(),se=(await t.executeStepList({...t,options:{...t.options,disableHealing:!0},listParams:{containerName:"AI action newly generated step",steps:[G],tracer:q}})).results[0];c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Waiting for page to stabilize before next action..."}),await i.browser.waitForDOMStability({logger:u});let de=await i.browser.screenshot({clearHighlights:!0,retries:1});m.results.push(se),f.push({screenshotBase64AfterCommand:`data:image/jpeg;base64,${de.toString("base64")}`,urlAfterCommand:i.browser.url(),serializedCommand:$n(V),elementInteracted:se.results[0]?.elementInteracted,thoughts:P});let wt={substepIndex:S,output:{...se,message:se.message??"Successfully executed preset action."},step:G,parentStepId:e.id};if(c.onDynamicCommandExecuted?.(wt),await n.finish({output:qa.parse(se),step:se,message:se.message,attempt:1}),se.status==="FAILED")if(m.status="FAILED",m.message=se.message,b<3)b++,v=`The last attempted action resulted in a Momentic error. A different element may need to be targeted. Error: ${se.message}`;else return m;else if(se.status==="CANCELLED")return m.status="CANCELLED",m.message=se.message,m;S++}};import{randomUUID as aI}from"crypto";var sI=3;async function ES(t){let{logger:e}=t.fixtures,{results:n}=t.failureRecoveryParams,r=n[n.length-1],o=cI(t.work,r);if(o)return e.info({failedResult:r,isNotEligible:o},"Skipping failure recovery because of ineligible failure"),{type:"NOT_ELIGIBLE",message:`The failed step is not eligible for failure recovery: ${o}`};t.work.state.failureRecoveryAttempts=(t.work.state.failureRecoveryAttempts??0)+1;try{return await lI(t)}catch(i){return e.warn({err:i},"Error during failure recovery attempt, continuing..."),null}}async function lI(t){let{fixtures:e,work:n,failureRecoveryParams:r}=t,{controller:o,logger:i}=e,{testMetadata:a}=t.inputs,{results:s,failedStep:l,nextSteps:c,tracer:d}=r;if(!s.length)throw new Error("Attempted failure recovery with no failed results");await Promise.allSettled(n.asyncTasks??[]);let u=o.browser.url(),m=`data:image/jpeg;base64,${(await o.browser.screenshot({})).toString("base64")}`,g=(await o.browser.getBrowserState({})).serialize(),{results:p}=await Xo(i,d,s,{numStepsWithScreenshots:8,addIndices:!0,includeBeforeScreenshots:!1}),h=c.map(L=>gr(L)),f=a?.description?.trim(),S=a?.advanced?.failureRecoveryInstructions?.trim(),{scenario:b,thoughts:E,instructions:v}=await o.getFailureRecoveryPlan({currentUrl:u,currentScreenshot:m,failedResults:p,currentPageState:g,nextStepsSerialized:h,testDescription:f||void 0,customInstructions:S||void 0});if(b!=="RECOVERABLE")return i.info({scenario:b,thoughts:E,instructions:v},"Failure recovery is not applicable"),{type:"NOT_ELIGIBLE",message:`Momentic's failure recovery agent determined that this failure is not eligible for recovery: ${E}`};if(!v)throw new Error("Momentic's failure recovery agent did not provide any instructions for recovery");let R={id:aI(),type:"AI_ACTION_DYNAMIC",text:v},C=await ai(t.work,()=>t.executeStepList({...t,fixtures:{...t.fixtures},listParams:{steps:[R,l],containerName:"AI-recovered step list",tracer:d}})),x=C.results[0];if(x&&x.type==="AI_ACTION_DYNAMIC")if(Ms({results:C.results,onPresetAction:L=>{L.aiSuggested=!0},onSimpleStepContainer:L=>{L.aiSuggested=!0}}),x.status==="SUCCESS"){let L=`The following steps were automatically executed by the failure recovery agent. Analysis: ${E}`;return x.message=L,i.info({thoughts:E},"Failure recovery succeeded"),{type:"ATTEMPTED",status:"SUCCESS",result:C,message:L}}else{let L=`The following steps were unsuccessfully attempted by the failure recovery agent. Analysis: ${E}`;return x.message=L,i.info({thoughts:E,aiActionResult:x},"Failure recovery failed"),{type:"ATTEMPTED",status:"FAILED",result:C,message:L}}return null}function cI(t,e){if(!e)return"There is no failed result";if(e.type!=="PRESET_ACTION")return"The failed step is not a preset action";let n=e.message;return n?n.includes("AbortError:")?"The user aborted the test":jm.some(r=>n.includes(r))?"The failed step is an irrecoverable configuration error":(t.state.failureRecoveryAttempts??0)>sI?"Too many failure recovery attempts":"":"There is no error message available on the failed step"}import{randomUUID as il}from"crypto";import dI from"fast-json-patch";import{cloneDeep as uI}from"lodash-es";async function CS(t){let e=t.failedResults,n=[],{sectionParams:r,fixtures:o,work:i,startingUrl:a,startingContextSnapshot:s,tracer:l}=t,{step:c}=r,{controller:d,logger:u}=o,m=c?.autohealingConfig,g=m?.restartBehavior??{type:"GO_TO_SECTION_START"},p=m?.attempts??1;for(let h=0;h<p;h++){if(!e.terminalResult?.message)throw new Error("No error message in terminal result");let f=uI(c.steps);await Promise.allSettled(i.asyncTasks??[]);let{results:S}=await Xo(u,l,e.results,{numStepsWithScreenshots:4}),b=await d.runSectionAutohealing({results:S,errorMessage:e.terminalResult?.message,goal:c.description});f=dI.applyPatch(f,b.patches).newDocument;let E=Yt.fromSnapshot({snapshot:s,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await mI({logger:u,controller:d,tracer:l,context:E,restartConfig:g,startingUrl:a});let v=await ai(t.work,()=>t.executeStepList({...t,fixtures:{...t.fixtures,context:E},listParams:{steps:f,containerName:"auto-healed step list",tracer:l}}));if(n.push(v.results),v.status==="SUCCESS")return{successfulHealing:{proposedStep:{...c,steps:f},listResult:v,context:E},healingAttempts:n};e=v}return{healingAttempts:n}}async function mI({logger:t,controller:e,tracer:n,restartConfig:r,context:o,startingUrl:i}){switch(r.type){case"NAVIGATE_URL":{let a={id:il(),type:"PRESET_ACTION",command:{id:il(),type:"NAVIGATE",url:r.url}},s=await n.startStep({logger:t,step:a,attempt:1});await e.executePresetCommand(null,s,a.command,o,!1);break}case"GO_TO_SECTION_START":{let a={id:il(),type:"PRESET_ACTION",command:{id:il(),type:"NAVIGATE",url:i}},s=await n.startStep({logger:t,step:a,attempt:1});await e.executePresetCommand(null,s,a.command,o,!1);break}}}function RS(t,e){switch(t||(t="ON_FAILURE"),t){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&Em(e.command.type))}}async function vS(t){let{step:e,tracer:n}=t.sectionParams,{logger:r,controller:o,context:i}=t.fixtures,a=new Date,s=o.browser.url(),l=i.toObjectCopy(),c=await n.startSubSteps(),d=async()=>t.executeStepList({...t,listParams:{steps:e.steps,containerName:"section step list",tracer:c}}),u=e.autohealingConfig?await ai(t.work,d):await d(),m,g;if(u.status==="FAILED"&&e.autohealingConfig&&!t.work.state.autoHealingDisabled&&RS(e.autohealingConfig.trigger,u.terminalResult)){let h=await n.startSubSteps(),f=await CS({...t,startingContextSnapshot:l,startingUrl:s,failedResults:u,tracer:h});f.successfulHealing&&(m=f.successfulHealing.proposedStep,u=f.successfulHealing.listResult,t.fixtures.context=f.successfulHealing.context),g=f.healingAttempts}let p={...e,...u,startedAt:a,finishedAt:new Date,proposedStep:m,healingAttempts:g};return xn({asyncTasks:t.work.asyncTasks,nestedResults:u.results,result:p,logger:r}),p}var gI=60*60*1e3;async function un(t){let{results:e=[],containerName:n,steps:r,tracer:o}=t.listParams,{logger:i}=t.fixtures,a=o.getParentStepIdChain(),{fromStep:s,toStep:l}=t.inputs,c=t.work,d="SUCCESS",u,m=0;for(m;m<r.length;m++){let g=r[m];if(g.skipped)continue;if(c.fastForwardingToStep&&s){let E=JSON.stringify(a);if(g.id===s.fromStepId&&E===JSON.stringify(s.parentStepIdChain))c.fastForwardingToStep=!1;else if(!Ch(g,a,s.fromStepId,s.parentStepIdChain))continue}let p=gr(g),h=0,f=1,S=Date.now();"retries"in g&&g.retries&&g.retries>0&&(f+=g.retries);let b;for(;h<f&&Date.now()-S<gI;){h++,i.info({step:g,currentAttempt:h},`Executing step ${m+1}/${r.length} in ${n}: ${p}`);let E=Date.now(),{stepResult:v,status:R,failureRecoveryResults:C,shouldStopExecuting:x}=await hI({attempt:h,params:t,step:g,i:m,steps:r,results:e,currentParentIdChain:a,work:c,fromStep:s,toStep:l,lastRetry:h===f});if(R==="FAILED"&&h<f){b=[...b??[],v],Date.now()-E<1e3&&await J(1e3-(Date.now()-E));continue}else e.push(v),b&&(v.previousAttempts=b);if(C&&e.push(...C),x)return d=R,u=v,{status:d,results:e,terminalResult:u};break}}return{status:d,results:e,terminalResult:u}}async function hI({attempt:t,params:e,step:n,i:r,steps:o,results:i,currentParentIdChain:a,work:s,fromStep:l,toStep:c,lastRetry:d}){let{tracer:u}=e.listParams,{logger:m,context:g,controller:p,codeEvalTools:h,billingReporter:f}=e.fixtures,{orgId:S}=e.inputs,b=new Date,E=await u.startStep({logger:m,step:n,attempt:t}),v=pI(n),R=g.toRedactedDisplayCopy(),C=p.browser.url(),x=p.executeAbortController.signal,L=zc(n.type);s.asyncTasks.push(f.reportCreditsUsed(m,n.type,L,{testId:e.inputs.testMetadata?.id,testName:e.inputs.testMetadata?.name,suiteId:e.inputs.suiteMetadata?.id,suiteName:e.inputs.suiteMetadata?.name}));let k,N;switch(n.type){case"PRESET_ACTION":{k="Preset action",N=await ao(n,async()=>await ol({...e,presetParams:{tracer:E,step:n}}),x);break}case"AI_ACTION":{k="AI action",N=await ao(n,()=>bS({...e,aiStepParams:{step:n,tracer:E},executeStepList:un}),x);break}case"AI_ACTION_DYNAMIC":{k="AI action",N=await ao(n,()=>wS({...e,aiStepParams:{step:n,tracer:E},executeStepList:un}),x);break}case"RESOLVED_MODULE":{k=`Module (${n.name})`,N=await ao(n,async()=>{let q=await uS({orgId:S,step:n,context:g,logger:m,flagStore:p.flagStore,codeEvalTools:h,signal:x});return Jd({...e,executeStepList:un,moduleParams:{step:n,resolvedInputs:q,tracer:E}})},x);break}case"CONDITIONAL":{k="Conditional step",N=await ao(n,()=>SS({...e,conditionalParams:{step:n,tracer:E},executeStepList:un}),x);break}case"SECTION":{k="Section",N=await ao(n,()=>vS({...e,sectionParams:{step:n,tracer:E},executeStepList:un}),x);break}default:return(re=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}N.beforeUrl=N.beforeUrl??C,N.beforeTestContext=R,n.envKey&&g.setVariable(n.envKey,N.data);let V=p.browser.url();g.setCurrentUrl(V),N.afterUrl=N.afterUrl??V,N.afterTestContext=g.toRedactedDisplayCopy(),await fI({startedAt:b,stepTypeName:k,result:N,callbacks:e.callbacks,globalWorkRef:e.work,tracer:E,attempt:t});let P,G;if(d&&N.status==="FAILED"&&!s.state.failureRecoveryDisabled&&l?.fromStepId===void 0&&c?.toStepId===void 0){let q=await ES({...e,executeStepList:un,failureRecoveryParams:{failedStep:v,nextSteps:o.slice(r+1),results:i.concat(N),tracer:u}});q&&(q.type==="ATTEMPTED"?(P=q.result.results,G=q.status):q.type==="NOT_ELIGIBLE"&&(N.message=N.message?`${N.message} ${q.message}`:q.message),N.type==="PRESET_ACTION"&&(N.failureRecoveryStatus={type:q.type,message:q.message}))}return s.fastForwardingToStep&&l&&(l.fromStepId===n.id&&JSON.stringify(a)===JSON.stringify(l.parentStepIdChain)&&(s.fastForwardingToStep=!1),n.type==="RESOLVED_MODULE"&&Td(a,l.parentStepIdChain)&&(s.fastForwardingToStep=!1)),N.status!=="SUCCESS"&&G!=="SUCCESS"||p.closed?{shouldStopExecuting:!0,status:N.status,stepResult:N,failureRecoveryResults:P}:c&&n.id===c.toStepId&&JSON.stringify(a)===JSON.stringify(c.parentStepIdChain)?(p.setClosed(),{shouldStopExecuting:!0,status:"SUCCESS",stepResult:N,failureRecoveryResults:P}):{shouldStopExecuting:!1,status:"SUCCESS",stepResult:N,failureRecoveryResults:P}}async function fI({stepTypeName:t,result:e,tracer:n,attempt:r}){let o=t.toLowerCase(),i=t.charAt(0).toUpperCase()+t.slice(1),a="";switch(e.status){case"SUCCESS":a=e.message??`${i} executed successfully.`;break;case"FAILED":a=e.message??`${i} failed.`;break;case"CANCELLED":a=e.message??`${i} cancelled.`;break;default:throw new Error(`Unexpected ${o} status: ${e.status}`)}await n.finish({step:e,message:a,output:qa.parse(e),attempt:r})}import{randomUUID as AS}from"crypto";async function xS({browser:t,signal:e}){let n=new Date;try{return await t.navigate({url:t.baseUrl,initialNavigation:!0}),{status:"PASSED",results:[]}}catch(r){let o={id:AS(),type:"PRESET_ACTION",status:e.aborted||r.name==="AbortError"?"CANCELLED":"FAILED",failureReason:"UserInfrastructureError",message:r.message,startedAt:n,finishedAt:new Date,results:[],command:{id:AS(),type:"NAVIGATE",url:t.baseUrl}};return{status:e.aborted||r.name==="AbortError"?"CANCELLED":"FAILED",results:[],failedStepResult:o}}}var al=async t=>{let{orgId:e,runId:n,testMetadata:r,suiteMetadata:o,steps:i,beforeSteps:a,afterSteps:s}=t.inputs;await t.fixtures.billingReporter.reportBillableEvent(t.fixtures.logger,"test-run",{eventId:n,testId:r?.id,testName:r?.name,suiteId:o?.id,suiteName:o?.name}),t.fixtures.logger=t.fixtures.logger.child({orgId:e,runId:n,testId:r?.id});let{logger:l,controller:c}=t.fixtures,{onTestComplete:d,onTestSuccess:u,onTestFailure:m}=t.callbacks.test,g=Yf(l);if(t.options.reinitializeBrowser){let h=await xS({browser:c.browser,signal:c.executeAbortController.signal});if(h.status!=="PASSED")return await d?.(),clearInterval(g?.interval),h}let p;try{return l.info({platform:g?.platform,cpuMetadata:g?.cpuMetadata,labels:r?.labels,orgSettings:t.inputs.orgSettings},`Starting run for Momentic test '${r?.name??"Unnamed test"}'`),p=await yI(t),p}finally{l.info({status:p?.status,labels:r?.labels},"Momentic test final result"),clearInterval(g?.interval),await d?.(),p?.status==="PASSED"?await u?.({steps:i,beforeSteps:a,afterSteps:s}):p?.status==="FAILED"&&await m?.({steps:i,beforeSteps:a,afterSteps:s})}};function SI({beforeStatus:t,mainStatus:e,afterStatus:n}){return t==="FAILED"?"FAILED":t==="CANCELLED"?"CANCELLED":n==="FAILED"?"FAILED":n==="CANCELLED"?"CANCELLED":e==="FAILED"?"FAILED":e==="CANCELLED"?"CANCELLED":"PASSED"}var yI=async t=>{let{tracer:e}=t.testParams,{fromStep:n,toStep:r,steps:o,beforeSteps:i,afterSteps:a}=t.inputs,{logger:s,controller:l,context:c,storage:d}=t.fixtures,{collectDebugData:u,disableHealing:m}=t.options;c.setCurrentUrl(l.browser.url());let g="test",p=o,h=[],f=m||n!==void 0||r!==void 0||void 0,S={results:h,state:{autoHealingDisabled:f,failureRecoveryDisabled:f,failureRecoveryAttempts:0},asyncTasks:[]},b=!1;n?.fromStepId&&n.fromStepId===r?.toStepId?(g="filtered step",S.fastForwardingToStep=!0):n?.fromStepId?(g="partial steps list from step",S.fastForwardingToStep=!0):r?g="partial steps list until step":(g="entire test",b=!0);let E,v;if(b&&i&&i.length>0){let N=await IS(i,"beforeSteps",t);E=N.status,v=N.results}let R,C;if(E===void 0||E==="PASSED"){s.info({fromStep:n,toStep:r},`Starting execution of ${g}`);let N=await e.startMainStepList(),V=await un({...t,work:S,listParams:{steps:p,containerName:g,results:h,tracer:N}});R=V.status,C=V.terminalResult}let x,L;if(b&&a&&a.length>0){let N=await IS(a,"afterSteps",t);x=N.status,L=N.results}let k=SI({beforeStatus:E,mainStatus:R,afterStatus:x});return u&&bI({tracer:e,work:S,controller:l,storage:d,context:c,logger:s,status:k}),await Promise.allSettled(S.asyncTasks),S.asyncTasks.push(Promise.resolve(t.callbacks.test.onSaveFinalRunResults?.({results:h,beforeResults:v,afterResults:L}))),k==="FAILED"?{status:"FAILED",results:h,beforeResults:v,afterResults:L,failedStepResult:C}:k==="CANCELLED"?{status:"CANCELLED",results:h,beforeResults:v,afterResults:L}:{status:"PASSED",failureRecoveryDetails:S.state.failureRecoveryAttempts?{attempts:S.state.failureRecoveryAttempts}:void 0,results:h,beforeResults:v,afterResults:L}};async function IS(t,e,n){let r=n.fixtures.logger,o=e==="beforeSteps"?await n.testParams.tracer.startBeforeStepList():await n.testParams.tracer.startAfterStepList();r.info(`Starting step execution for ${e}`);let i={results:[],asyncTasks:[],state:{autoHealingDisabled:!0,failureRecoveryDisabled:!0}},a={...n.callbacks,test:{...n.callbacks.test,onSaveFinalRunResults:void 0,onUpdateRun:void 0,onTestComplete:void 0,onTestSuccess:void 0}},{status:s,results:l}=await un({...n,work:i,callbacks:a,listParams:{steps:t,containerName:e,tracer:o}});await Promise.allSettled(i.asyncTasks);let c;return s==="SUCCESS"?c="PASSED":s==="CANCELLED"?c="CANCELLED":c="FAILED",{status:c,results:l}}function bI({tracer:t,work:e,controller:n,storage:r,logger:o,context:i,status:a}){let s=n.browser.retrieveAndClearDebugData(),l=Ph(s.logsPerPage),c=Yc(s.harPages||{},s.harEntries||{});t.attachConsoleLogs({logger:o,logs:l}),t.attachNetworkLogs({logger:o,logs:c}),e.asyncTasks.push((async()=>{try{let d=await n.browser.screenshot({quality:75}),u=await pS({codePath:"test-complete-final",storage:r,screenshotBuff:d,logger:o}),m=await z(n.browser.html(),{milliseconds:2e3});i.setVariable(fS,u),a!=="PASSED"&&a!=="SUCCESS"&&(o.debug({finalPageHtml:m},"Final page state HTML"),o.debug({finalScreenshotUrl:u},"Uploaded final screenshot URL"))}catch{}})())}async function sl({settings:t,customHeaders:e,envVariables:n,envName:r,testName:o,baseUrl:i,logger:a,localTools:s,orgId:l}){let c=Ja.parse(t);e&&(c.extraHeaders={...c.extraHeaders,...e});let d=new Yt({baseUrl:i,envName:r,testName:o,variablesFromEnvironment:n,currentUrl:i});await el({obj:c,context:d,bannedKeys:[],allowList:Km,localTools:s,logger:a,orgId:l});try{return Ja.parse(c)}catch(u){throw new A("UserConfigurationError",`The templated browser settings configured by the user are invalid: ${u.message}`)}}import{cloneDeep as IL}from"lodash-es";var PS={vimiumJs:'var D=Object.defineProperty;var P=(t,e,n)=>e in t?D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var b=(t,e,n)=>(P(t,typeof e!="symbol"?e+"":e,n),n);var y=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=y);var E={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?[E.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 T={_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=y(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=y(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(E.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),h=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>h,h};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let h of Array.from(t.children)){i=window.getComputedStyle(h,null);let m=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(m)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(h,!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=E.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,h,m,s=o.coords.split(",").map(l=>parseInt(l,10)),a=o.shape.toLowerCase();if(["rect","rectangle"].includes(a))s.length==4&&([r,h,i,m]=s);else if(["circle","circ"].includes(a)){if(s.length==3){let[l,c,d]=s,p=d/Math.sqrt(2);r=l-p,i=l+p,h=c-p,m=c+p}}else a==="default"?s.length==2&&([r,h,i,m]=[0,0,t.width,t.height]):s.length>=4&&([r,h,i,m]=s);let u=E.translate(E.create(r,h,i,m),t.left,t.top);u=this.cropRectToVisible(u),u&&!isNaN(u.top)&&!isNaN(u.left)&&!isNaN(u.width)&&!isNaN(u.height)&&n.push({element:o,rect:u})}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{}},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:h}=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&&h===!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 T.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?.parentNode,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 R={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){let e={};this.addAttributes(t,this.commonAttributes,e);let n=t.tagName.toLowerCase?.()||"";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,{tag:n,attributes:e,...o&&{content:o}})},getContent(t){let e=t.tagName.toLowerCase?.()||"";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){if((t.tagName.toLowerCase?.()||"")=="label"&&t.hasAttribute("for")){let o=t.getAttribute("for"),r=document.getElementById(o);r&&(e.target=this.describe(r))}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 C=null,k=()=>j()||document.scrollingElement||document.body,_=function(t){return t?t<0?-1:1:0},F={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},O=function(t,e,n){if(T.isString(n)){let o=n;return o==="viewSize"&&t===k()?e==="x"?window.innerWidth:window.innerHeight:t[F[e][o]]}else return n},I=function(t,e,n){let o=F[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},V=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},v=function(t,e,n,o){let r=o*O(t,e,n)||-1;return r=_(r),I(t,e,r)&&I(t,e,-r)},U=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),v(t,e,n,o)&&V(t,e)},H=function(t=null){let e;if(!t){let n=k();if(v(n,"y",1,1)||v(n,"y",-1,1))return n;t=document.body||k()}if(v(t,"y",1,1)||v(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=H(e.element);if(o)return o}return null}},M={init(){C=null},isScrollableElement(t){return C||(C=k()&&H()||k()),t!==C&&U(t)}},j=function(){let t=K[window.location.host];if(t)return document.querySelector(t)},K={"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=M;var x=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",y(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",y(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:x});var L=class{constructor(e){b(this,"element");b(this,"image");b(this,"rect");b(this,"linkText");b(this,"showLinkText");b(this,"reason");b(this,"secondClassCitizen");b(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},S={getLocalHintsForElement(t){let e=t.tagName.toLowerCase?.()||"",n=!1,o=!1,r=!1,i=[],h=[],m=null;if(e==="img"){let l=t.getAttribute("usemap");if(l){let c=t.getClientRects();l=l.replace(/^#/,"").replace(\'"\',\'\\\\"\');let d=document.querySelector(`map[name="${l}"]`);if(d&&c.length>0){n=!0;let p=d.getElementsByTagName("area"),g=f.getClientRectsForAreas(c[0],p);g=g.map(N=>Object.assign(N,{image:t})),h.push(...g)}}}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 c=[];for(let d of["","data-","x-"])for(let p of["-",":","_"])c.push(`${d}ng${p}click`);return function(d){for(let p of c)if(d.hasAttribute(p))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let l=t.getAttribute("role"),c=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(l!=null&&c.includes(l.toLowerCase()))n=!0;else{let d=t.getAttribute("contentEditable");d!=null&&["","contenteditable","true","plaintext-only"].includes(d.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let l=t.getAttribute("jsaction").split(";");for(let c of l){let d=c.trim().split(":");if(d.length>=1&&d.length<=2){let[p,g,N]=d.length===1?["click",...d[0].trim().split("."),"_"]:[d[0],...d[1].trim().split("."),"_"];n||(n=p==="click"&&g!=="none"&&N!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||=!t.disabled&&!t.readOnly;break;case"input":n||=!(t.getAttribute("type")?.toLowerCase()=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t));break;case"button":case"select":n||=!t.disabled;break;case"object":case"embed":n=!0;break;case"label":n||=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0;break;case"body":n||=t===document.body&&!x()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?m="Frame.":void 0,n||=t===document.body&&x()&&M.isScrollableElement(t)?m="Scroll.":void 0;break;case"img":n||=["zoom-in","zoom-out"].includes(t.style.cursor);break;case"div":case"ol":case"ul":n||=t.clientHeight<t.scrollHeight&&M.isScrollableElement(t)?m="Scroll.":void 0;break;case"details":n=!0,m="Open.";break}let a=t.getAttribute("class");!n&&a?.toLowerCase().includes("button")&&(n=!0,r=!0);let u=t.getAttribute("tabindex"),w=u?parseInt(u):-1;if(!n&&!(w<0)&&!isNaN(w)&&(n=!0,o=!0),n)if(h.length>0){let l=h.map(c=>new L({element:c.element,image:t,rect:c.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:m}));i.push(...l)}else{let l=f.getVisibleClientRect(t,!0);if(l!==null){let c=new L({element:t,rect:l,secondClassCitizen:o,possibleFalsePositive:r,reason:m});i.push(c)}}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?S.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,a)=>{a==null&&(a=[]);for(let u of Array.from(s.querySelectorAll("*")))a.push(u),u.shadowRoot&&e(u.shadowRoot,a);return a},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let a=this.getLocalHintsForElement(s);o.push(...a)}o=o.reverse();let r=[1,2,3];o=o.filter((s,a)=>{if(!s.possibleFalsePositive)return!0;let w=Math.max(0,a-6);for(;w<a;){let l=o[w].element;for(let c of r)if(l=l?.parentElement,l===s.element)return!1;w+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let a=s.rect,u=S.getElementFromPoint(a.left+a.width*.5,a.top+a.height*.5);if(u&&(s.element.contains(u)||u.contains(s.element))||s.element.localName=="area"&&u==s.image)return!0;let l=[a.top+.1,a.bottom-.1],c=[a.left+.1,a.right-.1];for(let d of l)for(let p of c){let g=S.getElementFromPoint(p,d);if(g&&(s.element.contains(g)||g.contains(s.element)))return!0}});i.reverse();let{top:h,left:m}=f.getViewportTopLeft();for(let s of i)s.rect.top+=h,s.rect.left+=m;return i}};var A=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}async capture(){this.reset(),this.createMarkers(),this.displayMarkers()}createMarkers(){this.hints=S.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{let o=f.createElement("div"),r=e.element.attributes["data-momentic-id"]?.value??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(R.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=A;\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:`// src/html/cache-evaluation.ts
36
+ ${R.feedback}`,m.status="FAILED",c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,status:"FAILED",message:m.message}),m;D&&c.onDynamicAIActionEvaluatingEvent?.({stepId:D,status:"FAILED",message:R.feedback});break}case"IMPOSSIBLE":return m.message=`Our AI evaluator determined this task cannot be achieved: ${x}`,m.status="FAILED",c.onDynamicAIActionEvaluatingEvent?.({stepId:D??e.id,status:"FAILED",message:m.message}),m}let _=setTimeout(()=>{c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Deciding what to do next..."})},1500);u.info({commandIndex:y,lastActionHint:w},`Generating new sub-command ${y} within AI action`);let K,P;try{({command:K,reasoning:P}=await a.promptToCommand({goal:p,history:f,startingScreenshot:h,disableCache:r?.advanced.disableAICaching??!1,logger:u,actionHint:w,langfuseSessionId:d})),u.info({command:K,reasoning:P},"Got proposed command")}finally{clearTimeout(_)}if(K.type==="FAILURE")return clearTimeout(_),m.status="FAILED",m.message=`Our AI agent determined that no supported actions can fulfill the goals: ${P}`,m;let W={id:au(),type:"PRESET_ACTION",command:K},k={substepIndex:y+1,message:P||"Generated new command."};c.onDynamicCommandGenerated?.({...k,step:W,parentStepId:e.id}),u.info({commandId:K.id},`Executing sub-command ${y} within AI step: ${jn(K)}`);let G=await n.startSubSteps(),Ce=(await t.executeStepList({...t,options:{...t.options,disableHealing:!0},listParams:{containerName:"AI action newly generated step",steps:[W],tracer:G}})).results[0];c.onDynamicAIActionStatusUpdateEvent?.({parentStepId:e.id,message:"Waiting for page to stabilize before next action..."}),await a.browser.waitForDOMStability({logger:u});let be=await a.browser.screenshot({clearHighlights:!0,retries:1});m.results.push(Ce),f.push({screenshotBase64AfterCommand:`data:image/jpeg;base64,${be.toString("base64")}`,urlAfterCommand:a.browser.url(),serializedCommand:jn(K),elementInteracted:Ce.results[0]?.elementInteracted,thoughts:P});let wt={substepIndex:y,output:{...Ce,message:Ce.message??"Successfully executed preset action."},step:W,parentStepId:e.id};if(c.onDynamicCommandExecuted?.(wt),await n.finish({output:Ji.parse(Ce),step:Ce,message:Ce.message,attempt:1}),Ce.status==="FAILED")if(m.status="FAILED",m.message=Ce.message,b<3)b++,C=`The last attempted action resulted in a Momentic error. A different element may need to be targeted. Error: ${Ce.message}`;else return m;else if(Ce.status==="CANCELLED")return m.status="CANCELLED",m.message=Ce.message,m;y++}};import{randomUUID as TI}from"crypto";var wI=3;async function OS(t){let{logger:e}=t.fixtures,{results:n}=t.failureRecoveryParams,r=n[n.length-1],o=RI(t.work,r);if(o)return e.info({failedResult:r,isNotEligible:o},"Skipping failure recovery because of ineligible failure"),{type:"NOT_ELIGIBLE",message:`The failed step is not eligible for failure recovery: ${o}`};t.work.state.failureRecoveryAttempts=(t.work.state.failureRecoveryAttempts??0)+1;try{return await EI(t)}catch(a){return e.warn({err:a},"Error during failure recovery attempt, continuing..."),null}}async function EI(t){let{fixtures:e,work:n,failureRecoveryParams:r}=t,{controller:o,logger:a}=e,{testMetadata:i}=t.inputs,{results:s,failedStep:l,nextSteps:c,tracer:d}=r;if(!s.length)throw new Error("Attempted failure recovery with no failed results");await Promise.allSettled(n.asyncTasks??[]);let u=o.browser.url(),m=`data:image/jpeg;base64,${(await o.browser.screenshot({})).toString("base64")}`,p=(await o.browser.getBrowserState({})).serialize(),{results:g}=await Qo(a,d,s,{numStepsWithScreenshots:8,addIndices:!0,includeBeforeScreenshots:!1}),h=c.map(M=>hr(M)),f=i?.description?.trim(),y=i?.advanced?.failureRecoveryInstructions?.trim(),{scenario:b,thoughts:w,instructions:C}=await o.getFailureRecoveryPlan({currentUrl:u,currentScreenshot:m,failedResults:g,currentPageState:p,nextStepsSerialized:h,testDescription:f||void 0,customInstructions:y||void 0});if(b!=="RECOVERABLE")return a.info({scenario:b,thoughts:w,instructions:C},"Failure recovery is not applicable"),{type:"NOT_ELIGIBLE",message:`Momentic's failure recovery agent determined that this failure is not eligible for recovery: ${w}`};if(!C)throw new Error("Momentic's failure recovery agent did not provide any instructions for recovery");let v={id:TI(),type:"AI_ACTION_DYNAMIC",text:C},R=await la(t.work,()=>t.executeStepList({...t,fixtures:{...t.fixtures},listParams:{steps:[v,l],containerName:"AI-recovered step list",tracer:d}})),x=R.results[0];if(x&&x.type==="AI_ACTION_DYNAMIC")if(Ds({results:R.results,onPresetAction:M=>{M.aiSuggested=!0},onSimpleStepContainer:M=>{M.aiSuggested=!0}}),x.status==="SUCCESS"){let M=`The following steps were automatically executed by the failure recovery agent. Analysis: ${w}`;return x.message=M,a.info({thoughts:w},"Failure recovery succeeded"),{type:"ATTEMPTED",status:"SUCCESS",result:R,message:M}}else{let M=`The following steps were unsuccessfully attempted by the failure recovery agent. Analysis: ${w}`;return x.message=M,a.info({thoughts:w,aiActionResult:x},"Failure recovery failed"),{type:"ATTEMPTED",status:"FAILED",result:R,message:M}}return null}function RI(t,e){if(!e)return"There is no failed result";if(e.type!=="PRESET_ACTION")return"The failed step is not a preset action";let n=e.message;return n?n.includes("AbortError:")?"The user aborted the test":Qm.some(r=>n.includes(r))?"The failed step is an irrecoverable configuration error":(t.state.failureRecoveryAttempts??0)>wI?"Too many failure recovery attempts":"":"There is no error message available on the failed step"}import{randomUUID as pl}from"crypto";import CI from"fast-json-patch";import{cloneDeep as vI}from"lodash-es";async function NS(t){let e=t.failedResults,n=[],{sectionParams:r,fixtures:o,work:a,startingUrl:i,startingContextSnapshot:s,tracer:l}=t,{step:c}=r,{controller:d,logger:u}=o,m=c?.autohealingConfig,p=m?.restartBehavior??{type:"GO_TO_SECTION_START"},g=m?.attempts??1;for(let h=0;h<g;h++){if(!e.terminalResult?.message)throw new Error("No error message in terminal result");let f=vI(c.steps);await Promise.allSettled(a.asyncTasks??[]);let{results:y}=await Qo(u,l,e.results,{numStepsWithScreenshots:4}),b=await d.runSectionAutohealing({results:y,errorMessage:e.terminalResult?.message,goal:c.description});f=CI.applyPatch(f,b.patches).newDocument;let w=Xt.fromSnapshot({snapshot:s,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await AI({logger:u,controller:d,tracer:l,context:w,restartConfig:p,startingUrl:i});let C=await la(t.work,()=>t.executeStepList({...t,fixtures:{...t.fixtures,context:w},listParams:{steps:f,containerName:"auto-healed step list",tracer:l}}));if(n.push(C.results),C.status==="SUCCESS")return{successfulHealing:{proposedStep:{...c,steps:f},listResult:C,context:w},healingAttempts:n};e=C}return{healingAttempts:n}}async function AI({logger:t,controller:e,tracer:n,restartConfig:r,context:o,startingUrl:a}){switch(r.type){case"NAVIGATE_URL":{let i={id:pl(),type:"PRESET_ACTION",command:{id:pl(),type:"NAVIGATE",url:r.url}},s=await n.startStep({logger:t,step:i,attempt:1});await e.executePresetCommand(null,s,i.command,o,!1);break}case"GO_TO_SECTION_START":{let i={id:pl(),type:"PRESET_ACTION",command:{id:pl(),type:"NAVIGATE",url:a}},s=await n.startStep({logger:t,step:i,attempt:1});await e.executePresetCommand(null,s,i.command,o,!1);break}}}function kS(t,e){switch(t||(t="ON_FAILURE"),t){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&Lm(e.command.type))}}async function _S(t){let{step:e,tracer:n}=t.sectionParams,{logger:r,controller:o,context:a}=t.fixtures,i=new Date,s=o.browser.url(),l=a.toObjectCopy(),c=await n.startSubSteps(),d=async()=>t.executeStepList({...t,listParams:{steps:e.steps,containerName:"section step list",tracer:c}}),u=e.autohealingConfig?await la(t.work,d):await d(),m,p;if(u.status==="FAILED"&&e.autohealingConfig&&!t.work.state.autoHealingDisabled&&kS(e.autohealingConfig.trigger,u.terminalResult)){let h=await n.startSubSteps(),f=await NS({...t,startingContextSnapshot:l,startingUrl:s,failedResults:u,tracer:h});f.successfulHealing&&(m=f.successfulHealing.proposedStep,u=f.successfulHealing.listResult,t.fixtures.context=f.successfulHealing.context),p=f.healingAttempts}let g={...e,...u,startedAt:i,finishedAt:new Date,proposedStep:m,healingAttempts:p};return In({asyncTasks:t.work.asyncTasks,nestedResults:u.results,result:g,logger:r}),g}var II=60*60*1e3;async function mn(t){let{results:e=[],containerName:n,steps:r,tracer:o}=t.listParams,{logger:a}=t.fixtures,i=o.getParentStepIdChain(),{fromStep:s,toStep:l}=t.inputs,c=t.work,d="SUCCESS",u,m=0;for(m;m<r.length;m++){let p=r[m];if(p.skipped)continue;if(c.fastForwardingToStep&&s){let w=JSON.stringify(i);if(p.id===s.fromStepId&&w===JSON.stringify(s.parentStepIdChain))c.fastForwardingToStep=!1;else if(!Nh(p,i,s.fromStepId,s.parentStepIdChain))continue}let g=hr(p),h=0,f=1,y=Date.now();"retries"in p&&p.retries&&p.retries>0&&(f+=p.retries);let b;for(;h<f&&Date.now()-y<II;){h++,a.info({step:p,currentAttempt:h},`Executing step ${m+1}/${r.length} in ${n}: ${g}`);let w=Date.now(),{stepResult:C,status:v,failureRecoveryResults:R,shouldStopExecuting:x}=await PI({attempt:h,params:t,step:p,i:m,steps:r,results:e,currentParentIdChain:i,work:c,fromStep:s,toStep:l,lastRetry:h===f});if(v==="FAILED"&&h<f){b=[...b??[],C],Date.now()-w<1e3&&await J(1e3-(Date.now()-w));continue}else e.push(C),b&&(C.previousAttempts=b);if(R&&e.push(...R),x)return d=v,u=C,{status:d,results:e,terminalResult:u};break}}return{status:d,results:e,terminalResult:u}}async function PI({attempt:t,params:e,step:n,i:r,steps:o,results:a,currentParentIdChain:i,work:s,fromStep:l,toStep:c,lastRetry:d}){let{tracer:u}=e.listParams,{logger:m,context:p,controller:g,codeEvalTools:h,billingReporter:f}=e.fixtures,{orgId:y}=e.inputs,b=new Date,w=await u.startStep({logger:m,step:n,attempt:t}),C=xI(n),v=p.toRedactedDisplayCopy(),R=g.browser.url(),x=g.executeAbortController.signal,M=qc(n.type);s.asyncTasks.push(f.reportCreditsUsed(m,n.type,M,{testId:e.inputs.testMetadata?.id,testName:e.inputs.testMetadata?.name,suiteId:e.inputs.suiteMetadata?.id,suiteName:e.inputs.suiteMetadata?.name}));let D,_;switch(n.type){case"PRESET_ACTION":{D="Preset action",_=await lo(n,async()=>await ml({...e,presetParams:{tracer:w,step:n}}),x);break}case"AI_ACTION":{D="AI action",_=await lo(n,()=>PS({...e,aiStepParams:{step:n,tracer:w},executeStepList:mn}),x);break}case"AI_ACTION_DYNAMIC":{D="AI action",_=await lo(n,()=>LS({...e,aiStepParams:{step:n,tracer:w},executeStepList:mn}),x);break}case"RESOLVED_MODULE":{D=`Module (${n.name})`,_=await lo(n,async()=>{let G=await wS({orgId:y,step:n,context:p,logger:m,flagStore:g.flagStore,codeEvalTools:h,signal:x});return ou({...e,executeStepList:mn,moduleParams:{step:n,resolvedInputs:G,tracer:w}})},x);break}case"CONDITIONAL":{D="Conditional step",_=await lo(n,()=>xS({...e,conditionalParams:{step:n,tracer:w},executeStepList:mn}),x);break}case"SECTION":{D="Section",_=await lo(n,()=>_S({...e,sectionParams:{step:n,tracer:w},executeStepList:mn}),x);break}default:return(we=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}_.beforeUrl=_.beforeUrl??R,_.beforeTestContext=v,n.envKey&&p.setVariable(n.envKey,_.data);let K=g.browser.url();p.setCurrentUrl(K),_.afterUrl=_.afterUrl??K,_.afterTestContext=p.toRedactedDisplayCopy(),await MI({startedAt:b,stepTypeName:D,result:_,callbacks:e.callbacks,globalWorkRef:e.work,tracer:w,attempt:t});let P,W;if(d&&_.status==="FAILED"&&!s.state.failureRecoveryDisabled&&l?.fromStepId===void 0&&c?.toStepId===void 0){let G=await OS({...e,executeStepList:mn,failureRecoveryParams:{failedStep:C,nextSteps:o.slice(r+1),results:a.concat(_),tracer:u}});G&&(G.type==="ATTEMPTED"?(P=G.result.results,W=G.status):G.type==="NOT_ELIGIBLE"&&(_.message=_.message?`${_.message} ${G.message}`:G.message),_.type==="PRESET_ACTION"&&(_.failureRecoveryStatus={type:G.type,message:G.message}))}return s.fastForwardingToStep&&l&&(l.fromStepId===n.id&&JSON.stringify(i)===JSON.stringify(l.parentStepIdChain)&&(s.fastForwardingToStep=!1),n.type==="RESOLVED_MODULE"&&Id(i,l.parentStepIdChain)&&(s.fastForwardingToStep=!1)),_.status!=="SUCCESS"&&W!=="SUCCESS"||g.closed?{shouldStopExecuting:!0,status:_.status,stepResult:_,failureRecoveryResults:P}:c&&n.id===c.toStepId&&JSON.stringify(i)===JSON.stringify(c.parentStepIdChain)?(g.setClosed(),{shouldStopExecuting:!0,status:"SUCCESS",stepResult:_,failureRecoveryResults:P}):{shouldStopExecuting:!1,status:"SUCCESS",stepResult:_,failureRecoveryResults:P}}async function MI({stepTypeName:t,result:e,tracer:n,attempt:r}){let o=t.toLowerCase(),a=t.charAt(0).toUpperCase()+t.slice(1),i="";switch(e.status){case"SUCCESS":i=e.message??`${a} executed successfully.`;break;case"FAILED":i=e.message??`${a} failed.`;break;case"CANCELLED":i=e.message??`${a} cancelled.`;break;default:throw new Error(`Unexpected ${o} status: ${e.status}`)}await n.finish({step:e,message:i,output:Ji.parse(e),attempt:r})}import{randomUUID as DS}from"crypto";async function FS({browser:t,signal:e}){let n=new Date;try{return await t.navigate({url:t.baseUrl,initialNavigation:!0}),{status:"PASSED",results:[]}}catch(r){let o={id:DS(),type:"PRESET_ACTION",status:e.aborted||r.name==="AbortError"?"CANCELLED":"FAILED",failureReason:"UserInfrastructureError",message:r.message,startedAt:n,finishedAt:new Date,results:[],command:{id:DS(),type:"NAVIGATE",url:t.baseUrl}};return{status:e.aborted||r.name==="AbortError"?"CANCELLED":"FAILED",results:[],failedStepResult:o}}}var gl=async t=>{let{orgId:e,runId:n,testMetadata:r,suiteMetadata:o,steps:a,beforeSteps:i,afterSteps:s}=t.inputs;await t.fixtures.billingReporter.reportBillableEvent(t.fixtures.logger,"test-run",{eventId:n,testId:r?.id,testName:r?.name,suiteId:o?.id,suiteName:o?.name}),t.fixtures.logger=t.fixtures.logger.child({orgId:e,runId:n,testId:r?.id});let{logger:l,controller:c}=t.fixtures,{onTestComplete:d,onTestSuccess:u,onTestFailure:m}=t.callbacks.test,p=aS(l);if(t.options.reinitializeBrowser){let h=await FS({browser:c.browser,signal:c.executeAbortController.signal});if(h.status!=="PASSED")return await d?.(),clearInterval(p?.interval),h}let g;try{return l.info({platform:p?.platform,cpuMetadata:p?.cpuMetadata,labels:r?.labels,orgSettings:t.inputs.orgSettings},`Starting run for Momentic test '${r?.name??"Unnamed test"}'`),g=await OI(t),g}finally{l.info({status:g?.status,labels:r?.labels},"Momentic test final result"),clearInterval(p?.interval),await d?.(),g?.status==="PASSED"?await u?.({steps:a,beforeSteps:i,afterSteps:s}):g?.status==="FAILED"&&await m?.({steps:a,beforeSteps:i,afterSteps:s})}};function LI({beforeStatus:t,mainStatus:e,afterStatus:n}){return t==="FAILED"?"FAILED":t==="CANCELLED"?"CANCELLED":n==="FAILED"?"FAILED":n==="CANCELLED"?"CANCELLED":e==="FAILED"?"FAILED":e==="CANCELLED"?"CANCELLED":"PASSED"}var OI=async t=>{let{tracer:e}=t.testParams,{fromStep:n,toStep:r,steps:o,beforeSteps:a,afterSteps:i}=t.inputs,{logger:s,controller:l,context:c,storage:d}=t.fixtures,{collectDebugData:u,disableHealing:m}=t.options;c.setCurrentUrl(l.browser.url());let p="test",g=o,h=[],f=m||n!==void 0||r!==void 0||void 0,y={results:h,state:{autoHealingDisabled:f,failureRecoveryDisabled:f,failureRecoveryAttempts:0},asyncTasks:[]},b=!1;n?.fromStepId&&n.fromStepId===r?.toStepId?(p="filtered step",y.fastForwardingToStep=!0):n?.fromStepId?(p="partial steps list from step",y.fastForwardingToStep=!0):r?p="partial steps list until step":(p="entire test",b=!0);let w,C;if(b&&a&&a.length>0){let _=await US(a,"beforeSteps",t);w=_.status,C=_.results}let v,R;if(w===void 0||w==="PASSED"){s.info({fromStep:n,toStep:r},`Starting execution of ${p}`);let _=await e.startMainStepList(),K=await mn({...t,work:y,listParams:{steps:g,containerName:p,results:h,tracer:_}});v=K.status,R=K.terminalResult}let x,M;if(b&&i&&i.length>0){let _=await US(i,"afterSteps",t);x=_.status,M=_.results}let D=LI({beforeStatus:w,mainStatus:v,afterStatus:x});return u&&NI({tracer:e,work:y,controller:l,storage:d,context:c,logger:s,status:D}),await Promise.allSettled(y.asyncTasks),y.asyncTasks.push(Promise.resolve(t.callbacks.test.onSaveFinalRunResults?.({results:h,beforeResults:C,afterResults:M}))),D==="FAILED"?{status:"FAILED",results:h,beforeResults:C,afterResults:M,failedStepResult:R}:D==="CANCELLED"?{status:"CANCELLED",results:h,beforeResults:C,afterResults:M}:{status:"PASSED",failureRecoveryDetails:y.state.failureRecoveryAttempts?{attempts:y.state.failureRecoveryAttempts}:void 0,results:h,beforeResults:C,afterResults:M}};async function US(t,e,n){let r=n.fixtures.logger,o=e==="beforeSteps"?await n.testParams.tracer.startBeforeStepList():await n.testParams.tracer.startAfterStepList();r.info(`Starting step execution for ${e}`);let a={results:[],asyncTasks:[],state:{autoHealingDisabled:!0,failureRecoveryDisabled:!0}},i={...n.callbacks,test:{...n.callbacks.test,onSaveFinalRunResults:void 0,onUpdateRun:void 0,onTestComplete:void 0,onTestSuccess:void 0}},{status:s,results:l}=await mn({...n,work:a,callbacks:i,listParams:{steps:t,containerName:e,tracer:o}});await Promise.allSettled(a.asyncTasks);let c;return s==="SUCCESS"?c="PASSED":s==="CANCELLED"?c="CANCELLED":c="FAILED",{status:c,results:l}}function NI({tracer:t,work:e,controller:n,storage:r,logger:o,context:a,status:i}){let s=n.browser.retrieveAndClearDebugData(),l=Bh(s.logsPerPage),c=nd(s.harPages||{},s.harEntries||{});t.attachConsoleLogs({logger:o,logs:l}),t.attachNetworkLogs({logger:o,logs:c}),e.asyncTasks.push((async()=>{try{let d=await n.browser.screenshot({quality:75}),u=await RS({codePath:"test-complete-final",storage:r,screenshotBuff:d,logger:o}),m=await H(n.browser.html(),{milliseconds:2e3});a.setVariable(AS,u),i!=="PASSED"&&i!=="SUCCESS"&&(o.debug({finalPageHtml:m},"Final page state HTML"),o.debug({finalScreenshotUrl:u},"Uploaded final screenshot URL"))}catch{}})())}async function hl({settings:t,customHeaders:e,envVariables:n,envName:r,testName:o,baseUrl:a,logger:i,localTools:s,orgId:l}){let c=es.parse(t);e&&(c.extraHeaders={...c.extraHeaders,...e});let d=new Xt({baseUrl:a,envName:r,testName:o,variablesFromEnvironment:n,currentUrl:a});await ll({obj:c,context:d,bannedKeys:[],allowList:np,localTools:s,logger:i,orgId:l});try{return es.parse(c)}catch(u){throw new A("UserConfigurationError",`The templated browser settings configured by the user are invalid: ${u.message}`)}}import{cloneDeep as jM}from"lodash-es";var BS={vimiumJs:'var D=Object.defineProperty;var P=(t,e,n)=>e in t?D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var b=(t,e,n)=>(P(t,typeof e!="symbol"?e+"":e,n),n);var y=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=y);var E={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?[E.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 T={_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=y(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=y(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(E.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),h=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>h,h};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let h of Array.from(t.children)){i=window.getComputedStyle(h,null);let m=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(m)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(h,!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=E.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,h,m,s=o.coords.split(",").map(l=>parseInt(l,10)),a=o.shape.toLowerCase();if(["rect","rectangle"].includes(a))s.length==4&&([r,h,i,m]=s);else if(["circle","circ"].includes(a)){if(s.length==3){let[l,c,d]=s,p=d/Math.sqrt(2);r=l-p,i=l+p,h=c-p,m=c+p}}else a==="default"?s.length==2&&([r,h,i,m]=[0,0,t.width,t.height]):s.length>=4&&([r,h,i,m]=s);let u=E.translate(E.create(r,h,i,m),t.left,t.top);u=this.cropRectToVisible(u),u&&!isNaN(u.top)&&!isNaN(u.left)&&!isNaN(u.width)&&!isNaN(u.height)&&n.push({element:o,rect:u})}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{}},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:h}=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&&h===!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 T.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?.parentNode,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 R={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){let e={};this.addAttributes(t,this.commonAttributes,e);let n=t.tagName.toLowerCase?.()||"";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,{tag:n,attributes:e,...o&&{content:o}})},getContent(t){let e=t.tagName.toLowerCase?.()||"";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){if((t.tagName.toLowerCase?.()||"")=="label"&&t.hasAttribute("for")){let o=t.getAttribute("for"),r=document.getElementById(o);r&&(e.target=this.describe(r))}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 C=null,k=()=>j()||document.scrollingElement||document.body,_=function(t){return t?t<0?-1:1:0},F={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},O=function(t,e,n){if(T.isString(n)){let o=n;return o==="viewSize"&&t===k()?e==="x"?window.innerWidth:window.innerHeight:t[F[e][o]]}else return n},I=function(t,e,n){let o=F[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},V=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},v=function(t,e,n,o){let r=o*O(t,e,n)||-1;return r=_(r),I(t,e,r)&&I(t,e,-r)},U=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),v(t,e,n,o)&&V(t,e)},H=function(t=null){let e;if(!t){let n=k();if(v(n,"y",1,1)||v(n,"y",-1,1))return n;t=document.body||k()}if(v(t,"y",1,1)||v(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=H(e.element);if(o)return o}return null}},M={init(){C=null},isScrollableElement(t){return C||(C=k()&&H()||k()),t!==C&&U(t)}},j=function(){let t=K[window.location.host];if(t)return document.querySelector(t)},K={"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=M;var x=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",y(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",y(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:x});var L=class{constructor(e){b(this,"element");b(this,"image");b(this,"rect");b(this,"linkText");b(this,"showLinkText");b(this,"reason");b(this,"secondClassCitizen");b(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},S={getLocalHintsForElement(t){let e=t.tagName.toLowerCase?.()||"",n=!1,o=!1,r=!1,i=[],h=[],m=null;if(e==="img"){let l=t.getAttribute("usemap");if(l){let c=t.getClientRects();l=l.replace(/^#/,"").replace(\'"\',\'\\\\"\');let d=document.querySelector(`map[name="${l}"]`);if(d&&c.length>0){n=!0;let p=d.getElementsByTagName("area"),g=f.getClientRectsForAreas(c[0],p);g=g.map(N=>Object.assign(N,{image:t})),h.push(...g)}}}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 c=[];for(let d of["","data-","x-"])for(let p of["-",":","_"])c.push(`${d}ng${p}click`);return function(d){for(let p of c)if(d.hasAttribute(p))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let l=t.getAttribute("role"),c=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(l!=null&&c.includes(l.toLowerCase()))n=!0;else{let d=t.getAttribute("contentEditable");d!=null&&["","contenteditable","true","plaintext-only"].includes(d.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let l=t.getAttribute("jsaction").split(";");for(let c of l){let d=c.trim().split(":");if(d.length>=1&&d.length<=2){let[p,g,N]=d.length===1?["click",...d[0].trim().split("."),"_"]:[d[0],...d[1].trim().split("."),"_"];n||(n=p==="click"&&g!=="none"&&N!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||=!t.disabled&&!t.readOnly;break;case"input":n||=!(t.getAttribute("type")?.toLowerCase()=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t));break;case"button":case"select":n||=!t.disabled;break;case"object":case"embed":n=!0;break;case"label":n||=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0;break;case"body":n||=t===document.body&&!x()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?m="Frame.":void 0,n||=t===document.body&&x()&&M.isScrollableElement(t)?m="Scroll.":void 0;break;case"img":n||=["zoom-in","zoom-out"].includes(t.style.cursor);break;case"div":case"ol":case"ul":n||=t.clientHeight<t.scrollHeight&&M.isScrollableElement(t)?m="Scroll.":void 0;break;case"details":n=!0,m="Open.";break}let a=t.getAttribute("class");!n&&a?.toLowerCase().includes("button")&&(n=!0,r=!0);let u=t.getAttribute("tabindex"),w=u?parseInt(u):-1;if(!n&&!(w<0)&&!isNaN(w)&&(n=!0,o=!0),n)if(h.length>0){let l=h.map(c=>new L({element:c.element,image:t,rect:c.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:m}));i.push(...l)}else{let l=f.getVisibleClientRect(t,!0);if(l!==null){let c=new L({element:t,rect:l,secondClassCitizen:o,possibleFalsePositive:r,reason:m});i.push(c)}}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?S.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,a)=>{a==null&&(a=[]);for(let u of Array.from(s.querySelectorAll("*")))a.push(u),u.shadowRoot&&e(u.shadowRoot,a);return a},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let a=this.getLocalHintsForElement(s);o.push(...a)}o=o.reverse();let r=[1,2,3];o=o.filter((s,a)=>{if(!s.possibleFalsePositive)return!0;let w=Math.max(0,a-6);for(;w<a;){let l=o[w].element;for(let c of r)if(l=l?.parentElement,l===s.element)return!1;w+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let a=s.rect,u=S.getElementFromPoint(a.left+a.width*.5,a.top+a.height*.5);if(u&&(s.element.contains(u)||u.contains(s.element))||s.element.localName=="area"&&u==s.image)return!0;let l=[a.top+.1,a.bottom-.1],c=[a.left+.1,a.right-.1];for(let d of l)for(let p of c){let g=S.getElementFromPoint(p,d);if(g&&(s.element.contains(g)||g.contains(s.element)))return!0}});i.reverse();let{top:h,left:m}=f.getViewportTopLeft();for(let s of i)s.rect.top+=h,s.rect.left+=m;return i}};var A=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}async capture(){this.reset(),this.createMarkers(),this.displayMarkers()}createMarkers(){this.hints=S.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{let o=f.createElement("div"),r=e.element.attributes["data-momentic-id"]?.value??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(R.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=A;\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:`// src/html/cache-evaluation.ts
37
37
  function isEligibleForAttrRemoval(bestCandidate, attrToRemove) {
38
38
  const customWindow = window;
39
39
  if (bestCandidate.textContent?.trim()) {
@@ -3885,34 +3885,34 @@ function registerAllMomenticListeners() {
3885
3885
 
3886
3886
  // src/html/index.ts
3887
3887
  registerAllMomenticListeners();
3888
- `};var Vn={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center","notion-selectable","notion-page-block","notion-collection-item","MuiSvgIcon","css-","rt-"],nonDynamicInputTypes:["button","file","hidden","image","radio","reset","submit"],generalStateAttributes:["aria-expanded","aria-haspopup","aria-checked","aria-pressed","aria-selected","aria-invalid","checked","open","aria-busy"],bannedElementTagNames:["html","head","meta","script","style","path","br","::marker","noscript","polygon","defs"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","tooltip","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","contenteditable","data-value","data-testid","data-cy","data-pw","data-test-id","data-test","data-role","data-type","data-key","data-action","data-qa","data-aria-hidden","data-hidden","data-automation-id","data-overlay","data-content-editable-leaf","data-wf-icon","data-tns","data-sticky-stack-name","data-popup-origin","data-handleid","data-handlepos","data-col-index","data-row-index","data-row","data-col","col-index","row-index","row","col","data-momentic-description","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden","aria-describedby","aria-labelledby","aria-valuenow","aria-valuemin","aria-valuemax"],alwaysUsefulAttributesForCssSelectorGeneration:["src","href","aria-describedby","aria-labelledby","aria-label"],stronglyIdentifyingAttributes:["aria-label","data-testid","id","name","href","aria-describedby","aria-labelledby","aria-description","data-row","data-col","data-row-index","data-col-index","for","aria-modal"],alwaysInterestingClassNames:["cm-line","cm-activeLine","cm-content"],alwaysInterestingClassPrefixes:["notion-",".w-"],alwaysInterestingTruthyPropertyNames:["contenteditable"],visualAttributesForSvgSerialization:["fill","stroke","color","patternContentUnits","xlink:href","transform","path","d","points","viewBox","preserveAspectRatio","r","rx","ry","cx","cy","x1","y1","x2","y2","font","text-anchor","dominant-baseline","gradient","pattern","stop-color"]};var LS="BoundingBoxMovedError",MS="ZeroOpacityError",ll="visual_actions",qn="data-momentic-id";function OS(t,e,n){if(t.length<n)return t;let r=t.indexOf(e);if(r===-1)return t;let o=Math.max(0,r-n/3),i=Math.min(r+n/3,t.length),a=t.indexOf(`
3889
- `,o);a>0&&a<r&&(o=a);let s=i,l=0;for(;l<1e3&&s>r&&t[s]!==`
3888
+ `};var qn={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center","notion-selectable","notion-page-block","notion-collection-item","MuiSvgIcon","css-","rt-"],nonDynamicInputTypes:["button","file","hidden","image","radio","reset","submit"],generalStateAttributes:["aria-expanded","aria-haspopup","aria-checked","aria-pressed","aria-selected","aria-invalid","checked","open","aria-busy"],bannedElementTagNames:["html","head","meta","script","style","path","br","::marker","noscript","polygon","defs"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts","data-ved","aria-controls","d"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","tooltip","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","contenteditable","data-value","data-testid","data-cy","data-pw","data-test-id","data-test","data-role","data-type","data-key","data-action","data-qa","data-aria-hidden","data-hidden","data-automation-id","data-overlay","data-content-editable-leaf","data-wf-icon","data-tns","data-sticky-stack-name","data-popup-origin","data-handleid","data-handlepos","data-col-index","data-row-index","data-row","data-col","col-index","row-index","row","col","data-momentic-description","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden","aria-describedby","aria-labelledby","aria-valuenow","aria-valuemin","aria-valuemax"],alwaysUsefulAttributesForCssSelectorGeneration:["src","href","aria-describedby","aria-labelledby","aria-label"],stronglyIdentifyingAttributes:["aria-label","data-testid","id","name","href","aria-describedby","aria-labelledby","aria-description","data-row","data-col","data-row-index","data-col-index","for","aria-modal"],alwaysInterestingClassNames:["cm-line","cm-activeLine","cm-content"],alwaysInterestingClassPrefixes:["notion-",".w-"],alwaysInterestingTruthyPropertyNames:["contenteditable"],visualAttributesForSvgSerialization:["fill","stroke","color","patternContentUnits","xlink:href","transform","path","d","points","viewBox","preserveAspectRatio","r","rx","ry","cx","cy","x1","y1","x2","y2","font","text-anchor","dominant-baseline","gradient","pattern","stop-color"]};var zS="BoundingBoxMovedError",HS="ZeroOpacityError",fl="visual_actions",Kn="data-momentic-id";function $S(t,e,n){if(t.length<n)return t;let r=t.indexOf(e);if(r===-1)return t;let o=Math.max(0,r-n/3),a=Math.min(r+n/3,t.length),i=t.indexOf(`
3889
+ `,o);i>0&&i<r&&(o=i);let s=a,l=0;for(;l<1e3&&s>r&&t[s]!==`
3890
3890
  `;)l++,s--;return s>r&&t[s]===`
3891
- `&&(i=s),t.slice(o,i)}function mn(t){let e=typeof t=="string"?t:t.toString();return`[${qn}="${e}"]`}import{execSync as jP}from"child_process";import{randomUUID as ky}from"crypto";import{diff as Eu}from"deep-object-diff";import{existsSync as bl,mkdirSync as GP,readFileSync as WP,writeFileSync as VP}from"fs";import{Jimp as _y}from"jimp";import qP from"js-beautify";import{cloneDeep as ga}from"lodash-es";import KP from"mime";import{homedir as Ru,hostname as YP,platform as XP}from"os";import{basename as JP,extname as QP,join as ci,resolve as ZP}from"path";import{chromium as Fy,devices as eL}from"playwright";import{addExtra as tL}from"playwright-extra";import nL from"puppeteer-extra-plugin-recaptcha";import{v4 as rL}from"uuid";import{rmSync as ey}from"fs";import{basename as GI,join as WI}from"path";import{errors as VI}from"playwright-core";var NS=new Set(["about:blank","chrome-error://chromewebdata/"]);var Zd=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],eu=1e4,pa=500;import{mkdirSync as wI,rmSync as kS,statSync as EI}from"fs";import*as ou from"node:fs";import CI from"nodejs-file-downloader";import{tmpdir as RI}from"os";import Sr,{basename as vI,dirname as AI}from"path";var iu="file://",ru=Sr.join(RI(),"momentic","downloads"),nu=1e4,xI=50*1024*1024;async function _S(t){let{uri:e}=t;return e.startsWith(iu)?PI(t):e.startsWith("http")?MI(t):LI(t)}function II(t,e){let n=Sr.join(ru,t,e.slice(iu.length)),r=Sr.join(ru,t),o=n.startsWith(r);if(!ou.existsSync(n)||!o)throw new A("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return n}async function PI({uri:t,orgId:e}){let n=II(e,t);return{filePath:n,cleanup:()=>{kS(AI(n),{recursive:!0,force:!0})}}}async function LI({uri:t}){let e=Sr.resolve(t);if(!ou.existsSync(e))throw new A("UserConfigurationError",`The referenced file (${t}) does not exist on disk. Please make sure that it has been downloaded successfully.`);return{filePath:e,cleanup:()=>{}}}async function MI({uri:t,logger:e,orgId:n}){let r=new URL(t);r.search&&(r.search="");let o=vI(r.href),i=su(o),a=Sr.extname(i);if(Yp.includes(a))throw new Error(`Downloading files with extension ${a} is not allowed.`);let s=au(n),l=new CI({url:t,fileName:i,directory:s,maxAttempts:2,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"},timeout:nu}),{downloadStatus:c,filePath:d}=await z(l.download(),{milliseconds:nu,message:`Download timed out after ${nu}ms`});if(c!=="COMPLETE")throw new Error(`Download ended in non-success status: ${c}`);if(!d)throw new Error("File path of successfully downloaded file was empty");let m=EI(d).size;if(m>xI)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:m,filePath:d,fileName:i},"Downloaded file to disk");let g;return{filePath:d,cleanup:()=>{clearTimeout(g),g=setTimeout(()=>kS(s,{recursive:!0,force:!0}),10*60*1e3)}}}function DS(t,e){return`${iu}${t}/${e}`}function au(t){let e=Math.random().toString(36).substring(4),n=Sr.join(ru,t,e);return wI(n,{recursive:!0}),n}function su(t){let e=Sr.extname(t),n=Sr.basename(t,e);return t=(n.length>100?n.slice(n.length-100):n)+e,t=t.trim().replaceAll(" ","_"),t}async function Kn(t,e){try{return await t.evaluate(r=>window.serializeElementOnlyWithText?.(r,{truncateToLength:500}),void 0,{timeout:1e3})}catch(n){e.debug({err:n},"Failed to get HTML from locator for Playwright error translation");return}}async function FS(t,e){let n=t.evaluate(async()=>{let i=window,a={};try{let s=await indexedDB.databases();for(let l of s){if(!l.name)continue;let c=await i.exportIdbToObject?.(l.name,l.version);c&&(a[l.name]=c)}return[a,void 0]}catch(s){return[void 0,s.message]}}),[r,o]=await z(n,{milliseconds:3e3});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),r}async function US(t,e,n){if(e){n.debug("Importing indexedDB data");try{let r=t.evaluate(async o=>{let i=window;for(let[a,s]of Object.entries(o))await i.importObjectToIdb?.(a,s)},e);await z(r,{milliseconds:3e3})}catch(r){n.warn({err:r},"Failed to import indexedDB data")}}}async function BS(t,e){try{let n=t.evaluate(async()=>{window.localStorage.clear(),window.sessionStorage.clear(),await indexedDB.databases().then(r=>{r.forEach(o=>{o.name&&indexedDB.deleteDatabase(o.name)})})});await z(n,{milliseconds:3e3})}catch(n){e.debug({err:n},"Failed clearing index db data, continuing...")}}async function zS(t,e,n,r,o){try{await OI(t,e,n,r)}catch(i){o.error({err:i,tabIndex:e},"Error handling new console log")}}async function OI(t,e,n,r){let o=r.text();o.length>pa&&(o=o.slice(0,pa)+"...(TRUNCATED)");let i=[];for(let a of r.args())try{let s=await a.jsonValue(),l=JSON.stringify(s);l.length>pa?i.push(l.slice(0,pa)+"...(TRUNCATED)"):(typeof s!="object"||Object.keys(s).length>0)&&i.push(s)}catch{}lu(t,n,e,{url:t.url(),location:r.location(),type:r.type(),text:r.text(),args:i})}function lu(t,e,n,r){let o=Date.now(),i=e.logsPerPage;if(i.length<=n||i[n]===void 0){i[n]=[];for(let a=0;a<n;a++)i[a]===void 0&&(i[a]=[])}i[n].length>eu&&(i[n]=i[n].slice(Math.floor(eu/2)),i[n]?.push({url:t.url(),timestamp:o,type:"warning",text:"[MOMENTIC] Truncated console logs due to buffer overflow",tabIndex:n})),i[n].push({...r,tabIndex:n,timestamp:o})}async function rn({fn:t,codePath:e,logObject:n,signal:r,logger:o}){r?.throwIfAborted();let i=Date.now(),a=await na({promiseGenerator:t,signal:r,codePath:e,logger:o}),s=Date.now();return n[e]=s-i,a}var NI="[redacted due to size]",kI=1e4;async function $S(t,e,n){let r=new Date().toISOString();e.harPages||(e.harPages={}),e.harPages[t]={id:t,startedDateTime:r,title:void 0,pageTimings:{}}}async function jS(t,e){let n=e.timing(),r=new URL(e.url()),o=[...r.searchParams.entries()].map(([s,l])=>({name:s,value:l})),i={...await WS(e),url:r.toString(),method:e.method(),queryString:o,postData:await DI(e)};return{pageref:t,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:i,timings:VS(n).timings}}async function GS(t,e,n){await n.finished();let r={};try{r=await FI(n)}catch{}let o={...await WS(n),status:n.status(),statusText:n.statusText(),content:r,redirectURL:n.headers().location};t.response=o;let i;try{i=await e.sizes(),t.request.bodySize=i.requestBodySize,t.request.headersSize=i.requestHeadersSize}catch{}t.response&&i&&(t.response.bodySize=i.responseBodySize,t.response.headersSize=i.responseHeadersSize,t.response.content.size=i.responseBodySize);let a=e.timing();t.startedDateTime=new Date(a.startTime).toISOString();let{timings:s,total:l}=VS(a);t.time=l,t.timings=s}function cu(t,e,n){t.harEntries||(t.harEntries={}),t.harEntries[n]=e}function HS(t){try{return new Date(t).toISOString()}catch{return}}function _I(t){let e={name:"",value:""},n=!0;for(let r of t.split(/; */)){let o=r.indexOf("="),i=o!==-1?r.substring(0,o).trim():r.trim(),a=o!==-1?r.substring(o+1,r.length).trim():"";if(n){n=!1,e.name=Ln(i),e.value=Ln(a);continue}i==="Domain"&&(e.domain=Ln(a)),i==="Expires"&&(e.expires=HS(a)),i==="HttpOnly"&&(e.httpOnly=!0),i==="Max-Age"&&(e.expires=HS(Date.now()+ +a*1e3)),i==="Path"&&(e.path=Ln(a)),i==="Secure"&&(e.secure=!0)}return e}async function WS(t){let e=await t.allHeaders(),n=e.cookie?.split(";").map(_I)??[];return{headers:Object.entries(e).map(([r,o])=>({name:Ln(r),value:Ln(o)})),cookies:n}}async function DI(t){let e=t.postData();if(!e)return;let n=await t.headerValue("content-type"),r={mimeType:n??"application/octet-stream",text:Ln(e),params:[]};if(n==="application/x-www-form-urlencoded"){let o=new URLSearchParams(e.toString());for(let[i,a]of o.entries())r.params.push({name:Ln(i),value:a?Ln(a):void 0})}return r}async function FI(t){return{mimeType:await t.headerValue("content-type")??void 0,text:Ln(await t.text()),encoding:await t.headerValue("content-encoding")??void 0}}function Ln(t){return t.length>kI?NI:t}function so(t){return t<0?0:t}function VS(t){return{timings:{blocked:so(t.domainLookupStart),dns:so(t.domainLookupEnd-t.domainLookupStart),connect:so(t.connectEnd-t.connectStart),send:so(t.responseStart-t.requestStart),wait:0,receive:so(t.responseEnd-t.responseStart),ssl:so(t.connectEnd-t.secureConnectionStart)},total:so(t.responseEnd)}}function qS(){return async t=>{let{fragment:e,code:n,context:r}=t,{env:o}=r||{},i=Object.getPrototypeOf(async function(){}).constructor;return{result:await Promise.resolve(new i("env",e?`return ${n}`:n)(o))}}}async function Qe({root:t,fn:e,arg:n,timeout:r,waitForPageLoad:o,codePath:i}){return await o(),await z(t.evaluate(e,n),{milliseconds:r,message:`Timed out ${i} after ${r}ms. This indicates that either the page is unresponsive or your machine is severely resource constrained.`})}function du(){return window.lastCursorPos}import{errors as UI}from"playwright-core";async function lo({func:t,action:e,logger:n,callbacks:r,retryTimeoutMs:o,targetingResult:i}){let a=Date.now(),s;for(;Date.now()-a<o;)try{return await t(i)}catch(l){let c=l;if(Hi(c)){n.warn("Attempting to recover from removed data-momentic-ids by re-adding ids to DOM");let[d]=await Promise.all([t(i),r.getBrowserState({skipWaitForPageLoad:!0,skipWait:!0})]);return d}else if(c instanceof UI.TimeoutError)n.warn({err:c,rootUrl:(await r.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),s=await BI(c,i.locator,r,n);else throw c}throw s instanceof A?s:new A("ActionFailureError",`Failed to interact with targeted element. Error: ${s.message}`,{errOptions:{cause:s}})}async function BI(t,e,n,r){return t.message.includes("attempt #")?zI(t,e,n,r):HI(t)}async function zI(t,e,n,r){let o=t.message.split(/- retrying \w+ action, attempt #\d+/).filter(l=>l.length>0);if(!o.length)return r.warn({err:t},"Failed to parse Playwright error message for translation, returning raw message"),t;let i=o.length>2?o[o.length-2]:o[0];i=i.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"").replaceAll(" - ","").trim().replaceAll(`
3892
- `,";").replace(/\s+/g," ");let a="",s=await Kn(e,r);if(s&&(a=`Target element HTML: ${He(s,100,!0)}`),i.includes("element is not enabled"))return new A("ActionFailureError",`The element you attempted to interact with was disabled for the entire timeout duration. Please explicitly wait for the element to be enabled, change the element description to target an interactive element, or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:t}});if(i.includes("intercepts pointer events")){let l="",c=i.match(/<.*?data-momentic-id="(\d+)".*?intercepts pointer events/)?.[1];if(c){let d=(await n.state.getRoot()).locator(mn(c)),u=await Kn(d,r);u&&(l=`Covering element HTML: ${He(u,100,!0)}`)}return new A("ActionFailureError",`The element you attempted to interact with was covered by another element such as dropdown, popup, or dialog for the entire timeout duration. Please add a step to hide the covering element or turn on the 'disable stability checks' option. ${a}
3893
- ${l}`,{errOptions:{cause:t}})}if(i.includes("element is not visible")){let l="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let c=await e.boundingBox({timeout:3e3});c?c.height===0?l="The element you attempted to interact with has zero height.":c.width===0&&(l="The element you attempted to interact with has zero width."):l="The element you attempted to interact with has no bounding box."}catch{}return new A("ActionFailureError",`${l} Please explicitly wait for the element to be visible or turn on the 'disable stability checks' option. ${a}`,{errOptions:{cause:t}})}return i.includes("element is outside of the viewport")?new A("ActionFailureError",`The element requested was outside of the browser viewport for the entire duration of the action. Please ensure you are not using non-standard zoom settings and the element is visible on the page. ${a}`):t}function HI(t){let e=t.message;if(e.includes("waiting for locator")&&e.includes("data-momentic-id")&&!e.match(/attempting \w+ action/)&&!e.includes("locator.evaluate"))throw new A("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:t}});return t}async function KS(t){try{return await $I(t)}catch(e){t.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function $I({locator:t,logger:e}){let[n,r]=await t.evaluate(l=>[l.id,l.tagName.toLowerCase()],{timeout:1e3}),o=await Kn(t,e),i=await t.boundingBox({timeout:1e3});if(i===null){e.warn({elementDisplayString:o},"Attempting to click on element with no bounding box, not performing Chakra redirection");return}if(i.width>5||i.height>5||r!=="input")return;if(n)try{let l=t.page().locator(`label[for=${JSON.stringify(n)}]`);return await l.waitFor({state:"visible",timeout:1e3}),{locator:l,relativePoint:void 0}}catch{}let a=await t.evaluate(l=>{let c=window,d=l.parentElement;if(!d)return{type:"error",error:"Input click target has no parent for redirection"};let u=l.getBoundingClientRect(),m=d.getBoundingClientRect();if(m.width===0||m.height===0)return{type:"error",error:"Parent element has no width or height"};let g={x:Math.min(Math.max(1,u.left-m.left),m.width-1),y:Math.min(Math.max(1,u.top-m.top),m.height-1)},p=c._MOMENTIC_FEATURE_FLAGS?.[ll],h=l.getAttribute(qn),f=!p&&h?mn(h):c.getMPath?.(l)?.join(" >");return f?{type:"result",selector:f,relativePoint:g,serializedForm:d.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:1e3});if(a.type==="error")throw new Error(a.error);let s=t.page().locator(a.selector);return await s.waitFor({state:"visible",timeout:1e3}),e.info({parentElementResult:a,originalElementDisplayString:o},`Redirected click to parent element with selector: ${a.selector}`),{locator:s,relativePoint:a.relativePoint}}var XS=["date","datetime-local","month","time","week"],YS={date:/^\d{4}-\d{2}-\d{2}$/,"datetime-local":/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/,month:/^\d{4}-\d{2}$/,time:/^\d{2}:\d{2}$/,week:/^\d{4}-W\d{2}$/};async function JS(t){try{await z(jI(t),{milliseconds:3e3})}catch(e){t.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function jI({root:t,text:e,options:n,logger:r,callbacks:o}){let i=(await Qe({root:t,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:1e3,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!YS[i])return;YS[i].test(e)&&r.warn(`Detected datetime input (${e}) in normalized format - this may fail to fill correctly as it is not how the user would input the value`),n.clearContent=!1,r.info("Transforming datetime input to use sequential key presses")}import{z as Dt}from"zod";var QS=Dt.object({doubleClick:Dt.boolean().optional(),rightClick:Dt.boolean().optional(),force:Dt.boolean().optional(),waitForDownload:Dt.boolean().optional(),delayMs:Dt.number().optional(),downloadTimeoutMs:Dt.number().optional(),relativePosition:Dt.object({x:Dt.number(),y:Dt.number()}).optional()}),mee=Dt.object({repeat:Dt.number().optional(),convertMeta:Dt.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Dt.number().optional()});async function cl({locator:t,callbacks:e,logger:n,timeoutMs:r=1e3}){try{await uu(e,r);let o=t.evaluate(i=>{let a=window;a.momenticIsEligible=u=>{let g=window.getComputedStyle(u,null).getPropertyValue("display");if(g==="none"||g==="contents")return!1;let p=u.getBoundingClientRect();return!(!p.height||!p.width)},a.removeHighlightTimers=a.removeHighlightTimers||[],a.removeHighlightFunctions=a.removeHighlightFunctions||{};let s=0;for(;!a.momenticIsEligible(i)&&s<3;){if(!i.parentElement)throw new Error("No eligible non-empty parent found for highlighting");i=i.parentElement,s++}let l=i.style.getPropertyValue("outline"),c=i.style.getPropertyPriority("outline");i.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let d=`momentic${Math.floor(Math.random()*1e7)}`;a[d]=()=>{i.style.removeProperty("outline"),i.style.setProperty("outline",l,c),i.getAttribute("style")||i.removeAttribute("style")},a.removeHighlightTimers.push(setTimeout(()=>{a[d](),a.removeHighlightFunctions?.[d]&&delete a.removeHighlightFunctions[d]},5e3)),a.removeHighlightFunctions[d]=a[d]},void 0,{timeout:r});return await z(o,{milliseconds:r}),!0}catch(o){return n.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function uu(t,e=1e3){let n=await t.state.getRoot();await Qe({root:n,fn:()=>{let o=window,i=o.removeHighlightTimers||[];for(;i.length;){let a=i.pop();clearTimeout(a)}Object.values(o.removeHighlightFunctions??{}).forEach(a=>{a()})},timeout:e,arg:void 0,waitForPageLoad:t.waitForPageLoad,codePath:"removing element highlights"})}async function mu(t){let e=!!t.browserCallbacks.state.userBrowserSettings.visualActions;return lo({action:"clicking element",targetingResult:t.targetingResult,logger:t.logger,retryTimeoutMs:t.retryTimeoutMs,callbacks:t.browserCallbacks,func:async n=>ty({...t,targetingResult:n,useVisualClick:e})})}async function qI(t,e){let{redirectionAttempts:n=0}=e;if(n>=2)throw t;try{return await KI(t,e)}catch(r){throw e.redirectionAttempts===0?(e.logger.error({redirectionAttemptError:r,originalError:t},"Error handling click error, rethrowing original error"),t):r}}async function KI(t,e){let{logger:n,redirectionAttempts:r=0}=e,o=e.targetingResult.locator;if(t.message.includes("label")&&t.message.includes("for=")&&t.message.includes("intercepts pointer events")){let i=await o.getAttribute("id",{timeout:1e3});if(!i)throw t;let a=o.page().locator(`[for=${JSON.stringify(i)}]`);return await a.waitFor({state:"visible",timeout:1e3}),n.warn({err:t},"Attempting locator redirection due to input being covered by label"),ty({...e,targetingResult:{locator:a},redirectionAttempts:r+1})}else throw n.error({err:t},"Click error does not match any known recoverable patterns, rethrowing"),t}async function YI(t){let{browserCallbacks:e,logger:n,targetingResult:r,position:o,options:i}=t,a=await e.state.getRoot(),s=a&&a!==r.locator.page()&&"frameElement"in a?await a.frameElement():null,l;try{l=s?await Qr({promiseGenerator:async()=>s.boundingBox(),timeoutMs:3e3,logger:n}):null}catch(p){throw new A("UserInfrastructureError",`The frame containing the element Momentic was instructed to interact with was removed. Error: ${p.message}`)}finally{await s?.dispose()}let c=Date.now(),{clickX:d,clickY:u,reason:m}=await QI({frameCoordinates:l,logger:n,targetingResult:r,position:o,options:i}),g=QS.safeParse(i);n.info({frameCoordinates:l,position:o,options:g.success?g.data:void 0,clickLocation:{clickX:d,clickY:u,reason:m},duration:Date.now()-c},"Visual click")}async function XI(t){let{actionSource:e,targetingResult:n,options:r,logger:o}=t,i=t.targetingResult.locator,a=r?.relativePosition??t.position;if(e==="click"&&!a){let l=await KS({locator:i,logger:o});l&&(i=l.locator,a=l.relativePoint??a)}let s=r?.force||n.hints?.force||!1;try{r?.doubleClick?await i.dblclick({button:r.rightClick?"right":"left",timeout:3e3,position:a,delay:r?.delayMs??25,force:s}):await i.click({button:r?.rightClick?"right":"left",timeout:3e3,position:a,delay:r?.delayMs??25,force:s})}catch(l){let c=l;if(eP(c))o.warn({err:c},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:c},"Error clicking on locator, attempting to recover..."),qI(c,{...t,targetingResult:{...i,locator:i}})}}async function ty(t){let{options:e,logger:n,browserCallbacks:r,controllerCallbacks:o,useVisualClick:i,targetingResult:a}=t,s;e?.waitForDownload&&(s=(async()=>{let l=e.downloadTimeoutMs??3e4;try{return await a.locator.page().waitForEvent("download",{timeout:l})}catch(c){return c instanceof VI.TimeoutError?new A("ActionFailureError",`Download did not complete in ${l}ms`):new A("ActionFailureError",`Download failed: ${c.message}`)}})());try{await cl({locator:a.locator,callbacks:r,logger:n,timeoutMs:1e3})}catch(l){n.warn({err:l},"Error highlighting locator in click, continuing...")}if(i?await YI(t):await XI(t),e?.waitForDownload)if(s){if(!o?.createIsolatedFolder)throw new A("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");n.info("Waiting for download to start and complete");let l=await z(s,{milliseconds:e.downloadTimeoutMs??3e4});if(l instanceof Error)throw l;return{downloadedFile:await ZI(l,o.createIsolatedFolder,n)}}else throw new Error("No download promise or error but the step requested to wait for a download")}async function JI(t,e){if(e.hints?.clickableXY){let i=(t?.x??0)+e.hints.clickableXY.x,a=(t?.y??0)+e.hints.clickableXY.y;return[{x:i,y:a},"targeting hint"]}let n=await e.locator.boundingBox({timeout:3e3});if(!n)throw new A("ActionFailureError","Element does not have a bounding box");let r=n.x+n.width/2,o=n.y+n.height/2;return[{x:r,y:o},"halfway point of the bounding box"]}async function QI({frameCoordinates:t,logger:e,options:n,targetingResult:r,position:o}){let i,a,s;if(o){let u=await r.locator.boundingBox({timeout:3e3});i=(t?.x??0)+(u?.x??0)+o.x,a=(t?.y??0)+(u?.y??0)+o.y,s="predefined position"}else{let[u,m]=await JI(t,r);i=u.x,a=u.y,s=m}let l=r.locator.page(),c=n?.rightClick?"right":"left",d=n?.delayMs??25;return n?.doubleClick?await l.mouse.dblclick(i,a,{button:c,delay:d}):await l.mouse.click(i,a,{button:c,delay:d}),{clickX:i,clickY:a,reason:s}}async function ZI(t,e,n){n.info("Download detected, saving file to disk");let r=await t.path(),o=su(t.suggestedFilename()),i=e();await t.saveAs(WI(i,o)),ey(r,{force:!0}),setTimeout(()=>{ey(i,{recursive:!0,force:!0})},5*60*1e3);let a=DS(GI(i),o);return n.info({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}function eP(t){return t.message.includes("locator.click: Timeout")&&t.message.includes("click action done")}import{platform as tP}from"os";var nP={goToNextWord:{win32:"Control+ArrowRight",darwin:"Alt+ArrowRight",linux:"Control+ArrowRight"},goToPreviousWord:{win32:"Control+ArrowLeft",darwin:"Alt+ArrowLeft",linux:"Control+ArrowLeft"},selectNextWord:{win32:"Control+Shift+ArrowRight",darwin:"Alt+Shift+ArrowRight",linux:"Control+Shift+ArrowRight"},selectPreviousWord:{win32:"Control+Shift+ArrowLeft",darwin:"Alt+Shift+ArrowLeft",linux:"Control+Shift+ArrowLeft"},selectToStartOfLine:{win32:"Shift+Home",darwin:"Meta+Shift+LeftArrow",linux:"Shift+Home"},selectToEndOfLine:{win32:"Shift+End",darwin:"Meta+Shift+RightArrow",linux:"Shift+End"},deleteNextWord:{win32:"Control+Delete",darwin:"Alt+Fn+Delete",linux:"Control+Delete"},deletePreviousWord:{win32:"Control+Backspace",darwin:"Alt+Delete",linux:"Control+Backspace"}};function rP(){let t=tP();return t==="win32"?"win32":t==="darwin"?"darwin":"linux"}function ny(t){return JSON.stringify(t.split("+").sort())}function dl(t){let e=rP(),n=ny(t);for(let r of Object.values(nP))if(Object.values(r).some(o=>ny(o)===n))return r[e];return process.platform==="darwin"?t=t.replaceAll("Control","Meta"):t=t.replaceAll("Meta","Control"),t}async function pu({frame:t,page:e,deltaX:n,directionX:r,deltaY:o,directionY:i,signal:a,callbacks:s,logger:l}){if(!n&&!o)return;let c=r==="left"?-1:1,d=i==="up"?-1:1;if(t)await Qe({root:t,fn:([u,m,g,p])=>window.scrollTo(window.scrollX+(u??window.innerWidth)*g,window.scrollY+(m??window.innerHeight)*p),arg:[n,o,c,d],waitForPageLoad:s.waitForPageLoad,timeout:2e3,codePath:"scrolling page"});else{let u=e.viewportSize()||Ot,m=await Qe({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:2e3,codePath:"computing page height"}),[g,p,h]=await Qe({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let S=f.getBoundingClientRect();return[f.scrollTop,S.x,S.y]},arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:2e3,codePath:"computing active element position"});await e.mouse.wheel((n??u.width)*c,(o??u.height)*d);try{let f=Date.now();for(;Date.now()-f<2e3;){a?.throwIfAborted();let S=await z(e.evaluate(()=>document.body.scrollHeight),{milliseconds:1e3}),[b,E,v]=await z(e.evaluate(()=>{let R=document.activeElement;if(!R)return[void 0,void 0,void 0];let C=R.getBoundingClientRect();return[R.scrollTop,C.x,C.y]}),{milliseconds:1e3});if(S===m&&b===g&&E===p&&v===h)break;m=S,g=b,p=E,h=v,await J(500)}}catch(f){l.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function gu(t,e){let n,r;for(let o=0;o<4;o++)try{return n=t.pages(),await Promise.all(n.map(async i=>{let a="";try{a=e?.getTitles?await i.title():""}catch{a="Unknown page"}return{title:a,url:i.url()}}))}catch(i){r=i,await J(500)}throw new Error(`Failed to get tab titles after all retries: ${r?.message}`)}import{randomUUID as mP}from"crypto";import{cloneDeep as fu}from"lodash-es";function yr(t,e){let n=t.findIndex(r=>r===e);if(!(n===-1||!t[n+1]))return t[n+1]}import{createHash as oP}from"crypto";var iP="v1";function ul(t,e){if(t.tagName.toLowerCase()==="svg"&&!sP(t))try{let n=ry(t,e),r=aP(JSON.stringify(n));return{version:iP,json:n,hash:r}}catch{return}}function aP(t){return oP("md5").update(t).digest("hex")}function ry(t,e){let n=t.tagName.toLowerCase(),r=lP(t);if(n==="image"&&r["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:n,props:r,children:[]};for(let i of t.childrenBackendIds){let a=e.backendIdToNode[i];if(a&&a.nodeType===1){let s=ry(a,e);s&&o.children.push(s)}}return o}function sP(t){let e=t.computedStyles.display,n=t.computedStyles.visibility,r=t.computedStyles.opacity;return e==="none"||n==="hidden"||r==="0"}function lP(t){let e={},n=t.attributes;for(let r of Object.keys(n))Vn.visualAttributesForSvgSerialization.includes(r)&&(e[r]=n[r]);return n.id&&t.tagName.toLowerCase()!=="svg"&&(e.id=n.id),e}var co={r:147,g:196,b:125,a:.55},iy={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:co,paddingColor:co,borderColor:co,marginColor:co,eventTargetColor:co,shapeColor:co,shapeMarginColor:co,showInfo:!0,showAccessibilityInfo:!0},ml=["display","opacity","visibility","height","position"];function ay({snapshot:t,devicePixelRatio:e,logger:n}){let r=t.strings,o=t.documents,i={},a={},s={roots:[],backendIdToNode:i,frameIndexToIframeNode:a};return o.forEach((l,c)=>{let d=cP({allDocuments:o,stringConstants:r,frameIndex:c,devicePixelRatio:e,backendIdToNode:i,frameIndexToIframeNode:a,logger:n});s.roots.push(d)}),s}function cP({allDocuments:t,stringConstants:e,devicePixelRatio:n,frameIndex:r,frameIndexToIframeNode:o,backendIdToNode:i,logger:a}){let s=t[r],l=s.layout,c={};l.nodeIndex.forEach((C,x)=>{c[C]=x});let d=l.styles,u=l.bounds??[],m=s.nodes,g=m.contentDocumentIndex??{index:[],value:[]},p=m.backendNodeId??[],h=m.attributes??[],f=m.parentIndex??[],S=m.nodeName??[],b=m.nodeType??[],E=m.pseudoType??{index:[],value:[]},v=m.inputChecked??{index:[]},R=e[s.frameId];for(let C=0;C<p.length;C++){let x=p[C],L=b[C],k=h[C]??[],N=f[C]!==void 0&&f[C]>=0?f[C]:void 0,V=N!==void 0?p[N]:void 0,P=V!==void 0?i[V]:void 0,G=E.index.indexOf(C),_=G!==-1?e[E.value[G]]:void 0,q=c[C],re;q?re=u[q]??[]:re=[];let se=S[C]!==void 0?e[S[C]]?.toLowerCase():void 0;if(!se){a.warn({backendNodeId:x,frameId:R,frameIndex:r,nodeBounds:re},"DOM node has no tag name");continue}let de={backendNodeId:x,psuedoType:_,nodeType:L,frameIndex:r,parentFrameId:R,ownedFrameId:void 0,bounds:{x:re[0]??null,y:re[1]??null,width:re[2]??null,height:re[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:V??null,tagName:se,parent:P??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};P&&P.childrenBackendIds.push(x);let wt=g.index.indexOf(C);if(wt!==-1){let pe=g.value[wt];o[pe]=de;let ie=t[pe]?.frameId;de.ownedFrameId=ie!==void 0?e[ie]:void 0}for(let pe of Object.keys(de.bounds)){let ie=pe;de.bounds[ie]!==null&&(de.bounds[ie]/=n)}let fn=q!==void 0?d[q]??[]:[];for(let pe=0;pe<fn.length&&!(pe>=ml.length);pe++){let ie=fn[pe];if(ie===void 0||isNaN(ie))continue;let ot=e[ie];if(ot===void 0)continue;let Pe=ml[pe];de.computedStyles[Pe]=ot}for(let pe=0;pe<k.length;pe+=2){let ie=k[pe],ot=k[pe+1];if(!ie||!ot)continue;let Pe=e[ie],kn=e[ot];!Pe||!kn||(de.attributes[Pe]=kn)}v.index.includes(C)&&(de.attributes.checked="true"),i[de.backendNodeId]=de}return i[p[0]]}function hu(t,e){if(t.mPathSelector)return t.mPathSelector;let n=t.parent,r;if(!n)r=t.tagName;else if(t.tagName==="body")r="body";else{let i=n.childrenBackendIds.filter(l=>e.backendIdToNode[l]?.nodeType===1&&!e.backendIdToNode[l]?.psuedoType).indexOf(t.backendNodeId),a=` > ${t.tagName}:nth-child(${i+1})`;r=`${hu(n,e)}${a}`}return t.mPathSelector=r,r}function oy(t,e){return t.parentBackendNodeId!==null?e.backendIdToNode[t.parentBackendNodeId]:t.frameIndex===0?void 0:e.frameIndexToIframeNode[t.frameIndex]}var dP=["html","#document","#document-fragment"];function sy({node:t,domGraph:e}){let n=[],r=t,o=oy(t,e);if(!o)return[t.tagName];let i=()=>{if(r=o,o=oy(o,e),!o&&r.frameIndex!==0)throw new Error("No parent node but not in main frame")},a=0;for(;o&&a<1e6;){if(a++,dP.includes(r.tagName)){i();continue}if(r.tagName==="body")n.push("body");else{let l=!1,c=1;for(let d=0;d<o.childrenBackendIds.length;d++){let u=o.childrenBackendIds[d],m=e.backendIdToNode[u];if(u===r.backendNodeId){n.push(`${r.tagName}:nth-child(${c})`),l=!0;break}else m?.nodeType===1&&!m.psuedoType&&c++}if(!l)throw new Error(`Could not find child (${r.tagName}) in parent's children list (${o.tagName})`)}i()}return n.reverse()}function ly(t,e){let n=t.locator("html"),r=[];for(let o=0;o<e.length;o++){let i=e[o];if(r.push(i),i.startsWith("iframe")){let a=r.join(" > ");r=[],o<e.length-1?n=n.frameLocator(a):n=n.locator(a)}}if(r.length&&(n=n.locator(r.join(" > "))),"owner"in n)throw new Error("Final locator from mpath is a frame locator");return n}async function cy(t,e){await t.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let n=await t.send({method:"DOM.requestNode",params:{objectId:e},timeout:2e3}),o=(await t.send({method:"DOM.getAttributes",params:{nodeId:n.nodeId},timeout:2e3})).attributes,i=yr(o,qn);if(!i)throw new Error(`Could not find attribute ${qn} for object ${e}`);return i}function dy(t){let e=[];for(let n=0;n<t.domGraph.roots.length;n++){let r=t.domGraph.roots[n],o=uP({root:r,domGraph:t.domGraph,existingHashes:t.existingHashes,flagStore:t.flagStore,logger:t.logger});e=e.concat(o)}return e}function uP(t){let{root:e,domGraph:n,existingHashes:r}=t,o=[],i=[e];for(;i.length;){let a=i.pop();if(a.nodeType===1&&a.tagName.toLowerCase()==="svg"){let s=ul(a,n);s&&!r[s.hash]&&o.push(s)}for(let s of a.childrenBackendIds){let l=n.backendIdToNode[s];l&&i.push(l)}}return o}var pP=["focusable","keyshortcuts","controls","live","relevant","orientation"],gP=["selected","readonly","modal","required","invalid"],hP=["id","name","role","content"],uy=["absolute","fixed","sticky"],fP=["path"],SP=["statictext","textbox","checkbox","combobox","iframe","rootwebarea","table","caption","columnheader","rowheader","gridcell","grid","row","rowgroup","cell","image","graphics-symbol","graphics-document","graphics-object","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch","tree","treeitem","separator"],gy=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],hy=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],yP=["menulistpopup","statictext","inlinetextbox"],bP=80,my=100,fy=50,pl=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],TP=["cite"],wP={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"],"graphics-symbol":["svg","rect"],gridcell:["td","th"],SvgRoot:["svg"],navigation:["nav"],cell:["td","th"],row:["tr"],list:["ul"],heading:["h1","h2","h3","h4","h5","h6"]},EP={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},py={indentLevel:0},Su=class t{id;role;name;nameSources;tagName;content;properties;internalProperties;ignoredReasons;dataMomenticId;pathFromRoot;parent;children;parentFrame;domNode;backendNodeId;ignoredByCDP;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.nameSources=e.nameSources,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeId=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,this.internalProperties=e.internalProperties??{},this.parentFrame=e.parentFrame,this.ignoredReasons=e.ignoredReasons,e.properties&&e.properties.forEach(n=>{n.name==="keyshortcuts"?this.dataMomenticId=parseInt(n.value.value):this.properties[n.name]=n.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let n=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(n&&n.length<fy?n:""),this.role=this.role||(e.domNode.attributes.role??""),AP(this.properties,e.domNode)}IP(this)}getSerializedFormWithContext(){return this.serialize({noId:!0,maxLevel:1,neighbors:1})}getNodeOnlySerializedForm(){return this.serialize({noId:!0,noChildren:!0,noContent:!0})}getLogForm(){return JSON.stringify({id:this.id,name:this.name??"",role:this.role??"",backendNodeId:this.backendNodeId})}isInteresting(){if(this.domNode&&fP.includes(this.domNode.tagName))return!1;if(SP.includes(this.role.toLowerCase()))return!0;if(this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>hy.includes(n)))return!1;if(this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||Vn.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let e=this.properties.class;return typeof e=="string"&&e.split(" ").some(n=>Ty(n))?!0:this.children.every(n=>n.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(n=>n.role==="StaticText")||this.children.length>1&&this.children.some(n=>n.tagName==="input")?!0:this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height)?!1:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(n=>n.startsWith("data"))}serialize(e=py){let n=Object.assign({},py,e),{indentLevel:r,noChildren:o,noProperties:i,noId:a,noContent:s,condensedMode:l}=n,c=fu(this.properties),d=" ".repeat(r),u=this.role||"",m=this.tagName??"unknown",g=this.name;u==="heading"&&g==="heading"&&(g=""),this.nameSources?.find(R=>!R.superseded&&R.type==="contents")&&this.children.length>0&&(g="");let h=this.nameSources?.find(R=>!R.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let R=h.attributeValue?.relatedNodes??[];R.length===1&&R[0].text&&R[0].text===g&&(g="")}let f=pl.includes(this.role)||TP.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${d}${g}
3894
- `;let S=`${d}<${m}`;!a&&!f&&(S+=` id="${this.id}"`);let b=s??!1;(c.multiline||c.contenteditable)&&this.children.length>0&&(b=!0),u&&u!=="generic"&&u!==m&&!(wP[u]??[]).includes(m)&&(S+=` role=${JSON.stringify(u)}`),g&&(S+=` name=${JSON.stringify(g)}`),this.content&&!b&&(S+=` content=${JSON.stringify(this.content)}`);let E=Date.now();if(Object.keys(c).length>0&&!i){if(Date.now()-E>1e3)throw new Error(`Serialization for the HTML element with tag ${m} and internal ID ${this.id} took too long. Please ensure your machine has enough resources to run Momentic.`);Object.entries(c).forEach(([R,C])=>{if(!pP.includes(R)){{if(gP.includes(R)&&(!C||C==="false"))return;if(R==="value"&&b&&(c.type==="text"||this.role==="textbox"))return;if(R==="level"&&`${C}`=="1")return;if(R==="url"&&c.src&&m==="img")return;if(R==="url"&&c.href&&m==="a")return;if(R==="editable"&&C==="plaintext")return;if(R==="type"&&C===m)return;if(l&&!EP[R])return}typeof C=="string"?S+=` ${R}="${He(C,my,!0)}"`:typeof C=="boolean"?C?S+=` ${R}`:S+=` ${R}={false}`:typeof C<"u"&&(S+=` ${R}={${He(JSON.stringify(C),my,!0)}}`)}})}if(m==="::before"||m==="::after"){let R="";for(let C of this.children)R+=C.serialize({...e,indentLevel:r,neighbors:0});return R}let v=e.maxLevel!==void 0&&r/2>=e.maxLevel;if(this.children.length===0||o||v)S+=` />
3895
- `;else{let R="";for(let x of this.children)R+=x.serialize({...e,indentLevel:r+2,neighbors:0});let C=R.trim();C.length<=bP&&!C.includes(`
3896
- `)?S+=`>${C}</${m}>
3897
- `:S+=`>
3898
- ${R}${d}</${m}>
3899
- `}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let R=this.parent.children.findIndex(L=>L.id===this.id),C=R>0?this.parent.children[R-1]?.serialize({...e,neighbors:0}):"",x=R<this.parent.children.length-1?this.parent.children[R+1]?.serialize({...e,neighbors:0}):"";return`${C||""}
3900
- ${S}
3901
- ${x||""}`}return S}shallowClone(){let e=new t({id:this.id,role:this.role,name:this.name,nameSources:this.nameSources,content:this.content,properties:[],pathFromRoot:this.pathFromRoot,children:[],ignoredReasons:this.ignoredReasons,backendNodeID:this.backendNodeId,ignoredByCDP:this.ignoredByCDP,internalProperties:fu(this.internalProperties),parentFrame:this.parentFrame});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=fu(this.properties),e}},yu=class t{constructor(e,n,r,o){this.root=e;this.a11yIdNodeMap=n;this.dataMomenticIdMap=r;this.selectorToNodeMap=o}serialize(e){return this.root.serialize(e)}pruneUsingRelevantIds(e){let n=this.root;if(!n)throw new Error("Cannot prune a11y tree with no root");function r(i,a=!1){let s=e.has(`${i.id}`)||i.id===n?.id,l=i.shallowClone(),c=i.children,d=!1,u=[];for(let m of c){let g=r(m,s||d);g&&(u.push(g),g.parent=l,d=!0)}if(l.children=u,s||d)return l;if(pl.includes(i.role)&&a)return l}let o=r(n);return new t(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function CP(t){return t.name?.value?`"${t.name.value}"`:t.role?.value&&t.role.value!=="none"&&t.role.value!=="generic"?`"${t.role.value}"`:`"${t.nodeId}"`}function RP(t,e,n,r){return t.bounds.x===null||t.bounds.y===null||t.bounds.height===null||t.bounds.width===null||t.bounds.width===0||t.bounds.height===0?!0:t.bounds.x+t.bounds.width<e.leftBound||t.bounds.x>e.rightBound?(Ts({logger:n,logKey:r,maxCount:5,intervalMs:3e3},{domNode:t,logKey:r},"Filtering out node since it is not in the viewport horizontally"),!1):t.bounds.y+t.bounds.height<e.upperBound||t.bounds.y>e.lowerBound?(Ts({logger:n,logKey:r,maxCount:5,intervalMs:3e3},{domNode:t,logKey:r},"Filtering out node since it is not in the viewport vertically"),!1):t.computedStyles.display==="none"?(n.debug({domNode:t},"Filtering out node since it has display none"),!1):!0}async function Sy({node:t,parent:e,frameId:n,frameContext:r,axGraph:o,domGraph:i,inputNodeMap:a,showZeroOpacityElements:s,filterByViewport:l,viewportDetails:c,useMPaths:d,cdpClient:u,logger:m,callId:g}){if(!e&&t.parentId)throw new Error(`Got no parent for accessibility node ${t.nodeId}: ${JSON.stringify(t)}`);let p=(P,G={})=>{},h=t.backendDOMNodeId,f=yP.includes((t.role?.value).toLowerCase());if(!f&&h===void 0)return p("Filtering out node since it doesn't exist in the DOM"),[];let S=h?i.backendIdToNode[h]:void 0;if(!f&&!S)try{let P=await z(u.send({method:"DOM.describeNode",params:{backendNodeId:h}}),{milliseconds:750,fallback:()=>{m.debug("Timeout getting node from CDP while processing a11y tree")}});if(P&&P.node.nodeName.toLowerCase()==="slot"&&P.node.distributedNodes?.length)m.debug({redirectedDomNode:S,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:t,cdpResult:P},"Redirecting node to assigned slot");else return p("Filtering out node since it doesn't exist in the DOM",{cdpResult:P}),[]}catch(P){return p("Filtering out node since it doesn't exist in the DOM",{err:P}),[]}if(S&&e&&l&&c&&t.backendDOMNodeId&&!RP(S,c,m,g))return S.momenticIgnored=!0,[];if(S&&S.computedStyles.display==="none")return S.momenticIgnored=!0,[];if(S&&S.computedStyles.opacity==="0"&&s!==!0){if(s==="inputs-only"&&S.tagName.toLowerCase()!=="input")return S.momenticIgnored=!0,[];if(s===!1)return S.momenticIgnored=!0,[]}let b=t.name?.value?typeof t.name.value=="string"?t.name.value:`${t.name.value}`:"",E=t.value?.value?typeof t.value.value=="string"?t.value.value:`${t.value.value}`:"",v=new Su({domNode:S,id:parseInt(t.nodeId),role:t.role?.value||"",name:b,nameSources:t.name?.sources,content:E,properties:t.properties,children:[],ignoredReasons:t.ignoredReasons?.filter(P=>gy.includes(P.name)||hy.includes(P.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+CP(t),backendNodeID:t.backendDOMNodeId,ignoredByCDP:t.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},parentFrame:r.type==="root"?void 0:r}),R=r,C=a[n],x=n;if(S?.tagName.toLowerCase()==="iframe"&&S.ownedFrameId){let P=r.childFrames.find(q=>q.frameId===S.ownedFrameId),G=o[P?.frameId??""]?.root,_=a[P?.frameId??""];if(P&&G&&_){t.childIds&&t.childIds.length>0&&m.debug("Replacing existing node's children with children from the iframe");let q=G;t.childIds=q.childIds,R=P,C=_,x=P.frameId}}let L=S?.childrenBackendIds?.length??0,k=(t.childIds??[]).filter(P=>!!C.get(parseInt(P))).length;if(L>k){let P=t.childIds?.map(_=>C.get(parseInt(_))).filter(Boolean).map(_=>_?.backendDOMNodeId).filter(_=>_!==void 0)??[],G=0;for(let _ of S?.childrenBackendIds??[]){if(P.includes(_)){G=(t.childIds?.findIndex(wt=>C.get(parseInt(wt))?.backendDOMNodeId===_)??0)+1;continue}let q=i.backendIdToNode[_];if(!q||q?.tagName.toLowerCase()!=="svg")continue;let re=Math.floor(-1*Math.random()*1e7),se={nodeId:re.toString(),parentId:t.nodeId,ignored:!1,backendDOMNodeId:_,frameId:x,role:{type:"string",value:"graphics-symbol"}};C.set(re,se),t.childIds||(t.childIds=[]),t.childIds.splice(G,0,re.toString()),G++}}for(let P of t.childIds??[]){if(!P)continue;let G=C.get(parseInt(P));if(!G)continue;let _=await Sy({node:G,parent:v,domGraph:i,axGraph:o,frameId:x,frameContext:R,inputNodeMap:a,cdpClient:u,logger:m,callId:g,filterByViewport:l,showZeroOpacityElements:s,viewportDetails:c,useMPaths:d});_.length&&(v.children=v.children.concat(_))}if(v.role==="StaticText"&&(v.children=[]),v.children.length===1&&v.children[0].role==="StaticText"){let P=v.name,G=v.children[0]?.name;(P===G||!G)&&(v.children=[])}let N=[];for(let P=v.children.length-1;P>=0;P--){let G=v.children[P];if(G.role!=="StaticText"){N.push(G);continue}if(P===0||v.children[P-1].role!=="StaticText"){N.push(G);continue}v.children[P-1].name+=G.name}if(v.children=N.reverse(),v.role==="generic"&&v.children.length===1){let P=v.children[0];if(v.name&&!pl.includes(P.role)&&v.name===P.name)return S&&(S.momenticIgnored=!0),v.children}if(!v.isInteresting()&&t.parentId)return S&&(S.momenticIgnored=!0),v.children;for(let P of v.children)P.parent=v;return xP(v),S&&d&&hu(S,i),[v]}function yy({node:t,a11yIdNodeMap:e,dataMomenticIdMap:n,logger:r,callId:o,domGraph:i,useMPaths:a,selectorToNodeMap:s,iconKnowledgeBase:l,startId:c=1}){t.id=c,c+=1,e[t.id]=t,t.dataMomenticId?n[t.dataMomenticId]=t:pl.includes(t.role);let d=t.backendNodeId,u=d!==void 0?i.backendIdToNode[d]:void 0;if(a&&u&&u.mPathSelector&&(s[u.mPathSelector]=t),l&&u&&u.tagName?.toLowerCase()==="svg"){let m=ul(u,i),g=m?l[m.hash]:void 0,p=g?g.description:void 0;g&&(t.properties["data-momentic-description"]=p)}for(let m of t.children)c=yy({node:m,a11yIdNodeMap:e,dataMomenticIdMap:n,logger:r,callId:o,startId:c,useMPaths:a,domGraph:i,selectorToNodeMap:s,iconKnowledgeBase:l});return c}async function by({rawA11yGraph:t,domGraph:e,startingFrameId:n,logger:r,cdpClient:o,filterByViewport:i,showZeroOpacityElements:a,viewportDetails:s,useMPaths:l,frameContext:c,iconKnowledgeBase:d}){let u=n??"root",m=t[u]?.root;if(!m)throw new Error("A11y tree has no root");let g=mP(),p=v=>{let R=v.allNodes.filter(x=>!x.ignoredReasons?.find(k=>gy.includes(k.name))),C=new Map;return R.forEach(x=>{C.set(parseInt(x.nodeId),x)}),C},h={};Object.entries(t).forEach(([v,R])=>{h[v]=p(R)});let f=await Sy({node:m,domGraph:e,parent:null,inputNodeMap:h,axGraph:t,frameId:u,frameContext:c,cdpClient:o,logger:r,callId:g,showZeroOpacityElements:a,filterByViewport:i,viewportDetails:s,useMPaths:l});if(f.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(f)}`);if(f.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let S={},b={},E={};return yy({node:f[0],a11yIdNodeMap:S,dataMomenticIdMap:b,selectorToNodeMap:E,domGraph:e,logger:r,callId:g,useMPaths:l,iconKnowledgeBase:d}),new yu(f[0],S,b,E)}function vP(t,e,n){if(t==="class"){if(n.tagName?.toLowerCase()==="svg")return e.split(" ").filter(i=>i.length<fy&&!Vn.bannedClassSubstrings.some(a=>i.includes(a))).slice(0,3).join(" ");let r=e.split(" "),o=[];for(let i of r)if(Ty(i)){o.push(i);continue}return o.length?o.join(" "):null}if(e==="true")return!0;if(e==="false")return!1;try{let r=parseInt(e);if(!isNaN(r))return r}catch{}return t==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e.length>60?e.slice(0,50)+"...":e}function AP(t,e){if(!e)return;Object.entries(e.attributes).forEach(([i,a])=>{if(Vn.relevantElementAttributes.includes(i)&&!hP.includes(i)&&!t[i]&&!i.startsWith("aria")){let s=vP(i,a,e);s!==null&&(t[i]=s)}});let n,r=[];if(e.computedStyles.position&&uy.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let i of uy)if(e.attributes.style.includes(`position: ${i}`)){n=i;break}}n&&r.push(`position: ${n}`);let o;e.computedStyles.opacity&&e.computedStyles.opacity==="0"&&(o="opacity: 0"),o&&r.push(o),r.length>0&&(t.style=r.join("; "))}function xP(t){let e=t.properties.class;if(typeof e=="string"&&e.includes("cm-content")){t.children.forEach((i,a)=>{i.properties["cm-line-number"]=`${a+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){t.children.forEach((i,a)=>{i.properties["block-number"]=`${a+1}`}),t.children.length>0&&(t.children[t.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(t.tagName==="table"){let i=[],a=t.children.find(l=>l.tagName==="thead");if(a){let l=a.children.find(c=>c.tagName==="tr");if(l){let c=l.children.filter(d=>d.tagName==="th");c.forEach((d,u)=>{d.properties["col-index"]||(d.properties["col-index"]=u+1),i?.push(He(d.name,100,!1))}),i?.length!==c.length&&(i=void 0)}}let s=0;for(let l of t.children)if(l.tagName==="tbody")for(let c=0;c<l.children.length;c++){let d=l.children[c];if(d.tagName!=="tr")continue;if(c===0&&!i?.length){let g=d.children.filter(p=>p.tagName==="th");if(g.length){if(i=g.map(p=>He(p.name,100,!1)),i.length===g.length)continue;i=void 0}}s+=1,d.properties["row-index"]||(d.properties["row-index"]=s);let u=d.children.filter(g=>g.tagName==="td"||g.tagName==="th"),m=u.length===i?.length;u.forEach((g,p)=>{g.tagName!=="th"&&(g.properties["col-index"]||(g.properties["col-index"]=p+1),m&&(g.properties.col||(g.properties.col=i[p])))})}}}function IP(t){let e=t.properties.class,n=typeof e=="string"&&e.includes("cm-content");t.internalProperties.inCodeMirrorEditor=t.internalProperties?.inCodeMirrorEditor||n}function Ty(t){if(Vn.bannedClassSubstrings.some(e=>t.includes(e)))return!1;if(Vn.alwaysInterestingClassNames.includes(t))return!0;for(let e of Vn.alwaysInterestingClassPrefixes)if(t.startsWith(e))return!0;return!1}var gl=class t{constructor(e,n,r,o,i){this.session=e;this.logger=n;this.contextGetter=r;this.pageGetter=o;this.defaultTimeoutMs=i}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;loadEventLogs=[];static async init({logger:e,contextGetter:n,pageGetter:r,defaultTimeoutMs:o}){let i=n(),a=r(),s,l;for(let d=0;d<2;d++)try{s=await z(i.newCDPSession(a),{milliseconds:o*d,fallback:()=>{throw new A("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${a.url()})`)}});break}catch(u){await J(500),l=u}if(!s)throw l;let c=new t(s,e,n,r,o);try{await z(c.registerHandlers(s),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(d){throw c.cdpFullyDead=!0,new A("UserInfrastructureError",`Failed to initialize CDP client: ${d}`)}return c}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(n){this.logger.warn({err:n},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",n=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(n)},this.logger.error({payload:n},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",n=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(n)},this.logger.error({payload:n},"CDP inspector session crashed, Momentic will likely not function correctly")}),e.on("Page.frameRequestedNavigation",n=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Frame requested navigation: ${JSON.stringify(n)}`)}),e.on("Page.navigatedWithinDocument",n=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Navigated within document: ${JSON.stringify(n)}`)}),e.on("Page.lifecycleEvent",n=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page lifecycle event: ${JSON.stringify(n)}`)}),e.on("Page.loadEventFired",()=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page load event fired`)}),await e.send("Accessibility.enable"),await e.send("Page.enable"),await e.send("DOM.enable"),await e.send("Overlay.enable"),await e.send("DOMSnapshot.enable"),await e.send("CSS.enable")}async send({method:e,params:n,timeout:r=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await z(this.cdpInitializingPromise,{milliseconds:r});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new A("UserInfrastructureError",`The browser inspector session encountered a critical crash: ${JSON.stringify(this.cdpCrashDetails)}`);this.logger.warn(`Detected crashed CDP client before method ${e}, reinitializing before proceeding...`),await this.reinitialize()}try{return await z(this.session.send(e,n),{milliseconds:r,message:o??`Chrome command ${e} timed out after ${r}ms. This is likely an infrastructure issue caused by a lack of compute resources or a crash at the browser level.`})}catch(i){throw["Internal error","Target crashed"].some(a=>i.message.includes(a))&&!this.cdpInitializingPromise&&(this.logger.warn({err:i},`CDP crashed during CDP method ${e}, re-initializing client`),await this.reinitialize()),i}}async createRawCDPSession(e=this.defaultTimeoutMs){let n=e,r=this.pageGetter(),o=await z(this.contextGetter().newCDPSession(r),{milliseconds:n,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${r.url()})`),new A("UserInfrastructureError",`Failed to initialize CDP session within the page load timeout (${r.url()})`)}});return this.logger.debug(`Created new CDP session for ${r.url()}`),o}async reinitialize(e=this.defaultTimeoutMs){await this.cdpInitializingPromise,this.cdpInitializingPromise=(async()=>{try{let n=this.session;this.session=await this.createRawCDPSession(e),await z(this.registerHandlers(this.session),{milliseconds:e,message:`Failed to register CDP handlers within ${e}ms`}),this.logger.debug("Successfully reinitialized and attached new handlers to CDP session");try{await z(n.detach(),{milliseconds:1e3})}catch(r){this.logger.warn({err:r},"Failed to detach old CDP session after reinitialization, continuing...")}this.cdpCrashDetails=void 0,this.cdpFullyDead=!1}catch(n){this.cdpCrashDetails={...this.cdpCrashDetails??{},reinitializeError:`${n}`},this.cdpFullyDead=!0}finally{this.cdpInitializingPromise=void 0}})(),await this.cdpInitializingPromise}on(e,n){return this.session.on(e,n),this.session}off(e,n){return this.session.off(e,n),this.session}addListener(e,n){return this.session.addListener(e,n),this.session}removeListener(e,n){return this.session.removeListener(e,n),this.session}};var si="<empty>";function PP(t){return t.includes("doubleclick.net")||t.includes("googletagmanager.com")||t.includes("googlesyndication.com")||t.includes("s.amazon-adsystem.com")||t.includes("smartadserver.com")||t.includes("omnitagjs.com")||t.includes("x.adroll.com")}function Ey(t){let e=t.adFrameStatus?.adFrameType;return e==="child"||e==="root"||PP(t.url)}async function LP(t,e){let n=await t.send({timeout:3e3,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await t.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[n.backendNodeId]}})).nodeIds[0],a=(await t.send({timeout:3e3,method:"DOM.describeNode",params:{backendNodeId:n.backendNodeId}})).node;return a.nodeId=o,a}async function li({cdpClient:t,page:e,logger:n}){let r={type:"root",childFrames:[],page:e},o=[],[i,a]=await Promise.all([t.send({timeout:3e3,method:"Page.getFrameTree",params:{}}),t.send({timeout:3e3,method:"DOM.getDocument",params:{depth:0}})]),c=(i.frameTree.childFrames??[]).map(async(u,m)=>{if(Ey(u.frame))return null;try{return await Cy({cdpClient:t,rawFrameTree:u,indices:[m],parent:r,warnings:o,logger:n})}catch(g){return o.push(`Failed to get child frame: ${g}`),null}}),d=await Promise.all(c);return r.childFrames=d.filter(u=>u!==null),o.length&&n?.warn({warnings:o},"Got warnings when fetching frame tree"),r}async function Cy({cdpClient:t,rawFrameTree:e,indices:n,parent:r,warnings:o,logger:i}){let a=e.frame.id,s=await LP(t,a),l=s.attributes??[],c=null,d=[];for(let p of["src","name","id","title","srcdoc","sandbox"]){let h=yr(l,p);h&&(d.push(`${p}=${JSON.stringify(h)}`),p==="src"&&(c=h))}let u={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:a,locationData:{indices:n,attributeSelectors:d},src:c,childFrames:[],parent:r,domNode:s},g=(e.childFrames??[]).map(async(p,h)=>{if(Ey(p.frame))return null;try{return await Cy({cdpClient:t,rawFrameTree:p,indices:[...n,h],parent:u,warnings:o,logger:i})}catch(f){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${f}`),null}});return u.childFrames=(await Promise.all(g)).filter(p=>p!==null),u}async function MP(t){try{return await t.owner().count()===1}catch{return!1}}async function OP(t){try{return await t.count()===1}catch{return!1}}async function Mn(t,e){let n=[],r=t;for(;r.parent.type==="frame";)n.push(r.parent),r=r.parent;n.reverse();let o=e,i=[];for(let c of n){let d=!1;for(let u of[...c.locationData.attributeSelectors,si]){let m=o.frameLocator(u===si?"iframe":`iframe[${u}]`);if(await MP(m)){d=!0,o=m,i.push(u);break}}if(!d)throw new A("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${c.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let a;for(let c of[...t.locationData.attributeSelectors,si]){let d=o.locator(c===si?"iframe":`iframe[${c}]`);if(await OP(d)){a=d,i.push(c);break}}if(!a)throw new A("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${t.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let s=await a.evaluateHandle(c=>c,{timeout:1e3}),l=await s.asElement().contentFrame();if(!l)throw new A("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${t.url}'`);return await s.dispose(),{frame:l,mPathSelectorTokens:i}}function wy(t,e){let n=[...t],r=[];for(;n.length;){let o=n.shift();e(o)&&r.push(o),n.push(...o.childFrames)}return r}async function Ry({page:t,frameTree:e,cache:n}){let r,o=e.childFrames,i=[];if(n.mPathSelectorTokens.length){let s=o;for(let d=0;d<n.mPathSelectorTokens.length-1;d++){let u=n.mPathSelectorTokens[d];u===si?s=s.length===1?s[0].childFrames:[]:s=s.filter(m=>m.locationData.attributeSelectors.includes(u)).map(m=>m.childFrames).flat()}let l=[],c=n.mPathSelectorTokens[n.mPathSelectorTokens.length-1];if(c===si?l=s:l=s.filter(d=>d.locationData.attributeSelectors.includes(c)),l.length===1)return r=l[0],i.push(`Found unique frame with mpath ${n.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await Mn(r,t)).frame,handle:r,mPathSelectorTokens:n.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${l.length} frames with mpath ${n.mPathSelectorTokens.join(" > ")}`)}if(n.frameSrcRegex){let s=new RegExp(n.frameSrcRegex),l=wy(o,c=>!!c.src&&s.test(c.src));if(l.length===1)return r=l[0],i.push(`Found unique frame with src regex ${n.frameSrcRegex}`),{resolution:{type:"auto",frame:(await Mn(r,t)).frame,handle:r,mPathSelectorTokens:n.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${l.length} frames with src regex ${n.frameSrcRegex}`),n.frameSrcRegex=void 0}if(n.frameUrlRegex){let s=new RegExp(n.frameUrlRegex),l=wy(o,c=>!!c.url&&s.test(c.url));if(l.length===1)return r=l[0],i.push(`Found unique frame with url regex ${n.frameUrlRegex}`),{resolution:{type:"auto",frame:(await Mn(r,t)).frame,handle:r,mPathSelectorTokens:n.mPathSelectorTokens,frameTree:e},logs:i};i.push(`Found ${l.length} frames with url regex ${n.frameUrlRegex}`),n.frameUrlRegex=void 0}let a=o;for(let s=0;s<n.indices.length-1;s++)a=a[n.indices[s]]?.childFrames??[];if(r=a[n.indices[n.indices.length-1]],r)return i.push(`Found unique frame with indices ${n.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await Mn(r,t)).frame,handle:r,mPathSelectorTokens:n.mPathSelectorTokens,frameTree:e},logs:i};throw i.push(`Found ${a.length} frames with indices ${n.indices}`),new wn("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:i}])}function hl(t){return t.type==="auto"?JSON.stringify({type:"auto",frameId:t.handle.frameId}):JSON.stringify(t)}function bu(t){for(;t.parent.type==="frame";)t=t.parent;return t.parent}function vy(t){let e=bu(t),n=t.src??"",r=t.url??"",o=[],i=[],a=[...e.childFrames];for(;a.length;){let s=a.shift();s.src&&o.push(s.src),s.url&&i.push(s.url),a.push(...s.childFrames)}return{srcs:o,urls:i,desiredSrc:n,desiredUrl:r}}function Ay(t){return t.type==="auto"?{type:"auto",frameId:t.handle.frameId,url:t.handle.url,src:t.handle.src??"",mPathSelectorTokens:t.mPathSelectorTokens.join(" > ")}:{type:"url",url:t.url}}async function xy({frame:t,logger:e,signal:n}){let r;try{r=await t.frameElement(),await NP({frameElementHandle:r,logger:e,signal:n})}catch(o){e.warn({err:o},"Failed to scroll iframe into view, continuing...")}finally{await r?.dispose()}}async function NP({frameElementHandle:t,logger:e,signal:n}){let r=await t.boundingBox();if(!r){e.warn("Active frame element has null bounding box, skipping scroll");return}await Qr({promiseGenerator:async()=>t.evaluate(async(i,{x:a,y:s})=>{window.scrollTo(window.scrollX+a,window.scrollY+s);let l=Date.now(),c,d,u;for(;Date.now()-l<1500;){let m=document.activeElement,g,p,h;if(!m)g=void 0,p=void 0,h=void 0;else{let f=m.getBoundingClientRect();g=m.scrollTop,p=f.x,h=f.y}if(c!==void 0&&d!==void 0&&u!==void 0&&g===c&&p===d&&h===u)break;c=g,d=p,u=h,await new Promise(f=>setTimeout(f,250))}},r),timeoutMs:2e3,codePath:"scrollIframeIntoView",signal:n}),e.info({bb:r},"Successfully scrolled iframe into view")}async function Iy({event:t,transformer:e,enricher:n,frame:r,lastScreenshotForRecording:o,logger:i}){let{warnings:a,error:s,properties:l}=t.target;if(s){i.error({error:s,warnings:a},"Error while capturing passive click");return}if(a.length&&i.warn({warnings:a},"Warnings while capturing passive click"),!l)return;let c=r.parentFrame()?r.url():void 0,u=r.page().frames().map(p=>p.url());i.debug({frameUrl:c,...t},"Passive click event captured on element");let m,g;if(c)try{let p=await r.frameElement();m=await z(p?.boundingBox(),{milliseconds:3e3})??void 0;let h=await n.constructIframeRegex({urls:u,srcs:[],desiredUrl:c});if(h.urlRegex)g={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(p){i.warn({err:p},"Failed to construct iframe details for recorded action, using hardcoded URL only"),g={type:"url",url:c}}(async()=>{try{await e.recordElementAction({...t,screenshotBase64:o,frameConfig:g,frameBoundingBox:m})}catch(p){i.error({err:p},"Failed to transform passive click action")}})()}import{randomUUID as On}from"crypto";import kP from"js-beautify";var _P=["Dead"],fl=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:n,generator:r,testId:o,orgId:i,logger:a}){this.signal=e,this.logger=a,this.testId=o,this.orgId=i,this.callbacks={onStepRecorded:(s,l)=>{this.recordedSteps.set(l,{step:s}),n.onStepRecorded(s,l)},onActionReceived:(s,l)=>{this.recordedSteps.set(l,{step:s}),n.onActionReceived?.(s,l)}},this.generator=r}reserveIndexForCommand(e){let n=this.nextStepOffset;return this.recordedSteps.set(n,{step:{id:On(),type:"PRESET_ACTION",command:Fn(e)}}),this.nextStepOffset++,n}async recordElementAction(e){let{type:n,target:r,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let i,a,s=r.properties.attributes.nodeOnlySerializedHtml.trim(),l=s,c;switch(e.frameConfig?e.frameBoundingBox?c={x:e.frameBoundingBox.x+r.properties.boundingBox.x,y:e.frameBoundingBox.y+r.properties.boundingBox.y,width:r.properties.boundingBox.width,height:r.properties.boundingBox.height}:this.logger.warn(e,"No frame bounding box found, refusing to write bounding box"):c=r.properties.boundingBox,n){case"CLICK":{i="CLICK";let h=Fn(i);a={id:On(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:l},iframeUrl:o?.url,cache:{target:{id:-1,...r.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:c}}}};break}case"SELECT":{i="SELECT_OPTION";let h=Fn(i);a={id:On(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:l},cache:{target:{id:-1,...r.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:c}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{i="MOUSE_DRAG";let h=Fn(i);a={id:On(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:l},deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),iframeUrl:o?.url,cache:{target:{id:-1,...r.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),targetUpdateLoggerTags:Oe(this.logger),boundingBox:c}}}};break}default:throw new Error(`Unknown action type: ${n}`)}let d;e.offset===void 0?(d=this.nextStepOffset,this.nextStepOffset++):d=e.offset,this.callbacks.onActionReceived?.(a,d);let u=e.target.browserState;try{u=kP.html(u,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),u=OS(u,"data-momentic-interacted",4e4)}catch{}let m;try{m=(await this.generator.getReverseMappedDescription({target:u,screenshot:e.screenshotBase64?`data:image/jpeg;base64,${e.screenshotBase64}`:void 0,boundingBox:r.properties.boundingBox},{disableCache:!1,loggerTags:{testId:this.testId,...Oe(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),m=s}let g=this.recordedSteps.get(d)?.step??a,p=g?.command;p&&"target"in p&&p.target?(p.target={type:"description",elementDescriptor:m},this.callbacks.onStepRecorded({...g,command:p},d)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:n,combinable:r}=e;if(_P.includes(n)||this.signal.aborted)return;let o="normal";n.length>1&&(o="special");let i;if(o==="normal"){let u=Fn("TYPE");i={id:On(),type:"PRESET_ACTION",command:{...u,target:void 0,value:n,clearContent:!1}}}else{let u=Fn("PRESS");i={id:On(),type:"PRESET_ACTION",command:{...u,value:n}}}let a,s=this.nextStepOffset-1,l=this.recordedSteps.get(s),c=l?.step,d=c?.command;if(r){if(d?.type===i.command.type){let u=d.value,m=i.command.value;i={id:On(),type:"PRESET_ACTION",command:{...d,value:i.command.type==="PRESS"?`${u}+${m}`:`${u}${m}`}},a=s}else if(d?.type==="CLICK"&&i.command.type==="TYPE")c.command={...i.command,target:d.target,cache:d.cache},i=l.step,a=s;else if(d?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let u=d.value;i={id:On(),type:"PRESET_ACTION",command:{...d,value:u.slice(0,u.length-1)}},a=s}}a===void 0&&(a=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(i,a)}recordScroll(e){if(this.signal.aborted)return;let n=()=>{let{deltaY:i}=e;if(!i)return;let a=this.nextStepOffset-1,s=this.recordedSteps.get(a)?.step.command,l;s?.type==="SCROLL_DOWN"&&s.deltaY?(i+=s.deltaY,l=a):s?.type==="SCROLL_UP"&&s.deltaY?(i-=s.deltaY,l=a):(l=this.nextStepOffset,this.nextStepOffset++);let c=i>0?"SCROLL_DOWN":"SCROLL_UP",d=Fn(c);d.deltaY=Math.abs(i);let u={id:On(),type:"PRESET_ACTION",command:d};this.callbacks.onStepRecorded(u,l)},r=()=>{let{deltaX:i}=e;if(!i)return;let a=this.nextStepOffset-1,s=this.recordedSteps.get(a)?.step.command,l;s?.type==="SCROLL_RIGHT"&&s.deltaX?(i+=s.deltaX,l=a):s?.type==="SCROLL_LEFT"&&s.deltaX?(i-=s.deltaX,l=a):(l=this.nextStepOffset,this.nextStepOffset++);let c=i>0?"SCROLL_RIGHT":"SCROLL_LEFT",d=Fn(c);d.deltaX=Math.abs(i);let u={id:On(),type:"PRESET_ACTION",command:d};this.callbacks.onStepRecorded(u,l)},o=this.recordedSteps.get(this.nextStepOffset-1);o?.step.command.type==="SCROLL_LEFT"||o?.step.command.type==="SCROLL_RIGHT"?(r(),e.deltaY>=20&&n()):(n(),e.deltaX>=20&&r())}};import{z as Tu}from"zod";var cne=Tu.object({type:Tu.literal("url"),url:Tu.string()});var Sl=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userBrowserSettings;enricher;iconKnowledgeBase;activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:n,allowPartialAccessibilityTree:r,logger:o,cdpClient:i,pageGetter:a,abortSignalGetter:s,enricher:l,iconKnowledgeBase:c,userBrowserSettings:d}){this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=n,this.allowPartialAccessibilityTree=r,this.logger=o,this.cdpClient=i,this.pageGetter=a,this.abortSignalGetter=s,this.enricher=l,this.iconKnowledgeBase=c,this.userBrowserSettings=d}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userBrowserSettings.autoExpandIframes)return;let n={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,n),n}async getAutoFrameDetailsFromHandle(e){let n=this.pageGetter(),r=bu(e),{frame:o,mPathSelectorTokens:i}=await Mn(e,n),a={indices:e.locationData.indices,mPathSelectorTokens:i};return this.constructIframeRegexAsync(e,a),{cache:a,config:{type:"auto",frame:o,handle:e,mPathSelectorTokens:i,frameTree:r,cache:a}}}async resolveAutoFrameCache(e){let n=this.pageGetter(),r=await li({cdpClient:this.cdpClient,page:n,logger:this.logger}),{resolution:o,logs:i}=await Ry({page:n,frameTree:r,cache:e});return this.logger.info({logs:i},"Resolved auto frame cache"),{...o,cache:e}}async resolveActiveFrameConfig({logger:e=this.logger,signal:n=this.abortSignalGetter()}){if(!this.frameConfig)return null;if(this.activeFrameCache)if(hl(this.frameConfig)!==this.activeFrameCache.frameIdentifierStringified)this.activeFrameCache=void 0;else if(this.activeFrameCache.frame&&"isDetached"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isDetached())this.activeFrameCache=void 0;else return this.activeFrameCache;let r;return this.frameConfig.type==="url"?r=await this.resolveUrlMatcherFrameConfig({config:this.frameConfig,logger:e,signal:n}):r={source:"auto",frame:this.frameConfig.frame,handle:this.frameConfig.handle,frameIdentifierStringified:hl(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await xy({frame:r.frame,logger:e,signal:n}),this.activeFrameCache=r,r}async executeFunctionInAllFrames(e,n){let r=this.pageGetter(),o=await li({cdpClient:this.cdpClient,page:r,logger:this.logger}),i=[z(r.evaluate(e,n),{milliseconds:2e3})],a=Array.from(o.childFrames);for(;a.length>0;){let l=a.shift(),c=l.url;c==="about:blank"||c.startsWith("chrome-error://")||(a.push(...l.childFrames),i.push(Mn(l,r).then(({frame:d})=>z(d.evaluate(e,n),{milliseconds:2e3})).catch(d=>(this.logger.warn({err:d,frameUrl:l.url},"Failed to evaluate function in frame"),"MOMENTIC_FRAME_EVAL_ERROR"))))}return(await Promise.all(i)).filter(l=>l!=="MOMENTIC_FRAME_EVAL_ERROR")}async getAllChildFrameUrls(){let e=this.pageGetter(),n=await li({cdpClient:this.cdpClient,page:e,logger:this.logger}),r=Array.from(n.childFrames),o=[];for(;r.length>0;){let i=r.shift();r.push(...i.childFrames),o.push(i.src??i.url)}return o}async getDomGraph({devicePixelRatio:e,signal:n,logger:r}){return this.getDOMTree({devicePixelRatio:e??1,signal:n,logger:r??this.logger})}async getA11yTree(e){let n={},r=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),i=this.pageGetter(),a,s,l=null;if(this.frameConfig?.type==="url"){if(a=await rn({fn:()=>this.resolveActiveFrameConfig({logger:r,signal:o}),codePath:"getActiveFrameDetails",logObject:n,signal:o,logger:r})??void 0,!a)throw new A("ActionFailureError","Got null frame details despite active frame config");s=a.handle,l=s.frameId}else this.userBrowserSettings.autoExpandIframes?(s=await rn({fn:()=>li({cdpClient:this.cdpClient,page:this.pageGetter(),logger:r}),codePath:"getMomenticFrameTree",logObject:n,signal:o,logger:r}),l=null):(s={type:"root",page:i,childFrames:[]},l=null);await rn({fn:async()=>this.addMomenticIds({rootPage:i,childFrames:s.childFrames,frameFilter:a?.frame,logger:r}),codePath:"addIdsToElement",logObject:n,signal:o,logger:r});let c=await rn({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:r}),codePath:"domFetch",logObject:n,signal:o,logger:r}),d=await rn({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:l,childFrames:s.childFrames,logTimings:n,logger:r,signal:o}),codePath:"totalA11yFetch",logObject:n,signal:o,logger:r}),{tree:u}=await rn({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:d,domGraph:c,startingFrameId:l,frameContext:s,logger:r,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements}),codePath:"a11yProcess",logObject:n,signal:o,logger:r});return Object.values(n).some(m=>m>750)&&r.warn({logTimings:n},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=u.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=u.dataMomenticIdMap,this.lastA11yTreeRoot=u.root,this.lastDomGraph=c,this.lastSelectorToNodeMap=u.selectorToNodeMap,u}async fetchA11yTreeForRecording(e,n){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:n,logger:qr,filterByViewport:!1}),Math.random()<.1){let r=this.lastA11yTreeRoot?.serialize();this.logger.debug({tree:r&&r.length>4e5?"REDACTED_DUE_TO_SIZE":r},"Refreshed a11y tree during recording")}}async getLocatorFromA11yNode({page:e,root:n,node:r}){if(r.backendNodeId===void 0)throw new Error(`Node with a11y id ${r.id} has no backend node ID: ${r.getNodeOnlySerializedForm()}`);if(this.userBrowserSettings.visualActions){let o=this.domGraph?.backendIdToNode[r.backendNodeId];if(!o)throw new Error(`Could not find DOM node for backend node ID ${r.backendNodeId}`);let i=sy({node:o,domGraph:this.domGraph});return ly(e,i)}else return this.getLocatorFromBackendId(n,r.backendNodeId)}async getLocatorFromBackendId(e,n){let r=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:n},timeout:2e3});if(!r||!r.object.objectId)throw new Error(`Could not resolve backend node ${n}`);let o;try{o=await cy(this.cdpClient,r.object.objectId)}catch(i){throw this.logger.debug({err:i,object:JSON.stringify(r.object)},"Failed to get ID attribute"),i}return e.locator(mn(o))}getNodeUsingMPathSelector(e){let n=this.selectorToNodeMap[e];if(n)return n;let r=e.split(" > "),o="";for(let i=r.length-1;i>=0;i--){let a=r.slice(i).join(" > ");if(this.selectorToNodeMap[a]){o=a;break}}this.logger.warn({selectorMapSize:Object.keys(this.selectorToNodeMap).length,selector:e,closestSelector:o},"Could not find a11y node using mpath selector")}async resolveUrlMatcherFrameConfig({config:e,signal:n=this.abortSignalGetter(),logger:r=this.logger}){let o=Date.now(),i,a,s,l=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{i=await li({cdpClient:this.cdpClient,page:this.pageGetter(),logger:r}),a=await this.getMatchingFrameByUrlWithCdp(i,e),r.info({frameId:a.handle.frameId,url:a.handle.url,src:a.handle.src,locationData:a.handle.locationData},`Found matching frame using ${a.matchType}`);break}catch(c){if(s=c,c instanceof A&&c.reason==="UserInfrastructureError")throw c;l%3===0&&this.logger.warn({attempt:l,err:c},"Failed to resolve active frame, retrying..."),await J(500,n)}finally{l++}if(a)return{source:"url",frame:a.frame,handle:a.handle,frameIdentifierStringified:hl(e),cacheTime:Date.now(),frameTree:i,mPathSelectorTokens:[]};throw s}async getMatchingFrameByUrlWithCdp(e,n){let r=n.url,o=this.pageGetter(),i=Array.from(e.childFrames),a=[];for(;i.length>0;){let s=i.shift(),l=s.domNode;i.push(...s.childFrames);let c=yr(l.attributes??[],"src"),d=l.contentDocument?.documentURL;if(!c&&!d){this.logger.debug("Skipping frame with no URL or src");continue}for(let u of[c,d])if(u){if(r.startsWith("/")&&r.endsWith("/")){if(new RegExp(r.slice(1,-1)).test(u)){a.push({handle:s,matchType:"regex",...await Mn(s,o)});break}}else if(r.trim()===u.trim()){a.push({handle:s,matchType:"url",...await Mn(s,o)});break}}}if(a.length===1){let s=a[0];return this.userBrowserSettings.autoExpandIframes||(s.handle.childFrames=[]),s}else throw a.length>1?new Error(`Found multiple frames with src matching '${r}'. Please use a more specific selector.`):new A("ActionFailureError",`Failed to find frame with src matching: ${r}`)}async composeA11yDomGraph({opts:e,a11yGraph:n,domGraph:r,startingFrameId:o,frameContext:i,logger:a,iconKnowledgeBase:s,showZeroOpacityElements:l}){let c=await by({rawA11yGraph:n,startingFrameId:o,frameContext:i,domGraph:r,logger:a,cdpClient:this.cdpClient,showZeroOpacityElements:l,filterByViewport:e.filterByViewport,viewportDetails:void 0,iconKnowledgeBase:s,useMPaths:this.userBrowserSettings.visualActions});if(!c||!c.root)throw new Error("Accessibility tree appears empty");return{tree:c}}async addMomenticIds({rootPage:e,childFrames:n,frameFilter:r,logger:o}){if(this.userBrowserSettings.visualActions)return;let i=await this.addMomenticIdsHelper(r??e,1);if(!this.userBrowserSettings.autoExpandIframes||r)return;let a=Array.from(n),s=[];for(;a.length>0;){let l=a.shift();a.push(...l.childFrames);let c=async()=>{try{let{frame:d}=await Mn(l,e);i=await this.addMomenticIdsHelper(d,i)}catch(d){l.url!=="about:blank"&&o.warn({err:d},"Error adding momentic IDs to child frame, continuing...")}};s.push(c())}await Promise.all(s)}async addMomenticIdsHelper(e,n){if(this.userBrowserSettings.visualActions)return n;let r=this.logger;return await Qe({root:e,fn:i=>window.addIdsToElement?.(document.body,i),arg:n,timeout:2e3,waitForPageLoad:async()=>{try{await e.waitForLoadState("domcontentloaded",{timeout:this.smartWaitingTimeoutMs})}catch(i){r.warn({err:i},"Error loading frame root adding momentic ids, continuing...")}},codePath:"adding Momentic element IDs to the page"})??n}getPageDomain(e){try{let n=new URL(e);if(!n.hostname)return null;let r=n.hostname.split("."),o=r.length>2?r.slice(-2).join("."):n.hostname;return`${n.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({logger:e,warnings:n,handle:r}){try{let{shouldUnroll:o,reason:i}=await this.decideChildFrameUnrollEligibilityHelper({domNode:r.domNode});return{shouldUnroll:o,reason:i}}catch(o){if(o.message.includes("Could not compute box model"))return{shouldUnroll:!1};let i=`Got error when determining whether to filter frame ${r.frameId} with url ${r.url}, allowing it to be fetched: ${o}`;return n?.push(i),e?.warn({err:o},i),{shouldUnroll:!0}}}async decideChildFrameUnrollEligibilityHelper({domNode:e}){let n=e.attributes??[];if(yr(n,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let r=yr(n,"style");if(r?.includes("display: none")||r?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,i]=await Promise.all([this.cdpClient.send({timeout:3e3,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:3e3,method:"CSS.getComputedStyleForNode",params:{nodeId:e.nodeId}})]);if(!o.model||!o.model.height||!o.model.width)return{shouldUnroll:!1,reason:"no bounding box"};if(o.model.height<10||o.model.width<10)return{shouldUnroll:!1,reason:"small bounding box"};for(let a of i.computedStyle){if(a.name==="display"&&a.value==="none")return{shouldUnroll:!1,reason:"display: none"};if(a.name==="visibility"&&a.value==="hidden")return{shouldUnroll:!1,reason:"visibility: hidden"};if(a.name==="opacity"&&a.value==="0")return{shouldUnroll:!1,reason:"opacity: 0"}}return{shouldUnroll:!0}}async getRawA11yGraph({cdpClient:e,frameId:n,childFrames:r,logTimings:o,logger:i=this.logger,signal:a=this.abortSignalGetter()}){let s=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(g){i.warn({err:g},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let l,c;for(let g=0;g<3;g++)try{c=await rn({fn:()=>this.getRawA11yTreeForFrame({frameId:n,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,signal:a,logger:i});break}catch(p){l=p,i.warn({err:p},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!c)throw new Error(`Failed to fetch accessibility tree for root page: ${l}`);let d={};if(d[n??"root"]=c,!this.userBrowserSettings.autoExpandIframes)return d;let u=Array.from(r),m=[];for(;u.length>0;){let g=u.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:g,warnings:s});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;s.push(`Got error when determining whether to filter frame ${g.frameId} with url ${g.url}, allowing it to be fetched: ${h}`)}u.push(...g.childFrames);let p=async()=>{try{let h=await rn({fn:()=>this.getRawA11yTreeForFrame({frameId:g.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${g.frameId}`,logObject:o,signal:a,logger:i});d[g.frameId]=h}catch(h){i.warn({err:h,url:g.url,src:g.src},`Error getting raw a11y tree for child frame ${g.frameId}, continuing...`)}};m.push(p())}return await Promise.all(m),s.length>0&&this.logger.warn({warnings:s},"Got warnings when fetching the raw a11y graph"),d}async getRawA11yTreeForFrame({frameId:e,timeoutMs:n,logTimings:r}){let o;if(this.allowPartialAccessibilityTree)o=(await rn({fn:()=>this.cdpClient.send({method:"Accessibility.getFullAXTree",params:{frameId:e??void 0},timeout:n,timeoutMsg:`Fetching the document tree took over ${n}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:r,signal:this.abortSignalGetter(),logger:this.logger})).nodes;else{let a=(await rn({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:2e3}),codePath:"cdp-get-root-ax-node",logObject:r,signal:this.abortSignalGetter(),logger:this.logger})).node.backendDOMNodeId;o=(await rn({fn:()=>this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:a},timeout:n,timeoutMsg:`Fetching the document tree took over ${n}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:r,signal:this.abortSignalGetter(),logger:this.logger})).nodes}if(!o||o.length<=1)throw new Error("Document is entirely empty");return{root:o[0],allNodes:o}}async getDOMTree({devicePixelRatio:e,signal:n,logger:r}){let o,i=0,a;for(;!o&&i<3;)try{if(o=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:ml},timeout:3e3}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(s){await J(500,n),i++,a=s}if(!o||!o.documents.length)throw r.error({err:a},"Fatal error fetching DOM tree"),new A("UserInfrastructureError","Received an empty HTML snapshot from the browser. This indicates the page has crashed due to resource consumption issues or hanging client-side JavaScript code.");return ay({snapshot:o,devicePixelRatio:e,logger:r})}constructIframeRegexAsync(e,n){if(n.frameSrcRegex||n.frameUrlRegex)return;let r=vy(e);(async()=>{try{let o=await this.enricher?.constructIframeRegex(r);o?.srcRegex&&(n.frameSrcRegex=o.srcRegex),o?.urlRegex&&(n.frameUrlRegex=o.urlRegex),this.logger.debug({result:o,params:r},"Constructed iframe regex for cache")}catch(o){this.logger.warn({err:o},"Failed to construct iframe regex, skipping...")}})()}};function wu(t){let e=[],n="";for(let r of t)r==="+"&&n?(e.push(n),n=""):n+=r;return e.push(n),e}import{randomUUID as DP}from"crypto";function Py(t,e){return async(n,r)=>{try{let o=await r.allHeaders();for(let{key:i,value:a,matcher:s}of t)(!s||s.test(r.url()))&&(o[i]=a);await n.fallback({headers:o})}catch(o){e.warn({err:o},"Failed to apply custom headers to request, continuing")}}}async function Ly(t,e,n,r,o,i){try{await FP(t,e,n,r,o,i)}catch(a){o.warn({err:a},"Error handling intercepted request, continuing...")}}async function FP(t,e,n,r,o,i){let a=DP(),s;try{if(s=await jS(t,n),s){cu(r,s,a);for(let l of Object.values(i))l.onRequestStart(a,s)}}catch(l){o.warn({err:l},"Failed to add request to HAR")}await e.continue();try{let l=await n.response();if(!l||!s)return;await GS(s,n,l),cu(r,s,a);for(let c of Object.values(i))c.onRequestComplete(a,s)}catch(l){l.message.includes("has been closed")||o.warn({err:l},"Failed to add response to HAR")}}var Cu=ci(Ru(),"momentic","chromium"),oL=ci(Ru(),"video"),Tl=process.env.TWO_CAPTCHA_KEY,Uy=tL(Fy);Uy.use(nL({provider:{id:"2captcha",token:Tl},visualFeedback:!0}));var Nn=class t{static USER_AGENT=eL["Desktop Chrome"].userAgent;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;lastIconKnowledgeBaseUpdateTime=0;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};recentFrameNavigations={};requestRecorders={};customHeaders=[];enricher;storage;flagStore;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;videos=[];baseUrl;constructor({storage:e,flagStore:n,enricher:r,browser:o,context:i,page:a,baseUrl:s,logger:l,userBrowserSettings:c,viewport:d,properties:u,clientCallbacks:m,iconKnowledgeBase:g}){if(nh(c),this.storage=e,this.flagStore=n,this.enricher=r,this.browser=o,this.context=i,this.page=a,this.baseUrl=s,this.logger=l,this.userControlledBrowserSettings=c,this.viewport=d,this.properties=u,this.clientCallbacks=m,u.recordVideo){let p=this.page.video();p&&this.videos.push(p)}this.iconKnowledgeBase=g}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:n}){if(this.contextInitialized)return;this.userControlledBrowserSettings.extraHeaders&&await this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders),e&&await this.context.grantPermissions(["clipboard-read","clipboard-write","microphone","camera","geolocation"]);let r={[ll]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:PS.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(r)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})];n&&await this.page.reload();let i=s=>this.handleNewPageEvent(s);this.context.on("page",i),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",i)});let a=Promise.all(o);await Promise.all([a]),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&XP()==="darwin"&&jP("system_profiler SPDisplaysDataType").toString().includes("Retina")?(y.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2):this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio)),this.cdpClient=await gl.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new Sl({smartWaitingTimeoutMs:this.smartWaitingTimeout,pageLoadTimeoutMs:this.pageLoadTimeout,allowPartialAccessibilityTree:this.userControlledBrowserSettings.allowPartialAccessibilityTree??!1,logger:this.logger,cdpClient:this.cdpClient,pageGetter:()=>this.page,abortSignalGetter:()=>this.abortSignal,enricher:this.enricher,iconKnowledgeBase:this.iconKnowledgeBase,userBrowserSettings:this.userBrowserSettings}),this.contextInitialized=!0}async fixViewportForNewHeadless(){this.properties.isNewHeadless&&this.viewport&&await this.cdpClient.send({method:"Emulation.setDeviceMetricsOverride",params:{width:this.viewport.width,height:this.viewport.height,deviceScaleFactor:0,mobile:this.viewport.width<1e3}})}async initializeScreencast(){await this.fixViewportForNewHeadless(),this.clientCallbacks?.onScreencastFrame&&this.viewport&&(await this.cdpClient.send({method:"Page.startScreencast",params:{format:"jpeg",quality:75,maxWidth:this.viewport.width,maxHeight:this.viewport.height}}),this.cdpClient.on("Page.screencastFrame",e=>{let n=e.sessionId,r=Buffer.from(e.data,"base64");this.lastScreenshotForRecording=r,this.clientCallbacks?.onScreencastFrame?.(r,()=>{(async()=>{try{await this.cdpClient.send({method:"Page.screencastFrameAck",params:{sessionId:n}})}catch{}})()})}))}static async init({baseUrl:e,logger:n,storage:r,flagStore:o,enricher:i,mockedServices:a,userBrowserSettings:s,contextArgs:l,recordVideo:c,iconKnowledgeBase:d,callbacks:u}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let m;switch(s.browserType){case"Google Chrome":m="chrome";break;case"Chrome for Testing":m=void 0;break;case"Chromium":m="chromium";break;default:m="chromium";break}let g={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:m},p={...l??{},geolocation:l?.geolocation||_o,locale:l?.locale||No,timezoneId:l?.timezoneId||ko,colorScheme:l?.colorScheme,httpCredentials:s.basicAuthorization?{username:s.basicAuthorization.username??"",password:s.basicAuthorization.password??""}:void 0,javaScriptEnabled:s.disableJavaScript?!1:void 0,ignoreHTTPSErrors:s.ignoreHttpsErrors??!1,userAgent:s.userAgent??t.USER_AGENT,viewport:l?.viewport??Ot},h=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream"],f=null,S,b,E={systemDevicePixelRatio:l?.deviceScaleFactor,recordVideo:c,isNewHeadless:!1};(m==="chrome"||m==="chromium")&&(E.isNewHeadless=!0,g.headless&&h.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&h.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`),s.disableGpu&&h.push("--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-audio-input","--disable-audio-output");let v=s.localChromeExtensionPaths?.map(C=>C.startsWith("~")?ci(Ru(),C.slice(1)):C);if(v?.length){if(m===void 0)throw new A("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let k of v){let N=ci(k,"manifest.json");if(!bl(N))throw new A("UserConfigurationError",`Chrome extension path ${N} does not exist.`)}let C=ci(Cu,`momentic-session-${Date.now()}`);if(!bl(C))try{GP(C,{recursive:!0})}catch(k){throw new A("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${Cu} folder: ${k}`)}let x=[...h],L=v.map(k=>ZP(k)).join(",");x.push(`--disable-extensions-except=${L}`),p?.deviceScaleFactor&&x.push(`--force-device-scale-factor=${p.deviceScaleFactor}`,`--device-scale-factor=${p.deviceScaleFactor}`),p.viewport&&x.push(`--window-size=${p.viewport.width},${p.viewport.height}`),S=await Fy.launchPersistentContext(ci(Cu,`momentic-session-${Date.now()}`),{...g,...p,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:x,baseURL:e}),n.debug({sharedContextOptions:p,sharedBrowserOptions:g,userBrowserSettings:s,chromeArgs:x,flags:o.getAllFlags(),properties:E,baseUrl:e},"Browser initialization context args (persistent)"),b=S.pages()[0]}else{f=await Uy.launch({...g,args:h});let C={...p,baseURL:e,recordVideo:c?{dir:oL}:void 0};S=await f.newContext(C),n.debug({contextArgs:C,sharedBrowserOptions:g,chromeArgs:h,userBrowserSettings:s,flags:o.getAllFlags(),properties:E,baseUrl:e},"Browser initialization context args (standard)"),b=await S.newPage()}let R=new t({browser:f,context:S,page:b,baseUrl:e,logger:n,storage:r,flagStore:o,mockedServices:a||{},enricher:i,userBrowserSettings:s,viewport:p.viewport||Ot,properties:E,clientCallbacks:u,iconKnowledgeBase:d});return await R.initialize({grantPermissions:!0,runInitScripts:!1}),R}static async fromExistingContext({context:e,storage:n,flagStore:r,enricher:o,userBrowserSettings:i,logger:a}){let s=e.pages()[0];if(!s)throw new Error("No page found in existing context");let l=s.viewportSize(),c=s?.url(),d=new t({browser:e.browser(),context:e,page:s,baseUrl:c,logger:a,storage:n,flagStore:r,mockedServices:{},enricher:o,userBrowserSettings:i,viewport:l,properties:{isNewHeadless:!0},clientCallbacks:void 0,iconKnowledgeBase:null});return await d.initialize({grantPermissions:!1,runInitScripts:!0}),d}async handleAvailableTabsChangeHelper(){try{let e=await gu(this.context,{getTitles:!0}),n=this.page.url();this.clientCallbacks?.onTabsChange?.(e,n)}catch(e){this.logger.error({err:e},"Error sending available tabs to frontend")}}handleAvailableTabsChange(){try{clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),500)}catch(e){this.logger.warn({err:e},"Error handling available tabs change")}}addToPageLoadPromises(e,n){let r=ky(),o=`${e}-${r}`,i=Date.now(),a=!1,s=async()=>{try{await z(n(),{signal:this.abortSignal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(l){l.name!=="AbortError"&&this.logger.error({err:l,promiseKey:o,codePath:e,duration:Date.now()-i},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],a=!0}};this.pageLoadPromises[o]=s().catch(()=>{}),a&&delete this.pageLoadPromises[o]}handlePageClosedEvent(e){if(this.page!==e){this.logger.debug({url:e.url()},"Detected background page was closed, just updating available tabs only"),this.handleAvailableTabsChange();return}let n=async()=>{if(this.closed)return;this.logger.info({url:e.url()},"Detected active page was closed, switching to another tab");let r=this.context.pages();for(let o=r.length-1;o>=0;o--){let i=r[o];if(!(!i||i.isClosed()||!Zr(i.url()))){this.logger.info(`Automatically switching to tab ${o} after close: ${i.url()}`),await this.switchToPage({type:"INDEX",index:String(o)});break}}};this.addToPageLoadPromises("page closed handler",async()=>n())}handleNewPageEvent(e){let n=e.url();if(this.logger.info({url:n},"Detected new page event, registering handlers and waiting for load to complete"),this.properties.recordVideo){let r=e.video();r&&this.videos.push(r)}try{this.handleNewPageEventHelper(e)}catch(r){this.logger.warn({err:r},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let n=ky(),r="new-page-load-handler";e.on("close",a=>this.handlePageClosedEvent(a)),e.on("framenavigated",a=>this.handleFrameNavigationEvent(a)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);e.on("console",a=>{zS(e,o,this.debugData,a,this.logger)});let i=async()=>{await $S(n,this.debugData,e),await e.route("**/*",async(a,s)=>{await Ly(n,a,s,this.debugData,this.logger,this.requestRecorders)}),await e.route("**/*",Py(this.customHeaders,this.logger)),await this.loadFrameAndRecordUrl({root:e,codePath:r}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(r,async()=>i())}async handleCollectSvgs(e){if(!this.flagStore.isBooleanFlagEnabled("icon_knowledge_base")||this.page.isClosed()||this.page.mainFrame()!==e||!this.iconKnowledgeBase||!this.clientCallbacks?.onSvgsCollected||Date.now()-this.lastIconKnowledgeBaseUpdateTime<5e3)return;this.lastIconKnowledgeBaseUpdateTime=Date.now();let n=await this.stateManager.getDomGraph({devicePixelRatio:this.devicePixelRatio}),r=dy({domGraph:n,flagStore:this.flagStore,logger:this.logger,existingHashes:this.iconKnowledgeBase});if(r.forEach(s=>{this.iconKnowledgeBase[s.hash]=s}),!r.length)return;let o=Oe(this.logger),i={pageUrl:e.url(),firstSeenTime:Date.now(),hostname:YP()};for(let s of["runId","testId"])o[s]&&(i[s]=o[s]);let a={metadata:i,newSvgs:r};this.clientCallbacks.onSvgsCollected(a)}handleFrameNavigationEvent(e){let n=e.url(),r=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${n.slice(0,50)}-${r}`;if(!n||n==="about:blank"||!Zr(n)||this.recentFrameNavigations[o]&&Date.now()-this.recentFrameNavigations[o]<1e3)return;this.recentFrameNavigations[o]=Date.now();let i=async()=>{try{if(e.isDetached())return;await this.loadFrameAndRecordUrl({root:e,codePath:o,signal:this.abortSignal}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(s){this.logger.warn({err:s},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(a){a.name!=="AbortError"&&this.logger.warn({err:a},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>i())}async injectKnowledgeBaseIntoBrowser(e){try{if(!this.iconKnowledgeBase||await e.evaluate(()=>!!window._MOMENTIC_ICON_KNOWLEDGE_BASE))return;let r={};Object.keys(this.iconKnowledgeBase).forEach(o=>{this.iconKnowledgeBase[o]?.description&&(r[o]=this.iconKnowledgeBase[o].description)}),await e.evaluate(o=>{let i=window;i._MOMENTIC_ICON_KNOWLEDGE_BASE=o},r)}catch(n){this.logger.warn({err:n},"Failed to inject icon knowledge base into browser, continuing...")}}getBrowserCallbacks(){return{waitForPageLoad:()=>this.waitForPageLoad(),waitForUrl:e=>this.waitForUrl(e),getBrowserState:e=>this.getBrowserState(e),waitForDomStability:e=>this.waitForDOMStability(e),state:{url:()=>this.url(),getDomGraph:()=>this.stateManager.domGraph,getOpenPages:()=>this.getOpenPages(),getRoot:()=>this.getActivePageOrFrame(),userBrowserSettings:this.userBrowserSettings},pageLoadTimeoutMs:this.pageLoadTimeout,signal:this.abortSignal}}ping(){if(this.closed)throw new Error("Page has been closed")}setActiveFrameConfig(e){this.stateManager.setActiveFrameConfig(e)}async reset(e){for(this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={};this.videos.length>0;)this.videos.pop();await this.clearAuthState({closeNonActiveTabs:!0}),await this.stopScreencast(),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await z(uu(this.getBrowserCallbacks()),{milliseconds:1e3})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0;try{this.originsVisited.clear(),await this.context.close(),await this.browser?.close(),this.browser=null}catch(e){this.logger.warn({err:e},"Error cleaning up browser, continuing...")}finally{this.browser=null}}get closed(){return this.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,n,r){let o=Date.now(),i=0,a=0;for(;Date.now()-o<8e3;){a++,r?.throwIfAborted();try{if(await Qe({fn:()=>{let l=window;return!!(l.generateCssSelectors&&l.evaluateCssSelectors&&l.evaluatePrimaryCaches&&l.generateHtmlCacheAttributes&&l.ldist)},timeout:1e3,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(s){if(i++,i>=3){n.warn({err:s},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await J(500),a%2===0&&n.warn("Still waiting for momentic browser scripts to load...")}throw new Error(`Failed to load momentic browser scripts on page ${e.url()}`)}async html(){let e=await this.getActivePageOrFrame();return await this.ensureMomenticBrowserScriptsLoaded(e,this.logger),Qe({root:e,fn:()=>{let n=window;if(!n?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return n.getFullHtmlTree()},arg:void 0,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the full HTML tree"})}url(){return this.page.url()}async stabilizePageForScreenshot(){try{await this.evaluateFunctionInPage(()=>{let e=window,n=[],r=new Map;document.querySelectorAll("input,textarea,[contenteditable]").forEach(o=>{r.set(o,{value:o.style.getPropertyValue("caret-color"),priority:o.style.getPropertyPriority("caret-color")}),o.style.setProperty("caret-color","transparent","important")}),n.push(()=>{for(let[o,i]of r)o.style.setProperty("caret-color",i.value,i.priority)}),e._MOMENTIC_SCREENSHOT_CLEANUP=()=>{for(let o of n)o();delete e._MOMENTIC_SCREENSHOT_CLEANUP}},void 0,"stabilizing page for screenshot")}catch(e){(!(e instanceof Error)||!e.message.includes("Execution context was destroyed"))&&this.logger.warn({err:e},"Failed to stabilize page before screenshot, continuing...")}}async removeScreenshotStabilization(){try{await this.evaluateFunctionInPage(()=>{window._MOMENTIC_SCREENSHOT_CLEANUP?.()},void 0,"removing screenshot stabilization")}catch{}}async screenshot(e){let{retries:n=1,stabilizeBeforeScreenshot:r=!1}=e,o=this.page.url();r&&await this.stabilizePageForScreenshot();let i=Date.now();try{await this.fixViewportForNewHeadless();let a=await this.screenshotHelper({...e,retries:n});if(a.byteLength>5e6)this.logger.error("Page screenshot is greater than 5MB, which may cause performance issues with some AI models");else if(a.length===0)throw new Error("Got empty screenshot");return a}catch(a){if(n<=0||a.message.includes("has been closed"))throw a;return this.logger.warn({err:a,pageUrl:o},"Failed taking screenshot, retrying..."),await J(250),this.screenshot({...e,retries:n-1})}finally{Date.now()-i>1e3&&this.logger.warn({pageUrl:o,duration:Date.now()-i},"Screenshot took longer than expected"),r&&await this.removeScreenshotStabilization()}}async screenshotHelper({locator:e,quality:n,saveToDiskPath:r,timeout:o,respectActiveFrame:i,clearHighlights:a=!1}){a&&await this.clearHighlights(),i&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement());let s=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:n,optimizeForSpeed:!0},timeout:o??2e3}),l=Buffer.from(s.data,"base64"),c=await _y.fromBuffer(l),{width:d,height:u}=this.getViewport()??{};if(d&&u&&(c.bitmap.width!==d||c.bitmap.height!==u)&&(l=await c.resize({w:d,h:u}).getBuffer("image/jpeg")),r&&VP(r,l),this.lastScreenshotForRecording=l,!e)return l;let m=await e.boundingBox({timeout:3e3});if(!m)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:g,y:p,width:h,height:f}=m;if(!h||!f)throw new Error("Attempted to screenshot an element with zero width or height");if(g<0||p<0)throw new Error("Attempted to screenshot an element with negative coordinates");g=Math.floor(g),p=Math.floor(p),h=Math.floor(h),f=Math.floor(f);try{l=await(await _y.fromBuffer(l)).crop({x:g,y:p,w:h,h:f}).getBuffer("image/jpeg")}catch(S){throw new Error(`Failed taking element screenshot at coordinates (${g}, ${p}) with size (${h}, ${f}): ${S}`)}return"dispose"in e&&await e?.dispose(),l}getViewport(){return this.viewport?this.viewport:this.page.viewportSize()}async navigate({url:e,initialNavigation:n=!1,loadTimeoutMs:r=this.pageLoadTimeout}){Sf(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();n||(await this.waitForPageLoad(),await this.waitForDOMStability());let i=!1,a;for(let l=0;l<3;l++)try{await this.page.goto(e,{timeout:r,waitUntil:"domcontentloaded"}),i=!0;break}catch(c){if(a=c,this.abortSignal?.throwIfAborted(),this.logger.warn({err:c},`Error occurred during navigation${l===0?", retrying...":" (fatal)"}`),await J(500),a.message.includes("Timeout")&&a.message.includes("exceeded")||a.message.includes("net::ERR_CONNECTION_REFUSED"))break;await this.cdpClient.send({method:"Page.stopLoading",params:{},timeout:1e3})}if(!i)throw new A("UserInfrastructureError",a?.message??"Failed to load page");await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"navigate-step-wait-for-load"}),this.logger.info({url:e},`Navigation complete in ${Math.floor(Date.now()-o)}ms`);let s=this.url();if(NS.has(s))throw new A("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);if(n)try{await this.exposeRecordingBindings()}catch(l){l instanceof Error&&l.message.includes("already registered")||this.logger.error({err:l},"Failed to install Momentic libraries for action recording")}await this.fixViewportForNewHeadless()}async type(e,n={},r=!1){await this.directTypeHelper(e,n,r)}async getActiveElement(e){try{return await Qe({root:e,fn:()=>{let r=document.activeElement?.textContent??void 0;return r&&r.length>100&&(r=r.slice(0,100)+"...[TRUNCATED]"),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:r}:void 0},arg:void 0,timeout:1e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the active element"})}catch(n){this.logger.warn({err:n},"Failed to get active element");return}}async directTypeHelper(e,n={},r=!1){let o=await this.getActivePageOrFrame();await JS({root:o,text:e,options:n,logger:this.logger,callbacks:this.getBrowserCallbacks()});let i=await this.getActiveElement(o);if(r){let a=Date.now();for(;Date.now()-a<this.smartWaitingTimeout&&(!i||i.tag==="body");)await J(250),this.abortSignal?.throwIfAborted(),i=await this.getActiveElement(o);i||this.logger.warn("No active element found to type into, attempting anyways")}n.clearContent&&(n.forceClearContent||i?.tag==="input"||i?.tag==="textarea"?(process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace"),await this.page.waitForTimeout(25)):this.logger.info({activeElementDetails:i},"Currently active element is not eligible for replace content, skipping...")),await this.page.keyboard.type(e,{delay:n.delay??bm}),n.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:2e3})}catch(n){this.logger.warn({err:n},"Failed to scroll into view, trying with raw JS");try{await e.evaluate(async r=>{let o=r.scrollTop;r.scrollIntoView(),await new Promise(a=>setTimeout(a,250));let i=Date.now();for(;Date.now()-i<1e3;){let a=r.scrollTop;if(a===o)break;o=a,await new Promise(s=>setTimeout(s,250))}},void 0,{timeout:2e3})}catch(r){this.logger.warn({err:r},"Failed to scroll into view using JS, continuing...")}}}async highlightA11yId(e){try{let{resolution:n}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(n.locator),!0}catch(n){return this.logger.debug({err:n,id:e},"Failed to highlight target"),!1}}async highlight(e){return cl({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let n=new URL(e).origin;if(n==="null")return;this.originsVisited.add(n)}catch(n){this.logger.warn({err:n},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),n=Object.values(this.pageLoadPromises),r=Object.keys(this.pageLoadPromises),o=-1,i=0;for(;n.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.error({outstandingPromiseKeys:r,outstandingPromises:n},"Still waiting on page load promises"),Date.now()-o<20&&(i++,i>2)){this.logger.error({outstandingPromiseKeys:r,outstandingPromises:n},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(n),n=Object.values(this.pageLoadPromises),r=Object.keys(this.pageLoadPromises)}}async clearAuthState(e){await this.context.clearCookies();for(let o of this.originsVisited)this.logger.debug({origin:o},`Clearing data using CDP for origin ${o}`),await this.cdpClient.send({method:"Storage.clearDataForOrigin",params:{origin:o,storageTypes:"all"},timeout:1e3}),this.originsVisited.delete(o);let n=this.context.pages().indexOf(this.page),r=[...this.context.pages()];for(let o=0;o<r.length;o++){let i=r[o];if(i.isClosed())continue;let a=i.url();try{this.originsVisited.delete(new URL(a).origin)}catch{}await BS(i,this.logger),o!==n&&e.closeNonActiveTabs&&(this.logger.info(`Closing tab ${o} with URL ${a}`),await i.close())}}async loadAuthState(e){await this.waitForPageLoad(),await this.waitForDOMStability(),!e||Object.keys(e).length===0?await this.clearAuthState({closeNonActiveTabs:!1}):await this.loadAuthStateHelper(e),await this.refresh(),await this.waitForDOMStability()}async loadAuthStateHelper(e){let n=[];for(let i of e.cookies??[]){let a=await this.setCookie(i);n=n.concat(a)}this.logger.info(`Loaded ${e.cookies?.length??0} cookies`),await this.cdpClient.send({method:"DOMStorage.enable",params:void 0,timeout:1e3});let r=0;for(let i of e.origins??[])for(let a of i.localStorage)try{await this.cdpClient.send({timeout:1e3,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(i.origin).origin,isLocalStorage:!0},key:a.name,value:a.value}}),r++}catch(s){this.logger.warn({err:s,origin:i},"Failed to set local storage entry, continuing...");break}this.logger.info(`Loaded ${r} local storage entries`);let o=e.idb;o&&Object.keys(o).length>0&&(await US(this.page,o,this.logger),this.logger.info(`Loaded ${Object.keys(o??{}).length} indexedDB databases`))}async saveAuthState(){let n=0,r=null;for(;n<=2;)try{await this.waitForPageLoad(),await this.waitForDOMStability();let o=await this.context.storageState();return o.idb=await FS(this.page,this.logger),o}catch(o){if(r=o,n++,n<=2){this.logger.warn({err:o,retryCount:n,maxRetries:2},`Error saving auth state, retrying (${n}/2)...`);let i=Math.pow(2,n)*100;await new Promise(a=>setTimeout(a,i))}}throw this.logger.error({err:r},"Failed to save auth state after 2 retries"),new A("ActionFailureError",`Failed to save auth state: ${r?.message}`)}async getOpenPages(e){return gu(this.context,e)}saveA11yDetailsToCache(e,n){n.content=e.content,n.name=e.name,n.role=e.role,n.numChildren=e.children.length,delete n.serializedForm,delete n.nodeOnlySerializedForm}async updateCacheWithNewNodeDetails({node:e,target:n,locator:r,forceSaveNewCssSelectors:o,startingBoundingBox:i,allowZeroOpacityOverride:a,logger:s=this.logger}){if(e&&this.saveA11yDetailsToCache(e,n),n.frameCache=this.stateManager.saveAutoFrameCacheDetails(n.frameCache),r)try{let l=await this.fetchHtmlAttributes({locator:r,logger:s,startingBoundingBox:i,allowZeroOpacityOverride:a}),c=!1;for(let d of["generatedSelectors","serializedHtml","nodeOnlySerializedHtml","hybridSelector"]){let u=l?.[d];if(u&&!n[d]){c=!0;break}if(u&&JSON.stringify(u)!==JSON.stringify(n[d])){c=!0;break}}l&&(o||c)&&(n.generatedSelectors=l.generatedSelectors,n.serializedHtml=l.serializedHtml,n.nodeOnlySerializedHtml=l.nodeOnlySerializedHtml,n.hybridSelector=l.hybridSelector)}catch(l){if(l instanceof En)throw l;s.warn({err:l},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:n,locator:r,logger:s,boundingBox:i})}catch(l){s.debug({err:l},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:n,logger:r,boundingBox:o}){if(!n)return{scrollPerformed:!1};if(!Zd.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(n),o||(o=await n.boundingBox({timeout:3e3})),!o||!o.width||!o.height)return r.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0,{scrollPerformed:!0};let{x:i=0,y:a=0,width:s=0,height:l=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-s)<1&&Math.abs(e.boundingBox.height-l)<1&&Math.abs((e.boundingBox.x??0)-i)<1&&Math.abs((e.boundingBox.y??0)-a)<1)return{scrollPerformed:!0};e.boundingBox=o;let c=await this.screenshot({locator:n,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(c),{scrollPerformed:!0}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async createTargetFromA11yId({id:e,description:n,targetSource:r,skipSaveToCache:o,logger:i=this.logger}){if(e<0)throw new A("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let a=this.stateManager.a11yIdToNodeMap[e];if(!a)throw new A("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let s=this.stateManager.frameConfig,l,c,d,u;if(this.userBrowserSettings.autoExpandIframes&&!s&&a.parentFrame){let f=a.parentFrame,{cache:S,config:b}=await this.stateManager.getAutoFrameDetailsFromHandle(f);c=S,d=b,l=b.frame,u="auto iframe"}else a.parentFrame&&s?(d=s,l=await this.getActivePageOrFrame(),u="hardcoded url already on the state manager"):(l=await this.getActivePageOrFrame(),u="should not be possible");let m=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:l,node:a}),g={id:e,inputDescription:n??void 0,targetSource:r,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:Oe(i),frameCache:c},p,h=!1;o||(d&&(i.info({frameConfigSource:u,frameConfig:Ay(d)},"A11y node was resolved to a target within an iframe"),p=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(d),h=!0),await this.updateCacheWithNewNodeDetails({node:a,target:g,locator:m,logger:i,forceSaveNewCssSelectors:!0,allowZeroOpacityOverride:!0}));try{return{resolution:{locator:m,a11yNode:a,displayString:a.getNodeOnlySerializedForm(),decisions:[]},target:g,frameConfig:d,frameConfigSource:u}}finally{h&&this.stateManager.setActiveFrameConfig(p)}}async resolveTarget(e,n,r={}){let{targetName:o,logger:i=this.logger,signal:a=this.abortSignal,allowZeroOpacityOverride:s}=r;if(n.frameCache&&this.userBrowserSettings.autoExpandIframes){let g,p=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(n.frameCache);this.setActiveFrameConfig(f),p=!0;break}catch(f){g=f,await J(500,a)}if(!p)throw g}let l=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(l,i,a);let c=Date.now(),d=0,u=0,m;for(;Date.now()-c<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),d++;let g=d===2||Date.now()-c>this.smartWaitingTimeout-2e3&&d%2===0;try{m=await this.resolveTargetHelper({root:l,target:n,primaryOnly:!0,logger:g?i:qr,allowZeroOpacityOverride:s,signal:a});break}catch(p){if(p instanceof zi)break;if(p instanceof En){if(u++,u>2)throw i.error({err:p},"Got multiple cache disqualification errors, giving up"),p;i.warn({err:p},"Got cache disqualification error, waiting and retrying resolution"),await J(500,a)}a?.throwIfAborted(),g&&i.info({err:p},`Could not resolve target using primary cache only (x${d})`),await J(500,a)}}return m||(m=await this.resolveTargetHelper({root:l,target:n,primaryOnly:!1,logger:i,signal:a,allowZeroOpacityOverride:s}),n.targetSource="HEURISTIC_HEALED",n.targetUpdateTime=new Date().toISOString(),n.targetUpdateLoggerTags=Oe(i),i.info({decisions:m.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:m?.decisions??[],pageState:void 0,targetSource:n.targetSource,targetUpdateTime:n.targetUpdateTime}),m}async resolveTargetHelper({root:e,target:n,primaryOnly:r,logger:o,signal:i,allowZeroOpacityOverride:a}){let s=[],l=(await this.getBrowserState({logger:o,abortSignal:i,skipWait:!0,allowZeroOpacityOverride:a})).serialize(),c;if(n.generatedSelectors||n.hybridSelector){let d;try{d=await this.resolveTargetWithPrimaryMethods({root:e,target:n,logger:o,allowZeroOpacityOverride:a})}catch(u){c=u,u instanceof wn&&s.push(...u.decisions)}if(d)return{...d,pageState:void 0,decisions:[...s,...d.decisions]};r||(s.push({type:"CSS_SELECTOR",matched:!1,reason:c?.message,selectors:ga(n.generatedSelectors??[])}),n.generatedSelectors=void 0,n.hybridSelector=void 0)}if(r)throw c;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let d=await this.resolveTargetWithSecondaryMethods({root:e,tree:l,target:n,decisions:s,logger:o,signal:i,allowZeroOpacityOverride:a});if(d)return d}throw new wn(`Could not find any relevant node given target: ${JSON.stringify(n)}`,s)}async resolveTargetWithPrimaryMethods({root:e,target:n,logger:r,allowZeroOpacityOverride:o}){if(!n.nodeOnlySerializedHtml)throw new zi("Insufficient data to resolve target using primary methods (missing node HTML)");let i=this.userControlledBrowserSettings.hybridSelectorMode,a={ldistThreshold:.05,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?n.boundingBox:void 0},{css:s,hybrid:l}=await Qe({fn:E=>window.evaluatePrimaryCaches(E),arg:{cssParams:{selectors:n.generatedSelectors??[],cachedElementSerialized:n.nodeOnlySerializedHtml,opts:a},hybridParams:i&&n.hybridSelector?{nodes:n.hybridSelector,cachedElementSerialized:n.nodeOnlySerializedHtml,opts:a}:void 0},root:e,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),c,d,u,m=[];if(i==="prefer"&&l?.result){c=l,d=l.result;let E={type:"HYBRID_SELECTOR",matched:!0,logs:l.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};m.push(E),u="HYBRID_SELECTOR"}else if(s?.result)c=s,d=s.result,m.push({type:"CSS_SELECTOR",matched:!0,logs:s.logs,reason:`${d.workingSelectors.length} CSS selectors matched the following element: ${d.serializedElement}`,selectors:d.workingSelectors.slice(0,5)}),u="CSS_SELECTOR";else throw m.push({type:"CSS_SELECTOR",matched:!1,reason:s.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:s.logs}),l&&m.push({type:"HYBRID_SELECTOR",matched:!1,reason:l.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:l.logs}),new wn("Cache evaluation failed",m);let g,p,h,f=!1;if(this.userBrowserSettings.visualActions){let E=d.mPath;if(!E)throw new Error("Found element did not have an mPath despite using visual actions");let v=E.join(" > ");g=e.locator(v),p=this.stateManager.getNodeUsingMPathSelector(v)}else if(d.dataMomenticId!==void 0)h=parseInt(d.dataMomenticId),p=this.stateManager.dataMomenticIdToNodeMap[h],"workingSelectors"in d?(g=e.locator(d.workingSelectors[0]),f=d.workingSelectors.length<5):g=e.locator(mn(h));else throw new A("InternalWebAgentError","Received an element resolution result with no identifying attributes");i&&n.hybridSelector&&(l?.logs.length===1?r.warn({hybridResult:l,cssResult:s,hybridMode:i},"Hybrid selector resolution rejected, continuing..."):l?.result?s?.result&&l?.result&&l.result.serializedElement!==s.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(s.result.mPath)!==JSON.stringify(l.result.mPath)?r.warn({originalCache:n,hybridResult:l,cssResult:s,hybridMode:i,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):s.result.dataMomenticId!==l.result.dataMomenticId&&r.warn({originalCache:n,hybridResult:l,cssResult:s,hybridMode:i,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):r.warn({originalCache:n,hybridResult:l,cssResult:s,hybridMode:i},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let S=ga(n);await this.updateCacheWithNewNodeDetails({node:p,target:n,locator:g,logger:r,startingBoundingBox:d.boundingBox,forceSaveNewCssSelectors:f,allowZeroOpacityOverride:o});let b=Eu(S,n);return b&&Object.keys(b).length>0&&(n.cacheResolutionUpdateTime=new Date().toISOString(),n.cacheResolutionUpdateLoggerTags=Oe(r),n.cacheResolutionUpdateSource=u),{a11yNode:p,displayString:d.serializedElement,locator:g,decisions:m}}async resolveHardcodedCssSelector(e){let{ctx:n,selector:r,logger:o=this.logger,signal:i=this.abortSignal,timeoutMs:a=this.smartWaitingTimeout}=e,s=await this.getActivePageOrFrame(),l=Date.now(),c=0,d,u=[];for(;Date.now()-l<a;){i?.throwIfAborted(),c++;let m=s.locator(r),g;try{return await m.waitFor({state:"attached",timeout:1e3}),g=await Kn(m,o)??"",u.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${r} matched an element on the page.`}),n?.details?.push({type:"TARGETING",name:e.targetName,elementLocationDecisions:u,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toISOString()}),{locator:m,displayString:g,decisions:u}}catch(p){let h=p.message;d=new A("ActionFailureError",`CSS selector '${r}' failed to resolve after ${c} attempts: ${h.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":h}`),await J(500,i)}}throw d}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let{x:n,y:r,width:o,height:i}=e.target.boundingBox,a=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!a)return;let s=await a.locator.boundingBox({timeout:3e3});if(!s){this.logger.debug({proposedNode:a.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:l,y:c,width:d,height:u}=s;if(Math.abs(d-o)>10||Math.abs(u-i)>10){this.logger.debug({newW:d,oldW:o,newH:u,oldH:i,proposedNode:a.displayString},"Rejecting secondary matching result due to difference in dimensions");return}else if(!n||!r||!l||!c){this.logger.debug({oldX:n,oldY:r,newX:l,newY:c,proposedNode:a.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(l-n)>100||Math.abs(c-r)>100){this.logger.debug({newX:l,newY:c,oldX:n,oldY:r,proposedNode:a.displayString},"Rejecting secondary matching result due to large difference in x/y coords");return}return a}async resolveTargetWithSecondaryMethodsHelper({root:e,target:n,decisions:r,logger:o,signal:i,allowZeroOpacityOverride:a}){if(n.nodeOnlySerializedHtml&&n.nodeOnlySerializedHtml.trim().length<10){let c="Refusing to attempt HTML comparison since the saved element is too short.";r.push({type:"HTML_DISTANCE",matched:!1,reason:c})}else if(n.nodeOnlySerializedHtml&&n.nodeOnlySerializedHtml.length>50)try{let c=await Qe({fn:u=>window.findClosestElementByLDist?.(u),arg:{nodeOnlySerializedHtml:n.nodeOnlySerializedHtml},timeout:2e3,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),d=Math.floor(.05*n.nodeOnlySerializedHtml.length);if(c&&c.closestDistance&&c.closestDistance>=d){let u=`Closest HTML candidate still has too far distance (${c.closestDistance}) from threshold (${d})`;r.push({type:"HTML_DISTANCE",matched:!1,reason:u,distance:c.closestDistance,closestElement:c.closestNodeSerialized})}else{if(c?.error)throw new Error(c.error);if(c?.dataMomenticId||c?.mPathSelector){let u=c.dataMomenticId?parseInt(c.dataMomenticId):void 0,m,g;if(u)m=this.stateManager.dataMomenticIdToNodeMap[u],g=e.locator(mn(u));else if(c.mPathSelector)m=this.stateManager.getNodeUsingMPathSelector(c.mPathSelector),g=e.locator(c.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let p=c.closestNodeSerialized??await Kn(g,o)??"unknown element";o.warn({result:c,originalTarget:n,displayString:p},"Resolved cached target to new node with pure html levenshtein distance");let h=ga(n);await this.updateCacheWithNewNodeDetails({node:m,target:n,locator:g,logger:o,startingBoundingBox:c.boundingBox,allowZeroOpacityOverride:a,forceSaveNewCssSelectors:!0});let f=Eu(h,n);return f&&Object.keys(f).length>0&&(n.cacheResolutionUpdateTime=new Date().toISOString(),n.cacheResolutionUpdateLoggerTags=Oe(o),n.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:c},"Updated cache after l-dist resolution")),r.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${d} string comparison distance of the saved element.`,logs:c.logs,distance:c.closestDistance,closestElement:p,savedElement:n.nodeOnlySerializedHtml}),{locator:g,a11yNode:m,displayString:p,decisions:r,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(c)}`)}}catch(c){o.info({err:c},"Failed to find closest HTML node using levenshtein distance"),r.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${c}`})}let s=n.screenshotUrl,l=n.role??"";if(s&&Zd.includes(l))try{let c=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:n,screenshotUrl:s,signal:i,allowZeroOpacityOverride:a});return{...c,decisions:[...r,...c.decisions],pageState:void 0}}catch(c){i?.throwIfAborted(),r.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${c}`,elementImageUrl:s}),o.warn({err:c},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({root:e,screenshotUrl:n,oldTarget:r,signal:o,allowZeroOpacityOverride:i}){let a;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let s=await this.screenshot({retries:0}),c=await(await fetch(n)).arrayBuffer(),d=rL(),u=await this.enricher.runTemplateMatching({id:d,searchImageBase64String:Buffer.from(c).toString("base64"),pageImageBase64String:s.toString("base64")},{signal:o}),{target:m,locator:g}=await this.getTargetFromPositionPercentages({percentX:u.x,percentY:u.y,allowZeroOpacityOverride:i}),p=m.boundingBox?.width,h=m.boundingBox?.height;if(!p||!h)throw a="Rejecting target from screenshot due to no bounding box",new Error(a);let f=m.id,S=this.stateManager.a11yIdToNodeMap[f],b=ga(r);await this.updateCacheWithNewNodeDetails({target:r,node:S,locator:g,forceSaveNewCssSelectors:!0,allowZeroOpacityOverride:i});let E=Eu(b,r);return E&&Object.keys(E).length>0&&(r.cacheResolutionUpdateTime=new Date().toISOString(),r.cacheResolutionUpdateLoggerTags=Oe(this.logger),r.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:d,diffs:E,templateMatch:u},"Updated cache after template matching resolution")),{locator:g,a11yNode:S,displayString:m.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:n}]}}async typeIntoTarget(e,n,r={}){await this.highlight(n.locator);let o=await n.locator.getAttribute("type",{timeout:1e3})??"",i=XS.some(a=>a===o.toLowerCase());return await mu({targetingResult:n,options:{force:r.force},logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,position:i?{x:1,y:1}:void 0,actionSource:"type",browserCallbacks:this.getBrowserCallbacks()}),await this.page.waitForTimeout(150),this.directTypeHelper(e,r)}async click(e,n,r={}){return mu({targetingResult:e,options:r,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:n,browserCallbacks:this.getBrowserCallbacks()})}async waitForUrl({beforeUrl:e,matcher:n},r){let o=r?.timeout??this.pageLoadTimeout,i=Date.now(),a=!1,s=e;for(;Date.now()-i<o;){if(this.abortSignal?.throwIfAborted(),s=this.url(),ff(s,n,r)){a=!0;break}await J(500,this.abortSignal)}if(!a)throw new A("ActionFailureError",`The active page URL ${r?.negated?"still does":"does not"} ${vd(n)} in ${o}ms.
3902
- Current tab: ${s}`);try{await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"wait-for-url-step"})}catch(l){this.logger.warn({err:l},"Failed waiting for page load after URL change, continuing...")}}async dragAndDrop(e,n,r={}){await this.hover({locator:e}),await this.page.mouse.down();let o=await n.boundingBox({timeout:3e3});if(!o)throw new A("ActionFailureError","Could not get bounding box of target element");let i=o.x+o.width/2,a=o.y+o.height/2,s=r.steps??5;await this.page.mouse.move(i,a,{steps:s}),await J(r.hoverSeconds?Math.min(r.hoverSeconds*1e3,2e3):500),await this.page.mouse.up()}async mouseDrag(e,n,r,o){o&&await this.hover({locator:o});let i=await(await this.getActivePageOrFrame()).evaluate(du);i||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,n+i.top,{steps:r}),await J(250),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await lo({func:async n=>{await this.scrollIntoViewIfNeeded(n.locator);let r=await n.locator.boundingBox({timeout:3e3});if(!r)throw new Error("Attempted to hover over element with no bounding box");await this.page.mouse.move(r.x+r.width/2,r.y+r.height/2,{steps:3})},action:"hovering over element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,targetingResult:e,callbacks:this.getBrowserCallbacks()})}async focus(e){await this.highlight(e.locator),await lo({func:n=>n.locator.focus({timeout:2e3}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let n=await this.getActivePageOrFrame();await Qe({fn:()=>{let r=document.activeElement;r&&r.nodeType===1&&r.blur()},root:n,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:1e3,codePath:"blurring the active element"});return}await this.highlight(e.locator),await lo({func:n=>n.locator.blur({timeout:2e3}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,n,r=!1){await this.highlight(e.locator),await lo({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{if(n.type==="INDEX"){let i=Number(n.index);if(isNaN(i))throw new A("UserConfigurationError",`Page index ${n.index} is not a number`)}await o.locator.selectOption({value:n.type==="VALUE"?n.value:void 0,label:n.type==="LABEL"?n.label:void 0,index:n.type==="INDEX"?Number(n.index):void 0},{force:r,timeout:3e3})},targetingResult:e})}async press(e,n){let r=n.repeat??1;if(n.convertMeta){let o=dl(e);o!==e&&(this.logger.info({key:e,convertedKey:o},"Converted platform dependent keys"),e=o)}for(let o=0;o<r;o++)await this.page.keyboard.press(e,{delay:n.delayMs??0})}async keyDown(e,n){if(n.convertMeta){let r=dl(e);r!==e&&(this.logger.info({keyString:e,convertedKey:r},"Converted platform dependent keys"),e=r)}for(let r of wu(e))await this.page.keyboard.down(r)}async keyUp(e,n){if(n.convertMeta){let r=dl(e);r!==e&&(this.logger.info({keyString:e,convertedKey:r},"Converted platform dependent keys"),e=r)}for(let r of wu(e))await this.page.keyboard.up(r)}async refresh(e){let n=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let r=0,o=2;for(;r<o;){r++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:n});break}catch(i){this.logger.warn({err:i,attempt:r},`Failed to reload page${r<o?", retrying...":", continuing..."}`)}}await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"reload-step"}),await this.waitForDOMStability()}async getBrowserState(e){let{maxAttempts:n=2,logger:r=this.logger,skipWaitForPageLoad:o,allowZeroOpacityOverride:i}=e,a=e.abortSignal??this.abortSignal,s=i?!0:this.userControlledBrowserSettings.showZeroOpacityElements;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:r,signal:a});let l=0,c;for(;l<n;){l++;try{return await z(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:a,logger:r,filterByViewport:e.filterByViewport,showZeroOpacityElements:s}),{milliseconds:this.pageLoadTimeout*l,signal:a,message:"Getting browser state took too long"})}catch(d){if(a?.throwIfAborted(),c=d instanceof Error?d.message:`${d}`,l>=n)throw d;r.warn({err:d,url:this.url()},"Error getting a11y tree, retrying...")}}throw new A("ActionFailureError",`Getting page content failed after ${n} attempts. Error: ${c}`)}async getViewportOffsetDetails(e){let[n,r,o,i,a]=await Qe({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:3e3,waitForPageLoad:async()=>{},codePath:"getting current viewport details"});return{upperBound:n,lowerBound:n+i,leftBound:r,rightBound:r+o,width:o,height:i,devicePixelRatio:this.properties.systemDevicePixelRatio??a}}async waitForDOMStability(e){let{logger:n=this.logger,timeout:r=this.smartWaitingTimeout,signal:o}=e??{},i={value:Date.now()},a=m=>{i.value=Date.now()},s=()=>a("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",s);let l=()=>a("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>l);let c=()=>a("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",c);let d=()=>a("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",d);let u=()=>a("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",u);try{await this.waitForDOMStabilityHelper(i,n,r,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",s),this.cdpClient.removeListener("Page.frameDetached",l),this.cdpClient.removeListener("Page.frameStartedLoading",c),this.cdpClient.removeListener("Page.navigatedWithinDocument",d),this.cdpClient.removeListener("Page.frameRequestedNavigation",u)}}async waitForDOMStabilityHelper(e,n,r,o){let i=!1,a=Date.now(),s,l={quality:25,retries:0,stabilizeBeforeScreenshot:!0},c=!1,d=0;for(;Date.now()-a<r;){if(o?.throwIfAborted(),await J(500,this.abortSignal),s)try{let m=await this.screenshot(l);if(!m.equals(s)){s=m,c=!1;continue}c=!0}catch(m){d++,d%3===0&&n.warn({err:m,screenshotErrors:d},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{s=await this.screenshot(l)}catch(m){d++,d%3===0&&n.warn({err:m,screenshotErrors:d},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<750)){i=!0;break}}let u={duration:Date.now()-a,a11yStableReceived:i,lastTreeUpdateMillisecondsAgo:Date.now()-e.value,screenshotStable:c};i||n.warn(u,"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,n){let{x:r,y:o}=e;this.logger.debug({x:r,y:o},"Executing mouse click with visual coordinates"),await this.waitForPageLoad(),await this.page.mouse.click(r,o,{button:n.rightClick?"right":"left",clickCount:n.doubleClick?2:1})}async dragAndDropUsingVisualCoordinates(e,n,r){await this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(n.x,n.y,{steps:3}),await J(r.hoverSeconds?Math.min(r.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y)}async mouseDragUsingVisualCoordinates(e,n,r,o){await this.hoverUsingVisualCoordinates(o);let i=await(await this.getActivePageOrFrame()).evaluate(du);i||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),i={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+i.left,n+i.top,{steps:r}),await J(250),await this.page.mouse.up()}async getElementLocation(e){let n=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:3e3}),r=await z(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:2e3});process.platform==="darwin"&&r===1&&(r=2);let o=n.documents[0],i=o.layout,a=o.nodes,s=a.nodeName||[],l=a.backendNodeId||[],c=i.nodeIndex,d=i.bounds,u=-1;for(let b=0;b<s.length;b++)if(l[b]===e){u=c.indexOf(b);break}if(u===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[m=0,g=0,p=0,h=0]=d[u];m/=r,g/=r,p/=r,h/=r;let f=m+p/2,S=g+h/2;return{centerX:f,centerY:S}}async scrollVertical(e){return pu({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:0,directionX:null,deltaY:e?Math.abs(e):null,directionY:e&&e>0?"down":"up",signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async scrollHorizontal(e){return pu({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-forward"})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-back"})}async createRawCDPSession(e){let n=await z(this.context.newCDPSession(this.page),{milliseconds:e??this.pageLoadTimeout,fallback:()=>{throw this.logger.error(`Timed out creating new CDP session for ${this.page.url()}`),new A("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${this.page.url()})`)}});return this.logger.info(`Created new CDP session for ${this.page.url()}`),n}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e),await this.initializeScreencast()}async stopScreencast(){if(this.clientCallbacks?.onScreencastFrame)try{await this.cdpClient.send({method:"Page.stopScreencast",params:{}})}catch{}}async changeActivePage(e,n){await this.stopScreencast(),this.recordUrlVisited(e.url()),this.page=e,await this.reinitializeCDPClient(n??this.pageLoadTimeout)}async createNewTab(e,n){let r=await this.context.newPage();await this.changeActivePage(r,n?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...n}),this.handleAvailableTabsChange()}async switchToPage(e,n){let r=!0,o,i=Date.now();for(;r||n?.retry&&Date.now()-i<this.smartWaitingTimeout;){r=!1;try{await this.switchToPageHelper(e,n);return}catch(a){this.logger.warn({err:a},"Error switching to page, retrying..."),o=a,await J(500)}}throw o}async switchToPageHelper(e,n){let r=this.context.pages().map((i,a)=>({page:i,url:i.url(),index:a})),o;if(e.type==="INDEX"){let i=Number(e.index);if(isNaN(i))throw new A("UserConfigurationError",`Page index ${e.index} is not a number`);if(i<0||i>=r.length)throw new Error(`Page index ${e.index} exceeds the number of available pages: ${JSON.stringify(r.map(a=>a.url))}`);o=r[i]}else{let i=r.filter(a=>e.type==="SUBSTRING"?a.url.includes(e.substring):a.url.match(e.pattern));i.length>1&&this.logger.warn(`More than one page matches the page switch criteria: ${JSON.stringify(i.map(a=>a.url))}`),o=i[i.length-1]}if(!o)throw new Error(`Could not find matching page using criteria: ${JSON.stringify(e)}.
3903
- Available pages:${JSON.stringify(r.map(i=>i.url))}`);if(!Zr(o.url,this.logger)){this.logger.error(`Refusing to switch to page with invalid URL: ${o.url}`);return}this.logger.info(`Switching to tab ${o.index} with url ${o.url}`),await this.changeActivePage(o.page,n?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let n;return typeof e=="string"?n=ss(e):n=[e],await this.context.addCookies(n),n}async setLocalStorage(e,n){let r;for(let o=0;o<2;o++)try{await this.evaluateFunctionInPage(([i,a])=>{i&&localStorage.setItem(i,a||"")},[e,n],`setting local storage key ${e}`);return}catch(i){r=i}if(r)throw r}async solveCaptcha(){await this.getBrowserState({allowZeroOpacityOverride:!0});let e;for(let s of Object.values(this.stateManager.a11yIdToNodeMap))if(s.role==="image"&&s.name.toLowerCase().includes("captcha")){if(!s.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,s.backendNodeId);break}if(!e){let s=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!s.captchas||!s.captchas.length)throw new Error("No captchas found on the page");return}let n=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:3e3}),r=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:Tl,task:{type:"ImageToTextTask",body:n.toString("base64"),case:!0},languagePool:"en"})});if(!r.ok){let s=`Captcha solver API returned error response: ${r.statusText}`;throw this.logger.error({text:await r.text()},s),new Error(s)}let{taskId:o}=await r.json(),i=Date.now(),a="";for(;Date.now()-i<6e4;){await J(2500);let s=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:Tl,taskId:o})});if(!s.ok){let c=`Captcha solution API returned error response: ${s.statusText}`;throw this.logger.error({text:await s.text()},c),new Error(c)}let l=await s.json();if(l.errorId){let c=`Captcha solution API returned error ID ${l.errorId}`;throw this.logger.error(c),new Error(c)}if(l.status==="ready"){a=l.solution.text;break}}if(!a)throw new Error("Captcha solution timed out");return a}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},n)=>{this.transformer&&Iy({event:n,frame:e,transformer:this.transformer,enricher:this.enricher,lastScreenshotForRecording:this.lastScreenshotForRecording?.toString("base64"),logger:this.logger})},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(e,n)=>{this.transformer&&this.transformer.recordKeystroke(n)})}async startRecordingCrons(e){if(e.aborted)return;let n,r=(await this.getOpenPages()).map(s=>s.url),o=0,i=!1,a=async()=>{if(e.aborted||o>8){clearTimeout(n);return}i=!0;let s;try{s=(await this.getOpenPages()).map(c=>c.url),o=0}catch(c){this.logger.debug({err:c},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let l=this.url();for(let c=s.length-1;c>=r.length;c--){let d=s[c];Zr(d,this.logger)&&d!==l&&this.logger.info({lastActivePages:r,currentUrl:l,newOpenPages:s},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(c)});break}r=s};n=setInterval(async()=>{if(!i){i=!0;try{await a()}catch(s){this.logger.error({err:s},"Error while checking pages during recording")}finally{i=!1}}},500),e.addEventListener("abort",async()=>{clearInterval(n)})}async startRecording(e,n,r){this.logger.debug({isClickToRecord:r},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(o=>{let i=window;i._MOMENTIC_RECORDING_ACTIVE=!0,i._MOMENTIC_CLICK_RECORD_ACTIVE=o},r),this.transformer=n,await this.injectKnowledgeBaseIntoBrowser(this.page),e.addEventListener("abort",async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let o=window;o._MOMENTIC_RECORDING_ACTIVE=!1,o._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}})}async getSelectOptions(e){return await e.evaluate(r=>Array.from(r.querySelectorAll("option")).map(i=>({value:i.value,label:i.label})),void 0,{timeout:1e3})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:n,codePath:r}){let o=this.pageLoadTimeout,i=e.url();if(!i.includes("chrome-error://")){try{await Qr({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:n,codePath:`loadFrameAndRecordUrlDomContentLoad-${r}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){let s=a;if(s.name==="AbortError")throw new A("UserInfrastructureError",`The page with URL ${He(i,50)} did not load within the configured timeout (${o}ms): ${s}`);if(!s.message.includes("detached"))throw s}try{await Qr({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:n,codePath:`loadFrameAndRecordUrlPageLoad-${r}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(a){this.logger.warn({err:a,codePath:r,url:i},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}}async getCondensedHtml(e){let{skipWait:n=!1}=e??{};return n||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return qP.html(e,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1})}async getRawCondensedHtml(){let e=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(e,this.logger,this.abortSignal);let{result:n,error:r}=await Qe({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:2e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(r)throw new Error(`Failed to process page HTML: ${r}`);if(!n)throw new A("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return n}registerDialogHandler(e){let n=async r=>{try{e==="ACCEPT"?await r.accept():await r.dismiss()}catch(o){this.logger.warn({err:o},"Failed to handle dialog")}};this.page.once("dialog",n)}async evaluateFunctionInAllFrames(e,n){return this.stateManager.executeFunctionInAllFrames(e,n)}async evaluateFunctionInPage(e,n,r,o=2e3){let i=await this.getActivePageOrFrame();return Qe({root:i,fn:e,arg:n,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:r})}async evaluateCodeInPage({code:e,fragment:n,context:r,timeoutMs:o=lr}){let i=qS(),a={code:e,fragment:n,context:r},{result:s}=await z(this.page.evaluate(i,a),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new A("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return s}async getDomNodeFromPixelPosition(e,n){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let r;try{r=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:n},timeout:1e3})}catch(o){throw this.logger.error({err:o,x:e,y:n},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return r}async getDomNodeFromPositionPercentages(e,{percentX:n,percentY:r}){if(n<0||n>1||r<0||r>1)throw new A("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:i,upperBound:a,leftBound:s}=await this.getViewportOffsetDetails(e),l=Math.round(a),c=Math.round(s),d=Math.ceil(o*n),u=Math.ceil(i*r),m=d+c,g=u+l;return this.getDomNodeFromPixelPosition(m,g)}async highlightFromPositionPercentages(e){let n=await this.getActivePageOrFrame(),r;try{r=await this.getDomNodeFromPositionPercentages(n,e)}catch{}return r?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:1e3,params:{highlightConfig:iy,backendNodeId:r.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:1e3,method:"Overlay.hideHighlight",params:{backendNodeId:r?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:1e3})}catch{}}async getTargetFromPositionPercentages(e){let n=await this.getActivePageOrFrame(),r=await this.getDomNodeFromPositionPercentages(n,e);return this.getTargetFromBackendNodeId({root:n,backendNodeId:r.backendNodeId,allowZeroOpacityOverride:e.allowZeroOpacityOverride})}async getTargetFromBackendNodeId({root:e,backendNodeId:n,allowZeroOpacityOverride:r}){let o=this.stateManager.domGraph?.backendIdToNode[n];if(!o)throw new Error("No DOM node was found with the given backend ID");let i=o?.attributes[qn],a=parseInt(i??"");if(!i||isNaN(a))throw new Error("No data-momentic-id was found on the DOM node");let s=e.locator(mn(a)),l;o.bounds.x!==null&&o.bounds.y!==null&&(l={x:o.bounds.x,y:o.bounds.y,width:o.bounds.width??0,height:o.bounds.height??0});let c=await this.fetchHtmlAttributes({locator:s,logger:this.logger,startingBoundingBox:l,allowZeroOpacityOverride:r}),d={id:-1,dataMomenticId:a,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...c};return this.logger.debug({target:d},"Tied backend ID to HTML node"),{target:d,locator:s}}async performTargetRedirection(e,n,r){try{return await this.scrollIntoViewIfNeeded(e),await z(this.performTargetRedirectionHelper(e,n,r),{milliseconds:3e3})??{locator:e}}catch(o){return n.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,n,r){let o=Date.now(),i=await Kn(e,n);if(r===void 0&&(r=await e.boundingBox({timeout:3e3})??void 0),!r){n.error(`Attempted to click on element with no bounding box: ${i}`);return}let{x:a,y:s,width:l,height:c}=r,d=this.getViewport();if(a<0||s<0||!d||a+l>d.width||s+c>d.height){n.info("Skipping locator redirection because the element is outside the viewport");return}let u=await this.getActivePageOrFrame(),{dataMomenticId:m,mPathSelector:g,error:p,serializedElement:h,point:f,force:S,logs:b}=await e.evaluate(v=>{let R=window;if(!R.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return R.performTargetRedirection(v)},void 0,{timeout:1e3}),E=Date.now()-o;if(p){n.warn({error:p,serializedElement:h,duration:E,force:S,logs:b},"Got error from target redirection with bounding box");return}else{if(m)return n.info({newDataMomenticId:m,serializedElement:h,duration:E,force:S,logs:b},"Redirected target to new element with bounding box with data-momentic-id"),{locator:u.locator(mn(m)),hints:{clickableXY:f,force:S}};if(g)return n.info({newMPathSelector:g,serializedElement:h,duration:E,force:S,logs:b},"Redirected target to new element with bounding box with mPath"),{locator:u.locator(g),hints:{clickableXY:f,force:S}};if(f)return n.info({point:f,serializedElement:h,duration:E,force:S,logs:b},"Chose specific visible point on original element"),{locator:e,hints:{clickableXY:f,force:S}};if(S)return n.info({serializedElement:h,duration:E,force:S,logs:b},"Forcing click on original element"),{locator:e,hints:{force:S}}}}async fetchHtmlAttributes({locator:e,logger:n=this.logger,startingBoundingBox:r,allowZeroOpacityOverride:o}){let{hybridSelectorMode:i,showZeroOpacityElements:a}=this.userControlledBrowserSettings,s=await e.evaluate((l,c)=>{let d=window;return d.generateHtmlCacheAttributes?d.generateHtmlCacheAttributes(l,c):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:i==="test"||i==="prefer",startingBoundingBox:r,showZeroOpacityElements:o?!0:a},{timeout:2e3});if("error"in s&&s.error)throw s.error.startsWith(LS)?new gs(s.error):s.error.startsWith(MS)?new hs(s.error):new Error(s.error);return s.warnings.length&&n.warn(s,"Got warnings while generating HTML attributes for target"),s.attributes}async moveMouseFromPositionPercentages(e,n){let r=this.getViewport();if(!r)throw new Error("Cannot move mouse using percentages without viewport");let o=Math.ceil(r.width*e),i=Math.ceil(r.height*n);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseMoved",x:o,y:i,button:"left",clickCount:0}}),{x:o,y:i}}async clickMouseFromPositionPercentages(e,n,r){let o=this.getViewport();if(!o)throw new Error("Cannot click mouse using percentages without viewport");let i=Math.ceil(o.width*n),a=Math.ceil(o.height*r);await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:e==="down"?"mousePressed":"mouseReleased",x:i,y:a,button:"left",clickCount:e==="down"?1:0},timeout:1e3})}async scrollFromPositionPercentages(e,n,r,o){let i=this.getViewport();if(!i)throw new Error("Cannot scroll using percentages without viewport");let a=Math.ceil(i.width*e),s=Math.ceil(i.height*n);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:a,deltaY:s,x:r,y:o}}),{deltaX:a,deltaY:s}}canSolveCaptchas(){return!!Tl}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(n){this.logger.debug({err:n,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,n,r,...o){let i=this.context.pages().indexOf(e);i=i===-1?0:i,lu(e,this.debugData,i,{type:n,text:`[MOMENTIC] ${r}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:n}){if(!bl(e)){let l=`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`;this.logger.error(l),this.logToUserConsole(this.page,"error",l);return}let r=n?.trim()||JP(e),o=WP(e),i=QP(e),a=Zc[i];this.page.once("filechooser",async l=>{this.logger.info({filePath:e,fileName:r},"File chooser triggered");try{if(!bl(e))throw new Error(`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`);await l.setFiles({name:r,buffer:o,mimeType:KP.getType(e)||"application/octet-stream"},{timeout:8e3})}catch(c){this.logger.error({err:c},"Error handling file chooser"),this.logToUserConsole(this.page,"error",c.message)}});let s=o.toString("base64");await this.evaluateFunctionInPage(({fileName:l,base64Data:c,mimeType:d})=>{let u=window;u.momenticFileName=l,u.momenticFileBase64=c;let m=atob(c),g=new Array(m.length);for(let h=0;h<m.length;h++)g[h]=m.charCodeAt(h);let p=new Uint8Array(g);u.MomenticFile=class extends Blob{kind="file";name=u.momenticFileName;constructor(){super([p],{type:d})}isSameEntry(h){return h.name===this.name}queryPermission(h){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(h){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let h=new Blob([p]);return new File([h],u.momenticFileName,{type:d})}async createSyncAccessHandle(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}async createWritable(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}},u.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new u.MomenticFile])},{fileName:r,base64Data:s,mimeType:a},"set-file-chooser-handler",5e3)}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){this.cdpClient.loadEventLogs.length>0&&(this.cdpClient.loadEventLogs=[]);let n={...this.debugData};return this.debugData={logsPerPage:[],harPages:{},harEntries:{}},n}async copy(e){try{await this.evaluateFunctionInPage(n=>navigator.clipboard.writeText(n),e,"copying text to clipboard")}catch(n){if(n instanceof Error&&n.message.includes("Document is not focused")){await this.evaluateFunctionInPage(()=>{document.activeElement||document.body.focus()},void 0,"focusing on body element before copying to clipboard"),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(r=>navigator.clipboard.writeText(r),e,"copying text to clipboard");return}throw n}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(e)}registerRequestRecorder(e,n,r){this.requestRecorders[e]={onRequestStart:(o,i)=>{n.test(i.request.url)&&r.onRequestStart(o,i)},onRequestComplete:(o,i)=>{n.test(i.request.url)&&r.onRequestComplete(o,i)}}}removeRequestRecorder(e){delete this.requestRecorders[e]}setHeader(e,n,r){this.customHeaders.push({key:e.toLowerCase(),value:n,matcher:r})}async setOfflineMode(e){await this.context.setOffline(e)}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??5e3}get userBrowserSettings(){return ga(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}};import EL from"fetch-cookie";import{cloneDeep as Qy}from"lodash-es";import{CookieJar as CL}from"tough-cookie";async function br(t,e={}){let n=await t.getBrowserState(e);return{serializedTree:n.serialize(),tree:n}}var di=3.1783027;function iL(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);!(r>=48&&r<=57)&&!(r>=65&&r<=90)&&!(r>=97&&r<=122)&&e++}return e}function ha(t){return Math.ceil(vu(t)/di)}function vu(t){let e=0;if(typeof t=="string"){let n=t;n=n.replaceAll(`
3904
- `,""),n=n.replaceAll(" ","");let r=iL(n);return n.length-r+di*r}if(typeof t>"u")return 0;if(typeof t=="number")return String(t).length;if(Array.isArray(t))return t.forEach(n=>{e+=vu(n)}),e;if(typeof t=="object"){let n=t;return Object.keys(n).forEach(r=>{e+=String(r).length,r==="image_url"?(n[r]??{}).detail==="high"?e+=1105*di:e+=85*di:e+=vu(n[r])}),e}if(typeof t=="boolean")return t?4:5;throw new Error(`Unsupported type passed to token length calculator '${typeof t}': ${t}`)}var zy={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},Hy={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:15e3,maxLineLength:500},By=/<(\S+) id="(\d+)".*?>/g,aL=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,$y=["h1","h2","section","footer","nav","aside","form","label","dialog"],sL=[...$y,"span","div","h3"],lL=["table","select","form","ul","ol","menu","pre","code","dialog"],cL=["table","form","dialog","nav","section","ul","select"];function Au(t){return t.serializedTree.length>t.maxCharacterLength&&(t.logger.warn({serializedTreeLength:t.serializedTree.length},"Serialized condensed tree is too long to chunk, truncating before chunking"),t.serializedTree=t.serializedTree.slice(0,t.maxCharacterLength)),dL(t)}function dL({serializedTree:t,options:e,logger:n}){let{minChunkTokenCount:r,acceptableChunkTokenCount:o,maxChunkTokenCount:i,maxLineLength:a}=e,s=[],l=t.split(`
3905
- `),c=0,d=[],u=0,m=[],g=[],p=!1;for(;c<l.length;){p&&(s.push({ids:m,content:d.join(`
3906
- `),tokenLength:u}),d=[],u=0,m=g.length?[g[g.length-1].id]:[],p=!1);let h=l[c],f=ha(h);u+=f,h.length>a&&(h=h.slice(0,a));let E=Array.from(h.matchAll(By)).map(_=>_&&_.length>=3?{tagName:_[1],id:_[2]}:void 0).filter(_=>!!_),R=Array.from(h.matchAll(aL)).map(_=>_&&(_[2]||_[4])).filter(_=>!!_);R.reverse();let C=h.replace(/ id="[0-9]+"/g,"");d.push(C);for(let _ of E)m.push(_.id),g.push(_);for(let _ of R){let q=g[g.length-1];q&&q.tagName===_&&g.pop()}let x=g.some(_=>lL.includes(_.tagName)),L=l[c+1]??"",k=ha(L),V=Array.from(L.matchAll(By)).map(_=>_&&_.length>2?_[1]:void 0).filter(_=>!!_),P=V.some(_=>$y.includes(_)),G=V.some(_=>sL.includes(_));u+k>=i&&(p=!0),u>=r&&(P&&!x||R.some(_=>cL.includes(_)))&&(p=!0),u>=o&&G&&!x&&(p=!0),c++}return d.length&&s.push({ids:m,content:d.join(`
3907
- `),tokenLength:u}),s.forEach((h,f)=>{n.debug({chunk:h},`Chunk for page filtering (index ${f+1}/${s.length})`)}),{chunks:s}}var xu=4e4,Iu=8e4;async function uo(t){let{serializedTree:e,logger:n,aiPageFiltering:r,softTokenLimit:o=xu}=t;if(ha(e)<o)return e;let a;r?a=Au({serializedTree:e,options:Hy,logger:n,maxCharacterLength:1e6}):a=Au({serializedTree:e,options:zy,logger:n,maxCharacterLength:3e6});try{return r?await z(uL({...t,chunks:a.chunks}),{milliseconds:2e4}):await z(pL({...t,chunkResult:a}),{milliseconds:15e3})}catch(s){n.warn({err:s},"Error executing page filtering, attempting AI keyword fallback");try{return await mL({...t,chunks:a.chunks})}catch(l){return n.warn({err:l},"Error executing page filtering using keyword matching, using naive truncation"),e.slice(0,Iu*di)}}}async function uL({chunks:t,generator:e,description:n,type:r,logger:o,signal:i,tree:a,softTokenLimit:s=xu,hardTokenLimit:l=Iu}){let c=await e.rankChunksWithAi({chunks:t,description:n,type:r,softTokenLimit:s,hardTokenLimit:l},{abortSignal:i,logger:o,loggerTags:Oe(o)}),d=[];t.forEach((m,g)=>{c.indices.includes(g)&&(d=d.concat(m.ids))});let u=a.pruneUsingRelevantIds(new Set(d)).serialize();return o.debug({description:n,type:r,selectedChunks:c,tree:u},"Pruned a11y tree with AI page filtering"),u}async function mL(t){let{type:e,description:n,generator:r,tree:o,logger:i,hardTokenLimit:a=Iu}=t;if(!n.trim())throw new Error("Empty description passed to page filtering");let s=await r.getExtractedKeywords({goal:n},{logger:t.logger,loggerTags:Oe(t.logger)});for(let l of s.keywords){let c=t.chunks.filter(g=>g.content.toLowerCase().includes(l.toLowerCase()));if(!c.length||c.reduce((g,p)=>g+p.tokenLength,0)>a&&c.length>1)continue;let u=c.flatMap(g=>g.ids),m=o.pruneUsingRelevantIds(new Set(u)).serialize();return i.debug({description:n,type:e,selectedChunks:c,tree:m},"Pruned a11y tree with keyword page filtering"),m}throw new Error("No keywords were unique enough for page filtering")}async function pL(t){let{description:e,generator:n,tree:r,logger:o,signal:i,chunkResult:a,softTokenLimit:s=xu}=t,l=await n.rankChunksWithRag({description:e,chunks:a.chunks,tokenLimit:s},{abortSignal:i,logger:o,loggerTags:Oe(o)});if(l.ids.length===0)throw new Error("RAG returned no important ids");{let c=r.pruneUsingRelevantIds(new Set(l.ids.map(d=>`${d}`))).serialize();return o.debug({browserState:c},"Pruned a11y tree with RAG"),c}}async function Lu(t,e){if(!t.description)throw new A("UserConfigurationError","Cannot locate element with empty description");return Pn({action:async()=>gL(t,e),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:e.browser,logger:t.logger})}async function gL(t,e){let{disableCache:n,testContext:r,filterByViewport:o,skipWait:i,source:a,memory:s,aiPageFiltering:l,logger:c,allowZeroOpacityOverride:d}=t,{ctx:u,orgId:m,browser:g,localCodeEvalTools:p,generator:h,abortSignal:f}=e,S=t.description,b=t.useMemory&&!n;r&&(S=await $t({orgId:m,s:S,context:r,localTools:p,signal:f,logger:c})),a&&(S=fL(S,a));let{serializedTree:E,tree:v}=await br(g,{allowZeroOpacityOverride:d,filterByViewport:o,abortSignal:f,skipWait:i,logger:c}),R,C=Date.now(),x;for(;!R&&Date.now()-C<3e3;){f.throwIfAborted();try{R=await g.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(se){x=se}}if(!R)throw new A("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${x?.message}`);let L=E,k=!1;L=await uo({type:"locator",description:S,serializedTree:E,aiPageFiltering:l,tree:v,logger:c,generator:h}),L!==E&&(k=!0);let V=`data:image/jpeg;base64,${R.toString("base64")}`,P=await h.getElementLocation({browserState:L,goal:S,screenshot:V,source:a,memory:b?s:void 0},{disableCache:n,abortSignal:f,loggerTags:Oe(c),useMemory:b});c.debug({usedRag:k,result:P},"Got locator result");let G=P.id>0;if(u?.details?.push({type:"AI_LOCATION",matched:G,pageState:L,ragUsed:k,thoughts:P.thoughts}),!G)throw new $o(`Could not find any relevant element: ${P.thoughts}`,P.updatedMemory?{type:"GCS_TRACES",traces:P.updatedMemory}:void 0);let{resolution:_,target:q,frameConfig:re}=await g.createTargetFromA11yId({id:P.id,description:S,targetSource:"AI",logger:c});if(_.a11yNode?.properties?.hidden&&_.a11yNode?.properties?.hidden!=="false")throw new A("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${_.displayString}`);return b&&(P.updatedMemory?q.memory={type:"GCS_TRACES",traces:P.updatedMemory}:s&&(q.memory=s)),{thoughts:P.thoughts,target:q,resolution:_,frameConfig:re,screenshot:V}}var hL=["Element exactly matching the description below. Interpret the description narrowly and do not assume there are any typos or errors. Err on the side of returning -1 unless there is a perfect match. Description:","Element closely matching the description below. Interpret the description narrowly and do not return elements that are merely loosely related. Description:","Element matching the description below. This element is being located as part of a negative check step (i.e. we are trying to verify the element does not exist). Therefore, interpret the description narrowly, do not assume there are typos, and err on the side of returning -1 unless there is a perfect match. Description:"],jy="<select> element:",Gy="text input or contenteditable element:",Wy="Element matching the description below. It is possible the element is hidden or doesn't exist. Interpret the description narrowly and do not assume there are typos. Return -1 unless there is an straightforward match. Description:",Vy="Element matching the description below. This element is being located as part of a check step (i.e. we are trying to verify certain properties about the element). Interpret the description narrowly and do not return elements that are merely loosely related. Description:",Pu=[jy,Gy,Wy,Vy,...hL];function qy(t,e){if(t===e)return!0;for(let n of Pu){if(!t.startsWith(n))continue;let r=t.slice(n.length).trim();if(Pu.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===r)||r===e.trim())return!0}return!!Pu.some(n=>e.startsWith(n)&&e.slice(n.length).trim()===t.trim())}function fL(t,e){if(!t||!e)return t;switch(e){case"SELECT_OPTION":return`${jy} ${t}`;case"TYPE":return`${Gy} ${t}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${Wy}
3908
- ${t}`;case"ELEMENT_CHECK":return`${Vy}
3909
- ${t}`;default:return t}}var SL=15;async function wl({command:t,aiPageFiltering:e,logger:n,fixtures:r,source:o,useMemory:i,maxRetries:a=SL}){if(!t.assertion.trim())throw new A("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=r,l=t.timeout?t.timeout*1e3:s.smartWaitingTimeout,c=hf(l),d=0,u=Date.now(),m,g,p;try{await Pn({action:()=>s.clearHighlights(),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:s,logger:n})}catch(f){n.warn({err:f},"Failed to clear highlights before AI check, continuing...")}let h;for(;d<a&&(!h||h-u<l);){r.abortSignal.throwIfAborted(),d!==0&&await J(c,r.abortSignal),h=Date.now();try{if(m=await Pn({action:async()=>{let S=await Ky(s,n,r.abortSignal);return g&&g.serializedTree===S.serializedTree&&g.screenshotBuff.equals(S.screenshotBuff)?m:(g=S,Yy({command:t,state:S,fixtures:r,useMemory:i,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:d,aiPageFiltering:e,logger:n,source:o}))},frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,logger:n,browser:s}),m?.updatedMemory&&(ks(t,m.updatedMemory),n.info({updatedMemory:m.updatedMemory,command:t},"Wrote new memory to assertion command")),m?.success)break;throw m?.thoughts?new A("AssertionFailureError",m.thoughts):new A("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(f){r.abortSignal.throwIfAborted(),p=f instanceof Error?f:new Error(`${f}`),n.info({err:f},`AI check assert attempt ${d} failed, retrying...`)}finally{d++}}if(!m?.success)try{m=await Pn({action:async()=>Yy({command:t,state:await Ky(s,n,r.abortSignal),fixtures:r,useMemory:i,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:d,aiPageFiltering:e,logger:n}),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,logger:n,browser:s})}catch(f){r.abortSignal.throwIfAborted(),p=f instanceof Error?f:new Error(`${f}`)}finally{d++}if(!m?.success){let f=`AI check still failing after ${d} attempts.`;throw p&&(f+=` Latest result: ${p.message}`),new A("AssertionFailureError",f)}return{...m,succeedImmediately:!1,urlAfterCommand:s.url()}}async function Ky(t,e,n){let[r,o]=await Promise.all([br(t,{abortSignal:n,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),t.screenshot({retries:1,respectActiveFrame:!0})]);return{...r,screenshotBuff:o}}async function Yy({command:t,state:e,fixtures:n,useConsensus:r,useMemory:o,highlightElementsOnFailure:i,aiPageFiltering:a,attemptNumber:s,source:l,logger:c}){let{browser:d,generator:u,abortSignal:m}=n,g={type:"ASSERTION"},{serializedTree:p,tree:h}=e,f=e.screenshotBuff,S=d.url(),b=t.contextChoice??"MULTIMODAL",E=p;b!=="VISION_ONLY"&&(E=await uo({type:"assertion",serializedTree:p,description:t.assertion,aiPageFiltering:a,tree:h,generator:u,logger:c,signal:m}),E!==p&&(g.ragUsed=!0),g.pageState=E);let v={goal:t.assertion,url:S,memory:o?t.cache?.memory:void 0,browserState:E,screenshot:f.toString("base64"),contextChoice:b,source:l},C=await(b==="VISION_ONLY"?(x,L)=>u.getVisualAssertionResult(x,L):(x,L)=>u.getAssertionResult(x,L))(v,{useConsensus:r,attemptNumber:s,useMemory:o,disableCache:!!t.disableCache,abortSignal:m,logger:c,loggerTags:Oe(c)});return(C.result||i)&&C.relevantElements&&(g.relevantElementsSerialized=C.relevantElements.map(x=>d.getSerializedFormFromA11yId(x)).filter(x=>!!x),await yL(C.relevantElements,d,c)),{success:C.result,thoughts:C.thoughts,afterScreenshotOverride:f,updatedMemory:o?C.updatedMemory:void 0}}async function yL(t,e,n){let r=Date.now();for(let o of t){if(Date.now()-r>2e3){n.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let i=new AbortController;await z(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw i.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(i){n.debug({err:i},"Failed to highlight relevant element after assertion, continuing...");return}}}var bL=3e4;async function Xy({command:t,logger:e,baseUrl:n,fetchImplementation:r=fetch}){let o=t.timeout??bL/1e3,i=new AbortController,a=Object.fromEntries(Object.entries(t.headers||{}).filter(([u,m])=>u&&m));a["Content-Type"]="application/json";let s;if(Jo(t.url)&&(s=t.url),n&&Qo(t.url,n)&&(s=new URL(t.url,n).toString()),!s)throw new A("ActionFailureError",`Invalid URL: ${t.url}`);let c=await z((async()=>{try{return await r(s,{headers:a,method:"POST",body:JSON.stringify({query:t.query,variables:t.variables}),signal:i.signal})}catch(u){e.error({err:u},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!c)throw new A("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!c.ok){let u,m=await c.text();try{u=JSON.parse(m)}catch{throw new A("ActionFailureError",`GraphQL request failed with status ${c.status}: ${m}`)}throw u?.errors?.length&&u?.errors[0]?.message?new A("ActionFailureError",`GraphQL request failed with status ${c.status}: ${u.errors[0].message}`):new A("ActionFailureError",`GraphQL request failed with status ${c.status}: ${m}`)}let d={};return c.headers.forEach((u,m)=>{d[m]=u}),{status:c.status,headers:d,json:await c.json()}}function El(t){try{return new RegExp(t)}catch(e){throw new A("UserConfigurationError",`The provided regex expression was invalid: ${e}`)}}async function TL(t){let e=t.postData();if(e){if((await t.headerValue("content-type"))?.includes("json"))try{return{json:t.postDataJSON()}}catch{return{}}else if((await t.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}async function wL(t){let e=await t.text();if(e){if((await t.headerValue("content-type"))?.includes("json"))try{return{json:await t.json()}}catch{return{}}else if((await t.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}function Mu(t){return{request:{url:t.request.url,method:t.request.method,headers:t.request.headers.reduce((e,n)=>({...e,[n.name]:n.value}),{}),...t.request.postData?t.request.postData.mimeType.includes("json")?{json:JSON.parse(t.request.postData.text)}:{text:t.request.postData.text}:{}},response:t.response?{status:t.response.status,headers:t.response.headers.reduce((e,n)=>({...e,[n.name]:n.value}),{}),...t.response.content?t.response.content.mimeType?.includes("json")&&t.response.content.text?{json:JSON.parse(t.response.content.text)}:{text:t.response.content.text}:{}}:void 0}}async function Jy(t){let e=t.request(),n=t.status(),r=t.headers(),o=await wL(t);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await TL(e)},response:{status:n,headers:r,...o},status:n,headers:r,...o}}var ui=class{flagStore;orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:n,logger:r,flagStore:o,storage:i,orgId:a,localCodeEvalTools:s,uploadedFileStorage:l,visualDiffScreenshotStorage:c,options:d}){this.orgId=a,this.options=d,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=i,this.uploadedFileStorage=l,this.visualDiffScreenshotStorage=c,this.localCodeEvalTools=s,this.generator=n,this.logger=r,this.flagStore=o}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:n,history:r,disableCache:o,langfuseSessionId:i,lastError:a,logger:s=this.logger}){let[l,c]=await Promise.all([br(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=await uo({type:"ai-action",description:e,serializedTree:l.serializedTree,tree:l.tree,logger:s,generator:this.generator,aiPageFiltering:!!this.options?.aiPageFiltering,softTokenLimit:25e3,hardTokenLimit:5e4}),u=`data:image/jpeg;base64,${c.toString("base64")}`,m={url:this.browser.url(),browserState:d,startingScreenshot:n,history:r,goal:e,screenshot:u,lastError:a};return await this.generator.getMultiturnAiActionEvaluation(m,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...Oe(s)},langfuseSessionId:i})}async promptToCommand({goal:e,startingScreenshot:n,history:r,actionHint:o,disableCache:i,logger:a=this.logger,langfuseSessionId:s}){let l=this.browser.url(),[c,d]=await Promise.all([br(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:a}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${d.toString("base64")}`,m=await uo({type:"ai-action",description:e,serializedTree:c.serializedTree,tree:c.tree,logger:a,generator:this.generator,aiPageFiltering:!!this.options?.aiPageFiltering,softTokenLimit:25e3,hardTokenLimit:5e4}),g={url:l,browserState:m,startingScreenshot:n,history:r,goal:e,actionHint:o,screenshot:u};try{return await this.generator.getMultiturnAiActionCommand(g,{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:{...Oe(a)},langfuseSessionId:s})}catch(p){throw new A("InternalWebAgentError",`Error generating command: ${p instanceof Error?p.message:p}`,{errOptions:{cause:p}})}}async getBrowserState(e){return br(this.browser,e)}async locateElement(e){return await Lu({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,n){return Pn({action:async()=>{let r=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:r}},frameConfig:n?{type:"url",url:n}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,flagStore:this.flagStore,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:n,command:r,targetNames:o,descriptions:i,caches:a,action:s,options:l,retriesWithAI:c=1}){let d=[];for(let u=0;u<i.length;u++){let m=i[u],g=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:m,cache:a[u],action:async p=>p,options:{...l,targetName:o[u]}});d.push(g)}try{let u=await s(...d.map(p=>p.result)),m=p=>p==="fromTarget"?"From Target":p==="toTarget"?"To Target":"Target",g=d.map((p,h)=>p.thoughts?`${m(o[h])}: ${p.thoughts}`:void 0).filter(p=>!!p).join(" -------------- ")||void 0;return{result:u,elementInteractedDisplayStrings:d.map(p=>p.elementInteractedDisplayString),thoughts:g}}catch(u){if(this.throwIfClosed(),c>0)return this.logger.warn({err:u},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:n,command:r,targetNames:o,descriptions:i,caches:i.map(()=>{}),action:s,options:l,retriesWithAI:c-1});throw new A("ActionFailureError",u.message,{errOptions:{cause:u}})}}async wrapElementTargetingCommand(e){let n=this.logger.child({commandId:e.command.id}),r;for(let o=0;o<2;o++)try{return await Pn({action:()=>this.wrapElementTargetingCommandHelper({...e,originalCache:e.originalCache??e.cache}),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:n})}catch(i){if(r=i,this.browser.userBrowserSettings.visualActions&&Jc(i)){n.warn({err:i},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&Hi(i)){n.warn({err:i},"Invalid momentic id error, retrying element targeting command");continue}if(Qc(i)&&n.warn({err:i},"Invalid backend node id error, retrying element targeting command"),i instanceof En&&i.retryableWithAI){n.warn({err:i},"Element cache disqualification error, retrying element targeting command");continue}throw i}throw r instanceof A?r:new A("ActionFailureError",r?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:n,action:r,options:o,command:i}){let a=this.logger.child({commandId:i.id}),{targetName:s}=o;if(n.type!=="description")throw new A("ActionFailureError","Cannot use selector with non-description target");let l,c=Date.now(),d=Date.now();for(;Date.now()-d<this.browser.smartWaitingTimeout;){c=Date.now();try{let u=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:n.elementDescriptor,targetName:s,logger:a});return{result:await r({locator:u.locator}),elementInteractedDisplayString:u.displayString}}catch(u){if(u.name==="AbortError")throw u;l=u,a.warn({err:u},"Failed to action on hardcoded css selector"),Date.now()-c<500&&await J(500)}}throw l}async wrapElementTargetingCommandHelper(e){let{ctx:n,tracer:r,target:o,originalCache:i,action:a,options:s,command:l}=e,{disableCache:c,useSelector:d,targetName:u,targetHealingInProgress:m,source:g}=s,p=this.logger.child({commandId:l.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,S=!1,b=Qy(e.cache);if((!b||c)&&!ec(o))throw new A("ActionFailureError","Cannot target element with no cached data or element descriptor");if(d)return this.wrapHardcodedCssTargetingCommandHelper(e);c&&(p.info("Cache explicitly disabled for this step"),S=!0,b=void 0),b&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&b.targetSource==="HEURISTIC_HEALED"&&(S=!0,b=void 0),b?.inputDescription&&!qy(o.elementDescriptor,b.inputDescription)&&(p.warn({old:b.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),S=!0,b=void 0);let E=R=>!!R&&pm(R),v=!0;if(!E(b)){v=!1,p.info({description:o.elementDescriptor,targetHealingInProgress:m,cacheBustedBeforeAction:S,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),S&&await J(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let R;try{R=await Lu({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:g,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowZeroOpacityOverride:s.allowZeroOpacityOverride,logger:p},this.getControllerFixtures(n))}catch(L){if(L instanceof $o&&L.updatedLocatorMemory){let k={id:-1,...i,memory:L.updatedLocatorMemory};Ns({cmd:l,key:u,newTarget:k,logger:p})}throw new A("ActionFailureError",L.message)}R.frameConfig&&this.browser.setActiveFrameConfig(R.frameConfig);let C=s.disableGlobalLocatorRedirect?{locator:R.resolution.locator}:await this.attemptLocatorRedirect(R.resolution.locator,p),x=await a(C);return Ns({cmd:l,key:u,newTarget:R.target,logger:p}),m&&(r.heal({healType:"AI"}),R.target.targetSource="AI_HEALED",R.target.targetUpdateTime=new Date().toUTCString(),R.target.targetUpdateLoggerTags=Oe(p)),{result:x,elementInteractedDisplayString:R.resolution.displayString,thoughts:R.thoughts}}try{let R=await this.browser.resolveTarget(n,b,{allowZeroOpacityOverride:s.allowZeroOpacityOverride,targetName:u,logger:p,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect)&&await this.browser.scrollIntoViewIfNeeded(R.locator);let C=s.disableGlobalLocatorRedirect?{locator:R.locator}:await this.attemptLocatorRedirect(R.locator,p),x=await a(C);if(Ns({cmd:l,key:u,newTarget:b,logger:p}),v){let L=R.decisions.filter(k=>k.matched);if(L.length!==1)p.warn({decisions:R.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let k=L[0].type;r.heal({healType:k})}}return{result:x,elementInteractedDisplayString:R.displayString}}catch(R){this.throwIfClosed();let C=!1;if((R instanceof En||Jc(R)||Hi(R)||Qc(R)||Vp(R)||qp(R))&&(C=!0),R instanceof A&&!C)throw p.error({err:R},"Failed to execute action with cached target (fatal)"),R;if(f>0&&o){p.info({err:R},"Failed to execute action with cached target, retrying with AI");let x;return b.memory&&La(b.memory)&&(x=b.memory),this.wrapElementTargetingCommand({ctx:n,tracer:r,command:l,target:o,cache:void 0,originalCache:i,action:a,options:{...s,memory:x,retriesWithAI:f,targetHealingInProgress:!0}})}throw new A("ActionFailureError",R.message,{errOptions:{cause:R}})}}async attemptLocatorRedirect(e,n){return this.browser.userBrowserSettings.globalLocatorRedirect?this.browser.performTargetRedirection(e,n):{locator:e}}async screenshotWithDimensions(e){return ma(this.browser,e)}async executePresetCommand(e,n,r,o,i){this.options?.slowMoMs&&await J(this.options.slowMoMs);let a=await this.browser.getOpenPages(),s=this.browser.url(),l;try{l=await this.resolveCommandTemplateStrings(r,o)}catch(c){throw this.throwIfClosed(),new A("ActionFailureError",`Failed to substitute template strings in command: ${c.message}`,{errOptions:{cause:c}})}try{let c=await this.executePresetCommandHelper(e,n,r,o,i);return this.browser.userBrowserSettings.visualActions&&wm(r)?await this.browser.waitForDOMStability({timeout:2e3}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(r.type)&&await this.browser.waitForDOMStability({timeout:1e3}),this.options?.autoFollowNewTabs&&await gS({beforeUrl:s,command:r,beforePages:a.map(d=>d.url),browser:this.browser,logger:this.logger}),c}catch(c){throw c.name!=="AbortError"&&this.logger.error({err:c},"Error thrown in action controller"),c}finally{rS(r,l)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>au(e)}}async resolveCommandTemplateStrings(e,n){return el({obj:e,context:n,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,n,r,o,i){i=i||"disableCache"in r&&!!r.disableCache;let a=this.logger.child({commandId:r.id});switch(r.type){case"SUCCESS":let s=r.condition;return s?.assertion.trim()?wl({command:s,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!r.assertion.trim())throw new A("ActionFailureError","Missing assertion");if(r.timeout&&r.timeout>1800)throw new A("AssertionFailureError",`AI check timeout of ${r.timeout} exceeds the maximum allowed value of 30 minutes.`);return wl({command:r,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:a})}case"AI_EXTRACT":{if(!r.goal.trim())throw new A("ActionFailureError","Cannot perform AI extraction without goal");if(r.schema){let f=th(r.schema);if(f)throw new A("UserConfigurationError",f)}let p=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:r.goal,browserState:p,returnSchema:r.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:i,abortSignal:this.executeAbortController.signal,loggerTags:Oe(a)});if(f.result==="NOT_FOUND")throw new A("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new A("UserConfigurationError",f.thoughts);return{thoughts:f.thoughts||void 0,data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(f){let S=f.message;throw S.includes("MaxGenerationLengthExceededError")?new A("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):S.includes("AIProviderError")&&S.includes("time")?new A("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:f}}):f}}case"NAVIGATE":if(!Jo(r.url)&&!Qo(r.url,this.browser.baseUrl))throw new A("ActionFailureError",`Invalid URL provided to navigate command: ${r.url}`);await this.browser.navigate({url:r.url,loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(r.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let l=await this.browser.solveCaptcha();l&&(await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:p=>this.browser.click(p,this.createCallbacksForBrowser(this.orgId),{}),options:{...r,targetName:"target",disableCache:i}}),await this.browser.type(l,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let p,h;if(r.target&&yn(r.target))await this.browser.hoverUsingVisualCoordinates(r.target.pixels);else if(r.target&&r.target.elementDescriptor.trim()){let{elementInteractedDisplayString:b,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:r.target,cache:r.cache?.target,action:v=>this.browser.hover(v),options:{...r,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:i}});p=b,h=E}let f=this.browser.getViewport()?.height??Ot.height,S=this.browser.getViewport()?.width??Ot.width;switch(r.type){case"SCROLL_UP":await this.browser.scrollVertical(-(r.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(r.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(r.deltaX??S));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(r.deltaX??S);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:p,thoughts:h}}case"WAIT_FOR_URL":{if(r.timeout&&r.timeout>1800)throw new A("UserConfigurationError",`Wait for URL timeout of ${r.timeout} exceeds the maximum allowed value of 30 minutes.`);let p=r.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:p},{timeout:r.timeout?r.timeout*1e3:void 0,negated:r.negated,caseInsensitive:r.caseInsensitive});break}case"WAIT":if(r.delay>1800)throw new A("UserConfigurationError",`Wait timeout of ${r.delay} seconds exceeds the maximum allowed value of 30 minutes`);let c=r.delay*1e3;await J(c,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0});break;case"CLICK":{if(yn(r.target)){await this.browser.clickUsingVisualCoordinates(r.target.pixels,r);break}let p=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:S}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,target:r.target,command:r,cache:r.cache?.target,action:E=>this.browser.click(E,this.createCallbacksForBrowser(this.orgId),r),options:{disableCache:i,targetName:"target",...r}}),b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:S,data:f};return Gs(p,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}case"COPY":return await this.browser.copy(r.value),{succeedImmediately:!1,data:r.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(yn(r.fromTarget)&&yn(r.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(r.fromTarget.pixels,r.toTarget.pixels,{hoverSeconds:r.hoverSeconds});break}if(yn(r.fromTarget)||yn(r.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:p,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:n,command:r,targetNames:["fromTarget","toTarget"],descriptions:[r.fromTarget,r.toTarget],caches:[r.cache?.fromTarget,r.cache?.toTarget],action:(f,S)=>this.browser.dragAndDrop(f.locator,S.locator,{hoverSeconds:r.hoverSeconds,steps:r.steps}),options:{useSelector:!!r.useSelector,disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:p[0],thoughts:h}}case"MOUSE_DRAG":{let p=parseInt(r.deltaX),h=parseInt(r.deltaY),f=r.steps??5;if(isNaN(p)||isNaN(h))throw new A("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${r.deltaX}, ${r.deltaY})`);if(r.target&&yn(r.target)){await this.browser.mouseDragUsingVisualCoordinates(p,h,f,r.target.pixels,{force:r.force});break}let S,b,E;if(r.target?.elementDescriptor){let{elementInteractedDisplayString:v,result:R,thoughts:C}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:r.target,cache:r.cache?.target,action:async x=>x.locator,options:{disableCache:i,targetName:"target",...r}});S=R,b=v,E=C}return await this.browser.mouseDrag(p,h,f,S,{force:r.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:b,thoughts:E}}case"SELECT_OPTION":{if(!nr(r.target))throw new Error("Select with x/y is not supported yet");let p=r.target.elementDescriptor,h=r.choice,{elementInteractedDisplayString:f,thoughts:S}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:{type:"description",elementDescriptor:p},cache:r.cache?.target,action:b=>this.browser.selectOption(b,h,r.force),options:{...r,targetName:"target",disableCache:i,source:Ur(r)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:S}}case"TAB":{let p={loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(r.action,p);break}case"NEW_TAB":await this.browser.createNewTab(r.url,{loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0});break;case"COOKIE":if(!r.value)break;let d=await this.browser.setCookie(r.value);a.debug({results:d},"Set cookies");break;case"LOCAL_STORAGE":if(!r.value||!r.key)break;await this.browser.setLocalStorage(r.key,r.value);break;case"JAVASCRIPT":{let p;try{r.environment==="BROWSER"?(p=await this.browser.evaluateCodeInPage({code:r.code,fragment:r.fragment??!1,context:o.toObjectCopy(),timeoutMs:r.timeout?r.timeout*1e3:void 0}),a.info({result:p},"Executed JavaScript in browser")):p=await io({orgId:this.orgId,code:r.code,fragment:!!r.fragment,context:o,timeoutMs:r.timeout?r.timeout*1e3:void 0,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async h=>{if(!this.options?.scratchPadId){a.warn({updates:h},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:h,logger:a})}}})}catch(h){throw this.throwIfClosed(),new A("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(p)}catch(h){throw new A("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:p}}case"TYPE":{if(r.target&&yn(r.target)){await this.browser.clickUsingVisualCoordinates(r.target.pixels,r),await this.browser.type(r.value,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter},!0);break}let p=this.browser.url(),h,f,S=Qy(r.target);if(S){let{elementInteractedDisplayString:E,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:S,cache:r.cache?.target,action:R=>this.browser.typeIntoTarget(r.value,R,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter}),options:{...r,targetName:"target",disableCache:i,disableGlobalLocatorRedirect:!0,source:Ur(r)}});h=E,f=v}else await this.browser.type(r.value,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter},!0);let b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return Gs(p,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}case"HOVER":{if(yn(r.target)){await this.browser.hoverUsingVisualCoordinates(r.target.pixels);break}let{elementInteractedDisplayString:p,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:r.target,cache:r.cache?.target,action:f=>this.browser.hover(f),options:{...r,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:p,thoughts:h}}case"FOCUS":{if(!nr(r.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:p,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:r.target,cache:r.cache?.target,action:f=>this.browser.focus(f),options:{...r,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:p,thoughts:h}}case"BLUR":{if(r.target&&!nr(r.target))throw new Error("Blur with x/y is not supported yet");if(!r.target||!r.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:p,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,target:r.target,command:r,cache:r.cache?.target,action:f=>this.browser.blur(f),options:{...r,targetName:"target",disableCache:i}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:p,thoughts:h}}case"PRESS":let u=this.browser.url();await this.browser.press(r.value,{repeat:r.repeat,convertMeta:r.convertMeta??!0,delayMs:r.delayMs});let m={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Gs(u,m.urlAfterCommand)&&(m.succeedImmediately=!0,m.succeedImmediatelyReason="URL changed"),m;case"KEY_DOWN":return await this.browser.keyDown(r.value,{convertMeta:r.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(r.value,{convertMeta:r.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let p=new CL,h=EL(fetch,p),f;try{f=new URL(r.url).hostname}catch{}return{data:{...await lS({command:r,baseUrl:this.browser.baseUrl,logger:a,fetchImplementation:h}),cookies:Cp(p,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await Xy({command:r,baseUrl:this.browser.baseUrl,logger:a}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return sS({ctx:e,tracer:n,command:r,disableCache:i,browser:this.browser,logger:a,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:p=>this.wrapElementTargetingCommand(p)});case"FILE_UPLOAD":{let p,h;if(r.fileSource.type==="URL"?(h=r.fileSource.url,p=await _S({uri:r.fileSource.url,logger:a,orgId:this.orgId})):r.fileSource.type==="USER_FILE"&&(h=r.fileSource.name,p=await this.uploadedFileStorage?.getFileForUpload(r.fileSource.name,this.orgId)),!p)throw new A("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...p,filename:r.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let p;if(!r.storageState.trim())p=void 0;else if(p=await io({orgId:this.orgId,code:r.storageState,fragment:!1,context:o,logger:a,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof p!="object")throw new A("ActionFailureError",`Credentials must evaluate to an object (received ${typeof p} instead)`);let h;try{h=ls.optional().parse(p)}catch(f){throw new A("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let p=(r.timeout??bn)*1e3,h=this.generator.getAgentConfig()?.assertion;if(iS(r.assertion)&&!r.useSelector&&r.target.type==="description"&&h&&h!=="v1"){let S={id:r.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${r.target.elementDescriptor}`,iframeUrl:r.iframeUrl,timeout:r.timeout,cache:r.cache&&"memory"in r.cache?{memory:r.cache?.memory}:void 0};try{let b=await wl({command:S,logger:a,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),source:"NEGATED_CHECK"});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${b.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:b.afterScreenshotOverride}}finally{S.cache?.memory&&ks(r,S.cache?.memory.traces)}}let f=await oS({command:r,tracer:n,timeoutMs:p,targetingWrapper:S=>this.wrapElementTargetingCommand(S),fixtures:this.getControllerFixtures(e),disableCache:i});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let p=await Pn({action:async()=>nl({assertion:r.assertion,browser:this.browser,logger:a,timeout:r.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:this.browser,logger:a});return{fail:!p.success,data:p.data,thoughts:p.success?"Page assertion passed.":p.err?.message??`Page assertion still failing after ${r.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let p=El(r.pattern),h=this.browser.registerRequestListener(p);return this.registeredListeners[r.key]=h.then(async f=>await Jy(f)).catch(f=>{a.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let p=this.registeredListeners[r.key];if(!p)throw new A("ActionFailureError",`No listener registered with key: ${r.key}`);let h=r.timeout??10;return{data:await z(p,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let p=El(r.pattern);return this.recordedRequests[r.key]={},this.browser.registerRequestRecorder(r.key,p,{onRequestStart:(h,f)=>{this.recordedRequests[r.key][h]=Mu(f)},onRequestComplete:(h,f)=>{this.recordedRequests[r.key][h]=Mu(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let p=this.recordedRequests[r.key];if(!p)throw new A("ActionFailureError",`No recorder registered with key: ${r.key}`);return delete this.recordedRequests[r.key],{data:Object.values(p),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let p;return r.urlPattern&&(p=El(r.urlPattern)),this.browser.setHeader(r.name,r.value,p),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"OFFLINE_MODE":return await this.browser.setOfflineMode(r.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(p=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:n,disableCache:r,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:n,screenshot:o},{disableCache:r,abortSignal:this.executeAbortController.signal,loggerTags:Oe(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:n,isClickToRecord:r}){this.recordAbortController=n;let o=new fl({signal:n.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,o,r),o}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Oe(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Oe(this.logger)})}};import{z as on}from"zod";var vae=on.object({useSelector:on.boolean().optional(),disableCache:on.boolean().optional(),iframeUrl:on.string().optional(),retriesWithAI:on.number().optional(),targetName:on.union([on.literal("target"),on.literal("fromTarget"),on.literal("toTarget")]),source:Ha.optional(),disableGlobalLocatorRedirect:on.boolean().optional(),allowZeroOpacityOverride:on.boolean().optional(),targetHealingInProgress:on.boolean().optional(),memory:To.optional()});import{cloneDeep as RL}from"lodash-es";var vL={showOverlay:!1},Cl=class{sessions=new Map;sessionCountByIp=new Map;latestSessionId;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:n,cleanup:r,clientIp:o,sessionId:i,socket:a}){return this.sessions.set(i,{controller:e,context:n,cleanup:r,clientIp:o,browserBehavior:RL(vL),socket:a}),this.latestSessionId=i,i}removeSession(e,n){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:i}=o;try{i.setClosed(),await i.browser.cleanup()}catch(a){n.error({err:a},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(a){n.error({err:a},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}getLatestSession(){if(this.latestSessionId)return this.getSession(this.latestSessionId)}};function Zy(t,e,n,r){let o=Date.now(),i=Date.now(),a,s,l,c,d=!1,u=async(h,f)=>{if(!h.closed&&!h.isInPageLoad)try{let S=l;l=void 0;let b=h.url(),E=f.toEditorDisplayCopy();JSON.stringify(E)===JSON.stringify(a)&&b===c&&o>i||(t.emit("browserState",{logsPerPage:S?.logsPerPage,harPages:S?.harPages,harEntries:S?.harEntries,viewport:h.getViewport(),url:b,iframeSrcUrls:s??[],context:E,isInPageLoad:h.isInPageLoad}),o=Date.now()),c=b,a=E}catch(S){if(!t.connected)return;let b=S instanceof Error?S.message:`${S}`;if(b.includes("Frame was detached")||b.includes("Not attached to an active page")||b.includes("browser has been closed")||b.includes("UserInfrastructureError"))return;n.error({err:S,sessionId:e},"Error grabbing browser state")}},m=setInterval(()=>{let h=r.getSession(e),f=h?.controller?.browser;if(!f||f.closed){n.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(m);return}u(f,h.context)},1e3),g=(h,f)=>!!(JSON.stringify(h)!==JSON.stringify(s)||f.logsPerPage.some(S=>S.length>0)||f.harPages&&Object.keys(f.harPages).length>0||f.harEntries&&Object.keys(f.harEntries).length>0),p=setInterval(async()=>{let f=r.getSession(e)?.controller?.browser;if(!f||f.closed){clearInterval(p);return}else if(d)return;d=!0;try{let S=await f.getAllFrameUrls(),b=f.retrieveAndClearDebugData();g(S,b)&&(s=S,l=b,i=Date.now())}catch(S){n.warn({err:S},"Failed to fetch extended details")}finally{d=!1}},2500);return{timers:[m,p]}}var AL=4;async function eb({socket:t,logger:e,storageFactory:n,uploadedFileStorage:r,visualDiffScreenshotStorage:o,serviceMocker:i,devicePixelRatio:a,generatorFactory:s,enricherFactory:l,authorization:c,flagStoreFactory:d,settingsFactory:u,getOrgId:m,branchGetter:g,globalE2eStateManager:p}){let h=t.id,f=t.handshake.query.testId;if(!f)throw new Error("Socket connection request is missing testId");let S=await m({type:"e2e",testId:f}),b=await g?.();e=e.child({testId:f,orgId:S,sessionId:h,branch:b});let E=await s(S,e),v=await l(S,e),R=await d(S),C=await u(S,e),x=await n(S),{testMetadata:L,baseUrl:k,envName:N,browserConfig:V,aiSettings:P,environmentVariables:G,localCodeEvalTools:_}=await mo({testId:f,orgId:S,logger:e,storage:x,authorization:c,flagStore:R,settings:C}),q=p.getSession(h);if(q)return e.info("Associating connection with existing session (likely reconnect)"),await q.controller.browser.clearAllCdpHighlights(),{type:"e2e",sessionId:h,orgId:S,testId:f};let re=t.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:re,event:"connect",args:t.handshake.query},"Websocket event (connect)"),re&&p.getCurrentConnectionsByIp(re)>=AL)throw e.error({clientIp:re,sessions:p.getCurrentSessionsByIp(),...t.handshake.query},"Socket connection browser creation rate limit triggered"),new Error("You have exceeded the maximum number of connections allowed. Momentic limits the number of simultaneously open tabs to uphold browser reliability. Please close duplicate tabs and try again later.");p.reserveCapacityByIp(re);try{await xL({socket:t,baseUrl:k,envName:N,testMetadata:L,orgId:S,sessionId:h,logger:e,environmentVariables:G,clientIp:re,devicePixelRatio:a,storage:x,uploadedFileStorage:r,visualDiffScreenshotStorage:o,serviceMocker:i,localCodeEvalTools:_,generator:E,enricher:v,browserConfig:V,aiSettings:P,flagStore:R,globalE2eStateManager:p})}catch(se){throw e.warn({err:se},"Error setting up socket session, possibly due to client closing the connection"),p.releaseCapacityByIp(re),se}return{type:"e2e",sessionId:h,testId:f,orgId:S}}async function xL({socket:t,baseUrl:e,envName:n,devicePixelRatio:r,testMetadata:o,orgId:i,sessionId:a,logger:s,storage:l,uploadedFileStorage:c,visualDiffScreenshotStorage:d,serviceMocker:u,localCodeEvalTools:m,generator:g,environmentVariables:p,browserConfig:h,aiSettings:f,clientIp:S,enricher:b,flagStore:E,globalE2eStateManager:v}){let R={viewport:o.advanced?.viewport??Ot,locale:o.advanced?.locale??No,timezoneId:o.advanced?.timezone??ko,geolocation:o.advanced?.geolocation??_o,colorScheme:o.advanced?.colorScheme};r&&(R.deviceScaleFactor=r);let C=o.id,x=await u?.initializeServicesForTest(i,C),L=await sl({settings:h,orgId:i,baseUrl:e,envName:n,testName:o.name,localTools:m,envVariables:p,logger:s,customHeaders:void 0});s=s.child({orgId:i,sessionId:a,testId:C});let k=!1,N=E.isBooleanFlagEnabled("icon_knowledge_base")?await l.fetchIconKnowledgeBase(s):null,V=await Nn.init({baseUrl:e,userBrowserSettings:L,enricher:b,storage:l,flagStore:E,mockedServices:x,logger:s,contextArgs:R,iconKnowledgeBase:N,callbacks:{onTabsChange:(re,se)=>{t.emit("tabs",{tabs:re,activeTab:se})},onScreencastFrame:(re,se)=>{let de=t;k&&(de=t.compress(!0)),de.emit("screenshot",{buffer:re},()=>{se()})},onSvgsCollected:re=>{t.emit("newIconDetected",{numIcons:re.newSvgs.length}),l.saveNewIcons(re,s)}}});await V.navigate({url:e,initialNavigation:!0});let P=new ui({browser:V,generator:g,logger:s,flagStore:E,orgId:i,options:{scratchPadId:void 0,slowMoMs:L.slowMoMs,autoFollowNewTabs:L.autoFollowNewTabs,useMemory:f.useMemory,aiPageFiltering:f.aiPageFiltering??E.isBooleanFlagEnabled("rag_v2")},storage:l,localCodeEvalTools:m,uploadedFileStorage:c,visualDiffScreenshotStorage:d}),G=Zy(t,a,s,v),_=async()=>{G.timers.forEach(re=>clearInterval(re))},q=new Yt({baseUrl:e,testName:o.name,currentUrl:P.browser.url(),variablesFromEnvironment:p,envName:n});if(!t.connected)throw await V.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");t.emit("session",{url:e,userAgent:Nn.USER_AGENT,viewport:P.browser.getViewport(),sessionId:a}),v.registerSession({controller:P,context:q,sessionId:a,cleanup:_,clientIp:S,socket:t})}async function mo({testId:t,orgId:e,logger:n,storage:r,authorization:o,flagStore:i,settings:a}){let s=await r.fetchTestMetadata(t,n);if(!s)throw new Error(`Test metadata could not found for test ${t}`);let l;o?.type==="API_KEY"&&(l=new pr({httpClient:new At({...o,logger:n}),fakerSeed:void 0}));let c=s.envs?.find(f=>f.default),d;c&&(d=await r.fetchEnvironment(c.name,n));let u=d&&"browser"in d?d.browser:void 0,m={...a.browser,...u,...s.advanced},g=s.baseUrl||d?.variables?.[it];if(!g)throw new Error("Base URL is empty in both test options and the configured environment");let p={...d?.variables};await Promise.all((s.parameters??[]).map(async f=>{let S=await $t({orgId:e,s:f.defaultValue,context:Yt.dummyContext(s.name,d?.name,p),logger:n,localTools:l});p[f.name]=S}));let h={...a.ai,...s.advanced};return{localCodeEvalTools:l,baseUrl:g,envName:d?.name,testName:s.name,browserConfig:m,environmentVariables:p,testMetadata:s,aiSettings:h}}var Ou=class{parentTracer=null;socket;step;constructor({step:e,socket:n,parentTracer:r}){this.socket=n,this.parentTracer=r,this.step=e}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}heal(){}async finish(e){switch(e.step.status){case"SUCCESS":this.socket.emit("success",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"FAILED":this.socket.emit("failure",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"CANCELLED":this.socket.emit("cancelled",{...e,parentStepIdChain:this.getParentStepIdChain()});return}}async startSubSteps(){return new Tr({parentStep:this.step,socket:this.socket,parentTracer:this})}},Tr=class{parentTracer;parentStep;socket;constructor({parentStep:e,socket:n,parentTracer:r}){this.parentTracer=r,this.parentStep=e,this.socket=n}async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:this.getParentStepIdChain(),attempt:e.attempt}),new Ou({step:e.step,parentTracer:this,socket:this.socket})}},Rl=class{constructor(e,n,r,o,i){this.socket=e;this.storage=n;this.orgId=r;this.testId=o;this.stepsBeforeRun=i}async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}attachConsoleLogs(){}attachNetworkLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new Tr({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new Tr({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new Tr({parentStep:null,parentTracer:null,socket:this.socket})}};var Nu={currentlyExecutingRequests:{}},PL=t=>async(e,n)=>{let{testId:r,orgId:o}=t.metadata,i=await t.flagStoreFactory(o),a=await t.settingsFactory(o,t.logger),s=await t.storageFactory(o),l,c=await mo({testId:r,orgId:o,logger:t.logger,storage:s,authorization:t.authorization,flagStore:i,settings:a}),d=`${r}|${c.baseUrl}`;try{let u=Nu.currentlyExecutingRequests[d]??0;Nu.currentlyExecutingRequests[d]=u+1,l=await LL({...t,...e,...c,done:n})}finally{t.logger.info({result:l,sessionId:t.metadata.sessionId},"Test execution complete"),Nu.currentlyExecutingRequests[d]--}},LL=async({socket:t,steps:e,baseUrl:n,testMetadata:r,reInitialize:o,toStep:i,fromStep:a,storageFactory:s,aiSettings:l,browserConfig:c,metadata:d,logger:u,envName:m,testName:g,environmentVariables:p,localCodeEvalTools:h,done:f,cacheStorageFactory:S,globalE2eStateManager:b})=>{let{testId:E,sessionId:v,orgId:R}=d,C=v,x=b.getSession(v);if(!x)throw new Error("No active session found");let{controller:L,context:k}=x;L.setOpen(),u=u.child({testId:E,orgId:R,sessionId:v,runId:C}),u.info({steps:e.map(ie=>`${ie.type}${"command"in ie?` - ${ie.command.type}`:""}`),toStep:i,fromStep:a,reInitialize:o,envName:m,testName:g,baseUrl:n,context:k,flags:L.flagStore.getAllFlags()},"Socket execution parameters");let N=p??{},V=async()=>{o&&(await L.browser.reset({newUrl:n}),k.reset({baseUrl:n,currentUrl:L.browser.url(),variablesFromEnvironment:N,envName:m,testName:g}))},P=await s(R),G=await S(R),_=async()=>{try{await G.resolveStepCacheEntries({schemaVersion:r.schemaVersion,testId:E,stepLists:{steps:e},logger:u})}catch(ie){u.error({err:ie},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};try{await na({promiseGenerator:async()=>Promise.all([V(),_()]),signal:L.executeAbortController.signal,codePath:"resolveStepCacheAndInitBrowser"}),L.setOpen()}catch(ie){if(t.emit("finished"),ie.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${ie}`)}let q=IL(e),re={collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},se={orgId:R,runId:C,testMetadata:r,steps:e,fromStep:a,toStep:i,orgSettings:{ai:l,browser:c}},de={controller:L,context:k,storage:P,codeEvalTools:h,billingReporter:new Uo,logger:u},wt={test:{},step:{onDynamicAIActionStatusUpdateEvent:ie=>{t.emit("dynamicCommandStatusUpdate",ie)},onDynamicAIActionEvaluatingEvent:ie=>{t.emit("dynamicCommandEvaluating",ie)},onDynamicCommandGenerated:ie=>{t.emit("dynamicCommandGenerated",ie)},onDynamicCommandExecuted:ie=>{t.emit("dynamicCommandExecuted",ie)}}},fn=new Rl(t,P,R,E,q),pe=await al({fixtures:de,options:re,callbacks:wt,inputs:se,testParams:{tracer:fn}});return pe?.status==="PASSED"?await _s({logger:u,cacheStorage:G,orgId:R,testId:E,originalSteps:{steps:q},updatedSteps:{steps:e}}):pe?.status==="FAILED"&&await Ds({logger:u,cacheStorage:G,orgId:R,testId:E,originalSteps:{steps:q},updatedSteps:{steps:e}}),await fn.finish(),f?.(pe),pe.status};var tb={event:"execute",createHandler:PL};import{cloneDeep as ML}from"lodash-es";var OL=t=>async({command:e},n)=>{let{logger:r,generatorFactory:o,metadata:i}=t,a=ML(e),s=Fh(a);if(s.category!=="NO_DESCRIPTION_PROVIDED"){if(s.category!=="NONE"){n?.({result:s});return}"cache"in a&&(a.cache=void 0);try{let c=await(await o(i.orgId,r)).getLintStepResult({command:a},{logger:r});n?.({result:c})}catch(l){r.error({event:"lint",err:l},"Failed to lint step"),n?.({result:void 0})}}},nb={event:"lintStep",createHandler:OL};var NL=({metadata:t,logger:e,storageFactory:n,globalE2eStateManager:r})=>{let{sessionId:o,orgId:i}=t;return async(a,s)=>{let{description:l,command:c,testMetadata:d,returnScreenshot:u}=a;e.info({params:a},`Locate handler called - ${l}`);let m=r.getSession(o);if(!m)throw new Error("No active session found");let{controller:g,context:p}=m;g.setOpen();let h=await n(i),f=jr.parse(d.advanced??{}),S={},b;if(l){if("useSelector"in c&&c.useSelector)try{let E=await g.locateElementWithSelector(l,"iframeUrl"in c?c.iframeUrl:void 0);b=E.resolution.locator,S={target:E.target,thoughts:E.thoughts}}catch(E){e.warn({err:E},"Failed resolving target with selector"),s({err:`Failed locating element: ${E.message}`,decisions:E instanceof wn?E.decisions:void 0});return}else try{let E=await g.locateElement({description:l,disableCache:f.disableAICaching??!1,skipWait:!0,testContext:p,source:Ur(c),iframeUrl:"iframeUrl"in c?c.iframeUrl:void 0,memory:"cache"in c&&c.cache&&"target"in c.cache&&La(c.cache.target.memory)?c.cache.target.memory:void 0,logger:e});S={target:E.target,thoughts:E.thoughts},b=E.resolution.locator}catch(E){(async()=>{try{let v=await g.browser.getCondensedHtml({skipWait:!0});e.warn({err:E,html:v.slice(0,1e5)},"Failed locating element with AI")}catch(v){e.warn({err:v},"Failed grabbing HTML after trying to locate element with AI")}})(),s({err:`${E.message}`});return}if(c.type==="SELECT_OPTION"&&b)try{S.options=await g.browser.getSelectOptions(b)}catch(E){e.warn({err:E},"Failed getting select options"),s({err:`Failed getting select options: ${E.message}`});return}e.info({result:S},"Locate handler result")}if(u)try{let{buffer:E,width:v,height:R}=await g.screenshotWithDimensions({clearHighlights:!0,locator:b}),C=await h.uploadScreenshot(E);S.screenshot={data:C,width:v,height:R},e.info({width:v,height:R},"Captured screenshot during locate")}catch(E){e.error({err:E},"Error capturing screenshot during locate"),s({err:`Error taking screenshot: ${E.message}`});return}if(s({result:S}),b)try{await Promise.all([g.browser.scrollIntoViewIfNeeded(b),g.browser.highlight(b)])}catch(E){e.warn({err:E},"Error highlighting element, continuing...")}}},rb={event:"locate",createHandler:NL};var kL=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async({event:o,percentX:i,percentY:a})=>{let s=n.getSession(r);if(!s)throw new Error("No active session found");let l=s.controller.browser;if(l.closed||l.getActivePage().isClosed()){e.warn("Ignoring mouse move because the browser is closed");return}try{await l.clickMouseFromPositionPercentages(o,i,a)}catch(c){e.error({err:c},"Error performing click during cloud recording in control mode")}}},ob={event:"mouseClickEvent",createHandler:kL};var _L=({metadata:t,generatorFactory:e,logger:n,socket:r,globalE2eStateManager:o})=>{let{sessionId:i,orgId:a,testId:s}=t;return async({stepId:l,parentStepIdChain:c,attribute:d})=>{let u=o.getSession(i);if(!u)throw new Error("No active session found");let{controller:m}=u,g=await e(a,n);m.setOpen(),u.browserBehavior.showOverlay=!0;let p=new AbortController;p.signal.addEventListener("abort",async()=>{try{u.browserBehavior.showOverlay=!1,await m.stopRecordMode()}catch(S){n.warn({err:S},"Failed to stop record mode in target click socket handler")}});let h=!1,f=(S,b)=>{b.type!=="PRESET_ACTION"||b.command.type!=="CLICK"||(r.emit("targetRecordingUpdate",{type:S,stepId:l,parentStepIdChain:c,command:b.command,attribute:d}),p.abort(),h=!0)};setTimeout(()=>{h||(p.abort(),r.emit("targetRecordingUpdate",{type:"error",err:"Timed out waiting for click event",stepId:l,parentStepIdChain:c,attribute:d}))},1e4),await m.startRecordMode({params:{generator:g,logger:n,testId:s,orgId:a,callbacks:{onActionReceived:S=>f("clickReceived",S),onStepRecorded:S=>f("descriptionGenerated",S)}},abortController:p,isClickToRecord:!0}),r.emit("targetRecordingUpdate",{type:"listenersInitialized",stepId:l,parentStepIdChain:c,attribute:d})}},ib={event:"recordTargetClick",createHandler:_L};var DL=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async({key:o})=>{let i=n.getSession(r);if(!i)throw new Error("No active session found");if(o==="Dead")return;let{controller:a}=i;if(a.browser.closed||a.browser.getActivePage().isClosed()){e.debug({sessionId:r},"Browser is closed, ignoring keyboard press socket event");return}try{a.setOpen(),await a.browser.keyDown(o,{})}catch(s){if(s.message.includes("has been closed")){e.debug({sessionId:r,err:s},"Browser is closed, ignoring key down socket event error");return}throw s}}},ab={event:"keyDownEvent",createHandler:DL};var FL=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async({key:o})=>{let i=n.getSession(r);if(!i)throw new Error("No active session found");if(o==="Dead")return;let{controller:a}=i;if(a.browser.closed||a.browser.getActivePage().isClosed()){e.debug({sessionId:r},"Browser is closed, ignoring keyboard press socket event");return}try{a.setOpen(),await a.browser.keyUp(o,{})}catch(s){if(s.message.includes("has been closed")){e.debug({sessionId:r,err:s},"Browser is closed, ignoring key up socket event error");return}throw s}}},sb={event:"keyUpEvent",createHandler:FL};var UL=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t,o,i=0,a=(c,d)=>{let u=async()=>{o=void 0};clearTimeout(o),o=setTimeout(u,Math.min(1e3,250*(i+1)))},s,l=0;return async c=>{let d=n.getSession(r);if(!d)throw new Error("No active session found");let{controller:u,browserBehavior:m}=d,g=u.browser;if(g.closed||g.getActivePage().isClosed()){e.warn("Ignoring mouse move because the page is closed");return}if(c.event==="scroll"){let p=await g.scrollFromPositionPercentages(c.percentX,c.percentY,s?.x??0,s?.y??0),h=d.browserBehavior.recordingState?.transformer;h&&p&&h.recordScroll(p);return}m.showOverlay&&a(g,c);try{let p=await g.moveMouseFromPositionPercentages(c.percentX,c.percentY);l=0,s=p}catch(p){l++,l%5===0&&e.warn({err:p,mouseErrors:l},"Error in socket mouse move handler")}}},lb={event:"mouseMoveEvent",createHandler:UL};var BL=({metadata:t,generatorFactory:e,socket:n,logger:r,globalE2eStateManager:o})=>{let{sessionId:i,orgId:a,testId:s}=t;return async({stepId:l})=>{let c=o.getSession(i);if(!c)throw new Error("No active session found");let{controller:d,browserBehavior:u}=c,m=await e(a,r);r.info("Starting cloud recording");let g=new AbortController,p=await d.startRecordMode({params:{generator:m,logger:r,testId:s,orgId:a,callbacks:{onActionReceived:(h,f)=>{n.emit("stepRecorded",{stepId:l,step:h,offset:f})},onStepRecorded:(h,f)=>{n.emit("stepRecorded",{stepId:l,step:h,offset:f})}}},abortController:g,isClickToRecord:!1});u.recordingState={transformer:p}}},cb={event:"recordingStart",createHandler:BL};var zL=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async()=>{let o=n.getSession(r);if(!o)throw new Error("No active session found");e.info("Stopping cloud recording"),await o.controller.stopRecordMode(),o.browserBehavior.recordingState=void 0,o.browserBehavior.showOverlay=!1}},db={event:"recordingStop",createHandler:zL};var HL=({socket:t,metadata:e,logger:n,storageFactory:r,authorization:o,flagStoreFactory:i,settingsFactory:a,globalE2eStateManager:s})=>async(l,c)=>{let{testId:d,sessionId:u,orgId:m}=e;n.info({testId:d,sessionId:u},"Refresh event received");let g=await i(m),p=await a(m,n),h=await r(m),{baseUrl:f}=await mo({testId:d,orgId:m,logger:n,storage:h,authorization:o,flagStore:g,settings:p}),S=s.getSession(u);if(!S){t.emit("error",{message:"No session to refresh"});return}let{controller:b}=S;b.setOpen(),await b.browser.refresh();let E=b.browser.getViewport();n.info({baseUrl:f,viewport:E},`Session refreshed for test ${d} at ${f}`),c()},ub={event:"refresh",createHandler:HL};var $L=({socket:t,metadata:e,logger:n,storageFactory:r,authorization:o,flagStoreFactory:i,settingsFactory:a,globalE2eStateManager:s})=>async()=>{let{testId:l,sessionId:c,orgId:d}=e;n.info({testId:l,sessionId:c},"Reset event received");let u=await i(d),m=await a(d,n),g=await r(d),{baseUrl:p,envName:h,testName:f,environmentVariables:S}=await mo({testId:l,orgId:d,logger:n,storage:g,authorization:o,flagStore:u,settings:m}),b=s.getSession(c);if(!b){t.emit("error",{message:"No session to reset"});return}let{controller:E,context:v}=b;await E.browser.reset({newUrl:p});let R=E.browser.baseUrl;v.reset({baseUrl:R,currentUrl:E.browser.url(),variablesFromEnvironment:S,envName:h,testName:f});let C=E.browser.getViewport(),x=Nn.USER_AGENT;n.info({baseUrl:p,viewport:C},`Session reset for test ${l} at ${R}`),t.emit("session",{url:R,userAgent:x,viewport:C,sessionId:c})},mb={event:"reset",createHandler:$L};var jL=({metadata:t,globalE2eStateManager:e})=>{let{sessionId:n}=t;return async({url:r})=>{let o=e.getSession(n);if(!o)throw new Error("No active session found");await o.controller.browser.switchToPage({type:"SUBSTRING",substring:r})}},pb={event:"switchTab",createHandler:jL};async function gb(t){return eb(t)}var hb=[qf,tb,rb,mb,ub,Gf,pb,nb,ib,cb,db,lb,ob,ab,sb,Vf,Wf];var fb=t=>{let{logger:e}=t,n=new GL(t.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0});return n.on("connection",async r=>{let o;try{e.info({event:"connection",transport:r.conn.transport.name},"Websocket connection established"),o=await gb({...t,socket:r,logger:e}),e=e.child(o)}catch(i){e.error({event:"connection",type:"websocket",err:i},"Failed to setup connection"),r.emit("error",{message:i instanceof Error?i.message:`${i}`}),r.disconnect(!0);return}hb.forEach(i=>WL(i,{...t,socket:r,metadata:o,logger:e}))}),n},WL=(t,e)=>{let n=t.createHandler(e),r=(...o)=>{["mouseMoveEvent","keyDownEvent","keyUpEvent","mouseClickEvent","lintStep"].includes(t.event)||e.logger.debug({...e.metadata,event:t.event},`Websocket event (${t.event})`);let i=a=>{e.logger.error({event:t.event,type:"websocket",err:a instanceof Error?a:new Error(`${a}`)},"Unhandled exception in socket handler"),e.socket.emit("error",{message:a instanceof Error?a.message:`${a}`})};try{let a=n.apply(void 0,o);a&&typeof a.catch=="function"&&a.catch(i)}catch(a){i(a)}};e.socket.on(t.event,r)};import{Router as JL}from"express";import{Router as KL}from"express";import Sa from"fs";import fa from"path";import{v4 as YL}from"uuid";import XL from"yaml";import{hostname as VL}from"os";var qL="2.15.2",ut=Cs({app:"desktop-server",hostname:VL(),disableConsoleLogs:!0}).child({cliVersion:qL});var mi=KL();async function ku(t){return(await Ys(t,ut)).map(r=>{let o=t.modules[r.moduleId];if(!o){y.warn(`Found a dangling module with ID ${r.moduleId} that could not be found on disk.`);return}return{...o,content:r}}).filter(r=>r!==void 0)}mi.get("/",me(async(t,e)=>{let n=ae(),r=te(n,y),o=await ku(r);e.status(200).json(o)}));mi.post("/",me(async(t,e)=>{let n;try{n=ng.parse(t.body)}catch(s){e.status(400).json({error:`Invalid request body: ${s}`});return}try{Vr(n.name)}catch(s){e.status(400).json({error:`Invalid module name: ${s}`});return}let r=ae(),o=te(r,y).modules;if(Object.values(o).find(s=>s.name===n.name)){e.status(400).send(`A module with the name "${n.name}" already exists. Please choose a different name.`);return}let i=fa.join(r.rootDir,n.folderPath??"");if(!Sa.existsSync(i)||!Sa.statSync(i).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${i}' does not exist.`});return}let a=await Rf({...n,folder:i,project:r});e.status(201).json(a)}));mi.get("/:moduleId",me(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let n=te(ae(),y),r=n.modules[t.params.moduleId];if(!r){e.status(404).json({error:"Module not found."});return}try{let o=await Ks(r,n,y);e.json(o)}catch(o){e.status(400).json({err:o})}}));mi.post("/:moduleId/duplicate",me(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=tg.parse(t.body)}catch(h){e.status(400).json({error:`Invalid request body: ${h}`});return}try{Vr(n.name)}catch(h){e.status(400).json({error:h.message});return}let r=ae(),o=te(r,y),i=o.modules[t.params.moduleId];if(!i){e.status(404).json({error:"Module not found."});return}if(Object.values(o.modules).find(h=>h.name===n.name)){e.status(400).send(`A module with the name "${n.name}" already exists. Please choose a different name.`);return}let a=await Ks(i,o,y),s=fa.join(r.rootDir,fa.dirname(i.relativePath));if(!Sa.existsSync(s)||!Sa.statSync(s).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${s}' does not exist.`});return}let l=ve(n.name),c=fa.join(s,`${l}.module.yaml`),d=YL(),{stepsToSave:u}=await ze({stepLists:{steps:a.steps},createNewCacheIds:!0,cacheCreationParams:{orgId:nn()}}),m={fileType:fe.MODULE,schemaVersion:ce,moduleId:d,name:n.name,description:"",enabled:!0,steps:u.steps,parameters:a.parameters,defaultParameters:a.defaultParameters,parameterEnums:a.parameterEnums,defaultCacheKey:a.defaultCacheKey,defaultCacheTtl:a.defaultCacheTtl,defaultCacheAllInvocations:a.defaultCacheAllInvocations,autoAuth:a.autoAuth,advanced:a.advanced},g=XL.stringify(m);Sa.writeFileSync(c,g,"utf-8");let p={relativeFilePath:fa.relative(r.rootDir,c)};e.status(201).json(p)}));mi.patch("/:moduleId/metadata",me(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=rg.parse(t.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let r=ae(),o=te(r,y);Cf({moduleId:t.params.moduleId,content:n,momenticFiles:o,logger:y,project:r}),e.status(201).json({message:"ok"})}));var Sb=mi;var yb=JL();yb.get("/",me(async(t,e)=>{let n=ae(),r=te(n,y),o=new Set;r?.tests&&Object.values(r.tests).forEach(c=>{c.labels?.forEach(d=>o.add(d))});let i=Array.from(o).sort(),a=Object.values(r.tests),s=await ku(r),l={labels:i,tests:a,modules:s};e.status(200).json(l)}));var bb=yb;import{Router as QL}from"express";var _u=QL();_u.get("/",me((t,e)=>{let n=If(ae(),ut);e.status(200).json(n)}));_u.get("/names",me((t,e)=>{let r=ae().config.environments?.map(o=>o.name)??[];e.status(200).json(r)}));var Tb=_u;import{Router as ZL}from"express";var wb=ZL();wb.get("/",me((t,e)=>{e.status(200).json({userId:Vs(),orgId:nn()})}));var Eb=wb;import{Router as eM}from"express";var vl=eM();vl.get("/",me((t,e)=>{let n=Gd().map(r=>({name:r.config.name,configFilePath:r.configFilePath}));e.status(200).json(n)}));vl.get("/current",me((t,e)=>{let n=ae();if(!n){e.status(404).json({error:"No project found."});return}let r={name:n.config.name,configFilePath:n.configFilePath};e.status(200).json(r)}));vl.post("/set",me((t,e)=>{let n;try{n=ig.parse(t.body)}catch(r){e.status(400).json({error:`Invalid request body: ${r}`});return}try{let r=ct({configFilePath:n.configFilePath});qs(r,o=>ct({configFilePath:o}))}catch(r){e.status(400).json({error:`Error setting project: ${r}`});return}e.sendStatus(204)}));var Cb=vl;import{Router as tM}from"express";var Rb=tM();Rb.get("/",me((t,e)=>{let r={ai:ae().config.ai};e.status(200).json(r)}));var vb=Rb;import{convertToModelMessages as vM,stepCountIs as AM,streamText as xM}from"ai";import IM from"dedent";import{Router as PM}from"express";import Ob from"fs";import ho from"path";import{v4 as Nb}from"uuid";import LM from"yaml";import nM from"path";var Al=class{_result=[];_includeSnapshot=!1;_includeTestContext=!1;_includeTest=!1;_isError;_browser;_testContext;_project;_logger;_testPath;constructor(e,n,r,o,i){this._browser=e,this._testContext=n,this._project=r,this._logger=o,this._testPath=i}addResult(e){this._result.push(e)}result(){return this._result.join(`
3891
+ `&&(a=s),t.slice(o,a)}function pn(t){let e=typeof t=="string"?t:t.toString();return`[${Kn}="${e}"]`}import{execSync as iM}from"child_process";import{randomUUID as Lu}from"crypto";import{diff as Ou}from"deep-object-diff";import{existsSync as Il,mkdirSync as sM,readFileSync as lM,writeFileSync as cM}from"fs";import{Jimp as Gy}from"jimp";import dM from"js-beautify";import{cloneDeep as yi}from"lodash-es";import uM from"mime";import{homedir as ku,hostname as mM,platform as pM}from"os";import{basename as gM,extname as hM,join as ua,resolve as fM}from"path";import{chromium as Vy,devices as SM}from"playwright";import{addExtra as yM}from"playwright-extra";import bM from"puppeteer-extra-plugin-recaptcha";import{v4 as TM}from"uuid";import{rmSync as cy}from"fs";import{basename as oP,join as aP}from"path";import{errors as iP}from"playwright-core";var jS=new Set(["about:blank","chrome-error://chromewebdata/"]);var iu=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],su=1e4,fi=500;import{mkdirSync as _I,rmSync as GS,statSync as DI}from"fs";import*as uu from"node:fs";import FI from"nodejs-file-downloader";import{tmpdir as UI}from"os";import br,{basename as BI,dirname as zI}from"path";var mu="file://",du=br.join(UI(),"momentic","downloads"),cu=1e4,HI=50*1024*1024;async function WS(t){let{uri:e}=t;return e.startsWith(mu)?jI(t):e.startsWith("http")?WI(t):GI(t)}function $I(t,e){let n=br.join(du,t,e.slice(mu.length)),r=br.join(du,t),o=n.startsWith(r);if(!uu.existsSync(n)||!o)throw new A("UserConfigurationError",`The referenced file (${e}) does not exist. Please make sure that it has been downloaded successfully.`);return n}async function jI({uri:t,orgId:e}){let n=$I(e,t);return{filePath:n,cleanup:()=>{GS(zI(n),{recursive:!0,force:!0})}}}async function GI({uri:t}){let e=br.resolve(t);if(!uu.existsSync(e))throw new A("UserConfigurationError",`The referenced file (${t}) does not exist on disk. Please make sure that it has been downloaded successfully.`);return{filePath:e,cleanup:()=>{}}}async function WI({uri:t,logger:e,orgId:n}){let r=new URL(t);r.search&&(r.search="");let o=BI(r.href),a=gu(o),i=br.extname(a);if(og.includes(i))throw new Error(`Downloading files with extension ${i} is not allowed.`);let s=pu(n),l=new FI({url:t,fileName:a,directory:s,maxAttempts:2,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36"},timeout:cu}),{downloadStatus:c,filePath:d}=await H(l.download(),{milliseconds:cu,message:`Download timed out after ${cu}ms`});if(c!=="COMPLETE")throw new Error(`Download ended in non-success status: ${c}`);if(!d)throw new Error("File path of successfully downloaded file was empty");let m=DI(d).size;if(m>HI)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:m,filePath:d,fileName:a},"Downloaded file to disk");let p;return{filePath:d,cleanup:()=>{clearTimeout(p),p=setTimeout(()=>GS(s,{recursive:!0,force:!0}),10*60*1e3)}}}function VS(t,e){return`${mu}${t}/${e}`}function pu(t){let e=Math.random().toString(36).substring(4),n=br.join(du,t,e);return _I(n,{recursive:!0}),n}function gu(t){let e=br.extname(t),n=br.basename(t,e);return t=(n.length>100?n.slice(n.length-100):n)+e,t=t.trim().replaceAll(" ","_"),t}async function Yn(t,e){try{return await t.evaluate(r=>window.serializeElementOnlyWithText?.(r,{truncateToLength:500}),void 0,{timeout:1e3})}catch(n){e.debug({err:n},"Failed to get HTML from locator for Playwright error translation");return}}async function qS(t,e){let n=t.evaluate(async()=>{let a=window,i={};try{let s=await indexedDB.databases();for(let l of s){if(!l.name)continue;let c=await a.exportIdbToObject?.(l.name,l.version);c&&(i[l.name]=c)}return[i,void 0]}catch(s){return[void 0,s.message]}}),[r,o]=await H(n,{milliseconds:3e3});return o&&e.warn({err:o},"Failed to fetch indexedDB data"),r}async function KS(t,e,n){if(e){n.debug("Importing indexedDB data");try{let r=t.evaluate(async o=>{let a=window;for(let[i,s]of Object.entries(o))await a.importObjectToIdb?.(i,s)},e);await H(r,{milliseconds:3e3})}catch(r){n.warn({err:r},"Failed to import indexedDB data")}}}async function YS(t,e){try{let n=t.evaluate(async()=>{window.localStorage.clear(),window.sessionStorage.clear(),await indexedDB.databases().then(r=>{r.forEach(o=>{o.name&&indexedDB.deleteDatabase(o.name)})})});await H(n,{milliseconds:3e3})}catch(n){e.debug({err:n},"Failed clearing index db data, continuing...")}}async function XS(t,e,n,r,o){try{await VI(t,e,n,r)}catch(a){o.error({err:a,tabIndex:e},"Error handling new console log")}}async function VI(t,e,n,r){let o=r.text();o.length>fi&&(o=o.slice(0,fi)+"...(TRUNCATED)");let a=[];for(let i of r.args())try{let s=await i.jsonValue(),l=JSON.stringify(s);l.length>fi?a.push(l.slice(0,fi)+"...(TRUNCATED)"):(typeof s!="object"||Object.keys(s).length>0)&&a.push(s)}catch{}hu(t,n,e,{url:t.url(),location:r.location(),type:r.type(),text:r.text(),args:a})}function hu(t,e,n,r){let o=Date.now(),a=e.logsPerPage;if(a.length<=n||a[n]===void 0){a[n]=[];for(let i=0;i<n;i++)a[i]===void 0&&(a[i]=[])}a[n].length>su&&(a[n]=a[n].slice(Math.floor(su/2)),a[n]?.push({url:t.url(),timestamp:o,type:"warning",text:"[MOMENTIC] Truncated console logs due to buffer overflow",tabIndex:n})),a[n].push({...r,tabIndex:n,timestamp:o})}async function on({fn:t,codePath:e,logObject:n,signal:r,logger:o}){r?.throwIfAborted();let a=Date.now(),i=await ai({promiseGenerator:t,signal:r,codePath:e,logger:o}),s=Date.now();return n[e]=s-a,i}var qI="[redacted due to size]",KI=1e4;async function QS(t,e,n){let r=new Date().toISOString();e.harPages||(e.harPages={}),e.harPages[t]={id:t,startedDateTime:r,title:void 0,pageTimings:{}}}async function fu(t,e){let n=e.timing(),r=new URL(e.url()),o=[...r.searchParams.entries()].map(([s,l])=>({name:s,value:l})),a={...await ey(e),url:r.toString(),method:e.method(),queryString:o,postData:await XI(e)};return{pageref:t,_resourceType:e.resourceType(),startedDateTime:new Date().toISOString(),request:a,timings:ty(n).timings}}async function ZS(t,e,n){await n.finished();let r={};try{r=await JI(n)}catch{}let o={...await ey(n),status:n.status(),statusText:n.statusText(),content:r,redirectURL:n.headers().location};t.response=o;let a;try{a=await e.sizes(),t.request.bodySize=a.requestBodySize,t.request.headersSize=a.requestHeadersSize}catch{}t.response&&a&&(t.response.bodySize=a.responseBodySize,t.response.headersSize=a.responseHeadersSize,t.response.content.size=a.responseBodySize);let i=e.timing();t.startedDateTime=new Date(i.startTime).toISOString();let{timings:s,total:l}=ty(i);t.time=l,t.timings=s}function Si(t,e,n){t.harEntries||(t.harEntries={}),t.harEntries[n]=e}function JS(t){try{return new Date(t).toISOString()}catch{return}}function YI(t){let e={name:"",value:""},n=!0;for(let r of t.split(/; */)){let o=r.indexOf("="),a=o!==-1?r.substring(0,o).trim():r.trim(),i=o!==-1?r.substring(o+1,r.length).trim():"";if(n){n=!1,e.name=Ln(a),e.value=Ln(i);continue}a==="Domain"&&(e.domain=Ln(i)),a==="Expires"&&(e.expires=JS(i)),a==="HttpOnly"&&(e.httpOnly=!0),a==="Max-Age"&&(e.expires=JS(Date.now()+ +i*1e3)),a==="Path"&&(e.path=Ln(i)),a==="Secure"&&(e.secure=!0)}return e}async function ey(t){let e=await t.allHeaders(),n=e.cookie?.split(";").map(YI)??[];return{headers:Object.entries(e).map(([r,o])=>({name:Ln(r),value:Ln(o)})),cookies:n}}async function XI(t){let e=t.postData();if(!e)return;let n=await t.headerValue("content-type"),r={mimeType:n??"application/octet-stream",text:Ln(e),params:[]};if(n==="application/x-www-form-urlencoded"){let o=new URLSearchParams(e.toString());for(let[a,i]of o.entries())r.params.push({name:Ln(a),value:i?Ln(i):void 0})}return r}async function JI(t){return{mimeType:await t.headerValue("content-type")??void 0,text:Ln(await t.text()),encoding:await t.headerValue("content-encoding")??void 0}}function Ln(t){return t.length>KI?qI:t}function co(t){return t<0?0:t}function ty(t){return{timings:{blocked:co(t.domainLookupStart),dns:co(t.domainLookupEnd-t.domainLookupStart),connect:co(t.connectEnd-t.connectStart),send:co(t.responseStart-t.requestStart),wait:0,receive:co(t.responseEnd-t.responseStart),ssl:co(t.connectEnd-t.secureConnectionStart)},total:co(t.responseEnd)}}function ny(){return async t=>{let{fragment:e,code:n,context:r}=t,{env:o}=r||{},a=Object.getPrototypeOf(async function(){}).constructor;return{result:await Promise.resolve(new a("env",e?`return ${n}`:n)(o))}}}async function Qe({root:t,fn:e,arg:n,timeout:r,waitForPageLoad:o,codePath:a}){return await o(),await H(t.evaluate(e,n),{milliseconds:r,message:`Timed out ${a} after ${r}ms. This indicates that either the page is unresponsive or your machine is severely resource constrained.`})}function Su(){return window.lastCursorPos}import{errors as QI}from"playwright-core";async function uo({func:t,action:e,logger:n,callbacks:r,retryTimeoutMs:o,targetingResult:a}){let i=Date.now(),s;for(;Date.now()-i<o;)try{return await t(a)}catch(l){let c=l;if(Ga(c)){n.warn("Attempting to recover from removed data-momentic-ids by re-adding ids to DOM");let[d]=await Promise.all([t(a),r.getBrowserState({skipWaitForPageLoad:!0,skipWait:!0})]);return d}else if(c instanceof QI.TimeoutError)n.warn({err:c,rootUrl:(await r.state.getRoot()).url()},`Encountered Playwright error while performing ${e}`),s=await ZI(c,a.locator,r,n);else throw c}throw s instanceof A?s:new A("ActionFailureError",`Failed to interact with targeted element. Error: ${s.message}`,{errOptions:{cause:s}})}async function ZI(t,e,n,r){return t.message.includes("attempt #")?eP(t,e,n,r):tP(t)}async function eP(t,e,n,r){let o=t.message.split(/- retrying \w+ action, attempt #\d+/).filter(l=>l.length>0);if(!o.length)return r.warn({err:t},"Failed to parse Playwright error message for translation, returning raw message"),t;let a=o.length>2?o[o.length-2]:o[0];a=a.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,"").replaceAll(" - ","").trim().replaceAll(`
3892
+ `,";").replace(/\s+/g," ");let i="",s=await Yn(e,r);if(s&&(i=`Target element HTML: ${$e(s,100,!0)}`),a.includes("element is not enabled"))return new A("ActionFailureError",`The element you attempted to interact with was disabled for the entire timeout duration. Please explicitly wait for the element to be enabled, change the element description to target an interactive element, or turn on the 'disable stability checks' option. ${i}`,{errOptions:{cause:t}});if(a.includes("intercepts pointer events")){let l="",c=a.match(/<.*?data-momentic-id="(\d+)".*?intercepts pointer events/)?.[1];if(c){let d=(await n.state.getRoot()).locator(pn(c)),u=await Yn(d,r);u&&(l=`Covering element HTML: ${$e(u,100,!0)}`)}return new A("ActionFailureError",`The element you attempted to interact with was covered by another element such as dropdown, popup, or dialog for the entire timeout duration. Please add a step to hide the covering element or turn on the 'disable stability checks' option. ${i}
3893
+ ${l}`,{errOptions:{cause:t}})}if(a.includes("element is not visible")){let l="The element you attempted to interact with has no bounding box or is explicitly hidden.";try{let c=await e.boundingBox({timeout:3e3});c?c.height===0?l="The element you attempted to interact with has zero height.":c.width===0&&(l="The element you attempted to interact with has zero width."):l="The element you attempted to interact with has no bounding box."}catch{}return new A("ActionFailureError",`${l} Please explicitly wait for the element to be visible or turn on the 'disable stability checks' option. ${i}`,{errOptions:{cause:t}})}return a.includes("element is outside of the viewport")?new A("ActionFailureError",`The element requested was outside of the browser viewport for the entire duration of the action. Please ensure you are not using non-standard zoom settings and the element is visible on the page. ${i}`):t}function tP(t){let e=t.message;if(e.includes("waiting for locator")&&e.includes("data-momentic-id")&&!e.match(/attempting \w+ action/)&&!e.includes("locator.evaluate"))throw new A("ActionFailureError",`Interacting with the element timed out. This is usually caused by the web page itself performing too many CPU-intensive operations or a lack of resources on your machine. Error: ${e}`,{errOptions:{cause:t}});return t}async function ry(t){try{return await nP(t)}catch(e){t.logger.warn({err:e},"Failed to transform locator for Chakra click, continuing...");return}}async function nP({locator:t,logger:e}){let[n,r]=await t.evaluate(l=>[l.id,l.tagName.toLowerCase()],{timeout:1e3}),o=await Yn(t,e),a=await t.boundingBox({timeout:1e3});if(a===null){e.warn({elementDisplayString:o},"Attempting to click on element with no bounding box, not performing Chakra redirection");return}if(a.width>5||a.height>5||r!=="input")return;if(n)try{let l=t.page().locator(`label[for=${JSON.stringify(n)}]`);return await l.waitFor({state:"visible",timeout:1e3}),{locator:l,relativePoint:void 0}}catch{}let i=await t.evaluate(l=>{let c=window,d=l.parentElement;if(!d)return{type:"error",error:"Input click target has no parent for redirection"};let u=l.getBoundingClientRect(),m=d.getBoundingClientRect();if(m.width===0||m.height===0)return{type:"error",error:"Parent element has no width or height"};let p={x:Math.min(Math.max(1,u.left-m.left),m.width-1),y:Math.min(Math.max(1,u.top-m.top),m.height-1)},g=c._MOMENTIC_FEATURE_FLAGS?.[fl],h=l.getAttribute(Kn),f=!g&&h?pn(h):c.getMPath?.(l)?.join(" >");return f?{type:"result",selector:f,relativePoint:p,serializedForm:d.outerHTML.slice(0,500)}:{type:"error",error:"Could not generate selector for parent element"}},{timeout:1e3});if(i.type==="error")throw new Error(i.error);let s=t.page().locator(i.selector);return await s.waitFor({state:"visible",timeout:1e3}),e.info({parentElementResult:i,originalElementDisplayString:o},`Redirected click to parent element with selector: ${i.selector}`),{locator:s,relativePoint:i.relativePoint}}var ay=["date","datetime-local","month","time","week"],oy={date:/^\d{4}-\d{2}-\d{2}$/,"datetime-local":/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/,month:/^\d{4}-\d{2}$/,time:/^\d{2}:\d{2}$/,week:/^\d{4}-W\d{2}$/};async function iy(t){try{await H(rP(t),{milliseconds:3e3})}catch(e){t.logger.warn({err:e},"Failed to transform native datetime input, continuing...")}}async function rP({root:t,text:e,options:n,logger:r,callbacks:o}){let a=(await Qe({root:t,fn:()=>document.activeElement?.getAttribute("type")??"",timeout:1e3,arg:void 0,waitForPageLoad:o.waitForPageLoad,codePath:"transforming native datetime input"})).toLowerCase();if(!oy[a])return;oy[a].test(e)&&r.warn(`Detected datetime input (${e}) in normalized format - this may fail to fill correctly as it is not how the user would input the value`),n.clearContent=!1,r.info("Transforming datetime input to use sequential key presses")}import{z as Ft}from"zod";var sy=Ft.object({doubleClick:Ft.boolean().optional(),rightClick:Ft.boolean().optional(),force:Ft.boolean().optional(),waitForDownload:Ft.boolean().optional(),delayMs:Ft.number().optional(),downloadTimeoutMs:Ft.number().optional(),relativePosition:Ft.object({x:Ft.number(),y:Ft.number()}).optional()}),$ee=Ft.object({repeat:Ft.number().optional(),convertMeta:Ft.boolean().optional().describe("misleading name due to backcompat. converts keyshortcuts + meta/control to platform-specific combos. defaults to true"),delayMs:Ft.number().optional()});async function Sl({locator:t,callbacks:e,logger:n,timeoutMs:r=1e3}){try{await yu(e,r);let o=t.evaluate(a=>{let i=window;i.momenticIsEligible=u=>{let p=window.getComputedStyle(u,null).getPropertyValue("display");if(p==="none"||p==="contents")return!1;let g=u.getBoundingClientRect();return!(!g.height||!g.width)},i.removeHighlightTimers=i.removeHighlightTimers||[],i.removeHighlightFunctions=i.removeHighlightFunctions||{};let s=0;for(;!i.momenticIsEligible(a)&&s<3;){if(!a.parentElement)throw new Error("No eligible non-empty parent found for highlighting");a=a.parentElement,s++}let l=a.style.getPropertyValue("outline"),c=a.style.getPropertyPriority("outline");a.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let d=`momentic${Math.floor(Math.random()*1e7)}`;i[d]=()=>{a.style.removeProperty("outline"),a.style.setProperty("outline",l,c),a.getAttribute("style")||a.removeAttribute("style")},i.removeHighlightTimers.push(setTimeout(()=>{i[d](),i.removeHighlightFunctions?.[d]&&delete i.removeHighlightFunctions[d]},5e3)),i.removeHighlightFunctions[d]=i[d]},void 0,{timeout:r});return await H(o,{milliseconds:r}),!0}catch(o){return n.debug({err:o},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}async function yu(t,e=1e3){let n=await t.state.getRoot();await Qe({root:n,fn:()=>{let o=window,a=o.removeHighlightTimers||[];for(;a.length;){let i=a.pop();clearTimeout(i)}Object.values(o.removeHighlightFunctions??{}).forEach(i=>{i()})},timeout:e,arg:void 0,waitForPageLoad:t.waitForPageLoad,codePath:"removing element highlights"})}async function bu(t){let e=!!t.browserCallbacks.state.userBrowserSettings.visualActions;return uo({action:"clicking element",targetingResult:t.targetingResult,logger:t.logger,retryTimeoutMs:t.retryTimeoutMs,callbacks:t.browserCallbacks,func:async n=>dy({...t,targetingResult:n,useVisualClick:e})})}async function sP(t,e){let{redirectionAttempts:n=0}=e;if(n>=2)throw t;try{return await lP(t,e)}catch(r){throw e.redirectionAttempts===0?(e.logger.error({redirectionAttemptError:r,originalError:t},"Error handling click error, rethrowing original error"),t):r}}async function lP(t,e){let{logger:n,redirectionAttempts:r=0}=e,o=e.targetingResult.locator;if(t.message.includes("label")&&t.message.includes("for=")&&t.message.includes("intercepts pointer events")){let a=await o.getAttribute("id",{timeout:1e3});if(!a)throw t;let i=o.page().locator(`[for=${JSON.stringify(a)}]`);return await i.waitFor({state:"visible",timeout:1e3}),n.warn({err:t},"Attempting locator redirection due to input being covered by label"),dy({...e,targetingResult:{locator:i},redirectionAttempts:r+1})}else throw n.error({err:t},"Click error does not match any known recoverable patterns, rethrowing"),t}async function cP(t){let{browserCallbacks:e,logger:n,targetingResult:r,position:o,options:a}=t,i=await e.state.getRoot(),s=i&&i!==r.locator.page()&&"frameElement"in i?await i.frameElement():null,l;try{l=s?await to({promiseGenerator:async()=>s.boundingBox(),timeoutMs:3e3,logger:n}):null}catch(g){throw new A("UserInfrastructureError",`The frame containing the element Momentic was instructed to interact with was removed. Error: ${g.message}`)}finally{await s?.dispose()}let c=Date.now(),{clickX:d,clickY:u,reason:m}=await mP({frameCoordinates:l,logger:n,targetingResult:r,position:o,options:a}),p=sy.safeParse(a);n.info({frameCoordinates:l,position:o,options:p.success?p.data:void 0,clickLocation:{clickX:d,clickY:u,reason:m},duration:Date.now()-c},"Visual click")}async function dP(t){let{actionSource:e,targetingResult:n,options:r,logger:o}=t,a=t.targetingResult.locator,i=r?.relativePosition??t.position;if(e==="click"&&!i){let l=await ry({locator:a,logger:o});l&&(a=l.locator,i=l.relativePoint??i)}let s=r?.force||n.hints?.force||!1;try{r?.doubleClick?await a.dblclick({button:r.rightClick?"right":"left",timeout:3e3,position:i,delay:r?.delayMs??25,force:s}):await a.click({button:r?.rightClick?"right":"left",timeout:3e3,position:i,delay:r?.delayMs??25,force:s})}catch(l){let c=l;if(gP(c))o.warn({err:c},"Click action timed out while waiting for navigation after completion, continuing...");else return o.error({err:c},"Error clicking on locator, attempting to recover..."),sP(c,{...t,targetingResult:{...a,locator:a}})}}async function dy(t){let{options:e,logger:n,browserCallbacks:r,controllerCallbacks:o,useVisualClick:a,targetingResult:i}=t,s;e?.waitForDownload&&(s=(async()=>{let l=e.downloadTimeoutMs??3e4;try{return await i.locator.page().waitForEvent("download",{timeout:l})}catch(c){return c instanceof iP.TimeoutError?new A("ActionFailureError",`Download did not complete in ${l}ms`):new A("ActionFailureError",`Download failed: ${c.message}`)}})());try{await Sl({locator:i.locator,callbacks:r,logger:n,timeoutMs:1e3})}catch(l){n.warn({err:l},"Error highlighting locator in click, continuing...")}if(a?await cP(t):await dP(t),e?.waitForDownload)if(s){if(!o?.createIsolatedFolder)throw new A("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");n.info("Waiting for download to start and complete");let l=await H(s,{milliseconds:e.downloadTimeoutMs??3e4});if(l instanceof Error)throw l;return{downloadedFile:await pP(l,o.createIsolatedFolder,n)}}else throw new Error("No download promise or error but the step requested to wait for a download")}async function uP(t,e){if(e.hints?.clickableXY){let a=(t?.x??0)+e.hints.clickableXY.x,i=(t?.y??0)+e.hints.clickableXY.y;return[{x:a,y:i},"targeting hint"]}let n=await e.locator.boundingBox({timeout:3e3});if(!n)throw new A("ActionFailureError","Element does not have a bounding box");let r=n.x+n.width/2,o=n.y+n.height/2;return[{x:r,y:o},"halfway point of the bounding box"]}async function mP({frameCoordinates:t,logger:e,options:n,targetingResult:r,position:o}){let a,i,s;if(o){let u=await r.locator.boundingBox({timeout:3e3});a=(t?.x??0)+(u?.x??0)+o.x,i=(t?.y??0)+(u?.y??0)+o.y,s="predefined position"}else{let[u,m]=await uP(t,r);a=u.x,i=u.y,s=m}let l=r.locator.page(),c=n?.rightClick?"right":"left",d=n?.delayMs??25;return n?.doubleClick?await l.mouse.dblclick(a,i,{button:c,delay:d}):await l.mouse.click(a,i,{button:c,delay:d}),{clickX:a,clickY:i,reason:s}}async function pP(t,e,n){n.info("Download detected, saving file to disk");let r=await t.path(),o=gu(t.suggestedFilename()),a=e();await t.saveAs(aP(a,o)),cy(r,{force:!0}),setTimeout(()=>{cy(a,{recursive:!0,force:!0})},5*60*1e3);let i=VS(oP(a),o);return n.info({uri:i,downloadFolder:a},"Saved download to isolated folder"),i}function gP(t){return t.message.includes("locator.click: Timeout")&&t.message.includes("click action done")}import{platform as hP}from"os";var fP={goToNextWord:{win32:"Control+ArrowRight",darwin:"Alt+ArrowRight",linux:"Control+ArrowRight"},goToPreviousWord:{win32:"Control+ArrowLeft",darwin:"Alt+ArrowLeft",linux:"Control+ArrowLeft"},selectNextWord:{win32:"Control+Shift+ArrowRight",darwin:"Alt+Shift+ArrowRight",linux:"Control+Shift+ArrowRight"},selectPreviousWord:{win32:"Control+Shift+ArrowLeft",darwin:"Alt+Shift+ArrowLeft",linux:"Control+Shift+ArrowLeft"},selectToStartOfLine:{win32:"Shift+Home",darwin:"Meta+Shift+LeftArrow",linux:"Shift+Home"},selectToEndOfLine:{win32:"Shift+End",darwin:"Meta+Shift+RightArrow",linux:"Shift+End"},deleteNextWord:{win32:"Control+Delete",darwin:"Alt+Fn+Delete",linux:"Control+Delete"},deletePreviousWord:{win32:"Control+Backspace",darwin:"Alt+Delete",linux:"Control+Backspace"}};function SP(){let t=hP();return t==="win32"?"win32":t==="darwin"?"darwin":"linux"}function uy(t){return JSON.stringify(t.split("+").sort())}function yl(t){let e=SP(),n=uy(t);for(let r of Object.values(fP))if(Object.values(r).some(o=>uy(o)===n))return r[e];return process.platform==="darwin"?t=t.replaceAll("Control","Meta"):t=t.replaceAll("Meta","Control"),t}async function Tu({frame:t,page:e,deltaX:n,directionX:r,deltaY:o,directionY:a,signal:i,callbacks:s,logger:l}){if(!n&&!o)return;let c=r==="left"?-1:1,d=a==="up"?-1:1;if(t)await Qe({root:t,fn:([u,m,p,g])=>window.scrollTo(window.scrollX+(u??window.innerWidth)*p,window.scrollY+(m??window.innerHeight)*g),arg:[n,o,c,d],waitForPageLoad:s.waitForPageLoad,timeout:2e3,codePath:"scrolling page"});else{let u=e.viewportSize()||Nt,m=await Qe({root:e,fn:()=>document.body.scrollHeight,arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:2e3,codePath:"computing page height"}),[p,g,h]=await Qe({root:e,fn:()=>{let f=document.activeElement;if(!f)return[void 0,void 0,void 0];let y=f.getBoundingClientRect();return[f.scrollTop,y.x,y.y]},arg:void 0,waitForPageLoad:s.waitForPageLoad,timeout:2e3,codePath:"computing active element position"});await e.mouse.wheel((n??u.width)*c,(o??u.height)*d);try{let f=Date.now();for(;Date.now()-f<2e3;){i?.throwIfAborted();let y=await H(e.evaluate(()=>document.body.scrollHeight),{milliseconds:1e3}),[b,w,C]=await H(e.evaluate(()=>{let v=document.activeElement;if(!v)return[void 0,void 0,void 0];let R=v.getBoundingClientRect();return[v.scrollTop,R.x,R.y]}),{milliseconds:1e3});if(y===m&&b===p&&w===g&&C===h)break;m=y,p=b,g=w,h=C,await J(500)}}catch(f){l.warn({err:f},"Failed to wait for scroll to complete, continuing...")}}}async function wu(t,e){let n,r;for(let o=0;o<4;o++)try{return n=t.pages(),await Promise.all(n.map(async a=>{let i="";try{i=e?.getTitles?await a.title():""}catch{i="Unknown page"}return{title:i,url:a.url()}}))}catch(a){r=a,await J(500)}throw new Error(`Failed to get tab titles after all retries: ${r?.message}`)}import{randomUUID as AP}from"crypto";import{cloneDeep as Ru}from"lodash-es";function Tr(t,e){let n=t.findIndex(r=>r===e);if(!(n===-1||!t[n+1]))return t[n+1]}import{createHash as yP}from"crypto";var bP="v1";function bl(t,e){if(t.tagName.toLowerCase()==="svg"&&!wP(t))try{let n=my(t,e),r=TP(JSON.stringify(n));return{version:bP,json:n,hash:r}}catch{return}}function TP(t){return yP("md5").update(t).digest("hex")}function my(t,e){let n=t.tagName.toLowerCase(),r=EP(t);if(n==="image"&&r["xlink:href"])throw new Error("Image tags within SVGs are not supported");let o={type:n,props:r,children:[]};for(let a of t.childrenBackendIds){let i=e.backendIdToNode[a];if(i&&i.nodeType===1){let s=my(i,e);s&&o.children.push(s)}}return o}function wP(t){let e=t.computedStyles.display,n=t.computedStyles.visibility,r=t.computedStyles.opacity;return e==="none"||n==="hidden"||r==="0"}function EP(t){let e={},n=t.attributes;for(let r of Object.keys(n))qn.visualAttributesForSvgSerialization.includes(r)&&(e[r]=n[r]);return n.id&&t.tagName.toLowerCase()!=="svg"&&(e.id=n.id),e}var mo={r:147,g:196,b:125,a:.55},gy={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:mo,paddingColor:mo,borderColor:mo,marginColor:mo,eventTargetColor:mo,shapeColor:mo,shapeMarginColor:mo,showInfo:!0,showAccessibilityInfo:!0},Tl=["display","opacity","visibility","height","position"];function hy({snapshot:t,devicePixelRatio:e,logger:n}){let r=t.strings,o=t.documents,a={},i={},s={roots:[],backendIdToNode:a,frameIndexToIframeNode:i};return o.forEach((l,c)=>{let d=RP({allDocuments:o,stringConstants:r,frameIndex:c,devicePixelRatio:e,backendIdToNode:a,frameIndexToIframeNode:i,logger:n});s.roots.push(d)}),s}function RP({allDocuments:t,stringConstants:e,devicePixelRatio:n,frameIndex:r,frameIndexToIframeNode:o,backendIdToNode:a,logger:i}){let s=t[r],l=s.layout,c={};l.nodeIndex.forEach((R,x)=>{c[R]=x});let d=l.styles,u=l.bounds??[],m=s.nodes,p=m.contentDocumentIndex??{index:[],value:[]},g=m.backendNodeId??[],h=m.attributes??[],f=m.parentIndex??[],y=m.nodeName??[],b=m.nodeType??[],w=m.pseudoType??{index:[],value:[]},C=m.inputChecked??{index:[]},v=e[s.frameId];for(let R=0;R<g.length;R++){let x=g[R],M=b[R],D=h[R]??[],_=f[R]!==void 0&&f[R]>=0?f[R]:void 0,K=_!==void 0?g[_]:void 0,P=K!==void 0?a[K]:void 0,W=w.index.indexOf(R),k=W!==-1?e[w.value[W]]:void 0,G=c[R],we;G?we=u[G]??[]:we=[];let Ce=y[R]!==void 0?e[y[R]]?.toLowerCase():void 0;if(!Ce){i.warn({backendNodeId:x,frameId:v,frameIndex:r,nodeBounds:we},"DOM node has no tag name");continue}let be={backendNodeId:x,psuedoType:k,nodeType:M,frameIndex:r,parentFrameId:v,ownedFrameId:void 0,bounds:{x:we[0]??null,y:we[1]??null,width:we[2]??null,height:we[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:K??null,tagName:Ce,parent:P??void 0,childrenBackendIds:[],momenticIgnored:void 0,mPathSelector:void 0};P&&P.childrenBackendIds.push(x);let wt=p.index.indexOf(R);if(wt!==-1){let de=p.value[wt];o[de]=be;let oe=t[de]?.frameId;be.ownedFrameId=oe!==void 0?e[oe]:void 0}for(let de of Object.keys(be.bounds)){let oe=de;be.bounds[oe]!==null&&(be.bounds[oe]/=n)}let Sn=G!==void 0?d[G]??[]:[];for(let de=0;de<Sn.length&&!(de>=Tl.length);de++){let oe=Sn[de];if(oe===void 0||isNaN(oe))continue;let ot=e[oe];if(ot===void 0)continue;let Pe=Tl[de];be.computedStyles[Pe]=ot}for(let de=0;de<D.length;de+=2){let oe=D[de],ot=D[de+1];if(!oe||!ot)continue;let Pe=e[oe],_n=e[ot];!Pe||!_n||(be.attributes[Pe]=_n)}C.index.includes(R)&&(be.attributes.checked="true"),a[be.backendNodeId]=be}return a[g[0]]}function Eu(t,e){if(t.mPathSelector)return t.mPathSelector;let n=t.parent,r;if(!n)r=t.tagName;else if(t.tagName==="body")r="body";else{let a=n.childrenBackendIds.filter(l=>e.backendIdToNode[l]?.nodeType===1&&!e.backendIdToNode[l]?.psuedoType).indexOf(t.backendNodeId),i=` > ${t.tagName}:nth-child(${a+1})`;r=`${Eu(n,e)}${i}`}return t.mPathSelector=r,r}function py(t,e){return t.parentBackendNodeId!==null?e.backendIdToNode[t.parentBackendNodeId]:t.frameIndex===0?void 0:e.frameIndexToIframeNode[t.frameIndex]}var CP=["html","#document","#document-fragment"];function fy({node:t,domGraph:e}){let n=[],r=t,o=py(t,e);if(!o)return[t.tagName];let a=()=>{if(r=o,o=py(o,e),!o&&r.frameIndex!==0)throw new Error("No parent node but not in main frame")},i=0;for(;o&&i<1e6;){if(i++,CP.includes(r.tagName)){a();continue}if(r.tagName==="body")n.push("body");else{let l=!1,c=1;for(let d=0;d<o.childrenBackendIds.length;d++){let u=o.childrenBackendIds[d],m=e.backendIdToNode[u];if(u===r.backendNodeId){n.push(`${r.tagName}:nth-child(${c})`),l=!0;break}else m?.nodeType===1&&!m.psuedoType&&c++}if(!l)throw new Error(`Could not find child (${r.tagName}) in parent's children list (${o.tagName})`)}a()}return n.reverse()}function Sy(t,e){let n=t.locator("html"),r=[];for(let o=0;o<e.length;o++){let a=e[o];if(r.push(a),a.startsWith("iframe")){let i=r.join(" > ");r=[],o<e.length-1?n=n.frameLocator(i):n=n.locator(i)}}if(r.length&&(n=n.locator(r.join(" > "))),"owner"in n)throw new Error("Final locator from mpath is a frame locator");return n}async function yy(t,e){await t.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let n=await t.send({method:"DOM.requestNode",params:{objectId:e},timeout:2e3}),o=(await t.send({method:"DOM.getAttributes",params:{nodeId:n.nodeId},timeout:2e3})).attributes,a=Tr(o,Kn);if(!a)throw new Error(`Could not find attribute ${Kn} for object ${e}`);return a}function by(t){let e=[];for(let n=0;n<t.domGraph.roots.length;n++){let r=t.domGraph.roots[n],o=vP({root:r,domGraph:t.domGraph,existingHashes:t.existingHashes,flagStore:t.flagStore,logger:t.logger});e=e.concat(o)}return e}function vP(t){let{root:e,domGraph:n,existingHashes:r}=t,o=[],a=[e];for(;a.length;){let i=a.pop();if(i.nodeType===1&&i.tagName.toLowerCase()==="svg"){let s=bl(i,n);s&&!r[s.hash]&&o.push(s)}for(let s of i.childrenBackendIds){let l=n.backendIdToNode[s];l&&a.push(l)}}return o}var xP=["focusable","keyshortcuts","controls","live","relevant","orientation"],IP=["selected","readonly","modal","required","invalid"],PP=["id","name","role","content"],Ty=["absolute","fixed","sticky"],MP=["path"],LP=["statictext","textbox","checkbox","combobox","iframe","rootwebarea","table","caption","columnheader","rowheader","gridcell","grid","row","rowgroup","cell","image","graphics-symbol","graphics-document","graphics-object","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch","tree","treeitem","separator"],Ry=["ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],Cy=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog"],OP=["menulistpopup","statictext","inlinetextbox"],NP=80,wy=100,vy=50,wl=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],kP=["cite"],_P={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"],"graphics-symbol":["svg","rect"],gridcell:["td","th"],SvgRoot:["svg"],navigation:["nav"],cell:["td","th"],row:["tr"],list:["ul"],heading:["h1","h2","h3","h4","h5","h6"]},DP={name:!0,value:!0,title:!0,alt:!0,placeholder:!0,checked:!0,selected:!0,contenteditable:!0},Ey={indentLevel:0},Cu=class t{id;role;name;nameSources;tagName;content;properties;internalProperties;ignoredReasons;dataMomenticId;pathFromRoot;parent;children;parentFrame;domNode;backendNodeId;ignoredByCDP;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.nameSources=e.nameSources,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeId=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,this.internalProperties=e.internalProperties??{},this.parentFrame=e.parentFrame,this.ignoredReasons=e.ignoredReasons,e.properties&&e.properties.forEach(n=>{n.name==="keyshortcuts"?this.dataMomenticId=parseInt(n.value.value):this.properties[n.name]=n.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let n=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(n&&n.length<vy?n:""),this.role=this.role||(e.domNode.attributes.role??""),zP(this.properties,e.domNode)}$P(this)}getSerializedFormWithContext(){return this.serialize({noId:!0,maxLevel:1,neighbors:1})}getNodeOnlySerializedForm(){return this.serialize({noId:!0,noChildren:!0,noContent:!0})}getLogForm(){return JSON.stringify({id:this.id,name:this.name??"",role:this.role??"",backendNodeId:this.backendNodeId})}isInteresting(){if(this.domNode&&MP.includes(this.domNode.tagName))return!1;if(LP.includes(this.role.toLowerCase()))return!0;if(this.domNode?.computedStyles.display==="contents"||this.ignoredReasons.some(n=>Cy.includes(n)))return!1;if(this.role.toLowerCase()==="inlinetextbox"&&this.tagName||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||qn.alwaysInterestingTruthyPropertyNames.some(n=>!!this.properties[n]))return!0;let e=this.properties.class;return typeof e=="string"&&e.split(" ").some(n=>Py(n))?!0:this.children.every(n=>n.role==="StaticText")&&this.internalProperties?.inCodeMirrorEditor?!1:this.children.some(n=>n.role==="StaticText")||this.children.length>1&&this.children.some(n=>n.tagName==="input")?!0:this.domNode&&(this.domNode.bounds.x===null||this.domNode.bounds.y===null||!this.domNode.bounds.width||!this.domNode.bounds.height)?!1:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(n=>n.startsWith("data"))}serialize(e=Ey){let n=Object.assign({},Ey,e),{indentLevel:r,noChildren:o,noProperties:a,noId:i,noContent:s,condensedMode:l}=n,c=Ru(this.properties),d=" ".repeat(r),u=this.role||"",m=this.tagName??"unknown",p=this.name;u==="heading"&&p==="heading"&&(p=""),this.nameSources?.find(v=>!v.superseded&&v.type==="contents")&&this.children.length>0&&(p="");let h=this.nameSources?.find(v=>!v.superseded);if(h&&!h.nativeSource&&h.type==="relatedElement"){let v=h.attributeValue?.relatedNodes??[];v.length===1&&v[0].text&&v[0].text===p&&(p="")}let f=wl.includes(this.role)||kP.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${d}${p}
3894
+ `;let y=`${d}<${m}`;!i&&!f&&(y+=` id="${this.id}"`);let b=s??!1;(c.multiline||c.contenteditable)&&this.children.length>0&&(b=!0),u&&u!=="generic"&&u!==m&&!(_P[u]??[]).includes(m)&&(y+=` role=${JSON.stringify(u)}`),p&&(y+=` name=${JSON.stringify(p)}`),this.content&&!b&&(y+=` content=${JSON.stringify(this.content)}`);let w=Date.now();if(Object.keys(c).length>0&&!a){if(Date.now()-w>1e3)throw new Error(`Serialization for the HTML element with tag ${m} and internal ID ${this.id} took too long. Please ensure your machine has enough resources to run Momentic.`);Object.entries(c).forEach(([v,R])=>{if(!xP.includes(v)){{if(IP.includes(v)&&(!R||R==="false"))return;if(v==="value"&&b&&(c.type==="text"||this.role==="textbox"))return;if(v==="level"&&`${R}`=="1")return;if(v==="url"&&c.src&&m==="img")return;if(v==="url"&&c.href&&m==="a")return;if(v==="editable"&&R==="plaintext")return;if(v==="type"&&R===m)return;if(l&&!DP[v])return}typeof R=="string"?y+=` ${v}="${$e(R,wy,!0)}"`:typeof R=="boolean"?R?y+=` ${v}`:y+=` ${v}={false}`:typeof R<"u"&&(y+=` ${v}={${$e(JSON.stringify(R),wy,!0)}}`)}})}if(m==="::before"||m==="::after"){let v="";for(let R of this.children)v+=R.serialize({...e,indentLevel:r,neighbors:0});return v}let C=e.maxLevel!==void 0&&r/2>=e.maxLevel;if(this.children.length===0||o||C)y+=` />
3895
+ `;else{let v="";for(let x of this.children)v+=x.serialize({...e,indentLevel:r+2,neighbors:0});let R=v.trim();R.length<=NP&&!R.includes(`
3896
+ `)?y+=`>${R}</${m}>
3897
+ `:y+=`>
3898
+ ${v}${d}</${m}>
3899
+ `}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let v=this.parent.children.findIndex(M=>M.id===this.id),R=v>0?this.parent.children[v-1]?.serialize({...e,neighbors:0}):"",x=v<this.parent.children.length-1?this.parent.children[v+1]?.serialize({...e,neighbors:0}):"";return`${R||""}
3900
+ ${y}
3901
+ ${x||""}`}return y}shallowClone(){let e=new t({id:this.id,role:this.role,name:this.name,nameSources:this.nameSources,content:this.content,properties:[],pathFromRoot:this.pathFromRoot,children:[],ignoredReasons:this.ignoredReasons,backendNodeID:this.backendNodeId,ignoredByCDP:this.ignoredByCDP,internalProperties:Ru(this.internalProperties),parentFrame:this.parentFrame});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=Ru(this.properties),e}},vu=class t{constructor(e,n,r,o){this.root=e;this.a11yIdNodeMap=n;this.dataMomenticIdMap=r;this.selectorToNodeMap=o}serialize(e){return this.root.serialize(e)}pruneUsingRelevantIds(e){let n=this.root;if(!n)throw new Error("Cannot prune a11y tree with no root");function r(a,i=!1){let s=e.has(`${a.id}`)||a.id===n?.id,l=a.shallowClone(),c=a.children,d=!1,u=[];for(let m of c){let p=r(m,s||d);p&&(u.push(p),p.parent=l,d=!0)}if(l.children=u,s||d)return l;if(wl.includes(a.role)&&i)return l}let o=r(n);return new t(o,this.a11yIdNodeMap,this.dataMomenticIdMap,this.selectorToNodeMap)}};function FP(t){return t.name?.value?`"${t.name.value}"`:t.role?.value&&t.role.value!=="none"&&t.role.value!=="generic"?`"${t.role.value}"`:`"${t.nodeId}"`}function UP(t,e,n,r){return t.bounds.x===null||t.bounds.y===null||t.bounds.height===null||t.bounds.width===null||t.bounds.width===0||t.bounds.height===0?!0:t.bounds.x+t.bounds.width<e.leftBound||t.bounds.x>e.rightBound?(Cs({logger:n,logKey:r,maxCount:5,intervalMs:3e3},{domNode:t,logKey:r},"Filtering out node since it is not in the viewport horizontally"),!1):t.bounds.y+t.bounds.height<e.upperBound||t.bounds.y>e.lowerBound?(Cs({logger:n,logKey:r,maxCount:5,intervalMs:3e3},{domNode:t,logKey:r},"Filtering out node since it is not in the viewport vertically"),!1):t.computedStyles.display==="none"?(n.debug({domNode:t},"Filtering out node since it has display none"),!1):!0}async function Ay({node:t,parent:e,frameId:n,frameContext:r,axGraph:o,domGraph:a,inputNodeMap:i,showZeroOpacityElements:s,filterByViewport:l,viewportDetails:c,useMPaths:d,cdpClient:u,logger:m,callId:p}){if(!e&&t.parentId)throw new Error(`Got no parent for accessibility node ${t.nodeId}: ${JSON.stringify(t)}`);let g=(P,W={})=>{},h=t.backendDOMNodeId,f=OP.includes((t.role?.value).toLowerCase());if(!f&&h===void 0)return g("Filtering out node since it doesn't exist in the DOM"),[];let y=h?a.backendIdToNode[h]:void 0;if(!f&&!y)try{let P=await H(u.send({method:"DOM.describeNode",params:{backendNodeId:h}}),{milliseconds:750,fallback:()=>{m.debug("Timeout getting node from CDP while processing a11y tree")}});if(P&&P.node.nodeName.toLowerCase()==="slot"&&P.node.distributedNodes?.length)m.debug({redirectedDomNode:y,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:t,cdpResult:P},"Redirecting node to assigned slot");else return g("Filtering out node since it doesn't exist in the DOM",{cdpResult:P}),[]}catch(P){return g("Filtering out node since it doesn't exist in the DOM",{err:P}),[]}if(y&&e&&l&&c&&t.backendDOMNodeId&&!UP(y,c,m,p))return y.momenticIgnored=!0,[];if(y&&y.computedStyles.display==="none")return y.momenticIgnored=!0,[];if(y&&y.computedStyles.opacity==="0"&&s!==!0){if(s==="inputs-only"&&y.tagName.toLowerCase()!=="input")return y.momenticIgnored=!0,[];if(s===!1)return y.momenticIgnored=!0,[]}let b=t.name?.value?typeof t.name.value=="string"?t.name.value:`${t.name.value}`:"",w=t.value?.value?typeof t.value.value=="string"?t.value.value:`${t.value.value}`:"",C=new Cu({domNode:y,id:parseInt(t.nodeId),role:t.role?.value||"",name:b,nameSources:t.name?.sources,content:w,properties:t.properties,children:[],ignoredReasons:t.ignoredReasons?.filter(P=>Ry.includes(P.name)||Cy.includes(P.name))??[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+FP(t),backendNodeID:t.backendDOMNodeId,ignoredByCDP:t.ignored,internalProperties:{inCodeMirrorEditor:e?.internalProperties?.inCodeMirrorEditor},parentFrame:r.type==="root"?void 0:r}),v=r,R=i[n],x=n;if(y?.tagName.toLowerCase()==="iframe"&&y.ownedFrameId){let P=r.childFrames.find(G=>G.frameId===y.ownedFrameId),W=o[P?.frameId??""]?.root,k=i[P?.frameId??""];if(P&&W&&k){t.childIds&&t.childIds.length>0&&m.debug("Replacing existing node's children with children from the iframe");let G=W;t.childIds=G.childIds,v=P,R=k,x=P.frameId}}let M=y?.childrenBackendIds?.length??0,D=(t.childIds??[]).filter(P=>!!R.get(parseInt(P))).length;if(M>D){let P=t.childIds?.map(k=>R.get(parseInt(k))).filter(Boolean).map(k=>k?.backendDOMNodeId).filter(k=>k!==void 0)??[],W=0;for(let k of y?.childrenBackendIds??[]){if(P.includes(k)){W=(t.childIds?.findIndex(wt=>R.get(parseInt(wt))?.backendDOMNodeId===k)??0)+1;continue}let G=a.backendIdToNode[k];if(!G||G?.tagName.toLowerCase()!=="svg")continue;let we=Math.floor(-1*Math.random()*1e7),Ce={nodeId:we.toString(),parentId:t.nodeId,ignored:!1,backendDOMNodeId:k,frameId:x,role:{type:"string",value:"graphics-symbol"}};R.set(we,Ce),t.childIds||(t.childIds=[]),t.childIds.splice(W,0,we.toString()),W++}}for(let P of t.childIds??[]){if(!P)continue;let W=R.get(parseInt(P));if(!W)continue;let k=await Ay({node:W,parent:C,domGraph:a,axGraph:o,frameId:x,frameContext:v,inputNodeMap:i,cdpClient:u,logger:m,callId:p,filterByViewport:l,showZeroOpacityElements:s,viewportDetails:c,useMPaths:d});k.length&&(C.children=C.children.concat(k))}if(C.role==="StaticText"&&(C.children=[]),C.children.length===1&&C.children[0].role==="StaticText"){let P=C.name,W=C.children[0]?.name;(P===W||!W)&&(C.children=[])}let _=[];for(let P=C.children.length-1;P>=0;P--){let W=C.children[P];if(W.role!=="StaticText"){_.push(W);continue}if(P===0||C.children[P-1].role!=="StaticText"){_.push(W);continue}C.children[P-1].name+=W.name}if(C.children=_.reverse(),C.role==="generic"&&C.children.length===1){let P=C.children[0];if(C.name&&!wl.includes(P.role)&&C.name===P.name)return y&&(y.momenticIgnored=!0),C.children}if(!C.isInteresting()&&t.parentId)return y&&(y.momenticIgnored=!0),C.children;for(let P of C.children)P.parent=C;return HP(C),y&&d&&Eu(y,a),[C]}function xy({node:t,a11yIdNodeMap:e,dataMomenticIdMap:n,logger:r,callId:o,domGraph:a,useMPaths:i,selectorToNodeMap:s,iconKnowledgeBase:l,startId:c=1}){t.id=c,c+=1,e[t.id]=t,t.dataMomenticId?n[t.dataMomenticId]=t:wl.includes(t.role);let d=t.backendNodeId,u=d!==void 0?a.backendIdToNode[d]:void 0;if(i&&u&&u.mPathSelector&&(s[u.mPathSelector]=t),l&&u&&u.tagName?.toLowerCase()==="svg"){let m=bl(u,a),p=m?l[m.hash]:void 0,g=p?p.description:void 0;p&&(t.properties["data-momentic-description"]=g)}for(let m of t.children)c=xy({node:m,a11yIdNodeMap:e,dataMomenticIdMap:n,logger:r,callId:o,startId:c,useMPaths:i,domGraph:a,selectorToNodeMap:s,iconKnowledgeBase:l});return c}async function Iy({rawA11yGraph:t,domGraph:e,startingFrameId:n,logger:r,cdpClient:o,filterByViewport:a,showZeroOpacityElements:i,viewportDetails:s,useMPaths:l,frameContext:c,iconKnowledgeBase:d}){let u=n??"root",m=t[u]?.root;if(!m)throw new Error("A11y tree has no root");let p=AP(),g=C=>{let v=C.allNodes.filter(x=>!x.ignoredReasons?.find(D=>Ry.includes(D.name))),R=new Map;return v.forEach(x=>{R.set(parseInt(x.nodeId),x)}),R},h={};Object.entries(t).forEach(([C,v])=>{h[C]=g(v)});let f=await Ay({node:m,domGraph:e,parent:null,inputNodeMap:h,axGraph:t,frameId:u,frameContext:c,cdpClient:o,logger:r,callId:p,showZeroOpacityElements:i,filterByViewport:a,viewportDetails:s,useMPaths:l});if(f.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(f)}`);if(f.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let y={},b={},w={};return xy({node:f[0],a11yIdNodeMap:y,dataMomenticIdMap:b,selectorToNodeMap:w,domGraph:e,logger:r,callId:p,useMPaths:l,iconKnowledgeBase:d}),new vu(f[0],y,b,w)}function BP(t,e,n){if(t==="class"){if(n.tagName?.toLowerCase()==="svg")return e.split(" ").filter(a=>a.length<vy&&!qn.bannedClassSubstrings.some(i=>a.includes(i))).slice(0,3).join(" ");let r=e.split(" "),o=[];for(let a of r)if(Py(a)){o.push(a);continue}return o.length?o.join(" "):null}if(e==="true")return!0;if(e==="false")return!1;try{let r=parseInt(e);if(!isNaN(r))return r}catch{}return t==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e.length>60?e.slice(0,50)+"...":e}function zP(t,e){if(!e)return;Object.entries(e.attributes).forEach(([a,i])=>{if(qn.relevantElementAttributes.includes(a)&&!PP.includes(a)&&!t[a]&&!a.startsWith("aria")){let s=BP(a,i,e);s!==null&&(t[a]=s)}});let n,r=[];if(e.computedStyles.position&&Ty.includes(e.computedStyles.position))n=e.computedStyles.position;else if(e.attributes.style){for(let a of Ty)if(e.attributes.style.includes(`position: ${a}`)){n=a;break}}n&&r.push(`position: ${n}`);let o;e.computedStyles.opacity&&e.computedStyles.opacity==="0"&&(o="opacity: 0"),o&&r.push(o),r.length>0&&(t.style=r.join("; "))}function HP(t){let e=t.properties.class;if(typeof e=="string"&&e.includes("cm-content")){t.children.forEach((a,i)=>{a.properties["cm-line-number"]=`${i+1}`});return}if(typeof e=="string"&&e.includes("notion-page-content")){t.children.forEach((a,i)=>{a.properties["block-number"]=`${i+1}`}),t.children.length>0&&(t.children[t.children.length-1].properties.description="This is the last block in the document. Click here to add new text to the end.");return}if(t.tagName==="table"){let a=[],i=t.children.find(l=>l.tagName==="thead");if(i){let l=i.children.find(c=>c.tagName==="tr");if(l){let c=l.children.filter(d=>d.tagName==="th");c.forEach((d,u)=>{d.properties["col-index"]||(d.properties["col-index"]=u+1),a?.push($e(d.name,100,!1))}),a?.length!==c.length&&(a=void 0)}}let s=0;for(let l of t.children)if(l.tagName==="tbody")for(let c=0;c<l.children.length;c++){let d=l.children[c];if(d.tagName!=="tr")continue;if(c===0&&!a?.length){let p=d.children.filter(g=>g.tagName==="th");if(p.length){if(a=p.map(g=>$e(g.name,100,!1)),a.length===p.length)continue;a=void 0}}s+=1,d.properties["row-index"]||(d.properties["row-index"]=s);let u=d.children.filter(p=>p.tagName==="td"||p.tagName==="th"),m=u.length===a?.length;u.forEach((p,g)=>{p.tagName!=="th"&&(p.properties["col-index"]||(p.properties["col-index"]=g+1),m&&(p.properties.col||(p.properties.col=a[g])))})}}}function $P(t){let e=t.properties.class,n=typeof e=="string"&&e.includes("cm-content");t.internalProperties.inCodeMirrorEditor=t.internalProperties?.inCodeMirrorEditor||n}function Py(t){if(qn.bannedClassSubstrings.some(e=>t.includes(e)))return!1;if(qn.alwaysInterestingClassNames.includes(t))return!0;for(let e of qn.alwaysInterestingClassPrefixes)if(t.startsWith(e))return!0;return!1}var El=class t{constructor(e,n,r,o,a){this.session=e;this.logger=n;this.contextGetter=r;this.pageGetter=o;this.defaultTimeoutMs=a}cdpInitializingPromise=void 0;cdpCrashDetails=void 0;cdpFullyDead=!1;loadEventLogs=[];static async init({logger:e,contextGetter:n,pageGetter:r,defaultTimeoutMs:o}){let a=n(),i=r(),s,l;for(let d=0;d<2;d++)try{s=await H(a.newCDPSession(i),{milliseconds:o*d,fallback:()=>{throw new A("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${i.url()})`)}});break}catch(u){await J(500),l=u}if(!s)throw l;let c=new t(s,e,n,r,o);try{await H(c.registerHandlers(s),{milliseconds:o,message:`CDP handler registration timed out after ${o}ms`})}catch(d){throw c.cdpFullyDead=!0,new A("UserInfrastructureError",`Failed to initialize CDP client: ${d}`)}return c}async registerHandlers(e){e.on("Target.attachedToTarget",async()=>{try{await e.send("Runtime.runIfWaitingForDebugger")}catch(n){this.logger.warn({err:n},"Failed to run Runtime.runIfWaitingForDebugger")}}),e.on("Target.targetCrashed",n=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},targetCrashDetails:JSON.stringify(n)},this.logger.error({payload:n},"CDP session crashed, Momentic will likely not function correctly")}),e.on("Inspector.targetCrashed",n=>{this.cdpCrashDetails={...this.cdpCrashDetails??{},inspectorCrashDetails:JSON.stringify(n)},this.logger.error({payload:n},"CDP inspector session crashed, Momentic will likely not function correctly")}),e.on("Page.frameRequestedNavigation",n=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Frame requested navigation: ${JSON.stringify(n)}`)}),e.on("Page.navigatedWithinDocument",n=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Navigated within document: ${JSON.stringify(n)}`)}),e.on("Page.lifecycleEvent",n=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page lifecycle event: ${JSON.stringify(n)}`)}),e.on("Page.loadEventFired",()=>{this.loadEventLogs.push(`[${new Date(Date.now()).toLocaleString("en-US",{timeZone:"America/Los_Angeles"})}] Page load event fired`)}),await e.send("Accessibility.enable"),await e.send("Page.enable"),await e.send("DOM.enable"),await e.send("Overlay.enable"),await e.send("DOMSnapshot.enable"),await e.send("CSS.enable")}async send({method:e,params:n,timeout:r=this.defaultTimeoutMs,timeoutMsg:o}){for(;this.cdpInitializingPromise;)await H(this.cdpInitializingPromise,{milliseconds:r});if(this.cdpCrashDetails){if(this.cdpFullyDead)throw new A("UserInfrastructureError",`The browser inspector session encountered a critical crash: ${JSON.stringify(this.cdpCrashDetails)}`);this.logger.warn(`Detected crashed CDP client before method ${e}, reinitializing before proceeding...`),await this.reinitialize()}try{return await H(this.session.send(e,n),{milliseconds:r,message:o??`Chrome command ${e} timed out after ${r}ms. This is likely an infrastructure issue caused by a lack of compute resources or a crash at the browser level.`})}catch(a){throw["Internal error","Target crashed"].some(i=>a.message.includes(i))&&!this.cdpInitializingPromise&&(this.logger.warn({err:a},`CDP crashed during CDP method ${e}, re-initializing client`),await this.reinitialize()),a}}async createRawCDPSession(e=this.defaultTimeoutMs){let n=e,r=this.pageGetter(),o=await H(this.contextGetter().newCDPSession(r),{milliseconds:n,fallback:()=>{throw this.logger.error(`Failed to initialize CDP session within the page load timeout (${r.url()})`),new A("UserInfrastructureError",`Failed to initialize CDP session within the page load timeout (${r.url()})`)}});return this.logger.debug(`Created new CDP session for ${r.url()}`),o}async reinitialize(e=this.defaultTimeoutMs){await this.cdpInitializingPromise,this.cdpInitializingPromise=(async()=>{try{let n=this.session;this.session=await this.createRawCDPSession(e),await H(this.registerHandlers(this.session),{milliseconds:e,message:`Failed to register CDP handlers within ${e}ms`}),this.logger.debug("Successfully reinitialized and attached new handlers to CDP session");try{await H(n.detach(),{milliseconds:1e3})}catch(r){this.logger.warn({err:r},"Failed to detach old CDP session after reinitialization, continuing...")}this.cdpCrashDetails=void 0,this.cdpFullyDead=!1}catch(n){this.cdpCrashDetails={...this.cdpCrashDetails??{},reinitializeError:`${n}`},this.cdpFullyDead=!0}finally{this.cdpInitializingPromise=void 0}})(),await this.cdpInitializingPromise}on(e,n){return this.session.on(e,n),this.session}off(e,n){return this.session.off(e,n),this.session}addListener(e,n){return this.session.addListener(e,n),this.session}removeListener(e,n){return this.session.removeListener(e,n),this.session}};var ca="<empty>";function jP(t){return t.includes("doubleclick.net")||t.includes("googletagmanager.com")||t.includes("googlesyndication.com")||t.includes("s.amazon-adsystem.com")||t.includes("smartadserver.com")||t.includes("omnitagjs.com")||t.includes("x.adroll.com")}function Ly(t){let e=t.adFrameStatus?.adFrameType;return e==="child"||e==="root"||jP(t.url)}async function GP(t,e){let n=await t.send({timeout:3e3,method:"DOM.getFrameOwner",params:{frameId:e}}),o=(await t.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[n.backendNodeId]}})).nodeIds[0],i=(await t.send({timeout:3e3,method:"DOM.describeNode",params:{backendNodeId:n.backendNodeId}})).node;return i.nodeId=o,i}async function da({cdpClient:t,page:e,logger:n}){let r={type:"root",childFrames:[],page:e},o=[],[a,i]=await Promise.all([t.send({timeout:3e3,method:"Page.getFrameTree",params:{}}),t.send({timeout:3e3,method:"DOM.getDocument",params:{depth:0}})]),c=(a.frameTree.childFrames??[]).map(async(u,m)=>{if(Ly(u.frame))return null;try{return await Oy({cdpClient:t,rawFrameTree:u,indices:[m],parent:r,warnings:o,logger:n})}catch(p){return o.push(`Failed to get child frame: ${p}`),null}}),d=await Promise.all(c);return r.childFrames=d.filter(u=>u!==null),o.length&&n?.warn({warnings:o},"Got warnings when fetching frame tree"),r}async function Oy({cdpClient:t,rawFrameTree:e,indices:n,parent:r,warnings:o,logger:a}){let i=e.frame.id,s=await GP(t,i),l=s.attributes??[],c=null,d=[];for(let g of["src","name","id","title","srcdoc","sandbox"]){let h=Tr(l,g);h&&(d.push(`${g}=${JSON.stringify(h)}`),g==="src"&&(c=h))}let u={type:"frame",cdpFrame:e.frame,url:e.frame.url,frameId:i,locationData:{indices:n,attributeSelectors:d},src:c,childFrames:[],parent:r,domNode:s},p=(e.childFrames??[]).map(async(g,h)=>{if(Ly(g.frame))return null;try{return await Oy({cdpClient:t,rawFrameTree:g,indices:[...n,h],parent:u,warnings:o,logger:a})}catch(f){return o.push(`Failed to get child frame (child ${h} of frame with url ${e.frame.url}): ${f}`),null}});return u.childFrames=(await Promise.all(p)).filter(g=>g!==null),u}async function WP(t){try{return await t.owner().count()===1}catch{return!1}}async function VP(t){try{return await t.count()===1}catch{return!1}}async function On(t,e){let n=[],r=t;for(;r.parent.type==="frame";)n.push(r.parent),r=r.parent;n.reverse();let o=e,a=[];for(let c of n){let d=!1;for(let u of[...c.locationData.attributeSelectors,ca]){let m=o.frameLocator(u===ca?"iframe":`iframe[${u}]`);if(await WP(m)){d=!0,o=m,a.push(u);break}}if(!d)throw new A("ActionFailureError",`Failed to find a unique attribute to identify intermediate frame with url matching '${c.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`)}let i;for(let c of[...t.locationData.attributeSelectors,ca]){let d=o.locator(c===ca?"iframe":`iframe[${c}]`);if(await VP(d)){i=d,a.push(c);break}}if(!i)throw new A("ActionFailureError",`Failed to find a unique attribute to identify target frame with url matching '${t.url}'. Please attach a unique 'id', 'name', 'title', or 'src' attribute to the frame.`);let s=await i.evaluateHandle(c=>c,{timeout:1e3}),l=await s.asElement().contentFrame();if(!l)throw new A("InternalWebAgentError",`Failed to load Playwright Frame for iframe with url '${t.url}'`);return await s.dispose(),{frame:l,mPathSelectorTokens:a}}function My(t,e){let n=[...t],r=[];for(;n.length;){let o=n.shift();e(o)&&r.push(o),n.push(...o.childFrames)}return r}async function Ny({page:t,frameTree:e,cache:n}){let r,o=e.childFrames,a=[];if(n.mPathSelectorTokens.length){let s=o;for(let d=0;d<n.mPathSelectorTokens.length-1;d++){let u=n.mPathSelectorTokens[d];u===ca?s=s.length===1?s[0].childFrames:[]:s=s.filter(m=>m.locationData.attributeSelectors.includes(u)).map(m=>m.childFrames).flat()}let l=[],c=n.mPathSelectorTokens[n.mPathSelectorTokens.length-1];if(c===ca?l=s:l=s.filter(d=>d.locationData.attributeSelectors.includes(c)),l.length===1)return r=l[0],a.push(`Found unique frame with mpath ${n.mPathSelectorTokens.join(" > ")}`),{resolution:{type:"auto",frame:(await On(r,t)).frame,handle:r,mPathSelectorTokens:n.mPathSelectorTokens,frameTree:e},logs:a};a.push(`Found ${l.length} frames with mpath ${n.mPathSelectorTokens.join(" > ")}`)}if(n.frameSrcRegex){let s=new RegExp(n.frameSrcRegex),l=My(o,c=>!!c.src&&s.test(c.src));if(l.length===1)return r=l[0],a.push(`Found unique frame with src regex ${n.frameSrcRegex}`),{resolution:{type:"auto",frame:(await On(r,t)).frame,handle:r,mPathSelectorTokens:n.mPathSelectorTokens,frameTree:e},logs:a};a.push(`Found ${l.length} frames with src regex ${n.frameSrcRegex}`),n.frameSrcRegex=void 0}if(n.frameUrlRegex){let s=new RegExp(n.frameUrlRegex),l=My(o,c=>!!c.url&&s.test(c.url));if(l.length===1)return r=l[0],a.push(`Found unique frame with url regex ${n.frameUrlRegex}`),{resolution:{type:"auto",frame:(await On(r,t)).frame,handle:r,mPathSelectorTokens:n.mPathSelectorTokens,frameTree:e},logs:a};a.push(`Found ${l.length} frames with url regex ${n.frameUrlRegex}`),n.frameUrlRegex=void 0}let i=o;for(let s=0;s<n.indices.length-1;s++)i=i[n.indices[s]]?.childFrames??[];if(r=i[n.indices[n.indices.length-1]],r)return a.push(`Found unique frame with indices ${n.indices.join(" > ")}`),{resolution:{type:"auto",frame:(await On(r,t)).frame,handle:r,mPathSelectorTokens:n.mPathSelectorTokens,frameTree:e},logs:a};throw a.push(`Found ${i.length} frames with indices ${n.indices}`),new En("Failed to find the iframe that previously contained this element",[{type:"AUTO_FRAME",matched:!1,logs:a}])}function Rl(t){return t.type==="auto"?JSON.stringify({type:"auto",frameId:t.handle.frameId}):JSON.stringify(t)}function Au(t){for(;t.parent.type==="frame";)t=t.parent;return t.parent}function ky(t){let e=Au(t),n=t.src??"",r=t.url??"",o=[],a=[],i=[...e.childFrames];for(;i.length;){let s=i.shift();s.src&&o.push(s.src),s.url&&a.push(s.url),i.push(...s.childFrames)}return{srcs:o,urls:a,desiredSrc:n,desiredUrl:r}}function _y(t){return t.type==="auto"?{type:"auto",frameId:t.handle.frameId,url:t.handle.url,src:t.handle.src??"",mPathSelectorTokens:t.mPathSelectorTokens.join(" > ")}:{type:"url",url:t.url}}async function Dy({frame:t,logger:e,signal:n}){let r;try{r=await t.frameElement(),await qP({frameElementHandle:r,logger:e,signal:n})}catch(o){e.warn({err:o},"Failed to scroll iframe into view, continuing...")}finally{await r?.dispose()}}async function qP({frameElementHandle:t,logger:e,signal:n}){let r=await t.boundingBox();if(!r){e.warn("Active frame element has null bounding box, skipping scroll");return}await to({promiseGenerator:async()=>t.evaluate(async(a,{x:i,y:s})=>{window.scrollTo(window.scrollX+i,window.scrollY+s);let l=Date.now(),c,d,u;for(;Date.now()-l<1500;){let m=document.activeElement,p,g,h;if(!m)p=void 0,g=void 0,h=void 0;else{let f=m.getBoundingClientRect();p=m.scrollTop,g=f.x,h=f.y}if(c!==void 0&&d!==void 0&&u!==void 0&&p===c&&g===d&&h===u)break;c=p,d=g,u=h,await new Promise(f=>setTimeout(f,250))}},r),timeoutMs:2e3,codePath:"scrollIframeIntoView",signal:n}),e.info({bb:r},"Successfully scrolled iframe into view")}function Fy(t,e){return async(n,r)=>{try{let o=await r.allHeaders();for(let{key:a,value:i,matcher:s}of t)(!s||s.matches({url:r.url(),method:r.method()}))&&(o[a]=i);await n.fallback({headers:o})}catch(o){e.warn({err:o},"Failed to apply custom headers to request, continuing")}}}import{randomUUID as KP}from"crypto";function Uy(t,e){for(let n of Object.values(e))if(n.matcher.matches({url:t.url(),method:t.method()}))return n}async function By(t){let{route:e,mock:n,entry:r,debugData:o,requestId:a,requestRecorders:i,logger:s}=t,l={url:r.request.url,options:{method:r.request.method,headers:r.request.headers.map(p=>[p.name,p.value]),body:r.request.postData?.text}},c;if(n.fetchOriginalResponse){let p=await e.fetch();c={body:await p.text(),options:{status:p.status(),statusText:p.statusText(),headers:Object.entries(await p.headers())}}}let d=await n.generateResponse(l,c),u={};d.headers.forEach((p,g)=>{u[g]=p});let m={body:await d.text(),contentType:d.headers.get("content-type")||"text/plain",headers:u,status:d.status};await e.fulfill(m);try{r.response={status:m.status,statusText:d.statusText,headers:Object.entries(m.headers).map(([p,g])=>({name:p,value:g})),cookies:[],content:{mimeType:m.contentType,text:m.body}},Si(o,r,a);for(let p of Object.values(i))p.onRequestComplete(a,r)}catch(p){p.message.includes("has been closed")||s.warn({err:p},"Failed to add response to HAR")}}async function xu(t){try{await YP(t)}catch(e){t.logger.warn({err:e},"Error handling intercepted request, continuing...")}}async function YP(t){let{pageId:e,route:n,request:r,debugData:o,logger:a,requestRecorders:i,mocks:s}=t,l=KP(),c=await fu(e,r);try{Si(o,c,l);for(let u of Object.values(i))u.onRequestStart(l,c)}catch(u){a.warn({err:u},"Failed to add request to HAR")}let d=Uy(r,s);d?await By({logger:a,route:n,mock:d,entry:c,debugData:o,requestId:l,requestRecorders:i}):await XP({route:n,request:r,debugData:o,logger:a,requestRecorders:i,entry:c,requestId:l})}async function XP({route:t,request:e,debugData:n,logger:r,requestRecorders:o,entry:a,requestId:i}){await t.continue();try{let s=await e.response();if(!s||!a)return;await ZS(a,e,s),Si(n,a,i);for(let l of Object.values(o))l.onRequestComplete(i,a)}catch(s){s.message.includes("has been closed")||r.warn({err:s},"Failed to add response to HAR")}}async function JP(t){let e=t.postData();if(e){if((await t.headerValue("content-type"))?.includes("json"))try{return{json:t.postDataJSON()}}catch{return{}}else if((await t.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}async function QP(t){let e=await t.text();if(e){if((await t.headerValue("content-type"))?.includes("json"))try{return{json:await t.json()}}catch{return{}}else if((await t.headerValue("content-type"))?.includes("text"))return{text:e}}return{}}function Cl(t){return{request:{url:t.request.url,method:t.request.method,headers:t.request.headers.reduce((e,n)=>({...e,[n.name]:n.value}),{}),...t.request.postData?t.request.postData.mimeType.includes("json")?{json:JSON.parse(t.request.postData.text)}:{text:t.request.postData.text}:{}},response:t.response?{status:t.response.status,headers:t.response.headers.reduce((e,n)=>({...e,[n.name]:n.value}),{}),...t.response.content?t.response.content.mimeType?.includes("json")&&t.response.content.text?{json:JSON.parse(t.response.content.text)}:{text:t.response.content.text}:{}}:void 0}}async function Iu(t){let e=t.request(),n=t.status(),r=t.headers(),o=await QP(t);return{request:{url:e.url(),method:e.method(),headers:e.headers(),...await JP(e)},response:{status:n,headers:r,...o},status:n,headers:r,...o}}var wr=class{requestMatcher;constructor(e){this.requestMatcher=e}matches(e){let{url:n,method:r}=e;return this.requestMatcher.method&&this.requestMatcher.method.toLowerCase()!==r.toLowerCase()?!1:Js(n,this.requestMatcher.urlMatcher)}};async function zy({event:t,transformer:e,enricher:n,frame:r,lastScreenshotForRecording:o,logger:a}){let{warnings:i,error:s,properties:l}=t.target;if(s){a.error({error:s,warnings:i},"Error while capturing passive click");return}if(i.length&&a.warn({warnings:i},"Warnings while capturing passive click"),!l)return;let c=r.parentFrame()?r.url():void 0,u=r.page().frames().map(g=>g.url());a.debug({frameUrl:c,...t},"Passive click event captured on element");let m,p;if(c)try{let g=await r.frameElement();m=await H(g?.boundingBox(),{milliseconds:3e3})??void 0;let h=await n.constructIframeRegex({urls:u,srcs:[],desiredUrl:c});if(h.urlRegex)p={type:"url",url:`/${h.urlRegex}/`};else throw new Error(`Got no url regex options: ${JSON.stringify(h)}`)}catch(g){a.warn({err:g},"Failed to construct iframe details for recorded action, using hardcoded URL only"),p={type:"url",url:c}}(async()=>{try{await e.recordElementAction({...t,screenshotBase64:o,frameConfig:p,frameBoundingBox:m})}catch(g){a.error({err:g},"Failed to transform passive click action")}})()}import{randomUUID as Nn}from"crypto";import ZP from"js-beautify";var eM=["Dead"],vl=class{recordedSteps=new Map;callbacks;signal;generator;testId;orgId;nextStepOffset=0;logger;constructor({signal:e,callbacks:n,generator:r,testId:o,orgId:a,logger:i}){this.signal=e,this.logger=i,this.testId=o,this.orgId=a,this.callbacks={onStepRecorded:(s,l)=>{this.recordedSteps.set(l,{step:s}),n.onStepRecorded(s,l)},onActionReceived:(s,l)=>{this.recordedSteps.set(l,{step:s}),n.onActionReceived?.(s,l)}},this.generator=r}reserveIndexForCommand(e){let n=this.nextStepOffset;return this.recordedSteps.set(n,{step:{id:Nn(),type:"PRESET_ACTION",command:Un(e)}}),this.nextStepOffset++,n}async recordElementAction(e){let{type:n,target:r,frameConfig:o}=e;if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let a,i,s=r.properties.attributes.nodeOnlySerializedHtml.trim(),l=s,c;switch(e.frameConfig?e.frameBoundingBox?c={x:e.frameBoundingBox.x+r.properties.boundingBox.x,y:e.frameBoundingBox.y+r.properties.boundingBox.y,width:r.properties.boundingBox.width,height:r.properties.boundingBox.height}:this.logger.warn(e,"No frame bounding box found, refusing to write bounding box"):c=r.properties.boundingBox,n){case"CLICK":{a="CLICK";let h=Un(a);i={id:Nn(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:l},iframeUrl:o?.url,cache:{target:{id:-1,...r.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:c}}}};break}case"SELECT":{a="SELECT_OPTION";let h=Un(a);i={id:Nn(),type:"PRESET_ACTION",command:{...h,type:"SELECT_OPTION",iframeUrl:o?.url,target:{type:"description",elementDescriptor:l},cache:{target:{id:-1,...r.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),boundingBox:c}},choice:{type:"VALUE",value:e.selectedValue??"Unknown option"}}};break}case"MOUSE_DRAG":{a="MOUSE_DRAG";let h=Un(a);i={id:Nn(),type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:l},deltaX:e.deltaX.toString(),deltaY:e.deltaY.toString(),iframeUrl:o?.url,cache:{target:{id:-1,...r.properties.attributes,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),targetUpdateLoggerTags:Oe(this.logger),boundingBox:c}}}};break}default:throw new Error(`Unknown action type: ${n}`)}let d;e.offset===void 0?(d=this.nextStepOffset,this.nextStepOffset++):d=e.offset,this.callbacks.onActionReceived?.(i,d);let u=e.target.browserState;try{u=ZP.html(u,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1}),u=$S(u,"data-momentic-interacted",4e4)}catch{}let m;try{m=(await this.generator.getReverseMappedDescription({target:u,screenshot:e.screenshotBase64?`data:image/jpeg;base64,${e.screenshotBase64}`:void 0,boundingBox:r.properties.boundingBox},{disableCache:!1,loggerTags:{testId:this.testId,...Oe(this.logger)}})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),m=s}let p=this.recordedSteps.get(d)?.step??i,g=p?.command;g&&"target"in g&&g.target?(g.target={type:"description",elementDescriptor:m},this.callbacks.onStepRecorded({...p,command:g},d)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:n,combinable:r}=e;if(eM.includes(n)||this.signal.aborted)return;let o="normal";n.length>1&&(o="special");let a;if(o==="normal"){let u=Un("TYPE");a={id:Nn(),type:"PRESET_ACTION",command:{...u,target:void 0,value:n,clearContent:!1}}}else{let u=Un("PRESS");a={id:Nn(),type:"PRESET_ACTION",command:{...u,value:n}}}let i,s=this.nextStepOffset-1,l=this.recordedSteps.get(s),c=l?.step,d=c?.command;if(r){if(d?.type===a.command.type){let u=d.value,m=a.command.value;a={id:Nn(),type:"PRESET_ACTION",command:{...d,value:a.command.type==="PRESS"?`${u}+${m}`:`${u}${m}`}},i=s}else if(d?.type==="CLICK"&&a.command.type==="TYPE")c.command={...a.command,target:d.target,cache:d.cache},a=l.step,i=s;else if(d?.type==="TYPE"&&a.command.type==="PRESS"&&a.command.value==="Backspace"){let u=d.value;a={id:Nn(),type:"PRESET_ACTION",command:{...d,value:u.slice(0,u.length-1)}},i=s}}i===void 0&&(i=this.nextStepOffset,this.nextStepOffset++),this.callbacks.onStepRecorded(a,i)}recordScroll(e){if(this.signal.aborted)return;let n=()=>{let{deltaY:a}=e;if(!a)return;let i=this.nextStepOffset-1,s=this.recordedSteps.get(i)?.step.command,l;s?.type==="SCROLL_DOWN"&&s.deltaY?(a+=s.deltaY,l=i):s?.type==="SCROLL_UP"&&s.deltaY?(a-=s.deltaY,l=i):(l=this.nextStepOffset,this.nextStepOffset++);let c=a>0?"SCROLL_DOWN":"SCROLL_UP",d=Un(c);d.deltaY=Math.abs(a);let u={id:Nn(),type:"PRESET_ACTION",command:d};this.callbacks.onStepRecorded(u,l)},r=()=>{let{deltaX:a}=e;if(!a)return;let i=this.nextStepOffset-1,s=this.recordedSteps.get(i)?.step.command,l;s?.type==="SCROLL_RIGHT"&&s.deltaX?(a+=s.deltaX,l=i):s?.type==="SCROLL_LEFT"&&s.deltaX?(a-=s.deltaX,l=i):(l=this.nextStepOffset,this.nextStepOffset++);let c=a>0?"SCROLL_RIGHT":"SCROLL_LEFT",d=Un(c);d.deltaX=Math.abs(a);let u={id:Nn(),type:"PRESET_ACTION",command:d};this.callbacks.onStepRecorded(u,l)},o=this.recordedSteps.get(this.nextStepOffset-1);o?.step.command.type==="SCROLL_LEFT"||o?.step.command.type==="SCROLL_RIGHT"?(r(),e.deltaY>=20&&n()):(n(),e.deltaX>=20&&r())}};import{z as Pu}from"zod";var ore=Pu.object({type:Pu.literal("url"),url:Pu.string()});var Al=class{smartWaitingTimeoutMs;pageLoadTimeoutMs;allowPartialAccessibilityTree;logger;cdpClient;pageGetter;abortSignalGetter;userBrowserSettings;enricher;iconKnowledgeBase;activeFrameCache;activeFrameConfig;lastA11yIdToNodeMap={};lastDataMomenticIdToNodeMap={};lastSelectorToNodeMap={};lastA11yTreeRoot;lastDomGraph;constructor({smartWaitingTimeoutMs:e,pageLoadTimeoutMs:n,allowPartialAccessibilityTree:r,logger:o,cdpClient:a,pageGetter:i,abortSignalGetter:s,enricher:l,iconKnowledgeBase:c,userBrowserSettings:d}){this.smartWaitingTimeoutMs=e,this.pageLoadTimeoutMs=n,this.allowPartialAccessibilityTree=r,this.logger=o,this.cdpClient=a,this.pageGetter=i,this.abortSignalGetter=s,this.enricher=l,this.iconKnowledgeBase=c,this.userBrowserSettings=d}get frameConfig(){return this.activeFrameConfig}get domGraph(){return this.lastDomGraph}get selectorToNodeMap(){return this.lastSelectorToNodeMap}get dataMomenticIdToNodeMap(){return this.lastDataMomenticIdToNodeMap}get a11yIdToNodeMap(){return this.lastA11yIdToNodeMap}get a11yTreeRoot(){return this.lastA11yTreeRoot}setActiveFrameConfig(e){e?(this.activeFrameConfig=e,this.activeFrameCache=void 0):(this.activeFrameConfig=void 0,this.activeFrameCache=void 0)}reset(){this.activeFrameCache=void 0,this.activeFrameConfig=void 0,this.lastA11yIdToNodeMap={},this.lastDataMomenticIdToNodeMap={},this.lastSelectorToNodeMap={},this.lastA11yTreeRoot=void 0,this.lastDomGraph=void 0}saveAutoFrameCacheDetails(e){if(!this.activeFrameConfig||this.activeFrameConfig.type!=="auto"||!this.userBrowserSettings.autoExpandIframes)return;let n={...e,indices:this.activeFrameConfig.handle.locationData.indices,mPathSelectorTokens:this.activeFrameConfig.mPathSelectorTokens};return this.constructIframeRegexAsync(this.activeFrameConfig.handle,n),n}async getAutoFrameDetailsFromHandle(e){let n=this.pageGetter(),r=Au(e),{frame:o,mPathSelectorTokens:a}=await On(e,n),i={indices:e.locationData.indices,mPathSelectorTokens:a};return this.constructIframeRegexAsync(e,i),{cache:i,config:{type:"auto",frame:o,handle:e,mPathSelectorTokens:a,frameTree:r,cache:i}}}async resolveAutoFrameCache(e){let n=this.pageGetter(),r=await da({cdpClient:this.cdpClient,page:n,logger:this.logger}),{resolution:o,logs:a}=await Ny({page:n,frameTree:r,cache:e});return this.logger.info({logs:a},"Resolved auto frame cache"),{...o,cache:e}}async resolveActiveFrameConfig({logger:e=this.logger,signal:n=this.abortSignalGetter()}){if(!this.frameConfig)return null;if(this.activeFrameCache)if(Rl(this.frameConfig)!==this.activeFrameCache.frameIdentifierStringified)this.activeFrameCache=void 0;else if(this.activeFrameCache.frame&&"isDetached"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isDetached())this.activeFrameCache=void 0;else return this.activeFrameCache;let r;return this.frameConfig.type==="url"?r=await this.resolveUrlMatcherFrameConfig({config:this.frameConfig,logger:e,signal:n}):r={source:"auto",frame:this.frameConfig.frame,handle:this.frameConfig.handle,frameIdentifierStringified:Rl(this.frameConfig),cacheTime:Date.now(),frameTree:this.frameConfig.frameTree,mPathSelectorTokens:this.frameConfig.mPathSelectorTokens},await Dy({frame:r.frame,logger:e,signal:n}),this.activeFrameCache=r,r}async executeFunctionInAllFrames(e,n){let r=this.pageGetter(),o=await da({cdpClient:this.cdpClient,page:r,logger:this.logger}),a=[H(r.evaluate(e,n),{milliseconds:2e3})],i=Array.from(o.childFrames);for(;i.length>0;){let l=i.shift(),c=l.url;c==="about:blank"||c.startsWith("chrome-error://")||(i.push(...l.childFrames),a.push(On(l,r).then(({frame:d})=>H(d.evaluate(e,n),{milliseconds:2e3})).catch(d=>(this.logger.warn({err:d,frameUrl:l.url},"Failed to evaluate function in frame"),"MOMENTIC_FRAME_EVAL_ERROR"))))}return(await Promise.all(a)).filter(l=>l!=="MOMENTIC_FRAME_EVAL_ERROR")}async getAllChildFrameUrls(){let e=this.pageGetter(),n=await da({cdpClient:this.cdpClient,page:e,logger:this.logger}),r=Array.from(n.childFrames),o=[];for(;r.length>0;){let a=r.shift();r.push(...a.childFrames),o.push(a.src??a.url)}return o}async getDomGraph({devicePixelRatio:e,signal:n,logger:r}){return this.getDOMTree({devicePixelRatio:e??1,signal:n,logger:r??this.logger})}async getA11yTree(e){let n={},r=e.logger??this.logger,o=e.abortSignal??this.abortSignalGetter(),a=this.pageGetter(),i,s,l=null;if(this.frameConfig?.type==="url"){if(i=await on({fn:()=>this.resolveActiveFrameConfig({logger:r,signal:o}),codePath:"getActiveFrameDetails",logObject:n,signal:o,logger:r})??void 0,!i)throw new A("ActionFailureError","Got null frame details despite active frame config");s=i.handle,l=s.frameId}else this.userBrowserSettings.autoExpandIframes?(s=await on({fn:()=>da({cdpClient:this.cdpClient,page:this.pageGetter(),logger:r}),codePath:"getMomenticFrameTree",logObject:n,signal:o,logger:r}),l=null):(s={type:"root",page:a,childFrames:[]},l=null);await on({fn:async()=>this.addMomenticIds({rootPage:a,childFrames:s.childFrames,frameFilter:i?.frame,logger:r}),codePath:"addIdsToElement",logObject:n,signal:o,logger:r});let c=await on({fn:()=>this.getDOMTree({devicePixelRatio:e.devicePixelRatio??1,signal:o,logger:r}),codePath:"domFetch",logObject:n,signal:o,logger:r}),d=await on({fn:()=>this.getRawA11yGraph({cdpClient:this.cdpClient,frameId:l,childFrames:s.childFrames,logTimings:n,logger:r,signal:o}),codePath:"totalA11yFetch",logObject:n,signal:o,logger:r}),{tree:u}=await on({fn:()=>this.composeA11yDomGraph({opts:e,a11yGraph:d,domGraph:c,startingFrameId:l,frameContext:s,logger:r,iconKnowledgeBase:this.iconKnowledgeBase,showZeroOpacityElements:e.showZeroOpacityElements}),codePath:"a11yProcess",logObject:n,signal:o,logger:r});return Object.values(n).some(m=>m>750)&&r.warn({logTimings:n},"A11y tree fetch component took a long time"),this.lastA11yIdToNodeMap=u.a11yIdNodeMap,this.lastDataMomenticIdToNodeMap=u.dataMomenticIdMap,this.lastA11yTreeRoot=u.root,this.lastDomGraph=c,this.lastSelectorToNodeMap=u.selectorToNodeMap,u}async fetchA11yTreeForRecording(e,n){if(await this.getA11yTree({devicePixelRatio:e,abortSignal:n,logger:Xr,filterByViewport:!1}),Math.random()<.1){let r=this.lastA11yTreeRoot?.serialize();this.logger.debug({tree:r&&r.length>4e5?"REDACTED_DUE_TO_SIZE":r},"Refreshed a11y tree during recording")}}async getLocatorFromA11yNode({page:e,root:n,node:r}){if(r.backendNodeId===void 0)throw new Error(`Node with a11y id ${r.id} has no backend node ID: ${r.getNodeOnlySerializedForm()}`);if(this.userBrowserSettings.visualActions){let o=this.domGraph?.backendIdToNode[r.backendNodeId];if(!o)throw new Error(`Could not find DOM node for backend node ID ${r.backendNodeId}`);let a=fy({node:o,domGraph:this.domGraph});return Sy(e,a)}else return this.getLocatorFromBackendId(n,r.backendNodeId)}async getLocatorFromBackendId(e,n){let r=await this.cdpClient.send({method:"DOM.resolveNode",params:{backendNodeId:n},timeout:2e3});if(!r||!r.object.objectId)throw new Error(`Could not resolve backend node ${n}`);let o;try{o=await yy(this.cdpClient,r.object.objectId)}catch(a){throw this.logger.debug({err:a,object:JSON.stringify(r.object)},"Failed to get ID attribute"),a}return e.locator(pn(o))}getNodeUsingMPathSelector(e){let n=this.selectorToNodeMap[e];if(n)return n;let r=e.split(" > "),o="";for(let a=r.length-1;a>=0;a--){let i=r.slice(a).join(" > ");if(this.selectorToNodeMap[i]){o=i;break}}this.logger.warn({selectorMapSize:Object.keys(this.selectorToNodeMap).length,selector:e,closestSelector:o},"Could not find a11y node using mpath selector")}async resolveUrlMatcherFrameConfig({config:e,signal:n=this.abortSignalGetter(),logger:r=this.logger}){let o=Date.now(),a,i,s,l=0;for(;Date.now()-o<this.smartWaitingTimeoutMs;)try{a=await da({cdpClient:this.cdpClient,page:this.pageGetter(),logger:r}),i=await this.getMatchingFrameByUrlWithCdp(a,e),r.info({frameId:i.handle.frameId,url:i.handle.url,src:i.handle.src,locationData:i.handle.locationData},`Found matching frame using ${i.matchType}`);break}catch(c){if(s=c,c instanceof A&&c.reason==="UserInfrastructureError")throw c;l%3===0&&this.logger.warn({attempt:l,err:c},"Failed to resolve active frame, retrying..."),await J(500,n)}finally{l++}if(i)return{source:"url",frame:i.frame,handle:i.handle,frameIdentifierStringified:Rl(e),cacheTime:Date.now(),frameTree:a,mPathSelectorTokens:[]};throw s}async getMatchingFrameByUrlWithCdp(e,n){let r=n.url,o=this.pageGetter(),a=Array.from(e.childFrames),i=[];for(;a.length>0;){let s=a.shift(),l=s.domNode;a.push(...s.childFrames);let c=Tr(l.attributes??[],"src"),d=l.contentDocument?.documentURL;if(!c&&!d){this.logger.debug("Skipping frame with no URL or src");continue}for(let u of[c,d])if(u){if(r.startsWith("/")&&r.endsWith("/")){if(new RegExp(r.slice(1,-1)).test(u)){i.push({handle:s,matchType:"regex",...await On(s,o)});break}}else if(r.trim()===u.trim()){i.push({handle:s,matchType:"url",...await On(s,o)});break}}}if(i.length===1){let s=i[0];return this.userBrowserSettings.autoExpandIframes||(s.handle.childFrames=[]),s}else throw i.length>1?new Error(`Found multiple frames with src matching '${r}'. Please use a more specific selector.`):new A("ActionFailureError",`Failed to find frame with src matching: ${r}`)}async composeA11yDomGraph({opts:e,a11yGraph:n,domGraph:r,startingFrameId:o,frameContext:a,logger:i,iconKnowledgeBase:s,showZeroOpacityElements:l}){let c=await Iy({rawA11yGraph:n,startingFrameId:o,frameContext:a,domGraph:r,logger:i,cdpClient:this.cdpClient,showZeroOpacityElements:l,filterByViewport:e.filterByViewport,viewportDetails:void 0,iconKnowledgeBase:s,useMPaths:this.userBrowserSettings.visualActions});if(!c||!c.root)throw new Error("Accessibility tree appears empty");return{tree:c}}async addMomenticIds({rootPage:e,childFrames:n,frameFilter:r,logger:o}){if(this.userBrowserSettings.visualActions)return;let a=await this.addMomenticIdsHelper(r??e,1);if(!this.userBrowserSettings.autoExpandIframes||r)return;let i=Array.from(n),s=[];for(;i.length>0;){let l=i.shift();i.push(...l.childFrames);let c=async()=>{try{let{frame:d}=await On(l,e);a=await this.addMomenticIdsHelper(d,a)}catch(d){l.url!=="about:blank"&&o.warn({err:d},"Error adding momentic IDs to child frame, continuing...")}};s.push(c())}await Promise.all(s)}async addMomenticIdsHelper(e,n){if(this.userBrowserSettings.visualActions)return n;let r=this.logger;return await Qe({root:e,fn:a=>window.addIdsToElement?.(document.body,a),arg:n,timeout:2e3,waitForPageLoad:async()=>{try{await e.waitForLoadState("domcontentloaded",{timeout:this.smartWaitingTimeoutMs})}catch(a){r.warn({err:a},"Error loading frame root adding momentic ids, continuing...")}},codePath:"adding Momentic element IDs to the page"})??n}getPageDomain(e){try{let n=new URL(e);if(!n.hostname)return null;let r=n.hostname.split("."),o=r.length>2?r.slice(-2).join("."):n.hostname;return`${n.protocol}//${o}`}catch{return null}}async decideChildFrameUnrollEligibility({logger:e,warnings:n,handle:r}){try{let{shouldUnroll:o,reason:a}=await this.decideChildFrameUnrollEligibilityHelper({domNode:r.domNode});return{shouldUnroll:o,reason:a}}catch(o){if(o.message.includes("Could not compute box model"))return{shouldUnroll:!1};let a=`Got error when determining whether to filter frame ${r.frameId} with url ${r.url}, allowing it to be fetched: ${o}`;return n?.push(a),e?.warn({err:o},a),{shouldUnroll:!0}}}async decideChildFrameUnrollEligibilityHelper({domNode:e}){let n=e.attributes??[];if(Tr(n,"aria-hidden")==="true")return{shouldUnroll:!1,reason:"aria-hidden"};let r=Tr(n,"style");if(r?.includes("display: none")||r?.includes("visibility: hidden"))return{shouldUnroll:!1,reason:"hidden CSS style"};await this.cdpClient.send({timeout:3e3,method:"DOM.pushNodesByBackendIdsToFrontend",params:{backendNodeIds:[e.backendNodeId]}});let[o,a]=await Promise.all([this.cdpClient.send({timeout:3e3,method:"DOM.getBoxModel",params:{backendNodeId:e.backendNodeId}}),this.cdpClient.send({timeout:3e3,method:"CSS.getComputedStyleForNode",params:{nodeId:e.nodeId}})]);if(!o.model||!o.model.height||!o.model.width)return{shouldUnroll:!1,reason:"no bounding box"};if(o.model.height<10||o.model.width<10)return{shouldUnroll:!1,reason:"small bounding box"};for(let i of a.computedStyle){if(i.name==="display"&&i.value==="none")return{shouldUnroll:!1,reason:"display: none"};if(i.name==="visibility"&&i.value==="hidden")return{shouldUnroll:!1,reason:"visibility: hidden"};if(i.name==="opacity"&&i.value==="0")return{shouldUnroll:!1,reason:"opacity: 0"}}return{shouldUnroll:!0}}async getRawA11yGraph({cdpClient:e,frameId:n,childFrames:r,logTimings:o,logger:a=this.logger,signal:i=this.abortSignalGetter()}){let s=[];try{await this.pageGetter().waitForLoadState("load",{timeout:this.pageLoadTimeoutMs})}catch(p){a.warn({err:p},"Failed to wait for page load event before a11y tree fetch, attempting to continue without it..."),await this.cdpClient.reinitialize()}let l,c;for(let p=0;p<3;p++)try{c=await on({fn:()=>this.getRawA11yTreeForFrame({frameId:n,timeoutMs:this.pageLoadTimeoutMs,logTimings:o}),codePath:"a11y-tree-fetch-root",logObject:o,signal:i,logger:a});break}catch(g){l=g,a.warn({err:g},"Reinitializing CDP client before retrying a11y graph fetch"),await this.cdpClient.reinitialize()}if(!c)throw new Error(`Failed to fetch accessibility tree for root page: ${l}`);let d={};if(d[n??"root"]=c,!this.userBrowserSettings.autoExpandIframes)return d;let u=Array.from(r),m=[];for(;u.length>0;){let p=u.shift();try{let{shouldUnroll:h}=await this.decideChildFrameUnrollEligibility({handle:p,warnings:s});if(!h)continue}catch(h){if(h.message.includes("Could not compute box model"))continue;s.push(`Got error when determining whether to filter frame ${p.frameId} with url ${p.url}, allowing it to be fetched: ${h}`)}u.push(...p.childFrames);let g=async()=>{try{let h=await on({fn:()=>this.getRawA11yTreeForFrame({frameId:p.frameId,timeoutMs:this.smartWaitingTimeoutMs,logTimings:o}),codePath:`a11y-tree-fetch-child-${p.frameId}`,logObject:o,signal:i,logger:a});d[p.frameId]=h}catch(h){a.warn({err:h,url:p.url,src:p.src},`Error getting raw a11y tree for child frame ${p.frameId}, continuing...`)}};m.push(g())}return await Promise.all(m),s.length>0&&this.logger.warn({warnings:s},"Got warnings when fetching the raw a11y graph"),d}async getRawA11yTreeForFrame({frameId:e,timeoutMs:n,logTimings:r}){let o;if(this.allowPartialAccessibilityTree)o=(await on({fn:()=>this.cdpClient.send({method:"Accessibility.getFullAXTree",params:{frameId:e??void 0},timeout:n,timeoutMsg:`Fetching the document tree took over ${n}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:r,signal:this.abortSignalGetter(),logger:this.logger})).nodes;else{let i=(await on({fn:()=>this.cdpClient.send({method:"Accessibility.getRootAXNode",params:{frameId:e??void 0},timeout:2e3}),codePath:"cdp-get-root-ax-node",logObject:r,signal:this.abortSignalGetter(),logger:this.logger})).node.backendDOMNodeId;o=(await on({fn:()=>this.cdpClient.send({method:"Accessibility.queryAXTree",params:{backendNodeId:i},timeout:n,timeoutMsg:`Fetching the document tree took over ${n}ms. This usually indicates that the current page is too large to be loaded at once, or your machine is severely resource constrained.`}),codePath:"cdp-query-ax-tree",logObject:r,signal:this.abortSignalGetter(),logger:this.logger})).nodes}if(!o||o.length<=1)throw new Error("Document is entirely empty");return{root:o[0],allNodes:o}}async getDOMTree({devicePixelRatio:e,signal:n,logger:r}){let o,a=0,i;for(;!o&&a<3;)try{if(o=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:Tl},timeout:3e3}),!o||!o.documents.length)throw new Error("Got empty DOM tree")}catch(s){await J(500,n),a++,i=s}if(!o||!o.documents.length)throw r.error({err:i},"Fatal error fetching DOM tree"),new A("UserInfrastructureError","Received an empty HTML snapshot from the browser. This indicates the page has crashed due to resource consumption issues or hanging client-side JavaScript code.");return hy({snapshot:o,devicePixelRatio:e,logger:r})}constructIframeRegexAsync(e,n){if(n.frameSrcRegex||n.frameUrlRegex)return;let r=ky(e);(async()=>{try{let o=await this.enricher?.constructIframeRegex(r);o?.srcRegex&&(n.frameSrcRegex=o.srcRegex),o?.urlRegex&&(n.frameUrlRegex=o.urlRegex),this.logger.debug({result:o,params:r},"Constructed iframe regex for cache")}catch(o){this.logger.warn({err:o},"Failed to construct iframe regex, skipping...")}})()}};function Mu(t){let e=[],n="";for(let r of t)r==="+"&&n?(e.push(n),n=""):n+=r;return e.push(n),e}var Nu=ua(ku(),"momentic","chromium"),wM=ua(ku(),"video"),Pl=process.env.TWO_CAPTCHA_KEY,qy=yM(Vy);qy.use(bM({provider:{id:"2captcha",token:Pl},visualFeedback:!0}));var kn=class t{static USER_AGENT=SM["Desktop Chrome"].userAgent;abortSignal=void 0;contextInitialized=!1;browser;context;properties;page;userControlledBrowserSettings;pageLoadPromises={};lastTabChangeEventTimeout=void 0;clientCallbacks;iconKnowledgeBase;lastIconKnowledgeBaseUpdateTime=0;cdpClient;debugData={logsPerPage:[],harPages:{},harEntries:{}};recentFrameNavigations={};requestRecorders={};mocks={};customHeaders=[];enricher;storage;flagStore;logger;stateManager;transformer;lastScreenshotForRecording=void 0;originsVisited=new Set;viewport;videos=[];baseUrl;constructor({storage:e,flagStore:n,enricher:r,browser:o,context:a,page:i,baseUrl:s,logger:l,userBrowserSettings:c,viewport:d,properties:u,clientCallbacks:m,iconKnowledgeBase:p}){if(mh(c),this.storage=e,this.flagStore=n,this.enricher=r,this.browser=o,this.context=a,this.page=i,this.baseUrl=s,this.logger=l,this.userControlledBrowserSettings=c,this.viewport=d,this.properties=u,this.clientCallbacks=m,u.recordVideo){let g=this.page.video();g&&this.videos.push(g)}this.iconKnowledgeBase=p}registerAbortSignal(e){this.abortSignal=e}async initialize({grantPermissions:e,runInitScripts:n}){if(this.contextInitialized)return;this.userControlledBrowserSettings.extraHeaders&&await this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders),e&&await this.context.grantPermissions(["clipboard-read","clipboard-write","microphone","camera","geolocation"]);let r={[fl]:this.userBrowserSettings.visualActions},o=[this.context.addInitScript({content:BS.htmlUtilsLibJs}),this.context.addInitScript({content:`window._MOMENTIC_BROWSER = true; window._MOMENTIC_FEATURE_FLAGS = ${JSON.stringify(r)}; window.addEventListener('load', (event) => { console.log('[MOMENTIC] Page loaded'); });`})];n&&await this.page.reload();let a=s=>this.handleNewPageEvent(s);this.context.on("page",a),this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.context.off("page",a)});let i=Promise.all(o);await Promise.all([i]),this.properties.systemDevicePixelRatio||(process.env.MOMENTIC_LOCAL_DEV==="1"&&pM()==="darwin"&&iM("system_profiler SPDisplaysDataType").toString().includes("Retina")?(S.warn("[DEV] Setting device pixel ratio to 2 in local dev since a Retina display was detected"),this.properties.systemDevicePixelRatio=2):this.properties.systemDevicePixelRatio=await this.page.evaluate(()=>window.devicePixelRatio)),this.cdpClient=await El.init({logger:this.logger,contextGetter:()=>this.context,pageGetter:()=>this.page,defaultTimeoutMs:this.pageLoadTimeout}),await this.initializeScreencast(),this.stateManager=new Al({smartWaitingTimeoutMs:this.smartWaitingTimeout,pageLoadTimeoutMs:this.pageLoadTimeout,allowPartialAccessibilityTree:this.userControlledBrowserSettings.allowPartialAccessibilityTree??!1,logger:this.logger,cdpClient:this.cdpClient,pageGetter:()=>this.page,abortSignalGetter:()=>this.abortSignal,enricher:this.enricher,iconKnowledgeBase:this.iconKnowledgeBase,userBrowserSettings:this.userBrowserSettings}),this.contextInitialized=!0}async fixViewportForNewHeadless(){this.properties.isNewHeadless&&this.viewport&&await this.cdpClient.send({method:"Emulation.setDeviceMetricsOverride",params:{width:this.viewport.width,height:this.viewport.height,deviceScaleFactor:0,mobile:this.viewport.width<1e3}})}async initializeScreencast(){await this.fixViewportForNewHeadless(),this.clientCallbacks?.onScreencastFrame&&this.viewport&&(await this.cdpClient.send({method:"Page.startScreencast",params:{format:"jpeg",quality:75,maxWidth:this.viewport.width,maxHeight:this.viewport.height}}),this.cdpClient.on("Page.screencastFrame",e=>{let n=e.sessionId,r=Buffer.from(e.data,"base64");this.lastScreenshotForRecording=r,this.clientCallbacks?.onScreencastFrame?.(r,()=>{(async()=>{try{await this.cdpClient.send({method:"Page.screencastFrameAck",params:{sessionId:n}})}catch{}})()})}))}static async init({baseUrl:e,logger:n,storage:r,flagStore:o,enricher:a,userBrowserSettings:i,contextArgs:s,recordVideo:l,iconKnowledgeBase:c,callbacks:d}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let u;switch(i.browserType){case"Google Chrome":u="chrome";break;case"Chrome for Testing":u=void 0;break;case"Chromium":u="chromium";break;default:u="chromium";break}let m={headless:process.env.MOMENTIC_HEADFUL_BROWSER!=="true",handleSIGTERM:!1,chromiumSandbox:!1,channel:u},p={...s??{},geolocation:s?.geolocation||Fo,locale:s?.locale||_o,timezoneId:s?.timezoneId||Do,colorScheme:s?.colorScheme,httpCredentials:i.basicAuthorization?{username:i.basicAuthorization.username??"",password:i.basicAuthorization.password??""}:void 0,javaScriptEnabled:i.disableJavaScript?!1:void 0,ignoreHTTPSErrors:i.ignoreHttpsErrors??!1,userAgent:i.userAgent??t.USER_AGENT,viewport:s?.viewport??Nt},g=["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--browser-test","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--disable-backgrounding-occluded-windows","--disable-background-timer-throttling","--disable-renderer-backgrounding","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream"],h=null,f,y,b={systemDevicePixelRatio:s?.deviceScaleFactor,recordVideo:l,isNewHeadless:!1};(u==="chrome"||u==="chromium")&&(b.isNewHeadless=!0,m.headless&&g.push("--headless=new")),process.env.BROWSER_MEMORY_MB&&g.push(`--js-flags=--max_old_space_size=${process.env.BROWSER_MEMORY_MB}`),i.disableGpu&&g.push("--disable-3d-apis","--disable-gpu","--disable-software-rasterizer","--disable-accelerated-2d-canvas","--disable-accelerated-mjpeg-decode","--disable-accelerated-video-decode","--disable-accelerated-video-encode","--disable-gl-drawing-for-tests","--disable-webgl","--disable-audio-input","--disable-audio-output");let w=i.localChromeExtensionPaths?.map(v=>v.startsWith("~")?ua(ku(),v.slice(1)):v);if(w?.length){if(u===void 0)throw new A("UserConfigurationError","Chrome extensions are only supported on Chromium and Google Chrome.");for(let M of w){let D=ua(M,"manifest.json");if(!Il(D))throw new A("UserConfigurationError",`Chrome extension path ${D} does not exist.`)}let v=ua(Nu,`momentic-session-${Date.now()}`);if(!Il(v))try{sM(v,{recursive:!0})}catch(M){throw new A("UserConfigurationError",`Failed to create browser cache directory. Please make sure you have sufficient permissions to create the ${Nu} folder: ${M}`)}let R=[...g],x=w.map(M=>fM(M)).join(",");R.push(`--disable-extensions-except=${x}`),p?.deviceScaleFactor&&R.push(`--force-device-scale-factor=${p.deviceScaleFactor}`,`--device-scale-factor=${p.deviceScaleFactor}`),p.viewport&&R.push(`--window-size=${p.viewport.width},${p.viewport.height}`),f=await Vy.launchPersistentContext(ua(Nu,`momentic-session-${Date.now()}`),{...m,...p,ignoreDefaultArgs:["--disable-extensions","--disable-component-extensions-with-background-pages"],args:R,baseURL:e}),n.debug({sharedContextOptions:p,sharedBrowserOptions:m,userBrowserSettings:i,chromeArgs:R,flags:o.getAllFlags(),properties:b,baseUrl:e},"Browser initialization context args (persistent)"),y=f.pages()[0]}else{h=await qy.launch({...m,args:g});let v={...p,baseURL:e,recordVideo:l?{dir:wM}:void 0};f=await h.newContext(v),n.debug({contextArgs:v,sharedBrowserOptions:m,chromeArgs:g,userBrowserSettings:i,flags:o.getAllFlags(),properties:b,baseUrl:e},"Browser initialization context args (standard)"),y=await f.newPage()}let C=new t({browser:h,context:f,page:y,baseUrl:e,logger:n,storage:r,flagStore:o,enricher:a,userBrowserSettings:i,viewport:p.viewport||Nt,properties:b,clientCallbacks:d,iconKnowledgeBase:c});return await C.initialize({grantPermissions:!0,runInitScripts:!1}),C}static async fromExistingContext({context:e,storage:n,flagStore:r,enricher:o,userBrowserSettings:a,logger:i}){let s=e.pages()[0];if(!s)throw new Error("No page found in existing context");let l=s.viewportSize(),c=s?.url(),d=new t({browser:e.browser(),context:e,page:s,baseUrl:c,logger:i,storage:n,flagStore:r,enricher:o,userBrowserSettings:a,viewport:l,properties:{isNewHeadless:!0},clientCallbacks:void 0,iconKnowledgeBase:null});return await d.initialize({grantPermissions:!1,runInitScripts:!0}),d}async handleAvailableTabsChangeHelper(){try{let e=await wu(this.context,{getTitles:!0}),n=this.page.url();this.clientCallbacks?.onTabsChange?.(e,n)}catch(e){this.logger.error({err:e},"Error sending available tabs to frontend")}}handleAvailableTabsChange(){try{clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),500)}catch(e){this.logger.warn({err:e},"Error handling available tabs change")}}addToPageLoadPromises(e,n){let r=Lu(),o=`${e}-${r}`,a=Date.now(),i=!1,s=async()=>{try{await H(n(),{signal:this.abortSignal,milliseconds:this.pageLoadTimeout,message:`Page load promise for code path ${e} timed out after ${this.pageLoadTimeout}ms`})}catch(l){l.name!=="AbortError"&&this.logger.error({err:l,promiseKey:o,codePath:e,duration:Date.now()-a},`Page load promise for code path ${e} encountered error`)}finally{delete this.pageLoadPromises[o],i=!0}};this.pageLoadPromises[o]=s().catch(()=>{}),i&&delete this.pageLoadPromises[o]}handlePageClosedEvent(e){if(this.page!==e){this.logger.debug({url:e.url()},"Detected background page was closed, just updating available tabs only"),this.handleAvailableTabsChange();return}let n=async()=>{if(this.closed)return;this.logger.info({url:e.url()},"Detected active page was closed, switching to another tab");let r=this.context.pages();for(let o=r.length-1;o>=0;o--){let a=r[o];if(!(!a||a.isClosed()||!no(a.url()))){this.logger.info(`Automatically switching to tab ${o} after close: ${a.url()}`),await this.switchToPage({type:"INDEX",index:String(o)});break}}};this.addToPageLoadPromises("page closed handler",async()=>n())}handleNewPageEvent(e){let n=e.url();if(this.logger.info({url:n},"Detected new page event, registering handlers and waiting for load to complete"),this.properties.recordVideo){let r=e.video();r&&this.videos.push(r)}try{this.handleNewPageEventHelper(e)}catch(r){this.logger.warn({err:r},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){let n=Lu(),r="new-page-load-handler";e.on("close",i=>this.handlePageClosedEvent(i)),e.on("framenavigated",i=>this.handleFrameNavigationEvent(i)),e.on("crash",()=>{this.logger.error("Page crashed at the Playwright level!")});let o=this.context.pages().indexOf(e);e.on("console",i=>{XS(e,o,this.debugData,i,this.logger)});let a=async()=>{await QS(n,this.debugData,e),await e.route("**/*",async(i,s)=>{await xu({pageId:n,route:i,request:s,debugData:this.debugData,logger:this.logger,requestRecorders:this.requestRecorders,mocks:this.mocks})}),await e.route("**/*",Fy(this.customHeaders,this.logger)),await this.loadFrameAndRecordUrl({root:e,codePath:r}),this.handleAvailableTabsChange()};this.addToPageLoadPromises(r,async()=>a())}async handleCollectSvgs(e){if(!this.flagStore.isBooleanFlagEnabled("icon_knowledge_base")||this.page.isClosed()||this.page.mainFrame()!==e||!this.iconKnowledgeBase||!this.clientCallbacks?.onSvgsCollected||Date.now()-this.lastIconKnowledgeBaseUpdateTime<5e3)return;this.lastIconKnowledgeBaseUpdateTime=Date.now();let n=await this.stateManager.getDomGraph({devicePixelRatio:this.devicePixelRatio}),r=by({domGraph:n,flagStore:this.flagStore,logger:this.logger,existingHashes:this.iconKnowledgeBase});if(r.forEach(s=>{this.iconKnowledgeBase[s.hash]=s}),!r.length)return;let o=Oe(this.logger),a={pageUrl:e.url(),firstSeenTime:Date.now(),hostname:mM()};for(let s of["runId","testId"])o[s]&&(a[s]=o[s]);let i={metadata:a,newSvgs:r};this.clientCallbacks.onSvgsCollected(i)}handleFrameNavigationEvent(e){let n=e.url(),r=e.parentFrame()?"has-parent":"no-parent",o=`frame-navigation-handler-${n.slice(0,50)}-${r}`;if(!n||n==="about:blank"||!no(n)||this.recentFrameNavigations[o]&&Date.now()-this.recentFrameNavigations[o]<1e3)return;this.recentFrameNavigations[o]=Date.now();let a=async()=>{try{if(e.isDetached())return;await this.loadFrameAndRecordUrl({root:e,codePath:o,signal:this.abortSignal}),this.handleAvailableTabsChange(),!e.parentFrame()&&!e.isDetached()&&this.clientCallbacks?.onSvgsCollected&&(setTimeout(()=>{(async()=>{try{await this.handleCollectSvgs(e)}catch(s){this.logger.warn({err:s},"Failed to collect SVGs on page, continuing...")}})()},5e3),this.transformer&&await this.injectKnowledgeBaseIntoBrowser(e))}catch(i){i.name!=="AbortError"&&this.logger.warn({err:i},"Failed to handle frame navigation event, continuing...")}};this.addToPageLoadPromises(o,async()=>a())}async injectKnowledgeBaseIntoBrowser(e){try{if(!this.iconKnowledgeBase||await e.evaluate(()=>!!window._MOMENTIC_ICON_KNOWLEDGE_BASE))return;let r={};Object.keys(this.iconKnowledgeBase).forEach(o=>{this.iconKnowledgeBase[o]?.description&&(r[o]=this.iconKnowledgeBase[o].description)}),await e.evaluate(o=>{let a=window;a._MOMENTIC_ICON_KNOWLEDGE_BASE=o},r)}catch(n){this.logger.warn({err:n},"Failed to inject icon knowledge base into browser, continuing...")}}getBrowserCallbacks(){return{waitForPageLoad:()=>this.waitForPageLoad(),waitForUrl:e=>this.waitForUrl(e),getBrowserState:e=>this.getBrowserState(e),waitForDomStability:e=>this.waitForDOMStability(e),state:{url:()=>this.url(),getDomGraph:()=>this.stateManager.domGraph,getOpenPages:()=>this.getOpenPages(),getRoot:()=>this.getActivePageOrFrame(),userBrowserSettings:this.userBrowserSettings},pageLoadTimeoutMs:this.pageLoadTimeout,signal:this.abortSignal}}ping(){if(this.closed)throw new Error("Page has been closed")}setActiveFrameConfig(e){this.stateManager.setActiveFrameConfig(e)}async reset(e){for(this.abortSignal=void 0,this.debugData.logsPerPage=[],this.debugData.harPages={},this.debugData.harEntries={},this.pageLoadPromises={};this.videos.length>0;)this.videos.pop();await this.clearAuthState({closeNonActiveTabs:!0}),await this.stopScreencast(),await this.reinitializeCDPClient(),await this.navigate({url:e.newUrl??this.baseUrl,initialNavigation:!0,loadTimeoutMs:e.timeout}),this.stateManager.reset()}async clearHighlights(){try{await H(yu(this.getBrowserCallbacks()),{milliseconds:1e3})}catch(e){this.logger.debug({err:e},"Failed to clear highlights, continuing...")}}async cleanup(){this.abortSignal=void 0;try{this.originsVisited.clear(),await this.context.close(),await this.browser?.close(),this.browser=null}catch(e){this.logger.warn({err:e},"Error cleaning up browser, continuing...")}finally{this.browser=null}}get closed(){return this.context.pages().every(e=>e.isClosed())||!!this.browser&&!this.browser.isConnected()}async ensureMomenticBrowserScriptsLoaded(e,n,r){let o=Date.now(),a=0,i=0;for(;Date.now()-o<8e3;){i++,r?.throwIfAborted();try{if(await Qe({fn:()=>{let l=window;return!!(l.generateCssSelectors&&l.evaluateCssSelectors&&l.evaluatePrimaryCaches&&l.generateHtmlCacheAttributes&&l.ldist)},timeout:1e3,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),root:e,codePath:"ensuring Momentic system scripts are loaded"}))return}catch(s){if(a++,a>=3){n.warn({err:s},"Multiple errors checking if Momentic scripts are loaded, aborting...");return}}await J(500),i%2===0&&n.warn("Still waiting for momentic browser scripts to load...")}throw new Error(`Failed to load momentic browser scripts on page ${e.url()}`)}async html(){let e=await this.getActivePageOrFrame();return await this.ensureMomenticBrowserScriptsLoaded(e,this.logger),Qe({root:e,fn:()=>{let n=window;if(!n?.getFullHtmlTree)throw new Error("Missing Momentic HTML library when fetching page HTML");return n.getFullHtmlTree()},arg:void 0,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the full HTML tree"})}url(){return this.page.url()}async stabilizePageForScreenshot(){try{await this.evaluateFunctionInPage(()=>{let e=window,n=[],r=new Map;document.querySelectorAll("input,textarea,[contenteditable]").forEach(o=>{r.set(o,{value:o.style.getPropertyValue("caret-color"),priority:o.style.getPropertyPriority("caret-color")}),o.style.setProperty("caret-color","transparent","important")}),n.push(()=>{for(let[o,a]of r)o.style.setProperty("caret-color",a.value,a.priority)}),e._MOMENTIC_SCREENSHOT_CLEANUP=()=>{for(let o of n)o();delete e._MOMENTIC_SCREENSHOT_CLEANUP}},void 0,"stabilizing page for screenshot")}catch(e){(!(e instanceof Error)||!e.message.includes("Execution context was destroyed"))&&this.logger.warn({err:e},"Failed to stabilize page before screenshot, continuing...")}}async removeScreenshotStabilization(){try{await this.evaluateFunctionInPage(()=>{window._MOMENTIC_SCREENSHOT_CLEANUP?.()},void 0,"removing screenshot stabilization")}catch{}}async screenshot(e){let{retries:n=1,stabilizeBeforeScreenshot:r=!1}=e,o=this.page.url();r&&await this.stabilizePageForScreenshot();let a=Date.now();try{await this.fixViewportForNewHeadless();let i=await this.screenshotHelper({...e,retries:n});if(i.byteLength>5e6)this.logger.error("Page screenshot is greater than 5MB, which may cause performance issues with some AI models");else if(i.length===0)throw new Error("Got empty screenshot");return i}catch(i){if(n<=0||i.message.includes("has been closed"))throw i;return this.logger.warn({err:i,pageUrl:o},"Failed taking screenshot, retrying..."),await J(250),this.screenshot({...e,retries:n-1})}finally{Date.now()-a>1e3&&this.logger.warn({pageUrl:o,duration:Date.now()-a},"Screenshot took longer than expected"),r&&await this.removeScreenshotStabilization()}}async screenshotHelper({locator:e,quality:n,saveToDiskPath:r,timeout:o,respectActiveFrame:a,clearHighlights:i=!1}){i&&await this.clearHighlights(),a&&this.stateManager.frameConfig&&(e=await(await this.getActivePageOrFrame()).frameElement());let s=await this.cdpClient.send({method:"Page.captureScreenshot",params:{format:"jpeg",quality:n,optimizeForSpeed:!0},timeout:o??2e3}),l=Buffer.from(s.data,"base64"),c=await Gy.fromBuffer(l),{width:d,height:u}=this.getViewport()??{};if(d&&u&&(c.bitmap.width!==d||c.bitmap.height!==u)&&(l=await c.resize({w:d,h:u}).getBuffer("image/jpeg")),r&&cM(r,l),this.lastScreenshotForRecording=l,!e)return l;let m=await e.boundingBox({timeout:3e3});if(!m)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:p,y:g,width:h,height:f}=m;if(!h||!f)throw new Error("Attempted to screenshot an element with zero width or height");if(p<0||g<0)throw new Error("Attempted to screenshot an element with negative coordinates");p=Math.floor(p),g=Math.floor(g),h=Math.floor(h),f=Math.floor(f);try{l=await(await Gy.fromBuffer(l)).crop({x:p,y:g,w:h,h:f}).getBuffer("image/jpeg")}catch(y){throw new Error(`Failed taking element screenshot at coordinates (${p}, ${g}) with size (${h}, ${f}): ${y}`)}return"dispose"in e&&await e?.dispose(),l}getViewport(){return this.viewport?this.viewport:this.page.viewportSize()}async navigate({url:e,initialNavigation:n=!1,loadTimeoutMs:r=this.pageLoadTimeout}){xf(e)&&(e=new URL(e,this.baseUrl).toString());let o=Date.now();n||(await this.waitForPageLoad(),await this.waitForDOMStability());let a=!1,i;for(let l=0;l<3;l++)try{await this.page.goto(e,{timeout:r,waitUntil:"domcontentloaded"}),a=!0;break}catch(c){if(i=c,this.abortSignal?.throwIfAborted(),this.logger.warn({err:c},`Error occurred during navigation${l===0?", retrying...":" (fatal)"}`),await J(500),i.message.includes("Timeout")&&i.message.includes("exceeded")||i.message.includes("net::ERR_CONNECTION_REFUSED"))break;await this.cdpClient.send({method:"Page.stopLoading",params:{},timeout:1e3})}if(!a)throw new A("UserInfrastructureError",i?.message??"Failed to load page");await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"navigate-step-wait-for-load"}),this.logger.info({url:e},`Navigation complete in ${Math.floor(Date.now()-o)}ms`);let s=this.url();if(jS.has(s))throw new A("UserInfrastructureError",`${e} took too long to load \u{1F61E}. Please ensure the site is accessible and returns content within the page load timeout.`);if(n)try{await this.exposeRecordingBindings()}catch(l){l instanceof Error&&l.message.includes("already registered")||this.logger.error({err:l},"Failed to install Momentic libraries for action recording")}await this.fixViewportForNewHeadless()}async type(e,n={},r=!1){await this.directTypeHelper(e,n,r)}async getActiveElement(e){try{return await Qe({root:e,fn:()=>{let r=document.activeElement?.textContent??void 0;return r&&r.length>100&&(r=r.slice(0,100)+"...[TRUNCATED]"),document.activeElement?{tag:document.activeElement.tagName.toLowerCase(),contentEditable:document.activeElement.getAttribute("contenteditable")??void 0,textContent:r}:void 0},arg:void 0,timeout:1e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting the active element"})}catch(n){this.logger.warn({err:n},"Failed to get active element");return}}async directTypeHelper(e,n={},r=!1){let o=await this.getActivePageOrFrame();await iy({root:o,text:e,options:n,logger:this.logger,callbacks:this.getBrowserCallbacks()});let a=await this.getActiveElement(o);if(r){let i=Date.now();for(;Date.now()-i<this.smartWaitingTimeout&&(!a||a.tag==="body");)await J(250),this.abortSignal?.throwIfAborted(),a=await this.getActiveElement(o);a||this.logger.warn("No active element found to type into, attempting anyways")}n.clearContent&&(n.forceClearContent||a?.tag==="input"||a?.tag==="textarea"?(process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace"),await this.page.waitForTimeout(25)):this.logger.info({activeElementDetails:a},"Currently active element is not eligible for replace content, skipping...")),await this.page.keyboard.type(e,{delay:n.delay??Im}),n.pressEnter&&await this.press("Enter",{})}async scrollIntoViewIfNeeded(e){try{await e.scrollIntoViewIfNeeded({timeout:2e3})}catch(n){this.logger.warn({err:n},"Failed to scroll into view, trying with raw JS");try{await e.evaluate(async r=>{let o=r.scrollTop;r.scrollIntoView(),await new Promise(i=>setTimeout(i,250));let a=Date.now();for(;Date.now()-a<1e3;){let i=r.scrollTop;if(i===o)break;o=i,await new Promise(s=>setTimeout(s,250))}},void 0,{timeout:2e3})}catch(r){this.logger.warn({err:r},"Failed to scroll into view using JS, continuing...")}}}async highlightA11yId(e){try{let{resolution:n}=await this.createTargetFromA11yId({id:e,description:null,targetSource:"AI",skipSaveToCache:!0});return await this.highlight(n.locator),!0}catch(n){return this.logger.debug({err:n,id:e},"Failed to highlight target"),!1}}async highlight(e){return Sl({locator:e,callbacks:this.getBrowserCallbacks(),logger:this.logger})}recordUrlVisited(e){try{let n=new URL(e).origin;if(n==="null")return;this.originsVisited.add(n)}catch(n){this.logger.warn({err:n},"Failed to record origin visited")}}async waitForPageLoad(){let e=Date.now(),n=Object.values(this.pageLoadPromises),r=Object.keys(this.pageLoadPromises),o=-1,a=0;for(;n.length!==0;){if(Date.now()-e>this.pageLoadTimeout&&this.logger.error({outstandingPromiseKeys:r,outstandingPromises:n},"Still waiting on page load promises"),Date.now()-o<20&&(a++,a>2)){this.logger.error({outstandingPromiseKeys:r,outstandingPromises:n},"Synchronous waiting loop detected, exiting page load wait");return}o=Date.now(),await Promise.allSettled(n),n=Object.values(this.pageLoadPromises),r=Object.keys(this.pageLoadPromises)}}async clearAuthState(e){await this.context.clearCookies();for(let o of this.originsVisited)this.logger.debug({origin:o},`Clearing data using CDP for origin ${o}`),await this.cdpClient.send({method:"Storage.clearDataForOrigin",params:{origin:o,storageTypes:"all"},timeout:1e3}),this.originsVisited.delete(o);let n=this.context.pages().indexOf(this.page),r=[...this.context.pages()];for(let o=0;o<r.length;o++){let a=r[o];if(a.isClosed())continue;let i=a.url();try{this.originsVisited.delete(new URL(i).origin)}catch{}await YS(a,this.logger),o!==n&&e.closeNonActiveTabs&&(this.logger.info(`Closing tab ${o} with URL ${i}`),await a.close())}}async loadAuthState(e){await this.waitForPageLoad(),await this.waitForDOMStability(),!e||Object.keys(e).length===0?await this.clearAuthState({closeNonActiveTabs:!1}):await this.loadAuthStateHelper(e),await this.refresh(),await this.waitForDOMStability()}async loadAuthStateHelper(e){let n=[];for(let a of e.cookies??[]){let i=await this.setCookie(a);n=n.concat(i)}this.logger.info(`Loaded ${e.cookies?.length??0} cookies`),await this.cdpClient.send({method:"DOMStorage.enable",params:void 0,timeout:1e3});let r=0;for(let a of e.origins??[])for(let i of a.localStorage)try{await this.cdpClient.send({timeout:1e3,method:"DOMStorage.setDOMStorageItem",params:{storageId:{securityOrigin:new URL(a.origin).origin,isLocalStorage:!0},key:i.name,value:i.value}}),r++}catch(s){this.logger.warn({err:s,origin:a},"Failed to set local storage entry, continuing...");break}this.logger.info(`Loaded ${r} local storage entries`);let o=e.idb;o&&Object.keys(o).length>0&&(await KS(this.page,o,this.logger),this.logger.info(`Loaded ${Object.keys(o??{}).length} indexedDB databases`))}async saveAuthState(){let n=0,r=null;for(;n<=2;)try{await this.waitForPageLoad(),await this.waitForDOMStability();let o=await this.context.storageState();return o.idb=await qS(this.page,this.logger),o}catch(o){if(r=o,n++,n<=2){this.logger.warn({err:o,retryCount:n,maxRetries:2},`Error saving auth state, retrying (${n}/2)...`);let a=Math.pow(2,n)*100;await new Promise(i=>setTimeout(i,a))}}throw this.logger.error({err:r},"Failed to save auth state after 2 retries"),new A("ActionFailureError",`Failed to save auth state: ${r?.message}`)}async getOpenPages(e){return wu(this.context,e)}saveA11yDetailsToCache(e,n){n.content=e.content,n.name=e.name,n.role=e.role,n.numChildren=e.children.length,delete n.serializedForm,delete n.nodeOnlySerializedForm}async updateCacheWithNewNodeDetails({node:e,target:n,locator:r,forceSaveNewCssSelectors:o,startingBoundingBox:a,allowZeroOpacityOverride:i,logger:s=this.logger}){if(e&&this.saveA11yDetailsToCache(e,n),n.frameCache=this.stateManager.saveAutoFrameCacheDetails(n.frameCache),r)try{let l=await this.fetchHtmlAttributes({locator:r,logger:s,startingBoundingBox:a,allowZeroOpacityOverride:i}),c=!1;for(let d of["generatedSelectors","serializedHtml","nodeOnlySerializedHtml","hybridSelector"]){let u=l?.[d];if(u&&!n[d]){c=!0;break}if(u&&JSON.stringify(u)!==JSON.stringify(n[d])){c=!0;break}}l&&(o||c)&&(n.generatedSelectors=l.generatedSelectors,n.serializedHtml=l.serializedHtml,n.nodeOnlySerializedHtml=l.nodeOnlySerializedHtml,n.hybridSelector=l.hybridSelector)}catch(l){if(l instanceof Rn)throw l;s.warn({err:l},"Failed to fetch HTML attributes for target, continuing...")}try{await this.saveElementVisualAttributes({target:n,locator:r,logger:s,boundingBox:a})}catch(l){s.debug({err:l},"Failed to save element visual details, continuing...")}}async saveElementVisualAttributes({target:e,locator:n,logger:r,boundingBox:o}){if(!n)return{scrollPerformed:!1};if(!iu.includes(e?.role??""))return{scrollPerformed:!1};if(await this.scrollIntoViewIfNeeded(n),o||(o=await n.boundingBox({timeout:3e3})),!o||!o.width||!o.height)return r.debug("Skipping visual attributes saving for element with no bounding box after action"),e.boundingBox=void 0,e.screenshotUrl=void 0,{scrollPerformed:!0};let{x:a=0,y:i=0,width:s=0,height:l=0}=o;if(e.boundingBox&&Math.abs(e.boundingBox.width-s)<1&&Math.abs(e.boundingBox.height-l)<1&&Math.abs((e.boundingBox.x??0)-a)<1&&Math.abs((e.boundingBox.y??0)-i)<1)return{scrollPerformed:!0};e.boundingBox=o;let c=await this.screenshot({locator:n,quality:75,retries:0});return e.screenshotUrl=await this.storage.uploadScreenshot(c),{scrollPerformed:!0}}async resolveAutoFrameCache(e){return this.stateManager.resolveAutoFrameCache(e)}async createTargetFromA11yId({id:e,description:n,targetSource:r,skipSaveToCache:o,logger:a=this.logger}){if(e<0)throw new A("InternalWebAgentError","Only positive IDs should be passed to resolveAllyIdToTarget");let i=this.stateManager.a11yIdToNodeMap[e];if(!i)throw new A("InternalWebAgentError",`Resolving target failed because id ${e} does not exist on the page. This generally indicates an incorrect element was targeted.`);let s=this.stateManager.frameConfig,l,c,d,u;if(this.userBrowserSettings.autoExpandIframes&&!s&&i.parentFrame){let f=i.parentFrame,{cache:y,config:b}=await this.stateManager.getAutoFrameDetailsFromHandle(f);c=y,d=b,l=b.frame,u="auto iframe"}else i.parentFrame&&s?(d=s,l=await this.getActivePageOrFrame(),u="hardcoded url already on the state manager"):(l=await this.getActivePageOrFrame(),u="should not be possible");let m=await this.stateManager.getLocatorFromA11yNode({page:this.page,root:l,node:i}),p={id:e,inputDescription:n??void 0,targetSource:r,targetUpdateTime:new Date().toISOString(),targetUpdateLoggerTags:Oe(a),frameCache:c},g,h=!1;o||(d&&(a.info({frameConfigSource:u,frameConfig:_y(d)},"A11y node was resolved to a target within an iframe"),g=this.stateManager.frameConfig,this.stateManager.setActiveFrameConfig(d),h=!0),await this.updateCacheWithNewNodeDetails({node:i,target:p,locator:m,logger:a,forceSaveNewCssSelectors:!0,allowZeroOpacityOverride:!0}));try{return{resolution:{locator:m,a11yNode:i,displayString:i.getNodeOnlySerializedForm(),decisions:[]},target:p,frameConfig:d,frameConfigSource:u}}finally{h&&this.stateManager.setActiveFrameConfig(g)}}async resolveTarget(e,n,r={}){let{targetName:o,logger:a=this.logger,signal:i=this.abortSignal,allowZeroOpacityOverride:s}=r;if(n.frameCache&&this.userBrowserSettings.autoExpandIframes){let p,g=!1,h=Date.now();for(;Date.now()-h<this.smartWaitingTimeout;)try{let f=await this.stateManager.resolveAutoFrameCache(n.frameCache);this.setActiveFrameConfig(f),g=!0;break}catch(f){p=f,await J(500,i)}if(!g)throw p}let l=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(l,a,i);let c=Date.now(),d=0,u=0,m;for(;Date.now()-c<this.smartWaitingTimeout;){this.abortSignal?.throwIfAborted(),d++;let p=d===2||Date.now()-c>this.smartWaitingTimeout-2e3&&d%2===0;try{m=await this.resolveTargetHelper({root:l,target:n,primaryOnly:!0,logger:p?a:Xr,allowZeroOpacityOverride:s,signal:i});break}catch(g){if(g instanceof ja)break;if(g instanceof Rn){if(u++,u>2)throw a.error({err:g},"Got multiple cache disqualification errors, giving up"),g;a.warn({err:g},"Got cache disqualification error, waiting and retrying resolution"),await J(500,i)}i?.throwIfAborted(),p&&a.info({err:g},`Could not resolve target using primary cache only (x${d})`),await J(500,i)}}return m||(m=await this.resolveTargetHelper({root:l,target:n,primaryOnly:!1,logger:a,signal:i,allowZeroOpacityOverride:s}),n.targetSource="HEURISTIC_HEALED",n.targetUpdateTime=new Date().toISOString(),n.targetUpdateLoggerTags=Oe(a),a.info({decisions:m.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:o,elementLocationDecisions:m?.decisions??[],pageState:void 0,targetSource:n.targetSource,targetUpdateTime:n.targetUpdateTime}),m}async resolveTargetHelper({root:e,target:n,primaryOnly:r,logger:o,signal:a,allowZeroOpacityOverride:i}){let s=[],l=(await this.getBrowserState({logger:o,abortSignal:a,skipWait:!0,allowZeroOpacityOverride:i})).serialize(),c;if(n.generatedSelectors||n.hybridSelector){let d;try{d=await this.resolveTargetWithPrimaryMethods({root:e,target:n,logger:o,allowZeroOpacityOverride:i})}catch(u){c=u,u instanceof En&&s.push(...u.decisions)}if(d)return{...d,pageState:void 0,decisions:[...s,...d.decisions]};r||(s.push({type:"CSS_SELECTOR",matched:!1,reason:c?.message,selectors:yi(n.generatedSelectors??[])}),n.generatedSelectors=void 0,n.hybridSelector=void 0)}if(r)throw c;if(!this.userBrowserSettings.disableSecondaryCacheResolution){let d=await this.resolveTargetWithSecondaryMethods({root:e,tree:l,target:n,decisions:s,logger:o,signal:a,allowZeroOpacityOverride:i});if(d)return d}throw new En(`Could not find any relevant node given target: ${JSON.stringify(n)}`,s)}async resolveTargetWithPrimaryMethods({root:e,target:n,logger:r,allowZeroOpacityOverride:o}){if(!n.nodeOnlySerializedHtml)throw new ja("Insufficient data to resolve target using primary methods (missing node HTML)");let a=this.userControlledBrowserSettings.hybridSelectorMode,i={ldistThreshold:.05,requireBoundingBox:!o,ignoreHrefForCaching:this.userControlledBrowserSettings.ignoreHrefForCaching,requireMatchingBoundingBox:this.userControlledBrowserSettings.bustCacheOnBoundingBoxChange?n.boundingBox:void 0},{css:s,hybrid:l}=await Qe({fn:w=>window.evaluatePrimaryCaches(w),arg:{cssParams:{selectors:n.generatedSelectors??[],cachedElementSerialized:n.nodeOnlySerializedHtml,opts:i},hybridParams:a&&n.hybridSelector?{nodes:n.hybridSelector,cachedElementSerialized:n.nodeOnlySerializedHtml,opts:i}:void 0},root:e,timeout:3e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"evaluating target caches"}),c,d,u,m=[];if(a==="prefer"&&l?.result){c=l,d=l.result;let w={type:"HYBRID_SELECTOR",matched:!0,logs:l.logs,reason:"Discovered a match using Momentic's hybrid text and CSS selector approach"};m.push(w),u="HYBRID_SELECTOR"}else if(s?.result)c=s,d=s.result,m.push({type:"CSS_SELECTOR",matched:!0,logs:s.logs,reason:`${d.workingSelectors.length} CSS selectors matched the following element: ${d.serializedElement}`,selectors:d.workingSelectors.slice(0,5)}),u="CSS_SELECTOR";else throw m.push({type:"CSS_SELECTOR",matched:!1,reason:s.logs.length===1?"CSS evaluation failed":"No CSS selectors matched",selectors:[],logs:s.logs}),l&&m.push({type:"HYBRID_SELECTOR",matched:!1,reason:l.logs.length===1?"Hybrid evaluation failed":"No hybrid selectors matched",logs:l.logs}),new En("Cache evaluation failed",m);let p,g,h,f=!1;if(this.userBrowserSettings.visualActions){let w=d.mPath;if(!w)throw new Error("Found element did not have an mPath despite using visual actions");let C=w.join(" > ");p=e.locator(C),g=this.stateManager.getNodeUsingMPathSelector(C)}else if(d.dataMomenticId!==void 0)h=parseInt(d.dataMomenticId),g=this.stateManager.dataMomenticIdToNodeMap[h],"workingSelectors"in d?(p=e.locator(d.workingSelectors[0]),f=d.workingSelectors.length<5):p=e.locator(pn(h));else throw new A("InternalWebAgentError","Received an element resolution result with no identifying attributes");a&&n.hybridSelector&&(l?.logs.length===1?r.warn({hybridResult:l,cssResult:s,hybridMode:a},"Hybrid selector resolution rejected, continuing..."):l?.result?s?.result&&l?.result&&l.result.serializedElement!==s.result.serializedElement&&(this.userBrowserSettings.visualActions&&JSON.stringify(s.result.mPath)!==JSON.stringify(l.result.mPath)?r.warn({originalCache:n,hybridResult:l,cssResult:s,hybridMode:a,mode:"visualActions"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing..."):s.result.dataMomenticId!==l.result.dataMomenticId&&r.warn({originalCache:n,hybridResult:l,cssResult:s,hybridMode:a,mode:"dataMomenticId"},"Hybrid selector resolution returned a different element than CSS selector resolution, continuing...")):r.warn({originalCache:n,hybridResult:l,cssResult:s,hybridMode:a},"Hybrid selector resolution returned no eligible elements while CSS resolution did, continuing..."));let y=yi(n);await this.updateCacheWithNewNodeDetails({node:g,target:n,locator:p,logger:r,startingBoundingBox:d.boundingBox,forceSaveNewCssSelectors:f,allowZeroOpacityOverride:o});let b=Ou(y,n);return b&&Object.keys(b).length>0&&(n.cacheResolutionUpdateTime=new Date().toISOString(),n.cacheResolutionUpdateLoggerTags=Oe(r),n.cacheResolutionUpdateSource=u),{a11yNode:g,displayString:d.serializedElement,locator:p,decisions:m}}async resolveHardcodedCssSelector(e){let{ctx:n,selector:r,logger:o=this.logger,signal:a=this.abortSignal,timeoutMs:i=this.smartWaitingTimeout}=e,s=await this.getActivePageOrFrame(),l=Date.now(),c=0,d,u=[];for(;Date.now()-l<i;){a?.throwIfAborted(),c++;let m=s.locator(r),p;try{return await m.waitFor({state:"attached",timeout:1e3}),p=await Yn(m,o)??"",u.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${r} matched an element on the page.`}),n?.details?.push({type:"TARGETING",name:e.targetName,elementLocationDecisions:u,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toISOString()}),{locator:m,displayString:p,decisions:u}}catch(g){let h=g.message;d=new A("ActionFailureError",`CSS selector '${r}' failed to resolve after ${c} attempts: ${h.includes("locator.waitFor: Timeout")?"the selector did not match any element on the page":h}`),await J(500,a)}}throw d}async resolveTargetWithSecondaryMethods(e){if(!e.target.boundingBox)return;let{x:n,y:r,width:o,height:a}=e.target.boundingBox,i=await this.resolveTargetWithSecondaryMethodsHelper(e);if(!i)return;let s=await i.locator.boundingBox({timeout:3e3});if(!s){this.logger.debug({proposedNode:i.displayString},"Rejecting secondary matching result due to lack of a bounding box");return}let{x:l,y:c,width:d,height:u}=s;if(Math.abs(d-o)>10||Math.abs(u-a)>10){this.logger.debug({newW:d,oldW:o,newH:u,oldH:a,proposedNode:i.displayString},"Rejecting secondary matching result due to difference in dimensions");return}else if(!n||!r||!l||!c){this.logger.debug({oldX:n,oldY:r,newX:l,newY:c,proposedNode:i.displayString},"Rejecting secondary matching result due to missing x/y coords");return}else if(Math.abs(l-n)>100||Math.abs(c-r)>100){this.logger.debug({newX:l,newY:c,oldX:n,oldY:r,proposedNode:i.displayString},"Rejecting secondary matching result due to large difference in x/y coords");return}return i}async resolveTargetWithSecondaryMethodsHelper({root:e,target:n,decisions:r,logger:o,signal:a,allowZeroOpacityOverride:i}){if(n.nodeOnlySerializedHtml&&n.nodeOnlySerializedHtml.trim().length<10){let c="Refusing to attempt HTML comparison since the saved element is too short.";r.push({type:"HTML_DISTANCE",matched:!1,reason:c})}else if(n.nodeOnlySerializedHtml&&n.nodeOnlySerializedHtml.length>50)try{let c=await Qe({fn:u=>window.findClosestElementByLDist?.(u),arg:{nodeOnlySerializedHtml:n.nodeOnlySerializedHtml},timeout:2e3,root:e,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"finding the closest element on the page"}),d=Math.floor(.05*n.nodeOnlySerializedHtml.length);if(c&&c.closestDistance&&c.closestDistance>=d){let u=`Closest HTML candidate still has too far distance (${c.closestDistance}) from threshold (${d})`;r.push({type:"HTML_DISTANCE",matched:!1,reason:u,distance:c.closestDistance,closestElement:c.closestNodeSerialized})}else{if(c?.error)throw new Error(c.error);if(c?.dataMomenticId||c?.mPathSelector){let u=c.dataMomenticId?parseInt(c.dataMomenticId):void 0,m,p;if(u)m=this.stateManager.dataMomenticIdToNodeMap[u],p=e.locator(pn(u));else if(c.mPathSelector)m=this.stateManager.getNodeUsingMPathSelector(c.mPathSelector),p=e.locator(c.mPathSelector);else throw new Error("HTML ldist comparison returned no error, data momentic id, or mPath selector");let g=c.closestNodeSerialized??await Yn(p,o)??"unknown element";o.warn({result:c,originalTarget:n,displayString:g},"Resolved cached target to new node with pure html levenshtein distance");let h=yi(n);await this.updateCacheWithNewNodeDetails({node:m,target:n,locator:p,logger:o,startingBoundingBox:c.boundingBox,allowZeroOpacityOverride:i,forceSaveNewCssSelectors:!0});let f=Ou(h,n);return f&&Object.keys(f).length>0&&(n.cacheResolutionUpdateTime=new Date().toISOString(),n.cacheResolutionUpdateLoggerTags=Oe(o),n.cacheResolutionUpdateSource="HTML_DISTANCE",o.info({diffs:f,result:c},"Updated cache after l-dist resolution")),r.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${d} string comparison distance of the saved element.`,logs:c.logs,distance:c.closestDistance,closestElement:g,savedElement:n.nodeOnlySerializedHtml}),{locator:p,a11yNode:m,displayString:g,decisions:r,pageState:void 0}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(c)}`)}}catch(c){o.info({err:c},"Failed to find closest HTML node using levenshtein distance"),r.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${c}`})}let s=n.screenshotUrl,l=n.role??"";if(s&&iu.includes(l))try{let c=await this.resolveTargetWithTemplateMatching({root:e,oldTarget:n,screenshotUrl:s,signal:a,allowZeroOpacityOverride:i});return{...c,decisions:[...r,...c.decisions],pageState:void 0}}catch(c){a?.throwIfAborted(),r.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${c}`,elementImageUrl:s}),o.warn({err:c},"Did not find any close element using saved screenshot")}}async resolveTargetWithTemplateMatching({root:e,screenshotUrl:n,oldTarget:r,signal:o,allowZeroOpacityOverride:a}){let i;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let s=await this.screenshot({retries:0}),c=await(await fetch(n)).arrayBuffer(),d=TM(),u=await this.enricher.runTemplateMatching({id:d,searchImageBase64String:Buffer.from(c).toString("base64"),pageImageBase64String:s.toString("base64")},{signal:o}),{target:m,locator:p}=await this.getTargetFromPositionPercentages({percentX:u.x,percentY:u.y,allowZeroOpacityOverride:a}),g=m.boundingBox?.width,h=m.boundingBox?.height;if(!g||!h)throw i="Rejecting target from screenshot due to no bounding box",new Error(i);let f=m.id,y=this.stateManager.a11yIdToNodeMap[f],b=yi(r);await this.updateCacheWithNewNodeDetails({target:r,node:y,locator:p,forceSaveNewCssSelectors:!0,allowZeroOpacityOverride:a});let w=Ou(b,r);return w&&Object.keys(w).length>0&&(r.cacheResolutionUpdateTime=new Date().toISOString(),r.cacheResolutionUpdateLoggerTags=Oe(this.logger),r.cacheResolutionUpdateSource="TEMPLATE_MATCHING",this.logger.info({id:d,diffs:w,templateMatch:u},"Updated cache after template matching resolution")),{locator:p,a11yNode:y,displayString:m.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:n}]}}async typeIntoTarget(e,n,r={}){await this.highlight(n.locator);let o=await n.locator.getAttribute("type",{timeout:1e3})??"",a=ay.some(i=>i===o.toLowerCase());return await bu({targetingResult:n,options:{force:r.force},logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,position:a?{x:1,y:1}:void 0,actionSource:"type",browserCallbacks:this.getBrowserCallbacks()}),await this.page.waitForTimeout(150),this.directTypeHelper(e,r)}async click(e,n,r={}){return bu({targetingResult:e,options:r,logger:this.logger,actionSource:"click",retryTimeoutMs:this.smartWaitingTimeout,controllerCallbacks:n,browserCallbacks:this.getBrowserCallbacks()})}async waitForUrl({beforeUrl:e,matcher:n},r){let o=r?.timeout??this.pageLoadTimeout,a=Date.now(),i=!1,s=e;for(;Date.now()-a<o;){if(this.abortSignal?.throwIfAborted(),s=this.url(),Js(s,n,r)){i=!0;break}await J(500,this.abortSignal)}if(!i)throw new A("ActionFailureError",`The active page URL ${r?.negated?"still does":"does not"} ${js(n)} in ${o}ms.
3902
+ Current tab: ${s}`);try{await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"wait-for-url-step"})}catch(l){this.logger.warn({err:l},"Failed waiting for page load after URL change, continuing...")}}async dragAndDrop(e,n,r={}){await this.hover({locator:e}),await this.page.mouse.down();let o=await n.boundingBox({timeout:3e3});if(!o)throw new A("ActionFailureError","Could not get bounding box of target element");let a=o.x+o.width/2,i=o.y+o.height/2,s=r.steps??5;await this.page.mouse.move(a,i,{steps:s}),await J(r.hoverSeconds?Math.min(r.hoverSeconds*1e3,2e3):500),await this.page.mouse.up()}async mouseDrag(e,n,r,o){o&&await this.hover({locator:o});let a=await(await this.getActivePageOrFrame()).evaluate(Su);a||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),a={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+a.left,n+a.top,{steps:r}),await J(250),await this.page.mouse.up()}async hover(e){await this.highlight(e.locator),await uo({func:async n=>{await this.scrollIntoViewIfNeeded(n.locator);let r=await n.locator.boundingBox({timeout:3e3});if(!r)throw new Error("Attempted to hover over element with no bounding box");await this.page.mouse.move(r.x+r.width/2,r.y+r.height/2,{steps:3})},action:"hovering over element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,targetingResult:e,callbacks:this.getBrowserCallbacks()})}async focus(e){await this.highlight(e.locator),await uo({func:n=>n.locator.focus({timeout:2e3}),action:"focusing element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async blur(e){if(!e){let n=await this.getActivePageOrFrame();await Qe({fn:()=>{let r=document.activeElement;r&&r.nodeType===1&&r.blur()},root:n,arg:void 0,waitForPageLoad:()=>this.waitForPageLoad(),timeout:1e3,codePath:"blurring the active element"});return}await this.highlight(e.locator),await uo({func:n=>n.locator.blur({timeout:2e3}),action:"blurring element",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),targetingResult:e})}async selectOption(e,n,r=!1){await this.highlight(e.locator),await uo({action:"selecting option from dropdown",logger:this.logger,retryTimeoutMs:this.smartWaitingTimeout,callbacks:this.getBrowserCallbacks(),func:async o=>{if(n.type==="INDEX"){let a=Number(n.index);if(isNaN(a))throw new A("UserConfigurationError",`Page index ${n.index} is not a number`)}await o.locator.selectOption({value:n.type==="VALUE"?n.value:void 0,label:n.type==="LABEL"?n.label:void 0,index:n.type==="INDEX"?Number(n.index):void 0},{force:r,timeout:3e3})},targetingResult:e})}async press(e,n){let r=n.repeat??1;if(n.convertMeta){let o=yl(e);o!==e&&(this.logger.info({key:e,convertedKey:o},"Converted platform dependent keys"),e=o)}for(let o=0;o<r;o++)await this.page.keyboard.press(e,{delay:n.delayMs??0})}async keyDown(e,n){if(n.convertMeta){let r=yl(e);r!==e&&(this.logger.info({keyString:e,convertedKey:r},"Converted platform dependent keys"),e=r)}for(let r of Mu(e))await this.page.keyboard.down(r)}async keyUp(e,n){if(n.convertMeta){let r=yl(e);r!==e&&(this.logger.info({keyString:e,convertedKey:r},"Converted platform dependent keys"),e=r)}for(let r of Mu(e))await this.page.keyboard.up(r)}async refresh(e){let n=e?.loadTimeoutMs??this.pageLoadTimeout;await this.waitForPageLoad();let r=0,o=2;for(;r<o;){r++;try{await this.page.reload({waitUntil:"domcontentloaded",timeout:n});break}catch(a){this.logger.warn({err:a,attempt:r},`Failed to reload page${r<o?", retrying...":", continuing..."}`)}}await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"reload-step"}),await this.waitForDOMStability()}async getBrowserState(e){let{maxAttempts:n=2,logger:r=this.logger,skipWaitForPageLoad:o,allowZeroOpacityOverride:a}=e,i=e.abortSignal??this.abortSignal,s=a?!0:this.userControlledBrowserSettings.showZeroOpacityElements;o||await this.waitForPageLoad(),e.skipWait||await this.waitForDOMStability({logger:r,signal:i});let l=0,c;for(;l<n;){l++;try{return await H(this.stateManager.getA11yTree({devicePixelRatio:this.devicePixelRatio,abortSignal:i,logger:r,filterByViewport:e.filterByViewport,showZeroOpacityElements:s}),{milliseconds:this.pageLoadTimeout*l,signal:i,message:"Getting browser state took too long"})}catch(d){if(i?.throwIfAborted(),c=d instanceof Error?d.message:`${d}`,l>=n)throw d;r.warn({err:d,url:this.url()},"Error getting a11y tree, retrying...")}}throw new A("ActionFailureError",`Getting page content failed after ${n} attempts. Error: ${c}`)}async getViewportOffsetDetails(e){let[n,r,o,a,i]=await Qe({root:e,fn:()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio],arg:void 0,timeout:3e3,waitForPageLoad:async()=>{},codePath:"getting current viewport details"});return{upperBound:n,lowerBound:n+a,leftBound:r,rightBound:r+o,width:o,height:a,devicePixelRatio:this.properties.systemDevicePixelRatio??i}}async waitForDOMStability(e){let{logger:n=this.logger,timeout:r=this.smartWaitingTimeout,signal:o}=e??{},a={value:Date.now()},i=m=>{a.value=Date.now()},s=()=>i("DOM.documentUpdated");this.cdpClient.addListener("DOM.documentUpdated",s);let l=()=>i("Page.frameDetached");this.cdpClient.addListener("Page.frameDetached",()=>l);let c=()=>i("Page.frameStartedLoading");this.cdpClient.addListener("Page.frameStartedLoading",c);let d=()=>i("Page.navigatedWithinDocument");this.cdpClient.addListener("Page.navigatedWithinDocument",d);let u=()=>i("frameRequestedNavListener");this.cdpClient.addListener("Page.frameRequestedNavigation",u);try{await this.waitForDOMStabilityHelper(a,n,r,o)}finally{this.cdpClient.removeListener("DOM.documentUpdated",s),this.cdpClient.removeListener("Page.frameDetached",l),this.cdpClient.removeListener("Page.frameStartedLoading",c),this.cdpClient.removeListener("Page.navigatedWithinDocument",d),this.cdpClient.removeListener("Page.frameRequestedNavigation",u)}}async waitForDOMStabilityHelper(e,n,r,o){let a=!1,i=Date.now(),s,l={quality:25,retries:0,stabilizeBeforeScreenshot:!0},c=!1,d=0;for(;Date.now()-i<r;){if(o?.throwIfAborted(),await J(500,this.abortSignal),s)try{let m=await this.screenshot(l);if(!m.equals(s)){s=m,c=!1;continue}c=!0}catch(m){d++,d%3===0&&n.warn({err:m,screenshotErrors:d},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}else try{s=await this.screenshot(l)}catch(m){d++,d%3===0&&n.warn({err:m,screenshotErrors:d},"Failed to take screenshot for DOM stability check"),o?.throwIfAborted()}if(!(Date.now()-e.value<750)){a=!0;break}}let u={duration:Date.now()-i,a11yStableReceived:a,lastTreeUpdateMillisecondsAgo:Date.now()-e.value,screenshotStable:c};a||n.warn(u,"A11y wait phase completed due to timeout, continuing...")}async clickUsingVisualCoordinates(e,n){let{x:r,y:o}=e;this.logger.debug({x:r,y:o},"Executing mouse click with visual coordinates"),await this.waitForPageLoad(),await this.page.mouse.click(r,o,{button:n.rightClick?"right":"left",clickCount:n.doubleClick?2:1})}async dragAndDropUsingVisualCoordinates(e,n,r){await this.page.mouse.move(e.x,e.y,{steps:3}),await this.page.mouse.down(),await this.page.mouse.move(n.x,n.y,{steps:3}),await J(r.hoverSeconds?Math.min(r.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){await this.page.mouse.move(e.x,e.y)}async mouseDragUsingVisualCoordinates(e,n,r,o){await this.hoverUsingVisualCoordinates(o);let a=await(await this.getActivePageOrFrame()).evaluate(Su);a||(this.logger.warn("Could not get current mouse position before mouse drag action, defaulting to 0,0"),a={left:0,top:0}),await this.page.mouse.down(),await this.page.mouse.move(e+a.left,n+a.top,{steps:r}),await J(250),await this.page.mouse.up()}async getElementLocation(e){let n=await this.cdpClient.send({method:"DOMSnapshot.captureSnapshot",params:{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0},timeout:3e3}),r=await H(this.page.evaluate(()=>window.devicePixelRatio),{milliseconds:2e3});process.platform==="darwin"&&r===1&&(r=2);let o=n.documents[0],a=o.layout,i=o.nodes,s=i.nodeName||[],l=i.backendNodeId||[],c=a.nodeIndex,d=a.bounds,u=-1;for(let b=0;b<s.length;b++)if(l[b]===e){u=c.indexOf(b);break}if(u===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[m=0,p=0,g=0,h=0]=d[u];m/=r,p/=r,g/=r,h/=r;let f=m+g/2,y=p+h/2;return{centerX:f,centerY:y}}async scrollVertical(e){return Tu({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:0,directionX:null,deltaY:e?Math.abs(e):null,directionY:e&&e>0?"down":"up",signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async scrollHorizontal(e){return Tu({frame:this.stateManager.frameConfig?await this.getActivePageOrFrame():null,page:this.page,deltaX:e?Math.abs(e):null,directionX:e&&e>0?"right":"left",deltaY:0,directionY:null,signal:this.abortSignal,callbacks:this.getBrowserCallbacks(),logger:this.logger})}async goForward(){await this.waitForPageLoad(),await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-forward"})}async goBack(){await this.waitForPageLoad(),await this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}),await this.loadFrameAndRecordUrl({root:this.page,signal:this.abortSignal,codePath:"go-back"})}async createRawCDPSession(e){let n=await H(this.context.newCDPSession(this.page),{milliseconds:e??this.pageLoadTimeout,fallback:()=>{throw this.logger.error(`Timed out creating new CDP session for ${this.page.url()}`),new A("UserInfrastructureError",`Failed to initialize Chrome session within the page load timeout (${this.page.url()})`)}});return this.logger.info(`Created new CDP session for ${this.page.url()}`),n}async reinitializeCDPClient(e){await this.cdpClient.reinitialize(e),await this.initializeScreencast()}async stopScreencast(){if(this.clientCallbacks?.onScreencastFrame)try{await this.cdpClient.send({method:"Page.stopScreencast",params:{}})}catch{}}async changeActivePage(e,n){await this.stopScreencast(),this.recordUrlVisited(e.url()),this.page=e,await this.reinitializeCDPClient(n??this.pageLoadTimeout)}async createNewTab(e,n){let r=await this.context.newPage();await this.changeActivePage(r,n?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...n}),this.handleAvailableTabsChange()}async switchToPage(e,n){let r=!0,o,a=Date.now();for(;r||n?.retry&&Date.now()-a<this.smartWaitingTimeout;){r=!1;try{await this.switchToPageHelper(e,n);return}catch(i){this.logger.warn({err:i},"Error switching to page, retrying..."),o=i,await J(500)}}throw o}async switchToPageHelper(e,n){let r=this.context.pages().map((a,i)=>({page:a,url:a.url(),index:i})),o;if(e.type==="INDEX"){let a=Number(e.index);if(isNaN(a))throw new A("UserConfigurationError",`Page index ${e.index} is not a number`);if(a<0||a>=r.length)throw new Error(`Page index ${e.index} exceeds the number of available pages: ${JSON.stringify(r.map(i=>i.url))}`);o=r[a]}else{let a=r.filter(i=>e.type==="SUBSTRING"?i.url.includes(e.substring):i.url.match(e.pattern));a.length>1&&this.logger.warn(`More than one page matches the page switch criteria: ${JSON.stringify(a.map(i=>i.url))}`),o=a[a.length-1]}if(!o)throw new Error(`Could not find matching page using criteria: ${JSON.stringify(e)}.
3903
+ Available pages:${JSON.stringify(r.map(a=>a.url))}`);if(!no(o.url,this.logger)){this.logger.error(`Refusing to switch to page with invalid URL: ${o.url}`);return}this.logger.info(`Switching to tab ${o.index} with url ${o.url}`),await this.changeActivePage(o.page,n?.loadTimeoutMs),await this.loadFrameAndRecordUrl({root:o.page,signal:this.abortSignal,codePath:"switch-to-tab-step"}),this.handleAvailableTabsChange()}async setCookie(e){let n;return typeof e=="string"?n=ds(e):n=[e],await this.context.addCookies(n),n}async setLocalStorage(e,n){let r;for(let o=0;o<2;o++)try{await this.evaluateFunctionInPage(([a,i])=>{a&&localStorage.setItem(a,i||"")},[e,n],`setting local storage key ${e}`);return}catch(a){r=a}if(r)throw r}async solveCaptcha(){await this.getBrowserState({allowZeroOpacityOverride:!0});let e;for(let s of Object.values(this.stateManager.a11yIdToNodeMap))if(s.role==="image"&&s.name.toLowerCase().includes("captcha")){if(!s.backendNodeId)continue;e=await this.stateManager.getLocatorFromBackendId(this.page,s.backendNodeId);break}if(!e){let s=await(await this.getActivePageOrFrame()).solveRecaptchas();if(!s.captchas||!s.captchas.length)throw new Error("No captchas found on the page");return}let n=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:3e3}),r=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:Pl,task:{type:"ImageToTextTask",body:n.toString("base64"),case:!0},languagePool:"en"})});if(!r.ok){let s=`Captcha solver API returned error response: ${r.statusText}`;throw this.logger.error({text:await r.text()},s),new Error(s)}let{taskId:o}=await r.json(),a=Date.now(),i="";for(;Date.now()-a<6e4;){await J(2500);let s=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:Pl,taskId:o})});if(!s.ok){let c=`Captcha solution API returned error response: ${s.statusText}`;throw this.logger.error({text:await s.text()},c),new Error(c)}let l=await s.json();if(l.errorId){let c=`Captcha solution API returned error ID ${l.errorId}`;throw this.logger.error(c),new Error(c)}if(l.status==="ready"){i=l.solution.text;break}}if(!i)throw new Error("Captcha solution timed out");return i}getActiveFrameConfig(){return this.stateManager.frameConfig}async exposeRecordingBindings(){await this.context.exposeBinding("isRecordingActive",()=>this.transformer!==void 0,{handle:!1}),await this.context.exposeBinding("captureTargetedEvent",({frame:e},n)=>{this.transformer&&zy({event:n,frame:e,transformer:this.transformer,enricher:this.enricher,lastScreenshotForRecording:this.lastScreenshotForRecording?.toString("base64"),logger:this.logger})},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async(e,n)=>{this.transformer&&this.transformer.recordKeystroke(n)})}async startRecordingCrons(e){if(e.aborted)return;let n,r=(await this.getOpenPages()).map(s=>s.url),o=0,a=!1,i=async()=>{if(e.aborted||o>8){clearTimeout(n);return}a=!0;let s;try{s=(await this.getOpenPages()).map(c=>c.url),o=0}catch(c){this.logger.debug({err:c},"Failed getting new open pages during recording tab switch cron, skipping..."),o++;return}let l=this.url();for(let c=s.length-1;c>=r.length;c--){let d=s[c];no(d,this.logger)&&d!==l&&this.logger.info({lastActivePages:r,currentUrl:l,newOpenPages:s},"Auto-following new tab during recording"),await this.switchToPage({type:"INDEX",index:String(c)});break}r=s};n=setInterval(async()=>{if(!a){a=!0;try{await i()}catch(s){this.logger.error({err:s},"Error while checking pages during recording")}finally{a=!1}}},500),e.addEventListener("abort",async()=>{clearInterval(n)})}async startRecording(e,n,r){this.logger.debug({isClickToRecord:r},"Starting recording mode in Chrome browser"),await this.startRecordingCrons(e),await this.page.evaluate(o=>{let a=window;a._MOMENTIC_RECORDING_ACTIVE=!0,a._MOMENTIC_CLICK_RECORD_ACTIVE=o},r),this.transformer=n,await this.injectKnowledgeBaseIntoBrowser(this.page),e.addEventListener("abort",async()=>{this.transformer=void 0,this.lastScreenshotForRecording=void 0;try{await this.page.evaluate(()=>{let o=window;o._MOMENTIC_RECORDING_ACTIVE=!1,o._MOMENTIC_CLICK_RECORD_ACTIVE=!1})}catch{}})}async getSelectOptions(e){return await e.evaluate(r=>Array.from(r.querySelectorAll("option")).map(a=>({value:a.value,label:a.label})),void 0,{timeout:1e3})}getActivePage(){return this.page}async getActivePageOrFrame(){let e=await this.stateManager.resolveActiveFrameConfig({});return e?(await this.loadFrameAndRecordUrl({root:e.frame,signal:this.abortSignal,codePath:"get-active-frame-locator"}),e.frame):this.page}async loadFrameAndRecordUrl({root:e,signal:n,codePath:r}){let o=this.pageLoadTimeout,a=e.url();if(!a.includes("chrome-error://")){try{await to({promiseGenerator:async()=>e.waitForLoadState("domcontentloaded",{timeout:o}),signal:n,codePath:`loadFrameAndRecordUrlDomContentLoad-${r}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(i){let s=i;if(s.name==="AbortError")throw new A("UserInfrastructureError",`The page with URL ${$e(a,50)} did not load within the configured timeout (${o}ms): ${s}`);if(!s.message.includes("detached"))throw s}try{await to({promiseGenerator:async()=>e.waitForLoadState("load",{timeout:o}),signal:n,codePath:`loadFrameAndRecordUrlPageLoad-${r}`,logger:this.logger,timeoutMs:this.pageLoadTimeout})}catch(i){this.logger.warn({err:i,codePath:r,url:a},"Failed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}}async getCondensedHtml(e){let{skipWait:n=!1}=e??{};return n||(await this.waitForPageLoad(),await this.waitForDOMStability()),this.getCondensedHtmlHelper()}async getCondensedHtmlHelper(){let e=await this.getRawCondensedHtml();return dM.html(e,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1})}async getRawCondensedHtml(){let e=await this.getActivePageOrFrame();await this.ensureMomenticBrowserScriptsLoaded(e,this.logger,this.abortSignal);let{result:n,error:r}=await Qe({fn:()=>window.getCondensedHtmlTree(),root:e,arg:void 0,timeout:2e3,waitForPageLoad:()=>this.waitForPageLoad(),codePath:"getting condensed HTML tree"});if(r)throw new Error(`Failed to process page HTML: ${r}`);if(!n)throw new A("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return n}registerDialogHandler(e){let n=async r=>{try{e==="ACCEPT"?await r.accept():await r.dismiss()}catch(o){this.logger.warn({err:o},"Failed to handle dialog")}};this.page.once("dialog",n)}async evaluateFunctionInAllFrames(e,n){return this.stateManager.executeFunctionInAllFrames(e,n)}async evaluateFunctionInPage(e,n,r,o=2e3){let a=await this.getActivePageOrFrame();return Qe({root:a,fn:e,arg:n,timeout:o,waitForPageLoad:()=>this.waitForPageLoad(),codePath:r})}async evaluateCodeInPage({code:e,fragment:n,context:r,timeoutMs:o=cr}){let a=ny(),i={code:e,fragment:n,context:r},{result:s}=await H(this.page.evaluate(a,i),{milliseconds:o,fallback:()=>{throw this.abortSignal?.throwIfAborted(),new A("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)},signal:this.abortSignal});return s}async getDomNodeFromPixelPosition(e,n){await this.cdpClient.send({method:"DOM.getDocument",params:{depth:0},timeout:2e3});let r;try{r=await this.cdpClient.send({method:"DOM.getNodeForLocation",params:{x:e,y:n},timeout:1e3})}catch(o){throw this.logger.error({err:o,x:e,y:n},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return r}async getDomNodeFromPositionPercentages(e,{percentX:n,percentY:r}){if(n<0||n>1||r<0||r>1)throw new A("UserConfigurationError","Invalid percent passed to percentage location");let{width:o,height:a,upperBound:i,leftBound:s}=await this.getViewportOffsetDetails(e),l=Math.round(i),c=Math.round(s),d=Math.ceil(o*n),u=Math.ceil(a*r),m=d+c,p=u+l;return this.getDomNodeFromPixelPosition(m,p)}async highlightFromPositionPercentages(e){let n=await this.getActivePageOrFrame(),r;try{r=await this.getDomNodeFromPositionPercentages(n,e)}catch{}return r?(await this.cdpClient.send({method:"Overlay.highlightNode",timeout:1e3,params:{highlightConfig:gy,backendNodeId:r.backendNodeId}}),async()=>{try{await this.cdpClient.send({timeout:1e3,method:"Overlay.hideHighlight",params:{backendNodeId:r?.backendNodeId}})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send({method:"Overlay.hideHighlight",params:void 0,timeout:1e3})}catch{}}async getTargetFromPositionPercentages(e){let n=await this.getActivePageOrFrame(),r=await this.getDomNodeFromPositionPercentages(n,e);return this.getTargetFromBackendNodeId({root:n,backendNodeId:r.backendNodeId,allowZeroOpacityOverride:e.allowZeroOpacityOverride})}async getTargetFromBackendNodeId({root:e,backendNodeId:n,allowZeroOpacityOverride:r}){let o=this.stateManager.domGraph?.backendIdToNode[n];if(!o)throw new Error("No DOM node was found with the given backend ID");let a=o?.attributes[Kn],i=parseInt(a??"");if(!a||isNaN(i))throw new Error("No data-momentic-id was found on the DOM node");let s=e.locator(pn(i)),l;o.bounds.x!==null&&o.bounds.y!==null&&(l={x:o.bounds.x,y:o.bounds.y,width:o.bounds.width??0,height:o.bounds.height??0});let c=await this.fetchHtmlAttributes({locator:s,logger:this.logger,startingBoundingBox:l,allowZeroOpacityOverride:r}),d={id:-1,dataMomenticId:i,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...c};return this.logger.debug({target:d},"Tied backend ID to HTML node"),{target:d,locator:s}}async performTargetRedirection(e,n,r){try{return await this.scrollIntoViewIfNeeded(e),await H(this.performTargetRedirectionHelper(e,n,r),{milliseconds:3e3})??{locator:e}}catch(o){return n.warn({err:o},"Error performing target redirection, using original element"),{locator:e}}}async performTargetRedirectionHelper(e,n,r){let o=Date.now(),a=await Yn(e,n);if(r===void 0&&(r=await e.boundingBox({timeout:3e3})??void 0),!r){n.error(`Attempted to click on element with no bounding box: ${a}`);return}let{x:i,y:s,width:l,height:c}=r,d=this.getViewport();if(i<0||s<0||!d||i+l>d.width||s+c>d.height){n.info("Skipping locator redirection because the element is outside the viewport");return}let u=await this.getActivePageOrFrame(),{dataMomenticId:m,mPathSelector:p,error:g,serializedElement:h,point:f,force:y,logs:b}=await e.evaluate(C=>{let v=window;if(!v.performTargetRedirection)throw new Error("performTargetRedirection script is not defined");return v.performTargetRedirection(C)},void 0,{timeout:1e3}),w=Date.now()-o;if(g){n.warn({error:g,serializedElement:h,duration:w,force:y,logs:b},"Got error from target redirection with bounding box");return}else{if(m)return n.info({newDataMomenticId:m,serializedElement:h,duration:w,force:y,logs:b},"Redirected target to new element with bounding box with data-momentic-id"),{locator:u.locator(pn(m)),hints:{clickableXY:f,force:y}};if(p)return n.info({newMPathSelector:p,serializedElement:h,duration:w,force:y,logs:b},"Redirected target to new element with bounding box with mPath"),{locator:u.locator(p),hints:{clickableXY:f,force:y}};if(f)return n.info({point:f,serializedElement:h,duration:w,force:y,logs:b},"Chose specific visible point on original element"),{locator:e,hints:{clickableXY:f,force:y}};if(y)return n.info({serializedElement:h,duration:w,force:y,logs:b},"Forcing click on original element"),{locator:e,hints:{force:y}}}}async fetchHtmlAttributes({locator:e,logger:n=this.logger,startingBoundingBox:r,allowZeroOpacityOverride:o}){let{hybridSelectorMode:a,showZeroOpacityElements:i}=this.userControlledBrowserSettings,s=await e.evaluate((l,c)=>{let d=window;return d.generateHtmlCacheAttributes?d.generateHtmlCacheAttributes(l,c):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},{generateHybridSelector:a==="test"||a==="prefer",startingBoundingBox:r,showZeroOpacityElements:o?!0:i},{timeout:2e3});if("error"in s&&s.error)throw s.error.startsWith(zS)?new ys(s.error):s.error.startsWith(HS)?new bs(s.error):new Error(s.error);return s.warnings.length&&n.warn(s,"Got warnings while generating HTML attributes for target"),s.attributes}async moveMouseFromPositionPercentages(e,n){let r=this.getViewport();if(!r)throw new Error("Cannot move mouse using percentages without viewport");let o=Math.ceil(r.width*e),a=Math.ceil(r.height*n);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseMoved",x:o,y:a,button:"left",clickCount:0}}),{x:o,y:a}}async clickMouseFromPositionPercentages(e,n,r){let o=this.getViewport();if(!o)throw new Error("Cannot click mouse using percentages without viewport");let a=Math.ceil(o.width*n),i=Math.ceil(o.height*r);await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:e==="down"?"mousePressed":"mouseReleased",x:a,y:i,button:"left",clickCount:e==="down"?1:0},timeout:1e3})}async scrollFromPositionPercentages(e,n,r,o){let a=this.getViewport();if(!a)throw new Error("Cannot scroll using percentages without viewport");let i=Math.ceil(a.width*e),s=Math.ceil(a.height*n);return await this.cdpClient.send({method:"Input.dispatchMouseEvent",params:{type:"mouseWheel",deltaX:i,deltaY:s,x:r,y:o}}),{deltaX:i,deltaY:s}}canSolveCaptchas(){return!!Pl}async getAllFrameUrls(){return await this.stateManager.getAllChildFrameUrls()}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(n){this.logger.debug({err:n,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}logToUserConsole(e,n,r,...o){let a=this.context.pages().indexOf(e);a=a===-1?0:a,hu(e,this.debugData,a,{type:n,text:`[MOMENTIC] ${r}`,args:o})}async setFileChooserHandlerHelper({filePath:e,filename:n}){if(!Il(e)){let l=`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`;this.logger.error(l),this.logToUserConsole(this.page,"error",l);return}let r=n?.trim()||gM(e),o=lM(e),a=hM(e),i=id[a];this.page.once("filechooser",async l=>{this.logger.info({filePath:e,fileName:r},"File chooser triggered");try{if(!Il(e))throw new Error(`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`);await l.setFiles({name:r,buffer:o,mimeType:uM.getType(e)||"application/octet-stream"},{timeout:8e3})}catch(c){this.logger.error({err:c},"Error handling file chooser"),this.logToUserConsole(this.page,"error",c.message)}});let s=o.toString("base64");await this.evaluateFunctionInPage(({fileName:l,base64Data:c,mimeType:d})=>{let u=window;u.momenticFileName=l,u.momenticFileBase64=c;let m=atob(c),p=new Array(m.length);for(let h=0;h<m.length;h++)p[h]=m.charCodeAt(h);let g=new Uint8Array(p);u.MomenticFile=class extends Blob{kind="file";name=u.momenticFileName;constructor(){super([g],{type:d})}isSameEntry(h){return h.name===this.name}queryPermission(h){return console.info("[MOMENTIC] MomenticFile.queryPermission called"),Promise.resolve("granted")}remove(){return console.info("[MOMENTIC] MomenticFile.remove called"),Promise.resolve()}async requestPermission(h){return console.info("[MOMENTIC] MomenticFile.requestPermission called"),Promise.resolve("granted")}async getFile(){console.info("[MOMENTIC] MomenticFile.getFile called");let h=new Blob([g]);return new File([h],u.momenticFileName,{type:d})}async createSyncAccessHandle(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}async createWritable(){throw console.error("[MOMENTIC] Not implemented"),new Error("Not implemented")}},u.showOpenFilePicker=async()=>(console.info("[MOMENTIC] showOpenFilePicker called"),[new u.MomenticFile])},{fileName:r,base64Data:s,mimeType:i},"set-file-chooser-handler",5e3)}getSerializedFormFromA11yId(e){return this.stateManager.a11yIdToNodeMap[e]?.getNodeOnlySerializedForm()}retrieveAndClearDebugData(){this.cdpClient.loadEventLogs.length>0&&(this.cdpClient.loadEventLogs=[]);let n={...this.debugData};return this.debugData={logsPerPage:[],harPages:{},harEntries:{}},n}async copy(e){try{await this.evaluateFunctionInPage(n=>navigator.clipboard.writeText(n),e,"copying text to clipboard")}catch(n){if(n instanceof Error&&n.message.includes("Document is not focused")){await this.evaluateFunctionInPage(()=>{document.activeElement||document.body.focus()},void 0,"focusing on body element before copying to clipboard"),await this.press("Tab",{}),await this.press("Shift+Tab",{}),await this.evaluateFunctionInPage(r=>navigator.clipboard.writeText(r),e,"copying text to clipboard");return}throw n}}async paste(){await this.waitForPageLoad(),await this.press("Meta+V",{convertMeta:!0})}async registerRequestListener(e){return this.page.waitForResponse(n=>{let r=n.request();return e.matches({url:r.url(),method:r.method()})})}registerRequestRecorder(e,n,r){this.requestRecorders[e]={onRequestStart:(o,a)=>{n.matches({url:a.request.url,method:a.request.method})&&r.onRequestStart(o,a)},onRequestComplete:(o,a)=>{n.matches({url:a.request.url,method:a.request.method})&&r.onRequestComplete(o,a)}}}removeRequestRecorder(e){delete this.requestRecorders[e]}setHeader(e,n,r){this.customHeaders.push({key:e.toLowerCase(),value:n,matcher:r})}registerMock(e,n,r,o){let a=e??Lu();return this.mocks[a]={matcher:n,generateResponse:r,fetchOriginalResponse:o},a}removeMock(e){if(!e){this.mocks={};return}delete this.mocks[e]}async setOfflineMode(e){await this.context.setOffline(e)}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??5e3}get userBrowserSettings(){return yi(this.userControlledBrowserSettings)}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}get isInPageLoad(){return Object.values(this.pageLoadPromises).length>0}get devicePixelRatio(){return this.properties.systemDevicePixelRatio??1}};import FM from"fetch-cookie";import{cloneDeep as ib}from"lodash-es";import{CookieJar as UM}from"tough-cookie";async function Er(t,e={}){let n=await t.getBrowserState(e);return{serializedTree:n.serialize(),tree:n}}var ma=3.1783027;function EM(t){let e=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);!(r>=48&&r<=57)&&!(r>=65&&r<=90)&&!(r>=97&&r<=122)&&e++}return e}function bi(t){return Math.ceil(_u(t)/ma)}function _u(t){let e=0;if(typeof t=="string"){let n=t;n=n.replaceAll(`
3904
+ `,""),n=n.replaceAll(" ","");let r=EM(n);return n.length-r+ma*r}if(typeof t>"u")return 0;if(typeof t=="number")return String(t).length;if(Array.isArray(t))return t.forEach(n=>{e+=_u(n)}),e;if(typeof t=="object"){let n=t;return Object.keys(n).forEach(r=>{e+=String(r).length,r==="image_url"?(n[r]??{}).detail==="high"?e+=1105*ma:e+=85*ma:e+=_u(n[r])}),e}if(typeof t=="boolean")return t?4:5;throw new Error(`Unsupported type passed to token length calculator '${typeof t}': ${t}`)}var Yy={minChunkTokenCount:500,acceptableChunkTokenCount:3e3,maxChunkTokenCount:8e3,maxLineLength:4e3},Xy={minChunkTokenCount:5e3,acceptableChunkTokenCount:1e4,maxChunkTokenCount:15e3,maxLineLength:500},Ky=/<(\S+) id="(\d+)".*?>/g,RM=/(<\/(\S+)>)|(<(\S+).*?\/>)/g,Jy=["h1","h2","section","footer","nav","aside","form","label","dialog"],CM=[...Jy,"span","div","h3"],vM=["table","select","form","ul","ol","menu","pre","code","dialog"],AM=["table","form","dialog","nav","section","ul","select"];function Du(t){return t.serializedTree.length>t.maxCharacterLength&&(t.logger.warn({serializedTreeLength:t.serializedTree.length},"Serialized condensed tree is too long to chunk, truncating before chunking"),t.serializedTree=t.serializedTree.slice(0,t.maxCharacterLength)),xM(t)}function xM({serializedTree:t,options:e,logger:n}){let{minChunkTokenCount:r,acceptableChunkTokenCount:o,maxChunkTokenCount:a,maxLineLength:i}=e,s=[],l=t.split(`
3905
+ `),c=0,d=[],u=0,m=[],p=[],g=!1;for(;c<l.length;){g&&(s.push({ids:m,content:d.join(`
3906
+ `),tokenLength:u}),d=[],u=0,m=p.length?[p[p.length-1].id]:[],g=!1);let h=l[c],f=bi(h);u+=f,h.length>i&&(h=h.slice(0,i));let w=Array.from(h.matchAll(Ky)).map(k=>k&&k.length>=3?{tagName:k[1],id:k[2]}:void 0).filter(k=>!!k),v=Array.from(h.matchAll(RM)).map(k=>k&&(k[2]||k[4])).filter(k=>!!k);v.reverse();let R=h.replace(/ id="[0-9]+"/g,"");d.push(R);for(let k of w)m.push(k.id),p.push(k);for(let k of v){let G=p[p.length-1];G&&G.tagName===k&&p.pop()}let x=p.some(k=>vM.includes(k.tagName)),M=l[c+1]??"",D=bi(M),K=Array.from(M.matchAll(Ky)).map(k=>k&&k.length>2?k[1]:void 0).filter(k=>!!k),P=K.some(k=>Jy.includes(k)),W=K.some(k=>CM.includes(k));u+D>=a&&(g=!0),u>=r&&(P&&!x||v.some(k=>AM.includes(k)))&&(g=!0),u>=o&&W&&!x&&(g=!0),c++}return d.length&&s.push({ids:m,content:d.join(`
3907
+ `),tokenLength:u}),s.forEach((h,f)=>{n.debug({chunk:h},`Chunk for page filtering (index ${f+1}/${s.length})`)}),{chunks:s}}var Fu=4e4,Uu=8e4;async function po(t){let{serializedTree:e,logger:n,aiPageFiltering:r,softTokenLimit:o=Fu}=t;if(bi(e)<o)return e;let i;r?i=Du({serializedTree:e,options:Xy,logger:n,maxCharacterLength:1e6}):i=Du({serializedTree:e,options:Yy,logger:n,maxCharacterLength:3e6});try{return r?await H(IM({...t,chunks:i.chunks}),{milliseconds:2e4}):await H(MM({...t,chunkResult:i}),{milliseconds:15e3})}catch(s){n.warn({err:s},"Error executing page filtering, attempting AI keyword fallback");try{return await PM({...t,chunks:i.chunks})}catch(l){return n.warn({err:l},"Error executing page filtering using keyword matching, using naive truncation"),e.slice(0,Uu*ma)}}}async function IM({chunks:t,generator:e,description:n,type:r,logger:o,signal:a,tree:i,softTokenLimit:s=Fu,hardTokenLimit:l=Uu}){let c=await e.rankChunksWithAi({chunks:t,description:n,type:r,softTokenLimit:s,hardTokenLimit:l},{abortSignal:a,logger:o,loggerTags:Oe(o)}),d=[];t.forEach((m,p)=>{c.indices.includes(p)&&(d=d.concat(m.ids))});let u=i.pruneUsingRelevantIds(new Set(d)).serialize();return o.debug({description:n,type:r,selectedChunks:c,tree:u},"Pruned a11y tree with AI page filtering"),u}async function PM(t){let{type:e,description:n,generator:r,tree:o,logger:a,hardTokenLimit:i=Uu}=t;if(!n.trim())throw new Error("Empty description passed to page filtering");let s=await r.getExtractedKeywords({goal:n},{logger:t.logger,loggerTags:Oe(t.logger)});for(let l of s.keywords){let c=t.chunks.filter(p=>p.content.toLowerCase().includes(l.toLowerCase()));if(!c.length||c.reduce((p,g)=>p+g.tokenLength,0)>i&&c.length>1)continue;let u=c.flatMap(p=>p.ids),m=o.pruneUsingRelevantIds(new Set(u)).serialize();return a.debug({description:n,type:e,selectedChunks:c,tree:m},"Pruned a11y tree with keyword page filtering"),m}throw new Error("No keywords were unique enough for page filtering")}async function MM(t){let{description:e,generator:n,tree:r,logger:o,signal:a,chunkResult:i,softTokenLimit:s=Fu}=t,l=await n.rankChunksWithRag({description:e,chunks:i.chunks,tokenLimit:s},{abortSignal:a,logger:o,loggerTags:Oe(o)});if(l.ids.length===0)throw new Error("RAG returned no important ids");{let c=r.pruneUsingRelevantIds(new Set(l.ids.map(d=>`${d}`))).serialize();return o.debug({browserState:c},"Pruned a11y tree with RAG"),c}}async function zu(t,e){if(!t.description)throw new A("UserConfigurationError","Cannot locate element with empty description");return Mn({action:async()=>LM(t,e),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:e.browser,logger:t.logger})}async function LM(t,e){let{disableCache:n,testContext:r,filterByViewport:o,skipWait:a,source:i,memory:s,aiPageFiltering:l,logger:c,allowZeroOpacityOverride:d}=t,{ctx:u,orgId:m,browser:p,localCodeEvalTools:g,generator:h,abortSignal:f}=e,y=t.description,b=t.useMemory&&!n;r&&(y=await jt({orgId:m,s:y,context:r,localTools:g,signal:f,logger:c})),i&&(y=NM(y,i));let{serializedTree:w,tree:C}=await Er(p,{allowZeroOpacityOverride:d,filterByViewport:o,abortSignal:f,skipWait:a,logger:c}),v,R=Date.now(),x;for(;!v&&Date.now()-R<3e3;){f.throwIfAborted();try{v=await p.screenshot({clearHighlights:!0,respectActiveFrame:!0,retries:2})}catch(Ce){x=Ce}}if(!v)throw new A("ActionFailureError",`Failed to take screenshot of page to locate element. The page may be unresponsive, or your machine might be severely resource constrained. Error: ${x?.message}`);let M=w,D=!1;M=await po({type:"locator",description:y,serializedTree:w,aiPageFiltering:l,tree:C,logger:c,generator:h}),M!==w&&(D=!0);let K=`data:image/jpeg;base64,${v.toString("base64")}`,P=await h.getElementLocation({browserState:M,goal:y,screenshot:K,source:i,memory:b?s:void 0},{disableCache:n,abortSignal:f,loggerTags:Oe(c),useMemory:b});c.debug({usedRag:D,result:P},"Got locator result");let W=P.id>0;if(u?.details?.push({type:"AI_LOCATION",matched:W,pageState:M,ragUsed:D,thoughts:P.thoughts}),!W)throw new Go(`Could not find any relevant element: ${P.thoughts}`,P.updatedMemory?{type:"GCS_TRACES",traces:P.updatedMemory}:void 0);let{resolution:k,target:G,frameConfig:we}=await p.createTargetFromA11yId({id:P.id,description:y,targetSource:"AI",logger:c});if(k.a11yNode?.properties?.hidden&&k.a11yNode?.properties?.hidden!=="false")throw new A("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${k.displayString}`);return b&&(P.updatedMemory?G.memory={type:"GCS_TRACES",traces:P.updatedMemory}:s&&(G.memory=s)),{thoughts:P.thoughts,target:G,resolution:k,frameConfig:we,screenshot:K}}var OM=["Element exactly matching the description below. Interpret the description narrowly and do not assume there are any typos or errors. Err on the side of returning -1 unless there is a perfect match. Description:","Element closely matching the description below. Interpret the description narrowly and do not return elements that are merely loosely related. Description:","Element matching the description below. This element is being located as part of a negative check step (i.e. we are trying to verify the element does not exist). Therefore, interpret the description narrowly, do not assume there are typos, and err on the side of returning -1 unless there is a perfect match. Description:"],Qy="<select> element:",Zy="text input or contenteditable element:",eb="Element matching the description below. It is possible the element is hidden or doesn't exist. Interpret the description narrowly and do not assume there are typos. Return -1 unless there is an straightforward match. Description:",tb="Element matching the description below. This element is being located as part of a check step (i.e. we are trying to verify certain properties about the element). Interpret the description narrowly and do not return elements that are merely loosely related. Description:",Bu=[Qy,Zy,eb,tb,...OM];function nb(t,e){if(t===e)return!0;for(let n of Bu){if(!t.startsWith(n))continue;let r=t.slice(n.length).trim();if(Bu.some(o=>e.startsWith(o)&&e.slice(o.length).trim()===r)||r===e.trim())return!0}return!!Bu.some(n=>e.startsWith(n)&&e.slice(n.length).trim()===t.trim())}function NM(t,e){if(!t||!e)return t;switch(e){case"SELECT_OPTION":return`${Qy} ${t}`;case"TYPE":return`${Zy} ${t}`;case"NEGATED_ELEMENT_VISIBLE_CHECK":return`${eb}
3908
+ ${t}`;case"ELEMENT_CHECK":return`${tb}
3909
+ ${t}`;default:return t}}var kM=15;async function Ml({command:t,aiPageFiltering:e,logger:n,fixtures:r,source:o,useMemory:a,maxRetries:i=kM}){if(!t.assertion.trim())throw new A("ActionFailureError","Assertion command is missing the assertion content");let{browser:s}=r,l=t.timeout?t.timeout*1e3:s.smartWaitingTimeout,c=Af(l),d=0,u=Date.now(),m,p,g;try{await Mn({action:()=>s.clearHighlights(),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,browser:s,logger:n})}catch(f){n.warn({err:f},"Failed to clear highlights before AI check, continuing...")}let h;for(;d<i&&(!h||h-u<l);){r.abortSignal.throwIfAborted(),d!==0&&await J(c,r.abortSignal),h=Date.now();try{if(m=await Mn({action:async()=>{let y=await rb(s,n,r.abortSignal);return p&&p.serializedTree===y.serializedTree&&p.screenshotBuff.equals(y.screenshotBuff)?m:(p=y,ob({command:t,state:y,fixtures:r,useMemory:a,useConsensus:!1,highlightElementsOnFailure:!1,attemptNumber:d,aiPageFiltering:e,logger:n,source:o}))},frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,logger:n,browser:s}),m?.updatedMemory&&(Bs(t,m.updatedMemory),n.info({updatedMemory:m.updatedMemory,command:t},"Wrote new memory to assertion command")),m?.success)break;throw m?.thoughts?new A("AssertionFailureError",m.thoughts):new A("InternalPlatformError","No thoughts were provided for AI assertion failure")}catch(f){r.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`),n.info({err:f},`AI check assert attempt ${d} failed, retrying...`)}finally{d++}}if(!m?.success)try{m=await Mn({action:async()=>ob({command:t,state:await rb(s,n,r.abortSignal),fixtures:r,useMemory:a,useConsensus:!0,highlightElementsOnFailure:!0,attemptNumber:d,aiPageFiltering:e,logger:n}),frameConfig:t.iframeUrl?{type:"url",url:t.iframeUrl}:void 0,logger:n,browser:s})}catch(f){r.abortSignal.throwIfAborted(),g=f instanceof Error?f:new Error(`${f}`)}finally{d++}if(!m?.success){let f=`AI check still failing after ${d} attempts.`;throw g&&(f+=` Latest result: ${g.message}`),new A("AssertionFailureError",f)}return{...m,succeedImmediately:!1,urlAfterCommand:s.url()}}async function rb(t,e,n){let[r,o]=await Promise.all([Er(t,{abortSignal:n,skipWait:!0,skipWaitForPageLoad:!0,logger:e}),t.screenshot({retries:1,respectActiveFrame:!0})]);return{...r,screenshotBuff:o}}async function ob({command:t,state:e,fixtures:n,useConsensus:r,useMemory:o,highlightElementsOnFailure:a,aiPageFiltering:i,attemptNumber:s,source:l,logger:c}){let{browser:d,generator:u,abortSignal:m}=n,p={type:"ASSERTION"},{serializedTree:g,tree:h}=e,f=e.screenshotBuff,y=d.url(),b=t.contextChoice??"MULTIMODAL",w=g;b!=="VISION_ONLY"&&(w=await po({type:"assertion",serializedTree:g,description:t.assertion,aiPageFiltering:i,tree:h,generator:u,logger:c,signal:m}),w!==g&&(p.ragUsed=!0),p.pageState=w);let C={goal:t.assertion,url:y,memory:o?t.cache?.memory:void 0,browserState:w,screenshot:f.toString("base64"),contextChoice:b,source:l},R=await(b==="VISION_ONLY"?(x,M)=>u.getVisualAssertionResult(x,M):(x,M)=>u.getAssertionResult(x,M))(C,{useConsensus:r,attemptNumber:s,useMemory:o,disableCache:!!t.disableCache,abortSignal:m,logger:c,loggerTags:Oe(c)});return(R.result||a)&&R.relevantElements&&(p.relevantElementsSerialized=R.relevantElements.map(x=>d.getSerializedFormFromA11yId(x)).filter(x=>!!x),await _M(R.relevantElements,d,c)),{success:R.result,thoughts:R.thoughts,afterScreenshotOverride:f,updatedMemory:o?R.updatedMemory:void 0}}async function _M(t,e,n){let r=Date.now();for(let o of t){if(Date.now()-r>2e3){n.debug("Highlighting relevant elements took over 2s, aborting...");return}try{let a=new AbortController;await H(e.highlightA11yId(o),{milliseconds:1e3,fallback:()=>{throw a.abort(),new Error("Timed out waiting for highlighting to complete")}})}catch(a){n.debug({err:a},"Failed to highlight relevant element after assertion, continuing...");return}}}var DM=3e4;async function ab({command:t,logger:e,baseUrl:n,fetchImplementation:r=fetch}){let o=t.timeout??DM/1e3,a=new AbortController,i=Object.fromEntries(Object.entries(t.headers||{}).filter(([u,m])=>u&&m));i["Content-Type"]="application/json";let s;if(Zo(t.url)&&(s=t.url),n&&ea(t.url,n)&&(s=new URL(t.url,n).toString()),!s)throw new A("ActionFailureError",`Invalid URL: ${t.url}`);let c=await H((async()=>{try{return await r(s,{headers:i,method:"POST",body:JSON.stringify({query:t.query,variables:t.variables}),signal:a.signal})}catch(u){e.error({err:u},"Failed to make HTTP request")}})(),{milliseconds:o*1e3});if(!c)throw new A("ActionFailureError",`GraphQL request timed out after ${o} seconds`);if(!c.ok){let u,m=await c.text();try{u=JSON.parse(m)}catch{throw new A("ActionFailureError",`GraphQL request failed with status ${c.status}: ${m}`)}throw u?.errors?.length&&u?.errors[0]?.message?new A("ActionFailureError",`GraphQL request failed with status ${c.status}: ${u.errors[0].message}`):new A("ActionFailureError",`GraphQL request failed with status ${c.status}: ${m}`)}let d={};return c.headers.forEach((u,m)=>{d[m]=u}),{status:c.status,headers:d,json:await c.json()}}var pa=class{flagStore;orgId;options;storage;localCodeEvalTools;uploadedFileStorage;visualDiffScreenshotStorage;browser;generator;executeAbortController=new AbortController;logger;recordAbortController=null;registeredListeners={};recordedRequests={};constructor({browser:e,generator:n,logger:r,flagStore:o,storage:a,orgId:i,localCodeEvalTools:s,uploadedFileStorage:l,visualDiffScreenshotStorage:c,options:d}){this.orgId=i,this.options=d,this.browser=e,this.browser.registerAbortSignal(this.executeAbortController.signal),this.storage=a,this.uploadedFileStorage=l,this.visualDiffScreenshotStorage=c,this.localCodeEvalTools=s,this.generator=n,this.logger=r,this.flagStore=o}setOpen(){this.executeAbortController=new AbortController,this.browser.registerAbortSignal(this.executeAbortController.signal)}setClosed(){this.executeAbortController.abort()}throwIfClosed(){this.executeAbortController.signal.throwIfAborted()}get closed(){return this.executeAbortController.signal.aborted}async evaluateAiAction({goal:e,startingScreenshot:n,history:r,disableCache:o,langfuseSessionId:a,lastError:i,logger:s=this.logger}){let[l,c]=await Promise.all([Er(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:s}),this.browser.screenshot({retries:1,clearHighlights:!0})]),d=await po({type:"ai-action",description:e,serializedTree:l.serializedTree,tree:l.tree,logger:s,generator:this.generator,aiPageFiltering:!!this.options?.aiPageFiltering,softTokenLimit:25e3,hardTokenLimit:5e4}),u=`data:image/jpeg;base64,${c.toString("base64")}`,m={url:this.browser.url(),browserState:d,startingScreenshot:n,history:r,goal:e,screenshot:u,lastError:i};return await this.generator.getMultiturnAiActionEvaluation(m,{disableCache:o,abortSignal:this.executeAbortController.signal,loggerTags:{...Oe(s)},langfuseSessionId:a})}async promptToCommand({goal:e,startingScreenshot:n,history:r,actionHint:o,disableCache:a,logger:i=this.logger,langfuseSessionId:s}){let l=this.browser.url(),[c,d]=await Promise.all([Er(this.browser,{abortSignal:this.executeAbortController.signal,skipWait:!0,skipWaitForPageLoad:!0,logger:i}),this.browser.screenshot({retries:1,clearHighlights:!0})]),u=`data:image/jpeg;base64,${d.toString("base64")}`,m=await po({type:"ai-action",description:e,serializedTree:c.serializedTree,tree:c.tree,logger:i,generator:this.generator,aiPageFiltering:!!this.options?.aiPageFiltering,softTokenLimit:25e3,hardTokenLimit:5e4}),p={url:l,browserState:m,startingScreenshot:n,history:r,goal:e,actionHint:o,screenshot:u};try{return await this.generator.getMultiturnAiActionCommand(p,{disableCache:a,abortSignal:this.executeAbortController.signal,loggerTags:{...Oe(i)},langfuseSessionId:s})}catch(g){throw new A("InternalWebAgentError",`Error generating command: ${g instanceof Error?g.message:g}`,{errOptions:{cause:g}})}}async getBrowserState(e){return Er(this.browser,e)}async locateElement(e){return await zu({...e,aiPageFiltering:!!this.options?.aiPageFiltering},this.getControllerFixtures())}async locateElementWithSelector(e,n){return Mn({action:async()=>{let r=await this.browser.resolveHardcodedCssSelector({ctx:null,selector:e,timeoutMs:2e3,logger:this.logger});return{thoughts:"Located element with selector",target:{id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},resolution:r}},frameConfig:n?{type:"url",url:n}:void 0,browser:this.browser,logger:this.logger})}getControllerFixtures(e){return{ctx:e??null,browser:this.browser,generator:this.generator,logger:this.logger,orgId:this.orgId,flagStore:this.flagStore,storage:this.storage,localCodeEvalTools:this.localCodeEvalTools,abortSignal:this.executeAbortController.signal}}shouldUseMemory(){return this.options?.useMemory??(this.orgId==="org_01HMSCJQBCCG51M2ZF65YC5B8W"||this.orgId==="org_01HMJTX4GT1KG94KZRCT8MZ6YB")}async wrapMultiElementTargetingCommand({ctx:e,tracer:n,command:r,targetNames:o,descriptions:a,caches:i,action:s,options:l,retriesWithAI:c=1}){let d=[];for(let u=0;u<a.length;u++){let m=a[u],p=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:m,cache:i[u],action:async g=>g,options:{...l,targetName:o[u]}});d.push(p)}try{let u=await s(...d.map(g=>g.result)),m=g=>g==="fromTarget"?"From Target":g==="toTarget"?"To Target":"Target",p=d.map((g,h)=>g.thoughts?`${m(o[h])}: ${g.thoughts}`:void 0).filter(g=>!!g).join(" -------------- ")||void 0;return{result:u,elementInteractedDisplayStrings:d.map(g=>g.elementInteractedDisplayString),thoughts:p}}catch(u){if(this.throwIfClosed(),c>0)return this.logger.warn({err:u},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand({ctx:e,tracer:n,command:r,targetNames:o,descriptions:a,caches:a.map(()=>{}),action:s,options:l,retriesWithAI:c-1});throw new A("ActionFailureError",u.message,{errOptions:{cause:u}})}}async wrapElementTargetingCommand(e){let n=this.logger.child({commandId:e.command.id}),r;for(let o=0;o<2;o++)try{return await Mn({action:()=>this.wrapElementTargetingCommandHelper({...e,originalCache:e.originalCache??e.cache}),frameConfig:e.options.iframeUrl?{type:"url",url:e.options.iframeUrl}:void 0,browser:this.browser,logger:n})}catch(a){if(r=a,this.browser.userBrowserSettings.visualActions&&od(a)){n.warn({err:a},"Invalid mpath error, retrying element targeting command");continue}if(!this.browser.userBrowserSettings.visualActions&&Ga(a)){n.warn({err:a},"Invalid momentic id error, retrying element targeting command");continue}if(ad(a)&&n.warn({err:a},"Invalid backend node id error, retrying element targeting command"),a instanceof Rn&&a.retryableWithAI){n.warn({err:a},"Element cache disqualification error, retrying element targeting command");continue}throw a}throw r instanceof A?r:new A("ActionFailureError",r?.message??"An unknown error occurred during element targeting")}async wrapHardcodedCssTargetingCommandHelper({ctx:e,target:n,action:r,options:o,command:a}){let i=this.logger.child({commandId:a.id}),{targetName:s}=o;if(n.type!=="description")throw new A("ActionFailureError","Cannot use selector with non-description target");let l,c=Date.now(),d=Date.now();for(;Date.now()-d<this.browser.smartWaitingTimeout;){c=Date.now();try{let u=await this.browser.resolveHardcodedCssSelector({ctx:e,selector:n.elementDescriptor,targetName:s,logger:i});return{result:await r({locator:u.locator}),elementInteractedDisplayString:u.displayString}}catch(u){if(u.name==="AbortError")throw u;l=u,i.warn({err:u},"Failed to action on hardcoded css selector"),Date.now()-c<500&&await J(500)}}throw l}async wrapElementTargetingCommandHelper(e){let{ctx:n,tracer:r,target:o,originalCache:a,action:i,options:s,command:l}=e,{disableCache:c,useSelector:d,targetName:u,targetHealingInProgress:m,source:p}=s,g=this.logger.child({commandId:l.id}),h=this.shouldUseMemory(),f=s.retriesWithAI??1,y=!1,b=ib(e.cache);if((!b||c)&&!lc(o))throw new A("ActionFailureError","Cannot target element with no cached data or element descriptor");if(d)return this.wrapHardcodedCssTargetingCommandHelper(e);c&&(g.info("Cache explicitly disabled for this step"),y=!0,b=void 0),b&&this.browser.userBrowserSettings.disableSecondaryCacheResolution&&b.targetSource==="HEURISTIC_HEALED"&&(y=!0,b=void 0),b?.inputDescription&&!nb(o.elementDescriptor,b.inputDescription)&&(g.warn({old:b.inputDescription,new:o.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),y=!0,b=void 0);let w=v=>!!v&&Em(v),C=!0;if(!w(b)){C=!1,g.info({description:o.elementDescriptor,targetHealingInProgress:m,cacheBustedBeforeAction:y,memory:s.memory,useMemory:h},"Prompting AI for an updated element location"),y&&await J(this.browser.smartWaitingTimeout,this.executeAbortController.signal),f--;let v;try{v=await zu({description:o.elementDescriptor,disableCache:!!s.disableCache,iframeUrl:s.iframeUrl,source:p,useMemory:h,memory:h?s.memory:void 0,aiPageFiltering:!!this.options?.aiPageFiltering,allowZeroOpacityOverride:s.allowZeroOpacityOverride,logger:g},this.getControllerFixtures(n))}catch(M){if(M instanceof Go&&M.updatedLocatorMemory){let D={id:-1,...a,memory:M.updatedLocatorMemory};Us({cmd:l,key:u,newTarget:D,logger:g})}throw new A("ActionFailureError",M.message)}v.frameConfig&&this.browser.setActiveFrameConfig(v.frameConfig);let R=s.disableGlobalLocatorRedirect?{locator:v.resolution.locator}:await this.attemptLocatorRedirect(v.resolution.locator,g),x=await i(R);return Us({cmd:l,key:u,newTarget:v.target,logger:g}),m&&(r.heal({healType:"AI"}),v.target.targetSource="AI_HEALED",v.target.targetUpdateTime=new Date().toUTCString(),v.target.targetUpdateLoggerTags=Oe(g)),{result:x,elementInteractedDisplayString:v.resolution.displayString,thoughts:v.thoughts}}try{let v=await this.browser.resolveTarget(n,b,{allowZeroOpacityOverride:s.allowZeroOpacityOverride,targetName:u,logger:g,signal:this.executeAbortController.signal});(this.browser.userBrowserSettings.visualActions||this.browser.userBrowserSettings.globalLocatorRedirect)&&await this.browser.scrollIntoViewIfNeeded(v.locator);let R=s.disableGlobalLocatorRedirect?{locator:v.locator}:await this.attemptLocatorRedirect(v.locator,g),x=await i(R);if(Us({cmd:l,key:u,newTarget:b,logger:g}),C){let M=v.decisions.filter(D=>D.matched);if(M.length!==1)g.warn({decisions:v.decisions},"Expected exactly 1 matching method for element location, got more or less");else{let D=M[0].type;r.heal({healType:D})}}return{result:x,elementInteractedDisplayString:v.displayString}}catch(v){this.throwIfClosed();let R=!1;if((v instanceof Rn||od(v)||Ga(v)||ad(v)||tg(v)||ng(v))&&(R=!0),v instanceof A&&!R)throw g.error({err:v},"Failed to execute action with cached target (fatal)"),v;if(f>0&&o){g.info({err:v},"Failed to execute action with cached target, retrying with AI");let x;return b.memory&&ki(b.memory)&&(x=b.memory),this.wrapElementTargetingCommand({ctx:n,tracer:r,command:l,target:o,cache:void 0,originalCache:a,action:i,options:{...s,memory:x,retriesWithAI:f,targetHealingInProgress:!0}})}throw new A("ActionFailureError",v.message,{errOptions:{cause:v}})}}async attemptLocatorRedirect(e,n){return this.browser.userBrowserSettings.globalLocatorRedirect?this.browser.performTargetRedirection(e,n):{locator:e}}async screenshotWithDimensions(e){return hi(this.browser,e)}async executePresetCommand(e,n,r,o,a){this.options?.slowMoMs&&await J(this.options.slowMoMs);let i=await this.browser.getOpenPages(),s=this.browser.url(),l;try{l=await this.resolveCommandTemplateStrings(r,o)}catch(c){throw this.throwIfClosed(),new A("ActionFailureError",`Failed to substitute template strings in command: ${c.message}`,{errOptions:{cause:c}})}try{let c=await this.executePresetCommandHelper(e,n,r,o,a);return this.browser.userBrowserSettings.visualActions&&Mm(r)?await this.browser.waitForDOMStability({timeout:2e3}):!this.browser.userBrowserSettings.visualActions&&["PRESS","TYPE"].includes(r.type)&&await this.browser.waitForDOMStability({timeout:1e3}),this.options?.autoFollowNewTabs&&await CS({beforeUrl:s,command:r,beforePages:i.map(d=>d.url),browser:this.browser,logger:this.logger}),c}catch(c){throw c.name!=="AbortError"&&this.logger.error({err:c},"Error thrown in action controller"),c}finally{pS(r,l)}}createCallbacksForBrowser(e){return{createIsolatedFolder:()=>pu(e)}}async resolveCommandTemplateStrings(e,n){return ll({obj:e,context:n,bannedKeys:["type","a11yData","thoughts","cache","code"],orgId:this.orgId,logger:this.logger,signal:this.executeAbortController.signal,localTools:this.localCodeEvalTools})}async executePresetCommandHelper(e,n,r,o,a){a=a||"disableCache"in r&&!!r.disableCache;let i=this.logger.child({commandId:r.id});switch(r.type){case"SUCCESS":let s=r.condition;return s?.assertion.trim()?Ml({command:s,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:i}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!r.assertion.trim())throw new A("ActionFailureError","Missing assertion");if(r.timeout&&r.timeout>1800)throw new A("AssertionFailureError",`AI check timeout of ${r.timeout} exceeds the maximum allowed value of 30 minutes.`);return Ml({command:r,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),aiPageFiltering:!!this.options?.aiPageFiltering,logger:i})}case"AI_EXTRACT":{if(!r.goal.trim())throw new A("ActionFailureError","Cannot perform AI extraction without goal");if(r.schema){let f=uh(r.schema);if(f)throw new A("UserConfigurationError",f)}let g=await this.browser.getCondensedHtml(),h=await this.browser.screenshot({retries:2});try{let f=await this.generator.getTextExtraction({goal:r.goal,browserState:g,returnSchema:r.schema,screenshot:`data:image/jpeg;base64,${h.toString("base64")}`},{disableCache:a,abortSignal:this.executeAbortController.signal,loggerTags:Oe(i)});if(f.result==="NOT_FOUND")throw new A("ActionFailureError","No relevant data found for extraction goal on this page");if(f.thoughts?.includes("MaxGenerationLengthExceededError"))throw new A("UserConfigurationError",f.thoughts);return{thoughts:f.thoughts||void 0,data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}catch(f){let y=f.message;throw y.includes("MaxGenerationLengthExceededError")?new A("UserConfigurationError","You tried to extract too much data. Please rephrase your query to limit the results returned or use a JavaScript step in the browser instead."):y.includes("AIProviderError")&&y.includes("time")?new A("AIProviderError","The AI provider responded with an error. This may be because you tried to extract too much data. Please limit extraction results to 2000 characters.",{errOptions:{cause:f}}):f}}case"NAVIGATE":if(!Zo(r.url)&&!ea(r.url,this.browser.baseUrl))throw new A("ActionFailureError",`Invalid URL provided to navigate command: ${r.url}`);await this.browser.navigate({url:r.url,loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(r.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let l=await this.browser.solveCaptcha();l&&(await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:g=>this.browser.click(g,this.createCallbacksForBrowser(this.orgId),{}),options:{...r,targetName:"target",disableCache:a}}),await this.browser.type(l,{clearContent:!0,pressEnter:!0},!0));break;case"GO_BACK":await this.browser.goBack();break;case"GO_FORWARD":await this.browser.goForward();break;case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SCROLL_DOWN":case"SCROLL_UP":{let g,h;if(r.target&&bn(r.target))await this.browser.hoverUsingVisualCoordinates(r.target.pixels);else if(r.target&&r.target.elementDescriptor.trim()){let{elementInteractedDisplayString:b,thoughts:w}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:r.target,cache:r.cache?.target,action:C=>this.browser.hover(C),options:{...r,targetName:"target",disableGlobalLocatorRedirect:!0,disableCache:a}});g=b,h=w}let f=this.browser.getViewport()?.height??Nt.height,y=this.browser.getViewport()?.width??Nt.width;switch(r.type){case"SCROLL_UP":await this.browser.scrollVertical(-(r.deltaY??f));break;case"SCROLL_DOWN":await this.browser.scrollVertical(r.deltaY??f);break;case"SCROLL_LEFT":await this.browser.scrollHorizontal(-(r.deltaX??y));break;case"SCROLL_RIGHT":await this.browser.scrollHorizontal(r.deltaX??y);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"WAIT_FOR_URL":{if(r.timeout&&r.timeout>1800)throw new A("UserConfigurationError",`Wait for URL timeout of ${r.timeout} exceeds the maximum allowed value of 30 minutes.`);let g=r.matcher;await this.browser.waitForUrl({beforeUrl:this.browser.url(),matcher:g},{timeout:r.timeout?r.timeout*1e3:void 0,negated:r.negated,caseInsensitive:r.caseInsensitive});break}case"WAIT":if(r.delay>1800)throw new A("UserConfigurationError",`Wait timeout of ${r.delay} seconds exceeds the maximum allowed value of 30 minutes`);let c=r.delay*1e3;await J(c,this.executeAbortController.signal);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0});break;case"CLICK":{if(bn(r.target)){await this.browser.clickUsingVisualCoordinates(r.target.pixels,r);break}let g=this.browser.url(),{elementInteractedDisplayString:h,result:f,thoughts:y}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,target:r.target,command:r,cache:r.cache?.target,action:w=>this.browser.click(w,this.createCallbacksForBrowser(this.orgId),r),options:{disableCache:a,targetName:"target",...r}}),b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:y,data:f};return Qs(g,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}case"COPY":return await this.browser.copy(r.value),{succeedImmediately:!1,data:r.value,urlAfterCommand:this.browser.url()};case"PASTE":{await this.browser.paste();break}case"DRAG":{if(bn(r.fromTarget)&&bn(r.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(r.fromTarget.pixels,r.toTarget.pixels,{hoverSeconds:r.hoverSeconds});break}if(bn(r.fromTarget)||bn(r.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{elementInteractedDisplayStrings:g,thoughts:h}=await this.wrapMultiElementTargetingCommand({ctx:e,tracer:n,command:r,targetNames:["fromTarget","toTarget"],descriptions:[r.fromTarget,r.toTarget],caches:[r.cache?.fromTarget,r.cache?.toTarget],action:(f,y)=>this.browser.dragAndDrop(f.locator,y.locator,{hoverSeconds:r.hoverSeconds,steps:r.steps}),options:{useSelector:!!r.useSelector,disableCache:a}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g[0],thoughts:h}}case"MOUSE_DRAG":{let g=parseInt(r.deltaX),h=parseInt(r.deltaY),f=r.steps??5;if(isNaN(g)||isNaN(h))throw new A("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${r.deltaX}, ${r.deltaY})`);if(r.target&&bn(r.target)){await this.browser.mouseDragUsingVisualCoordinates(g,h,f,r.target.pixels,{force:r.force});break}let y,b,w;if(r.target?.elementDescriptor){let{elementInteractedDisplayString:C,result:v,thoughts:R}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:r.target,cache:r.cache?.target,action:async x=>x.locator,options:{disableCache:a,targetName:"target",...r}});y=v,b=C,w=R}return await this.browser.mouseDrag(g,h,f,y,{force:r.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:b,thoughts:w}}case"SELECT_OPTION":{if(!rr(r.target))throw new Error("Select with x/y is not supported yet");let g=r.target.elementDescriptor,h=r.choice,{elementInteractedDisplayString:f,thoughts:y}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:{type:"description",elementDescriptor:g},cache:r.cache?.target,action:b=>this.browser.selectOption(b,h,r.force),options:{...r,targetName:"target",disableCache:a,source:Hr(r)}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:y}}case"TAB":{let g={loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0,retry:!0};await this.browser.switchToPage(r.action,g);break}case"NEW_TAB":await this.browser.createNewTab(r.url,{loadTimeoutMs:r.loadTimeout?r.loadTimeout*1e3:void 0});break;case"COOKIE":if(!r.value)break;let d=await this.browser.setCookie(r.value);i.debug({results:d},"Set cookies");break;case"LOCAL_STORAGE":if(!r.value||!r.key)break;await this.browser.setLocalStorage(r.key,r.value);break;case"JAVASCRIPT":{let g;try{r.environment==="BROWSER"?(g=await this.browser.evaluateCodeInPage({code:r.code,fragment:r.fragment??!1,context:o.toObjectCopy(),timeoutMs:r.timeout?r.timeout*1e3:void 0}),i.info({result:g},"Executed JavaScript in browser")):g=await yr({orgId:this.orgId,code:r.code,fragment:!!r.fragment,context:o,timeoutMs:r.timeout?r.timeout*1e3:void 0,logger:i,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal,callbacks:{onPersistentVariableUpdates:async h=>{if(!this.options?.scratchPadId){i.warn({updates:h},"Got persistent variable updates but scratch pad is not available");return}await this.storage.savePersistentVariables?.({scratchPadId:this.options?.scratchPadId,orgId:this.orgId,updates:h,logger:i})}}})}catch(h){throw this.throwIfClosed(),new A("ActionFailureError",h instanceof Error?h.message:`${h}`,{errOptions:{cause:h}})}try{JSON.stringify(g)}catch(h){throw new A("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{errOptions:{cause:h}})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:g}}case"TYPE":{if(r.target&&bn(r.target)){await this.browser.clickUsingVisualCoordinates(r.target.pixels,r),await this.browser.type(r.value,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter},!0);break}let g=this.browser.url(),h,f,y=ib(r.target);if(y){let{elementInteractedDisplayString:w,thoughts:C}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:y,cache:r.cache?.target,action:v=>this.browser.typeIntoTarget(r.value,v,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter}),options:{...r,targetName:"target",disableCache:a,disableGlobalLocatorRedirect:!0,source:Hr(r)}});h=w,f=C}else await this.browser.type(r.value,{force:r.force,clearContent:r.clearContent,forceClearContent:r.forceClearContent,delay:r.delay,pressEnter:r.pressEnter},!0);let b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return Qs(g,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}case"HOVER":{if(bn(r.target)){await this.browser.hoverUsingVisualCoordinates(r.target.pixels);break}let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:r.target,cache:r.cache?.target,action:f=>this.browser.hover(f),options:{...r,targetName:"target",disableCache:a}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"FOCUS":{if(!rr(r.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,command:r,target:r.target,cache:r.cache?.target,action:f=>this.browser.focus(f),options:{...r,targetName:"target",disableCache:a}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"BLUR":{if(r.target&&!rr(r.target))throw new Error("Blur with x/y is not supported yet");if(!r.target||!r.target.elementDescriptor)return await this.browser.blur(null),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};let{elementInteractedDisplayString:g,thoughts:h}=await this.wrapElementTargetingCommand({ctx:e,tracer:n,target:r.target,command:r,cache:r.cache?.target,action:f=>this.browser.blur(f),options:{...r,targetName:"target",disableCache:a}});return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:h}}case"PRESS":let u=this.browser.url();await this.browser.press(r.value,{repeat:r.repeat,convertMeta:r.convertMeta??!0,delayMs:r.delayMs});let m={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Qs(u,m.urlAfterCommand)&&(m.succeedImmediately=!0,m.succeedImmediatelyReason="URL changed"),m;case"KEY_DOWN":return await this.browser.keyDown(r.value,{convertMeta:r.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"KEY_UP":return await this.browser.keyUp(r.value,{convertMeta:r.convertMeta??!0}),{urlAfterCommand:this.browser.url(),succeedImmediately:!1};case"REQUEST":{let g=new UM,h=FM(fetch,g),f;try{f=new URL(r.url).hostname}catch{}return{data:{...await yS({command:r,baseUrl:this.browser.baseUrl,logger:i,fetchImplementation:h}),cookies:Lp(g,f)},succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GRAPHQL_REQUEST":return{data:await ab({command:r,baseUrl:this.browser.baseUrl,logger:i}),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"VISUAL_DIFF":return SS({ctx:e,tracer:n,command:r,disableCache:a,browser:this.browser,logger:i,storage:this.storage,screenshotStorage:this.visualDiffScreenshotStorage,targetingWrapper:g=>this.wrapElementTargetingCommand(g)});case"FILE_UPLOAD":{let g,h;if(r.fileSource.type==="URL"?(h=r.fileSource.url,g=await WS({uri:r.fileSource.url,logger:i,orgId:this.orgId})):r.fileSource.type==="USER_FILE"&&(h=r.fileSource.name,g=await this.uploadedFileStorage?.getFileForUpload(r.fileSource.name,this.orgId)),!g)throw new A("UserConfigurationError",`Attempted to use non-existent file for upload step: ${h}`);await this.browser.setFileChooserHandler({...g,filename:r.filename});break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let g;if(!r.storageState.trim())g=void 0;else if(g=await yr({orgId:this.orgId,code:r.storageState,fragment:!1,context:o,logger:i,localTools:this.localCodeEvalTools,signal:this.executeAbortController.signal}),typeof g!="object")throw new A("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let h;try{h=us.optional().parse(g)}catch(f){throw new A("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{let g=(r.timeout??Tn)*1e3,h=this.generator.getAgentConfig()?.assertion;if(hS(r.assertion)&&!r.useSelector&&r.target.type==="description"&&h&&h!=="v1"){let y={id:r.id,type:"AI_ASSERTION",assertion:`There is no element on the page closely matches the following description. If the description has single quotes, remember that requires an exact text substring match. Description: ${r.target.elementDescriptor}`,iframeUrl:r.iframeUrl,timeout:r.timeout,cache:r.cache&&"memory"in r.cache?{memory:r.cache?.memory}:void 0};try{let b=await Ml({command:y,logger:i,aiPageFiltering:!!this.options?.aiPageFiltering,fixtures:this.getControllerFixtures(e),useMemory:this.shouldUseMemory(),source:"NEGATED_CHECK"});return{succeedImmediately:!1,thoughts:`The element described does not exist on the page: ${b.thoughts}`,urlAfterCommand:this.browser.url(),afterScreenshotOverride:b.afterScreenshotOverride}}finally{y.cache?.memory&&Bs(r,y.cache?.memory.traces)}}let f=await gS({command:r,tracer:n,timeoutMs:g,targetingWrapper:y=>this.wrapElementTargetingCommand(y),fixtures:this.getControllerFixtures(e),disableCache:a});return{fail:!f.success,data:f.data,elementInteracted:f.elementInteractedDisplayString,thoughts:f.err?.message??f.thoughts??`Element assertion ${f.success?"succeeded":"failed"}.`,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"PAGE_CHECK":{let g=await Mn({action:async()=>dl({assertion:r.assertion,browser:this.browser,logger:i,timeout:r.timeout,signal:this.executeAbortController.signal,autoExpandIframes:!!this.browser.userBrowserSettings.autoExpandIframes}),frameConfig:r.iframeUrl?{type:"url",url:r.iframeUrl}:void 0,browser:this.browser,logger:i});return{fail:!g.success,data:g.data,thoughts:g.success?"Page assertion passed.":g.err?.message??`Page assertion still failing after ${r.timeout} seconds.`,urlAfterCommand:this.browser.url(),succeedImmediately:!1}}case"REGISTER_REQUEST_LISTENER":{let g=new wr(r.requestMatcher),h=this.browser.registerRequestListener(g);return this.registeredListeners[r.key]=h.then(async f=>await Iu(f)).catch(f=>{i.error({err:f},"Failed to get request listener response")}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"AWAIT_LISTENER":{let g=this.registeredListeners[r.key];if(!g)throw new A("ActionFailureError",`No listener registered with key: ${r.key}`);let h=r.timeout??10;return{data:await H(g,{milliseconds:h*1e3,message:`Request listener timed out after ${h} seconds`}),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"RECORD_REQUESTS":{let g=new wr(r.requestMatcher);return this.recordedRequests[r.key]={},this.browser.registerRequestRecorder(r.key,g,{onRequestStart:(h,f)=>{this.recordedRequests[r.key][h]=Cl(f)},onRequestComplete:(h,f)=>{this.recordedRequests[r.key][h]=Cl(f)}}),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"GET_RECORDED_REQUESTS":{let g=this.recordedRequests[r.key];if(!g)throw new A("ActionFailureError",`No recorder registered with key: ${r.key}`);return delete this.recordedRequests[r.key],{data:Object.values(g),succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"SET_HEADER":{let g;return r.requestMatcher&&(g=new wr(r.requestMatcher)),this.browser.setHeader(r.name,r.value,g),{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"MOCK_ROUTE":return{data:{key:this.browser.registerMock(r.key,new wr(r.requestMatcher),async(h,f)=>{let y=await yr({orgId:this.orgId,code:r.responseGenerator,fragment:!1,context:o,timeoutMs:void 0,logger:i,localTools:this.localCodeEvalTools,mock:{request:h,response:f},disallowVariableUpdates:!0,responseSerialization:"RESPONSE"}),b=Gp.parse(y);return new Response(b.body,{status:b.status,headers:b.headers})},r.fetchOriginalResponse??!1)},succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"REMOVE_ROUTE_MOCK":return this.browser.removeMock(r.key),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"OFFLINE_MODE":return await this.browser.setOfflineMode(r.enable),{succeedImmediately:!1,urlAfterCommand:this.browser.url()};default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedDescription({browserState:e,targetId:n,disableCache:r,screenshot:o}){return(await this.generator.getReverseMappedDescription({browserState:e,target:n,screenshot:o},{disableCache:r,abortSignal:this.executeAbortController.signal,loggerTags:Oe(this.logger)})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode({params:e,abortController:n,isClickToRecord:r}){this.recordAbortController=n;let o=new vl({signal:n.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,o,r),o}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Oe(this.logger)})}async getFailureRecoveryPlan(e){return this.generator.getFailureRecoveryPlan(e,{disableCache:!0,abortSignal:this.executeAbortController.signal,loggerTags:Oe(this.logger)})}};import{z as an}from"zod";var bse=an.object({useSelector:an.boolean().optional(),disableCache:an.boolean().optional(),iframeUrl:an.string().optional(),retriesWithAI:an.number().optional(),targetName:an.union([an.literal("target"),an.literal("fromTarget"),an.literal("toTarget")]),source:Wi.optional(),disableGlobalLocatorRedirect:an.boolean().optional(),allowZeroOpacityOverride:an.boolean().optional(),targetHealingInProgress:an.boolean().optional(),memory:Eo.optional()});import{cloneDeep as BM}from"lodash-es";var zM={showOverlay:!1},Ll=class{sessions=new Map;sessionCountByIp=new Map;latestSessionId;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:n,cleanup:r,clientIp:o,sessionId:a,socket:i}){return this.sessions.set(a,{controller:e,context:n,cleanup:r,clientIp:o,browserBehavior:BM(zM),socket:i}),this.latestSessionId=a,a}removeSession(e,n){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:a}=o;try{a.setClosed(),await a.browser.cleanup()}catch(i){n.error({err:i},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(i){n.error({err:i},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}getLatestSession(){if(this.latestSessionId)return this.getSession(this.latestSessionId)}};function sb(t,e,n,r){let o=Date.now(),a=Date.now(),i,s,l,c,d=!1,u=async(h,f)=>{if(!h.closed&&!h.isInPageLoad)try{let y=l;l=void 0;let b=h.url(),w=f.toEditorDisplayCopy();JSON.stringify(w)===JSON.stringify(i)&&b===c&&o>a||(t.emit("browserState",{logsPerPage:y?.logsPerPage,harPages:y?.harPages,harEntries:y?.harEntries,viewport:h.getViewport(),url:b,iframeSrcUrls:s??[],context:w,isInPageLoad:h.isInPageLoad}),o=Date.now()),c=b,i=w}catch(y){if(!t.connected)return;let b=y instanceof Error?y.message:`${y}`;if(b.includes("Frame was detached")||b.includes("Not attached to an active page")||b.includes("browser has been closed")||b.includes("UserInfrastructureError"))return;n.error({err:y,sessionId:e},"Error grabbing browser state")}},m=setInterval(()=>{let h=r.getSession(e),f=h?.controller?.browser;if(!f||f.closed){n.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(m);return}u(f,h.context)},1e3),p=(h,f)=>!!(JSON.stringify(h)!==JSON.stringify(s)||f.logsPerPage.some(y=>y.length>0)||f.harPages&&Object.keys(f.harPages).length>0||f.harEntries&&Object.keys(f.harEntries).length>0),g=setInterval(async()=>{let f=r.getSession(e)?.controller?.browser;if(!f||f.closed){clearInterval(g);return}else if(d)return;d=!0;try{let y=await f.getAllFrameUrls(),b=f.retrieveAndClearDebugData();p(y,b)&&(s=y,l=b,a=Date.now())}catch(y){n.warn({err:y},"Failed to fetch extended details")}finally{d=!1}},2500);return{timers:[m,g]}}var HM=4;async function lb({socket:t,logger:e,storageFactory:n,uploadedFileStorage:r,visualDiffScreenshotStorage:o,devicePixelRatio:a,generatorFactory:i,enricherFactory:s,authorization:l,flagStoreFactory:c,settingsFactory:d,getOrgId:u,branchGetter:m,globalE2eStateManager:p}){let g=t.id,h=t.handshake.query.testId;if(!h)throw new Error("Socket connection request is missing testId");let f=await u({type:"e2e",testId:h}),y=await m?.();e=e.child({testId:h,orgId:f,sessionId:g,branch:y});let b=await i(f,e),w=await s(f,e),C=await c(f),v=await d(f,e),R=await n(f),{testMetadata:x,baseUrl:M,envName:D,browserConfig:_,aiSettings:K,environmentVariables:P,localCodeEvalTools:W}=await go({testId:h,orgId:f,logger:e,storage:R,authorization:l,flagStore:C,settings:v}),k=p.getSession(g);if(k)return e.info("Associating connection with existing session (likely reconnect)"),await k.controller.browser.clearAllCdpHighlights(),{type:"e2e",sessionId:g,orgId:f,testId:h};let G=t.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:G,event:"connect",args:t.handshake.query},"Websocket event (connect)"),G&&p.getCurrentConnectionsByIp(G)>=HM)throw e.error({clientIp:G,sessions:p.getCurrentSessionsByIp(),...t.handshake.query},"Socket connection browser creation rate limit triggered"),new Error("You have exceeded the maximum number of connections allowed. Momentic limits the number of simultaneously open tabs to uphold browser reliability. Please close duplicate tabs and try again later.");p.reserveCapacityByIp(G);try{await $M({socket:t,baseUrl:M,envName:D,testMetadata:x,orgId:f,sessionId:g,logger:e,environmentVariables:P,clientIp:G,devicePixelRatio:a,storage:R,uploadedFileStorage:r,visualDiffScreenshotStorage:o,localCodeEvalTools:W,generator:b,enricher:w,browserConfig:_,aiSettings:K,flagStore:C,globalE2eStateManager:p})}catch(we){throw e.warn({err:we},"Error setting up socket session, possibly due to client closing the connection"),p.releaseCapacityByIp(G),we}return{type:"e2e",sessionId:g,testId:h,orgId:f}}async function $M({socket:t,baseUrl:e,envName:n,devicePixelRatio:r,testMetadata:o,orgId:a,sessionId:i,logger:s,storage:l,uploadedFileStorage:c,visualDiffScreenshotStorage:d,localCodeEvalTools:u,generator:m,environmentVariables:p,browserConfig:g,aiSettings:h,clientIp:f,enricher:y,flagStore:b,globalE2eStateManager:w}){let C={viewport:o.advanced?.viewport??Nt,locale:o.advanced?.locale??_o,timezoneId:o.advanced?.timezone??Do,geolocation:o.advanced?.geolocation??Fo,colorScheme:o.advanced?.colorScheme};r&&(C.deviceScaleFactor=r);let v=o.id,R=await hl({settings:g,orgId:a,baseUrl:e,envName:n,testName:o.name,localTools:u,envVariables:p,logger:s,customHeaders:void 0});s=s.child({orgId:a,sessionId:i,testId:v});let x=!1,M=b.isBooleanFlagEnabled("icon_knowledge_base")?await l.fetchIconKnowledgeBase(s):null,D=await kn.init({baseUrl:e,userBrowserSettings:R,enricher:y,storage:l,flagStore:b,logger:s,contextArgs:C,iconKnowledgeBase:M,callbacks:{onTabsChange:(k,G)=>{t.emit("tabs",{tabs:k,activeTab:G})},onScreencastFrame:(k,G)=>{let we=t;x&&(we=t.compress(!0)),we.emit("screenshot",{buffer:k},()=>{G()})},onSvgsCollected:k=>{t.emit("newIconDetected",{numIcons:k.newSvgs.length}),l.saveNewIcons(k,s)}}});await D.navigate({url:e,initialNavigation:!0});let _=new pa({browser:D,generator:m,logger:s,flagStore:b,orgId:a,options:{scratchPadId:void 0,slowMoMs:R.slowMoMs,autoFollowNewTabs:R.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering??b.isBooleanFlagEnabled("rag_v2")},storage:l,localCodeEvalTools:u,uploadedFileStorage:c,visualDiffScreenshotStorage:d}),K=sb(t,i,s,w),P=async()=>{K.timers.forEach(k=>clearInterval(k))},W=new Xt({baseUrl:e,testName:o.name,currentUrl:_.browser.url(),variablesFromEnvironment:p,envName:n});if(!t.connected)throw await D.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");t.emit("session",{url:e,userAgent:kn.USER_AGENT,viewport:_.browser.getViewport(),sessionId:i}),w.registerSession({controller:_,context:W,sessionId:i,cleanup:P,clientIp:f,socket:t})}async function go({testId:t,orgId:e,logger:n,storage:r,authorization:o,flagStore:a,settings:i}){let s=await r.fetchTestMetadata(t,n);if(!s)throw new Error(`Test metadata could not found for test ${t}`);let l;o?.type==="API_KEY"&&(l=new gr({httpClient:new xt({...o,logger:n}),fakerSeed:void 0}));let c=s.envs?.find(f=>f.default),d;c&&(d=await r.fetchEnvironment(c.name,n));let u=d&&"browser"in d?d.browser:void 0,m={...i.browser,...u,...s.advanced},p=s.baseUrl||d?.variables?.[at];if(!p)throw new Error("Base URL is empty in both test options and the configured environment");let g={...d?.variables};await Promise.all((s.parameters??[]).map(async f=>{let y=await jt({orgId:e,s:f.defaultValue,context:Xt.dummyContext(s.name,d?.name,g),logger:n,localTools:l});g[f.name]=y}));let h={...i.ai,...s.advanced};return{localCodeEvalTools:l,baseUrl:p,envName:d?.name,testName:s.name,browserConfig:m,environmentVariables:g,testMetadata:s,aiSettings:h}}var Hu=class{parentTracer=null;socket;step;constructor({step:e,socket:n,parentTracer:r}){this.socket=n,this.parentTracer=r,this.step=e}getParentStepIdChain(){return this.parentTracer?this.parentTracer?.getParentStepIdChain()??[]:[]}attachBeforeScreenshot(){}attachAfterScreenshot(){}attachBeforeHtmlSnapshot(){}attachAfterHtmlSnapshot(){}heal(){}async finish(e){switch(e.step.status){case"SUCCESS":this.socket.emit("success",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"FAILED":this.socket.emit("failure",{...e,parentStepIdChain:this.getParentStepIdChain()});return;case"CANCELLED":this.socket.emit("cancelled",{...e,parentStepIdChain:this.getParentStepIdChain()});return}}async startSubSteps(){return new Rr({parentStep:this.step,socket:this.socket,parentTracer:this})}},Rr=class{parentTracer;parentStep;socket;constructor({parentStep:e,socket:n,parentTracer:r}){this.parentTracer=r,this.parentStep=e,this.socket=n}async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}getParentStepIdChain(){return this.parentStep?[...this.parentTracer?.getParentStepIdChain()??[],this.parentStep.id]:[]}async startStep(e){return this.socket.emit("started",{stepId:e.step.id,parentStepIdChain:this.getParentStepIdChain(),attempt:e.attempt}),new Hu({step:e.step,parentTracer:this,socket:this.socket})}},Ol=class{constructor(e,n,r,o,a){this.socket=e;this.storage=n;this.orgId=r;this.testId=o;this.stepsBeforeRun=a}async getScreenshot(){throw new Error("getScreenshot is not supported in the editor")}async getHtmlSnapshot(){throw new Error("getHtmlSnapshot is not supported in the editor")}attachConsoleLogs(){}attachNetworkLogs(){}async finish(){this.socket.emit("finished")}async startBeforeStepList(){return new Rr({parentStep:null,parentTracer:null,socket:this.socket})}async startMainStepList(){return new Rr({parentStep:null,parentTracer:null,socket:this.socket})}async startAfterStepList(){return new Rr({parentStep:null,parentTracer:null,socket:this.socket})}};var $u={currentlyExecutingRequests:{}},GM=t=>async(e,n)=>{let{testId:r,orgId:o}=t.metadata,a=await t.flagStoreFactory(o),i=await t.settingsFactory(o,t.logger),s=await t.storageFactory(o),l,c=await go({testId:r,orgId:o,logger:t.logger,storage:s,authorization:t.authorization,flagStore:a,settings:i}),d=`${r}|${c.baseUrl}`;try{let u=$u.currentlyExecutingRequests[d]??0;$u.currentlyExecutingRequests[d]=u+1,l=await WM({...t,...e,...c,done:n})}finally{t.logger.info({result:l,sessionId:t.metadata.sessionId},"Test execution complete"),$u.currentlyExecutingRequests[d]--}},WM=async({socket:t,steps:e,baseUrl:n,testMetadata:r,reInitialize:o,toStep:a,fromStep:i,storageFactory:s,aiSettings:l,browserConfig:c,metadata:d,logger:u,envName:m,testName:p,environmentVariables:g,localCodeEvalTools:h,done:f,cacheStorageFactory:y,globalE2eStateManager:b})=>{let{testId:w,sessionId:C,orgId:v}=d,R=C,x=b.getSession(C);if(!x)throw new Error("No active session found");let{controller:M,context:D}=x;M.setOpen(),u=u.child({testId:w,orgId:v,sessionId:C,runId:R}),u.info({steps:e.map(oe=>`${oe.type}${"command"in oe?` - ${oe.command.type}`:""}`),toStep:a,fromStep:i,reInitialize:o,envName:m,testName:p,baseUrl:n,context:D,flags:M.flagStore.getAllFlags()},"Socket execution parameters");let _=g??{},K=async()=>{o&&(await M.browser.reset({newUrl:n}),D.reset({baseUrl:n,currentUrl:M.browser.url(),variablesFromEnvironment:_,envName:m,testName:p}))},P=await s(v),W=await y(v),k=async()=>{try{await W.resolveStepCacheEntries({schemaVersion:r.schemaVersion,testId:w,stepLists:{steps:e},logger:u})}catch(oe){u.error({err:oe},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};try{await ai({promiseGenerator:async()=>Promise.all([K(),k()]),signal:M.executeAbortController.signal,codePath:"resolveStepCacheAndInitBrowser"}),M.setOpen()}catch(oe){if(t.emit("finished"),oe.name!=="AbortError")throw new Error(`Failed to setup browser for execution: ${oe}`)}let G=jM(e),we={collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},Ce={orgId:v,runId:R,testMetadata:r,steps:e,fromStep:i,toStep:a,orgSettings:{ai:l,browser:c}},be={controller:M,context:D,storage:P,codeEvalTools:h,billingReporter:new zo,logger:u},wt={test:{},step:{onDynamicAIActionStatusUpdateEvent:oe=>{t.emit("dynamicCommandStatusUpdate",oe)},onDynamicAIActionEvaluatingEvent:oe=>{t.emit("dynamicCommandEvaluating",oe)},onDynamicCommandGenerated:oe=>{t.emit("dynamicCommandGenerated",oe)},onDynamicCommandExecuted:oe=>{t.emit("dynamicCommandExecuted",oe)}}},Sn=new Ol(t,P,v,w,G),de=await gl({fixtures:be,options:we,callbacks:wt,inputs:Ce,testParams:{tracer:Sn}});return de?.status==="PASSED"?await zs({logger:u,cacheStorage:W,orgId:v,testId:w,originalSteps:{steps:G},updatedSteps:{steps:e}}):de?.status==="FAILED"&&await Hs({logger:u,cacheStorage:W,orgId:v,testId:w,originalSteps:{steps:G},updatedSteps:{steps:e}}),await Sn.finish(),f?.(de),de.status};var cb={event:"execute",createHandler:GM};import{cloneDeep as VM}from"lodash-es";var qM=t=>async({command:e},n)=>{let{logger:r,generatorFactory:o,metadata:a}=t,i=VM(e),s=qh(i);if(s.category!=="NO_DESCRIPTION_PROVIDED"){if(s.category!=="NONE"){n?.({result:s});return}"cache"in i&&(i.cache=void 0);try{let c=await(await o(a.orgId,r)).getLintStepResult({command:i},{logger:r});n?.({result:c})}catch(l){r.error({event:"lint",err:l},"Failed to lint step"),n?.({result:void 0})}}},db={event:"lintStep",createHandler:qM};var KM=({metadata:t,logger:e,storageFactory:n,globalE2eStateManager:r})=>{let{sessionId:o,orgId:a}=t;return async(i,s)=>{let{description:l,command:c,testMetadata:d,returnScreenshot:u}=i;e.info({params:i},`Locate handler called - ${l}`);let m=r.getSession(o);if(!m)throw new Error("No active session found");let{controller:p,context:g}=m;p.setOpen();let h=await n(a),f=Vr.parse(d.advanced??{}),y={},b;if(l){if("useSelector"in c&&c.useSelector)try{let w=await p.locateElementWithSelector(l,"iframeUrl"in c?c.iframeUrl:void 0);b=w.resolution.locator,y={target:w.target,thoughts:w.thoughts}}catch(w){e.warn({err:w},"Failed resolving target with selector"),s({err:`Failed locating element: ${w.message}`,decisions:w instanceof En?w.decisions:void 0});return}else try{let w=await p.locateElement({description:l,disableCache:f.disableAICaching??!1,skipWait:!0,testContext:g,source:Hr(c),iframeUrl:"iframeUrl"in c?c.iframeUrl:void 0,memory:"cache"in c&&c.cache&&"target"in c.cache&&ki(c.cache.target.memory)?c.cache.target.memory:void 0,logger:e});y={target:w.target,thoughts:w.thoughts},b=w.resolution.locator}catch(w){(async()=>{try{let C=await p.browser.getCondensedHtml({skipWait:!0});e.warn({err:w,html:C.slice(0,1e5)},"Failed locating element with AI")}catch(C){e.warn({err:C},"Failed grabbing HTML after trying to locate element with AI")}})(),s({err:`${w.message}`});return}if(c.type==="SELECT_OPTION"&&b)try{y.options=await p.browser.getSelectOptions(b)}catch(w){e.warn({err:w},"Failed getting select options"),s({err:`Failed getting select options: ${w.message}`});return}e.info({result:y},"Locate handler result")}if(u)try{let{buffer:w,width:C,height:v}=await p.screenshotWithDimensions({clearHighlights:!0,locator:b}),R=await h.uploadScreenshot(w);y.screenshot={data:R,width:C,height:v},e.info({width:C,height:v},"Captured screenshot during locate")}catch(w){e.error({err:w},"Error capturing screenshot during locate"),s({err:`Error taking screenshot: ${w.message}`});return}if(s({result:y}),b)try{await Promise.all([p.browser.scrollIntoViewIfNeeded(b),p.browser.highlight(b)])}catch(w){e.warn({err:w},"Error highlighting element, continuing...")}}},ub={event:"locate",createHandler:KM};var YM=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async({event:o,percentX:a,percentY:i})=>{let s=n.getSession(r);if(!s)throw new Error("No active session found");let l=s.controller.browser;if(l.closed||l.getActivePage().isClosed()){e.warn("Ignoring mouse move because the browser is closed");return}try{await l.clickMouseFromPositionPercentages(o,a,i)}catch(c){e.error({err:c},"Error performing click during cloud recording in control mode")}}},mb={event:"mouseClickEvent",createHandler:YM};var XM=({metadata:t,generatorFactory:e,logger:n,socket:r,globalE2eStateManager:o})=>{let{sessionId:a,orgId:i,testId:s}=t;return async({stepId:l,parentStepIdChain:c,attribute:d})=>{let u=o.getSession(a);if(!u)throw new Error("No active session found");let{controller:m}=u,p=await e(i,n);m.setOpen(),u.browserBehavior.showOverlay=!0;let g=new AbortController;g.signal.addEventListener("abort",async()=>{try{u.browserBehavior.showOverlay=!1,await m.stopRecordMode()}catch(y){n.warn({err:y},"Failed to stop record mode in target click socket handler")}});let h=!1,f=(y,b)=>{b.type!=="PRESET_ACTION"||b.command.type!=="CLICK"||(r.emit("targetRecordingUpdate",{type:y,stepId:l,parentStepIdChain:c,command:b.command,attribute:d}),g.abort(),h=!0)};setTimeout(()=>{h||(g.abort(),r.emit("targetRecordingUpdate",{type:"error",err:"Timed out waiting for click event",stepId:l,parentStepIdChain:c,attribute:d}))},1e4),await m.startRecordMode({params:{generator:p,logger:n,testId:s,orgId:i,callbacks:{onActionReceived:y=>f("clickReceived",y),onStepRecorded:y=>f("descriptionGenerated",y)}},abortController:g,isClickToRecord:!0}),r.emit("targetRecordingUpdate",{type:"listenersInitialized",stepId:l,parentStepIdChain:c,attribute:d})}},pb={event:"recordTargetClick",createHandler:XM};var JM=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async({key:o})=>{let a=n.getSession(r);if(!a)throw new Error("No active session found");if(o==="Dead")return;let{controller:i}=a;if(i.browser.closed||i.browser.getActivePage().isClosed()){e.debug({sessionId:r},"Browser is closed, ignoring keyboard press socket event");return}try{i.setOpen(),await i.browser.keyDown(o,{})}catch(s){if(s.message.includes("has been closed")){e.debug({sessionId:r,err:s},"Browser is closed, ignoring key down socket event error");return}throw s}}},gb={event:"keyDownEvent",createHandler:JM};var QM=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async({key:o})=>{let a=n.getSession(r);if(!a)throw new Error("No active session found");if(o==="Dead")return;let{controller:i}=a;if(i.browser.closed||i.browser.getActivePage().isClosed()){e.debug({sessionId:r},"Browser is closed, ignoring keyboard press socket event");return}try{i.setOpen(),await i.browser.keyUp(o,{})}catch(s){if(s.message.includes("has been closed")){e.debug({sessionId:r,err:s},"Browser is closed, ignoring key up socket event error");return}throw s}}},hb={event:"keyUpEvent",createHandler:QM};var ZM=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t,o,a=0,i=(c,d)=>{let u=async()=>{o=void 0};clearTimeout(o),o=setTimeout(u,Math.min(1e3,250*(a+1)))},s,l=0;return async c=>{let d=n.getSession(r);if(!d)throw new Error("No active session found");let{controller:u,browserBehavior:m}=d,p=u.browser;if(p.closed||p.getActivePage().isClosed()){e.warn("Ignoring mouse move because the page is closed");return}if(c.event==="scroll"){let g=await p.scrollFromPositionPercentages(c.percentX,c.percentY,s?.x??0,s?.y??0),h=d.browserBehavior.recordingState?.transformer;h&&g&&h.recordScroll(g);return}m.showOverlay&&i(p,c);try{let g=await p.moveMouseFromPositionPercentages(c.percentX,c.percentY);l=0,s=g}catch(g){l++,l%5===0&&e.warn({err:g,mouseErrors:l},"Error in socket mouse move handler")}}},fb={event:"mouseMoveEvent",createHandler:ZM};var eL=({metadata:t,generatorFactory:e,socket:n,logger:r,globalE2eStateManager:o})=>{let{sessionId:a,orgId:i,testId:s}=t;return async({stepId:l})=>{let c=o.getSession(a);if(!c)throw new Error("No active session found");let{controller:d,browserBehavior:u}=c,m=await e(i,r);r.info("Starting cloud recording");let p=new AbortController,g=await d.startRecordMode({params:{generator:m,logger:r,testId:s,orgId:i,callbacks:{onActionReceived:(h,f)=>{n.emit("stepRecorded",{stepId:l,step:h,offset:f})},onStepRecorded:(h,f)=>{n.emit("stepRecorded",{stepId:l,step:h,offset:f})}}},abortController:p,isClickToRecord:!1});u.recordingState={transformer:g}}},Sb={event:"recordingStart",createHandler:eL};var tL=({metadata:t,logger:e,globalE2eStateManager:n})=>{let{sessionId:r}=t;return async()=>{let o=n.getSession(r);if(!o)throw new Error("No active session found");e.info("Stopping cloud recording"),await o.controller.stopRecordMode(),o.browserBehavior.recordingState=void 0,o.browserBehavior.showOverlay=!1}},yb={event:"recordingStop",createHandler:tL};var nL=({socket:t,metadata:e,logger:n,storageFactory:r,authorization:o,flagStoreFactory:a,settingsFactory:i,globalE2eStateManager:s})=>async(l,c)=>{let{testId:d,sessionId:u,orgId:m}=e;n.info({testId:d,sessionId:u},"Refresh event received");let p=await a(m),g=await i(m,n),h=await r(m),{baseUrl:f}=await go({testId:d,orgId:m,logger:n,storage:h,authorization:o,flagStore:p,settings:g}),y=s.getSession(u);if(!y){t.emit("error",{message:"No session to refresh"});return}let{controller:b}=y;b.setOpen(),await b.browser.refresh();let w=b.browser.getViewport();n.info({baseUrl:f,viewport:w},`Session refreshed for test ${d} at ${f}`),c()},bb={event:"refresh",createHandler:nL};var rL=({socket:t,metadata:e,logger:n,storageFactory:r,authorization:o,flagStoreFactory:a,settingsFactory:i,globalE2eStateManager:s})=>async()=>{let{testId:l,sessionId:c,orgId:d}=e;n.info({testId:l,sessionId:c},"Reset event received");let u=await a(d),m=await i(d,n),p=await r(d),{baseUrl:g,envName:h,testName:f,environmentVariables:y}=await go({testId:l,orgId:d,logger:n,storage:p,authorization:o,flagStore:u,settings:m}),b=s.getSession(c);if(!b){t.emit("error",{message:"No session to reset"});return}let{controller:w,context:C}=b;await w.browser.reset({newUrl:g});let v=w.browser.baseUrl;C.reset({baseUrl:v,currentUrl:w.browser.url(),variablesFromEnvironment:y,envName:h,testName:f});let R=w.browser.getViewport(),x=kn.USER_AGENT;n.info({baseUrl:g,viewport:R},`Session reset for test ${l} at ${v}`),t.emit("session",{url:v,userAgent:x,viewport:R,sessionId:c})},Tb={event:"reset",createHandler:rL};var oL=({metadata:t,globalE2eStateManager:e})=>{let{sessionId:n}=t;return async({url:r})=>{let o=e.getSession(n);if(!o)throw new Error("No active session found");await o.controller.browser.switchToPage({type:"SUBSTRING",substring:r})}},wb={event:"switchTab",createHandler:oL};async function Eb(t){return lb(t)}var Rb=[rS,cb,ub,Tb,bb,eS,wb,db,pb,Sb,yb,fb,mb,gb,hb,nS,tS];var Cb=t=>{let{logger:e}=t,n=new aL(t.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:15*60*1e3,pingInterval:15*60*1e3,maxHttpBufferSize:1e7,perMessageDeflate:!0});return n.on("connection",async r=>{let o;try{e.info({event:"connection",transport:r.conn.transport.name},"Websocket connection established"),o=await Eb({...t,socket:r,logger:e}),e=e.child(o)}catch(a){e.error({event:"connection",type:"websocket",err:a},"Failed to setup connection"),r.emit("error",{message:a instanceof Error?a.message:`${a}`}),r.disconnect(!0);return}Rb.forEach(a=>iL(a,{...t,socket:r,metadata:o,logger:e}))}),n},iL=(t,e)=>{let n=t.createHandler(e),r=(...o)=>{["mouseMoveEvent","keyDownEvent","keyUpEvent","mouseClickEvent","lintStep"].includes(t.event)||e.logger.debug({...e.metadata,event:t.event},`Websocket event (${t.event})`);let a=i=>{e.logger.error({event:t.event,type:"websocket",err:i instanceof Error?i:new Error(`${i}`)},"Unhandled exception in socket handler"),e.socket.emit("error",{message:i instanceof Error?i.message:`${i}`})};try{let i=n.apply(void 0,o);i&&typeof i.catch=="function"&&i.catch(a)}catch(i){a(i)}};e.socket.on(t.event,r)};import{Router as mL}from"express";import{Router as cL}from"express";import wi from"fs";import Ti from"path";import{v4 as dL}from"uuid";import uL from"yaml";import{hostname as sL}from"os";var lL="2.16.0",ut=Is({app:"desktop-server",hostname:sL(),disableConsoleLogs:!0}).child({cliVersion:lL});var ga=cL();async function ju(t){return(await rl(t,ut)).map(r=>{let o=t.modules[r.moduleId];if(!o){S.warn(`Found a dangling module with ID ${r.moduleId} that could not be found on disk.`);return}return{...o,content:r}}).filter(r=>r!==void 0)}ga.get("/",ce(async(t,e)=>{let n=ae(),r=te(n,S),o=await ju(r);e.status(200).json(o)}));ga.post("/",ce(async(t,e)=>{let n;try{n=ug.parse(t.body)}catch(s){e.status(400).json({error:`Invalid request body: ${s}`});return}try{Yr(n.name)}catch(s){e.status(400).json({error:`Invalid module name: ${s}`});return}let r=ae(),o=te(r,S).modules;if(Object.values(o).find(s=>s.name===n.name)){e.status(400).send(`A module with the name "${n.name}" already exists. Please choose a different name.`);return}let a=Ti.join(r.rootDir,n.folderPath??"");if(!wi.existsSync(a)||!wi.statSync(a).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${a}' does not exist.`});return}let i=await kf({...n,folder:a,project:r});e.status(201).json(i)}));ga.get("/:moduleId",ce(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let n=te(ae(),S),r=n.modules[t.params.moduleId];if(!r){e.status(404).json({error:"Module not found."});return}try{let o=await nl(r,n,S);e.json(o)}catch(o){e.status(400).json({err:o})}}));ga.post("/:moduleId/duplicate",ce(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=dg.parse(t.body)}catch(h){e.status(400).json({error:`Invalid request body: ${h}`});return}try{Yr(n.name)}catch(h){e.status(400).json({error:h.message});return}let r=ae(),o=te(r,S),a=o.modules[t.params.moduleId];if(!a){e.status(404).json({error:"Module not found."});return}if(Object.values(o.modules).find(h=>h.name===n.name)){e.status(400).send(`A module with the name "${n.name}" already exists. Please choose a different name.`);return}let i=await nl(a,o,S),s=Ti.join(r.rootDir,Ti.dirname(a.relativePath));if(!wi.existsSync(s)||!wi.statSync(s).isDirectory()){e.status(400).json({error:`The folder configured for module creation '${s}' does not exist.`});return}let l=ve(n.name),c=Ti.join(s,`${l}.module.yaml`),d=dL(),{stepsToSave:u}=await He({stepLists:{steps:i.steps},createNewCacheIds:!0,cacheCreationParams:{orgId:rn()}}),m={fileType:pe.MODULE,schemaVersion:se,moduleId:d,name:n.name,description:"",enabled:!0,steps:u.steps,parameters:i.parameters,defaultParameters:i.defaultParameters,parameterEnums:i.parameterEnums,defaultCacheKey:i.defaultCacheKey,defaultCacheTtl:i.defaultCacheTtl,defaultCacheAllInvocations:i.defaultCacheAllInvocations,autoAuth:i.autoAuth,advanced:i.advanced},p=uL.stringify(m);wi.writeFileSync(c,p,"utf-8");let g={relativeFilePath:Ti.relative(r.rootDir,c)};e.status(201).json(g)}));ga.patch("/:moduleId/metadata",ce(async(t,e)=>{if(!t.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let n;try{n=mg.parse(t.body)}catch(a){e.status(400).json({error:`Invalid request body: ${a}`});return}let r=ae(),o=te(r,S);Nf({moduleId:t.params.moduleId,content:n,momenticFiles:o,logger:S,project:r}),e.status(201).json({message:"ok"})}));var vb=ga;var Ab=mL();Ab.get("/",ce(async(t,e)=>{let n=ae(),r=te(n,S),o=new Set;r?.tests&&Object.values(r.tests).forEach(c=>{c.labels?.forEach(d=>o.add(d))});let a=Array.from(o).sort(),i=Object.values(r.tests),s=await ju(r),l={labels:a,tests:i,modules:s};e.status(200).json(l)}));var xb=Ab;import{Router as pL}from"express";var Gu=pL();Gu.get("/",ce((t,e)=>{let n=Uf(ae(),ut);e.status(200).json(n)}));Gu.get("/names",ce((t,e)=>{let r=ae().config.environments?.map(o=>o.name)??[];e.status(200).json(r)}));var Ib=Gu;import{Router as gL}from"express";var Pb=gL();Pb.get("/",ce((t,e)=>{e.status(200).json({userId:el(),orgId:rn()})}));var Mb=Pb;import{Router as hL}from"express";var Nl=hL();Nl.get("/",ce((t,e)=>{let n=Jd().map(r=>({name:r.config.name,configFilePath:r.configFilePath}));e.status(200).json(n)}));Nl.get("/current",ce((t,e)=>{let n=ae();if(!n){e.status(404).json({error:"No project found."});return}let r={name:n.config.name,configFilePath:n.configFilePath};e.status(200).json(r)}));Nl.post("/set",ce((t,e)=>{let n;try{n=gg.parse(t.body)}catch(r){e.status(400).json({error:`Invalid request body: ${r}`});return}try{let r=ct({configFilePath:n.configFilePath});tl(r,o=>ct({configFilePath:o}))}catch(r){e.status(400).json({error:`Error setting project: ${r}`});return}e.sendStatus(204)}));var Lb=Nl;import{Router as fL}from"express";var Ob=fL();Ob.get("/",ce((t,e)=>{let r={ai:ae().config.ai};e.status(200).json(r)}));var Nb=Ob;import{convertToModelMessages as zL,stepCountIs as HL,streamText as $L}from"ai";import jL from"dedent";import{Router as GL}from"express";import zb from"fs";import So from"path";import{v4 as Hb}from"uuid";import WL from"yaml";import SL from"path";var kl=class{_result=[];_includeSnapshot=!1;_includeTestContext=!1;_includeTest=!1;_isError;_browser;_testContext;_project;_logger;_testPath;constructor(e,n,r,o,a){this._browser=e,this._testContext=n,this._project=r,this._logger=o,this._testPath=a}addResult(e){this._result.push(e)}result(){return this._result.join(`
3910
3910
  `)}setIncludeSnapshot(){this._includeSnapshot=!0}async snapshot(){if(!this._includeSnapshot)return"";let e=this._browser.getActivePage(),n=await this._browser.getBrowserState({skipWait:!1}),r=[];return r.push("### Page state",`- Page URL: ${e.url()}`,`- Page Title: ${await e.title()}`,"- Page Snapshot:","```xml",n.serialize(),"```"),r.join(`
3911
3911
  `)}setIncludeTestContext(){this._includeTestContext=!0}testContext(){if(!this._includeTestContext)return"";let e=[],n=this._testContext.toObjectCopy();return e.push("### Environment variables","```json",JSON.stringify(n,null,2),"```"),e.join(`
3912
- `)}setIncludeTest(){this._includeTest=!0}async test(){if(!this._includeTest)return"";let e=te(this._project,this._logger),n=await Pt(nM.join(this._project.rootDir,this._testPath),this._logger,e),r=[];return r.push("### Test","```json",JSON.stringify(n,null,2),"```"),r.join(`
3912
+ `)}setIncludeTest(){this._includeTest=!0}async test(){if(!this._includeTest)return"";let e=te(this._project,this._logger),n=await Mt(SL.join(this._project.rootDir,this._testPath),this._logger,e),r=[];return r.push("### Test","```json",JSON.stringify(n,null,2),"```"),r.join(`
3913
3913
  `)}addError(e){this._result.push(e),this._isError=!0}async serialize(){let e=[];this._result.length&&(e.push("### Result"),e.push(this._result.join(`
3914
3914
  `)),e.push(""));let n=await this.snapshot();n&&e.push(n,"");let r=this.testContext();r&&e.push(r,"");let o=await this.test();return o&&e.push(o,""),{content:[{type:"text",text:e.join(`
3915
- `)}],isError:this._isError}}};import{z as oM}from"zod";import{tool as rM}from"ai";var mt=t=>({builder:(n,r)=>rM({description:t.schema.description,inputSchema:t.schema.inputSchema,execute:async o=>{try{await t.handle(n,o,r)}catch(i){r.addError(String(i))}return r.serialize()}}),name:t.schema.name});var iM=mt({schema:{name:"observe_page",description:"Observe the current page's accessibility snapshot.",inputSchema:oM.object({})},handle:async(t,e,n)=>{n.setIncludeSnapshot()}}),Ab=[iM];import{randomUUID as xl}from"crypto";import{z as ba}from"zod";import{z as aM}from"zod";var po={id:!0,cache:!0},go=aM.discriminatedUnion("type",[Pr.omit(po),Nr.omit(po),Mr.omit(po),ir.omit(po),or.omit(po),Lr.omit(po),Or.omit(po),ic.omit({id:!0}),mc.omit({id:!0}),vo.omit({id:!0}),uc.omit({id:!0}),pc.omit({id:!0}),ac.omit({id:!0})]);import{createAnthropic as sM}from"@ai-sdk/anthropic";import{randomUUID as lM}from"crypto";var xb=t=>e=>sM({baseURL:`https://api.momentic.ai/v1/llm/anthropic/${e}`,headers:{Authorization:`Bearer ${t}`},apiKey:t})(e);var ya=async({step:t,controller:e,storage:n,codeEvalTools:r,logger:o,socket:i,testContext:a,orgId:s})=>{let{results:l}=await cM({steps:[t],controller:e,storage:n,codeEvalTools:r,logger:o,socket:i,testContext:a,orgId:s});return l[0]},cM=async({steps:t,controller:e,storage:n,codeEvalTools:r,logger:o,socket:i,testContext:a,orgId:s})=>{let l={controller:e,storage:n,codeEvalTools:r,logger:o,context:a,billingReporter:new Uo};return un({listParams:{containerName:"copilot-steps",steps:t,tracer:new Tr({parentStep:null,parentTracer:null,socket:i})},fixtures:l,options:{collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},inputs:{orgId:s,runId:lM(),steps:t,testMetadata:null,orgSettings:{}},callbacks:{test:{},step:{}},work:{results:[],asyncTasks:[],state:{}}})};var dM=mt({schema:{name:"preview_preflight",description:"Resolve and validate locators without changing the page. If found, it will return the locator ID and HTML.",inputSchema:ba.object({description:ba.string().describe("Description of the element to preview.")})},handle:async({controller:t,logger:e,testContext:n},r,o)=>{o.setIncludeSnapshot();try{let i=await t.locateElement({description:r.description,disableCache:!0,skipWait:!0,logger:e,testContext:n});i.resolution.locator&&await Promise.all([t.browser.scrollIntoViewIfNeeded(i.resolution.locator),t.browser.highlight(i.resolution.locator)]),o.addResult(`Found element matching description: ${i.target.id}`),i.target.nodeOnlySerializedHtml&&o.addResult(`HTML: ${i.target.nodeOnlySerializedHtml}`);return}catch(i){o.addError(`Failed to find any element matching description: ${i}`)}}}),uM=mt({schema:{name:"preview_ensure",description:"Confirm page state.",inputSchema:ba.object({assertion:ba.string().describe("Assertion to confirm page state.")})},handle:async(t,e,n)=>{n.setIncludeSnapshot();let{logger:r,storage:o,controller:i,codeEvalTools:a,socket:s,orgId:l,testContext:c}=t,d={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.assertion,id:xl()},id:xl()},u=await ya({step:d,controller:i,storage:o,codeEvalTools:a,logger:r,socket:s,orgId:l,testContext:c});if(!u){n.addError("Assertion executed with unknown result.");return}if(u.status==="SUCCESS"){n.addResult(`Assertion is true: ${u.message}`);return}n.addError(`Assertion is false: ${u.message}`)}}),mM=mt({schema:{name:"preview_step",description:"Execute a step without adding it to the test.",inputSchema:ba.object({command:go})},handle:async(t,e,n)=>{n.setIncludeSnapshot(),n.setIncludeTestContext();let{logger:r,storage:o,controller:i,codeEvalTools:a,socket:s,orgId:l,testContext:c}=t;n.setIncludeSnapshot();let d={type:"PRESET_ACTION",command:{...e.command,id:xl()},id:xl()},u=await ya({step:d,controller:i,storage:o,codeEvalTools:a,logger:r,socket:s,orgId:l,testContext:c});if(!u){n.addError("Assertion executed with unknown result.");return}if(u.status==="SUCCESS"){n.addResult(`Assertion is true: ${u.message}`);return}n.addError(`Assertion is false: ${u.message}`)}}),Ib=[dM,uM,mM];import pM from"path";import{z as Il}from"zod";var gM=mt({schema:{name:"get_environment_variables",description:"Get the current environment variables.",inputSchema:Il.object({})},handle:async(t,e,n)=>{n.setIncludeTestContext()}}),hM=mt({schema:{name:"reset_session",description:"Reset the browser session. This will clear any authentication state and also navigate to the starting URL of the test.",inputSchema:Il.object({})},handle:async(t,e,n)=>{n.setIncludeTestContext(),n.setIncludeSnapshot(),await t.controller.browser.reset({})}}),fM=mt({schema:{name:"run_step",description:"Run the step in the test at the given index.",inputSchema:Il.object({index:Il.number()})},handle:async(t,e,n)=>{n.setIncludeTestContext(),n.setIncludeSnapshot();let{project:r,logger:o,testPath:i,storage:a,controller:s,codeEvalTools:l,socket:c,orgId:d,testContext:u}=t,m=te(r,o),p=(await Pt(pM.join(r.rootDir,i),o,m)).steps[e.index];if(!p){n.addError(`Step at index ${e.index} does not exist.`);return}let h=await ya({step:p,controller:s,storage:a,codeEvalTools:l,logger:o,socket:c,orgId:d,testContext:u});if(!h){n.addError(`Step at index ${e.index} executed with unknown result.`);return}if(h.status==="SUCCESS"){n.addResult(`Step at index ${e.index} executed successfully: ${h.message}`),h.data&&n.addResult(`Data: ${JSON.stringify(h.data,null,2)}`);return}n.addError(`Step at index ${e.index} failed: ${h.message}`)}}),Pb=[gM,hM,fM];import{randomUUID as wr}from"crypto";import Ta from"path";import{z as pn}from"zod";var SM=mt({schema:{name:"test_get",description:"Get test contents.",inputSchema:pn.object({})},handle:async(t,e,n)=>{n.setIncludeTest()}}),yM=mt({schema:{name:"test_insert_step",description:"Insert a step into the test.",inputSchema:pn.object({index:pn.number(),command:go})},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:i,socket:a}=t,s=te(r,o),l=await Pt(Ta.join(r.rootDir,i),o,s),c={type:"PRESET_ACTION",command:{...e.command,id:wr()},id:wr()};l.steps.splice(e.index,0,c);let{stepsToSave:d,moduleUpdates:u}=await ze({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{Ht({content:m,schemaVersion:ce,momenticFiles:s,project:r})}),It({relativeTestPath:i,steps:d,schemaVersion:ce,project:r}),a.emit("copilotStepsUpdated",l.steps)}}),bM=mt({schema:{name:"test_replace_step",description:"Replace a step in the test.",inputSchema:pn.object({index:pn.number(),command:go})},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:i,socket:a}=t,s=te(r,o),l=await Pt(Ta.join(r.rootDir,i),o,s),c={type:"PRESET_ACTION",command:{...e.command,id:wr()},id:wr()};l.steps.splice(e.index,1,c);let{stepsToSave:d,moduleUpdates:u}=await ze({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{Ht({content:m,schemaVersion:ce,momenticFiles:s,project:r})}),It({relativeTestPath:i,steps:d,schemaVersion:ce,project:r}),a.emit("copilotStepsUpdated",l.steps)}}),TM=mt({schema:{name:"test_remove_step",description:"Remove a step from the test.",inputSchema:pn.object({index:pn.number()})},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:i,socket:a}=t,s=te(r,o),l=await Pt(Ta.join(r.rootDir,i),o,s);l.steps.splice(e.index,1);let{stepsToSave:c,moduleUpdates:d}=await ze({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});d.forEach(u=>{Ht({content:u,schemaVersion:ce,momenticFiles:s,project:r})}),It({relativeTestPath:i,steps:c,schemaVersion:ce,project:r}),a.emit("copilotStepsUpdated",l.steps)}}),wM=mt({schema:{name:"test_splice_steps",description:"Splice steps in the test.",inputSchema:pn.object({startIndex:pn.number(),deleteCount:pn.number(),commands:go.array()})},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:i,socket:a}=t,s=te(r,o),l=await Pt(Ta.join(r.rootDir,i),o,s),c=e.commands.map(m=>({type:"PRESET_ACTION",command:{...m,id:wr()},id:wr()}));l.steps.splice(e.startIndex,e.deleteCount,...c);let{stepsToSave:d,moduleUpdates:u}=await ze({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{Ht({content:m,schemaVersion:ce,momenticFiles:s,project:r})}),It({relativeTestPath:i,steps:d,schemaVersion:ce,project:r}),a.emit("copilotStepsUpdated",l.steps)}}),EM=mt({schema:{name:"test_overwrite",description:"Overwrite the test with the given steps.",inputSchema:pn.object({commands:go.array()})},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:i,socket:a}=t,s=te(r,o),l=await Pt(Ta.join(r.rootDir,i),o,s),c=e.commands.map(m=>({type:"PRESET_ACTION",command:{...m,id:wr()},id:wr()}));l.steps=c;let{stepsToSave:d,moduleUpdates:u}=await ze({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{Ht({content:m,schemaVersion:ce,momenticFiles:s,project:r})}),It({relativeTestPath:i,steps:d,schemaVersion:ce,project:r}),a.emit("copilotStepsUpdated",l.steps)}}),Lb=[SM,yM,bM,TM,wM,EM];var Mb=[...Ab,...Pb,...Ib,...Lb];var Pl=new Cl;var pi=class extends Wo{constructor(n,r){super(n,r);this.client=n;this.orgId=r}async fetchTestMetadata(n,r){let o=ae(),a=te(o,r).tests[n];if(a)return Xs(a.relativePath,o)}async fetchApiTestMetadata(){throw new Error("API tests are not available in the desktop app")}async fetchEnvironment(n,r){let o=ae();return la(n,o,qr)}async fetchIconKnowledgeBase(n){try{return await this.client.fetchIconKnowledgeBase(n)}catch(r){return n.error({err:r},"Failed to fetch icon knowledge base"),null}}};import{randomUUID as CM}from"node:crypto";import{PostHog as RM}from"posthog-node";var Ll=class t{bindings;client;options;constructor(e,n={}){this.bindings=e,this.options=n,this.client=new RM("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...n})}async shutdown(){await this.client.shutdown()}identify(e){return this.bindings={...this.bindings,...e},this}child(e){return new t({...this.bindings,...e},this.options)}track(e,n){if(!Sp(this.bindings))return console.error(`Cannot track ${e.type} event without required bindings.`,this.bindings),this;let{type:r,...o}=e;return this.client.capture({distinctId:CM(),event:r,timestamp:n?.timestamp,properties:{...this.bindings,...o}}),this}};var wa=new Ll({platform:"local_app"},{flushAt:1,flushInterval:0});var Er=PM();Er.post("/",me(async(t,e)=>{let n;try{n=Zp.parse(t.body)}catch(u){e.status(400).json({error:`Invalid request body: ${u}`});return}try{Vr(n.name)}catch(u){e.status(400).json({error:u.message});return}let o={id:Nb(),name:n.name,description:n.description,baseUrl:n.baseUrl,schemaVersion:ce,advanced:{browserType:n.browserType??"Chromium",viewport:n.viewport??Ot},retries:0,steps:[]};n.environment&&(o.envs=[{name:n.environment,default:!0}]);let i=ae(),a=te(i,y);if(Object.values(a.tests).find(u=>u.name===n.name)){e.status(400).send(`A test with the name "${n.name}" already exists. Please use a different name.`);return}let l=ho.join(i.rootDir,...n.pathSegments||[]),c=await Af({test:o,name:n.name,folder:l}),d={...o,relativeFilePath:ho.relative(i.rootDir,c)};wa.track({type:"test_editor:test_create"}),e.status(201).json(d)}));Er.get("/:testPath",me(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r=ae(),o=te(r,y),i;try{i=await Pt(ho.join(r.rootDir,n),ut,o),e.status(200).json(i)}catch(a){e.status(400).send({error:a.message});return}(async()=>{try{let{stepsToSave:a,moduleUpdates:s}=await ze({stepLists:{steps:i.steps,beforeSteps:i.beforeSteps,afterSteps:i.afterSteps}});s.forEach(l=>{Ht({content:l,schemaVersion:ce,momenticFiles:o,project:r})}),It({relativeTestPath:n,steps:a,schemaVersion:ce,project:r})}catch(a){ut.error({err:a},"Failed to save migrated test to disk after initial fetch")}})()}));Er.patch("/:testPath/metadata",me(async(t,e)=>{if(!t.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=Qp.parse(t.body)}catch(i){e.status(400).json({error:`Invalid request body: ${i}`});return}let o={message:"ok",newRelativeTestPath:Fd(t.params.testPath,n,ae()).newRelativeTestPath};e.status(200).json(o)}));Er.patch("/:testPath",me(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=Jp.parse(t.body)}catch(g){e.status(400).json({error:`Invalid request body: ${g}`});return}let o=ae(),i=te(o,y),a;try{a=Xs(n,o)}catch(g){e.status(400).json({error:`Existing test file on disk is invalid: ${g}`});return}let{stepsToSave:s,moduleUpdates:l,cachesToSave:c}=await ze({stepLists:r.stepLists,cacheCreationParams:{testId:a.id,orgId:nn()}}),d=new Je({apiKey:kd(),baseUrl:ra(),logger:ut}),u=await fr(ut,d,o);await Zo({orgId:nn(),client:d,gitMetadata:u}).saveStepCacheEntries({logger:ut,testId:a.id,entries:c}),l.forEach(g=>{Ht({content:g,schemaVersion:r.schemaVersion,momenticFiles:i,project:o})}),It({relativeTestPath:n,steps:s,schemaVersion:r.schemaVersion,project:o}),e.status(201).json({message:"ok"})}));Er.patch("/:testPath/environments",me(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=og.parse(t.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}Fd(n,{envs:r.defaultEnv?[{name:r.defaultEnv,default:!0}]:[]},ae()),e.status(201).json({message:"ok"})}));Er.post("/:testPath/duplicate",me(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=eg.parse(t.body)}catch(f){e.status(400).json({error:`Invalid request body: ${f}`});return}try{Vr(r.name)}catch(f){e.status(400).json({error:f.message});return}let o=ae(),i=ho.join(o.rootDir,n);if(!Ob.existsSync(i)){e.status(404).json({error:"Test not found."});return}let a=te(o,y),s;try{s=await Pt(i,ut,a)}catch(f){e.status(400).send({error:f.message});return}let l=Nb(),c=Zt.parse({...s,name:r.name,id:l}),{stepsToSave:d}=await ze({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps},createNewCacheIds:!0,cacheCreationParams:{testId:l,orgId:nn()}}),u=jn({fileType:fe.TEST,...c,beforeSteps:d.beforeSteps??void 0,steps:d.steps,afterSteps:d.afterSteps??void 0}),m=ho.dirname(i),g=ho.join(m,`${r.name}.${st.TEST}`),p=LM.stringify(u);Ob.writeFileSync(g,p,"utf-8");let h={relativeFilePath:ho.relative(o.rootDir,g)};wa.track({type:"test_editor:test_create"}),e.status(201).json(h)}));Er.post("/:testPath/chat",me(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r=Pl.getLatestSession();if(!r){e.status(400).json({error:"No active session."});return}let{messages:o}=t.body,i=kd(),a=nn(),s=ra(),l=ae(),c=ut,d=new Je({apiKey:i,baseUrl:s,logger:c}),u=new pi(d,a),m=new hr(l.config),g=new pr({httpClient:new At({baseUrl:d.baseUrl,apiKey:d.apiKey,logger:c}),fakerSeed:l.config.advanced?.fakerConstantSeed?us:void 0}),p={project:l,apiKey:i,orgId:a,baseUrl:s,logger:c,storage:u,flagStore:m,codeEvalTools:g,testPath:n,testContext:r.context,controller:r.controller,socket:r.socket},h=Mb.reduce((b,{name:E,builder:v})=>(b[E]=v(p,new Al(p.controller.browser,p.testContext,p.project,p.logger,p.testPath)),b),{}),f=xb(i);xM({model:f("claude-opus-4-20250514"),stopWhen:AM(30),maxRetries:4,system:IM`
3915
+ `)}],isError:this._isError}}};import{z as bL}from"zod";import{tool as yL}from"ai";var mt=t=>({builder:(n,r)=>yL({description:t.schema.description,inputSchema:t.schema.inputSchema,execute:async o=>{try{await t.handle(n,o,r)}catch(a){r.addError(String(a))}return r.serialize()}}),name:t.schema.name});var TL=mt({schema:{name:"observe_page",description:"Observe the current page's accessibility snapshot.",inputSchema:bL.object({})},handle:async(t,e,n)=>{n.setIncludeSnapshot()}}),kb=[TL];import{randomUUID as _l}from"crypto";import{z as Ri}from"zod";import{z as wL}from"zod";var ho={id:!0,cache:!0},fo=wL.discriminatedUnion("type",[Or.omit(ho),Dr.omit(ho),kr.omit(ho),ir.omit(ho),ar.omit(ho),Nr.omit(ho),_r.omit(ho),gc.omit({id:!0}),wc.omit({id:!0}),xo.omit({id:!0}),Tc.omit({id:!0}),Ec.omit({id:!0}),hc.omit({id:!0})]);import{createAnthropic as EL}from"@ai-sdk/anthropic";import{randomUUID as RL}from"crypto";var _b=t=>e=>EL({baseURL:`https://api.momentic.ai/v1/llm/anthropic/${e}`,headers:{Authorization:`Bearer ${t}`},apiKey:t})(e);var Ei=async({step:t,controller:e,storage:n,codeEvalTools:r,logger:o,socket:a,testContext:i,orgId:s})=>{let{results:l}=await CL({steps:[t],controller:e,storage:n,codeEvalTools:r,logger:o,socket:a,testContext:i,orgId:s});return l[0]},CL=async({steps:t,controller:e,storage:n,codeEvalTools:r,logger:o,socket:a,testContext:i,orgId:s})=>{let l={controller:e,storage:n,codeEvalTools:r,logger:o,context:i,billingReporter:new zo};return mn({listParams:{containerName:"copilot-steps",steps:t,tracer:new Rr({parentStep:null,parentTracer:null,socket:a})},fixtures:l,options:{collectDebugData:!1,reinitializeBrowser:!1,disableHealing:!0},inputs:{orgId:s,runId:RL(),steps:t,testMetadata:null,orgSettings:{}},callbacks:{test:{},step:{}},work:{results:[],asyncTasks:[],state:{}}})};var vL=mt({schema:{name:"preview_preflight",description:"Resolve and validate locators without changing the page. If found, it will return the locator ID and HTML.",inputSchema:Ri.object({description:Ri.string().describe("Description of the element to preview.")})},handle:async({controller:t,logger:e,testContext:n},r,o)=>{o.setIncludeSnapshot();try{let a=await t.locateElement({description:r.description,disableCache:!0,skipWait:!0,logger:e,testContext:n});a.resolution.locator&&await Promise.all([t.browser.scrollIntoViewIfNeeded(a.resolution.locator),t.browser.highlight(a.resolution.locator)]),o.addResult(`Found element matching description: ${a.target.id}`),a.target.nodeOnlySerializedHtml&&o.addResult(`HTML: ${a.target.nodeOnlySerializedHtml}`);return}catch(a){o.addError(`Failed to find any element matching description: ${a}`)}}}),AL=mt({schema:{name:"preview_ensure",description:"Confirm page state.",inputSchema:Ri.object({assertion:Ri.string().describe("Assertion to confirm page state.")})},handle:async(t,e,n)=>{n.setIncludeSnapshot();let{logger:r,storage:o,controller:a,codeEvalTools:i,socket:s,orgId:l,testContext:c}=t,d={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.assertion,id:_l()},id:_l()},u=await Ei({step:d,controller:a,storage:o,codeEvalTools:i,logger:r,socket:s,orgId:l,testContext:c});if(!u){n.addError("Assertion executed with unknown result.");return}if(u.status==="SUCCESS"){n.addResult(`Assertion is true: ${u.message}`);return}n.addError(`Assertion is false: ${u.message}`)}}),xL=mt({schema:{name:"preview_step",description:"Execute a step without adding it to the test.",inputSchema:Ri.object({command:fo})},handle:async(t,e,n)=>{n.setIncludeSnapshot(),n.setIncludeTestContext();let{logger:r,storage:o,controller:a,codeEvalTools:i,socket:s,orgId:l,testContext:c}=t;n.setIncludeSnapshot();let d={type:"PRESET_ACTION",command:{...e.command,id:_l()},id:_l()},u=await Ei({step:d,controller:a,storage:o,codeEvalTools:i,logger:r,socket:s,orgId:l,testContext:c});if(!u){n.addError("Assertion executed with unknown result.");return}if(u.status==="SUCCESS"){n.addResult(`Assertion is true: ${u.message}`);return}n.addError(`Assertion is false: ${u.message}`)}}),Db=[vL,AL,xL];import IL from"path";import{z as Dl}from"zod";var PL=mt({schema:{name:"get_environment_variables",description:"Get the current environment variables.",inputSchema:Dl.object({})},handle:async(t,e,n)=>{n.setIncludeTestContext()}}),ML=mt({schema:{name:"reset_session",description:"Reset the browser session. This will clear any authentication state and also navigate to the starting URL of the test.",inputSchema:Dl.object({})},handle:async(t,e,n)=>{n.setIncludeTestContext(),n.setIncludeSnapshot(),await t.controller.browser.reset({})}}),LL=mt({schema:{name:"run_step",description:"Run the step in the test at the given index.",inputSchema:Dl.object({index:Dl.number()})},handle:async(t,e,n)=>{n.setIncludeTestContext(),n.setIncludeSnapshot();let{project:r,logger:o,testPath:a,storage:i,controller:s,codeEvalTools:l,socket:c,orgId:d,testContext:u}=t,m=te(r,o),g=(await Mt(IL.join(r.rootDir,a),o,m)).steps[e.index];if(!g){n.addError(`Step at index ${e.index} does not exist.`);return}let h=await Ei({step:g,controller:s,storage:i,codeEvalTools:l,logger:o,socket:c,orgId:d,testContext:u});if(!h){n.addError(`Step at index ${e.index} executed with unknown result.`);return}if(h.status==="SUCCESS"){n.addResult(`Step at index ${e.index} executed successfully: ${h.message}`),h.data&&n.addResult(`Data: ${JSON.stringify(h.data,null,2)}`);return}n.addError(`Step at index ${e.index} failed: ${h.message}`)}}),Fb=[PL,ML,LL];import{randomUUID as Cr}from"crypto";import Ci from"path";import{z as gn}from"zod";var OL=mt({schema:{name:"test_get",description:"Get test contents.",inputSchema:gn.object({})},handle:async(t,e,n)=>{n.setIncludeTest()}}),NL=mt({schema:{name:"test_insert_step",description:"Insert a step into the test.",inputSchema:gn.object({index:gn.number(),command:fo})},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:a,socket:i}=t,s=te(r,o),l=await Mt(Ci.join(r.rootDir,a),o,s),c={type:"PRESET_ACTION",command:{...e.command,id:Cr()},id:Cr()};l.steps.splice(e.index,0,c);let{stepsToSave:d,moduleUpdates:u}=await He({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{$t({content:m,schemaVersion:se,momenticFiles:s,project:r})}),Pt({relativeTestPath:a,steps:d,schemaVersion:se,project:r}),i.emit("copilotStepsUpdated",l.steps)}}),kL=mt({schema:{name:"test_replace_step",description:"Replace a step in the test.",inputSchema:gn.object({index:gn.number(),command:fo})},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:a,socket:i}=t,s=te(r,o),l=await Mt(Ci.join(r.rootDir,a),o,s),c={type:"PRESET_ACTION",command:{...e.command,id:Cr()},id:Cr()};l.steps.splice(e.index,1,c);let{stepsToSave:d,moduleUpdates:u}=await He({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{$t({content:m,schemaVersion:se,momenticFiles:s,project:r})}),Pt({relativeTestPath:a,steps:d,schemaVersion:se,project:r}),i.emit("copilotStepsUpdated",l.steps)}}),_L=mt({schema:{name:"test_remove_step",description:"Remove a step from the test.",inputSchema:gn.object({index:gn.number()})},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:a,socket:i}=t,s=te(r,o),l=await Mt(Ci.join(r.rootDir,a),o,s);l.steps.splice(e.index,1);let{stepsToSave:c,moduleUpdates:d}=await He({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});d.forEach(u=>{$t({content:u,schemaVersion:se,momenticFiles:s,project:r})}),Pt({relativeTestPath:a,steps:c,schemaVersion:se,project:r}),i.emit("copilotStepsUpdated",l.steps)}}),DL=mt({schema:{name:"test_splice_steps",description:"Splice steps in the test.",inputSchema:gn.object({startIndex:gn.number(),deleteCount:gn.number(),commands:fo.array()})},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:a,socket:i}=t,s=te(r,o),l=await Mt(Ci.join(r.rootDir,a),o,s),c=e.commands.map(m=>({type:"PRESET_ACTION",command:{...m,id:Cr()},id:Cr()}));l.steps.splice(e.startIndex,e.deleteCount,...c);let{stepsToSave:d,moduleUpdates:u}=await He({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{$t({content:m,schemaVersion:se,momenticFiles:s,project:r})}),Pt({relativeTestPath:a,steps:d,schemaVersion:se,project:r}),i.emit("copilotStepsUpdated",l.steps)}}),FL=mt({schema:{name:"test_overwrite",description:"Overwrite the test with the given steps.",inputSchema:gn.object({commands:fo.array()})},handle:async(t,e,n)=>{n.setIncludeTest();let{project:r,logger:o,testPath:a,socket:i}=t,s=te(r,o),l=await Mt(Ci.join(r.rootDir,a),o,s),c=e.commands.map(m=>({type:"PRESET_ACTION",command:{...m,id:Cr()},id:Cr()}));l.steps=c;let{stepsToSave:d,moduleUpdates:u}=await He({stepLists:{steps:l.steps,beforeSteps:l.beforeSteps,afterSteps:l.afterSteps}});u.forEach(m=>{$t({content:m,schemaVersion:se,momenticFiles:s,project:r})}),Pt({relativeTestPath:a,steps:d,schemaVersion:se,project:r}),i.emit("copilotStepsUpdated",l.steps)}}),Ub=[OL,NL,kL,_L,DL,FL];var Bb=[...kb,...Fb,...Db,...Ub];var Fl=new Ll;var ha=class extends qo{constructor(n,r){super(n,r);this.client=n;this.orgId=r}async fetchTestMetadata(n,r){let o=ae(),i=te(o,r).tests[n];if(i)return ol(i.relativePath,o)}async fetchApiTestMetadata(){throw new Error("API tests are not available in the desktop app")}async fetchEnvironment(n,r){let o=ae();return ui(n,o,Xr)}async fetchIconKnowledgeBase(n){try{return await this.client.fetchIconKnowledgeBase(n)}catch(r){return n.error({err:r},"Failed to fetch icon knowledge base"),null}}};import{randomUUID as UL}from"node:crypto";import{PostHog as BL}from"posthog-node";var Ul=class t{bindings;client;options;constructor(e,n={}){this.bindings=e,this.options=n,this.client=new BL("phc_oy1FexHsc0S3axxOMXCm46yZsW35zROAoV4SOzpDSXH",{host:"https://us.i.posthog.com",...n})}async shutdown(){await this.client.shutdown()}identify(e){return this.bindings={...this.bindings,...e},this}child(e){return new t({...this.bindings,...e},this.options)}track(e,n){if(!vp(this.bindings))return console.error(`Cannot track ${e.type} event without required bindings.`,this.bindings),this;let{type:r,...o}=e;return this.client.capture({distinctId:UL(),event:r,timestamp:n?.timestamp,properties:{...this.bindings,...o}}),this}};var vi=new Ul({platform:"local_app"},{flushAt:1,flushInterval:0});var vr=GL();vr.post("/",ce(async(t,e)=>{let n;try{n=lg.parse(t.body)}catch(u){e.status(400).json({error:`Invalid request body: ${u}`});return}try{Yr(n.name)}catch(u){e.status(400).json({error:u.message});return}let o={id:Hb(),name:n.name,description:n.description,baseUrl:n.baseUrl,schemaVersion:se,advanced:{browserType:n.browserType??"Chromium",viewport:n.viewport??Nt},retries:0,steps:[]};n.environment&&(o.envs=[{name:n.environment,default:!0}]);let a=ae(),i=te(a,S);if(Object.values(i.tests).find(u=>u.name===n.name)){e.status(400).send(`A test with the name "${n.name}" already exists. Please use a different name.`);return}let l=So.join(a.rootDir,...n.pathSegments||[]),c=await Df({test:o,name:n.name,folder:l}),d={...o,relativeFilePath:So.relative(a.rootDir,c)};vi.track({type:"test_editor:test_create"}),e.status(201).json(d)}));vr.get("/:testPath",ce(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r=ae(),o=te(r,S),a;try{a=await Mt(So.join(r.rootDir,n),ut,o),e.status(200).json(a)}catch(i){e.status(400).send({error:i.message});return}(async()=>{try{let{stepsToSave:i,moduleUpdates:s}=await He({stepLists:{steps:a.steps,beforeSteps:a.beforeSteps,afterSteps:a.afterSteps}});s.forEach(l=>{$t({content:l,schemaVersion:se,momenticFiles:o,project:r})}),Pt({relativeTestPath:n,steps:i,schemaVersion:se,project:r})}catch(i){ut.error({err:i},"Failed to save migrated test to disk after initial fetch")}})()}));vr.patch("/:testPath/metadata",ce(async(t,e)=>{if(!t.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let n;try{n=sg.parse(t.body)}catch(a){e.status(400).json({error:`Invalid request body: ${a}`});return}let o={message:"ok",newRelativeTestPath:Gd(t.params.testPath,n,ae()).newRelativeTestPath};e.status(200).json(o)}));vr.patch("/:testPath",ce(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=ig.parse(t.body)}catch(p){e.status(400).json({error:`Invalid request body: ${p}`});return}let o=ae(),a=te(o,S),i;try{i=ol(n,o)}catch(p){e.status(400).json({error:`Existing test file on disk is invalid: ${p}`});return}let{stepsToSave:s,moduleUpdates:l,cachesToSave:c}=await He({stepLists:r.stepLists,cacheCreationParams:{testId:i.id,orgId:rn()}}),d=new Je({apiKey:Hd(),baseUrl:ii(),logger:ut}),u=await Sr(ut,d,o);await ta({orgId:rn(),client:d,gitMetadata:u}).saveStepCacheEntries({logger:ut,testId:i.id,entries:c}),l.forEach(p=>{$t({content:p,schemaVersion:r.schemaVersion,momenticFiles:a,project:o})}),Pt({relativeTestPath:n,steps:s,schemaVersion:r.schemaVersion,project:o}),e.status(201).json({message:"ok"})}));vr.patch("/:testPath/environments",ce(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=pg.parse(t.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}Gd(n,{envs:r.defaultEnv?[{name:r.defaultEnv,default:!0}]:[]},ae()),e.status(201).json({message:"ok"})}));vr.post("/:testPath/duplicate",ce(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r;try{r=cg.parse(t.body)}catch(f){e.status(400).json({error:`Invalid request body: ${f}`});return}try{Yr(r.name)}catch(f){e.status(400).json({error:f.message});return}let o=ae(),a=So.join(o.rootDir,n);if(!zb.existsSync(a)){e.status(404).json({error:"Test not found."});return}let i=te(o,S),s;try{s=await Mt(a,ut,i)}catch(f){e.status(400).send({error:f.message});return}let l=Hb(),c=en.parse({...s,name:r.name,id:l}),{stepsToSave:d}=await He({stepLists:{steps:s.steps,beforeSteps:s.beforeSteps,afterSteps:s.afterSteps},createNewCacheIds:!0,cacheCreationParams:{testId:l,orgId:rn()}}),u=Gn({fileType:pe.TEST,...c,beforeSteps:d.beforeSteps??void 0,steps:d.steps,afterSteps:d.afterSteps??void 0}),m=So.dirname(a),p=So.join(m,`${r.name}.${st.TEST}`),g=WL.stringify(u);zb.writeFileSync(p,g,"utf-8");let h={relativeFilePath:So.relative(o.rootDir,p)};vi.track({type:"test_editor:test_create"}),e.status(201).json(h)}));vr.post("/:testPath/chat",ce(async(t,e)=>{let{testPath:n}=t.params;if(!n){e.status(400).json({error:"Missing testPath in url path."});return}let r=Fl.getLatestSession();if(!r){e.status(400).json({error:"No active session."});return}let{messages:o}=t.body,a=Hd(),i=rn(),s=ii(),l=ae(),c=ut,d=new Je({apiKey:a,baseUrl:s,logger:c}),u=new ha(d,i),m=new fr(l.config),p=new gr({httpClient:new xt({baseUrl:d.baseUrl,apiKey:d.apiKey,logger:c}),fakerSeed:l.config.advanced?.fakerConstantSeed?gs:void 0}),g={project:l,apiKey:a,orgId:i,baseUrl:s,logger:c,storage:u,flagStore:m,codeEvalTools:p,testPath:n,testContext:r.context,controller:r.controller,socket:r.socket},h=Bb.reduce((b,{name:w,builder:C})=>(b[w]=C(g,new kl(g.controller.browser,g.testContext,g.project,g.logger,g.testPath)),b),{}),f=_b(a);$L({model:f("claude-opus-4-20250514"),stopWhen:HL(30),maxRetries:4,system:jL`
3916
3916
  <core-identity>
3917
3917
  You are the Momentic Copilot. You are an experienced SDET who is building and editing a Momentic browser E2E test. Instead of CSS selectors, Momentic uses natural language descriptions to identify elements. Your responses must be specific, accurate, and concise.
3918
3918
  </core-identity>
@@ -3958,27 +3958,27 @@ ${t}`;default:return t}}var SL=15;async function wl({command:t,aiPageFiltering:e
3958
3958
  - Never insert destructive actions (e.g., mass delete) unless explicitly asked.
3959
3959
  - Keep edits scoped to the user's intent; do not optimize unrelated steps.
3960
3960
  </safety>
3961
- `,messages:vM(o),tools:h}).pipeUIMessageStreamToResponse(e,{onError:b=>b instanceof Error?b.message:String(b)})}));var kb=Er;var Ea=class{async prepareGoldenScreenshotForComparison(e,n,r){return await new ii(ae(),!1).prepareGoldenScreenshotForComparison(e,n,r)}};async function Ub(t){let{momenticServerUrl:e,apiKey:n,serverPort:r,staticDir:o,devicePixelRatio:i,alwaysSaveCache:a,noCache:s,initialProject:l}=t;e&&Tf(e),await wf(n);let c=nn(),d=Vs();wa.identify({user_id:d,org_id:c});let u=t.logger??ut;u=u.child({orgId:c,userId:d}),u.debug({params:t},"Desktop server init and api key check done");let m=FM(o,r,u),g=`http://localhost:${r}`;y.info(`Desktop server is running at ${g}`),qs(l,v=>ct({configFilePath:v})),await new Promise(v=>{try{m.listen(r,()=>{u.info(`Desktop server is running at ${g}`),v()})}catch(R){R.message.includes("EADDRINUSE")?Bb(r):y.error(`An unexpected error occurred while starting the server: ${R.message}`),process.exit(1)}});let h={type:"API_KEY",baseUrl:ra(),apiKey:n,logger:u},f=async()=>{let v=ae();return new qo(v.config.ai?.agentConfig,h)},S=async()=>new Ko(h,await f()),b=new Je(h),E=new Ea;fb({baseServer:m,getOrgId:async()=>nn(),generatorFactory:f,enricherFactory:S,cacheStorageFactory:async v=>{let R=ae(),C=await fr(u,b,R);return Zo({orgId:v,client:b,gitMetadata:C,alwaysSaveCache:a,noCache:s})},branchGetter:async()=>{try{return(await qd(u))?.gitBranchName}catch(v){u.error({err:v},"Failed to get environment git metadata");return}},flagStoreFactory:async v=>{let R=ae();return new hr(R.config)},settingsFactory:async()=>{let v=ae();return{ai:{},browser:{},...v.config}},storageFactory:async v=>new pi(b,v),logger:u,devicePixelRatio:i,authorization:h,visualDiffScreenshotStorage:E,globalE2eStateManager:Pl})}var Fb="25mb";function FM(t,e,n){let r=Db();r.use(MM()),r.use(_b.json({limit:Fb})),r.use(_b.urlencoded({extended:!1,limit:Fb}));let o=kM();if(o.use("/tests",kb),o.use("/modules",Sb),o.use("/environments",Tb),o.use("/projects",Cb),o.use("/folders",Dd),o.use("/settings",vb),o.use("/identify",Eb),o.use("/entities",bb),r.use("/api",o),r.use((a,s,l)=>{a.path!=="/healthcheck"&&!a.path.startsWith("/assets")&&n.debug({url:a.url,path:a.path,query:a.query,method:a.method,body:a.body,headers:a.rawHeaders,client:a.ip},"Received desktop-server request"),s.on("close",()=>{s.statusCode>=400&&n.error({url:a.url,method:a.method,statusCode:s.statusCode},"Request completed in error")}),l()}),r.use((a,s,l,c)=>{if(a instanceof Error&&a.message.includes("BadRequestError: request aborted")){l.status(400).send("Client disconnected");return}n.error({stack:a.stack,msg:a.message,err:a,url:s.url,method:s.method},"Unhandled exception leading to 500 on desktop-server"),y.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${a.message}
3962
- ${a.stack}`),l.status(500).send(`Internal Server Error: ${a.message}`)}),t){let a=Db.static(t,{setHeaders:s=>{s.setHeader("Cache-Control","no-cache")},redirect:!1});r.use(a),r.use("*",(s,l)=>{l.sendFile(DM.join(t,"index.html"))})}let i=_M.createServer(r);return i.once("error",a=>{"code"in a&&a.code==="EADDRINUSE"?(Bb(e),process.exit(1)):console.error("An unexpected server error occurred:",a.message)}),i}NM.setMaxListeners(50);process.on("warning",t=>{ut.warn({err:t},`Node warning received on desktop-server: ${t.message}`)});process.on("uncaughtException",t=>{ut.error({err:t},"Uncaught exception on desktop-server"),y.error(`Oh no! The Momentic desktop app encountered a fatal error \u{1F61E}. Error logs: ${t.message}`)});process.on("unhandledRejection",(t,e)=>{ut.error({reason:`${t}`,stack:t?.stack},"Uncaught exception on desktop-server (promise rejection)"),y.error(`Oh no! The Momentic desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${t}`)});function Bb(t){y.error(OM`Port ${t} is already in use by another process. Please close the other process and try again.
3961
+ `,messages:zL(o),tools:h}).pipeUIMessageStreamToResponse(e,{onError:b=>b instanceof Error?b.message:String(b)})}));var $b=vr;var Ai=class{async prepareGoldenScreenshotForComparison(e,n,r){return await new sa(ae(),!1).prepareGoldenScreenshotForComparison(e,n,r)}};async function Vb(t){let{momenticServerUrl:e,apiKey:n,serverPort:r,staticDir:o,devicePixelRatio:a,alwaysSaveCache:i,noCache:s,initialProject:l}=t;e&&Mf(e),await Lf(n);let c=rn(),d=el();vi.identify({user_id:d,org_id:c});let u=t.logger??ut;u=u.child({orgId:c,userId:d}),u.debug({params:t},"Desktop server init and api key check done");let m=QL(o,r,u),p=`http://localhost:${r}`;S.info(`Desktop server is running at ${p}`),tl(l,C=>ct({configFilePath:C})),await new Promise(C=>{try{m.listen(r,()=>{u.info(`Desktop server is running at ${p}`),C()})}catch(v){v.message.includes("EADDRINUSE")?qb(r):S.error(`An unexpected error occurred while starting the server: ${v.message}`),process.exit(1)}});let h={type:"API_KEY",baseUrl:ii(),apiKey:n,logger:u},f=async()=>{let C=ae();return new Yo(C.config.ai?.agentConfig,h)},y=async()=>new Xo(h,await f()),b=new Je(h),w=new Ai;Cb({baseServer:m,getOrgId:async()=>rn(),generatorFactory:f,enricherFactory:y,cacheStorageFactory:async C=>{let v=ae(),R=await Sr(u,b,v);return ta({orgId:C,client:b,gitMetadata:R,alwaysSaveCache:i,noCache:s})},branchGetter:async()=>{try{return(await eu(u))?.gitBranchName}catch(C){u.error({err:C},"Failed to get environment git metadata");return}},flagStoreFactory:async C=>{let v=ae();return new fr(v.config)},settingsFactory:async()=>{let C=ae();return{ai:{},browser:{},...C.config}},storageFactory:async C=>new ha(b,C),logger:u,devicePixelRatio:a,authorization:h,visualDiffScreenshotStorage:w,globalE2eStateManager:Fl})}var Wb="25mb";function QL(t,e,n){let r=Gb();r.use(VL()),r.use(jb.json({limit:Wb})),r.use(jb.urlencoded({extended:!1,limit:Wb}));let o=YL();if(o.use("/tests",$b),o.use("/modules",vb),o.use("/environments",Ib),o.use("/projects",Lb),o.use("/folders",jd),o.use("/settings",Nb),o.use("/identify",Mb),o.use("/entities",xb),r.use("/api",o),r.use((i,s,l)=>{i.path!=="/healthcheck"&&!i.path.startsWith("/assets")&&n.debug({url:i.url,path:i.path,query:i.query,method:i.method,body:i.body,headers:i.rawHeaders,client:i.ip},"Received desktop-server request"),s.on("close",()=>{s.statusCode>=400&&n.error({url:i.url,method:i.method,statusCode:s.statusCode},"Request completed in error")}),l()}),r.use((i,s,l,c)=>{if(i instanceof Error&&i.message.includes("BadRequestError: request aborted")){l.status(400).send("Client disconnected");return}n.error({stack:i.stack,msg:i.message,err:i,url:s.url,method:s.method},"Unhandled exception leading to 500 on desktop-server"),S.error(`Oh no! We seem to have hit an unexpected snag \u{1F61E}. Please contact Momentic Support with the following error: ${i.message}
3962
+ ${i.stack}`),l.status(500).send(`Internal Server Error: ${i.message}`)}),t){let i=Gb.static(t,{setHeaders:s=>{s.setHeader("Cache-Control","no-cache")},redirect:!1});r.use(i),r.use("*",(s,l)=>{l.sendFile(JL.join(t,"index.html"))})}let a=XL.createServer(r);return a.once("error",i=>{"code"in i&&i.code==="EADDRINUSE"?(qb(e),process.exit(1)):console.error("An unexpected server error occurred:",i.message)}),a}KL.setMaxListeners(50);process.on("warning",t=>{ut.warn({err:t},`Node warning received on desktop-server: ${t.message}`)});process.on("uncaughtException",t=>{ut.error({err:t},"Uncaught exception on desktop-server"),S.error(`Oh no! The Momentic desktop app encountered a fatal error \u{1F61E}. Error logs: ${t.message}`)});process.on("unhandledRejection",(t,e)=>{ut.error({reason:`${t}`,stack:t?.stack},"Uncaught exception on desktop-server (promise rejection)"),S.error(`Oh no! The Momentic desktop app encountered an asynchronous error \u{1F61E}. Error logs: ${t}`)});function qb(t){S.error(qL`Port ${t} is already in use by another process. Please close the other process and try again.
3963
3963
  Using Bash on MacOS or Linux:
3964
3964
  lsof -t -i :58888 | xargs kill -9
3965
3965
 
3966
3966
  Using Command Prompt on Windows:
3967
3967
  for /f "tokens=5" %a in ('netstat -ano ^| findstr :58888') do taskkill /PID %a /F
3968
- `)}import $O from"events";import Yl from"fs";import jO from"open";import{cpus as HT}from"os";import Kl from"path";import{fileURLToPath as GO}from"url";import UM from"diff-lines";import{gt as BM}from"semver";async function zb({test:t,fragment:e,entities:n,client:r,logger:o,yes:i}){BM(e.schemaVersion,ce)&&(y.error(`This version of the CLI does not support the schema version of the fragment (${e.schemaVersion}). Please update to the latest version of the CLI and retry this command.`),process.exit(1)),Ih(e.steps).forEach(p=>{n.modules[p]||(y.error(`The test patch contains a module with id ${p} that could not be found in the current project. This suggests that either this test patch or your local file system may be out of date.`),process.exit(1))}),e.createdAt.getTime()<Date.now()-7*24*60*60*1e3&&!i&&!await bt("The test patch you are applying is more than 7 days old. Are you sure you want to continue?",!0)&&process.exit(1);let s=t.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<s&&!i&&!await bt("The test patch you are applying was created before the test was last updated. Are you sure you want to continue?",!0)&&process.exit(1);let l=no(t.fullFilePath,o,n),c=l.steps;if(!Array.isArray(c))throw new Error(`Test ${t.fullFilePath} is missing steps array`);let d,u;if(e.schemaVersion!==ce){let{steps:p,newVersion:h}=await ea({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:y});d=h,u=$e.array().parse(p)}else u=$e.array().parse(e.steps);let{stepsToSave:m}=await ze({stepLists:{steps:u}});m.beforeSteps=l.beforeSteps??void 0,m.afterSteps=l.afterSteps??void 0;let g=UM(JSON.stringify(c,void 0,2),JSON.stringify(m,void 0,2),{n_surrounding:5});y.dimmed("=".repeat(30)),y.dimmed(g),y.dimmed("=".repeat(30)),y.dimmed(""),d&&y.warn(`If this patch is applied, your test will also be automatically upgraded to the latest schema version (${d}). Schema upgrades have no impact on functionality, although you may notice minor differences in the test YAML.`),!i&&!await bt("Do you want to apply this patch?")&&(y.dimmed("Cancelled."),process.exit(1)),It({relativeTestPath:t.relativePath,steps:m,schemaVersion:d??e.schemaVersion,project:n.project}),y.success("Patch applied successfully."),await r.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{randomUUID as jt}from"crypto";import{z as Hb}from"zod";function Ca(t){return Hb.string().uuid().safeParse(t).success}async function Ml({fix:t,project:e}){let n=te(e,y),r=Object.values(n.tests),o={},i={},a=new Set,s={},l=new Set,c=0;for(let u of r)try{let m=no(u.fullFilePath,X,n),g=!1,p=!1;Ca(u.id)||(y.error(`Test '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${u.id}'`),c++,p=!0,t&&(u.id=jt(),g=!0)),n.duplicateEntities[u.id]&&(y.error(`Test '${u.name}' (${u.relativePath}) has a duplicate ID: '${u.id}'`),c++,p=!0,t&&(u.id=jt(),g=!0));let h=m.steps;if(!h||h.length===0||!Array.isArray(h)){y.debug(`Test ${u.name} (${u.relativePath}) has no steps, skipping...`);continue}let f=St.parse(m),S=await Jr(f,h,y);S.steps=S.steps.map((b,E)=>{b.id||(y.error(`Step ${E} in test '${u.name}' (${u.relativePath}) does not have an ID`),p=!0,t&&(g=!0,b.id=jt())),Ca(b.id)||(y.error(`Step ${E} in test '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${b.id}'`),c++,p=!0,t&&(g=!0,b.id=jt()));let v=o[b.id]?.testId,R=o[b.id]?.testRelativePath;if(v?(c++,p=!0,v===u.id?y.error(`Multiple steps in the test '${u.name}' (${u.relativePath}) have the same ID '${b.id}'`):y.error(`Step ${E} in test '${u.name}' (${u.relativePath}) has the ID ${b.id} which is duplicated in ${R}`),t&&(g=!0,b.id=jt())):o[b.id]={testId:u.id,testRelativePath:u.relativePath},b.type==="PRESET_ACTION"){let C=b.command.id;Ca(C)||(y.error(`Command ${E} in test '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${C}'`),c++,p=!0,t&&(g=!0,b.command.id=jt()));let x=i[C]?.testId,L=i[C]?.testRelativePath;x?(c++,p=!0,x===u.id?y.error(`Multiple commands in the test '${u.name}' (${u.relativePath}) have the same ID '${C}'`):y.error(`Command ${E} in test '${u.name}' (${u.relativePath}) has the ID ${C} which is duplicated in test ${L}`),t&&(g=!0,b.command.id=jt())):i[C]={testId:u.id,testRelativePath:u.relativePath}}return Le.parse(b)}),p&&y.dimmed("=".repeat(80)),g&&t&&(It({relativeTestPath:u.relativePath,steps:{beforeSteps:m.beforeSteps,steps:S.steps,afterSteps:m.afterSteps},schemaVersion:ce,project:e}),a.add(u.fullFilePath))}catch(m){y.error({err:m},`Failed to parse test ${u.name} (${u.relativePath})`);continue}let d=Object.values(n.modules);for(let u of d)try{let m=!1,g=!1;Ca(u.id)||(y.error(`Module '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${u.id}'`),c++,g=!0,t&&(u.id=jt(),m=!0)),n.duplicateEntities[u.id]&&(y.error(`Module '${u.name}' (${u.relativePath}) has a duplicate ID: '${u.id}'`),c++,g=!0,t&&(u.id=jt(),m=!0));let p=Gn(u.fullFilePath,y),h=p.steps;if(!h||h.length===0||!Array.isArray(h)){y.debug(`Module ${u.name} (${u.relativePath}) has no steps, skipping...`);continue}let f,S;try{let E=await Jr({id:p.moduleId,schemaVersion:p.schemaVersion},p.steps,y);f=E.steps,S=E.newVersion}catch(E){y.error({err:E},`Failed to migrate module ${u.name} (${u.relativePath})`);continue}let b=f.map((E,v)=>{if(Hb.string().uuid().safeParse(E.id)||(y.error(`Step ${v} in module '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${E.id}'`),c++,g=!0,t&&(m=!0,E.id=jt())),o[E.id]?.testId){let C=o[E.id]?.testRelativePath;c++,g=!0,y.error(`Step ${v} in module '${u.name}' (${u.relativePath}) has the ID ${E.id} which is duplicated in test ${C}`),t&&(m=!0,E.id=jt())}if(E.type==="PRESET_ACTION"){let C=E.command.id;Ca(C)||(y.error(`Command ${v} in module '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${C}'`),c++,g=!0,t&&(m=!0,E.command.id=jt()));let x=i[C],L=s[C];x||L?(c++,g=!0,L?.moduleId===u.id?y.error(`Multiple commands in module '${u.name}' (${u.relativePath}) have the same ID '${C}'`):x?y.error(`Command in module '${u.name}' (${u.relativePath}) has the ID ${C} which is duplicated in test ${x.testRelativePath}`):y.error(`Command ${v} in module '${u.name}' (${u.relativePath}) has the ID ${C} which is duplicated in module ${L.moduleRelativePath}`),t&&(m=!0,E.command.id=jt())):s[C]={moduleId:u.id,moduleRelativePath:u.relativePath}}return Le.parse(E)});g&&y.dimmed("=".repeat(80)),m&&t&&(Ht({content:{...p,steps:b},schemaVersion:S,momenticFiles:n,project:e,forceSaveOnNoDiffs:!0}),l.add(u.fullFilePath))}catch(m){y.error({err:m},`Failed to parse module ${u.name} (${u.relativePath})`);continue}return{errors:c,modifiedTestFilePaths:a,modifiedModuleFilePaths:l}}async function $b({fix:t,project:e}){let{errors:n,modifiedTestFilePaths:r,modifiedModuleFilePaths:o}=await Ml({fix:t,project:e});n>0?(y.error(`Found errors in ${n} steps`),t?(y.warn(`Modified the following test files:
3969
- ${[...r].map(i=>`${Ke}- ${i}`).join(`
3970
- `)}`),o.size>0&&y.warn(`Modified the following module files:
3971
- ${[...o].map(i=>`${Ke}- ${i}`).join(`
3972
- `)}`)):y.warn("To fix these errors automatically, re-run this check with the --fix flag and then commit the resulting changes"),process.exit(1)):(y.success("No duplicates detected. All test, module, step and command IDs are unique."),process.exit(0))}async function jb({project:t}){let e=te(t,y),n=Object.values(e.tests),r=await Ys(e,X),o={},i={},a=new Set,s=new Set;for(let c of n)o[c.name]?i[c.name]?i[c.name].push(c.fullFilePath):i[c.name]=[o[c.name],c.fullFilePath]:o[c.name]=c.fullFilePath;for(let c of r)s.has(c.name)&&a.add(c.name),s.add(c.name);if(Object.entries(i).length>0||a.size>0){for(let[c,d]of Object.entries(i))for(let u of d)y.error(`Test Name ${c} is duplicated in ${u}`);for(let c of a)y.error(`Module name ${c} is duplicated in your project`);process.exit(1)}y.success("No duplicates detected. All test and module names are unique."),process.exit(0)}import{cloneDeep as zM}from"lodash-es";async function Gb({client:t,skipPrompts:e,project:n}){let r=await t.getAllEnvironments(),o=zM(n.config);o.environments||(o.environments=[]);for(let i of r){let a=o.environments?.find(s=>s.name===i.name);if(a)!e&&!await bt(`Environment ${i.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),a.baseUrl=i.variables[it],delete i.variables[it],a.envVariables=i.variables;else{let s=i.variables[it];delete i.variables[it],o.environments.push({name:i.name,baseUrl:s,envVariables:i.variables})}}ri(o,n.configFilePath),y.success(`Pulled ${r.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as Wb}from"crypto";import Vb from"fs";async function Du({testsToFetch:t,client:e,all:n,yes:r}){let{tests:o,modules:i}=await e.getTestYAMLExport({paths:t,all:n}),a=0;for(let[l,c]of Object.entries(o)){let d=qb(l,fe.TEST);!r&&!await gd(d)||(a+=1,Vb.writeFileSync(d,c,"utf-8"),X.info({checksum:Wb("md5").update(c).digest("hex")},`Wrote '${d}'`))}let s=0;for(let[l,c]of Object.entries(i)){let d=qb(l,fe.MODULE);!r&&!await gd(d)||(s+=1,Vb.writeFileSync(d,c,"utf-8"),X.info({checksum:Wb("md5").update(c).digest("hex")},`Wrote '${d}'`))}a===0?y.success("Pulled 0 tests."):y.success(`Pulled ${a} test${a>1?"s":""}${s?` and ${s} module${s>1?"s":""}`:""}!`)}function qb(t,e){switch(e){case fe.TEST:return`${ve(t)}.${st.TEST}`;case fe.MODULE:return`${ve(t)}.${st.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function Kb(t){let{project:e,client:n,skipPrompts:r}=t;y.info("Welcome to the Momentic Cloud importer wizard! \u{1F636}\u200D\u{1F32B}\uFE0F"),y.info("Importing environments from Momentic Cloud."),y.info(`This command will overwrite all local environment configuration in ${e.configFilePath} with environments from Momentic Cloud.`),await bt("Are you sure you want to proceed?",!0)||(y.info("Aborting..."),process.exit(1)),await Gb({client:n,project:e,skipPrompts:r}),y.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.`),y.info("Importing tests and modules from Momentic Cloud."),await Du({testsToFetch:[],client:n,all:!0,yes:r}),y.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.")}async function Yb(t){let{client:e,skipPrompts:n,paths:r}=t;await Du({testsToFetch:r,client:e,all:void 0,yes:n}),y.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{Argument as fo,InvalidArgumentError as Ra,Option as Ie}from"@commander-js/extra-typings";import{validateHeaderValue as HM}from"http";import{z as Xb}from"zod";var Ol=58888;function Cr(t){let e=parseInt(t,10);if(isNaN(e))throw new Ra("Not a number.");return e}function Nl(t){if(t===void 0)return;let e={};for(let n of t){let r=n.indexOf("=");if(r===-1)throw new Error(`Header value pair does not contain '=': ${n}`);let o=n.slice(0,r),i=n.slice(r+1);HM(o,i),e[o]=i}return e}var gn=new Ie("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(t=>{if(!t)throw new Ra("API key is required.");return t}).makeOptionMandatory(),hn=new Ie("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(t=>{try{return Xb.string().url().parse(t),t}catch{throw new Ra("Not a valid URL.")}}),Rr=new Ie("-y, --yes","Skip all confirmation prompts.").env("CI"),Fu=new Ie("-w, --wait","Wait for tests to finish running before exiting."),Uu=new Ie("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Defaults to ${18e5/1e3} seconds.`).default(18e5/1e3).implies({wait:!0}).argParser(Cr),kl=new Ie("--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."),Jb=new Ie("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(ns)),Qb=new Ie("--reporter-dir <reporterDir>","Output directory to store report files. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml.").default("reports"),Bu=new Ie("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),Zb=new Ie("--upload-results","Upload test results to Momentic Cloud.").default(!1),zu=new Ie("--include <includePatterns...>","Only include tests that match the provided regex patterns. Multiple patterns can be provided. The patterns will be matched against the test file paths and the pattern only needs to match a part of the path for the test to be included."),Hu=new Ie("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),$u=new Ie("--pixel-ratio <pixelRatio>","Device pixel ratio of your screen or monitor. Mac OS Retina displays and machines marketed as 'HiDPI' should set this to 2. Visit https://www.mydevice.io/ to find your device's pixel ratio.").argParser(Cr),ju=new Ie("--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."),_l=new Ie("--env <env>","Name of the environment to use when running tests."),Dl=new Ie("--url-override <urlOverride>","Fully qualified URL (e.g. https://www.google.com) to start all tests from. Overrides any default starting URL set from the test or environment.").argParser(t=>{try{return Xb.string().url().parse(t),t}catch{throw new Ra("Not a valid URL.")}}),eT=new Ie("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(t=>{let e=Cr(t);if(e<1)throw new Ra("Shard index must be greater than 0.");return e}),tT=new Ie("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(Cr),Gt=new Ie("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),gi=new Ie("-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."),nT=new Ie("--fix","Attempt to fix any issues found."),Gu=new Ie("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI"),Wu=new Ie("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes."),rT=new Ie("--skip-quarantined","Skip quarantined tests entirely.").implies({onlyQuarantined:!1,ignoreQuarantine:!1}),oT=new Ie("--only-quarantined","Run only tests that are currently quarantined. When running with this option, any test failures will cause the pipeline to fail, even though the tests are quarantined.").implies({skipQuarantined:!1,ignoreQuarantine:!1}),iT=new Ie("--ignore-quarantine","Run all tests even if they are quarantined. This is useful for validating that quarantined tests are fixed before moving them out of quarantine.").implies({skipQuarantined:!1,onlyQuarantined:!1}),aT=new fo("<tests...>","One or more test paths to queue on Momentic Cloud."),sT=new fo("<tests...>","One or more test paths to import from Momentic Cloud.").argOptional(),Vu=new fo("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional(),lT=new fo("<suites...>","One or more suite paths that exist on Momentic Cloud."),cT=new fo("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),dT=new fo("<results>","Path to the results archive.").argRequired(),qu=new Ie("--reason <reason>","The reason for quarantining the test. This will be used to generate a report on the test run."),Ku=new fo("<test>","Name of the test to quarantine.").argOptional();async function uT(t){let e=te(t,y),n=Object.values(e.tests);for(let r of n)try{let o=no(r.fullFilePath,y,e),i=o.steps;if(!i||i.length===0||!Array.isArray(i)){y.debug(`Test ${r.name} (${r.relativePath}) has no steps, skipping...`);continue}let a=St.parse(o),s=await Jr(a,i,y);y.dimmed(`Updating ${r.relativePath}`),It({relativeTestPath:r.relativePath,steps:{beforeSteps:o.beforeSteps,steps:s.steps,afterSteps:o.afterSteps},schemaVersion:ce,project:t,forceSaveOnNoDiffs:!0})}catch(o){y.error({err:o},`Failed to read or migrate test ${r.name} (${r.relativePath}), continuing...`)}for(let r of Object.values(e.modules)){y.dimmed(`Updating ${r.relativePath}`);try{let o=Gn(r.fullFilePath,y),i=o.steps;if(!i||i.length===0||!Array.isArray(i)){y.debug(`Module ${r.name} (${r.relativePath}) has no steps, skipping...`);continue}let a=await Jr({id:o.moduleId,schemaVersion:o.schemaVersion},i,y);Ht({content:{...o,steps:a.steps},schemaVersion:ce,momenticFiles:e,project:t,forceSaveOnNoDiffs:!0})}catch(o){y.error({err:o},`Failed to read or migrate module ${r.name} (${r.relativePath}), continuing...`)}}}import{spawnSync as GM}from"child_process";import{PostHog as jM}from"posthog-node";async function mT(t,e){let n,r=0,o=3,i,a;for(;r<o;)try{let s=await z(t.getAllFlagsAndPayloads(e),{milliseconds:5e3});i=s.featureFlags||{},a=s.featureFlagPayloads||{};break}catch(s){n=s,r++,await new Promise(l=>setTimeout(l,100*r))}if(i&&a)return{flags:i,payloads:a};throw n}var Fl=class t extends $i{constructor(n,r,o,i){super(o,i);this.client=n;this.orgId=r}static async init(n){let r=new jM("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:o,payloads:i}=await mT(r,n);return new t(r,n,o,i)}async refresh(){let{flags:n,payloads:r}=await mT(this.client,this.orgId);this.flags=n,this.payloads=r}};function WM(){try{let e=GM("git remote show origin",{encoding:"utf8",maxBuffer:5242880}).stdout.match(/HEAD branch: (.*)$/m);if(e&&e[1])return e[1].trim();y.warn("Could not determine your Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field.");return}catch(t){let e=t instanceof Error?t.message:String(t);y.warn(`Could not determine Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field. Error:
3973
- ${e}`)}}async function pT({project:t,orgId:e,apiClient:n}){y.info("Pulling browser and AI configuration options from Cloud");let r=await Fl.init(e);t.config.browser={autoExpandIframes:r.isBooleanFlagEnabled("auto_expand_iframes"),disableSecondaryCacheResolution:r.isBooleanFlagEnabled("disable_secondary_cache_resolution"),globalLocatorRedirect:r.isBooleanFlagEnabled("global_locator_redirect"),visualActions:r.isBooleanFlagEnabled("visual_actions"),...t.config.browser},t.config.advanced={fakerConstantSeed:r.isBooleanFlagEnabled("faker_constant_seed"),...t.config.advanced},t.config.ai={aiPageFiltering:r.isBooleanFlagEnabled("rag_v2"),agentConfig:await n.getAgentConfig(),...t.config.ai},y.info(`Updated ${t.configFilePath} to include V2 browser and AI configuration options`),y.info("Determining main Git branch"),t.config.gitMainBranch=WM(),ri(t.config,t.configFilePath),y.success("Migration complete!")}import{input as VM,search as qM}from"@inquirer/prompts";import KM from"fuse.js";async function Ul({prompt:t,inputtedTest:e,testOptions:n}){if(e){let a=n.find(s=>s.name===e);if(!a)y.error(`${e} is not a valid test option.`);else return{name:a.name,id:a.value}}let r=new KM(n,{keys:[{name:"name",weight:1}],threshold:.4,includeScore:!0,findAllMatches:!0,ignoreLocation:!0,useExtendedSearch:!0,shouldSort:!0,includeMatches:!0,distance:100,ignoreFieldNorm:!1}),o=await qM({message:t,source:async a=>!a||a.length===0?n:r.search({name:a}).map(l=>l.item)}),i=n.find(a=>a.value===o);return{name:i.name,id:i.value}}async function Bl({prompt:t,inputtedReason:e}){return e||VM({message:t})}async function gT({test:t,reason:e,apiClient:n,project:r,logger:o,identity:i}){let a=te(r,y).tests,s=Object.values(a).map(d=>({value:d.id,name:d.name})),l=await Ul({prompt:"Select a test to quarantine.",inputtedTest:t,testOptions:s}),c=await Bl({prompt:"Enter a reason for quarantining the test.",inputtedReason:e});await n.quarantineTest(l,c,i),y.success(`Test ${l.name} has been successfully quarantined. Navigate to ${n.getAppUrl()}/quarantine to view all quarantined tests. Remove this test from quarantine by running 'npx momentic quarantine remove ${l.name}'.`)}async function hT({test:t,reason:e,apiClient:n,project:r,logger:o,identity:i}){let a=te(r,y).tests,s=Object.values(a).map(g=>({value:g.id,name:g.name})),l=(await n.getQuarantinedTests()).quarantined,c=new Set(l.map(g=>g.testId)),d=s.filter(g=>c.has(g.value)),u=await Ul({prompt:"Select a test to unquarantine.",inputtedTest:t,testOptions:d}),m=await Bl({prompt:"Enter a reason for unquarantining the test.",inputtedReason:e});await n.unquarantineTest(u,m,i),y.success(`Test ${u.name} has been successfully removed from quarantine.`)}function fT(t){return t?ve(t):"Unknown suite"}async function ST({client:t,orgId:e,suitePaths:n,wait:r,waitTimeout:o,...i}){let{suiteRunIds:a,runGroupIds:s}=await t.queueSuiteRuns({paths:n,...i});X.info({orgId:e,suiteRunIds:a,runGroupIds:s,suitePaths:n},"Queued suites remotely"),y.dimmed(`Queued ${n.length} suites.`),r||process.exit(0);let l=Date.now();y.dimmed(`Waiting for ${n.length} suites to finish. You can view results upon completion at:`);for(let f of s)y.dimmed(`${Ke}- ${t.getAppUrl()}/run-groups/${f}`);let c=new Set,d=[],u=f=>(f.status==="FAILED"||f.status==="PASSED"||f.status==="CANCELLED")&&f.runs.every(b=>b.status==="FAILED"&&(b.failureReason||b.finishedAt&&Date.now()-b.finishedAt.getTime()>30*1e3)||b.status==="PASSED"||b.status==="CANCELLED"),m=await vs({name:"suites",getResults:async()=>{let f=s.filter(E=>!d.some(v=>v.id===E)),S=await t.bulkGetRunGroupStatus(f),b=[];for(let E of S)u(E)?d.push(E):b.push(E);return[...d,...b]},timeoutMs:o?o*1e3:void 0,checkDone:f=>(f.forEach(S=>{S.status==="RUNNING"&&(c.has(S.id)||(c.add(S.id),y.log(`${c.size}/${s.length} ${fT(S.suite?.name)}`)))}),f.every(u))}),g=t.getAppUrl(),h=Go({results:m,startTime:l,onFailed:f=>{let S=fT(f.suite?.name),b=f.runs.filter(v=>v.status==="FAILED").length,E=f.runs.length;y.error(`${S} (${b}/${E} tests failed):`);for(let v of f.runs)if(v.status==="FAILED"){let R=v.testName||v.test?.name;y.error(` ${R?ve(R):"Unknown test"} (${g}/runs/${v.id})`)}},entity:"suite",getDisplayLine:f=>` ${f.suite?.name?ve(f.suite.name):"Unknown suite name"} (${g}/run-groups/${f.id})`});process.exit(h.failed>0?1:0)}async function yT({tests:t,client:e,orgId:n,...r}){!r.yes&&!await bt(`This command will queue ${t.length} tests to run remotely on Momentic's infrastructure. Results will be available on ${e.getAppUrl()}. Continue?`)&&process.exit(1);let{queuedTests:o,runIds:i}=await e.queueTests({testPaths:t,...r});if(X.info({queuedTests:o,runIds:i,orgId:n},"Queued tests remotely"),y.dimmed(`Queued ${o.length} tests. Processing time may depend on a variety of factors, including how many tests have already been queued from your organization.`),r.wait||process.exit(0),!i.length)return;y.dimmed(`Waiting for ${o.length} tests to complete.`);let a=new Set,s=[],l=g=>g.status==="FAILED"&&g.failureReason||g.status==="PASSED"||g.status==="CANCELLED",c=e.getAppUrl(),d=Date.now(),u=await vs({name:"runs",getResults:async()=>{let g=i.filter(f=>!s.some(S=>S.id===f)),p=await e.bulkGetRunStatus(g),h=[];for(let f of p)l(f)?s.push(f):h.push(f);return[...s,...h]},timeoutMs:r.waitTimeout?r.waitTimeout*1e3:void 0,checkDone:g=>(g.forEach(p=>{if(p.status==="RUNNING"&&!a.has(p.id)){a.add(p.id);let h=p.testName||p.test?.name;h&&y.log(`${a.size}/${o.length} ${ve(h)}`)}}),g.every(l))}),m=Go({results:u,startTime:d,onFailed:g=>{let p=g.testName||g.test?.name;As(g,p?ve(p):"Unknown test")},getDisplayLine:g=>{let p=g.testName||g.test?.name,h=` ${p?ve(p):"Unknown test"}`;return g.id&&(h+=` (${c}/runs/${g.id})`),h},entity:"test"});process.exit(m.failed>0?1:0)}import{randomUUID as kO}from"crypto";import _O from"fs";import{existsSync as lO,mkdirSync as cO,statSync as dO}from"fs";import{randomUUID as bT}from"crypto";import Yu from"fs";import{hostname as YM}from"os";import Xu from"path";async function zl(t,e,n,r){if(r){let o=await e.getScreenshot(t,r);if(o){let i=`${r}-screenshot.jpeg`,a=Xu.join(n,i);return Yu.writeFileSync(a,o),i}}}async function XM(t,e,n,r){let o=r.runId??bT(),i={uuid:o,historyId:o,testCaseId:r.test.id,fullName:r.test.name,name:ve(r.test.name),status:r.status==="PASSED"?"passed":r.status==="CANCELLED"?"skipped":"failed",start:r.lastAttemptStartedAt.getTime(),stop:r.finishedAt.getTime(),parameters:[],labels:[{name:"suite",value:n.suiteName},{name:"host",value:YM()},{name:"platform",value:"momentic"},{name:"attempts",value:r.attempts.toString()}],steps:[]};r.runId&&i.labels?.push({name:"runUrl",value:`https://app.momentic.ai/runs/${r.runId}`});for(let[s,l]of Object.entries(r.parameters))l!=null&&i.parameters.push({name:s,value:JSON.stringify(l)});r.results&&await JM(t,e,n.folder,i.steps,r.results);let a=`${o}-result.json`;Yu.writeFileSync(Xu.join(n.folder,a),JSON.stringify(i,void 0,2))}async function hi(t,e,n,r){let o={name:gr(r),start:r.startedAt.getTime(),stop:r.finishedAt.getTime(),status:r.status==="SUCCESS"?"passed":r.status==="CANCELLED"?"skipped":"failed",labels:[],steps:[],attachments:[]};r.beforeUrl&&o.labels?.push({name:"URL before step",value:r.beforeUrl}),r.afterUrl&&o.labels?.push({name:"URL after step",value:r.afterUrl});let i=await zl(t,e,n,r.beforeSnapshot);i&&o.attachments.push({name:"Screenshot before step",source:i,type:"image/jpeg"});let a=await zl(t,e,n,r.afterSnapshot);if(a&&o.attachments.push({name:"Screenshot after step",source:a,type:"image/jpeg"}),r.message&&(o.statusDetails={message:r.message}),r.data){let s=`${bT()}-attachment.json`,l=Xu.join(n,s);Yu.writeFileSync(l,JSON.stringify(r.data,null,2)),o.attachments.push({name:"Step output data",source:s,type:"text/plain"})}return o}async function JM(t,e,n,r,o){for(let i of o)switch(i.type){case"PRESET_ACTION":{r.push(await hi(t,e,n,i));break}case"CONDITIONAL":{let a=await hi(t,e,n,i);a.steps=[],i.assertionResult&&a.steps.push(await hi(t,e,n,i.assertionResult)),a.steps.push(...await Promise.all(i.results.map(s=>hi(t,e,n,s)))),r.push(a);break}case"AI_ACTION":case"SECTION":case"MODULE":{let a=await hi(t,e,n,i);if(a.steps=await Promise.all(i.results.map(s=>hi(t,e,n,s))),i.type==="MODULE"&&i.inputs){a.parameters=[];for(let[s,l]of Object.entries(i.inputs))a.parameters.push({name:s,value:l})}r.push(a)}}}async function TT(t,e,n,r){for(let o of r.runs)await XM(t,e,{folder:n,suiteName:r.suiteName},o)}import QM from"junit-report-builder";import Hl from"path";function ZM(t,e){if(e.name(t.test.name).className(t.test.name).file(Hl.relative(".",t.filePath)).property("id",t.test.id).property("dd_tags[id]",t.test.id),t.test.labels&&(e.property("labels",t.test.labels.join(",")),t.test.labels.forEach(n=>{e.property("dd_tags[label]",n)})),t.baseUrl&&(e.property("base_url",t.baseUrl),e.property("dd_tags[base_url]",t.baseUrl)),t.runId&&(e.property("run_url",`https://app.momentic.ai/runs/${t.runId}`),e.property("dd_tags[run_url]",`https://app.momentic.ai/runs/${t.runId}`)),t.quarantined&&(e.property("quarantined","true"),e.property("dd_tags[quarantined]","true"),t.quarantinedReason&&(e.property("quarantined_reason",t.quarantinedReason),e.property("dd_tags[quarantined_reason]",t.quarantinedReason))),t.beforeResults?.some(n=>n.status==="FAILED")&&(e.property("setup_failed","true"),e.property("dd_tags[setup_failed]","true")),t.results?.some(n=>n.status==="FAILED")&&(e.property("main_failed","true"),e.property("dd_tags[main_failed]","true")),t.afterResults?.some(n=>n.status==="FAILED")&&(e.property("teardown_failed","true"),e.property("dd_tags[teardown_failed]","true")),t.status==="FAILED"){if(t.failureReason){let n=Ga[t.failureDetails?.classification?.reason||t.failureReason],r=t.failureDetails?.classification?.summary||Mo[t.failureReason];t.runId&&(r+=` Visit https://app.momentic.ai/runs/${t.runId} for more details.`),e.failure(r,n)}t.failureDetails?.errorStack&&e.stacktrace(t.failureDetails.errorStack)}else t.status==="CANCELLED"&&e.skipped();return e.time((t.finishedAt.getTime()-t.lastAttemptStartedAt.getTime())/1e3).property("started_at",t.lastAttemptStartedAt.toISOString()).property("dd_tags[started_at]",t.lastAttemptStartedAt.toISOString()).property("finished_at",t.finishedAt.toISOString()).property("dd_tags[finished_at]",t.finishedAt.toISOString()),e.property("attempts",t.attempts.toString()).property("dd_tags[attempts]",t.attempts.toString()),t.parameters.envName&&(e.property("environment",t.parameters.envName),e.property("dd_tags[environment]",t.parameters.envName)),t.parameters.urlOverride&&e.property("url_override",t.parameters.urlOverride),e}function eO(t,{suiteId:e,suiteName:n,startedAt:r,finishedAt:o,runs:i,testsToSkip:a,quarantinedTestsToSkip:s,quarantinedTestReasons:l}){let c=t.testSuite().name(n);e&&c.property("id",e),c.timestamp(r).property("startedAt",r.toISOString()).property("finishedAt",o.toISOString()).time((o.getTime()-r.getTime())/1e3);for(let d of i){let u=c.testCase();ZM(d,u)}for(let d of a){let u=c.testCase();u.name(d.name).className(d.name).file(Hl.relative(".",d.relativeFilePath)).property("id",d.id),d.baseUrl&&u.property("baseUrl",d.baseUrl),d.labels&&(u.property("labels",d.labels.join(",")),d.labels.forEach(m=>{u.property("dd_tags[label]",m)})),u.skipped()}for(let d of s){let u=c.testCase();u.name(d.name).className(d.name).file(Hl.relative(".",d.relativeFilePath)).property("id",d.id).property("quarantined","true");let m=l[d.id];m&&u.property("quarantinedReason",m),d.baseUrl&&u.property("baseUrl",d.baseUrl),d.labels&&(u.property("labels",d.labels.join(",")),d.labels.forEach(g=>{u.property("dd_tags[label]",g)})),u.skipped()}return c}function wT(t,e){let n=QM.newBuilder();eO(n,e),n.writeTo(Hl.join(t,`${e.suiteName}.xml`))}import tO from"fs";import nO from"path";function ET(t){return{title:gr(t),duration:t.finishedAt.getTime()-t.startedAt.getTime(),error:t.status==="FAILED"?{value:t.failureReason}:void 0,steps:t.results&&t.type!=="PRESET_ACTION"?t.results.map(ET):[]}}async function rO(t,e,n,r){if(r.results?.length){let o=await zl(t,e,n,r.results[r.results.length-1].afterSnapshot);return o?[{name:"Final state screenshot",path:o,contentType:"image/jpeg"}]:[]}return[]}async function oO(t,e,n,r){return{status:r.status==="PASSED"?"passed":r.status==="CANCELLED"?"interrupted":"failed",duration:r.finishedAt.getTime()-r.lastAttemptStartedAt.getTime(),error:r.status==="FAILED"&&r.failureReason?{value:r.failureDetails?.classification?.reason||r.failureReason,message:r.failureDetails?.classification?.summary||Mo[r.failureReason]}:void 0,retry:r.attempts-1,steps:r.results?.map(ET)||[],startTime:r.lastAttemptStartedAt.toISOString(),attachments:await rO(t,e,n,r)}}async function iO(t,e,n,r){return{expectedStatus:"passed",status:r.status==="PASSED"?"expected":"unexpected",results:[await oO(t,e,n,r)]}}async function aO(t,e,n,r){return{tags:[],title:r.test.name,ok:r.status==="PASSED",tests:[await iO(t,e,n,r)],id:r.runId,file:r.filePath}}function Ju(t,e){return t.reduce((n,r)=>e(r)?n+1:n,0)}async function sO(t,e,n,r){return{suites:[{title:r.suiteName,file:r.projectConfigPath,specs:await Promise.all(r.runs.map(o=>aO(t,e,n,o)))}],errors:[],stats:{startTime:r.startedAt.toISOString(),duration:r.finishedAt.getTime()-r.startedAt.getTime(),expected:Ju(r.runs,o=>o.status==="PASSED"),unexpected:Ju(r.runs,o=>o.status!=="PASSED"),flaky:Ju(r.runs,o=>!!o.isFlake),skipped:0}}}async function CT(t,e,n,r){let o=await sO(t,e,n,r);tO.writeFileSync(nO.join(n,`${r.suiteName}.json`),JSON.stringify(o,null,2))}async function RT(t,e,n,r,o){switch(lO(o)?dO(o).isDirectory()||(y.error(`The specified reporter output directory '${o}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)):(y.info(`Reporter output directory '${o}' does not exist on disk, creating it now...`),cO(o,{recursive:!0})),n){case"junit":wT(o,r);return;case"allure":case"allure-json":await TT(t,e,o,r);return;case"playwright-json":await CT(t,e,o,r);return;default:throw new Error(`Unknown reporter format requested: '${n}'`)}}import DO from"wait-on";import{execSync as uO}from"child_process";import{platform as mO}from"os";function Qu(){return vT()?(y.dimmed("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),y.dimmed(`If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
3974
- `),2):(y.dimmed("Setting device pixel ratio to 1."),y.dimmed(`If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
3975
- l.`),1)}function vT(){return mO()==="darwin"&&uO("system_profiler SPDisplaysDataType").toString().includes("Retina")}function Zu(t){vT()&&t===1&&(y.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),y.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import pO from"@actions/exec";import gO from"@actions/io";import hO from"quote";import fO from"string-argv";async function AT(t,e=!0){let n=fO(t),r=await gO.which(n[0],!0),o=n.slice(1),i=pO.exec(hO(r),o,{delay:100});if(e)return i}import SO from"csv-parser";import{createReadStream as yO}from"fs";function em(t){return new Promise((e,n)=>{let r=[];yO(t).pipe(SO()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>n(o))})}import $l from"semver";import{z as jl}from"zod";var Yn="2.15.2",bO="https://registry.npmjs.org/momentic",TO=jl.object({versions:jl.record(jl.string(),jl.unknown()).optional()});async function xT(t){try{await wO(t)}catch(e){y.warn({err:e},"Failed to check CLI version against NPM servers")}}async function wO(t){if(!Yn){t.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let r=0;r<2;r++)try{let o=await z(fetch(bO),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let i=await o.json();e=TO.parse(i).versions;break}catch(o){t.warn({err:o},"Failed to fetch npm registry data")}if(!e){t.warn("Failed to fetch npm registry data. Skipping version check.");return}let n;for(let r of Object.keys(e))$l.valid(r)&&(!n||$l.gt(r,n))&&$l.gt(r,Yn)&&$l.lt(r,"2.0.0")&&!r.includes("alpha")&&(n=r);n&&(y.warn(`Update available: v${Yn} -> v${n}`),y.warn("This version may be missing critical fixes, features, and security updates."),y.warn(`Run "npx momentic@${n} -V" to update`))}import tm from"fs";import{compact as EO,partition as Gl}from"lodash-es";import nm from"path";import{cwd as CO}from"process";import RO from"semver";async function Wl({tests:t,momenticFiles:e,project:n,yes:r,include:o,exclude:i,labels:a,logger:s}){let l=new Set;if(t&&t.length>0){let d=t.some(m=>tm.existsSync(m)),u=CO();d?(u!==n.rootDir&&s.warn(`The current working directory ('${u}') is different from the project root directory ('${n.rootDir}'). All test path arguments will be resolved relative to the current working directory and only those tests matched by the project inclusion configuration will be ran. To avoid confusion, Momentic strongly recommends running the CLI from the project root directory or using substring filters rather than file paths.`),s.info(`Reading tests from the following local file paths:
3968
+ `)}import rN from"events";import rc from"fs";import oN from"open";import{cpus as YT}from"os";import nc from"path";import{fileURLToPath as aN}from"url";import ZL from"diff-lines";import{gt as eO}from"semver";async function Kb({test:t,fragment:e,entities:n,client:r,logger:o,yes:a}){eO(e.schemaVersion,se)&&(S.error(`This version of the CLI does not support the schema version of the fragment (${e.schemaVersion}). Please update to the latest version of the CLI and retry this command.`),process.exit(1)),Uh(e.steps).forEach(g=>{n.modules[g]||(S.error(`The test patch contains a module with id ${g} that could not be found in the current project. This suggests that either this test patch or your local file system may be out of date.`),process.exit(1))}),e.createdAt.getTime()<Date.now()-7*24*60*60*1e3&&!a&&!await bt("The test patch you are applying is more than 7 days old. Are you sure you want to continue?",!0)&&process.exit(1);let s=t.lastModified.getTime();e.createdAt.getTime()+60*60*1e3<s&&!a&&!await bt("The test patch you are applying was created before the test was last updated. Are you sure you want to continue?",!0)&&process.exit(1);let l=ao(t.fullFilePath,o,n),c=l.steps;if(!Array.isArray(c))throw new Error(`Test ${t.fullFilePath} is missing steps array`);let d,u;if(e.schemaVersion!==se){let{steps:g,newVersion:h}=await ri({metadata:{id:e.id,schemaVersion:e.schemaVersion},steps:e.steps,logger:S});d=h,u=Ge.array().parse(g)}else u=Ge.array().parse(e.steps);let{stepsToSave:m}=await He({stepLists:{steps:u}});m.beforeSteps=l.beforeSteps??void 0,m.afterSteps=l.afterSteps??void 0;let p=ZL(JSON.stringify(c,void 0,2),JSON.stringify(m,void 0,2),{n_surrounding:5});S.dimmed("=".repeat(30)),S.dimmed(p),S.dimmed("=".repeat(30)),S.dimmed(""),d&&S.warn(`If this patch is applied, your test will also be automatically upgraded to the latest schema version (${d}). Schema upgrades have no impact on functionality, although you may notice minor differences in the test YAML.`),!a&&!await bt("Do you want to apply this patch?")&&(S.dimmed("Cancelled."),process.exit(1)),Pt({relativeTestPath:t.relativePath,steps:m,schemaVersion:d??e.schemaVersion,project:n.project}),S.success("Patch applied successfully."),await r.patchTestFragment(e.id,{applied:!0,appliedAt:new Date})}import{randomUUID as Gt}from"crypto";import{z as Yb}from"zod";function xi(t){return Yb.string().uuid().safeParse(t).success}async function Bl({fix:t,project:e}){let n=te(e,S),r=Object.values(n.tests),o={},a={},i=new Set,s={},l=new Set,c=0;for(let u of r)try{let m=ao(u.fullFilePath,X,n),p=!1,g=!1;xi(u.id)||(S.error(`Test '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${u.id}'`),c++,g=!0,t&&(u.id=Gt(),p=!0)),n.duplicateEntities[u.id]&&(S.error(`Test '${u.name}' (${u.relativePath}) has a duplicate ID: '${u.id}'`),c++,g=!0,t&&(u.id=Gt(),p=!0));let h=m.steps;if(!h||h.length===0||!Array.isArray(h)){S.debug(`Test ${u.name} (${u.relativePath}) has no steps, skipping...`);continue}let f=St.parse(m),y=await eo(f,h,S);y.steps=y.steps.map((b,w)=>{b.id||(S.error(`Step ${w} in test '${u.name}' (${u.relativePath}) does not have an ID`),g=!0,t&&(p=!0,b.id=Gt())),xi(b.id)||(S.error(`Step ${w} in test '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${b.id}'`),c++,g=!0,t&&(p=!0,b.id=Gt()));let C=o[b.id]?.testId,v=o[b.id]?.testRelativePath;if(C?(c++,g=!0,C===u.id?S.error(`Multiple steps in the test '${u.name}' (${u.relativePath}) have the same ID '${b.id}'`):S.error(`Step ${w} in test '${u.name}' (${u.relativePath}) has the ID ${b.id} which is duplicated in ${v}`),t&&(p=!0,b.id=Gt())):o[b.id]={testId:u.id,testRelativePath:u.relativePath},b.type==="PRESET_ACTION"){let R=b.command.id;xi(R)||(S.error(`Command ${w} in test '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${R}'`),c++,g=!0,t&&(p=!0,b.command.id=Gt()));let x=a[R]?.testId,M=a[R]?.testRelativePath;x?(c++,g=!0,x===u.id?S.error(`Multiple commands in the test '${u.name}' (${u.relativePath}) have the same ID '${R}'`):S.error(`Command ${w} in test '${u.name}' (${u.relativePath}) has the ID ${R} which is duplicated in test ${M}`),t&&(p=!0,b.command.id=Gt())):a[R]={testId:u.id,testRelativePath:u.relativePath}}return Me.parse(b)}),g&&S.dimmed("=".repeat(80)),p&&t&&(Pt({relativeTestPath:u.relativePath,steps:{beforeSteps:m.beforeSteps,steps:y.steps,afterSteps:m.afterSteps},schemaVersion:se,project:e}),i.add(u.fullFilePath))}catch(m){S.error({err:m},`Failed to parse test ${u.name} (${u.relativePath})`);continue}let d=Object.values(n.modules);for(let u of d)try{let m=!1,p=!1;xi(u.id)||(S.error(`Module '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${u.id}'`),c++,p=!0,t&&(u.id=Gt(),m=!0)),n.duplicateEntities[u.id]&&(S.error(`Module '${u.name}' (${u.relativePath}) has a duplicate ID: '${u.id}'`),c++,p=!0,t&&(u.id=Gt(),m=!0));let g=Wn(u.fullFilePath,S),h=g.steps;if(!h||h.length===0||!Array.isArray(h)){S.debug(`Module ${u.name} (${u.relativePath}) has no steps, skipping...`);continue}let f,y;try{let w=await eo({id:g.moduleId,schemaVersion:g.schemaVersion},g.steps,S);f=w.steps,y=w.newVersion}catch(w){S.error({err:w},`Failed to migrate module ${u.name} (${u.relativePath})`);continue}let b=f.map((w,C)=>{if(Yb.string().uuid().safeParse(w.id)||(S.error(`Step ${C} in module '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${w.id}'`),c++,p=!0,t&&(m=!0,w.id=Gt())),o[w.id]?.testId){let R=o[w.id]?.testRelativePath;c++,p=!0,S.error(`Step ${C} in module '${u.name}' (${u.relativePath}) has the ID ${w.id} which is duplicated in test ${R}`),t&&(m=!0,w.id=Gt())}if(w.type==="PRESET_ACTION"){let R=w.command.id;xi(R)||(S.error(`Command ${C} in module '${u.name}' (${u.relativePath}) has an ID that does not parse as a UUID: '${R}'`),c++,p=!0,t&&(m=!0,w.command.id=Gt()));let x=a[R],M=s[R];x||M?(c++,p=!0,M?.moduleId===u.id?S.error(`Multiple commands in module '${u.name}' (${u.relativePath}) have the same ID '${R}'`):x?S.error(`Command in module '${u.name}' (${u.relativePath}) has the ID ${R} which is duplicated in test ${x.testRelativePath}`):S.error(`Command ${C} in module '${u.name}' (${u.relativePath}) has the ID ${R} which is duplicated in module ${M.moduleRelativePath}`),t&&(m=!0,w.command.id=Gt())):s[R]={moduleId:u.id,moduleRelativePath:u.relativePath}}return Me.parse(w)});p&&S.dimmed("=".repeat(80)),m&&t&&($t({content:{...g,steps:b},schemaVersion:y,momenticFiles:n,project:e,forceSaveOnNoDiffs:!0}),l.add(u.fullFilePath))}catch(m){S.error({err:m},`Failed to parse module ${u.name} (${u.relativePath})`);continue}return{errors:c,modifiedTestFilePaths:i,modifiedModuleFilePaths:l}}async function Xb({fix:t,project:e}){let{errors:n,modifiedTestFilePaths:r,modifiedModuleFilePaths:o}=await Bl({fix:t,project:e});n>0?(S.error(`Found errors in ${n} steps`),t?(S.warn(`Modified the following test files:
3969
+ ${[...r].map(a=>`${Ke}- ${a}`).join(`
3970
+ `)}`),o.size>0&&S.warn(`Modified the following module files:
3971
+ ${[...o].map(a=>`${Ke}- ${a}`).join(`
3972
+ `)}`)):S.warn("To fix these errors automatically, re-run this check with the --fix flag and then commit the resulting changes"),process.exit(1)):(S.success("No duplicates detected. All test, module, step and command IDs are unique."),process.exit(0))}async function Jb({project:t}){let e=te(t,S),n=Object.values(e.tests),r=await rl(e,X),o={},a={},i=new Set,s=new Set;for(let c of n)o[c.name]?a[c.name]?a[c.name].push(c.fullFilePath):a[c.name]=[o[c.name],c.fullFilePath]:o[c.name]=c.fullFilePath;for(let c of r)s.has(c.name)&&i.add(c.name),s.add(c.name);if(Object.entries(a).length>0||i.size>0){for(let[c,d]of Object.entries(a))for(let u of d)S.error(`Test Name ${c} is duplicated in ${u}`);for(let c of i)S.error(`Module name ${c} is duplicated in your project`);process.exit(1)}S.success("No duplicates detected. All test and module names are unique."),process.exit(0)}import{cloneDeep as tO}from"lodash-es";async function Qb({client:t,skipPrompts:e,project:n}){let r=await t.getAllEnvironments(),o=tO(n.config);o.environments||(o.environments=[]);for(let a of r){let i=o.environments?.find(s=>s.name===a.name);if(i)!e&&!await bt(`Environment ${a.name} already exists in the project configuration file. Would you like to overwrite its variables?`)&&process.exit(1),i.baseUrl=a.variables[at],delete a.variables[at],i.envVariables=a.variables;else{let s=a.variables[at];delete a.variables[at],o.environments.push({name:a.name,baseUrl:s,envVariables:a.variables})}}aa(o,n.configFilePath),S.success(`Pulled ${r.length} environments successfully! Please make sure to commit any changes to your project configuration file.`)}import{createHash as Zb}from"crypto";import eT from"fs";async function Wu({testsToFetch:t,client:e,all:n,yes:r}){let{tests:o,modules:a}=await e.getTestYAMLExport({paths:t,all:n}),i=0;for(let[l,c]of Object.entries(o)){let d=tT(l,pe.TEST);!r&&!await Ed(d)||(i+=1,eT.writeFileSync(d,c,"utf-8"),X.info({checksum:Zb("md5").update(c).digest("hex")},`Wrote '${d}'`))}let s=0;for(let[l,c]of Object.entries(a)){let d=tT(l,pe.MODULE);!r&&!await Ed(d)||(s+=1,eT.writeFileSync(d,c,"utf-8"),X.info({checksum:Zb("md5").update(c).digest("hex")},`Wrote '${d}'`))}i===0?S.success("Pulled 0 tests."):S.success(`Pulled ${i} test${i>1?"s":""}${s?` and ${s} module${s>1?"s":""}`:""}!`)}function tT(t,e){switch(e){case pe.TEST:return`${ve(t)}.${st.TEST}`;case pe.MODULE:return`${ve(t)}.${st.MODULE}`;default:throw new Error(`Unknown entity type ${e}`)}}async function nT(t){let{project:e,client:n,skipPrompts:r}=t;S.info("Welcome to the Momentic Cloud importer wizard! \u{1F636}\u200D\u{1F32B}\uFE0F"),S.info("Importing environments from Momentic Cloud."),S.info(`This command will overwrite all local environment configuration in ${e.configFilePath} with environments from Momentic Cloud.`),await bt("Are you sure you want to proceed?",!0)||(S.info("Aborting..."),process.exit(1)),await Qb({client:n,project:e,skipPrompts:r}),S.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.`),S.info("Importing tests and modules from Momentic Cloud."),await Wu({testsToFetch:[],client:n,all:!0,yes:r}),S.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.")}async function rT(t){let{client:e,skipPrompts:n,paths:r}=t;await Wu({testsToFetch:r,client:e,all:void 0,yes:n}),S.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{Argument as yo,InvalidArgumentError as Ii,Option as Ie}from"@commander-js/extra-typings";import{validateHeaderValue as nO}from"http";import{z as oT}from"zod";var zl=58888;function Ar(t){let e=parseInt(t,10);if(isNaN(e))throw new Ii("Not a number.");return e}function Hl(t){if(t===void 0)return;let e={};for(let n of t){let r=n.indexOf("=");if(r===-1)throw new Error(`Header value pair does not contain '=': ${n}`);let o=n.slice(0,r),a=n.slice(r+1);nO(o,a),e[o]=a}return e}var hn=new Ie("--api-key <key>","Momentic API key").env("MOMENTIC_API_KEY").argParser(t=>{if(!t)throw new Ii("API key is required.");return t}).makeOptionMandatory(),fn=new Ie("--server <server>","Momentic server to use.").env("MOMENTIC_SERVER").default("https://api.momentic.ai").argParser(t=>{try{return oT.string().url().parse(t),t}catch{throw new Ii("Not a valid URL.")}}),xr=new Ie("-y, --yes","Skip all confirmation prompts.").env("CI"),Vu=new Ie("-w, --wait","Wait for tests to finish running before exiting."),qu=new Ie("--wait-timeout <waitTimeout>",`The maximum number of seconds to wait for tests to complete. Defaults to ${18e5/1e3} seconds.`).default(18e5/1e3).implies({wait:!0}).argParser(Ar),$l=new Ie("--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."),aT=new Ie("--reporter <reporter>","Output report files in a standardized format to a local directory.").choices(Object.values(as)),iT=new Ie("--reporter-dir <reporterDir>","Output directory to store report files. Relative paths are resolved relative to the project root, which is defined by the detected momentic.config.yaml.").default("reports"),Ku=new Ie("--output-dir <outputDir>","Output directory to store run artifacts such as screenshots, results, and logs."),sT=new Ie("--upload-results","Upload test results to Momentic Cloud.").default(!1),Yu=new Ie("--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."),Xu=new Ie("--exclude <excludePatterns...>","The inverted version of --include: a test that matches any of the provided exclusion patterns will be excluded from running."),Ju=new Ie("--pixel-ratio <pixelRatio>","Device pixel ratio of your screen or monitor. Mac OS Retina displays and machines marketed as 'HiDPI' should set this to 2. Visit https://www.mydevice.io/ to find your device's pixel ratio.").argParser(Ar),Qu=new Ie("--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."),jl=new Ie("--env <env>","Name of the environment to use when running tests."),Gl=new Ie("--url-override <urlOverride>","Fully qualified URL (e.g. https://www.google.com) to start all tests from. Overrides any default starting URL set from the test or environment.").argParser(t=>{try{return oT.string().url().parse(t),t}catch{throw new Ii("Not a valid URL.")}}),lT=new Ie("--shard-index <shardIndex>","The index of the shard to run tests for. Defaults to 1.").default(1).argParser(t=>{let e=Ar(t);if(e<1)throw new Ii("Shard index must be greater than 0.");return e}),cT=new Ie("--shard-count <shardCount>","The number of shards that tests are being run on. Defaults to 1.").default(1).argParser(Ar),Wt=new Ie("-c, --config <configPath>","Absolute or relative path to a Momentic configuration file."),fa=new Ie("-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."),dT=new Ie("--fix","Attempt to fix any issues found."),Zu=new Ie("--save-cache","Always save updated step caches after successful test runs. By default, caches are not saved when running on protected branches.").env("CI"),em=new Ie("--disable-cache","Disable using step caches completely. Using this option may lead to non-deterministic behavior and significantly longer runtimes."),uT=new Ie("--skip-quarantined","Skip quarantined tests entirely.").implies({onlyQuarantined:!1,ignoreQuarantine:!1}),mT=new Ie("--only-quarantined","Run only tests that are currently quarantined. When running with this option, any test failures will cause the pipeline to fail, even though the tests are quarantined.").implies({skipQuarantined:!1,ignoreQuarantine:!1}),pT=new Ie("--ignore-quarantine","Run all tests even if they are quarantined. This is useful for validating that quarantined tests are fixed before moving them out of quarantine.").implies({skipQuarantined:!1,onlyQuarantined:!1}),gT=new yo("<tests...>","One or more test paths to queue on Momentic Cloud."),hT=new yo("<tests...>","One or more test paths to import from Momentic Cloud.").argOptional(),tm=new yo("<tests...>","One or more test file path or folders that exist on the local machine.").argOptional(),fT=new yo("<suites...>","One or more suite paths that exist on Momentic Cloud."),ST=new yo("<resultsPath>","Path to a directory that contains on or more test results archives.").argRequired(),yT=new yo("<results>","Path to the results archive.").argRequired(),nm=new Ie("--reason <reason>","The reason for quarantining the test. This will be used to generate a report on the test run."),rm=new yo("<test>","Name of the test to quarantine.").argOptional();async function bT(t){let e=te(t,S),n=Object.values(e.tests);for(let r of n)try{let o=ao(r.fullFilePath,S,e),a=o.steps;if(!a||a.length===0||!Array.isArray(a)){S.debug(`Test ${r.name} (${r.relativePath}) has no steps, skipping...`);continue}let i=St.parse(o),s=await eo(i,a,S);S.dimmed(`Updating ${r.relativePath}`),Pt({relativeTestPath:r.relativePath,steps:{beforeSteps:o.beforeSteps,steps:s.steps,afterSteps:o.afterSteps},schemaVersion:se,project:t,forceSaveOnNoDiffs:!0})}catch(o){S.error({err:o},`Failed to read or migrate test ${r.name} (${r.relativePath}), continuing...`)}for(let r of Object.values(e.modules)){S.dimmed(`Updating ${r.relativePath}`);try{let o=Wn(r.fullFilePath,S),a=o.steps;if(!a||a.length===0||!Array.isArray(a)){S.debug(`Module ${r.name} (${r.relativePath}) has no steps, skipping...`);continue}let i=await eo({id:o.moduleId,schemaVersion:o.schemaVersion},a,S);$t({content:{...o,steps:i.steps},schemaVersion:se,momenticFiles:e,project:t,forceSaveOnNoDiffs:!0})}catch(o){S.error({err:o},`Failed to read or migrate module ${r.name} (${r.relativePath}), continuing...`)}}}import{spawnSync as aO}from"child_process";import{PostHog as oO}from"posthog-node";async function TT(t,e){let n,r=0,o=3,a,i;for(;r<o;)try{let s=await H(t.getAllFlagsAndPayloads(e),{milliseconds:5e3});a=s.featureFlags||{},i=s.featureFlagPayloads||{};break}catch(s){n=s,r++,await new Promise(l=>setTimeout(l,100*r))}if(a&&i)return{flags:a,payloads:i};throw n}var Wl=class t extends Wa{constructor(n,r,o,a){super(o,a);this.client=n;this.orgId=r}static async init(n){let r=new oO("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://us.i.posthog.com"}),{flags:o,payloads:a}=await TT(r,n);return new t(r,n,o,a)}async refresh(){let{flags:n,payloads:r}=await TT(this.client,this.orgId);this.flags=n,this.payloads=r}};function iO(){try{let e=aO("git remote show origin",{encoding:"utf8",maxBuffer:5242880}).stdout.match(/HEAD branch: (.*)$/m);if(e&&e[1])return e[1].trim();S.warn("Could not determine your Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field.");return}catch(t){let e=t instanceof Error?t.message:String(t);S.warn(`Could not determine Git main branch. Please set it manually in your project configuration under the 'gitMainBranch' field. Error:
3973
+ ${e}`)}}async function wT({project:t,orgId:e,apiClient:n}){S.info("Pulling browser and AI configuration options from Cloud");let r=await Wl.init(e);t.config.browser={autoExpandIframes:r.isBooleanFlagEnabled("auto_expand_iframes"),disableSecondaryCacheResolution:r.isBooleanFlagEnabled("disable_secondary_cache_resolution"),globalLocatorRedirect:r.isBooleanFlagEnabled("global_locator_redirect"),visualActions:r.isBooleanFlagEnabled("visual_actions"),...t.config.browser},t.config.advanced={fakerConstantSeed:r.isBooleanFlagEnabled("faker_constant_seed"),...t.config.advanced},t.config.ai={aiPageFiltering:r.isBooleanFlagEnabled("rag_v2"),agentConfig:await n.getAgentConfig(),...t.config.ai},S.info(`Updated ${t.configFilePath} to include V2 browser and AI configuration options`),S.info("Determining main Git branch"),t.config.gitMainBranch=iO(),aa(t.config,t.configFilePath),S.success("Migration complete!")}import{input as sO,search as lO}from"@inquirer/prompts";import cO from"fuse.js";async function Vl({prompt:t,inputtedTest:e,testOptions:n}){if(e){let i=n.find(s=>s.name===e);if(!i)S.error(`${e} is not a valid test option.`);else return{name:i.name,id:i.value}}let r=new cO(n,{keys:[{name:"name",weight:1}],threshold:.4,includeScore:!0,findAllMatches:!0,ignoreLocation:!0,useExtendedSearch:!0,shouldSort:!0,includeMatches:!0,distance:100,ignoreFieldNorm:!1}),o=await lO({message:t,source:async i=>!i||i.length===0?n:r.search({name:i}).map(l=>l.item)}),a=n.find(i=>i.value===o);return{name:a.name,id:a.value}}async function ql({prompt:t,inputtedReason:e}){return e||sO({message:t})}async function ET({test:t,reason:e,apiClient:n,project:r,logger:o,identity:a}){let i=te(r,S).tests,s=Object.values(i).map(d=>({value:d.id,name:d.name})),l=await Vl({prompt:"Select a test to quarantine.",inputtedTest:t,testOptions:s}),c=await ql({prompt:"Enter a reason for quarantining the test.",inputtedReason:e});await n.quarantineTest(l,c,a),S.success(`Test ${l.name} has been successfully quarantined. Navigate to ${n.getAppUrl()}/quarantine to view all quarantined tests. Remove this test from quarantine by running 'npx momentic quarantine remove ${l.name}'.`)}async function RT({test:t,reason:e,apiClient:n,project:r,logger:o,identity:a}){let i=te(r,S).tests,s=Object.values(i).map(p=>({value:p.id,name:p.name})),l=(await n.getQuarantinedTests()).quarantined,c=new Set(l.map(p=>p.testId)),d=s.filter(p=>c.has(p.value)),u=await Vl({prompt:"Select a test to unquarantine.",inputtedTest:t,testOptions:d}),m=await ql({prompt:"Enter a reason for unquarantining the test.",inputtedReason:e});await n.unquarantineTest(u,m,a),S.success(`Test ${u.name} has been successfully removed from quarantine.`)}function CT(t){return t?ve(t):"Unknown suite"}async function vT({client:t,orgId:e,suitePaths:n,wait:r,waitTimeout:o,...a}){let{suiteRunIds:i,runGroupIds:s}=await t.queueSuiteRuns({paths:n,...a});X.info({orgId:e,suiteRunIds:i,runGroupIds:s,suitePaths:n},"Queued suites remotely"),S.dimmed(`Queued ${n.length} suites.`),r||process.exit(0);let l=Date.now();S.dimmed(`Waiting for ${n.length} suites to finish. You can view results upon completion at:`);for(let f of s)S.dimmed(`${Ke}- ${t.getAppUrl()}/run-groups/${f}`);let c=new Set,d=[],u=f=>(f.status==="FAILED"||f.status==="PASSED"||f.status==="CANCELLED")&&f.runs.every(b=>b.status==="FAILED"&&(b.failureReason||b.finishedAt&&Date.now()-b.finishedAt.getTime()>30*1e3)||b.status==="PASSED"||b.status==="CANCELLED"),m=await Ms({name:"suites",getResults:async()=>{let f=s.filter(w=>!d.some(C=>C.id===w)),y=await t.bulkGetRunGroupStatus(f),b=[];for(let w of y)u(w)?d.push(w):b.push(w);return[...d,...b]},timeoutMs:o?o*1e3:void 0,checkDone:f=>(f.forEach(y=>{y.status==="RUNNING"&&(c.has(y.id)||(c.add(y.id),S.log(`${c.size}/${s.length} ${CT(y.suite?.name)}`)))}),f.every(u))}),p=t.getAppUrl(),h=Vo({results:m,startTime:l,onFailed:f=>{let y=CT(f.suite?.name),b=f.runs.filter(C=>C.status==="FAILED").length,w=f.runs.length;S.error(`${y} (${b}/${w} tests failed):`);for(let C of f.runs)if(C.status==="FAILED"){let v=C.testName||C.test?.name;S.error(` ${v?ve(v):"Unknown test"} (${p}/runs/${C.id})`)}},entity:"suite",getDisplayLine:f=>` ${f.suite?.name?ve(f.suite.name):"Unknown suite name"} (${p}/run-groups/${f.id})`});process.exit(h.failed>0?1:0)}async function AT({tests:t,client:e,orgId:n,...r}){!r.yes&&!await bt(`This command will queue ${t.length} tests to run remotely on Momentic's infrastructure. Results will be available on ${e.getAppUrl()}. Continue?`)&&process.exit(1);let{queuedTests:o,runIds:a}=await e.queueTests({testPaths:t,...r});if(X.info({queuedTests:o,runIds:a,orgId:n},"Queued tests remotely"),S.dimmed(`Queued ${o.length} tests. Processing time may depend on a variety of factors, including how many tests have already been queued from your organization.`),r.wait||process.exit(0),!a.length)return;S.dimmed(`Waiting for ${o.length} tests to complete.`);let i=new Set,s=[],l=p=>p.status==="FAILED"&&p.failureReason||p.status==="PASSED"||p.status==="CANCELLED",c=e.getAppUrl(),d=Date.now(),u=await Ms({name:"runs",getResults:async()=>{let p=a.filter(f=>!s.some(y=>y.id===f)),g=await e.bulkGetRunStatus(p),h=[];for(let f of g)l(f)?s.push(f):h.push(f);return[...s,...h]},timeoutMs:r.waitTimeout?r.waitTimeout*1e3:void 0,checkDone:p=>(p.forEach(g=>{if(g.status==="RUNNING"&&!i.has(g.id)){i.add(g.id);let h=g.testName||g.test?.name;h&&S.log(`${i.size}/${o.length} ${ve(h)}`)}}),p.every(l))}),m=Vo({results:u,startTime:d,onFailed:p=>{let g=p.testName||p.test?.name;Ls(p,g?ve(g):"Unknown test")},getDisplayLine:p=>{let g=p.testName||p.test?.name,h=` ${g?ve(g):"Unknown test"}`;return p.id&&(h+=` (${c}/runs/${p.id})`),h},entity:"test"});process.exit(m.failed>0?1:0)}import{randomUUID as YO}from"crypto";import XO from"fs";import{existsSync as RO,mkdirSync as CO,statSync as vO}from"fs";import{randomUUID as xT}from"crypto";import om from"fs";import{hostname as dO}from"os";import am from"path";async function Kl(t,e,n,r){if(r){let o=await e.getScreenshot(t,r);if(o){let a=`${r}-screenshot.jpeg`,i=am.join(n,a);return om.writeFileSync(i,o),a}}}async function uO(t,e,n,r){let o=r.runId??xT(),a={uuid:o,historyId:o,testCaseId:r.test.id,fullName:r.test.name,name:ve(r.test.name),status:r.status==="PASSED"?"passed":r.status==="CANCELLED"?"skipped":"failed",start:r.lastAttemptStartedAt.getTime(),stop:r.finishedAt.getTime(),parameters:[],labels:[{name:"suite",value:n.suiteName},{name:"host",value:dO()},{name:"platform",value:"momentic"},{name:"attempts",value:r.attempts.toString()}],steps:[]};r.runId&&a.labels?.push({name:"runUrl",value:`https://app.momentic.ai/runs/${r.runId}`});for(let[s,l]of Object.entries(r.parameters))l!=null&&a.parameters.push({name:s,value:JSON.stringify(l)});r.results&&await mO(t,e,n.folder,a.steps,r.results);let i=`${o}-result.json`;om.writeFileSync(am.join(n.folder,i),JSON.stringify(a,void 0,2))}async function Sa(t,e,n,r){let o={name:hr(r),start:r.startedAt.getTime(),stop:r.finishedAt.getTime(),status:r.status==="SUCCESS"?"passed":r.status==="CANCELLED"?"skipped":"failed",labels:[],steps:[],attachments:[]};r.beforeUrl&&o.labels?.push({name:"URL before step",value:r.beforeUrl}),r.afterUrl&&o.labels?.push({name:"URL after step",value:r.afterUrl});let a=await Kl(t,e,n,r.beforeSnapshot);a&&o.attachments.push({name:"Screenshot before step",source:a,type:"image/jpeg"});let i=await Kl(t,e,n,r.afterSnapshot);if(i&&o.attachments.push({name:"Screenshot after step",source:i,type:"image/jpeg"}),r.message&&(o.statusDetails={message:r.message}),r.data){let s=`${xT()}-attachment.json`,l=am.join(n,s);om.writeFileSync(l,JSON.stringify(r.data,null,2)),o.attachments.push({name:"Step output data",source:s,type:"text/plain"})}return o}async function mO(t,e,n,r,o){for(let a of o)switch(a.type){case"PRESET_ACTION":{r.push(await Sa(t,e,n,a));break}case"CONDITIONAL":{let i=await Sa(t,e,n,a);i.steps=[],a.assertionResult&&i.steps.push(await Sa(t,e,n,a.assertionResult)),i.steps.push(...await Promise.all(a.results.map(s=>Sa(t,e,n,s)))),r.push(i);break}case"AI_ACTION":case"SECTION":case"MODULE":{let i=await Sa(t,e,n,a);if(i.steps=await Promise.all(a.results.map(s=>Sa(t,e,n,s))),a.type==="MODULE"&&a.inputs){i.parameters=[];for(let[s,l]of Object.entries(a.inputs))i.parameters.push({name:s,value:l})}r.push(i)}}}async function IT(t,e,n,r){for(let o of r.runs)await uO(t,e,{folder:n,suiteName:r.suiteName},o)}import pO from"junit-report-builder";import Yl from"path";function gO(t,e){if(e.name(t.test.name).className(t.test.name).file(Yl.relative(".",t.filePath)).property("id",t.test.id).property("dd_tags[id]",t.test.id),t.test.labels&&(e.property("labels",t.test.labels.join(",")),t.test.labels.forEach(n=>{e.property("dd_tags[label]",n)})),t.baseUrl&&(e.property("base_url",t.baseUrl),e.property("dd_tags[base_url]",t.baseUrl)),t.runId&&(e.property("run_url",`https://app.momentic.ai/runs/${t.runId}`),e.property("dd_tags[run_url]",`https://app.momentic.ai/runs/${t.runId}`)),t.quarantined&&(e.property("quarantined","true"),e.property("dd_tags[quarantined]","true"),t.quarantinedReason&&(e.property("quarantined_reason",t.quarantinedReason),e.property("dd_tags[quarantined_reason]",t.quarantinedReason))),t.beforeResults?.some(n=>n.status==="FAILED")&&(e.property("setup_failed","true"),e.property("dd_tags[setup_failed]","true")),t.results?.some(n=>n.status==="FAILED")&&(e.property("main_failed","true"),e.property("dd_tags[main_failed]","true")),t.afterResults?.some(n=>n.status==="FAILED")&&(e.property("teardown_failed","true"),e.property("dd_tags[teardown_failed]","true")),t.status==="FAILED"){if(t.failureReason){let n=Ki[t.failureDetails?.classification?.reason||t.failureReason],r=t.failureDetails?.classification?.summary||No[t.failureReason];t.runId&&(r+=` Visit https://app.momentic.ai/runs/${t.runId} for more details.`),e.failure(r,n)}t.failureDetails?.errorStack&&e.stacktrace(t.failureDetails.errorStack)}else t.status==="CANCELLED"&&e.skipped();return e.time((t.finishedAt.getTime()-t.lastAttemptStartedAt.getTime())/1e3).property("started_at",t.lastAttemptStartedAt.toISOString()).property("dd_tags[started_at]",t.lastAttemptStartedAt.toISOString()).property("finished_at",t.finishedAt.toISOString()).property("dd_tags[finished_at]",t.finishedAt.toISOString()),e.property("attempts",t.attempts.toString()).property("dd_tags[attempts]",t.attempts.toString()),t.parameters.envName&&(e.property("environment",t.parameters.envName),e.property("dd_tags[environment]",t.parameters.envName)),t.parameters.urlOverride&&e.property("url_override",t.parameters.urlOverride),e}function hO(t,{suiteId:e,suiteName:n,startedAt:r,finishedAt:o,runs:a,testsToSkip:i,quarantinedTestsToSkip:s,quarantinedTestReasons:l}){let c=t.testSuite().name(n);e&&c.property("id",e),c.timestamp(r).property("startedAt",r.toISOString()).property("finishedAt",o.toISOString()).time((o.getTime()-r.getTime())/1e3);for(let d of a){let u=c.testCase();gO(d,u)}for(let d of i){let u=c.testCase();u.name(d.name).className(d.name).file(Yl.relative(".",d.relativeFilePath)).property("id",d.id),d.baseUrl&&u.property("baseUrl",d.baseUrl),d.labels&&(u.property("labels",d.labels.join(",")),d.labels.forEach(m=>{u.property("dd_tags[label]",m)})),u.skipped()}for(let d of s){let u=c.testCase();u.name(d.name).className(d.name).file(Yl.relative(".",d.relativeFilePath)).property("id",d.id).property("quarantined","true");let m=l[d.id];m&&u.property("quarantinedReason",m),d.baseUrl&&u.property("baseUrl",d.baseUrl),d.labels&&(u.property("labels",d.labels.join(",")),d.labels.forEach(p=>{u.property("dd_tags[label]",p)})),u.skipped()}return c}function PT(t,e){let n=pO.newBuilder();hO(n,e),n.writeTo(Yl.join(t,`${e.suiteName}.xml`))}import fO from"fs";import SO from"path";function MT(t){return{title:hr(t),duration:t.finishedAt.getTime()-t.startedAt.getTime(),error:t.status==="FAILED"?{value:t.failureReason}:void 0,steps:t.results&&t.type!=="PRESET_ACTION"?t.results.map(MT):[]}}async function yO(t,e,n,r){if(r.results?.length){let o=await Kl(t,e,n,r.results[r.results.length-1].afterSnapshot);return o?[{name:"Final state screenshot",path:o,contentType:"image/jpeg"}]:[]}return[]}async function bO(t,e,n,r){return{status:r.status==="PASSED"?"passed":r.status==="CANCELLED"?"interrupted":"failed",duration:r.finishedAt.getTime()-r.lastAttemptStartedAt.getTime(),error:r.status==="FAILED"&&r.failureReason?{value:r.failureDetails?.classification?.reason||r.failureReason,message:r.failureDetails?.classification?.summary||No[r.failureReason]}:void 0,retry:r.attempts-1,steps:r.results?.map(MT)||[],startTime:r.lastAttemptStartedAt.toISOString(),attachments:await yO(t,e,n,r)}}async function TO(t,e,n,r){return{expectedStatus:"passed",status:r.status==="PASSED"?"expected":"unexpected",results:[await bO(t,e,n,r)]}}async function wO(t,e,n,r){return{tags:[],title:r.test.name,ok:r.status==="PASSED",tests:[await TO(t,e,n,r)],id:r.runId,file:r.filePath}}function im(t,e){return t.reduce((n,r)=>e(r)?n+1:n,0)}async function EO(t,e,n,r){return{suites:[{title:r.suiteName,file:r.projectConfigPath,specs:await Promise.all(r.runs.map(o=>wO(t,e,n,o)))}],errors:[],stats:{startTime:r.startedAt.toISOString(),duration:r.finishedAt.getTime()-r.startedAt.getTime(),expected:im(r.runs,o=>o.status==="PASSED"),unexpected:im(r.runs,o=>o.status!=="PASSED"),flaky:im(r.runs,o=>!!o.isFlake),skipped:0}}}async function LT(t,e,n,r){let o=await EO(t,e,n,r);fO.writeFileSync(SO.join(n,`${r.suiteName}.json`),JSON.stringify(o,null,2))}async function OT(t,e,n,r,o){switch(RO(o)?vO(o).isDirectory()||(S.error(`The specified reporter output directory '${o}' exists on disk but is not a folder. Please move or delete the existing object or specify a different reporter path.`),process.exit(1)):(S.info(`Reporter output directory '${o}' does not exist on disk, creating it now...`),CO(o,{recursive:!0})),n){case"junit":PT(o,r);return;case"allure":case"allure-json":await IT(t,e,o,r);return;case"playwright-json":await LT(t,e,o,r);return;default:throw new Error(`Unknown reporter format requested: '${n}'`)}}import JO from"wait-on";import{execSync as AO}from"child_process";import{platform as xO}from"os";function sm(){return NT()?(S.dimmed("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),S.dimmed(`If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
3974
+ `),2):(S.dimmed("Setting device pixel ratio to 1."),S.dimmed(`If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations. Confirm your device's pixel-ratio at https://www.mydevice.io.
3975
+ l.`),1)}function NT(){return xO()==="darwin"&&AO("system_profiler SPDisplaysDataType").toString().includes("Retina")}function lm(t){NT()&&t===1&&(S.warn("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),S.warn("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import IO from"@actions/exec";import PO from"@actions/io";import MO from"quote";import LO from"string-argv";async function kT(t,e=!0){let n=LO(t),r=await PO.which(n[0],!0),o=n.slice(1),a=IO.exec(MO(r),o,{delay:100});if(e)return a}import OO from"csv-parser";import{createReadStream as NO}from"fs";function cm(t){return new Promise((e,n)=>{let r=[];NO(t).pipe(OO()).on("data",o=>r.push(o)).on("end",()=>e(r)).on("error",o=>n(o))})}import Xl from"semver";import{z as Jl}from"zod";var Xn="2.16.0",kO="https://registry.npmjs.org/momentic",_O=Jl.object({versions:Jl.record(Jl.string(),Jl.unknown()).optional()});async function _T(t){try{await DO(t)}catch(e){S.warn({err:e},"Failed to check CLI version against NPM servers")}}async function DO(t){if(!Xn){t.warn("Unable to check CLI version because CLI_VERSION is not set");return}let e;for(let r=0;r<2;r++)try{let o=await H(fetch(kO),{milliseconds:5e3});if(!o.ok)throw new Error(`Got error status code ${o.statusText}`);let a=await o.json();e=_O.parse(a).versions;break}catch(o){t.warn({err:o},"Failed to fetch npm registry data")}if(!e){t.warn("Failed to fetch npm registry data. Skipping version check.");return}let n;for(let r of Object.keys(e))Xl.valid(r)&&(!n||Xl.gt(r,n))&&Xl.gt(r,Xn)&&Xl.lt(r,"2.0.0")&&!r.includes("alpha")&&(n=r);n&&(S.warn(`Update available: v${Xn} -> v${n}`),S.warn("This version may be missing critical fixes, features, and security updates."),S.warn(`Run "npx momentic@${n} -V" to update`))}import dm from"fs";import{compact as FO,partition as Ql}from"lodash-es";import um from"path";import{cwd as UO}from"process";import BO from"semver";async function Zl({tests:t,momenticFiles:e,project:n,yes:r,include:o,exclude:a,labels:i,logger:s}){let l=new Set;if(t&&t.length>0){let d=t.some(m=>dm.existsSync(m)),u=UO();d?(u!==n.rootDir&&s.warn(`The current working directory ('${u}') is different from the project root directory ('${n.rootDir}'). All test path arguments will be resolved relative to the current working directory and only those tests matched by the project inclusion configuration will be ran. To avoid confusion, Momentic strongly recommends running the CLI from the project root directory or using substring filters rather than file paths.`),s.info(`Reading tests from the following local file paths:
3976
3976
  ${t.map(m=>`${Ke}- ${m}`).join(`
3977
3977
  `)}
3978
- `),t.forEach(m=>{if(!tm.existsSync(m))throw new Error(`Path '${m}' does not exist.`);let g,p;try{g=tm.statSync(m),p=g.isDirectory()}catch(f){s.warn({err:f},`Skipping path ${m} because it cannot be read`);return}let h=nm.resolve(m);Object.values(e.tests).filter(f=>p?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{l.add(f.fullFilePath)})})):(s.info(`Reading all tests from the project and running those matching the following substring filters:
3978
+ `),t.forEach(m=>{if(!dm.existsSync(m))throw new Error(`Path '${m}' does not exist.`);let p,g;try{p=dm.statSync(m),g=p.isDirectory()}catch(f){s.warn({err:f},`Skipping path ${m} because it cannot be read`);return}let h=um.resolve(m);Object.values(e.tests).filter(f=>g?f.fullFilePath.startsWith(h):f.fullFilePath===h).forEach(f=>{l.add(f.fullFilePath)})})):(s.info(`Reading all tests from the project and running those matching the following substring filters:
3979
3979
  ${t.map(m=>`${Ke}- ${m}`).join(`
3980
- `)}`),Object.values(e.tests).forEach(m=>{t.some(g=>m.relativePath.includes(g))&&l.add(m.fullFilePath)}))}else{!r&&!await bt("No test paths or substrings were provided. Do you want to run all tests?")&&(s.error("Cancelled by user."),process.exit(1));let d=Object.values(e.tests);s.info(`Reading all ${d.length} tests in the project from local disk.`),d.forEach(u=>{l.add(u.fullFilePath)})}for(let d of l){let u=nm.relative(n.rootDir,d);o&&!o.some(m=>new RegExp(m).test(u))&&l.delete(d),i&&i.some(m=>new RegExp(m).test(u))&&l.delete(d)}let c=Array.from(l).map(async d=>{try{let u=await Pt(d,X,e);if(RO.gt(u.schemaVersion,ce)&&s.warn(`Test ${d} has schema version ${u.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`),a&&a.length>0){let m=u.labels||[];if(!a.some(p=>m.includes(p)))return null}return{...u,fullFilePath:d,relativeFilePath:nm.relative(n.rootDir,d)}}catch(u){s.error(`Failed to read and resolve test at '${d}': ${u}`),process.exit(1)}});return Promise.all(c).then(EO)}function IT({testDefinitions:t,quarantinedTestReasons:e,onlyQuarantined:n=!1,skipQuarantined:r=!1}){if(n){let[d,u]=Gl(t,p=>p.id in e),[m,g]=Gl(d,p=>p.disabled||r);return{testsToSkip:m,quarantinedTestsToSkip:[],testsToRun:g,quarantinedTestsToRun:[]}}let[o,i]=Gl(t,d=>d.disabled),[a,s]=Gl(i,d=>d.id in e);return{testsToSkip:o,testsToRun:s,quarantinedTestsToRun:r?[]:a,quarantinedTestsToSkip:r?a:[]}}function PT({testsToRun:t,quarantinedTestsToRun:e,quarantinedTestReasons:n,testInputMatrix:r}){let o=[],i=(a,s,l)=>{r?r.forEach((c,d)=>{o.push({inputs:c,inputIndex:d,testDefinition:a,quarantined:s,quarantinedReason:l})}):o.push({inputs:void 0,testDefinition:a,quarantined:s,quarantinedReason:l})};return t.forEach(a=>i(a,!1)),e.forEach(a=>i(a,!0,n[a.id])),o}import{partition as vO}from"lodash-es";function Vl(t){return t.length===1?"test":"tests"}function LT(t){return t===1?"1 worker":`${t} workers`}function MT(t){t.length!==0&&(y.info(`Skipping ${t.length} disabled ${Vl(t)}:`),t.forEach(e=>{y.info(`${Ke}- ${[e.relativeFilePath]}`)}),y.log(""))}function OT(t,e){t.length!==0&&(y.info(`Skipping ${t.length} quarantined ${Vl(t)}:`),t.forEach(n=>{y.info(`${Ke}- ${[n.relativeFilePath]}: ${e[n.id]}`)}),y.log(""))}function AO(t,e){t.length!==0&&(y.info(`Running ${t.length} quarantined ${Vl(t)} with ${LT(e)}:`),t.forEach(n=>{y.info(`${Ke}- ${[n.testDefinition.relativeFilePath]}${typeof n.inputIndex=="number"?` with input set ${n.inputIndex}`:""}`)}),y.log(""))}function xO(t,e,n){e.length===0&&t.length>0||(y.info(`Running ${e.length} ${Vl(e)} with ${LT(n)}:`),e.forEach(r=>{y.info(`${Ke}- ${[r.testDefinition.relativeFilePath]}${typeof r.inputIndex=="number"?` with input set ${r.inputIndex}`:""}`)}),y.log(""))}function NT({logger:t,localTestsToRunWithInputs:e,parallel:n,shardCount:r,shardIndex:o}){t.info({tests:e.length,shardCount:r,shardIndex:o,parallel:n},"Running local tests");let[i,a]=vO(e,s=>s.quarantined);AO(i,n),xO(i,a,n)}import{cloneDeep as fi}from"lodash-es";async function kT({orgId:t,codeEvalTools:e,logger:n,outputDefinitions:r,testContext:o,flagStore:i}){let a={};for(let s of r){let{name:l,value:c}=s;a[l]=await $t({orgId:t,s:c,localTools:e,logger:n,context:o})}return a}async function _T({baseUrl:t,envName:e,testName:n,devicePixelRatio:r,apiClient:o,test:i,storageClient:a,codeEvalTools:s,generator:l,orgId:c,variables:d,logger:u,customHeaders:m,testInputs:g,localBrowserConfig:p,aiSettings:h,visualDiffScreenshotStorage:f,flagStore:S}){let b=await sl({settings:p,customHeaders:m,envVariables:d,envName:e,testName:n,baseUrl:t,logger:u,localTools:s,orgId:c}),E={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:X},v=S.isBooleanFlagEnabled("icon_knowledge_base")?await a.fetchIconKnowledgeBase(u):null,R=b.browserType??"Chromium";if(!yh(R)){let k=`Browser ${R} is required by the test named ${i.name} but does not appear to be installed on this machine. Please install it using 'momentic install-browsers' before running tests. Attempting to continue...`;y.warn(k),X.warn(k)}let C=await Nn.init({baseUrl:t,logger:u,userBrowserSettings:b,storage:a,flagStore:S,enricher:new Ko(E,l),contextArgs:{viewport:i.advanced.viewport??Ot,locale:i.advanced.locale??No,geolocation:i.advanced.geolocation??_o,timezoneId:i.advanced.timezone??ko,colorScheme:i.advanced.colorScheme,deviceScaleFactor:r},iconKnowledgeBase:v}),x=new ui({browser:C,generator:l,logger:u,orgId:c,options:{scratchPadId:void 0,slowMoMs:b.slowMoMs,autoFollowNewTabs:b.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering??S.isBooleanFlagEnabled("rag_v2")},storage:a,flagStore:S,localCodeEvalTools:s,visualDiffScreenshotStorage:f}),L=new Yt({baseUrl:t,currentUrl:x.browser.url(),variablesFromEnvironment:d,envName:e,testName:n});return i.parameters&&await Promise.all(i.parameters.map(async k=>{let{name:N,defaultValue:V,required:P}=k,G=g?.[N];P&&G===void 0&&(y.error(`Required parameter '${N}' is required by test '${i.name}' but not provided`),process.exit(1));let _=await $t({orgId:c,s:G??V,localTools:s,logger:u,context:Yt.dummyContext(L.getEnvName())});L.setMomenticSystemVariable(N,_)})),{controller:x,context:L}}async function DT({testAdvancedSettings:t,orgSettings:e,logger:n}){if(t.failureRecovery===!1||t.failureRecovery===void 0&&!e?.failureRecovery)return!1;if(!Ti){let r="This test is ineligible for failure recovery since this does not appear to be a CI environment";return n.warn(r),y.warn(r),!1}return!0}async function FT({attemptInputs:t,attemptFixtures:e,attemptMetadata:n}){let{orgId:r,runId:o}=n,{controller:i,context:a,codeEvalTools:s,storageClient:l,logger:c,billingReporter:d,tracer:u}=e,{test:m,orgSettings:g}=t;c.info(`Running test '${m.name}' locally (run link: https://app.momentic.ai/runs/${o})`);let p={controller:i,storage:l,billingReporter:d,context:a,logger:c,codeEvalTools:s},h={orgId:r,runId:o,testMetadata:m,steps:m.steps,beforeSteps:m.beforeSteps,afterSteps:m.afterSteps,orgSettings:g},f={collectDebugData:!0,reinitializeBrowser:!0,disableHealing:!await DT({testAdvancedSettings:m.advanced,orgSettings:g.ai,logger:c})};return await al({fixtures:p,inputs:h,options:f,callbacks:{step:{},test:{onTestComplete:async()=>{await i.browser.cleanup()}}},testParams:{tracer:u}})}async function UT(t){let{testDefinition:e,logger:n}=t,r=new Date;try{return await IO(t)}catch(o){let i="Fatal error running test";return y.error(`${i}: ${o.message}`),n.error({err:o},i),{results:[],parameters:t,failureReason:"UnknownError",failureDetails:{errorMessage:o.message,errorStack:o.stack},status:"FAILED",attempts:0,test:e,filePath:e.relativeFilePath,startedAt:r,lastAttemptStartedAt:r,finishedAt:new Date,outputs:{}}}}async function IO(t){let{testDefinition:e,project:n,apiClient:r,orgId:o,urlOverride:i,runSigIntHandlers:a,runGroupTracer:s,logger:l,gitMetadata:c,alwaysSaveCache:d,noCache:u,runId:m,testInputs:g,quarantined:p,quarantinedReason:h,billingReporter:f}=t,S=new Wo(r,o),b=Zo({orgId:o,client:r,gitMetadata:c,alwaysSaveCache:d,noCache:u}),E=fi(e.steps),v=fi(e.beforeSteps)??void 0,R=fi(e.afterSteps)??void 0;try{await b.resolveStepCacheEntries({testId:e.id,stepLists:{steps:E,beforeSteps:v,afterSteps:R},schemaVersion:e.schemaVersion,logger:l})}catch(P){throw l.error({err:P},"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 a Momentic issue, please contact Support with the following error: ${P}`)}let C=t.envName??LO(e),x,L={};if(C){try{x=la(C,n,l)}catch(P){let G=`Failed to resolve environment ${C} for test ${e.name}: ${P}`;throw new Error(G)}L=x.variables}let k=e.baseUrl;if(i)k=i;else if(!k){let P=L[it];typeof P=="string"&&(k=P)}if(!k){let P=`Cannot run test with no base URL and no ${it} variable defined in its environment`;throw new Error(P)}let N=await s.startRun({logger:l,runId:m,originalSteps:{beforeSteps:e.beforeSteps,steps:e.steps,afterSteps:e.afterSteps},testId:e.id,testName:e.name,testDescription:e.description??void 0,testLabels:e.labels,baseUrl:k,environmentName:C,schemaVersion:e.schemaVersion,resolvedInputs:g,quarantined:p,quarantinedReason:h}),V=l.child(N.loggerBindings||{});Object.entries(N.envVarBindings||{}).forEach(([P,G])=>{L[P]=G});try{let P=await PO({...t,variables:L,envName:C,resolvedEnv:x,baseUrl:k,storageClient:S,tracer:N,logger:V,cacheStorage:b,stepsWithCaches:E,beforeStepsWithCaches:v,afterStepsWithCaches:R,billingReporter:f});return await N.finish({logger:l,status:P.status,finishedAt:P.finishedAt,failureDetails:P.failureDetails,failureReason:P.failureReason,isFlake:P.isFlake,failureRecoveryDetails:P.failureRecoveryDetails}),{runId:N.runId,...P}}finally{a?.pop()}}async function PO(t){let{testDefinition:e,stepsWithCaches:n,beforeStepsWithCaches:r,afterStepsWithCaches:o,project:i,regenerateGoldenFiles:a,apiClient:s,generator:l,baseUrl:c,storageClient:d,orgId:u,envName:m,urlOverride:g,customHeaders:p,testInputs:h,variables:f,resolvedEnv:S,retriesOverride:b,devicePixelRatio:E,logUpdate:v,tracer:R,logger:C,flagStore:x,cacheStorage:L,gitMetadata:k,quarantined:N,quarantinedReason:V,billingReporter:P}=t,G=i.config.ai?.aiFailureAnalysis??!1,_=new Date,q=new ii(i,a),re={...i.config},se={envName:m,urlOverride:g,customHeaders:p,testInputs:h},de,wt=Math.abs(b??i.config.retries??e.retries??0),fn=[];C.info({...k,labels:e.labels,name:e.name,cwd:process.cwd()},"Starting test run using CLI");for(let pe=0;pe<=wt;pe++){let ie=await R.startAttempt(),ot=C.child(ie.loggerBindings||{}),Pe={...e,steps:fi(n),beforeSteps:fi(r),afterSteps:fi(o)};pe!==0&&v("RETRY",`attempt ${pe+1}/${wt+1}`);let kn=new Date,va=re.advanced?.fakerConstantSeed??x.isBooleanFlagEnabled("faker_constant_seed"),yi=new pr({httpClient:new At({baseUrl:s.baseUrl,apiKey:s.apiKey,logger:ot}),fakerSeed:va?us:void 0}),Xl=ie;try{let{controller:_n,context:Ut}=await _T({baseUrl:c,envName:m,testName:Pe.name,apiClient:s,devicePixelRatio:E,logger:ot,storageClient:d,codeEvalTools:yi,test:Pe,generator:l,orgId:u,variables:f,customHeaders:p,testInputs:h,localBrowserConfig:{...i.config.browser||{},...S?.browser||{},...Pe.advanced},aiSettings:{...i.config.ai||{},...Pe.advanced||{}},visualDiffScreenshotStorage:q,flagStore:x});de=await FT({attemptMetadata:{attemptNumber:pe+1,orgId:u,runId:R.runId},attemptFixtures:{logger:ot,storageClient:d,billingReporter:P,codeEvalTools:yi,flagStore:x,apiClient:s,context:Ut,controller:_n,tracer:ie},attemptInputs:{test:Pe,orgSettings:re}});let H=new Date,Ar={logger:C,cacheStorage:L,orgId:u,testId:e.id,originalSteps:{steps:e.steps,beforeSteps:e.beforeSteps,afterSteps:e.afterSteps},updatedSteps:{steps:Pe.steps,beforeSteps:Pe.beforeSteps,afterSteps:Pe.afterSteps}};de?.status==="PASSED"?await _s(Ar):de?.status==="FAILED"&&await Ds(Ar),await ie.finish({logger:ot,result:de}),fn.unshift(de.status);let Sn=await kT({orgId:u,codeEvalTools:yi,logger:ot,outputDefinitions:e.outputs??[],testContext:Ut,flagStore:x}),So=Jm(fn),yo=pe+1;if(de.status!=="FAILED")return{...de,parameters:se,test:Pe,filePath:Pe.relativeFilePath,startedAt:_,lastAttemptStartedAt:kn,finishedAt:H,attempts:yo,baseUrl:c,outputs:Sn,isFlake:So,quarantined:N,quarantinedReason:V};let Xn=de.failedStepResult,Dn=Xn?.message||"Unknown failure",xr=Xn?.failureReason??Wp(Dn)??"UnknownError",Jn=ot.child({errResult:Xn,failureReason:xr,errorMessage:Dn,numAttempts:wt+1,name:Pe.name});if(pe<wt){Jn.warn(`Retrying failed execution attempt for run: ${Dn}`);continue}Jn.error(`Test failed after all exhausting attempts: ${Dn}`);let Jl=new Error(Dn),Aa={errorMessage:Dn,errorStack:Jl.stack},pt;if(G){let Qn;try{if(de.results&&de.results.length>0){let{classification:Zn,aiFailureReason:Et}=await yf({logger:ot,browserStateStorage:Xl,generator:l,results:de.results,error:Jl,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});Qn=Zn,pt=Et}}catch(Zn){ot.warn({err:Zn},"Failed to classify test results")}Qn&&(Aa.classification=Qn,xr=pt??xr)}return{...de,parameters:se,failureDetails:Aa,failureReason:xr,test:Pe,filePath:Pe.relativeFilePath,startedAt:_,lastAttemptStartedAt:kn,finishedAt:H,attempts:pe+1,baseUrl:c,outputs:Sn,quarantined:N,quarantinedReason:V}}catch(_n){bi(_n);let Ut=`Encountered fatal platform error while running test '${Pe.name}': ${_n}`,H=new Date,Ar=pe+1;ot.error({err:_n},Ut),y.error(Ut);let Sn={errorMessage:_n.message,errStack:_n.stack},So={status:"FAILED",failureDetails:Sn,failureReason:"InternalPlatformError",finishedAt:H};return await ie.finish({logger:ot,result:{status:"FAILED",results:[]}}),{...So,results:[],parameters:se,test:Pe,filePath:Pe.relativeFilePath,startedAt:_,lastAttemptStartedAt:kn,finishedAt:new Date,attempts:Ar,baseUrl:c,outputs:{},quarantined:N,quarantinedReason:V}}}throw new Error("This code should not be reachable")}function LO(t){for(let e of t.envs??[])if(e.default)return e.name}import{randomUUID as MO}from"crypto";var vr="assets";function OO(t){switch(t){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}function NO(t){switch(t){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var rm=class{constructor(e,n,r,o){this.testId=e;this.testName=n;this.metadata=r;this.diskStorage=o}children=[];finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:n,screenshot:r}=e;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${vr}/${n}.jpeg`,contents:r})}attachAfterScreenshot(e){let{snapshotId:n,screenshot:r}=e;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${vr}/${n}.jpeg`,contents:r})}attachBeforeHtmlSnapshot(e){let{snapshotId:n,html:r}=e;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${vr}/${n}.html`,contents:r})}attachAfterHtmlSnapshot(e){let{snapshotId:n,html:r}=e;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${vr}/${n}.html`,contents:r})}heal(e){let{healType:n}=e;this.metadata.healMetadata={healType:n,healedAt:new Date}}async finishInternal(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(n=>n.finish({status:NO(e.status),finishedAt:e.finishedAt}))))}async finish(e){await this.finishInternal(e.step)}async startSubSteps(){let e=new Si(this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},Si=class{constructor(e,n,r){this.testId=e;this.testName=n;this.diskStorage=r}children=[];finished=!1;async getScreenshot(e,n){return this.diskStorage.readFile(`${vr}/${n}.jpeg`)}async getHtmlSnapshot(e,n){return this.diskStorage.readFile(`${vr}/${n}.html`)?.toString()}getParentStepIdChain(){return[]}async startStep(e){let{step:n}=e,r={step:n,status:"RUNNING",startedAt:new Date},o=new rm(this.testId,this.testName,r,this.diskStorage);return this.children.push(o),o}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(n=>n.finishInternal({status:OO(e.status),finishedAt:e.finishedAt}))))}},om=class{constructor(e,n,r,o,i){this.testId=e;this.testName=n;this.runAttemptId=r;this.metadata=o;this.diskStorage=i;this.diskStorage.mkdir("assets")}finished=!1;children=[];get loggerBindings(){return{runAttemptId:this.runAttemptId}}attachNetworkLogs(e){let{logs:n}=e;this.diskStorage.storeFile({name:"network.har",contents:JSON.stringify(n,null,2)})}attachConsoleLogs(e){let{logs:n}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(n,null,2)})}async finish(e){if(this.finished)return;this.finished=!0;let{logger:n,result:r}=e,o={...this.metadata,status:r.status,finishedAt:new Date,results:Us(r.results,n),beforeResults:r.beforeResults?Us(r.beforeResults,n):void 0,afterResults:r.afterResults?Us(r.afterResults,n):void 0};await Promise.all(this.children.map(i=>i.finish({status:o.status,finishedAt:o.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)})}async startBeforeStepList(){let e=new Si(this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new Si(this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new Si(this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,n){return this.diskStorage.readFile(`${vr}/${n}.jpeg`)}async getHtmlSnapshot(e,n){return this.diskStorage.readFile(`${vr}/${n}.html`)?.toString()}},im=class{constructor(e,n,r,o,i){this.testId=e;this.testName=n;this.runId=r;this.metadata=o;this.diskStorage=i}children=[];finished=!1;get loggerBindings(){return{runId:this.runId}}get envVarBindings(){return{[hS]:this.runId}}async finish(e){if(this.finished)return;this.finished=!0;let n={...this.metadata,finishedAt:e.finishedAt||new Date,status:e.status,failureDetails:e.failureDetails,failureReason:e.failureReason,flake:e.isFlake||!1,failureRecoveryDetails:e.failureRecoveryDetails};await Promise.all(this.children.map(r=>r.finish({logger:e.logger,result:{status:n.status,results:[],beforeResults:[],afterResults:[]}}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)}),this.diskStorage.close()}async startAttempt(){this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)});let e=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),n=MO(),r={id:n,schemaVersion:ce,runAttemptSchemaVersion:rh,startedAt:new Date,status:"RUNNING"};e.storeFile({name:"metadata.json",contents:JSON.stringify(r,null,2)});let o=new om(this.testId,this.testName,n,r,e);return this.children.push(o),o}},ql=class t{constructor(e,n,r,o){this.orgId=e;this.runGroupId=n;this.metadata=r;this.diskStorage=o}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start(e,n,r,o,i){let a={...o,id:n,trigger:Xt.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Yn,labels:i??[]},s=new da(r);return s.storeFile({name:"metadata.json",contents:JSON.stringify(a,null,2)}),new t(e,n,a,s)}async finish(e){if(this.finished)return;this.finished=!0;let{status:n}=e,r={...this.metadata,status:n,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(o=>o.finish({logger:e.logger,status:r.status,finishedAt:r.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(r,null,2)})}async startRun(e){let n=this.diskStorage.createRunArchive(e.runId),r={stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,testDescription:e.testDescription,labels:e.testLabels,trigger:"CLI",status:"RUNNING",resolvedBaseUrl:e.baseUrl,environmentName:e.environmentName,resolvedInputs:e.resolvedInputs,cliVersion:Yn,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined??!1,quarantinedReason:e.quarantinedReason,executionType:"WEB"};n.storeFile({name:"metadata.json",contents:JSON.stringify(r,null,2)});let o=new im(e.testId,e.testName,e.runId,r,n);return this.children.push(o),o}};async function BT(t,e,n){if(n)return{};try{return(await e.getQuarantinedTests()).quarantined.reduce((o,i)=>(o[i.testId]=i.quarantinedReason,o),{})}catch(r){return t.warn({err:r},"Failed to fetch quarantined tests, proceeding without them."),{}}}async function zT(t){let{logger:e,tests:n,yes:r,start:o,waitOn:i,client:a,debugDataStorage:s,billingReporter:l,flagStore:c,project:d,retriesOverride:u,urlOverride:m,envName:g,orgId:p,devicePixelRatio:h,customHeaders:f,testInputMatrix:S,reporter:b,include:E,exclude:v,labels:R,reporterDir:C=Ff,outputDir:x=Uf,uploadResults:L=!1,waitOnTimeout:k=60,parallel:N,shardIndex:V=1,shardCount:P=1,regenerateGoldenFiles:G,gitMetadata:_,alwaysSaveCache:q,noCache:re,ignoreQuarantine:se,skipQuarantined:de,onlyQuarantined:wt,runGroupId:fn}=t;o&&(e.info({orgId:p},`Executing start command: ${o}`),await AT(o,!1)),i&&(e.info({orgId:p},`Waiting for url: ${i} with timeout: ${k} seconds.`),await DO({resources:[i],interval:2500,timeout:k*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let pe=new qo(d.config.ai?.agentConfig,{baseUrl:a.baseUrl,apiKey:a.apiKey,logger:e}),ie=te(d,y),ot=await Wl({tests:n,momenticFiles:ie,yes:r,project:d,include:E,exclude:v,labels:R,logger:y}),Pe=await BT(e,a,se),{testsToSkip:kn,quarantinedTestsToSkip:va,testsToRun:yi,quarantinedTestsToRun:Xl}=IT({testDefinitions:ot,quarantinedTestReasons:Pe,onlyQuarantined:wt,skipQuarantined:de});MT(kn),OT(va,Pe);let _n=PT({testsToRun:yi,quarantinedTestsToRun:Xl,quarantinedTestReasons:Pe,testInputMatrix:S}),Ut=UO({globalTestsToRunWithInputs:_n,shardIndex:V,shardCount:P});NT({logger:e,localTestsToRunWithInputs:Ut,parallel:N,shardCount:P,shardIndex:V});let H=[],Ar=new Date,Sn=new Set,So=async()=>{let pt=a.getAppUrl(),Qn=Go({results:H,startTime:Ar.getTime(),onFailed:Et=>{As(Et,Et.filePath)},getDisplayLine:Et=>{let Ir=`${Ke}- ${Et.filePath}${Et.failureRecoveryDetails?" [recovered] ":""}`;return Et.runId&&(Ir+=` ( link when uploaded: ${pt}/runs/${Et.runId} )`),Ir},entity:"test"}),Zn=H.filter(Et=>!!Et.failureRecoveryDetails?.attempts);return Zn.length>0&&y.warn(`Our AI agent automatically prevented ${Zn.length} tests from failing due to transient issues. Use the run links above to review the additional steps that were executed.`),y.log(""),L?(y.success(`Test results have been saved to the folder ${x}. Uploading to Momentic Cloud...`),await Zs({client:a,consoleLogger:y,resultsPath:x})):y.success(`Test results have been saved to the folder ${x}. Upload them to Momentic Cloud by running 'npx momentic results upload ${x}'.`),Qn};_O.existsSync(x)&&y.warn(`Output directory ${x} already exists, removing before test execution...`);let yo=await ql.start(p,fn,x,_,R),Xn=e.child(yo.loggerBindings||{}),Dn=[],xr=async()=>{y.warn("SIGINT received. Stopping tests and printing latest results..."),await yo.finish({logger:Xn,status:"CANCELLED"}),await So(),await Promise.allSettled(Dn.map(pt=>pt())),process.exit(1)};process.once("SIGINT",xr);let Jn={};for(let pt=0;pt<Ut.length;pt++){let Qn=Object.values(Jn);Qn.length===N&&await Promise.race(Qn.map(Ir=>Ir.promise));let Zn=Ut[pt],Et=`test-${pt}`;Jn[Et]={done:!1,promise:(async({inputs:Ir,quarantined:VT,quarantinedReason:qT,testDefinition:bo})=>{Sn.add({inputs:Ir});let xa=bo.relativeFilePath.includes("..")?bo.fullFilePath:bo.relativeFilePath;Xi({status:"START",testLogRef:xa,getRunningTestsCount:()=>Sn.size,getTotalTestsCount:()=>Ut.length});let KT=setInterval(()=>Xi({status:"RUN",testLogRef:xa,getRunningTestsCount:()=>Sn.size,getTotalTestsCount:()=>Ut.length}),5*60*1e3),lm=kO(),cm=Xn.child({testId:bo.id,runId:lm});try{let Ia=await UT({testDefinition:bo,project:d,testInputs:Ir,quarantined:VT,quarantinedReason:qT,orgId:p,runId:lm,devicePixelRatio:h,apiClient:a,runGroupTracer:yo,generator:pe,retriesOverride:u,urlOverride:m,envName:g,customHeaders:f,regenerateGoldenFiles:G,logUpdate:(Pa,YT)=>Xi({status:Pa,testLogRef:xa,getRunningTestsCount:()=>Sn.size,getTotalTestsCount:()=>Ut.length,additionalText:YT}),runSigIntHandlers:Dn,logger:cm,flagStore:c,gitMetadata:_,alwaysSaveCache:q,noCache:re,billingReporter:l});Xi({status:Ia.status,testLogRef:xa,getRunningTestsCount:()=>Sn.size,getTotalTestsCount:()=>Ut.length}),H.push(Ia)}catch(Ia){let Pa=`Encountered unexpected fatal error when running test '${bo.name}': ${Ia.message}`;y.error(Pa),cm.error(Pa)}finally{clearInterval(KT),Jn[Et].done=!0,delete Jn[Et]}})(Zn)}}await Promise.allSettled(Object.values(Jn).map(pt=>pt.promise));let Aa=H.some(pt=>!pt.quarantined&&pt.status==="FAILED")?"FAILED":"PASSED";return await yo.finish({logger:Xn,status:Aa}),process.off("SIGINT",xr),b&&await RT(Xn,s,b,{projectConfigPath:d.configFilePath,suiteName:d.config.name,startedAt:Ar,finishedAt:new Date,runs:H,testsToSkip:kn,quarantinedTestsToSkip:va,quarantinedTestReasons:Pe},C),So()}function FO(t,e,n){if(n>t.length&&(y.warn(`Shard count ${n} is greater than the number of tests ${t.length}! Some workers won't have any tests to run.`),n=Math.max(n,t.length),e>n))return[];let r=Math.floor((e-1)*(t.length/n)),o=Math.floor(e*(t.length/n));return t.sort().filter((a,s)=>s>=r&&s<o)}function UO({globalTestsToRunWithInputs:t,shardIndex:e,shardCount:n}){return n&&n>1?FO(t,e,n):t}Ql||X.warn("Sentry is not enabled in this environment due to unsupported node version");var WO=process.argv.some(t=>t.includes("--log-level"))&&process.argv.some(t=>t.includes("debug")),am=t=>{WO&&y.dimmed(t)},Tt=new BO;Tt.name("momentic").description("Momentic CLI").version(Yn);Tt.command("install-browsers").description("Install browser executables onto the local machine.").option("-f, --force","Force reinstallation even if the browser executables already exist on disk.").option("-a, --all","Install all browsers types.").argument("[browsers...]",`Browsers to install. Available choices: ${hd.join(", ")}.`).action(async(t,e)=>{!e.all&&t.length===0&&(y.error("No browsers specified"),process.exit(1)),await bh({rawBrowsers:t,force:e.force,all:e.all})});Tt.addOption(new Ft("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",t=>{t==="debug"&&y.info("Enabling debug logging"),y.setMinLevel(t.toLowerCase())});Tt.addOption(new Ft("--verbose","enable verbose logging")).on("option:verbose",()=>{X.enableConsoleLogs(),y.setMinLevel(20)});var sm=Tt.command("checks").alias("check").description("Perform various project checks");sm.command("config").addOption(Gt).action(async t=>{ct({configFilePath:t.config})});sm.command("duplicate-ids").description("Checks if any steps in your entire Momentic test repository share the same ID.").addOption(Gt).addOption(nT).action(async t=>{let e=ct({configFilePath:t.config});await $b({project:e,fix:t.fix})});sm.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(Gt).action(async t=>{let e=ct({configFilePath:t.config});await jb({project:e})});var $T=Tt.command("migrate").description("Migrate and upgrade tooling");$T.command("steps").description("Migrate steps in all tests and modules to the latest schema version. Note that this is always done when a test is loaded through the interactive editor, so is generally not needed.").addOption(Gt).action(async t=>{let e=ct({configFilePath:t.config});await uT(e)});$T.command("v1-v2").description("Migrate from v1 of the Momentic CLI to v2").addOption(hn).addOption(Gt).addOption(gn).addOption(Rr).action(async t=>{!t.yes&&!await bt("This command will modify your existing Momentic configuration. Please backup your local directory using Git or another version control system before proceeding. Continue?",!0)&&process.exit(1);let e=ct({configFilePath:t.config}),n=new Je({baseUrl:t.server,apiKey:t.apiKey,logger:X}),{orgId:r}=await n.getAuthInfo();await pT({project:e,orgId:r,apiClient:n}),process.exit(0)});Tt.command("import").addOption(gn).addOption(hn).addOption(Gt).addOption(Rr).addArgument(sT).action(async(t,e)=>{let{apiKey:n,server:r,config:o,yes:i}=e,a=ct({configFilePath:o}),s=new Je({baseUrl:r,apiKey:n,logger:X});!t||t.length===0?await Kb({client:s,project:a,skipPrompts:i}):await Yb({client:s,project:a,paths:t,skipPrompts:i}),process.exit(0)});Tt.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new Ft("--name <name>","Name of the project")).action(async t=>{y.info(`Welcome to the Momentic project setup wizard! \u{1F680}
3981
- `),y.info("This wizard will help you bootstrap a new Momentic project. If you need to import existing assets from Momentic Cloud, you can call the 'import' command after initialization."),Yl.existsSync(ni)&&(y.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 n={name:t.name??await gh("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:Bd};ri(n,ni),y.success(`Initialized Momentic project file at ${Kl.resolve(ni)}`)});Tt.command("app").addOption(gn).addOption(hn).addOption(Rr).addOption($u).addOption(Gt).addOption(Gu).addOption(Wu).action(async t=>{let{apiKey:e,yes:n,server:r,pixelRatio:o,disableCache:i,saveCache:a}=t,s=ct({configFilePath:t.config,nameFilter:void 0}),{errors:l}=await Ml({project:s,fix:!1});l>0&&(y.error(`Found ${l} errors`),y.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1));let c=new Je({baseUrl:r,apiKey:e,logger:X});await bd({client:c,skipPrompts:n});let d=GO(import.meta.url),u=Kl.dirname(d),m=Kl.resolve(u,"..","static"),g=Kl.resolve(u,"..","assets"),p=o??Qu();Zu(p),await Ub({momenticServerUrl:r,apiKey:e,serverPort:Ol,appPort:Ol,staticDir:m,assetsDir:g,devicePixelRatio:p,noCache:i,alwaysSaveCache:a,initialProject:s});let h=`http://localhost:${Ol}`;await jO(h)});var jT=Tt.command("queue").description("Queue tests or suites to run on Momentic Cloud");jT.command("suites").description("Run one or more suites on Momentic Cloud").addOption(gn).addOption(hn).addOption(Fu).addOption(Uu).addOption(Rr).addArgument(lT).addOption(Dl).addOption(_l).addOption(kl).action(async(t,e)=>{let{apiKey:n,server:r,wait:o,waitTimeout:i,env:a,urlOverride:s}=e,l=Nl(e.customHeaders),c=new Je({baseUrl:r,apiKey:n,logger:X});(!t||!Array.isArray(t)||!t.length)&&(y.error("Must pass at least one suite to run."),process.exit(1));let{orgId:d}=await c.getAuthInfo();await ST({client:c,orgId:d,wait:o,suitePaths:t,waitTimeout:i,env:a,urlOverride:s,customHeaders:l})});jT.command("tests").description("Run one or more tests on Momentic Cloud").addOption(gn).addOption(hn).addOption(Rr).addOption(kl).addOption(ju).addOption(Dl).addOption(_l).addOption(new Ft("--all","Run all tests.").default(!1)).addOption(Fu).addOption(Uu).addArgument(aT).action(async(t,e)=>{let{all:n,apiKey:r,env:o,server:i,inputCsv:a,urlOverride:s,wait:l,waitTimeout:c,yes:d}=e,u=Nl(e.customHeaders);for(let h of t)(h.endsWith(".yaml")||Yl.existsSync(h))&&y.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 m=new Je({baseUrl:i,apiKey:r,logger:X}),{orgId:g}=await m.getAuthInfo(),p;a&&(p=await em(a)),await yT({client:m,orgId:g,tests:t,all:n,customHeaders:u,env:o,urlOverride:s,wait:l,waitTimeout:c,testInputMatrix:p,yes:d}),process.exit(0)});var VO=Tt.command("list").description("List test paths");VO.addOption(Gt).addOption(gi).addOption(zu).addOption(Hu).addOption(new Ft("--labels <labels...>","Only run tests with the specified label(s).")).addArgument(Vu).action(async(t,e)=>{let n=ct({configFilePath:e.config,nameFilter:e.filter}),r=te(n,y),o=await Wl({tests:t,momenticFiles:r,yes:!0,project:n,include:e.include,exclude:e.exclude,labels:e.labels,logger:new Wi(40,{})});y.info(o.map(i=>i.relativeFilePath).join(`
3982
- `)),process.exit(0)});var qO=Tt.command("run").alias("test").description("Run tests on the local machine");qO.addOption(gn).addOption(hn).addOption(Gt).addOption(gi).addOption(Rr).addOption(kl).addOption(ju).addOption(Gu).addOption(Wu).addOption(rT).addOption(oT).addOption(iT).addOption(_l).addOption(Dl).addOption($u).addOption(new Ft("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new Ft("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new Ft("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.").default(60).argParser(Cr)).addOption(new Ft("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.").argParser(Cr)).addOption(new Ft("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(Cr)).addOption(new Ft("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new Ft("--update-golden-files","Update locally stored golden files for steps that this is enabled for.").default(!1)).addOption(Jb).addOption(Qb).addOption(Bu).addOption(Zb).addOption(tT).addOption(eT).addOption(zu).addOption(Hu).addArgument(Vu).action(async(t,e)=>{if(e.shardIndex>e.shardCount)throw new Error("Shard index cannot be greater than shard count");let n=Nl(e.customHeaders),r=ct({configFilePath:e.config,nameFilter:e.filter}),o=e.parallel??r.config.parallel??1;HT().length<o*2&&y.warn(`You requested to run tests in parallel ${o} at a time on a machine with ${HT().length} cores. This may cause performance issues and test failures as Chrome requires at least 2 cores per browser instance.`),y.debug({projectName:r.config.name},"Identified project config");let{errors:i}=await Ml({project:r,fix:!1});i>0&&(y.error(`Found ${i} errors`),y.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1));let a=new Je({baseUrl:e.server,apiKey:e.apiKey,logger:X});y.debug("Checking API key and dependencies");let{orgId:s,userId:l}=await bd({client:a,skipPrompts:e.yes});y.debug("API key check and browser installation complete");let c=new Is(a),d=new Bi,u=e.outputDir??r.config.outputDir,m=e.reporterDir??r.config.reporterDir,g=HO(),p=X.child({runGroupId:g,orgId:s,userId:l,cliVersion:Yn,trigger:"CLI"}),h=await fr(X,a,r);p.info(h,"Got local git metadata");let f=new hr(r.config),S;e.inputCsv&&(S=await em(e.inputCsv));let b=e.pixelRatio??Qu();Zu(b);try{(await zT({...e,parallel:o,retriesOverride:e.retries,devicePixelRatio:b,tests:t,project:r,client:a,debugDataStorage:d,billingReporter:c,flagStore:f,outputDir:u,uploadResults:e.uploadResults,reporterDir:m,customHeaders:n,envName:e.env,orgId:s,testInputMatrix:S,logger:p,regenerateGoldenFiles:e.updateGoldenFiles,gitMetadata:h,alwaysSaveCache:e.saveCache,noCache:e.disableCache,runGroupId:g})).failed>0?process.exit(1):process.exit(0)}catch(E){y.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),y.error(E),process.exit(1)}});var KO=Tt.command("apply").description("Apply an operation to local resources");KO.command("patch").addOption(gn).addOption(hn).addOption(Gt).addOption(gi).addOption(Rr).addOption(new Ft("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new Ft("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async t=>{let{apiKey:e,server:n,config:r,yes:o}=t,i=ct({configFilePath:r}),a=X,s=new Je({baseUrl:n,apiKey:e,logger:a}),l=te(i,y),c=l.tests[t.to]??Object.values(l.tests).find(u=>ve(u.name)===t.to.trim());c||(y.error(`No test matching '${t.to}' could be found in the current project.`),process.exit(1));let d=await s.fetchTestFragment(t.from);await zb({client:s,test:c,fragment:d,yes:o,entities:l,logger:X}),process.exit(0)});var GT=Tt.command("results").description("Merge and upload test results.");GT.command("merge").description("Merge test results files.").addOption(Bu).addArgument(cT).action(async(t,e)=>{let{outputDir:n}=e;n||(y.error("Output directory is required."),process.exit(1)),Yl.existsSync(t)||(y.warn("Results path does not exist, skipping merge."),process.exit(0)),Yl.existsSync(n)&&y.warn(`Output directory ${n} already exists, removing before merging...`),$f(X,n,t)});GT.command("upload").description("Upload test results to Momentic cloud.").addOption(gn).addOption(hn).addArgument(dT).action(async(t,e)=>{let{apiKey:n,server:r}=e,o=X,i=new Je({baseUrl:r,apiKey:n,logger:o});await Zs({consoleLogger:y,resultsPath:t,client:i}),process.exit(0)});var WT=Tt.command("quarantine").description("Manage test quarantines");WT.command("add").description("Add a test to the quarantine. This will prevent it from running.").addOption(gn).addOption(hn).addOption(Gt).addOption(gi).addOption(qu).addArgument(Ku).action(async(t,e)=>{let{apiKey:n,server:r,config:o,reason:i}=e,a=X,s=ct({configFilePath:o}),l=new Je({baseUrl:r,apiKey:n,logger:a}),c=await fr(X,l,s);await gT({test:t,reason:i,apiClient:l,project:s,logger:a,identity:c})});WT.command("remove").description("Remove a test from the quarantine. This will allow it to run again.").addOption(gn).addOption(hn).addOption(Gt).addOption(gi).addOption(qu).addArgument(Ku).action(async(t,e)=>{let{apiKey:n,server:r,config:o,reason:i}=e,a=X,s=ct({configFilePath:o}),l=new Je({baseUrl:r,apiKey:n,logger:a}),c=await fr(X,l,s);await hT({test:t,reason:i,apiClient:l,project:s,logger:a,identity:c})});async function YO(){am("Main program started"),await xT(X),am("CLI version check complete");try{await Tt.parseAsync(process.argv)}catch(t){let e={};try{e.playwrightVersion=zO("npx playwright --version").toString()}catch(n){X.error({err:n},"Error fetching debug information")}X.error({err:t,debugInfo:e},"Uncaught error in CLI"),X.flush(),bi(t,e),y.error(t),process.exit(1)}}$O.setMaxListeners(50);process.on("warning",t=>{X.warn({err:t},`Node warning received on CLI: ${t.message}`)});am("CLI parsing setup complete");YO();
3980
+ `)}`),Object.values(e.tests).forEach(m=>{t.some(p=>m.relativePath.includes(p))&&l.add(m.fullFilePath)}))}else{!r&&!await bt("No test paths or substrings were provided. Do you want to run all tests?")&&(s.error("Cancelled by user."),process.exit(1));let d=Object.values(e.tests);s.info(`Reading all ${d.length} tests in the project from local disk.`),d.forEach(u=>{l.add(u.fullFilePath)})}for(let d of l){let u=um.relative(n.rootDir,d);o&&!o.some(m=>new RegExp(m).test(u))&&l.delete(d),a&&a.some(m=>new RegExp(m).test(u))&&l.delete(d)}let c=Array.from(l).map(async d=>{try{let u=await Mt(d,X,e);if(BO.gt(u.schemaVersion,se)&&s.warn(`Test ${d} has schema version ${u.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`),i&&i.length>0){let m=u.labels||[];if(!i.some(g=>m.includes(g)))return null}return{...u,fullFilePath:d,relativeFilePath:um.relative(n.rootDir,d)}}catch(u){s.error(`Failed to read and resolve test at '${d}': ${u}`),process.exit(1)}});return Promise.all(c).then(FO)}function DT({testDefinitions:t,quarantinedTestReasons:e,onlyQuarantined:n=!1,skipQuarantined:r=!1}){if(n){let[d,u]=Ql(t,g=>g.id in e),[m,p]=Ql(d,g=>g.disabled||r);return{testsToSkip:m,quarantinedTestsToSkip:[],testsToRun:p,quarantinedTestsToRun:[]}}let[o,a]=Ql(t,d=>d.disabled),[i,s]=Ql(a,d=>d.id in e);return{testsToSkip:o,testsToRun:s,quarantinedTestsToRun:r?[]:i,quarantinedTestsToSkip:r?i:[]}}function FT({testsToRun:t,quarantinedTestsToRun:e,quarantinedTestReasons:n,testInputMatrix:r}){let o=[],a=(i,s,l)=>{r?r.forEach((c,d)=>{o.push({inputs:c,inputIndex:d,testDefinition:i,quarantined:s,quarantinedReason:l})}):o.push({inputs:void 0,testDefinition:i,quarantined:s,quarantinedReason:l})};return t.forEach(i=>a(i,!1)),e.forEach(i=>a(i,!0,n[i.id])),o}import{partition as zO}from"lodash-es";function ec(t){return t.length===1?"test":"tests"}function UT(t){return t===1?"1 worker":`${t} workers`}function BT(t){t.length!==0&&(S.info(`Skipping ${t.length} disabled ${ec(t)}:`),t.forEach(e=>{S.info(`${Ke}- ${[e.relativeFilePath]}`)}),S.log(""))}function zT(t,e){t.length!==0&&(S.info(`Skipping ${t.length} quarantined ${ec(t)}:`),t.forEach(n=>{S.info(`${Ke}- ${[n.relativeFilePath]}: ${e[n.id]}`)}),S.log(""))}function HO(t,e){t.length!==0&&(S.info(`Running ${t.length} quarantined ${ec(t)} with ${UT(e)}:`),t.forEach(n=>{S.info(`${Ke}- ${[n.testDefinition.relativeFilePath]}${typeof n.inputIndex=="number"?` with input set ${n.inputIndex}`:""}`)}),S.log(""))}function $O(t,e,n){e.length===0&&t.length>0||(S.info(`Running ${e.length} ${ec(e)} with ${UT(n)}:`),e.forEach(r=>{S.info(`${Ke}- ${[r.testDefinition.relativeFilePath]}${typeof r.inputIndex=="number"?` with input set ${r.inputIndex}`:""}`)}),S.log(""))}function HT({logger:t,localTestsToRunWithInputs:e,parallel:n,shardCount:r,shardIndex:o}){t.info({tests:e.length,shardCount:r,shardIndex:o,parallel:n},"Running local tests");let[a,i]=zO(e,s=>s.quarantined);HO(a,n),$O(a,i,n)}import{cloneDeep as ya}from"lodash-es";async function $T({orgId:t,codeEvalTools:e,logger:n,outputDefinitions:r,testContext:o,flagStore:a}){let i={};for(let s of r){let{name:l,value:c}=s;i[l]=await jt({orgId:t,s:c,localTools:e,logger:n,context:o})}return i}async function jT({baseUrl:t,envName:e,testName:n,devicePixelRatio:r,apiClient:o,test:a,storageClient:i,codeEvalTools:s,generator:l,orgId:c,variables:d,logger:u,customHeaders:m,testInputs:p,localBrowserConfig:g,aiSettings:h,visualDiffScreenshotStorage:f,flagStore:y}){let b=await hl({settings:g,customHeaders:m,envVariables:d,envName:e,testName:n,baseUrl:t,logger:u,localTools:s,orgId:c}),w={baseUrl:o.baseUrl,apiKey:o.apiKey,logger:X},C=y.isBooleanFlagEnabled("icon_knowledge_base")?await i.fetchIconKnowledgeBase(u):null,v=b.browserType??"Chromium";if(!Ih(v)){let D=`Browser ${v} is required by the test named ${a.name} but does not appear to be installed on this machine. Please install it using 'momentic install-browsers' before running tests. Attempting to continue...`;S.warn(D),X.warn(D)}let R=await kn.init({baseUrl:t,logger:u,userBrowserSettings:b,storage:i,flagStore:y,enricher:new Xo(w,l),contextArgs:{viewport:a.advanced.viewport??Nt,locale:a.advanced.locale??_o,geolocation:a.advanced.geolocation??Fo,timezoneId:a.advanced.timezone??Do,colorScheme:a.advanced.colorScheme,deviceScaleFactor:r},iconKnowledgeBase:C}),x=new pa({browser:R,generator:l,logger:u,orgId:c,options:{scratchPadId:void 0,slowMoMs:b.slowMoMs,autoFollowNewTabs:b.autoFollowNewTabs,useMemory:h.useMemory,aiPageFiltering:h.aiPageFiltering??y.isBooleanFlagEnabled("rag_v2")},storage:i,flagStore:y,localCodeEvalTools:s,visualDiffScreenshotStorage:f}),M=new Xt({baseUrl:t,currentUrl:x.browser.url(),variablesFromEnvironment:d,envName:e,testName:n});return a.parameters&&await Promise.all(a.parameters.map(async D=>{let{name:_,defaultValue:K,required:P}=D,W=p?.[_];P&&W===void 0&&(S.error(`Required parameter '${_}' is required by test '${a.name}' but not provided`),process.exit(1));let k=await jt({orgId:c,s:W??K,localTools:s,logger:u,context:Xt.dummyContext(M.getEnvName())});M.setMomenticSystemVariable(_,k)})),{controller:x,context:M}}async function GT({testAdvancedSettings:t,orgSettings:e,logger:n}){if(t.failureRecovery===!1||t.failureRecovery===void 0&&!e?.failureRecovery)return!1;if(!Ea){let r="This test is ineligible for failure recovery since this does not appear to be a CI environment";return n.warn(r),S.warn(r),!1}return!0}async function WT({attemptInputs:t,attemptFixtures:e,attemptMetadata:n}){let{orgId:r,runId:o}=n,{controller:a,context:i,codeEvalTools:s,storageClient:l,logger:c,billingReporter:d,tracer:u}=e,{test:m,orgSettings:p}=t;c.info(`Running test '${m.name}' locally (run link: https://app.momentic.ai/runs/${o})`);let g={controller:a,storage:l,billingReporter:d,context:i,logger:c,codeEvalTools:s},h={orgId:r,runId:o,testMetadata:m,steps:m.steps,beforeSteps:m.beforeSteps,afterSteps:m.afterSteps,orgSettings:p},f={collectDebugData:!0,reinitializeBrowser:!0,disableHealing:!await GT({testAdvancedSettings:m.advanced,orgSettings:p.ai,logger:c})};return await gl({fixtures:g,inputs:h,options:f,callbacks:{step:{},test:{onTestComplete:async()=>{await a.browser.cleanup()}}},testParams:{tracer:u}})}async function VT(t){let{testDefinition:e,logger:n}=t,r=new Date;try{return await jO(t)}catch(o){let a="Fatal error running test";return S.error(`${a}: ${o.message}`),n.error({err:o},a),{results:[],parameters:t,failureReason:"UnknownError",failureDetails:{errorMessage:o.message,errorStack:o.stack},status:"FAILED",attempts:0,test:e,filePath:e.relativeFilePath,startedAt:r,lastAttemptStartedAt:r,finishedAt:new Date,outputs:{}}}}async function jO(t){let{testDefinition:e,project:n,apiClient:r,orgId:o,urlOverride:a,runSigIntHandlers:i,runGroupTracer:s,logger:l,gitMetadata:c,alwaysSaveCache:d,noCache:u,runId:m,testInputs:p,quarantined:g,quarantinedReason:h,billingReporter:f}=t,y=new qo(r,o),b=ta({orgId:o,client:r,gitMetadata:c,alwaysSaveCache:d,noCache:u}),w=ya(e.steps),C=ya(e.beforeSteps)??void 0,v=ya(e.afterSteps)??void 0;try{await b.resolveStepCacheEntries({testId:e.id,stepLists:{steps:w,beforeSteps:C,afterSteps:v},schemaVersion:e.schemaVersion,logger:l})}catch(P){throw l.error({err:P},"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 a Momentic issue, please contact Support with the following error: ${P}`)}let R=t.envName??WO(e),x,M={};if(R){try{x=ui(R,n,l)}catch(P){let W=`Failed to resolve environment ${R} for test ${e.name}: ${P}`;throw new Error(W)}M=x.variables}let D=e.baseUrl;if(a)D=a;else if(!D){let P=M[at];typeof P=="string"&&(D=P)}if(!D){let P=`Cannot run test with no base URL and no ${at} variable defined in its environment`;throw new Error(P)}let _=await s.startRun({logger:l,runId:m,originalSteps:{beforeSteps:e.beforeSteps,steps:e.steps,afterSteps:e.afterSteps},testId:e.id,testName:e.name,testDescription:e.description??void 0,testLabels:e.labels,baseUrl:D,environmentName:R,schemaVersion:e.schemaVersion,resolvedInputs:p,quarantined:g,quarantinedReason:h}),K=l.child(_.loggerBindings||{});Object.entries(_.envVarBindings||{}).forEach(([P,W])=>{M[P]=W});try{let P=await GO({...t,variables:M,envName:R,resolvedEnv:x,baseUrl:D,storageClient:y,tracer:_,logger:K,cacheStorage:b,stepsWithCaches:w,beforeStepsWithCaches:C,afterStepsWithCaches:v,billingReporter:f});return await _.finish({logger:l,status:P.status,finishedAt:P.finishedAt,failureDetails:P.failureDetails,failureReason:P.failureReason,isFlake:P.isFlake,failureRecoveryDetails:P.failureRecoveryDetails}),{runId:_.runId,...P}}finally{i?.pop()}}async function GO(t){let{testDefinition:e,stepsWithCaches:n,beforeStepsWithCaches:r,afterStepsWithCaches:o,project:a,regenerateGoldenFiles:i,apiClient:s,generator:l,baseUrl:c,storageClient:d,orgId:u,envName:m,urlOverride:p,customHeaders:g,testInputs:h,variables:f,resolvedEnv:y,retriesOverride:b,devicePixelRatio:w,logUpdate:C,tracer:v,logger:R,flagStore:x,cacheStorage:M,gitMetadata:D,quarantined:_,quarantinedReason:K,billingReporter:P}=t,W=a.config.ai?.aiFailureAnalysis??!1,k=new Date,G=new sa(a,i),we={...a.config},Ce={envName:m,urlOverride:p,customHeaders:g,testInputs:h},be,wt=Math.abs(b??a.config.retries??e.retries??0),Sn=[];R.info({...D,labels:e.labels,name:e.name,cwd:process.cwd()},"Starting test run using CLI");for(let de=0;de<=wt;de++){let oe=await v.startAttempt(),ot=R.child(oe.loggerBindings||{}),Pe={...e,steps:ya(n),beforeSteps:ya(r),afterSteps:ya(o)};de!==0&&C("RETRY",`attempt ${de+1}/${wt+1}`);let _n=new Date,Pi=we.advanced?.fakerConstantSeed??x.isBooleanFlagEnabled("faker_constant_seed"),Ta=new gr({httpClient:new xt({baseUrl:s.baseUrl,apiKey:s.apiKey,logger:ot}),fakerSeed:Pi?gs:void 0}),oc=oe;try{let{controller:Dn,context:Bt}=await jT({baseUrl:c,envName:m,testName:Pe.name,apiClient:s,devicePixelRatio:w,logger:ot,storageClient:d,codeEvalTools:Ta,test:Pe,generator:l,orgId:u,variables:f,customHeaders:g,testInputs:h,localBrowserConfig:{...a.config.browser||{},...y?.browser||{},...Pe.advanced},aiSettings:{...a.config.ai||{},...Pe.advanced||{}},visualDiffScreenshotStorage:G,flagStore:x});be=await WT({attemptMetadata:{attemptNumber:de+1,orgId:u,runId:v.runId},attemptFixtures:{logger:ot,storageClient:d,billingReporter:P,codeEvalTools:Ta,flagStore:x,apiClient:s,context:Bt,controller:Dn,tracer:oe},attemptInputs:{test:Pe,orgSettings:we}});let yn=new Date,Pr={logger:R,cacheStorage:M,orgId:u,testId:e.id,originalSteps:{steps:e.steps,beforeSteps:e.beforeSteps,afterSteps:e.afterSteps},updatedSteps:{steps:Pe.steps,beforeSteps:Pe.beforeSteps,afterSteps:Pe.afterSteps}};be?.status==="PASSED"?await zs(Pr):be?.status==="FAILED"&&await Hs(Pr),await oe.finish({logger:ot,result:be}),Sn.unshift(be.status);let $=await $T({orgId:u,codeEvalTools:Ta,logger:ot,outputDefinitions:e.outputs??[],testContext:Bt,flagStore:x}),bo=ap(Sn),To=de+1;if(be.status!=="FAILED")return{...be,parameters:Ce,test:Pe,filePath:Pe.relativeFilePath,startedAt:k,lastAttemptStartedAt:_n,finishedAt:yn,attempts:To,baseUrl:c,outputs:$,isFlake:bo,quarantined:_,quarantinedReason:K};let Jn=be.failedStepResult,Fn=Jn?.message||"Unknown failure",Mr=Jn?.failureReason??eg(Fn)??"UnknownError",Qn=ot.child({errResult:Jn,failureReason:Mr,errorMessage:Fn,numAttempts:wt+1,name:Pe.name});if(de<wt){Qn.warn(`Retrying failed execution attempt for run: ${Fn}`);continue}Qn.error(`Test failed after all exhausting attempts: ${Fn}`);let ac=new Error(Fn),Mi={errorMessage:Fn,errorStack:ac.stack},pt;if(W){let Zn;try{if(be.results&&be.results.length>0){let{classification:er,aiFailureReason:Et}=await If({logger:ot,browserStateStorage:oc,generator:l,results:be.results,error:ac,maxItemsFromEnd:void 0,numStepsWithScreenshots:void 0,disableCache:!1});Zn=er,pt=Et}}catch(er){ot.warn({err:er},"Failed to classify test results")}Zn&&(Mi.classification=Zn,Mr=pt??Mr)}return{...be,parameters:Ce,failureDetails:Mi,failureReason:Mr,test:Pe,filePath:Pe.relativeFilePath,startedAt:k,lastAttemptStartedAt:_n,finishedAt:yn,attempts:de+1,baseUrl:c,outputs:$,quarantined:_,quarantinedReason:K}}catch(Dn){wa(Dn);let Bt=`Encountered fatal platform error while running test '${Pe.name}': ${Dn}`,yn=new Date,Pr=de+1;ot.error({err:Dn},Bt),S.error(Bt);let $={errorMessage:Dn.message,errStack:Dn.stack},bo={status:"FAILED",failureDetails:$,failureReason:"InternalPlatformError",finishedAt:yn};return await oe.finish({logger:ot,result:{status:"FAILED",results:[]}}),{...bo,results:[],parameters:Ce,test:Pe,filePath:Pe.relativeFilePath,startedAt:k,lastAttemptStartedAt:_n,finishedAt:new Date,attempts:Pr,baseUrl:c,outputs:{},quarantined:_,quarantinedReason:K}}}throw new Error("This code should not be reachable")}function WO(t){for(let e of t.envs??[])if(e.default)return e.name}import{randomUUID as VO}from"crypto";var Ir="assets";function qO(t){switch(t){case"PASSED":return"SUCCESS";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":case"PENDING":case"RETRYING":case"WAITING_FOR_USER":return"RUNNING"}}function KO(t){switch(t){case"SUCCESS":return"PASSED";case"FAILED":return"FAILED";case"CANCELLED":return"CANCELLED";case"RUNNING":return"RUNNING";case"IDLE":return"PENDING"}}var mm=class{constructor(e,n,r,o){this.testId=e;this.testName=n;this.metadata=r;this.diskStorage=o}children=[];finished=!1;getParentStepIdChain(){return[]}attachBeforeScreenshot(e){let{snapshotId:n,screenshot:r}=e;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${Ir}/${n}.jpeg`,contents:r})}attachAfterScreenshot(e){let{snapshotId:n,screenshot:r}=e;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${Ir}/${n}.jpeg`,contents:r})}attachBeforeHtmlSnapshot(e){let{snapshotId:n,html:r}=e;this.metadata.beforeSnapshotId=n,this.diskStorage.storeFile({name:`${Ir}/${n}.html`,contents:r})}attachAfterHtmlSnapshot(e){let{snapshotId:n,html:r}=e;this.metadata.afterSnapshotId=n,this.diskStorage.storeFile({name:`${Ir}/${n}.html`,contents:r})}heal(e){let{healType:n}=e;this.metadata.healMetadata={healType:n,healedAt:new Date}}async finishInternal(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(n=>n.finish({status:KO(e.status),finishedAt:e.finishedAt}))))}async finish(e){await this.finishInternal(e.step)}async startSubSteps(){let e=new ba(this.testId,this.testName,this.diskStorage);return this.children.push(e),e}},ba=class{constructor(e,n,r){this.testId=e;this.testName=n;this.diskStorage=r}children=[];finished=!1;async getScreenshot(e,n){return this.diskStorage.readFile(`${Ir}/${n}.jpeg`)}async getHtmlSnapshot(e,n){return this.diskStorage.readFile(`${Ir}/${n}.html`)?.toString()}getParentStepIdChain(){return[]}async startStep(e){let{step:n}=e,r={step:n,status:"RUNNING",startedAt:new Date},o=new mm(this.testId,this.testName,r,this.diskStorage);return this.children.push(o),o}async finish(e){this.finished||(this.finished=!0,await Promise.all(this.children.map(n=>n.finishInternal({status:qO(e.status),finishedAt:e.finishedAt}))))}},pm=class{constructor(e,n,r,o,a){this.testId=e;this.testName=n;this.runAttemptId=r;this.metadata=o;this.diskStorage=a;this.diskStorage.mkdir("assets")}finished=!1;children=[];get loggerBindings(){return{runAttemptId:this.runAttemptId}}attachNetworkLogs(e){let{logs:n}=e;this.diskStorage.storeFile({name:"network.har",contents:JSON.stringify(n,null,2)})}attachConsoleLogs(e){let{logs:n}=e;this.diskStorage.storeFile({name:"console.json",contents:JSON.stringify(n,null,2)})}async finish(e){if(this.finished)return;this.finished=!0;let{logger:n,result:r}=e,o={...this.metadata,status:r.status,finishedAt:new Date,results:Ws(r.results,n),beforeResults:r.beforeResults?Ws(r.beforeResults,n):void 0,afterResults:r.afterResults?Ws(r.afterResults,n):void 0};await Promise.all(this.children.map(a=>a.finish({status:o.status,finishedAt:o.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(o,null,2)})}async startBeforeStepList(){let e=new ba(this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startMainStepList(){let e=new ba(this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async startAfterStepList(){let e=new ba(this.testId,this.testName,this.diskStorage);return this.children.push(e),e}async getScreenshot(e,n){return this.diskStorage.readFile(`${Ir}/${n}.jpeg`)}async getHtmlSnapshot(e,n){return this.diskStorage.readFile(`${Ir}/${n}.html`)?.toString()}},gm=class{constructor(e,n,r,o,a){this.testId=e;this.testName=n;this.runId=r;this.metadata=o;this.diskStorage=a}children=[];finished=!1;get loggerBindings(){return{runId:this.runId}}get envVarBindings(){return{[vS]:this.runId}}async finish(e){if(this.finished)return;this.finished=!0;let n={...this.metadata,finishedAt:e.finishedAt||new Date,status:e.status,failureDetails:e.failureDetails,failureReason:e.failureReason,flake:e.isFlake||!1,failureRecoveryDetails:e.failureRecoveryDetails};await Promise.all(this.children.map(r=>r.finish({logger:e.logger,result:{status:n.status,results:[],beforeResults:[],afterResults:[]}}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(n,null,2)}),this.diskStorage.close()}async startAttempt(){this.metadata.attempts=this.metadata.attempts+1,this.metadata.status="RUNNING",this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(this.metadata,null,2)});let e=this.diskStorage.cd(`attempts/${this.metadata.attempts}`),n=VO(),r={id:n,schemaVersion:se,runAttemptSchemaVersion:ph,startedAt:new Date,status:"RUNNING"};e.storeFile({name:"metadata.json",contents:JSON.stringify(r,null,2)});let o=new pm(this.testId,this.testName,n,r,e);return this.children.push(o),o}},tc=class t{constructor(e,n,r,o){this.orgId=e;this.runGroupId=n;this.metadata=r;this.diskStorage=o}children=[];finished=!1;get loggerBindings(){return{orgId:this.orgId,runGroupId:this.runGroupId,branch:this.metadata.gitBranchName}}static async start(e,n,r,o,a){let i={...o,id:n,trigger:Jt.CLI,startedAt:new Date,status:"RUNNING",cliVersion:Xn,labels:a??[]},s=new pi(r);return s.storeFile({name:"metadata.json",contents:JSON.stringify(i,null,2)}),new t(e,n,i,s)}async finish(e){if(this.finished)return;this.finished=!0;let{status:n}=e,r={...this.metadata,status:n,updatedAt:new Date,finishedAt:new Date};await Promise.all(this.children.map(o=>o.finish({logger:e.logger,status:r.status,finishedAt:r.finishedAt}))),this.diskStorage.storeFile({name:"metadata.json",contents:JSON.stringify(r,null,2)})}async startRun(e){let n=this.diskStorage.createRunArchive(e.runId),r={stepsSnapshot:e.originalSteps.steps,runGroupId:this.runGroupId,testId:e.testId,testName:e.testName,testDescription:e.testDescription,labels:e.testLabels,trigger:"CLI",status:"RUNNING",resolvedBaseUrl:e.baseUrl,environmentName:e.environmentName,resolvedInputs:e.resolvedInputs,cliVersion:Xn,schemaVersion:e.schemaVersion,startedAt:new Date,attempts:0,quarantined:e.quarantined??!1,quarantinedReason:e.quarantinedReason,executionType:"WEB"};n.storeFile({name:"metadata.json",contents:JSON.stringify(r,null,2)});let o=new gm(e.testId,e.testName,e.runId,r,n);return this.children.push(o),o}};async function qT(t,e,n){if(n)return{};try{return(await e.getQuarantinedTests()).quarantined.reduce((o,a)=>(o[a.testId]=a.quarantinedReason,o),{})}catch(r){return t.warn({err:r},"Failed to fetch quarantined tests, proceeding without them."),{}}}async function KT(t){let{logger:e,tests:n,yes:r,start:o,waitOn:a,client:i,debugDataStorage:s,billingReporter:l,flagStore:c,project:d,retriesOverride:u,urlOverride:m,envName:p,orgId:g,devicePixelRatio:h,customHeaders:f,testInputMatrix:y,reporter:b,include:w,exclude:C,labels:v,reporterDir:R=qf,outputDir:x=Kf,uploadResults:M=!1,waitOnTimeout:D=60,parallel:_,shardIndex:K=1,shardCount:P=1,regenerateGoldenFiles:W,gitMetadata:k,alwaysSaveCache:G,noCache:we,ignoreQuarantine:Ce,skipQuarantined:be,onlyQuarantined:wt,runGroupId:Sn}=t;o&&(e.info({orgId:g},`Executing start command: ${o}`),await kT(o,!1)),a&&(e.info({orgId:g},`Waiting for url: ${a} with timeout: ${D} seconds.`),await JO({resources:[a],interval:2500,timeout:D*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!1,log:!0,strictSSL:!1}));let de=new Yo(d.config.ai?.agentConfig,{baseUrl:i.baseUrl,apiKey:i.apiKey,logger:e}),oe=te(d,S),ot=await Zl({tests:n,momenticFiles:oe,yes:r,project:d,include:w,exclude:C,labels:v,logger:S}),Pe=await qT(e,i,Ce),{testsToSkip:_n,quarantinedTestsToSkip:Pi,testsToRun:Ta,quarantinedTestsToRun:oc}=DT({testDefinitions:ot,quarantinedTestReasons:Pe,onlyQuarantined:wt,skipQuarantined:be});BT(_n),zT(Pi,Pe);let Dn=FT({testsToRun:Ta,quarantinedTestsToRun:oc,quarantinedTestReasons:Pe,testInputMatrix:y}),Bt=ZO({globalTestsToRunWithInputs:Dn,shardIndex:K,shardCount:P});HT({logger:e,localTestsToRunWithInputs:Bt,parallel:_,shardCount:P,shardIndex:K});let yn=[],Pr=new Date,$=new Set,bo=async()=>{let pt=i.getAppUrl(),Zn=Vo({results:yn,startTime:Pr.getTime(),onFailed:Et=>{Ls(Et,Et.filePath)},getDisplayLine:Et=>{let Lr=`${Ke}- ${Et.filePath}${Et.failureRecoveryDetails?" [recovered] ":""}`;return Et.runId&&(Lr+=` ( link when uploaded: ${pt}/runs/${Et.runId} )`),Lr},entity:"test"}),er=yn.filter(Et=>!!Et.failureRecoveryDetails?.attempts);return er.length>0&&S.warn(`Our AI agent automatically prevented ${er.length} tests from failing due to transient issues. Use the run links above to review the additional steps that were executed.`),S.log(""),M?(S.success(`Test results have been saved to the folder ${x}. Uploading to Momentic Cloud...`),await sl({client:i,consoleLogger:S,resultsPath:x})):S.success(`Test results have been saved to the folder ${x}. Upload them to Momentic Cloud by running 'npx momentic results upload ${x}'.`),Zn};XO.existsSync(x)&&S.warn(`Output directory ${x} already exists, removing before test execution...`);let To=await tc.start(g,Sn,x,k,v),Jn=e.child(To.loggerBindings||{}),Fn=[],Mr=async()=>{S.warn("SIGINT received. Stopping tests and printing latest results..."),await To.finish({logger:Jn,status:"CANCELLED"}),await bo(),await Promise.allSettled(Fn.map(pt=>pt())),process.exit(1)};process.once("SIGINT",Mr);let Qn={};for(let pt=0;pt<Bt.length;pt++){let Zn=Object.values(Qn);Zn.length===_&&await Promise.race(Zn.map(Lr=>Lr.promise));let er=Bt[pt],Et=`test-${pt}`;Qn[Et]={done:!1,promise:(async({inputs:Lr,quarantined:ew,quarantinedReason:tw,testDefinition:wo})=>{$.add({inputs:Lr});let Li=wo.relativeFilePath.includes("..")?wo.fullFilePath:wo.relativeFilePath;Za({status:"START",testLogRef:Li,getRunningTestsCount:()=>$.size,getTotalTestsCount:()=>Bt.length});let nw=setInterval(()=>Za({status:"RUN",testLogRef:Li,getRunningTestsCount:()=>$.size,getTotalTestsCount:()=>Bt.length}),5*60*1e3),Sm=YO(),ym=Jn.child({testId:wo.id,runId:Sm});try{let Oi=await VT({testDefinition:wo,project:d,testInputs:Lr,quarantined:ew,quarantinedReason:tw,orgId:g,runId:Sm,devicePixelRatio:h,apiClient:i,runGroupTracer:To,generator:de,retriesOverride:u,urlOverride:m,envName:p,customHeaders:f,regenerateGoldenFiles:W,logUpdate:(Ni,rw)=>Za({status:Ni,testLogRef:Li,getRunningTestsCount:()=>$.size,getTotalTestsCount:()=>Bt.length,additionalText:rw}),runSigIntHandlers:Fn,logger:ym,flagStore:c,gitMetadata:k,alwaysSaveCache:G,noCache:we,billingReporter:l});Za({status:Oi.status,testLogRef:Li,getRunningTestsCount:()=>$.size,getTotalTestsCount:()=>Bt.length}),yn.push(Oi)}catch(Oi){let Ni=`Encountered unexpected fatal error when running test '${wo.name}': ${Oi.message}`;S.error(Ni),ym.error(Ni)}finally{clearInterval(nw),Qn[Et].done=!0,delete Qn[Et]}})(er)}}await Promise.allSettled(Object.values(Qn).map(pt=>pt.promise));let Mi=yn.some(pt=>!pt.quarantined&&pt.status==="FAILED")?"FAILED":"PASSED";return await To.finish({logger:Jn,status:Mi}),process.off("SIGINT",Mr),b&&await OT(Jn,s,b,{projectConfigPath:d.configFilePath,suiteName:d.config.name,startedAt:Pr,finishedAt:new Date,runs:yn,testsToSkip:_n,quarantinedTestsToSkip:Pi,quarantinedTestReasons:Pe},R),bo()}function QO(t,e,n){if(n>t.length&&(S.warn(`Shard count ${n} is greater than the number of tests ${t.length}! Some workers won't have any tests to run.`),n=Math.max(n,t.length),e>n))return[];let r=Math.floor((e-1)*(t.length/n)),o=Math.floor(e*(t.length/n));return t.sort().filter((i,s)=>s>=r&&s<o)}function ZO({globalTestsToRunWithInputs:t,shardIndex:e,shardCount:n}){return n&&n>1?QO(t,e,n):t}ic||X.warn("Sentry is not enabled in this environment due to unsupported node version");var iN=process.argv.some(t=>t.includes("--log-level"))&&process.argv.some(t=>t.includes("debug")),hm=t=>{iN&&S.dimmed(t)},Tt=new eN;Tt.name("momentic").description("Momentic CLI").version(Xn);Tt.command("install-browsers").description("Install browser executables onto the local machine.").option("-f, --force","Force reinstallation even if the browser executables already exist on disk.").option("-a, --all","Install all browsers types.").argument("[browsers...]",`Browsers to install. Available choices: ${Rd.join(", ")}.`).action(async(t,e)=>{!e.all&&t.length===0&&(S.error("No browsers specified"),process.exit(1)),await Ph({rawBrowsers:t,force:e.force,all:e.all})});Tt.addOption(new Ut("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",t=>{t==="debug"&&S.info("Enabling debug logging"),S.setMinLevel(t.toLowerCase())});Tt.addOption(new Ut("--verbose","enable verbose logging")).on("option:verbose",()=>{X.enableConsoleLogs(),S.setMinLevel(20)});var fm=Tt.command("checks").alias("check").description("Perform various project checks");fm.command("config").addOption(Wt).action(async t=>{ct({configFilePath:t.config})});fm.command("duplicate-ids").description("Checks if any steps in your entire Momentic test repository share the same ID.").addOption(Wt).addOption(dT).action(async t=>{let e=ct({configFilePath:t.config});await Xb({project:e,fix:t.fix})});fm.command("duplicate-names").description("Checks if tests or modules with duplicate names or ids exist").addOption(Wt).action(async t=>{let e=ct({configFilePath:t.config});await Jb({project:e})});var XT=Tt.command("migrate").description("Migrate and upgrade tooling");XT.command("steps").description("Migrate steps in all tests and modules to the latest schema version. Note that this is always done when a test is loaded through the interactive editor, so is generally not needed.").addOption(Wt).action(async t=>{let e=ct({configFilePath:t.config});await bT(e)});XT.command("v1-v2").description("Migrate from v1 of the Momentic CLI to v2").addOption(fn).addOption(Wt).addOption(hn).addOption(xr).action(async t=>{!t.yes&&!await bt("This command will modify your existing Momentic configuration. Please backup your local directory using Git or another version control system before proceeding. Continue?",!0)&&process.exit(1);let e=ct({configFilePath:t.config}),n=new Je({baseUrl:t.server,apiKey:t.apiKey,logger:X}),{orgId:r}=await n.getAuthInfo();await wT({project:e,orgId:r,apiClient:n}),process.exit(0)});Tt.command("import").addOption(hn).addOption(fn).addOption(Wt).addOption(xr).addArgument(hT).action(async(t,e)=>{let{apiKey:n,server:r,config:o,yes:a}=e,i=ct({configFilePath:o}),s=new Je({baseUrl:r,apiKey:n,logger:X});!t||t.length===0?await nT({client:s,project:i,skipPrompts:a}):await rT({client:s,project:i,paths:t,skipPrompts:a}),process.exit(0)});Tt.command("init").description("Initialize an empty Momentic project in the current working directory").addOption(new Ut("--name <name>","Name of the project")).action(async t=>{S.info(`Welcome to the Momentic project setup wizard! \u{1F680}
3981
+ `),S.info("This wizard will help you bootstrap a new Momentic project. If you need to import existing assets from Momentic Cloud, you can call the 'import' command after initialization."),rc.existsSync(oa)&&(S.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 n={name:t.name??await Ch("Choose an identifier for your project, such as a service, product, or team name (default: 'app'):","app"),include:Vd};aa(n,oa),S.success(`Initialized Momentic project file at ${nc.resolve(oa)}`)});Tt.command("app").addOption(hn).addOption(fn).addOption(xr).addOption(Ju).addOption(Wt).addOption(Zu).addOption(em).action(async t=>{let{apiKey:e,yes:n,server:r,pixelRatio:o,disableCache:a,saveCache:i}=t,s=ct({configFilePath:t.config,nameFilter:void 0}),{errors:l}=await Bl({project:s,fix:!1});l>0&&(S.error(`Found ${l} errors`),S.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1));let c=new Je({baseUrl:r,apiKey:e,logger:X});await xd({client:c,skipPrompts:n});let d=aN(import.meta.url),u=nc.dirname(d),m=nc.resolve(u,"..","static"),p=nc.resolve(u,"..","assets"),g=o??sm();lm(g),await Vb({momenticServerUrl:r,apiKey:e,serverPort:zl,appPort:zl,staticDir:m,assetsDir:p,devicePixelRatio:g,noCache:a,alwaysSaveCache:i,initialProject:s});let h=`http://localhost:${zl}`;await oN(h)});var JT=Tt.command("queue").description("Queue tests or suites to run on Momentic Cloud");JT.command("suites").description("Run one or more suites on Momentic Cloud").addOption(hn).addOption(fn).addOption(Vu).addOption(qu).addOption(xr).addArgument(fT).addOption(Gl).addOption(jl).addOption($l).action(async(t,e)=>{let{apiKey:n,server:r,wait:o,waitTimeout:a,env:i,urlOverride:s}=e,l=Hl(e.customHeaders),c=new Je({baseUrl:r,apiKey:n,logger:X});(!t||!Array.isArray(t)||!t.length)&&(S.error("Must pass at least one suite to run."),process.exit(1));let{orgId:d}=await c.getAuthInfo();await vT({client:c,orgId:d,wait:o,suitePaths:t,waitTimeout:a,env:i,urlOverride:s,customHeaders:l})});JT.command("tests").description("Run one or more tests on Momentic Cloud").addOption(hn).addOption(fn).addOption(xr).addOption($l).addOption(Qu).addOption(Gl).addOption(jl).addOption(new Ut("--all","Run all tests.").default(!1)).addOption(Vu).addOption(qu).addArgument(gT).action(async(t,e)=>{let{all:n,apiKey:r,env:o,server:a,inputCsv:i,urlOverride:s,wait:l,waitTimeout:c,yes:d}=e,u=Hl(e.customHeaders);for(let h of t)(h.endsWith(".yaml")||rc.existsSync(h))&&S.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 m=new Je({baseUrl:a,apiKey:r,logger:X}),{orgId:p}=await m.getAuthInfo(),g;i&&(g=await cm(i)),await AT({client:m,orgId:p,tests:t,all:n,customHeaders:u,env:o,urlOverride:s,wait:l,waitTimeout:c,testInputMatrix:g,yes:d}),process.exit(0)});var sN=Tt.command("list").description("List test paths");sN.addOption(Wt).addOption(fa).addOption(Yu).addOption(Xu).addOption(new Ut("--labels <labels...>","Only run tests with the specified label(s).")).addArgument(tm).action(async(t,e)=>{let n=ct({configFilePath:e.config,nameFilter:e.filter}),r=te(n,S),o=await Zl({tests:t,momenticFiles:r,yes:!0,project:n,include:e.include,exclude:e.exclude,labels:e.labels,logger:new Ka(40,{})});S.info(o.map(a=>a.relativeFilePath).join(`
3982
+ `)),process.exit(0)});var lN=Tt.command("run").alias("test").description("Run tests on the local machine");lN.addOption(hn).addOption(fn).addOption(Wt).addOption(fa).addOption(xr).addOption($l).addOption(Qu).addOption(Zu).addOption(em).addOption(uT).addOption(mT).addOption(pT).addOption(jl).addOption(Gl).addOption(Ju).addOption(new Ut("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new Ut("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new Ut("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.").default(60).argParser(Ar)).addOption(new Ut("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.").argParser(Ar)).addOption(new Ut("-p, --parallel <parallel>","The number of tests to run in parallel. Defaults to 1.").argParser(Ar)).addOption(new Ut("--labels <labels...>","Only run tests with the specified label(s).")).addOption(new Ut("--update-golden-files","Update locally stored golden files for steps that this is enabled for.").default(!1)).addOption(aT).addOption(iT).addOption(Ku).addOption(sT).addOption(cT).addOption(lT).addOption(Yu).addOption(Xu).addArgument(tm).action(async(t,e)=>{if(e.shardIndex>e.shardCount)throw new Error("Shard index cannot be greater than shard count");let n=Hl(e.customHeaders),r=ct({configFilePath:e.config,nameFilter:e.filter}),o=e.parallel??r.config.parallel??1;YT().length<o*2&&S.warn(`You requested to run tests in parallel ${o} at a time on a machine with ${YT().length} cores. This may cause performance issues and test failures as Chrome requires at least 2 cores per browser instance.`),S.debug({projectName:r.config.name},"Identified project config");let{errors:a}=await Bl({project:r,fix:!1});a>0&&(S.error(`Found ${a} errors`),S.warn("To fix these errors automatically, run the duplicate-ids check with the --fix flag and then commit the resulting changes"),process.exit(1));let i=new Je({baseUrl:e.server,apiKey:e.apiKey,logger:X});S.debug("Checking API key and dependencies");let{orgId:s,userId:l}=await xd({client:i,skipPrompts:e.yes});S.debug("API key check and browser installation complete");let c=new Ns(i),d=new $a,u=e.outputDir??r.config.outputDir,m=e.reporterDir??r.config.reporterDir,p=nN(),g=X.child({runGroupId:p,orgId:s,userId:l,cliVersion:Xn,trigger:"CLI"}),h=await Sr(X,i,r);g.info(h,"Got local git metadata");let f=new fr(r.config),y;e.inputCsv&&(y=await cm(e.inputCsv));let b=e.pixelRatio??sm();lm(b);try{(await KT({...e,parallel:o,retriesOverride:e.retries,devicePixelRatio:b,tests:t,project:r,client:i,debugDataStorage:d,billingReporter:c,flagStore:f,outputDir:u,uploadResults:e.uploadResults,reporterDir:m,customHeaders:n,envName:e.env,orgId:s,testInputMatrix:y,logger:g,regenerateGoldenFiles:e.updateGoldenFiles,gitMetadata:h,alwaysSaveCache:e.saveCache,noCache:e.disableCache,runGroupId:p})).failed>0?process.exit(1):process.exit(0)}catch(w){S.error("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),S.error(w),process.exit(1)}});var cN=Tt.command("apply").description("Apply an operation to local resources");cN.command("patch").addOption(hn).addOption(fn).addOption(Wt).addOption(fa).addOption(xr).addOption(new Ut("--from <from>","Name or ID of the patch to apply").makeOptionMandatory()).addOption(new Ut("--to <to>","Name or ID of the test to apply the patch to").makeOptionMandatory()).action(async t=>{let{apiKey:e,server:n,config:r,yes:o}=t,a=ct({configFilePath:r}),i=X,s=new Je({baseUrl:n,apiKey:e,logger:i}),l=te(a,S),c=l.tests[t.to]??Object.values(l.tests).find(u=>ve(u.name)===t.to.trim());c||(S.error(`No test matching '${t.to}' could be found in the current project.`),process.exit(1));let d=await s.fetchTestFragment(t.from);await Kb({client:s,test:c,fragment:d,yes:o,entities:l,logger:X}),process.exit(0)});var QT=Tt.command("results").description("Merge and upload test results.");QT.command("merge").description("Merge test results files.").addOption(Ku).addArgument(ST).action(async(t,e)=>{let{outputDir:n}=e;n||(S.error("Output directory is required."),process.exit(1)),rc.existsSync(t)||(S.warn("Results path does not exist, skipping merge."),process.exit(0)),rc.existsSync(n)&&S.warn(`Output directory ${n} already exists, removing before merging...`),Qf(X,n,t)});QT.command("upload").description("Upload test results to Momentic cloud.").addOption(hn).addOption(fn).addArgument(yT).action(async(t,e)=>{let{apiKey:n,server:r}=e,o=X,a=new Je({baseUrl:r,apiKey:n,logger:o});await sl({consoleLogger:S,resultsPath:t,client:a}),process.exit(0)});var ZT=Tt.command("quarantine").description("Manage test quarantines");ZT.command("add").description("Add a test to the quarantine. This will prevent it from running.").addOption(hn).addOption(fn).addOption(Wt).addOption(fa).addOption(nm).addArgument(rm).action(async(t,e)=>{let{apiKey:n,server:r,config:o,reason:a}=e,i=X,s=ct({configFilePath:o}),l=new Je({baseUrl:r,apiKey:n,logger:i}),c=await Sr(X,l,s);await ET({test:t,reason:a,apiClient:l,project:s,logger:i,identity:c})});ZT.command("remove").description("Remove a test from the quarantine. This will allow it to run again.").addOption(hn).addOption(fn).addOption(Wt).addOption(fa).addOption(nm).addArgument(rm).action(async(t,e)=>{let{apiKey:n,server:r,config:o,reason:a}=e,i=X,s=ct({configFilePath:o}),l=new Je({baseUrl:r,apiKey:n,logger:i}),c=await Sr(X,l,s);await RT({test:t,reason:a,apiClient:l,project:s,logger:i,identity:c})});async function dN(){hm("Main program started"),await _T(X),hm("CLI version check complete");try{await Tt.parseAsync(process.argv)}catch(t){let e={};try{e.playwrightVersion=tN("npx playwright --version").toString()}catch(n){X.error({err:n},"Error fetching debug information")}X.error({err:t,debugInfo:e},"Uncaught error in CLI"),X.flush(),wa(t,e),S.error(t),process.exit(1)}}rN.setMaxListeners(50);process.on("warning",t=>{X.warn({err:t},`Node warning received on CLI: ${t.message}`)});hm("CLI parsing setup complete");dN();
3983
3983
  //# sourceMappingURL=cli.js.map
3984
- //# debugId=1d5113a9-8b0f-5942-99ae-c98bf948c708
3984
+ //# debugId=5ae4a21c-85ec-580b-8627-11d5337ee5e5