momentic 0.0.124 → 0.0.126
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 +351 -309
- package/dist/index.js +338 -296
- package/package.json +1 -1
- package/static/assets/index-2riAu_K7.js +668 -0
- package/static/index.html +1 -1
- package/static/assets/index-4oWSfJzr.js +0 -624
package/bin/cli.js
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{execSync as Eh}from"child_process";import*as _ from"zod";var qt=(i=>(i.AI="AI",i.AI_HEALED="AI_HEALED",i.CLICK_TO_FIND="CLICK_TO_FIND",i.XY_PERCENT="XY_PERCENT",i.RECORDING="RECORDING",i.USER_CSS_SELECTOR="USER_CSS_SELECTOR",i))(qt||{}),Ct=_.object({id:_.number().int(),dataMomenticId:_.number().int().optional(),selector:_.string().optional(),generatedSelectors:_.string().array().optional(),role:_.string().optional(),name:_.string().optional(),numChildren:_.number().optional(),content:_.string().optional(),pathFromRoot:_.string().optional(),serializedForm:_.string().optional(),nodeOnlySerializedForm:_.string().optional(),serializedHtml:_.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:_.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:_.string().url().optional(),boundingBox:_.object({x:_.number().optional(),y:_.number().optional(),width:_.number(),height:_.number()}).describe("css pixel bounding box").optional(),inputDescription:_.string().optional().describe("the description that generated this cache"),targetSource:_.nativeEnum(qt).optional()});function Jr(r){return!!(r.name||r.role||r.content||r.serializedForm||r.serializedHtml||r.screenshotUrl)}var Qc=_.object({percentX:_.number().describe("between 0 and 1"),percentY:_.number()}),Zc=_.object({type:_.literal("description"),elementDescriptor:_.string(),a11yData:Ct.optional().describe("DEPRECATED: new a11y cache is stored in DB and resolved into the 'cache' field")});function Ke(r){return r.type==="description"}function Tt(r){return r.type==="coordinates"}var le=_.discriminatedUnion("type",[Zc,_.object({type:_.literal("coordinates"),percentXYLocation:Qc})]);function ro(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor;case"coordinates":return r.percentXYLocation.percentX>=0||r.percentXYLocation.percentY>=0}return!0}function ce(r){if(!r)return"";switch(r.type){case"description":return r.elementDescriptor;case"coordinates":return`x: ${r.percentXYLocation.percentX}, y: ${r.percentXYLocation.percentY}`}}import{z as W}from"zod";var ks=W.object({thoughts:W.string(),result:W.boolean(),relevantElements:W.array(W.number()).optional()}),fr=(n=>(n.CONTAINS="CONTAINS",n.STARTS_WITH="STARTS_WITH",n.EQUALS="EQUALS",n))(fr||{});var ed=W.object({type:W.literal("ELEMENT_CONTENT"),negated:W.boolean().optional(),operation:W.nativeEnum(fr),value:W.string()}),td=W.object({type:W.literal("ELEMENT_ATTRIBUTE"),negated:W.boolean().optional(),operation:W.nativeEnum(fr),attr:W.string(),value:W.string()}),yr=(o=>(o.EXISTS="EXISTS",o.VISIBLE="VISIBLE",o.ENABLED="ENABLED",o.EDITABLE="EDITABLE",o))(yr||{}),rd=W.object({type:W.literal("ELEMENT_EXISTENCE"),negated:W.boolean().optional(),condition:W.nativeEnum(yr)}),Ds=W.discriminatedUnion("type",[ed,td,rd]);var nd=W.object({type:W.literal("CONTENT"),negated:W.boolean().optional(),value:W.string()}),Fs=W.discriminatedUnion("type",[nd]);import Yh from"string-argv";import{v4 as Jh}from"uuid";import{z as Y}from"zod";import{v4 as ee}from"uuid";import*as y from"zod";var de=(D=>(D.AI_EXTRACT="AI_EXTRACT",D.AI_ASSERTION="AI_ASSERTION",D.AI_WAIT="AI_WAIT",D.AUTH_LOAD="AUTH_LOAD",D.AUTH_SAVE="AUTH_SAVE",D.BLUR="BLUR",D.CAPTCHA="CAPTCHA",D.CLICK="CLICK",D.COOKIE="COOKIE",D.DIALOG="DIALOG",D.DRAG="DRAG",D.ELEMENT_CHECK="ELEMENT_CHECK",D.FILE_UPLOAD="FILE_UPLOAD",D.FOCUS="FOCUS",D.GO_BACK="GO_BACK",D.GO_FORWARD="GO_FORWARD",D.HOVER="HOVER",D.JAVASCRIPT="JAVASCRIPT",D.LOCAL_STORAGE="LOCAL_STORAGE",D.MOUSE_DRAG="MOUSE_DRAG",D.NAVIGATE="NAVIGATE",D.NEW_TAB="NEW_TAB",D.PAGE_CHECK="PAGE_CHECK",D.PRESS="PRESS",D.REFRESH="REFRESH",D.REQUEST="REQUEST",D.SCROLL_DOWN="SCROLL_DOWN",D.SCROLL_UP="SCROLL_UP",D.SCROLL_LEFT="SCROLL_LEFT",D.SCROLL_RIGHT="SCROLL_RIGHT",D.SELECT_OPTION="SELECT_OPTION",D.TAB="TAB",D.TYPE="TYPE",D.VISUAL_DIFF="VISUAL_DIFF",D.WAIT="WAIT",D.SUCCESS="SUCCESS",D))(de||{}),F=y.object({thoughts:y.string().optional(),id:y.string().uuid().describe("unique identifier to this step, used for step cache")}),Ie=y.object({useSelector:y.boolean().optional(),useXY:y.boolean().optional(),force:y.boolean().optional(),disableCache:y.boolean().optional().describe("disable element caching for this step"),iframeUrl:y.string().optional().describe("url or url regex for the iframe")}),$e=y.object({target:Ct}).optional(),Qr=y.object({loadTimeout:y.number().int().max(60).optional().describe("Max seconds for the page to load"),networkTimeout:y.number().int().max(60).optional().describe("How many seconds to wait for network idle after navigation")}),od=F.merge(Qr).merge(y.object({type:y.literal("NAVIGATE"),url:y.string()})),Zr=Ie.merge(y.object({cache:$e})),en=F.merge(Zr.merge(y.object({target:le.optional(),type:y.literal("SCROLL_UP"),deltaY:y.number().optional()}))),tn=F.merge(Zr.merge(y.object({target:le.optional(),type:y.literal("SCROLL_DOWN"),deltaY:y.number().optional()}))),rn=F.merge(Zr.merge(y.object({target:le.optional(),type:y.literal("SCROLL_LEFT"),deltaX:y.number().optional()}))),nn=F.merge(Zr.merge(y.object({target:le.optional(),type:y.literal("SCROLL_RIGHT"),deltaX:y.number().optional()}))),Bh=y.discriminatedUnion("type",[en,tn,rn,nn]),sd=F.merge(y.object({type:y.literal("DIALOG"),action:y.union([y.literal("ACCEPT"),y.literal("DISMISS")])})),id=F.merge(y.object({type:y.literal("WAIT"),delay:y.number()})),ad=F.merge(Qr).merge(y.object({type:y.literal("REFRESH")})),ld=F.merge(y.object({type:y.literal("GO_BACK")})),cd=F.merge(y.object({type:y.literal("GO_FORWARD")})),dd=F.extend({type:y.literal("AUTH_SAVE")}),ud=F.extend({type:y.literal("AUTH_LOAD"),storageState:y.string().describe("JSON string auth state")}),Bs=F.merge(Ie).extend({type:y.literal("CAPTCHA")}),md=F.merge(y.object({type:y.literal("JAVASCRIPT"),code:y.string(),fragment:y.boolean().optional(),envKey:y.string().optional(),environment:y.union([y.literal("NODE"),y.literal("BROWSER")]).optional().describe("default NODE"),timeout:y.number().int().max(60).optional().describe("Max seconds for the code to complete")})),no=F.merge(Ie).merge(y.object({type:y.literal("CLICK"),target:le,doubleClick:y.boolean().optional(),rightClick:y.boolean().optional(),waitForUrl:y.string().optional().describe("call playwright waitForURL after click"),waitForDownload:y.boolean().optional().describe("wait for a download to occur and return the file downloaded"),cache:$e})),oo=F.merge(Ie).merge(y.object({type:y.literal("DRAG"),fromTarget:le,toTarget:le,hoverSeconds:y.number().optional().describe("Seconds to hover the object before dropping"),cache:y.object({fromTarget:Ct.optional(),toTarget:Ct.optional()}).optional()})),so=F.merge(Ie).merge(y.object({type:y.literal("MOUSE_DRAG"),target:le.optional(),deltaX:y.string().describe("pixels to move horizontally, can be template"),deltaY:y.string().describe("pixels to move vertically, can be template"),steps:y.number().optional(),cache:$e})),io=F.merge(Ie).merge(y.object({type:y.literal("HOVER"),target:le,cache:$e})),ao=F.merge(Ie).merge(y.object({type:y.literal("FOCUS"),target:le,cache:$e})),lo=F.merge(Ie).merge(y.object({type:y.literal("BLUR"),target:le,cache:$e})),pd=F.extend({type:y.literal("FILE_UPLOAD"),fileSource:y.discriminatedUnion("type",[y.object({type:y.literal("URL"),url:y.string()}).describe("Accessible link to the file, either public http or local file://")])}),co=F.merge(Ie).merge(y.object({type:y.literal("SELECT_OPTION"),target:le,option:y.string(),cache:$e})),uo=F.merge(y.object({type:y.literal("AI_ASSERTION"),assertion:y.string(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional()})),gd=uo.merge(y.object({type:y.literal("AI_WAIT"),timeout:y.number().int().optional().describe("Max seconds to wait for assertion to be true")})),Et=5,mo=60,po=F.merge(Ie).extend({type:y.literal("ELEMENT_CHECK"),target:le,assertion:Ds,cache:$e,timeout:y.number().int().min(0).max(mo).optional().describe("max seconds to wait for the assertion to be true")}),hd=F.extend({type:y.literal("PAGE_CHECK"),assertion:Fs,timeout:y.number().int().min(0).max(mo).optional().describe("max seconds to wait for the assertion to be true")}),fd=F.merge(y.object({type:y.literal("AI_EXTRACT"),goal:y.string(),schema:y.string().optional(),envKey:y.string().optional(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional()})),yd=y.object({clearContent:y.boolean().optional(),pressKeysSequentially:y.boolean().optional(),force:y.boolean().optional()}),go=F.merge(Ie).merge(yd).extend({type:y.literal("TYPE"),target:le.optional(),value:y.string(),pressEnter:y.boolean().optional(),cache:$e}),Sd=F.merge(y.object({type:y.literal("PRESS"),value:y.string()})),wd=F.merge(Qr).merge(y.object({type:y.literal("TAB"),url:y.string()})),bd=F.merge(Qr).merge(y.object({type:y.literal("NEW_TAB"),url:y.string()})),Cd=F.merge(y.object({type:y.literal("COOKIE"),value:y.string()})),Td=F.merge(y.object({type:y.literal("LOCAL_STORAGE"),key:y.string(),value:y.string()})),Ed=F.merge(y.object({type:y.literal("REQUEST"),url:y.string(),method:y.union([y.literal("GET"),y.literal("POST"),y.literal("PUT"),y.literal("DELETE"),y.literal("PATCH")]),headers:y.record(y.string(),y.string()).optional(),params:y.record(y.string(),y.string()).optional(),body:y.string().optional(),timeout:y.number().int().optional().describe("Max seconds to wait for the request to complete")})),vd=F.merge(y.object({type:y.literal("SUCCESS"),condition:uo.optional()})),Ad=F.merge(y.object({type:y.literal("FAILURE")})),Rd=y.object({data:y.string().describe("s3 url to a jpg"),width:y.number(),height:y.number()}),ho=F.merge(Ie).merge(y.object({type:y.literal("VISUAL_DIFF"),threshold:y.number().optional().describe("default 0.1"),target:le.optional(),screenshot:Rd.optional(),cache:$e})),on=y.discriminatedUnion("type",[no,go,Sd,co,od,tn,en,uo,gd,vd]),xd=y.discriminatedUnion("type",[fd,ud,dd,Bs,Cd,sd,oo,po,pd,ld,cd,io,md,Td,so,bd,hd,ad,Ed,rn,nn,wd,ho,id,ao,lo]),sn=y.discriminatedUnion("type",[...on.options,...xd.options]),fo=y.discriminatedUnion("type",[...on.options,Ad]);var ut=r=>{let e;switch(r){case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:ee(),type:r};break;case"AUTH_LOAD":{e={id:ee(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:ee(),type:r,goal:""};break;case"DIALOG":e={id:ee(),type:r,action:"DISMISS"};break;case"DRAG":e={id:ee(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:ee(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT":e={id:ee(),type:r,delay:1};break;case"HOVER":case"BLUR":case"FOCUS":case"CLICK":e={id:ee(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"TYPE":e={id:ee(),type:r,value:"",clearContent:!0};break;case"SELECT_OPTION":e={id:ee(),type:r,target:{type:"description",elementDescriptor:""},option:""};break;case"NAVIGATE":case"NEW_TAB":case"TAB":e={id:ee(),type:r,url:""};break;case"REQUEST":e={id:ee(),type:r,url:"",method:"GET"};break;case"LOCAL_STORAGE":e={id:ee(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:ee(),type:r,code:""};break;case"AI_WAIT":case"AI_ASSERTION":e={id:ee(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:ee(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:ee(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:ee(),type:r,assertion:{type:"CONTENT",value:""}};break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return sn.parse(e)},be={type:!0,cache:!0},vt=y.discriminatedUnion("type",[lo.pick(be),no.pick(be),oo.pick(be),po.pick(be),ao.pick(be),io.pick(be),so.pick(be),en.pick(be),tn.pick(be),rn.pick(be),nn.pick(be),co.pick(be),go.pick(be),ho.pick(be)]),yo=Object.values(de).filter(r=>vt.options.some(e=>e.shape.type.safeParse(r).success));sn.options.forEach(r=>{if("target"in r.shape&&!yo.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});var $h=y.discriminatedUnion("type",[lo,Bs,no,oo,ao,io,so,en,tn,rn,nn,co,go,ho,po]);import{z as Kt}from"zod";var ue=(a=>(a.AI_PROVIDER="AIProviderError",a.ACTION_FAILURE="ActionFailureError",a.ASSERTION_FAILURE="AssertionFailureError",a.CONFIG_ERROR="UserConfigurationError",a.JOB_TIMEOUT="JobTimeoutError",a.WEB_AGENT_PLATFORM="InternalWebAgentError",a.UNKNOWN_PLATFORM="InternalPlatformError",a))(ue||{});var $s={ActionFailureError:"Action failure",AssertionFailureError:"Assertion failure",UserConfigurationError:"Configuration error",AIProviderError:"AI provider error",InternalWebAgentError:"Momentic AI agent error",InternalPlatformError:"Infrastructure error",JobTimeoutError:"Job timeout"},Hs={ActionFailureError:"A browser action such as a click or type failed to execute because of the underlying page state is incorrect, suggesting a bug in the application itself.",AssertionFailureError:"An AI assertion or check failed for a legitimate reason, such as a missing element, a change in the page structure, or an unexpected state (e.g. loading state).",UserConfigurationError:"The error message suggests a misconfiguration in the test, such as a variable being undefined, an environment variable missing, or a typo in a step. Do not use this reason if the error is caused by a bug in the application being tested, or Momentic's AI software.",AIProviderError:"The AI provider failed to return a response or returned a malformed response.",InternalWebAgentError:"The AI testing framework failed to find the correct element or evaluate the assertion correctly, even though the test steps and application state look valid. In other words, the AI agent failed to understand the page.",InternalPlatformError:"A platform error occurred, such as the Chromium browser failing, the network being down, or an action timing out. The error is likely caused by a transient infrastructure issue such as lack of resources or network flakiness.",JobTimeoutError:"The test took too long to complete, suggesting a problem with the test itself."},So=Kt.object({reason:Kt.nativeEnum(ue),summary:Kt.string()}),Ws=Kt.object({errorMessage:Kt.string(),errorStack:Kt.string().optional(),classification:So.optional()});var Ye=class extends Error{constructor(e,t={}){super(e,t),this.name="CancellationError"}};var an=class extends Error{constructor(e,t,n,o={}){super(`The ${n} with id ${t} is invalid: ${e}`,o),this.name="InvalidEntityError"}};var ln=class extends Error{constructor(e,t={}){super(e,t),this.name="TemplateMatcherThresholdError"}},A=class extends Error{reason;emitToUser;constructor(e,t,n={},o=!1){let s=!1;for(let i of Object.values(ue))if(t.startsWith(i)){s=!0,e=i;break}s?super(t,n):super(`${e}${t?`: ${t}`:""}`,n),this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e,this.emitToUser=o}toString(){return this.message}toJSON(){return{message:this.message}}},At=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundError"}};var tf=Y.object({command:Y.string(),thoughts:Y.string()}),rf=Y.string().pipe(Y.coerce.number());var Gs=Y.object({phrase:Y.string()}),wo=Y.object({result:Y.union([Y.literal("NOT_FOUND"),Y.string(),Y.number(),Y.array(Y.unknown()),Y.record(Y.unknown(),Y.unknown())])}),js=Y.object({thoughts:Y.string(),id:Y.number().int()});import{z as bo}from"zod";var cn=bo.object({width:bo.number().min(200).max(1e4),height:bo.number().min(200).max(1e4)}),Vs={"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}},sf=Object.keys(Vs);var Xe=Vs["Desktop Large"];import{z as Ks}from"zod";import{z as qs}from"zod";import{z as Co}from"zod";var Le=Co.object({index:Co.number().optional().describe("global index"),skipped:Co.boolean().optional()});var V=(i=>(i.PRESET_ACTION="PRESET_ACTION",i.MODULE="MODULE",i.AI_ACTION="AI_ACTION",i.CONDITIONAL="CONDITIONAL",i.IFRAME="IFRAME",i.SECTION="SECTION",i))(V||{});var Pe=Le.extend({type:qs.literal("PRESET_ACTION"),command:sn,skipped:qs.boolean().optional()});var Yt=Le.extend({type:Ks.literal("AI_ACTION"),text:Ks.string(),steps:Pe.array().optional()});import{z as X}from"zod";var Id=X.object({cacheKey:X.string(),cacheExpiryMs:X.number()}),To=Le.extend({id:X.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:X.record(X.string()).optional(),cacheConfig:Id.optional()}),Xt=To.extend({type:X.literal("MODULE"),moduleId:X.string().uuid()}),Ld=X.union([Xt.pick({type:!0,moduleId:!0}),X.record(X.unknown())]),De=X.object({moduleId:X.string().uuid(),name:X.string(),parameters:X.string().array().nullish(),defaultParameters:X.record(X.string(),X.string()).nullish(),defaultCacheKey:X.string().nullish(),defaultCacheTtl:X.number().nullish()});import{z as ne}from"zod";import{z as Ys}from"zod";var Sr=Le.extend({type:Ys.literal("CONDITIONAL"),skipped:Ys.boolean().optional()});import{z as Oe}from"zod";var Pd=Oe.object({type:Oe.literal("attr"),name:Oe.string(),value:Oe.string()}),Od=Oe.object({type:Oe.literal("css"),selector:Oe.string()}),Md=Oe.object({type:Oe.literal("url"),url:Oe.string()}),Nd=Oe.union([Pd,Md,Od]),wr=Le.extend({type:Oe.literal("IFRAME"),identifier:Nd});import{z as Xs}from"zod";var br=Le.extend({type:Xs.literal("SECTION"),description:Xs.string()});var Js=De.merge(To).extend({type:ne.literal("RESOLVED_MODULE"),steps:ne.lazy(()=>Ae.array())}),Eo=De.extend({steps:ne.lazy(()=>Ae.array())}),_d=wr.extend({steps:ne.lazy(()=>Me.array())}),kd=wr.extend({steps:ne.lazy(()=>Ae.array())}),Dd=br.extend({steps:ne.lazy(()=>Me.array())}),Fd=br.extend({steps:ne.lazy(()=>Ae.array())}),Ud=Sr.extend({blocks:ne.object({assertion:ne.lazy(()=>Pe),steps:ne.lazy(()=>Me.array())}).array(),elseSteps:ne.lazy(()=>Me.array().optional())}),zd=Sr.extend({blocks:ne.object({assertion:ne.lazy(()=>Pe),steps:ne.lazy(()=>Ae.array())}).array(),elseSteps:ne.lazy(()=>Ae.array().optional())}),Me=ne.discriminatedUnion("type",[Pe,Yt,Xt,Ud,_d,Dd]),Ae=ne.discriminatedUnion("type",[Pe,Yt,Js,zd,kd,Fd]);var Ce="1.0.9";import{z as Rt}from"zod";var vo=Rt.object({key:Rt.string(),testId:Rt.string().optional(),moduleId:Rt.string().optional(),organizationId:Rt.string(),value:vt}),Qs=Rt.record(Rt.string(),vo);var Ay=new Set(Object.values(de));var Ao={AI_ACTION:"AI action",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_WAIT:"AI wait",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"Local storage",REQUEST:"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",SUCCESS:"Done"},Ry={AI_ACTION:"Ask AI to plan and execute something on the page.",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI whether something is true on the page.",AI_WAIT:"Wait until AI considers a condition to be true.",CLICK:"Click on an element on the page based on a description.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page based on a description.",HOVER:"Hover over an element on the page based on a description.",FILE_UPLOAD:"Automatically upload a file when the next file chooser is activated.",FOCUS:"Focus an element on the page based on a description.",BLUR:"Remove focus from an element on the page based on a description.",SELECT_OPTION:"Select an option from an HTML Select <select> element based on a description.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Ctrl+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session",LOCAL_STORAGE:"Set a local storage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",JAVASCRIPT:"Run JavaScript code in an isolated context.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load auth state (cookies, local storage) from the JavaScript object format returned by 'Save auth state' and then refresh the page.",AUTH_SAVE:"Save auth state (cookies, local storage) into a JavaScript object format usable by 'Load auth state'.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's state using pre-built conditions, including URL and content checks.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."};import{z as B}from"zod";var Ly=B.object({body:B.string(),to:B.string(),from:B.string()}),Py=B.object({from:B.string().optional(),to:B.string().optional(),timeout:B.number().optional(),beforeDate:B.string().pipe(B.coerce.date()).or(B.date()).optional(),afterDate:B.string().pipe(B.coerce.date()).or(B.date()).optional()}),Oy=B.object({inbox:B.string(),afterDate:B.string().pipe(B.coerce.date()).or(B.date()).optional(),timeout:B.number().optional(),trimWhitespace:B.boolean().optional()});var Bd=B.object({result:B.unknown(),variableUpdates:B.record(B.string(),B.unknown()).optional(),error:B.string().optional(),success:B.boolean()}),Zs=15e3;import*as M from"zod";import{cloneDeep as Zt}from"lodash-es";import*as K from"zod";import{z as Jt}from"zod";var Je="BASE_URL",dn="CURRENT_URL",Qt="ENV_NAME",_y={[Je]:"https://www.google.com"},ei=Jt.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),Re=Jt.object({name:Jt.string(),variables:Jt.record(Jt.string().describe("variable name"),Jt.string().describe("variable value"))});import*as xt from"zod";var ti=xt.object({type:xt.nativeEnum(V),generatedStep:on.optional(),serializedCommand:xt.string().optional(),elementInteracted:xt.string().optional()});var mt=K.object({goal:K.string(),url:K.string(),browserState:K.string(),history:K.string(),numPrevious:K.number(),lastCommand:ti.or(K.null()),returnSchema:K.string().optional()}),Ro=K.object({env:K.record(K.unknown()),results:K.array(K.unknown()),inputs:K.record(K.unknown()).optional()}),$d="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",Hd=[Je,Qt],ri=[dn,Je,Qt],he=class r{env={};inputs=void 0;results=[];varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static fromSnapshot({snapshot:e,environmentVariables:t}){let n=e.env[Je]??"about:blank",o=e.env[dn]??"about:blank",s=e.env[Qt],i={};for(let[l,c]of Object.entries(e.env))ri.includes(l)||(t??{})[l]===void 0&&(i[l]=c);let a=new r({baseUrl:n,currentUrl:o,dynamicVariables:i,envName:s,variablesFromEnvironment:t??{}});return a.setInputs(e.inputs),a.setResults(e.results),a}setEnvVariables(e){let t=Zt(e);this.env=Object.assign(this.env,t)}setInputs(e){this.inputs=e}setResult(e,t){this.results[e]=t||null;for(let n=0;n<e;n++)this.results[n]===void 0&&(this.results[n]=null)}getResult(e){return this.results[e]}getResultsCopy(){return Zt(this.results)}setResults(e){this.results=e}clearResults(){this.results=[]}getVariable(e){return this.env[e]}setVariable(e,t){Hd.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[Qt]}toObjectCopy(){let e={results:this.results,env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return this.inputs&&(e.inputs=this.inputs),Zt(e)}toRedactedDisplayCopy(){let e=this.toObjectCopy();return e.env=Object.fromEntries(Object.entries(e.env).map(([t,n])=>ri.includes(t)||this.varsFromMomenticEnvironment[t]===void 0?[t,n]:[t,$d])),e}setUrl(e){this.env[dn]=e}reset(e){this.results=[],this.env={},this.varsFromMomenticEnvironment={},this.env[Je]=e.baseUrl,e.envName&&(this.env[Qt]=e.envName),this.setUrl(e.currentUrl),this.setEnvVariables(e.dynamicVariables??{}),this.varsFromMomenticEnvironment=Zt(e.variablesFromEnvironment)}getDynamicVariablesCopy(){return Zt(this.env)}getVariablesFromEnvironmentCopy(){return Zt(this.varsFromMomenticEnvironment)}},ni=Object.getPrototypeOf(async function(){}).constructor;var Qe=(s=>(s.SUCCESS="SUCCESS",s.FAILED="FAILED",s.RUNNING="RUNNING",s.IDLE="IDLE",s.CANCELLED="CANCELLED",s))(Qe||{}),un=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(un||{}),Wd=M.object({beforeUrl:M.string(),beforeScreenshot:M.string().optional(),afterUrl:M.string().optional(),afterScreenshot:M.string().optional(),startedAt:M.coerce.date(),finishedAt:M.coerce.date(),viewport:M.object({height:M.number(),width:M.number()}),status:M.nativeEnum(un),message:M.string().optional(),elementInteracted:M.string().optional()}),It=M.object({startedAt:M.coerce.date(),finishedAt:M.coerce.date(),status:M.nativeEnum(Qe),message:M.string().optional(),data:M.unknown().optional(),beforeTestContext:Ro.optional(),afterTestContext:Ro.optional(),failureReason:M.nativeEnum(ue).optional(),details:M.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information.")}),xo=It.merge(Pe).extend({results:Wd.array()}),Gd=It.merge(Yt).extend({results:M.lazy(()=>xo.array())}),jd=It.merge(Xt).extend({moduleName:M.string().optional(),results:M.lazy(()=>Lt.array())}),Vd=It.merge(Sr).extend({assertion:xo.optional(),results:M.lazy(()=>Lt.array()).describe("results for the block actually executed")}),qd=It.merge(wr).extend({results:M.lazy(()=>Lt.array())}),Kd=It.merge(br).extend({results:M.lazy(()=>Lt.array())}),Lt=M.discriminatedUnion("type",[Gd,xo,jd,Vd,qd,Kd]),mn=It.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),Qy=M.object({results:Lt.array(),errorMessage:M.string(),errorStack:M.string().optional()});import{parseString as Yd,splitCookiesString as Xd}from"set-cookie-parser";import{z as J}from"zod";var oi=J.object({name:J.string(),value:J.string(),url:J.string().optional(),domain:J.string().optional(),path:J.string().optional(),expires:J.number().default(Date.now()/1e3+60*60*24*365),httpOnly:J.boolean().optional(),secure:J.boolean().default(!0),sameSite:J.union([J.literal("Strict"),J.literal("Lax"),J.literal("None")]).default("None")});function si(r){let e=[],t=Xd(r);for(let n of t){let o=Yd(n);if(!o.name)throw new Error("Name missing from cookie");if(!o.value)throw new Error("Value missing from cookie");let s;if(o.sameSite){let c=o.sameSite.trim().toLowerCase();if(c==="strict")s="Strict";else if(c==="lax")s="Lax";else if(c==="none")s="None";else throw new Error(`Invalid sameSite setting in cookie: ${c}`)}o.httpOnly===void 0&&(o.httpOnly=!1),!o.path&&o.domain&&(o.path="/");let i=oi.parse({...o,expires:o.expires?o.expires.getTime()/1e3:void 0,sameSite:s});e.push(i);let a=[i.name,...Object.keys(i)].map(c=>c.toLowerCase()),l=n.match(/\b(\w+)=([^;]*)/g);if(l)for(let c of l){let[u,d]=c.split("=");if(!u||!d)throw new Error(`Invalid key-value pair in cookie: ${c}`);a.includes(u.toLowerCase())||e.push({...i,name:u,value:d})}}return e}var Jd=J.object({origin:J.string(),localStorage:J.array(J.object({name:J.string(),value:J.string()}))}),ii=J.object({cookies:oi.array(),origins:Jd.array()});import{z as Ze}from"zod";var pn=Ze.object({x:Ze.number(),y:Ze.number(),correlation:Ze.number()}),oS=Ze.object({searchImageBase64String:Ze.string(),pageImageBase64String:Ze.string(),id:Ze.string().uuid(),timeoutMs:Ze.number().max(1e4).min(0).optional()});import{z as Te}from"zod";var Qd=Te.object({orgId:Te.string(),cacheKeys:Te.string().array()}),aS=Te.object({keyParams:Qd,clientMetadata:Te.string(),lockAcquisitionTimeoutMs:Te.number().optional()}),ai=Te.object({acquired:Te.boolean(),acquiredByMetadata:Te.string(),keyPrefix:Te.string()}),lS=Te.object({keyPrefix:Te.string(),result:Te.string(),ttlMs:Te.number()}),li=0,ci=5*60*1e3;var gn=class{flags;constructor(e){this.flags=e}isBooleanFlagEnabled(e){return this.flags[e]===!0}getAllFlags(){return this.flags}};import{z as Ne}from"zod";import{z as Q}from"zod";import{z}from"zod";var pt="momentic",gt="modules",hn="fixtures",er="environments",Io="chromium",fn=[gt,hn,er,Io];import{isValidCron as Zd}from"cron-validator";import{z as oe}from"zod";var di=1e4,ui=6e4,Cr=oe.object({pageLoadTimeoutMs:oe.number().optional().refine(r=>r===void 0||r<=ui&&r>=-1,{message:`Page load timeout must be between 0 and ${ui/1e3} seconds`}),smartWaitingTimeoutMs:oe.number().optional().refine(r=>r===void 0||r<=di&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${di/1e3} seconds`}),extraHeaders:oe.record(oe.string(),oe.string()).optional().describe("HTTP headers to be sent on every request")}),eu=oe.object({disableAICaching:oe.boolean().default(!1),viewport:cn.optional()}),Pt=eu.merge(Cr),mi=oe.object({cron:oe.string().refine(r=>Zd(r),{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()}),pi=oe.object({onSuccess:oe.boolean().default(!1),onFailure:oe.boolean().default(!0)});var tu=z.string().min(1).max(255).superRefine((r,e)=>{try{Tr(r)}catch(t){return e.addIssue({code:z.ZodIssueCode.custom,message:t.message,fatal:!0}),z.NEVER}}),ru=z.object({name:z.string(),default:z.boolean().optional(),defaultOnLocal:z.boolean().optional().describe("DEPRECATED: migrated to default instead"),defaultOnCloud:z.boolean().optional().describe("DEPRECATED: migrated to default instead"),fixtures:ei.array().optional()}),me=z.object({id:z.string(),name:tu,baseUrl:z.preprocess(r=>r===null?"":r,z.union([z.string().url(),z.literal("")])).optional(),schemaVersion:z.string(),advanced:Pt,retries:z.number(),envs:z.array(ru).optional()}),CS=me.pick({name:!0,baseUrl:!0,retries:!0}).extend({advanced:Pt}),gi=z.object({createdAt:z.coerce.date(),updatedAt:z.coerce.date(),schedule:mi,notification:pi,createdBy:z.string(),organizationId:z.string()}),TS=me.merge(gi),ES=me.merge(gi).merge(z.object({steps:z.array(Ae)})),yn=me.merge(z.object({steps:z.array(Ae)})),vS=me.extend({steps:z.record(z.string(),z.unknown()).array()}),nu=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;function Tr(r){if(r=r.toLowerCase().trim(),r.length===0||r.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"\/\\|?*\x00]/.test(r))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(r))throw new Error(`"${r}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(r)||/^\s|\s$/.test(r))throw new Error("Name cannot start or end with a space or dot.");if(r.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(r==="none")throw new Error("Name cannot be 'none'.");if(fn.includes(r))throw new Error("'modules' is a reserved folder name in Momentic. Please choose a different name.");if(r.match(nu))throw new Error("Name cannot be a UUID. Please choose a different name.")}var OS=De.extend({fileType:Q.literal("momentic/module"),schemaVersion:Q.string(),steps:Q.record(Q.string(),Q.unknown()).array()}),Er=De.extend({steps:Q.array(Q.record(Q.string(),Q.unknown())),schemaVersion:Q.string()}),MS=me.extend({steps:Q.array(Q.record(Q.string(),Q.unknown()))}),NS=Q.object({test:Q.string().describe("YAML for the test, including metadata and steps"),modules:Q.record(Q.string(),Q.string()).describe("Map of module name to YAML for the module")});var ou="1.0.0",hi=Ne.object({run:Ne.string().describe("Run a single command in the shell. The working directory will be set to where the CLI was invoked from."),waitForCompletion:Ne.boolean().optional().describe("Defaults to true")}),fi=Ne.object({type:Ne.literal("momentic/fixture"),schemaVersion:Ne.string(),name:Ne.string(),description:Ne.string().optional(),setup:Ne.object({steps:hi.array(),timeout:Ne.number().optional().describe("Timeout for all steps in seconds")}).optional(),teardown:Ne.object({steps:hi.array(),timeout:Ne.number().optional().describe("Timeout for all steps in seconds")}).optional()}),FS={type:"momentic/fixture",schemaVersion:ou,name:"example",description:"An example fixture",setup:{steps:[{run:"./scripts/seed_db.sh",waitForCompletion:!0},{run:"npm run start",waitForCompletion:!1}],timeout:30},teardown:{steps:[{run:"./scripts/shutdown_db.sh"}]}};import{z as su}from"zod";var BS=su.string().array();import{z as $}from"zod";var YS=$.array($.object({id:$.string(),name:$.string(),fullFilePath:$.string(),testPath:$.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:$.string(),lastModified:$.coerce.date(),createdAt:$.coerce.date()}));var yi=$.object({steps:Ae.array()}),Si=me,wi=$.object({name:$.string(),baseUrl:$.string().url().optional(),environment:$.string().optional(),viewport:cn.optional()}),XS=yn.merge($.object({testPath:$.string()})),bi=$.object({name:$.string(),steps:$.lazy(()=>Ae.array())});var JS=Eo.array(),QS=$.array($.object({name:$.string(),moduleId:$.string().uuid(),numSteps:$.number()})),ZS=$.array(Re),Ci=$.object({defaultEnv:$.string().optional().describe("name of the default env, or undefined to unset")});import*as U from"zod";var nw=U.object({thoughts:U.string().optional().describe("only provided if a description was provided"),target:Ct.optional().describe("only provided if a description was provided"),pageState:U.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:U.array(U.string()).optional().describe("provided for <select> elements only"),screenshot:U.object({data:U.string(),height:U.number().int(),width:U.number().int()}).optional().describe("only provided if returnScreenshot is true")});function Ar(r,e){if(!e||"useSelector"in r&&r.useSelector)return e;switch(r.type){case"SELECT_OPTION":return`<select> element: ${e}`;case"TYPE":return`text input element: ${e}`;default:return e}return e}var tr=U.object({matched:U.boolean(),reason:U.string().optional().describe("Human understandable description")}),iu=tr.extend({type:U.literal("A11Y_ID")}),au=tr.extend({type:U.literal("USER_SELECTOR")}),lu=tr.extend({type:U.literal("CSS_SELECTOR"),selectors:U.string().array()}),cu=tr.extend({type:U.literal("A11Y_DISTANCE"),distance:U.number().optional(),closestElement:U.string().optional(),savedElement:U.string().optional()}),du=tr.extend({type:U.literal("HTML_DISTANCE"),distance:U.number().optional(),closestElement:U.string().optional(),savedElement:U.string().optional()}),uu=tr.extend({type:U.literal("TEMPLATE_MATCHING"),elementImageUrl:U.string().url()}),Ti=U.discriminatedUnion("type",[iu,au,lu,cu,du,uu]);var mu={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},pu={0:"\x1B[90m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},Lo=class r{minLogLevel;logBindings;constructor(e,t){this.minLogLevel=e,this.logBindings=t}logWithLevel(e,...t){let n=mu[e],o;Array.isArray(t[0])?(o=t[0],t=t.slice(1)):typeof t[0]=="object"&&!(t[0]instanceof Error)&&(o={...t[0],...this.logBindings},t=t.slice(1));let s=pu[e],i=[`${s}[${new Date().toTimeString().slice(0,8)}][${n}]`];if(e!==0&&i.push("\x1B[39m"),i.push(...t),console.log(...i),o&&!Array.isArray(o))for(let[a,l]of Object.entries(o)){let c=l;l instanceof Error?c=l.message:typeof l=="object"&&(c=JSON.stringify(l,void 0,2),c=c.split(`
|
|
2
|
+
import{execSync as Ph}from"child_process";import*as k from"zod";var Et=(i=>(i.AI="AI",i.AI_HEALED="AI_HEALED",i.CLICK_TO_FIND="CLICK_TO_FIND",i.XY_PERCENT="XY_PERCENT",i.RECORDING="RECORDING",i.USER_CSS_SELECTOR="USER_CSS_SELECTOR",i))(Et||{}),Tt=k.object({id:k.number().int(),dataMomenticId:k.number().int().optional(),selector:k.string().optional(),generatedSelectors:k.string().array().optional(),role:k.string().optional(),name:k.string().optional(),numChildren:k.number().optional(),content:k.string().optional(),pathFromRoot:k.string().optional(),serializedForm:k.string().optional(),nodeOnlySerializedForm:k.string().optional(),serializedHtml:k.string().optional().describe("pruned html including 1 neighbor and 1 layer of children. value for text inputs pruned."),nodeOnlySerializedHtml:k.string().optional().describe("outerHtml of the element without any children. value for text inputs pruned."),screenshotUrl:k.string().url().optional(),boundingBox:k.object({x:k.number().optional(),y:k.number().optional(),width:k.number(),height:k.number()}).describe("css pixel bounding box").optional(),inputDescription:k.string().optional().describe("the description that generated this cache"),targetSource:k.nativeEnum(Et).optional()});function en(r){return!!(r.name||r.role||r.content||r.serializedForm||r.serializedHtml||r.screenshotUrl)}var rd=k.object({percentX:k.number().describe("between 0 and 1"),percentY:k.number()}),nd=k.object({type:k.literal("description"),elementDescriptor:k.string(),a11yData:Tt.optional().describe("DEPRECATED: new a11y cache is stored in DB and resolved into the 'cache' field")});function qe(r){return r.type==="description"}function vt(r){return r.type==="coordinates"}var ce=k.discriminatedUnion("type",[nd,k.object({type:k.literal("coordinates"),percentXYLocation:rd})]);function io(r){if(!r)return!1;switch(r.type){case"description":return!!r.elementDescriptor;case"coordinates":return r.percentXYLocation.percentX>=0||r.percentXYLocation.percentY>=0}return!0}function de(r){if(!r)return"";switch(r.type){case"description":return r.elementDescriptor;case"coordinates":return`x: ${r.percentXYLocation.percentX}, y: ${r.percentXYLocation.percentY}`}}import{z as G}from"zod";var $s=G.object({thoughts:G.string(),result:G.boolean(),relevantElements:G.array(G.number()).optional()}),yr=(n=>(n.CONTAINS="CONTAINS",n.STARTS_WITH="STARTS_WITH",n.EQUALS="EQUALS",n))(yr||{});var od=G.object({type:G.literal("ELEMENT_CONTENT"),negated:G.boolean().optional(),operation:G.nativeEnum(yr),value:G.string()}),sd=G.object({type:G.literal("ELEMENT_ATTRIBUTE"),negated:G.boolean().optional(),operation:G.nativeEnum(yr),attr:G.string(),value:G.string()}),Sr=(o=>(o.EXISTS="EXISTS",o.VISIBLE="VISIBLE",o.ENABLED="ENABLED",o.EDITABLE="EDITABLE",o))(Sr||{}),id=G.object({type:G.literal("ELEMENT_EXISTENCE"),negated:G.boolean().optional(),condition:G.nativeEnum(Sr)}),Hs=G.discriminatedUnion("type",[od,sd,id]);var ad=G.object({type:G.literal("CONTENT"),negated:G.boolean().optional(),value:G.string()}),Ws=G.discriminatedUnion("type",[ad]);import rf from"string-argv";import{v4 as of}from"uuid";import{z as Y}from"zod";import{v4 as Q}from"uuid";import*as y from"zod";var ue=(_=>(_.AI_EXTRACT="AI_EXTRACT",_.AI_ASSERTION="AI_ASSERTION",_.AI_WAIT="AI_WAIT",_.AUTH_LOAD="AUTH_LOAD",_.AUTH_SAVE="AUTH_SAVE",_.BLUR="BLUR",_.CAPTCHA="CAPTCHA",_.CLICK="CLICK",_.COOKIE="COOKIE",_.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",_.PRESS="PRESS",_.REFRESH="REFRESH",_.REQUEST="REQUEST",_.SCROLL_DOWN="SCROLL_DOWN",_.SCROLL_UP="SCROLL_UP",_.SCROLL_LEFT="SCROLL_LEFT",_.SCROLL_RIGHT="SCROLL_RIGHT",_.SELECT_OPTION="SELECT_OPTION",_.TAB="TAB",_.TYPE="TYPE",_.VISUAL_DIFF="VISUAL_DIFF",_.WAIT="WAIT",_.WAIT_FOR_URL="WAIT_FOR_URL",_.SUCCESS="SUCCESS",_))(ue||{}),D=y.object({thoughts:y.string().optional(),id:y.string().uuid().describe("unique identifier to this step, used for step cache")}),Ie=y.object({useSelector:y.boolean().optional(),useXY:y.boolean().optional(),force:y.boolean().optional(),disableCache:y.boolean().optional().describe("disable element caching for this step"),iframeUrl:y.string().optional().describe("url or url regex for the iframe")}),Be=y.object({target:Tt}).optional(),tn=y.object({loadTimeout:y.number().int().max(60).optional().describe("Max seconds for the page to load")}),ld=D.merge(tn).merge(y.object({type:y.literal("NAVIGATE"),url:y.string()})),rn=Ie.merge(y.object({cache:Be})),nn=D.merge(rn.merge(y.object({target:ce.optional(),type:y.literal("SCROLL_UP"),deltaY:y.number().optional()}))),on=D.merge(rn.merge(y.object({target:ce.optional(),type:y.literal("SCROLL_DOWN"),deltaY:y.number().optional()}))),sn=D.merge(rn.merge(y.object({target:ce.optional(),type:y.literal("SCROLL_LEFT"),deltaX:y.number().optional()}))),an=D.merge(rn.merge(y.object({target:ce.optional(),type:y.literal("SCROLL_RIGHT"),deltaX:y.number().optional()}))),Kh=y.discriminatedUnion("type",[nn,on,sn,an]),cd=D.merge(y.object({type:y.literal("DIALOG"),action:y.union([y.literal("ACCEPT"),y.literal("DISMISS")])})),dd=D.merge(y.object({type:y.literal("WAIT"),delay:y.number()})),ud=D.merge(y.object({type:y.literal("WAIT_FOR_URL"),url:y.string(),timeout:y.number().int().optional().describe("Max seconds to wait for the URL to match")})),md=D.merge(tn).merge(y.object({type:y.literal("REFRESH")})),pd=D.merge(y.object({type:y.literal("GO_BACK")})),gd=D.merge(y.object({type:y.literal("GO_FORWARD")})),hd=D.extend({type:y.literal("AUTH_SAVE")}),fd=D.extend({type:y.literal("AUTH_LOAD"),storageState:y.string().describe("JSON string auth state")}),Vs=D.merge(Ie).extend({type:y.literal("CAPTCHA")}),yd=D.merge(y.object({type:y.literal("JAVASCRIPT"),code:y.string(),fragment:y.boolean().optional(),envKey:y.string().optional(),environment:y.union([y.literal("NODE"),y.literal("BROWSER")]).optional().describe("default NODE"),timeout:y.number().int().max(60).optional().describe("Max seconds for the code to complete")})),ao=D.merge(Ie).merge(y.object({type:y.literal("CLICK"),target:ce,doubleClick:y.boolean().optional(),rightClick:y.boolean().optional(),waitForUrl:y.string().optional().describe("call playwright waitForURL after click"),waitForDownload:y.boolean().optional().describe("wait for a download to occur and return the file downloaded"),cache:Be})),lo=D.merge(Ie).merge(y.object({type:y.literal("DRAG"),fromTarget:ce,toTarget:ce,hoverSeconds:y.number().optional().describe("Seconds to hover the object before dropping"),cache:y.object({fromTarget:Tt.optional(),toTarget:Tt.optional()}).optional()})),co=D.merge(Ie).merge(y.object({type:y.literal("MOUSE_DRAG"),target:ce.optional(),deltaX:y.string().describe("pixels to move horizontally, can be template"),deltaY:y.string().describe("pixels to move vertically, can be template"),steps:y.number().optional(),cache:Be})),uo=D.merge(Ie).merge(y.object({type:y.literal("HOVER"),target:ce,cache:Be})),mo=D.merge(Ie).merge(y.object({type:y.literal("FOCUS"),target:ce,cache:Be})),po=D.merge(Ie).merge(y.object({type:y.literal("BLUR"),target:ce,cache:Be})),Sd=D.extend({type:y.literal("FILE_UPLOAD"),fileSource:y.discriminatedUnion("type",[y.object({type:y.literal("URL"),url:y.string()}).describe("Accessible link to the file, either public http or local file://")])}),go=D.merge(Ie).merge(y.object({type:y.literal("SELECT_OPTION"),target:ce,option:y.string(),cache:Be})),ho=D.merge(y.object({type:y.literal("AI_ASSERTION"),assertion:y.string(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional(),timeout:y.number().int().optional().describe("Max seconds to wait for assertion to be true")})),wd=ho.extend({type:y.literal("AI_WAIT")}),Rt=5,fo=60,yo=D.merge(Ie).extend({type:y.literal("ELEMENT_CHECK"),target:ce,assertion:Hs,cache:Be,timeout:y.number().int().min(0).max(fo).optional().describe("max seconds to wait for the assertion to be true")}),bd=D.extend({type:y.literal("PAGE_CHECK"),assertion:Ws,timeout:y.number().int().min(0).max(fo).optional().describe("max seconds to wait for the assertion to be true")}),Cd=D.merge(y.object({type:y.literal("AI_EXTRACT"),goal:y.string(),schema:y.string().optional(),envKey:y.string().optional(),disableCache:y.boolean().optional(),iframeUrl:y.string().optional()})),Ed=y.object({clearContent:y.boolean().optional(),pressKeysSequentially:y.boolean().optional(),force:y.boolean().optional(),pressEnter:y.boolean().optional()}),So=D.merge(Ie).merge(Ed).extend({type:y.literal("TYPE"),target:ce.optional(),value:y.string(),cache:Be}),Td=D.merge(y.object({type:y.literal("PRESS"),value:y.string()})),vd=D.merge(tn).merge(y.object({type:y.literal("TAB"),url:y.string()})),Rd=D.merge(tn).merge(y.object({type:y.literal("NEW_TAB"),url:y.string()})),Ad=D.merge(y.object({type:y.literal("COOKIE"),value:y.string()})),xd=D.merge(y.object({type:y.literal("LOCAL_STORAGE"),key:y.string(),value:y.string()})),Id=D.merge(y.object({type:y.literal("REQUEST"),url:y.string(),method:y.union([y.literal("GET"),y.literal("POST"),y.literal("PUT"),y.literal("DELETE"),y.literal("PATCH")]),headers:y.record(y.string(),y.string()).optional(),params:y.record(y.string(),y.string()).optional(),body:y.string().optional(),timeout:y.number().int().optional().describe("Max seconds to wait for the request to complete")})),Ld=D.merge(y.object({type:y.literal("SUCCESS"),condition:ho.optional()})),Pd=D.merge(y.object({type:y.literal("FAILURE")})),Od=y.object({data:y.string().describe("s3 url to a jpg"),width:y.number(),height:y.number()}),wo=D.merge(Ie).merge(y.object({type:y.literal("VISUAL_DIFF"),threshold:y.number().optional().describe("default 0.1"),target:ce.optional(),screenshot:Od.optional(),cache:Be})),ln=y.discriminatedUnion("type",[ao,So,Td,go,ld,on,nn,ho,Ld]),Md=y.discriminatedUnion("type",[wd,Cd,fd,hd,Vs,Ad,cd,lo,yo,Sd,pd,gd,uo,yd,xd,co,Rd,bd,md,Id,sn,an,vd,wo,dd,mo,po,ud]),cn=y.discriminatedUnion("type",[...ln.options,...Md.options]),bo=y.discriminatedUnion("type",[...ln.options,Pd]);var pt=r=>{let e;switch(r){case"AUTH_SAVE":case"VISUAL_DIFF":case"SUCCESS":case"SCROLL_DOWN":case"SCROLL_UP":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"CAPTCHA":case"GO_BACK":case"GO_FORWARD":case"REFRESH":e={id:Q(),type:r};break;case"AUTH_LOAD":{e={id:Q(),type:r,storageState:""};break}case"AI_EXTRACT":e={id:Q(),type:r,goal:""};break;case"DIALOG":e={id:Q(),type:r,action:"DISMISS"};break;case"DRAG":e={id:Q(),type:r,fromTarget:{type:"description",elementDescriptor:""},toTarget:{type:"description",elementDescriptor:""}};break;case"MOUSE_DRAG":e={id:Q(),type:r,deltaX:"0",deltaY:"0",steps:1};break;case"WAIT_FOR_URL":e={id:Q(),type:r,url:""};break;case"WAIT":e={id:Q(),type:r,delay:1};break;case"HOVER":case"BLUR":case"FOCUS":case"CLICK":e={id:Q(),type:r,target:{type:"description",elementDescriptor:""}};break;case"COOKIE":case"PRESS":case"TYPE":e={id:Q(),type:r,value:"",clearContent:!0};break;case"SELECT_OPTION":e={id:Q(),type:r,target:{type:"description",elementDescriptor:""},option:""};break;case"NAVIGATE":case"NEW_TAB":case"TAB":e={id:Q(),type:r,url:""};break;case"REQUEST":e={id:Q(),type:r,url:"",method:"GET"};break;case"LOCAL_STORAGE":e={id:Q(),type:r,key:"",value:""};break;case"JAVASCRIPT":e={id:Q(),type:r,code:""};break;case"AI_WAIT":case"AI_ASSERTION":e={id:Q(),type:r,assertion:""};break;case"FILE_UPLOAD":{e={id:Q(),type:r,fileSource:{type:"URL",url:""}};break}case"ELEMENT_CHECK":{e={id:Q(),type:r,target:{type:"description",elementDescriptor:""},assertion:{type:"ELEMENT_EXISTENCE",condition:"EXISTS"}};break}case"PAGE_CHECK":{e={id:Q(),type:r,assertion:{type:"CONTENT",value:""}};break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}return cn.parse(e)},we={type:!0,cache:!0},At=y.discriminatedUnion("type",[po.pick(we),ao.pick(we),lo.pick(we),yo.pick(we),mo.pick(we),uo.pick(we),co.pick(we),nn.pick(we),on.pick(we),sn.pick(we),an.pick(we),go.pick(we),So.pick(we),wo.pick(we)]),Co=Object.values(ue).filter(r=>At.options.some(e=>e.shape.type.safeParse(r).success));cn.options.forEach(r=>{if("target"in r.shape&&!Co.includes(r.shape.type.value))throw new Error(`Command ${r.shape.type.value} has a target but no cache`)});var qh=y.discriminatedUnion("type",[po,Vs,ao,lo,mo,uo,co,nn,on,sn,an,go,So,wo,yo]);import{z as Vt}from"zod";var te=(a=>(a.AI_PROVIDER="AIProviderError",a.ACTION_FAILURE="ActionFailureError",a.ASSERTION_FAILURE="AssertionFailureError",a.CONFIG_ERROR="UserConfigurationError",a.JOB_TIMEOUT="JobTimeoutError",a.WEB_AGENT_PLATFORM="InternalWebAgentError",a.UNKNOWN_PLATFORM="InternalPlatformError",a))(te||{});var Ks={ActionFailureError:"Action failure",AssertionFailureError:"Assertion failure",UserConfigurationError:"Configuration error",AIProviderError:"AI provider error",InternalWebAgentError:"Momentic AI agent error",InternalPlatformError:"Infrastructure error",JobTimeoutError:"Job timeout"},qs={ActionFailureError:"A browser action such as a click or type failed to execute because of the underlying page state is incorrect, suggesting a bug in the application itself.",AssertionFailureError:"An AI assertion or check failed for a legitimate reason, such as a missing element, a change in the page structure, or an unexpected state (e.g. loading state).",UserConfigurationError:"The error message suggests a misconfiguration in the test, such as a variable being undefined, an environment variable missing, or a typo in a step. Do not use this reason if the error is caused by a bug in the application being tested, or Momentic's AI software.",AIProviderError:"The AI provider failed to return a response or returned a malformed response.",InternalWebAgentError:"The AI testing framework failed to find the correct element or evaluate the assertion correctly, even though the test steps and application state look valid. In other words, the AI agent failed to understand the page.",InternalPlatformError:"A platform error occurred, such as the Chromium browser failing, the network being down, or an action timing out. The error is likely caused by a transient infrastructure issue such as lack of resources or network flakiness.",JobTimeoutError:"The test took too long to complete, suggesting a problem with the test itself."},Eo=Vt.object({reason:Vt.nativeEnum(te),summary:Vt.string()}),Ys=Vt.object({errorMessage:Vt.string(),errorStack:Vt.string().optional(),classification:Eo.optional()});var $e=class extends Error{constructor(e,t={}){super(e,t),this.name="CancellationError"}};var dn=class extends Error{constructor(e,t,n,o={}){super(`The ${n} with id ${t} is invalid: ${e}`,o),this.name="InvalidEntityError"}};var un=class extends Error{constructor(e,t={}){super(e,t),this.name="TemplateMatcherThresholdError"}},R=class extends Error{reason;emitToUser;constructor(e,t,n={},o=!1){let s=!1;for(let i of Object.values(te))if(t.startsWith(i)){s=!0,e=i;break}s?super(t,n):super(`${e}${t?`: ${t}`:""}`,n),this.name="TestFailureError",this.stack=this.stack?.slice(this.name.length+2),this.reason=e,this.emitToUser=o}toString(){return this.message}toJSON(){return{message:this.message}}},Ye=class extends Error{decisions;constructor(e,t,n={}){super(e,n),this.decisions=t,this.name="NoElementsFoundError"}toString(){return`${this.message}
|
|
3
|
+
Decisions:
|
|
4
|
+
${this.decisions.map(e=>e.toString()).join(`
|
|
5
|
+
`)}`}};var To=(m=>(m.COMMAND="command",m.ASSERTION="assertion",m.LOCATOR="locator",m.VISUAL_LOCATOR="visual-locator",m.VISUAL_ASSERTION="visual-assertion",m.REVERSE_MAPPER="reverse-mapper",m.TEXT_EXTRACTION="text-extraction",m.GOAL_SPLITTER="goal-splitter",m.TEST_GEN_PLANNING="test-gen-planning",m.TEST_GEN_REVISING="test-gen-revising",m.TEST_GEN_EVAL="test-gen-evaluation",m.TEST_GEN_TASK_RABBIT="test-gen-task-rabbit",m.RESULT_CLASSIFICATION="result-classification",m.KEYWORD_EXTRACTOR="keyword-extractor",m))(To||{});var cf=Y.object({command:Y.string(),thoughts:Y.string()}),df=Y.string().pipe(Y.coerce.number());var Xs=Y.object({phrase:Y.string()}),vo=Y.object({result:Y.union([Y.literal("NOT_FOUND"),Y.string(),Y.number(),Y.array(Y.unknown()),Y.record(Y.unknown(),Y.unknown())])}),Js=Y.object({thoughts:Y.string(),id:Y.number().int()});import{z as Ro}from"zod";var mn=Ro.object({width:Ro.number().min(200).max(1e4),height:Ro.number().min(200).max(1e4)}),Qs={"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}},pf=Object.keys(Qs);var Xe=Qs["Desktop Large"];import{z as ei}from"zod";import{z as Zs}from"zod";import{z as Ao}from"zod";var Le=Ao.object({index:Ao.number().optional().describe("global index"),skipped:Ao.boolean().optional()});var K=(i=>(i.PRESET_ACTION="PRESET_ACTION",i.MODULE="MODULE",i.AI_ACTION="AI_ACTION",i.CONDITIONAL="CONDITIONAL",i.IFRAME="IFRAME",i.SECTION="SECTION",i))(K||{});var Pe=Le.extend({type:Zs.literal("PRESET_ACTION"),command:cn,skipped:Zs.boolean().optional()});var Kt=Le.extend({type:ei.literal("AI_ACTION"),text:ei.string(),steps:Pe.array().optional()});import{z as X}from"zod";var Nd=X.object({cacheKey:X.string(),cacheExpiryMs:X.number()}),xo=Le.extend({id:X.string().uuid().describe("ID of the module step itself. Used to 'namespace' step cache entries."),inputs:X.record(X.string()).optional(),cacheConfig:Nd.optional()}),qt=xo.extend({type:X.literal("MODULE"),moduleId:X.string().uuid()}),_d=X.union([qt.pick({type:!0,moduleId:!0}),X.record(X.unknown())]),De=X.object({moduleId:X.string().uuid(),name:X.string(),parameters:X.string().array().nullish(),defaultParameters:X.record(X.string(),X.string()).nullish(),defaultCacheKey:X.string().nullish(),defaultCacheTtl:X.number().nullish()});import{z as oe}from"zod";import{z as ti}from"zod";var wr=Le.extend({type:ti.literal("CONDITIONAL"),skipped:ti.boolean().optional()});import{z as Oe}from"zod";var kd=Oe.object({type:Oe.literal("attr"),name:Oe.string(),value:Oe.string()}),Dd=Oe.object({type:Oe.literal("css"),selector:Oe.string()}),Fd=Oe.object({type:Oe.literal("url"),url:Oe.string()}),Ud=Oe.union([kd,Fd,Dd]),br=Le.extend({type:Oe.literal("IFRAME"),identifier:Ud});import{z as ri}from"zod";var Cr=Le.extend({type:ri.literal("SECTION"),description:ri.string()});var ni=De.merge(xo).extend({type:oe.literal("RESOLVED_MODULE"),steps:oe.lazy(()=>Re.array())}),Io=De.extend({steps:oe.lazy(()=>Re.array())}),zd=br.extend({steps:oe.lazy(()=>Me.array())}),Bd=br.extend({steps:oe.lazy(()=>Re.array())}),$d=Cr.extend({steps:oe.lazy(()=>Me.array())}),Hd=Cr.extend({steps:oe.lazy(()=>Re.array())}),Wd=wr.extend({blocks:oe.object({assertion:oe.lazy(()=>Pe),steps:oe.lazy(()=>Me.array())}).array(),elseSteps:oe.lazy(()=>Me.array().optional())}),Gd=wr.extend({blocks:oe.object({assertion:oe.lazy(()=>Pe),steps:oe.lazy(()=>Re.array())}).array(),elseSteps:oe.lazy(()=>Re.array().optional())}),Me=oe.discriminatedUnion("type",[Pe,Kt,qt,Wd,zd,$d]),Re=oe.discriminatedUnion("type",[Pe,Kt,ni,Gd,Bd,Hd]);var be="1.0.10";import{z as xt}from"zod";var Lo=xt.object({key:xt.string(),testId:xt.string().optional(),moduleId:xt.string().optional(),organizationId:xt.string(),value:At}),oi=xt.record(xt.string(),Lo);var My=new Set(Object.values(ue));var Po={AI_ACTION:"AI action",RESOLVED_MODULE:"Module",AI_ASSERTION:"AI check",AI_WAIT:"AI wait",AI_EXTRACT:"AI extract",CLICK:"Click",TYPE:"Type",JAVASCRIPT:"JavaScript",SELECT_OPTION:"Select",PRESS:"Press",NAVIGATE:"Navigate",SCROLL_UP:"Scroll up",SCROLL_DOWN:"Scroll down",SCROLL_LEFT:"Scroll left",SCROLL_RIGHT:"Scroll right",HOVER:"Hover",BLUR:"Blur",FILE_UPLOAD:"File upload",FOCUS:"Focus",GO_BACK:"Go back",GO_FORWARD:"Go forward",WAIT:"Wait",REFRESH:"Refresh",TAB:"Switch tab",NEW_TAB:"New tab",COOKIE:"Cookie",LOCAL_STORAGE:"Local storage",REQUEST:"Request",CAPTCHA:"CAPTCHA",DRAG:"Drag & drop",VISUAL_DIFF:"Visual diff",DIALOG:"Dialog",MOUSE_DRAG:"Mouse drag",AUTH_LOAD:"Load auth state",AUTH_SAVE:"Save auth state",ELEMENT_CHECK:"Element check",PAGE_CHECK:"Page check",WAIT_FOR_URL:"Wait for URL",SUCCESS:"Done"},Ny={AI_ACTION:"Ask AI to plan and execute something on the page.",RESOLVED_MODULE:"A list of steps that can be reused in multiple tests.",AI_ASSERTION:"Ask AI whether something is true on the page, retrying until a configurable timeout.",AI_WAIT:"Wait until AI considers a condition to be true.",CLICK:"Click on an element on the page based on a description.",DIALOG:"Specify how native browser dialogs should be handled.",AI_EXTRACT:"Ask AI to extract data from the page based on a description.",HOVER:"Hover over an element on the page based on a description.",FILE_UPLOAD:"Automatically upload a file when the next file chooser is activated.",FOCUS:"Focus an element on the page based on a description.",BLUR:"Remove focus from an element on the page based on a description.",SELECT_OPTION:"Select an option from an HTML Select <select> element based on a description.",TYPE:"Type the specified text into an element.",PRESS:"Press the specified keys using the keyboard. (e.g. Ctrl+A)",NAVIGATE:"Navigate to the specified URL.",SCROLL_UP:"Scroll up by a specified height.",SCROLL_DOWN:"Scroll down by a specified height.",SCROLL_LEFT:"Scroll left by a specified width.",SCROLL_RIGHT:"Scroll right by a specified width.",GO_BACK:"Go back in browser history.",GO_FORWARD:"Go forward in browser history.",WAIT:"Wait for the specified number of seconds.",REFRESH:"Refresh the page. This will not clear cookies or session data.",TAB:"Switch to different tab in the browser.",NEW_TAB:"Create and switch to a new tab in the browser.",COOKIE:"Set a cookie that will persist throughout the browser session",LOCAL_STORAGE:"Set a local storage value that will persist throughout the browser session",CAPTCHA:"Solve CAPTCHAs on the page. This feature is only available on Momentic Cloud and may take up to 60 seconds. Disabling CAPTCHAs in non-production environments is strongly advised.",REQUEST:"Make an API request to a URL.",JAVASCRIPT:"Run JavaScript code in an isolated context.",DRAG:"Click and drag an element to another location.",VISUAL_DIFF:"Compare a screenshot of the page or a specific element to a baseline image.",MOUSE_DRAG:"Click and drag the mouse by a specified distance.",AUTH_LOAD:"Load auth state (cookies, local storage) from the JavaScript object format returned by 'Save auth state' and then refresh the page.",AUTH_SAVE:"Save auth state (cookies, local storage) into a JavaScript object format usable by 'Load auth state'.",ELEMENT_CHECK:"Assert on an element's state using pre-built conditions, including content, visibility, attribute value checks.",PAGE_CHECK:"Assert on the active page's state using pre-built conditions, including URL and content checks.",WAIT_FOR_URL:"Wait for the active page's URL to match a specific URL or glob pattern. If a new tab is opened, this command will wait for the new tab's URL to match instead.",SUCCESS:"Indicate the entire AI action has succeeded, optionally based on a condition."};import{z as B}from"zod";var Dy=B.object({body:B.string(),to:B.string(),from:B.string()}),Fy=B.object({from:B.string().optional(),to:B.string().optional(),timeout:B.number().optional(),beforeDate:B.string().pipe(B.coerce.date()).or(B.date()).optional(),afterDate:B.string().pipe(B.coerce.date()).or(B.date()).optional()}),Uy=B.object({inbox:B.string(),afterDate:B.string().pipe(B.coerce.date()).or(B.date()).optional(),timeout:B.number().optional(),trimWhitespace:B.boolean().optional()});var jd=B.object({result:B.unknown(),variableUpdates:B.record(B.string(),B.unknown()).optional(),error:B.string().optional(),success:B.boolean()}),si=15e3;import*as M from"zod";import{cloneDeep as Jt}from"lodash-es";import*as q from"zod";import{z as Yt}from"zod";var Je="BASE_URL",pn="CURRENT_URL",Xt="ENV_NAME",$y={[Je]:"https://www.google.com"},ii=Yt.string().describe("Name of the fixture (must be available locally in the fixtures directory)."),Ae=Yt.object({name:Yt.string(),variables:Yt.record(Yt.string().describe("variable name"),Yt.string().describe("variable value"))});import*as It from"zod";var ai=It.object({type:It.nativeEnum(K),generatedStep:ln.optional(),serializedCommand:It.string().optional(),elementInteracted:It.string().optional()});var gt=q.object({goal:q.string(),url:q.string(),browserState:q.string(),history:q.string(),numPrevious:q.number(),lastCommand:ai.or(q.null()),returnSchema:q.string().optional()}),Oo=q.object({env:q.record(q.unknown()),results:q.array(q.unknown()),inputs:q.record(q.unknown()).optional()}),Vd="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022",Kd=[Je,Xt],li=[pn,Je,Xt],ge=class r{env={};inputs=void 0;results=[];varsFromMomenticEnvironment={};constructor(e){this.reset(e)}static fromSnapshot({snapshot:e,environmentVariables:t}){let n=e.env[Je]??"about:blank",o=e.env[pn]??"about:blank",s=e.env[Xt],i={};for(let[l,c]of Object.entries(e.env))li.includes(l)||(t??{})[l]===void 0&&(i[l]=c);let a=new r({baseUrl:n,currentUrl:o,dynamicVariables:i,envName:s,variablesFromEnvironment:t??{}});return a.setInputs(e.inputs),a.setResults(e.results),a}setEnvVariables(e){let t=Jt(e);this.env=Object.assign(this.env,t)}setInputs(e){this.inputs=e}setResult(e,t){this.results[e]=t||null;for(let n=0;n<e;n++)this.results[n]===void 0&&(this.results[n]=null)}getResult(e){return this.results[e]}getResultsCopy(){return Jt(this.results)}setResults(e){this.results=e}clearResults(){this.results=[]}getVariable(e){return this.env[e]}setVariable(e,t){Kd.includes(e)||(this.env[e]=t)}getEnvName(){return this.env[Xt]}toObjectCopy(){let e={results:this.results,env:Object.assign({},this.env,this.varsFromMomenticEnvironment)};return this.inputs&&(e.inputs=this.inputs),Jt(e)}toRedactedDisplayCopy(){let e=this.toObjectCopy();return e.env=Object.fromEntries(Object.entries(e.env).map(([t,n])=>li.includes(t)||this.varsFromMomenticEnvironment[t]===void 0?[t,n]:[t,Vd])),e}setUrl(e){this.env[pn]=e}reset(e){this.results=[],this.env={},this.varsFromMomenticEnvironment={},this.env[Je]=e.baseUrl,e.envName&&(this.env[Xt]=e.envName),this.setUrl(e.currentUrl),this.setEnvVariables(e.dynamicVariables??{}),this.varsFromMomenticEnvironment=Jt(e.variablesFromEnvironment)}getDynamicVariablesCopy(){return Jt(this.env)}getVariablesFromEnvironmentCopy(){return Jt(this.varsFromMomenticEnvironment)}},ci=Object.getPrototypeOf(async function(){}).constructor;var Qe=(s=>(s.SUCCESS="SUCCESS",s.FAILED="FAILED",s.RUNNING="RUNNING",s.IDLE="IDLE",s.CANCELLED="CANCELLED",s))(Qe||{}),gn=(n=>(n.SUCCESS="SUCCESS",n.FAILED="FAILED",n.CANCELLED="CANCELLED",n))(gn||{}),qd=M.object({beforeUrl:M.string(),beforeScreenshot:M.string().optional(),afterUrl:M.string().optional(),afterScreenshot:M.string().optional(),startedAt:M.coerce.date(),finishedAt:M.coerce.date(),viewport:M.object({height:M.number(),width:M.number()}),status:M.nativeEnum(gn),message:M.string().optional(),elementInteracted:M.string().optional()}),Lt=M.object({startedAt:M.coerce.date(),finishedAt:M.coerce.date(),status:M.nativeEnum(Qe),message:M.string().optional(),data:M.unknown().optional(),beforeTestContext:Oo.optional(),afterTestContext:Oo.optional(),failureReason:M.nativeEnum(te).optional(),details:M.unknown().describe("Parse using StepExecutionLogSchema.array() to get type safety. We don't explicitly type it because it's non-critical information.")}),Mo=Lt.merge(Pe).extend({results:qd.array()}),Yd=Lt.merge(Kt).extend({results:M.lazy(()=>Mo.array())}),Xd=Lt.merge(qt).extend({moduleName:M.string().optional(),results:M.lazy(()=>Pt.array())}),Jd=Lt.merge(wr).extend({assertion:Mo.optional(),results:M.lazy(()=>Pt.array()).describe("results for the block actually executed")}),Qd=Lt.merge(br).extend({results:M.lazy(()=>Pt.array())}),Zd=Lt.merge(Cr).extend({results:M.lazy(()=>Pt.array())}),Pt=M.discriminatedUnion("type",[Yd,Mo,Xd,Jd,Qd,Zd]),hn=Lt.pick({startedAt:!0,finishedAt:!0,status:!0,message:!0,data:!0}),sS=M.object({results:Pt.array(),errorMessage:M.string(),errorStack:M.string().optional()});import{parseString as eu,splitCookiesString as tu}from"set-cookie-parser";import{z as J}from"zod";var di=J.object({name:J.string(),value:J.string(),url:J.string().optional(),domain:J.string().optional(),path:J.string().optional(),expires:J.number().default(Date.now()/1e3+60*60*24*365),httpOnly:J.boolean().optional(),secure:J.boolean().default(!0),sameSite:J.union([J.literal("Strict"),J.literal("Lax"),J.literal("None")]).default("None")});function ui(r){let e=[],t=tu(r);for(let n of t){let o=eu(n);if(!o.name)throw new Error("Name missing from cookie");if(!o.value)throw new Error("Value missing from cookie");let s;if(o.sameSite){let c=o.sameSite.trim().toLowerCase();if(c==="strict")s="Strict";else if(c==="lax")s="Lax";else if(c==="none")s="None";else throw new Error(`Invalid sameSite setting in cookie: ${c}`)}o.httpOnly===void 0&&(o.httpOnly=!1),!o.path&&o.domain&&(o.path="/");let i=di.parse({...o,expires:o.expires?o.expires.getTime()/1e3:void 0,sameSite:s});e.push(i);let a=[i.name,...Object.keys(i)].map(c=>c.toLowerCase()),l=n.match(/\b(\w+)=([^;]*)/g);if(l)for(let c of l){let[u,d]=c.split("=");if(!u||!d)throw new Error(`Invalid key-value pair in cookie: ${c}`);a.includes(u.toLowerCase())||e.push({...i,name:u,value:d})}}return e}var ru=J.object({origin:J.string(),localStorage:J.array(J.object({name:J.string(),value:J.string()}))}),mi=J.object({cookies:di.array(),origins:ru.array()});import{z as Ze}from"zod";var fn=Ze.object({x:Ze.number(),y:Ze.number(),correlation:Ze.number()}),uS=Ze.object({searchImageBase64String:Ze.string(),pageImageBase64String:Ze.string(),id:Ze.string().uuid(),timeoutMs:Ze.number().max(1e4).min(0).optional()});import{z as Ce}from"zod";var nu=Ce.object({orgId:Ce.string(),cacheKeys:Ce.string().array()}),gS=Ce.object({keyParams:nu,clientMetadata:Ce.string(),lockAcquisitionTimeoutMs:Ce.number().optional()}),pi=Ce.object({acquired:Ce.boolean(),acquiredByMetadata:Ce.string(),keyPrefix:Ce.string()}),hS=Ce.object({keyPrefix:Ce.string(),result:Ce.string(),ttlMs:Ce.number()}),gi=0,hi=5*60*1e3;var yn=class{flags;constructor(e){this.flags=e}isBooleanFlagEnabled(e){return this.flags[e]===!0}getAllFlags(){return this.flags}};import{z as Ne}from"zod";import{z as Z}from"zod";import{z}from"zod";var ht="momentic",ft="modules",Sn="fixtures",Qt="environments",No="chromium",wn=[ft,Sn,Qt,No];import{isValidCron as ou}from"cron-validator";import{z as re}from"zod";var fi=1e4,yi=6e4,Er=re.object({pageLoadTimeoutMs:re.number().optional().refine(r=>r===void 0||r<=yi&&r>=-1,{message:`Page load timeout must be between 0 and ${yi/1e3} seconds`}),smartWaitingTimeoutMs:re.number().optional().refine(r=>r===void 0||r<=fi&&r>=-1,{message:`Smart waiting timeout must be between 0 and ${fi/1e3} seconds`}),extraHeaders:re.record(re.string(),re.string()).optional().describe("HTTP headers to be sent on every request"),userAgent:re.string().optional()}),su=re.object({disableAICaching:re.boolean().default(!1),viewport:mn.optional()}),Ot=su.merge(Er),Si=re.object({cron:re.string().refine(r=>ou(r),{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()}),wi=re.object({onSuccess:re.boolean().default(!1),onFailure:re.boolean().default(!0)});var iu=z.string().min(1).max(255).superRefine((r,e)=>{try{Tr(r)}catch(t){return e.addIssue({code:z.ZodIssueCode.custom,message:t.message,fatal:!0}),z.NEVER}}),au=z.object({name:z.string(),default:z.boolean().optional(),defaultOnLocal:z.boolean().optional().describe("DEPRECATED: migrated to default instead"),defaultOnCloud:z.boolean().optional().describe("DEPRECATED: migrated to default instead"),fixtures:ii.array().optional()}),me=z.object({id:z.string(),name:iu,baseUrl:z.preprocess(r=>r===null?"":r,z.union([z.string().url(),z.literal("")])).optional(),schemaVersion:z.string(),advanced:Ot,retries:z.number(),envs:z.array(au).optional()}),IS=me.pick({name:!0,baseUrl:!0,retries:!0}).extend({advanced:Ot}),bi=z.object({createdAt:z.coerce.date(),updatedAt:z.coerce.date(),schedule:Si,notification:wi,createdBy:z.string(),organizationId:z.string()}),LS=me.merge(bi),PS=me.merge(bi).merge(z.object({steps:z.array(Re)})),bn=me.merge(z.object({steps:z.array(Re)})),OS=me.extend({steps:z.record(z.string(),z.unknown()).array()}),lu=/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;function Tr(r){if(r=r.toLowerCase().trim(),r.length===0||r.length>255)throw new Error("Name must be between 1 and 255 characters long");if(/[<>:"\/\\|?*\x00]/.test(r))throw new Error('Name contains one of the following invalid characters: <>:"/\\|?*');if(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i.test(r))throw new Error(`"${r}" is a reserved name on Windows and cannot be used as a filename.`);if(/^\.+$/.test(r)||/^\s|\s$/.test(r))throw new Error("Name cannot start or end with a space or dot.");if(r.endsWith(".yaml"))throw new Error('Name cannot end with ".yaml".');if(r==="none")throw new Error("Name cannot be 'none'.");if(wn.includes(r))throw new Error("'modules' is a reserved folder name in Momentic. Please choose a different name.");if(r.match(lu))throw new Error("Name cannot be a UUID. Please choose a different name.")}var US=De.extend({fileType:Z.literal("momentic/module"),schemaVersion:Z.string(),steps:Z.record(Z.string(),Z.unknown()).array()}),vr=De.extend({steps:Z.array(Z.record(Z.string(),Z.unknown())),schemaVersion:Z.string()}),zS=me.extend({steps:Z.array(Z.record(Z.string(),Z.unknown()))}),BS=Z.object({test:Z.string().describe("YAML for the test, including metadata and steps"),modules:Z.record(Z.string(),Z.string()).describe("Map of module name to YAML for the module")});var cu="1.0.0",Ci=Ne.object({run:Ne.string().describe("Run a single command in the shell. The working directory will be set to where the CLI was invoked from."),waitForCompletion:Ne.boolean().optional().describe("Defaults to true")}),Ei=Ne.object({type:Ne.literal("momentic/fixture"),schemaVersion:Ne.string(),name:Ne.string(),description:Ne.string().optional(),setup:Ne.object({steps:Ci.array(),timeout:Ne.number().optional().describe("Timeout for all steps in seconds")}).optional(),teardown:Ne.object({steps:Ci.array(),timeout:Ne.number().optional().describe("Timeout for all steps in seconds")}).optional()}),GS={type:"momentic/fixture",schemaVersion:cu,name:"example",description:"An example fixture",setup:{steps:[{run:"./scripts/seed_db.sh",waitForCompletion:!0},{run:"npm run start",waitForCompletion:!1}],timeout:30},teardown:{steps:[{run:"./scripts/shutdown_db.sh"}]}};import{z as du}from"zod";var KS=du.string().array();import{z as $}from"zod";var rw=$.array($.object({id:$.string(),name:$.string(),fullFilePath:$.string(),testPath:$.string().describe("path relative to the root test directory, i.e. my-folder/my-test.yaml"),fileName:$.string(),lastModified:$.coerce.date(),createdAt:$.coerce.date()}));var Ti=$.object({steps:Re.array()}),vi=me,Ri=$.object({name:$.string(),baseUrl:$.string().url().optional(),environment:$.string().optional(),viewport:mn.optional()}),nw=bn.merge($.object({testPath:$.string()})),Ai=$.object({name:$.string(),steps:$.lazy(()=>Re.array())});var ow=Io.array(),sw=$.array($.object({name:$.string(),moduleId:$.string().uuid(),numSteps:$.number()})),iw=$.array(Ae),xi=$.object({defaultEnv:$.string().optional().describe("name of the default env, or undefined to unset")});import*as U from"zod";var dw=U.object({thoughts:U.string().optional().describe("only provided if a description was provided"),target:Tt.optional().describe("only provided if a description was provided"),pageState:U.string().optional().describe("serialized a11y tree, only provided if a description was provided"),options:U.array(U.string()).optional().describe("provided for <select> elements only"),screenshot:U.object({data:U.string(),height:U.number().int(),width:U.number().int()}).optional().describe("only provided if returnScreenshot is true")});function Ar(r,e){if(!e||"useSelector"in r&&r.useSelector)return e;switch(r.type){case"SELECT_OPTION":return`<select> element: ${e}`;case"TYPE":return`text input element: ${e}`;default:return e}return e}var Zt=U.object({matched:U.boolean(),reason:U.string().optional().describe("Human understandable description")}),uu=Zt.extend({type:U.literal("A11Y_ID")}),mu=Zt.extend({type:U.literal("USER_SELECTOR")}),pu=Zt.extend({type:U.literal("CSS_SELECTOR"),selectors:U.string().array()}),gu=Zt.extend({type:U.literal("A11Y_DISTANCE"),distance:U.number().optional(),closestElement:U.string().optional(),savedElement:U.string().optional()}),hu=Zt.extend({type:U.literal("HTML_DISTANCE"),distance:U.number().optional(),closestElement:U.string().optional(),savedElement:U.string().optional()}),fu=Zt.extend({type:U.literal("TEMPLATE_MATCHING"),elementImageUrl:U.string().url()}),Ii=U.discriminatedUnion("type",[uu,mu,pu,gu,hu,fu]);var yu={0:"DEBUG",1:"INFO",2:"WARN",3:"ERROR"},Su={0:"\x1B[90m",1:"\x1B[32m",2:"\x1B[33m",3:"\x1B[31m"},_o=class r{minLogLevel;logBindings;constructor(e,t){this.minLogLevel=e,this.logBindings=t}logWithLevel(e,...t){let n=yu[e],o;Array.isArray(t[0])?(o=t[0],t=t.slice(1)):typeof t[0]=="object"&&!(t[0]instanceof Error)&&(o={...t[0],...this.logBindings},t=t.slice(1));let s=Su[e],i=[`${s}[${new Date().toTimeString().slice(0,8)}][${n}]`];if(e!==0&&i.push("\x1B[39m"),i.push(...t),console.log(...i),o&&!Array.isArray(o))for(let[a,l]of Object.entries(o)){let c=l;l instanceof Error?c=l.message:typeof l=="object"&&(c=JSON.stringify(l,void 0,2),c=c.split(`
|
|
3
6
|
`).map((u,d)=>d>0?` ${u}`:u).join(`
|
|
4
7
|
`)),console.log(e===0?`${s} ${a}:`:` ${a}:`,c)}else if(o)for(let a of o){let l=a;typeof a=="object"&&(l=JSON.stringify(a,void 0,2),l=l.split(`
|
|
5
8
|
`).map((c,u)=>u>0?` ${c}`:c).join(`
|
|
6
|
-
`)),console.log(e===0?`${s} `:" ",l)}e===0&&process.stdout.write("\x1B[39m")}setMinLevel(e){this.minLogLevel=e}log(...e){this.info(...e)}info(...e){1<this.minLogLevel||this.logWithLevel(1,...e)}debug(...e){0<this.minLogLevel||this.logWithLevel(0,...e)}warn(...e){2<this.minLogLevel||this.logWithLevel(2,...e)}error(...e){3<this.minLogLevel||this.logWithLevel(3,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},Ei=new Lo(1,{}),Po={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>Po,flush:()=>{},bindings:()=>({})},Sn={},Ot=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,s,...i)=>{let a=Sn[e];a?clearTimeout(a.timer):(a={count:0,totalCount:0},Sn[e]=a),a.totalCount++,a.count<t&&(a.count++,r.debug(o,s,...i)),a.timer=setTimeout(()=>{let l=Sn[e];l?.totalCount!==l?.count&&r.debug({logKey:e,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${e}`),delete Sn[e]},n)};import{z as fe}from"zod";var gu=fe.object({id:fe.string(),createdAt:fe.coerce.date(),createdBy:fe.string(),organizationId:fe.string(),name:fe.string(),schemaVersion:fe.string().describe("Schema version for steps"),parameters:fe.string().array().nullish().describe("Parameter list"),defaultParameters:fe.record(fe.string(),fe.string()).nullish(),defaultCacheKey:fe.string().nullish(),defaultCacheTtl:fe.number().nullish(),numSteps:fe.number()}),mw=gu.omit({numSteps:!0}).extend({steps:fe.lazy(()=>Me.array())}),vi=5*60*1e3;var pe=r=>{let e=r.trim().toLowerCase().replace(/[^a-z0-9]/g,"-");for(;e.includes("--");)e=e.replaceAll("--","-");return e.startsWith("-")&&(e=e.slice(1)),e.endsWith("-")&&(e=e.slice(0,e.length-1)),e};import*as T from"zod";import{z as k}from"zod";var Rr={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},ht=(a=>(a.PENDING="PENDING",a.RUNNING="RUNNING",a.PASSED="PASSED",a.FAILED="FAILED",a.CANCELLED="CANCELLED",a.RETRYING="RETRYING",a.WAITING_FOR_USER="WAITING_FOR_USER",a))(ht||{}),hu={PASSED:"PASSED",FAILED:"FAILED"},et=k.string().pipe(k.coerce.date()).or(k.date()),wn=k.object({id:k.string(),runKey:k.string(),organizationId:k.string(),createdAt:et,createdBy:k.string(),scheduledAt:et.or(k.null()),startedAt:et.or(k.null()),updatedAt:et.nullish(),finishedAt:et.or(k.null()),status:k.unknown().transform(r=>k.nativeEnum(ht).parse(r)),expectedStatus:k.nativeEnum(hu).or(k.null()),trigger:k.nativeEnum(Rr),attempts:k.number(),failureReason:k.nativeEnum(ue).nullish(),failureDetails:Ws.nullish(),testId:k.string().or(k.null()),testName:k.string().or(k.null()).optional(),test:k.object({name:k.string(),id:k.string()}).or(k.null()),suiteId:k.string().or(k.null()).optional()}),bw=wn.omit({failureReason:!0,failureDetails:!0}),xr=wn.merge(k.object({results:Lt.array(),test:k.object({name:k.string(),id:k.string(),baseUrl:k.string(),advanced:Pt.optional()}).or(k.null())})),Cw=k.object({id:k.string(),name:k.string()});var Mt=T.object({disableCache:T.boolean()}),Ow=T.object({error:T.boolean(),reason:T.string(),message:T.string()}),Mw=mt.merge(Mt),Ai=fo,Nw=mt.merge(Mt).merge(T.object({screenshot:T.string().optional()})),Ri=ks,_w=mt.pick({browserState:!0,goal:!0}).merge(Mt).merge(T.object({screenshot:T.string().optional()})),kw=mt.pick({goal:!0}).merge(Mt).merge(T.object({screenshot:T.string().describe("base64 encoded image"),hintActivatedScreenshot:T.string().describe("base64 encoded image")})),xi=js,Dw=mt.pick({goal:!0,url:!0}).merge(Mt),Ii=T.string().array(),Fw=mt.pick({goal:!0,browserState:!0}).merge(Mt),Li=Gs,Uw=mt.pick({goal:!0,browserState:!0,returnSchema:!0}).merge(Mt);var zw=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()}),Pi=T.object({message:T.string(),queuedTests:T.object({name:T.string(),id:T.string()}).array(),runIds:T.string().uuid().array()}),Oi=yn,Mi=T.string().array(),Bw=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")})]),Ni=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"))}),fu=T.object({test:T.string().describe("test YAML"),modules:T.record(T.string().describe("moduleId"),T.string().describe("module YAML"))}),$w=fu.array(),Hw=T.object({testId:T.string(),schemaVersion:T.string(),steps:T.array(T.record(T.unknown()))}),Ww=T.object({entries:T.array(vo),testId:T.string()}),Gw=T.object({steps:T.array(T.record(T.unknown())),testId:T.string(),schemaVersion:T.string(),organizationId:T.string()}),_i=Qs;var jw=T.object({testId:T.string(),testName:T.string(),trigger:T.nativeEnum(Rr)}),ki=xr,Di=xr,yu=xr.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Fi=yu.array(),Vw=xr.pick({startedAt:!0,finishedAt:!0,results:!0,status:!0,failureDetails:!0,failureReason:!0}).partial(),qw=T.object({screenshot:T.string()}),Ui=T.object({key:T.string()}),zi=T.object({orgId:T.string()}),Bi=T.array(Re),Kw=T.array(Re),$i=T.record(T.string(),T.union([T.string(),T.boolean()])),Yw=T.object({paths:T.string().array(),env:T.string().optional(),urlOverride:T.string().optional(),customHeaders:T.record(T.string(),T.string()).optional()}),Hi=T.object({suiteRunIds:T.string().array()});import{z as ye}from"zod";var Su=ye.object({content:ye.string(),ids:ye.string().array(),tokenLength:ye.number()}),wu=ye.object({chunks:Su.array(),numRecs:ye.number()}),Qw=ye.object({ids:ye.string().array(),score:ye.number(),tokenLength:ye.number()}),Zw=ye.object({description:ye.string(),tokenLimit:ye.number()}).merge(wu),Wi=ye.object({ids:ye.number().array()});import{z as se}from"zod";var bu=se.object({type:se.literal("TARGETING"),name:se.string().optional().describe("Target name for steps with multiple targets"),elementLocationDecisions:Ti.array(),pageState:se.string().optional(),targetSource:se.nativeEnum(qt).optional()}),Cu=se.object({type:se.literal("AI_LOCATION"),matched:se.boolean(),pageState:se.string().optional(),ragUsed:se.boolean().optional(),thoughts:se.string().optional()}),Tu=se.object({type:se.literal("ASSERTION"),relevantElementsSerialized:se.string().array().optional(),pageState:se.string().optional(),ragUsed:se.boolean().optional()}),ob=se.discriminatedUnion("type",[bu,Cu,Tu]);function bn(){return{details:[]}}import{z as Fe}from"zod";var Gi=Fe.object({id:Fe.string().uuid(),orgId:Fe.string(),createdAt:et,startedAt:et.or(Fe.null()),finishedAt:et.or(Fe.null()),status:Fe.string().transform(r=>Fe.nativeEnum(ht).parse(r)),trigger:Fe.nativeEnum(Rr),suite:Fe.object({id:Fe.string(),name:Fe.string()}),runs:wn.array()});import{validator as pb}from"@exodus/schemasafe";var ji=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"];var Vi=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};var rr=class extends Error{status;constructor(e,t,n={}){super(t,n),this.status=e}},nr=class{baseUrl;apiKey;logger;constructor(e){this.baseUrl=e.baseUrl,this.apiKey=e.apiKey,this.logger=e.logger}async sendRequest(e,t,n=3,o=3e4){let s=new AbortController,i=setTimeout(()=>s.abort(),o),a=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},signal:s.signal});if(clearTimeout(i),!a.ok){if(a.status>500&&n>0)return await new Promise(c=>setTimeout(c,1500*Math.random())),this.sendRequest(e,t,n-1);throw new rr(a.status,`Request to ${e} failed with status ${a.status}: ${await a.text()}`)}let l;return a.status===204?l=await a.text():l=await a.json(),this.logger&&!t.noLog&&this.logger.debug({result:l,path:e,baseUrl:this.baseUrl,status:a.status},"Got response from Momentic server"),l}};var j="v1",ie=class extends nr{constructor(e){super(e)}getAppUrl(){return this.baseUrl.replace(/\/\/api/,"//app")}async getOrgId(){let e=await this.sendRequest(`/${j}/auth/check`,{method:"GET",noLog:!0}),{orgId:t}=zi.parse(e);return t}async getRun(e){let t=await this.sendRequest(`/${j}/runs/${e}`,{method:"GET",noLog:!0});return Di.parse(t)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${j}/runs/status`,{method:"POST",body:e,noLog:!0});return Fi.parse(t)}async createRun(e){let t=await this.sendRequest(`/${j}/runs`,{method:"POST",body:e,noLog:!0});return ki.parse(t)}async updateRun(e,t){await this.sendRequest(`/${j}/runs/${e}`,{method:"PATCH",body:t,noLog:!0})}async getTest(e){let t=await this.sendRequest(`/${j}/tests/${e}`,{method:"GET"});return Oi.parse(t)}async getAllTestIds(){let e=await this.sendRequest(`/${j}/tests`,{method:"GET"});return Mi.parse(e)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${j}/tests/export`,{method:"POST",body:e});return Ni.parse(t)}async updateTestWithYAML(e){await this.sendRequest(`/${j}/tests/update`,{method:"POST",body:e})}async updateResolvedTest(e){await this.sendRequest(`/${j}/tests/${e.testId}`,{method:"PATCH",body:e})}async updateStepCaches(e){await this.sendRequest(`/${j}/cache`,{method:"PATCH",body:e})}async getStepCacheForTest(e){let t=await this.sendRequest(`/${j}/cache`,{method:"POST",body:e});return _i.parse(t)}async queueTests(e){let t=await this.sendRequest(`/${j}/tests/queue`,{method:"POST",body:e});return Pi.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${j}/screenshots`,{method:"POST",body:e,noLog:!0});return Ui.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${j}/environments`,{method:"GET"});return Bi.parse(e)}async getEnvironment(e){let t=await this.sendRequest(`/${j}/environments/${e}`,{method:"GET"});return Re.parse(t)}async updateEnvironments(e){await this.sendRequest(`/${j}/environments`,{method:"POST",body:e})}async getAllFeatureFlags(){let e=await this.sendRequest(`/${j}/auth/flags`,{method:"GET",noLog:!0});return $i.parse(e)}async acquireCacheLock(e){let t=await this.sendRequest(`/${j}/result-cache/entry`,{method:"POST",body:e});return ai.parse(t)}async releaseCacheLock(e){await this.sendRequest(`/${j}/result-cache/entry`,{method:"DELETE",body:{key:e}})}async setCacheResult(e){await this.sendRequest(`/${j}/result-cache/entry`,{method:"PATCH",body:e})}async getCacheResult(e){try{return await this.sendRequest(`/${j}/result-cache/entry`,{method:"POST",body:e})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${j}/suites/queue`,{method:"POST",body:e});return Hi.parse(t)}async bulkGetSuiteStatus(e){let t={suiteRunIds:e},n=await this.sendRequest(`/${j}/suites/status`,{method:"POST",body:t,noLog:!0});return Gi.array().parse(n)}async updateCacheLastUsedDate(e,t){try{await this.sendRequest(`/${j}/cache/lastUsedAt`,{method:"PATCH",body:e})}catch(n){t.error({err:n},"Failed to update cache last used date")}}};function or({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:s}=t,i=[],a=[],l=0,c=(d,m)=>{try{let h=vt.parse(m.value);if(h.type!==d.type){o.warn({parsedCacheEntry:h,command:d},"Not using step cache due to type mismatch"),a.push(m.key);return}d.cache=h.cache,i.push(m.key)}catch(h){a.push(m.key),o.error({err:h,cacheEntry:m},"Not using step cache due to parsing error")}},u=(d,m)=>{let h=Eu(d.id,m),p=h.find(g=>!!n[g]);p?c(d,n[p]):(a.push(h[0]),o.debug({command:d,possibleKeys:h},"Step cache miss"))};for(let d of r)switch(d.type){case"RESOLVED_MODULE":{l+=d.steps.length;let{hits:h,misses:p}=or({...t,steps:d.steps,keyPrefix:s?`${s}:${d.id}`:d.id,topLevel:!1});i=i.concat(h),a=a.concat(p);break}case"IFRAME":case"SECTION":case"AI_ACTION":{if(l+=d.steps?.length??0,!d.steps?.length)break;let{hits:h,misses:p}=or({...t,steps:d.steps,topLevel:!1});i=i.concat(h),a=a.concat(p);break}case"PRESET_ACTION":{if(!yo.includes(d.command.type)||d.command.type==="TYPE"&&!d.command.target||d.command.type==="MOUSE_DRAG"&&!d.command.target||"cache"in d.command&&d.command.cache)continue;l++,u(d.command,s);break}case"CONDITIONAL":{for(let h of d.blocks){l++,u(h.assertion.command,s),l+=h.steps.length;let{hits:p,misses:g}=or({...t,steps:h.steps,topLevel:!1});i=i.concat(p),a=a.concat(g);break}if(d.elseSteps){l+=d.elseSteps.length;let{hits:h,misses:p}=or({...t,steps:d.elseSteps,topLevel:!1});i=i.concat(h),a=a.concat(p)}break}default:return(h=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(d)}return e&&l&&a.length>0&&o.debug({totalSteps:l,cacheMisses:a,cacheHits:i,cacheEntries:n.length},"Step cache did not fully resolve"),{hits:i,misses:a}}function qi(r,e){return e?`${e}:${r}`:r}function Eu(r,e){let t=[],n=e?.split(":")??[];for(let o=n.length;o>=0;o--){let s=[...n.slice(o),r];t.push(s.join(":"))}return t}function Ki(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
|
|
7
|
-
${JSON.stringify(t)}`);let n=[];if(!r.skipIntermediateEntries)for(let o=e.length;o>0;o--){let s=t[o-1],i=e.slice(o,e.length).join(":");n.push({key:qi(r.id,i),moduleId:s,organizationId:r.orgId,value:r.value})}return n.push({key:qi(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function Yi(r){switch(r.type){case"DRAG":{if(r.fromTarget.type==="coordinates"||r.toTarget.type==="coordinates"||!r.fromTarget?.a11yData||!r.toTarget?.a11yData)return;r.cache={fromTarget:r.fromTarget.a11yData,toTarget:r.toTarget.a11yData},delete r.fromTarget.a11yData,delete r.toTarget.a11yData;return}case"MOUSE_DRAG":case"HOVER":case"SCROLL_UP":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SELECT_OPTION":case"TYPE":case"VISUAL_DIFF":case"CLICK":case"FOCUS":case"BLUR":{if(r.target?.type==="coordinates"||!r.target?.a11yData)return;r.cache={target:r.target.a11yData},delete r.target.a11yData;return}default:return}}function Xi(r,e){return r.length<e?r:r.slice(0,e-3)+"[...]"}var Nt={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with"},_t={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with"},Oo={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable"},Mo={EXISTS:"does not exists",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable"};function vu(r){switch(r.type){case"ELEMENT_CONTENT":return`${r.negated?_t[r.operation]:Nt[r.operation]} '${r.value}'`;case"ELEMENT_ATTRIBUTE":{let t=r.negated?_t[r.operation]:Nt[r.operation];return`attribute '${r.attr}' ${t} '${r.value}'`}case"ELEMENT_EXISTENCE":return r.negated?Mo[r.condition]:Oo[r.condition];default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var BC={CONTENT:"The page"};function Au(r){switch(r.type){case"CONTENT":return`${r.negated?_t.CONTAINS:Nt.CONTAINS} '${r.value}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function ft(r){switch(r.type){case"SUCCESS":return r.condition?.assertion?`Check success condition: ${r.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${r.goal}`;case"NAVIGATE":return`Go to URL: ${Xi(r.url,30)}`;case"DIALOG":return`Automatically ${r.action.toLowerCase()} the next dialog`;case"CAPTCHA":return"Solve captchas on the page";case"GO_BACK":return"Go back to the previous page";case"GO_FORWARD":return"Go forward to the next page";case"SCROLL_DOWN":return`Scroll down ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${ce(r.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${ce(r.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${ce(r.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${ce(r.target)}`:""}`;case"WAIT":return`Wait for ${r.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(r.target?.type==="coordinates")return`Click at coordinates: ${ce(r.target)}`;let o="";return r.target?.elementDescriptor.length?o=` on element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(o=` on element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Click${o}`}case"FOCUS":return`Focus ${ce(r.target)}`;case"BLUR":return`Focus ${ce(r.target)}`;case"DRAG":return`Drag ${ce(r.fromTarget)} onto ${ce(r.toTarget)}`;case"MOUSE_DRAG":return r.target?`Click and drag ${ce(r.target)} by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`:`Click and drag mouse by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`;case"TYPE":{let o="";return r.target?.type==="coordinates"?o=` in element at coordinates: ${ce(r.target)}`:r.target?.elementDescriptor.length?o=` in element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(o=` in element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Type '${r.value}'${o||""}`}case"HOVER":{let o="";return r.target.type==="coordinates"?o=` over coordinates: ${ce(r.target)}`:r.target.elementDescriptor.length>0?o=` over element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(o=` over element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Hover${o}`}case"PRESS":return`Press ${r.value}`;case"SELECT_OPTION":let e="";return r.target.type==="coordinates"?e=` from element at coordinates: ${ce(r.target)}`:r.target.elementDescriptor.length>0?e=` from: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(e=` from: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${r.option}'${e}`;case"TAB":return`Switch to tab with substring: ${r.url}`;case"NEW_TAB":return`Open new tab to: ${r.url}`;case"REQUEST":return`Send ${r.method} request to ${r.url}`;case"COOKIE":return`Set cookie: ${r.value}`;case"LOCAL_STORAGE":return`Set local storage: ${r.key}: ${r.value}`;case"JAVASCRIPT":return`Run JavaScript: ${Xi(r.code,30)}`;case"AI_ASSERTION":return`Assertion: '${r.assertion}'`;case"AI_WAIT":return`Wait until assertion is true: '${r.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${r.target?`for element: ${ce(r.target)}`:"for entire page"}`;case"FILE_UPLOAD":return`Upload file: ${r.fileSource.url}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Assert the element ${ce(r.target)} ${vu(r.assertion)}`;case"PAGE_CHECK":return`Assert the page ${Au(r.assertion)}`;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function tt(r){let{onPresetAction:e,onStepContainer:t,onConditional:n}=r;for(let o of r.steps)switch(o.type){case"PRESET_ACTION":e(o);break;case"CONDITIONAL":n?.(o);for(let i of o.blocks)e(i.assertion),tt({...r,steps:i.steps});tt({...r,steps:o.elseSteps??[]});break;case"RESOLVED_MODULE":case"IFRAME":case"SECTION":case"AI_ACTION":t?.(o),o.steps&&tt({...r,steps:o.steps});break;default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(o)}}function Cn(r){let e=0;tt({steps:r,onPresetAction:t=>{t.index=e++},onConditional:t=>{t.index=e++},onStepContainer:t=>{t.index=e++}})}function Ji(r){tt({steps:r,onPresetAction:e=>{delete e.index},onConditional:e=>{delete e.index},onStepContainer:e=>{delete e.index}})}var Ru=(r,e)=>{switch(r.type){case"RESOLVED_MODULE":return r.steps[e];case"AI_ACTION":return r.steps[e];case"CONDITIONAL":{let n=r.blocks.map(o=>[o.assertion,...o.steps]).flat();return r.elseSteps&&(n=n.concat(r.elseSteps)),n[e]}case"SECTION":case"IFRAME":return r.steps[e];case"PRESET_ACTION":default:throw new Error(`Cannot get a child step from step type ${r.type}`)}};function Tn(r,e){let t=r[e[0]];for(let n=1;n<e.length;n++)t=Ru(t,e[n]);return t}function En(r){let e=0;return tt({steps:r,onPresetAction:t=>{e=Math.max(e,t.index)},onConditional:t=>{e=Math.max(e,t.index)},onStepContainer:t=>{e=Math.max(e,t.index)}}),e}import{cloneDeep as YC,unset as XC}from"lodash-es";function Qi(r){switch(r.type){case"AI_ACTION":return`AI action: ${r.text}`;case"PRESET_ACTION":return ft(r.command);case"MODULE":return`Module: ${r.id}`;case"RESOLVED_MODULE":return`Module: ${r.name}`;case"CONDITIONAL":return"Conditional";case"IFRAME":return"Frame step";case"SECTION":return"Section"}}function Zi(r,e){if(!(!r.envs||!r.envs.length)){for(let t of r.envs)e in t&&(t[e]&&(t.default=!0),delete t.defaultOnCloud,delete t.defaultOnLocal);r.envs.some(t=>t.default)||(r.envs[0].default=!0)}}import Lu from"diff-lines";import An,{gte as Pu}from"semver";var ea={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>(r=r.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),r=r.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),r)};var ta={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,n=t[t.length-1];return n&&n.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var xu=["target","fromTarget","toTarget"];function ra(r){for(let e of xu){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var na={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":return ra(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])ra(n);return e}default:return e}})};import{v4 as Iu}from"uuid";var oa={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=Iu()),e;default:return e}})};import{v4 as sa}from"uuid";var ia={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??sa(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??sa()}})),delete e.commands),e;default:return e}})};var aa={name:"Migrate AI assertions to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async r=>r.map(e=>{if(e.type!=="AI_ASSERTION")return e;let n={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...n};return delete o.text,o}),stopOnFailure:!0};var vn=new Set(["CLICK","TYPE","SELECT_OPTION"]),la={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type,o=t?.elementDescriptor;return(o!==void 0||vn.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let a=i?.elementDescriptor,l=i?.type;(a!==void 0||vn.has(l))&&(i.target={elementDescriptor:a??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let a=i.command,l=a?.elementDescriptor,c=a?.type;(l!==void 0||vn.has(c))&&(a.target={elementDescriptor:l??""}),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(d=>{let m=d?.elementDescriptor,h=d?.type;(m!==void 0||vn.has(h))&&(d.target={elementDescriptor:m??""})})}),e}),stopOnFailure:!0};var ca={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(n=>{if(n&&typeof n=="object"){let o=n;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var da={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type;return n?.startsWith("PRESET_")&&(t.type=n.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(s=>{let i=s.type;i?.startsWith("PRESET_")&&(s.type=i.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(s=>{let i=s.command,a=i?.type;a?.startsWith("PRESET_")&&(i.type=a.slice(7)),s.commands&&Array.isArray(s.commands)&&s.commands.forEach(c=>{let u=c.type;u?.startsWith("PRESET_")&&(c.type=u.slice(7))})}),e}),stopOnFailure:!0};var kt=[aa,ca,da,la,ea,ta,na,oa,ia];if(Ce!==kt[kt.length-1].toVersion)throw new Error("Please bump LATEST_VERSION in types package after adding a migration");kt.forEach((r,e)=>{if(!An.valid(r.toVersion)||!An.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!An.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(kt[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});function Ou(r){return r.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var No=async({metadata:r,steps:e,logger:t,toVersion:n})=>{let o=e,{schemaVersion:s,id:i}=r,a=kt.findIndex(u=>An.gt(u.toVersion,s));if(a===-1)return{steps:o,newVersion:s};let l=s;for(let u=a;u<kt.length;u++){if(n&&Pu(l,n)){t.debug("Stopping migration early because toVersion was reached");break}let d=kt[u],m={id:i,migration:d.name,toVersion:d.toVersion};try{o=await ua(o,d),l=d.toVersion}catch(h){throw t.error({err:h,...m},"Migration failed"),new Error(`Step migration ${d.name} failed: ${h}`)}}let c=Lu(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return c.trim()&&t.debug({diffs:c,id:i},"Migration diffs"),{newVersion:l,steps:o}};async function ua(r,e){let t=await e.execute(r);for(let n of t)for(let o of Object.keys(n)){if(!e.recursiveKeys.has(o))continue;let s=n[o];!s||!Array.isArray(s)||Ou(s)&&(n[o]=await ua(s,e))}return t}async function ma({rawSteps:r,metadata:e,logger:t,callbacks:n}){Zi(e,"defaultOnCloud");let o={},{resolvedSteps:s,newSchemaVersion:i}=await _o({rawSteps:r,metadata:e,logger:t,callbacks:n,resolvedModuleCache:o});return{resolvedTest:{...e,steps:s,schemaVersion:i},moduleIds:Array.from(Object.keys(o))}}async function _o({rawSteps:r,metadata:e,logger:t,callbacks:n,resolvedModuleCache:o={}}){let{newVersion:s,steps:i}=await No({metadata:e,steps:r,logger:t}),a;try{a=Me.array().parse(i)}catch(c){throw t.error({type:"zod",err:c,newVersion:s,id:e.id,steps:i},"Failed to parse test steps while migrating test"),new an(`Failed to parse test steps while migrating test: ${c}`,e.id,"entity",{cause:c})}let l=[];for(let c of a)l.push(await Ir({step:c,callbacks:n,logger:t,resolvedModuleCache:o}));return{resolvedSteps:l,newSchemaVersion:s}}async function Ir({step:r,callbacks:e,logger:t,resolvedModuleCache:n}){switch(r.type){case"AI_ACTION":return r;case"PRESET_ACTION":return r;case"MODULE":{let l=r.moduleId,c=n[l];if(c)return{...c,...r,type:"RESOLVED_MODULE"};let u=await e.onFetchModule({id:l,logger:t});if(!u)throw new Error(`Could not find module with id ${l}`);let{newVersion:d,steps:m}=await No({metadata:{id:l,schemaVersion:u.schemaVersion},steps:u.steps,logger:t}),h;try{h=Me.array().parse(m)}catch(f){throw t.error({type:"zod",err:f,steps:m,newVersion:d,id:l},"Module failed to parse"),f}let p;try{p=await Promise.all(h.map(f=>Ir({step:f,callbacks:e,logger:t,resolvedModuleCache:n})))}catch(f){throw t.error({err:f,...r},`Failed to recursively resolve module '${u.name}': ${f}`),f}let g={...u,steps:p};return n[l]=g,{...g,...r,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let l of r.blocks){let c=[];for(let u of l.steps)c.push(await Ir({step:u,callbacks:e,logger:t,resolvedModuleCache:n}));o.push({...l,steps:c})}let s;if(r.elseSteps){s=[];for(let l of r.elseSteps)s.push(await Ir({step:l,callbacks:e,logger:t,resolvedModuleCache:n}))}return{...r,blocks:o,elseSteps:s};case"SECTION":case"IFRAME":let i=[];for(let l of r.steps)i.push(await Ir({step:l,callbacks:e,logger:t,resolvedModuleCache:n}));return{...r,steps:i};default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}import{cloneDeep as Mu}from"lodash-es";import{v4 as pa}from"uuid";async function He(r){let e=Mu(r.steps);return sr({...r,steps:e,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:new Map,seenModules:new Set})}async function sr({steps:r,...e}){let{seenModules:t,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:s,moduleIdReplacements:i,shouldCreateNewModuleId:a}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let c of r)switch(delete c.index,c.type){case"PRESET_ACTION":{let d=c.command;d.id=n?.createNewCacheIds?pa():d.id,Yi(d),"cache"in d&&d.cache&&(n&&(l.cachesToSave=l.cachesToSave.concat(Ki({id:d.id,orgId:n.orgId,testId:n.testId,value:vt.parse(d),moduleIdParents:o,moduleStepParents:s,skipIntermediateEntries:e.skipCacheIntermediateEntries}))),delete d.cache),l.stepsToSave.push({...c,command:d});break}case"RESOLVED_MODULE":{let d=n?.createNewCacheIds?pa():c.id,m=c.moduleId;if(i.has(m))m=i.get(m);else if(a){let S=await a(c);i.set(c.moduleId,S)}let{cachesToSave:h,stepsToSave:p,moduleUpdates:g}=await sr({...e,steps:c.steps,cacheCreationParams:n?{...n,createNewCacheIds:!1}:void 0,moduleStepParents:[...s,d],moduleIdParents:[...o,m],skipCacheIntermediateEntries:n?.createNewCacheIds});l.moduleUpdates=l.moduleUpdates.concat(g),l.cachesToSave=l.cachesToSave.concat(h),t.has(m)||(t.add(m),l.moduleUpdates.push({...De.parse(c),steps:Me.array().parse(p)}));let f={type:"MODULE",moduleId:m,inputs:c.inputs,id:d,skipped:c.skipped,cacheConfig:c.cacheConfig};l.stepsToSave.push(f);break}case"AI_ACTION":{if(!c.steps){l.stepsToSave.push(c);break}let{stepsToSave:d,cachesToSave:m}=await sr({...e,steps:c.steps});try{c.steps=Pe.array().parse(d)}catch(h){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${h}`)}l.stepsToSave.push(c),l.cachesToSave=l.cachesToSave.concat(m);break}case"CONDITIONAL":{let d=[];for(let h of c.blocks){let{stepsToSave:p,cachesToSave:g,moduleUpdates:f}=await sr({...e,steps:h.steps});d.push({...h,steps:p}),l.cachesToSave=l.cachesToSave.concat(g),l.moduleUpdates=l.moduleUpdates.concat(f)}let m={...c,elseSteps:void 0,blocks:d};if(c.elseSteps){let{stepsToSave:h,cachesToSave:p,moduleUpdates:g}=await sr({...e,steps:c.elseSteps});m.elseSteps=h,l.cachesToSave=l.cachesToSave.concat(p),l.moduleUpdates=l.moduleUpdates.concat(g)}l.stepsToSave.push(m);break}case"IFRAME":case"SECTION":{let{stepsToSave:d,cachesToSave:m,moduleUpdates:h}=await sr({...e,steps:c.steps}),p={...c,steps:d};l.moduleUpdates=l.moduleUpdates.concat(h),l.stepsToSave.push(p),l.cachesToSave=l.cachesToSave.concat(m);break}default:return(d=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(c)}return l}import{cloneDeep as Nu}from"lodash-es";import{stringify as ko}from"yaml";async function ga(r,e=new Set){let t={id:r.id,name:r.name,baseUrl:r.baseUrl,schemaVersion:r.schemaVersion,advanced:r.advanced,retries:r.retries,envs:r.envs},n={},o=await _u(r.steps,r.schemaVersion,n,e),s={fileType:"momentic/test",...t,steps:o};return{test:ko(s),modules:n}}async function _u(r,e,t,n){let o=Nu(r);ku(o);let{stepsToSave:s,moduleUpdates:i}=await He({steps:o});for(let a of i)n.has(a.name)||(t[a.name]=Du(a),n.add(a.name));return s}function ku(r){tt({steps:r,onPresetAction:e=>{e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.index=void 0},onStepContainer:e=>{e.index=void 0}})}function Du(r){let e=De.parse(r),t={fileType:"momentic/module",...e,schemaVersion:Ce,steps:r.steps};return ko(t)}function Do(r){return ko({fileType:"momentic/environment",...r})}var ir=class{constructor(e,t){this.client=e;this.orgId=t}inMemoryCache={};async acquireCacheLock(e){return this.client.acquireCacheLock(e)}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}async saveStepCacheEntries(e,t,n){try{await this.client.updateStepCaches({entries:e,testId:t})}catch(o){n.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let t=await this.client.getStepCacheForTest({testId:e.testId,organizationId:e.organizationId,steps:e.steps,schemaVersion:e.schemaVersion}),{hits:n}=or({steps:e.steps,stepCacheEntries:t,logger:e.logger});this.client.updateCacheLastUsedDate(n,e.logger)}async getOrgId(e){return this.orgId}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async fetchEnvironment(e,t,n){try{return await this.client.getEnvironment(t)}catch(o){n.warn({err:o},"Error fetching environment, continuing...");return}}};var Fo="v1",rt=class extends nr{type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this)};email={fetchLatest:this.fetchLatestEmail.bind(this)};constructor(e){super(e)}async sendSms(e){await this.sendRequest(`/${Fo}/tools/sms/send`,{method:"POST",body:e})}async fetchLatestSms(e){try{return await this.sendRequest(`/${Fo}/tools/sms/fetchLatest`,{method:"POST",body:e})}catch(t){throw t instanceof rr&&t.status===404?new Error("No recent SMS messages found."):t}}async fetchLatestEmail(e){try{return this.sendRequest(`/${Fo}/tools/email/fetchLatest`,{method:"POST",body:e})}catch(t){throw t instanceof rr&&t.status===404?new Error("No matching emails found."):new Error(`Failed to fetch latest emails: ${t.message}`)}}};import{Command as vh,Option as Ve}from"commander";import bg from"body-parser";import Cg from"cors";import ps from"express";import{existsSync as zu,readFileSync as In,readdirSync as Bu,statSync as $u,writeFileSync as Bo}from"fs";import St from"path";import{parse as Pr,stringify as Hu}from"yaml";var te=process.env.MOMENTIC_DIR??pt;import{readFileSync as Lr,readdirSync as Uo,writeFileSync as fa}from"fs";import Fu,{join as zo}from"path";import{v4 as Uu}from"uuid";import{parse as Rn,stringify as ya}from"yaml";var yt=zo(te,gt);function Sa(r){let e=xn(yt,r.moduleId).path,t=Lr(e,"utf-8"),n=Rn(t),o={fileType:"momentic/module",...n,...r},s=ya(o);fa(e,s,"utf-8")}async function wa(r,e){let t=pe(r),n=zo(yt,`${t}.yaml`),o=Uu(),{stepsToSave:s}=await He({steps:e}),i={fileType:"momentic/module",schemaVersion:Ce,moduleId:o,name:r,steps:s},a=ya(i);return fa(n,a,"utf-8"),{moduleId:o,name:r,steps:e}}function ba(){let r=[];for(let e in Uo(yt)){if(!e.endsWith(".yaml"))continue;let t=Lr(e,"utf-8"),n=Rn(t),o={name:n.name,moduleId:n.moduleId,numSteps:n.steps.length};r.push(o)}return r}async function Ca(r){let e=new Set;for(let t of Uo(yt)){if(!t.endsWith(".yaml"))continue;let n=zo(yt,t),o=Lr(n,"utf-8"),s=Rn(o),i;try{i=Er.parse(s)}catch(a){r.warn({err:a,filePath:t,moduleContents:o},`${t} does not parse as a valid module, skipping...`);continue}e.add(i.moduleId)}return Ea(Array.from(e),r)}function ha(r,e){let t=xn(yt,r).path,n=Lr(t,"utf-8"),o=Rn(n);try{return Er.parse(o)}catch(s){throw e.error({err:s,moduleFilePath:t,moduleContents:n},`${t} does not parse as a valid module`),s}}async function Ta(r,e){return(await Ea([r],e)).find(n=>n.moduleId===r)}async function Ea(r,e){let t={};return await Promise.all(r.map(async n=>{let o=ha(n,e),{resolvedSteps:s}=await _o({rawSteps:o.steps,metadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:t,logger:e,callbacks:{onFetchModule:async i=>ha(i.id,e)}});t[n]={...o,steps:s}})),Array.from(Object.values(t))}function xn(r,e){let t=Uo(r);for(let n of t){let o=Fu.join(r,n),s=Lr(o,"utf8");if(s.includes(e))return{path:o,content:s}}throw new Error(`Could not find module file for module ${e} in ${r}`)}var va=fn,Wu=new Set([...va,"node_modules","dist","bin",".git","logs",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"]);async function Aa(r,e){let t=await ga(r);for(let[s,i]of Object.entries(t.modules)){let a=pe(s);Bo(St.join(te,gt,`${a}.yaml`),i,"utf-8")}let n=pe(e),o=St.join(te,`${n}.yaml`);return Bo(o,t.test,"utf-8"),`${n}.yaml`}function Ln(r,e){if(!zu(e))throw new Error(`Test not found at path: ${St}`);let t=In(e,"utf-8"),o={...Pr(t),...r},s=me.parse(o),i={fileType:"momentic/test",...s,steps:o.steps},a=Hu(i);Bo(e,a,"utf-8")}function Or(r,e,t=r){let n=r.split(St.sep).pop()??"";if(Wu.has(n))return va.includes(n)||e.warn(`Skipping directory '${r}' because it is likely an artifact folder.`),[];let o=Bu(r),s=[];return o.forEach(i=>{let a=St.join(r,i),l;try{l=$u(a)}catch(c){e.warn({err:c},`Skipping path '${a}' because it could not be read.`);return}if(l.isDirectory())s=s.concat(Or(a,e,r));else if(i.endsWith(".yaml")){let c=In(a,"utf-8");try{let u=Pr(c),d=me.parse(u);s.push({id:d.id,name:d.name,fullFilePath:a,testPath:St.relative(St.resolve(t),St.resolve(a)),fileName:i,lastModified:l.mtime,createdAt:l.ctime})}catch{e.warn(`Skipping file '${a}' because it does not parse as a valid Momentic test.`)}}}),s}function Ra(r){let e;try{e=In(r,"utf8"),e=e.replace(/\r\n|\r/g,`
|
|
8
|
-
`)}catch(n){throw new Error(`Could not read test file ${r}: ${n}`)}let t;try{t=
|
|
9
|
-
`)}catch(a){throw new Error(`Could not read test file ${r}: ${a}`)}let n=new Set,o=/moduleId: (.*)/g,s;for(;(s=o.exec(t))!==null;)n.add(s[1].trim());let i={};return n.size>0&&n.forEach(a=>{i[a]||(i[a]=xn(e,a).content)}),{test:t,modules:i}}async function Pn(r,e,t){let{test:n,modules:o}=$o(r,e),s=Pr(n);if(!s.steps||!Array.isArray(s.steps))throw new Error(`Test ${r} is missing steps`);let i;try{i=me.parse(s)}catch(c){throw new Error(`Test ${r} is missing metadata or has invalid metadata: ${c}`)}let a={};for(let[c,u]of Object.entries(o)){let d;try{d=Pr(u)}catch(m){throw new Error(`Module ${c} is not valid YAML: ${m}`)}try{let m=Er.parse(d);a[c]=m}catch(m){throw new Error(`Module ${c} is missing metadata or has invalid metadata: ${m}`)}}let{resolvedTest:l}=await ma({rawSteps:s.steps,metadata:i,logger:t,callbacks:{onFetchModule:async({id:c})=>a[c]}});return l}import{existsSync as Gu,readFileSync as ju,readdirSync as Vu}from"fs";import{join as xa}from"path";import{parse as qu}from"yaml";var Ho=xa(te,er);function Ia(){let r=[];if(!Gu(Ho))return[];for(let e of Vu(Ho)){if(!e.endsWith(".yaml"))continue;let t=xa(Ho,e),n=ju(t,"utf-8"),o=qu(n);try{let s=Re.parse(o);r.push(s)}catch(s){Ei.warn({err:s},"Error parsing environment, skipping...")}}return r}import{existsSync as Tg,statSync as Eg}from"fs";import vg from"http";import Ag from"open";import Rg from"path";import{Server as ig}from"socket.io";import{cloneDeep as Ku}from"lodash-es";var Wo=r=>{let e=[];for(let t of r){let n;switch(t.type){case"PRESET_ACTION":{n={before:t.beforeTestContext,after:t.afterTestContext};break}case"CONDITIONAL":case"IFRAME":case"SECTION":case"AI_ACTION":case"MODULE":{n={before:t.beforeTestContext,after:t.afterTestContext,nestedResults:Wo(t.results)};break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}e.push(n)}return e},Mr=class{results;constructor(){this.results=[]}setResults(e){this.results=Wo(e)}setIndividualResult(e,t){let n=Wo([e])[0],o=this.results;for(let i=0;i<t.length-1;i++){let a=t[i];o[a]===void 0&&(o[a]={nestedResults:[]});let l=o[a];l.nestedResults===void 0&&(l.nestedResults=[]),o=l.nestedResults}let s=t[t.length-1];o[s]=n}getContextCopyAtIndices(e){let t=this.getContextAtIndicesHelper(e);if(t!==void 0)return Ku(t)}getContextAtIndicesHelper(e){let t=this.results;for(let o=0;o<e.length-1;o++){let s=e[o],i=t[s];if(i===void 0)return t.length>0?t[t.length-1].after:void 0;if(i.nestedResults===void 0)return i.before;t=i.nestedResults}let n=e[e.length-1];if(n>t.length&&(n=t.length),n===0)return t[0]?.before;for(let o=n-1;o>=0;o--)if(t[o]?.after)return t[o].after}};var La={showOverlay:!1},Go=class{sessions=new Map;sessionCountByIp=new Map;getCurrentConnectionsByIp(e){return this.sessionCountByIp.get(e)??0}getCurrentSessionsByIp(){return Object.fromEntries(this.sessionCountByIp)}reserveCapacityByIp(e){e&&this.sessionCountByIp.set(e,(this.sessionCountByIp.get(e)??0)+1)}releaseCapacityByIp(e){e&&this.sessionCountByIp.set(e,Math.max(this.getCurrentConnectionsByIp(e)-1,0))}registerSession({controller:e,context:t,cleanup:n,clientIp:o,sessionId:s,browserbaseSessionId:i}){return this.sessions.set(s,{controller:e,context:t,cleanup:n,clientIp:o,executionCancelled:!1,resultsManager:new Mr,browserbaseSessionId:i,browserBehavior:La}),s}removeSession(e,t){(async()=>{try{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:s}=o;await s.browser.cleanup(),await o.cleanup?.(),this.sessions.delete(e)}catch(o){t.error({err:o},"Error cleaning up session in global state manager")}})()}getSession(e){return this.sessions.get(e)}cancelExecution(e){let t=this.sessions.get(e);t&&(t.executionCancelled=!0)}resumeExecution(e){let t=this.sessions.get(e);t&&(t.executionCancelled=!1)}},N=new Go;var Yu=200;function Pa(r,e,t){let n=Date.now(),o=-1,s=0,i=Date.now(),a,l,c=async m=>{if(!m.closed){if(s>0&&Math.random()>=1/Math.max(s,8)){s<8&&t.error({sessionId:e},"Dropping screenshot due to previous failures");return}try{(!a||!l||Date.now()-i>=1e3)&&(a=await m.getViewport(),l=await m.getFrameSrcUrls(),i=Date.now()),r.emit("browserState",{viewport:a,buffer:await m.screenshot({retries:0,timeout:1e3,scale:"device",quality:75}),url:m.url(),iframeSrcUrls:l}),n=Date.now(),s=0}catch(h){if(!r.connected)return;let p=h instanceof Error?h.message:`${h}`;if(p.includes("Frame was detached")||p.includes("Not attached to an active page")||p.includes("browser has been closed"))return;s++,t.error({err:h,sessionId:e},"Error taking screenshot")}finally{r.connected&&Date.now()-n>15e3&&Date.now()-o>3e4&&(t.error({sessionId:e},"Screenshots to client are stale"),o=Date.now())}}},u={timer:void 0},d=()=>{let h=N.getSession(e)?.controller?.browser;if(!h||h.closed){t.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(u.timer);return}c(h)};return u.timer=setInterval(d,Yu),u}var Xu=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async()=>{if(e.info({sessionId:t},"Cancel event received"),!N.getSession(t))throw new Error("No active session found");N.cancelExecution(t)}},Oa={event:"cancel",createHandler:Xu};var Ju=({metadata:r,logger:e})=>{let{sessionId:t}=r;return n=>{e.info({sessionId:t,reason:n},`Disconnect event received (${n})`),N.removeSession(t,e)}},Ma={event:"disconnect",createHandler:Ju};import{diff as Tm}from"deep-object-diff";import{spawn as Qu}from"child_process";async function Na(r){return new Promise((e,t)=>{let n={stdio:"inherit",env:process.env,detached:!0},o=Qu("bash",["-c",r],n),s=!1;process.on("exit",()=>o.pid!==void 0&&!s&&process.kill(-o.pid)),o.on("close",i=>{if(s=!0,i===0){e();return}t(`command exited with code ${i}`)})})}async function Nr(r,e,t,n,o){try{let[s,i]=await Promise.all([e?n(e):void 0,t?n(t):void 0]);r.beforeScreenshot=s,r.afterScreenshot=i}catch(s){o.debug({err:s},"Error saving screenshot to S3")}}var _a=async r=>{let e=r.step,{logger:t,controller:n,context:o}=r.fixtures,{takeScreenshots:s}=r.options,{testMetadata:i}=r.inputs,a=r.callbacks.test,l=n.browser.url(),c=new Date,u;if(s)try{u=await n.browser.screenshot({retries:1,clearHighlights:!0})}catch(g){t.debug({err:g},"Failed to take screenshot before step, likely because the page is still loading. This is non-fatal and does not affect the test.")}let d,m,h,p=bn();try{let g=await n.executePresetStep(p,e.command,o,i.advanced.disableAICaching,r.callbacks.test.isExecutionCancelled);if(g.beforeScreenshotOverride&&(u=g.beforeScreenshotOverride),h=g.afterScreenshotOverride,g.fail)throw new A("ActionFailureError",g.thoughts||"Preset action failed.");let f=new Date,S=n.browser.url();m={beforeUrl:l,afterUrl:S,startedAt:c,finishedAt:f,viewport:await n.browser.getViewport(),status:"SUCCESS"},d={...e,message:g.thoughts??"Successfully executed preset action.",finishedAt:f,startedAt:c,status:"SUCCESS",data:g.data,results:[m],details:p.details},"assertion"in e.command&&(d.message=g.thoughts||"Assertion passed."),(e.command.type==="AI_EXTRACT"||e.command.type==="JAVASCRIPT")&&e.command.envKey&&o.setVariable(e.command.envKey,d.data)}catch(g){t.error({err:g},`Failed executing preset step ${ft(e.command)}`);let f=new Date,S=g instanceof Error?g.message:`${g}`;m={beforeUrl:l,afterUrl:n.browser.url(),startedAt:c,finishedAt:f,viewport:await n.browser.getViewport(),status:g instanceof Ye?"CANCELLED":"FAILED",message:S},d={...e,startedAt:c,finishedAt:f,status:g instanceof Ye?"CANCELLED":"FAILED",message:S,failureReason:g instanceof A?g.reason:void 0,results:[m],details:p.details}}if(s&&!h)try{h=await n.browser.screenshot({retries:1})}catch(g){t.debug({err:g},"Failed to take screenshot after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return Nr(m,u,h,a.onSaveScreenshot,t),d};import jo from"os";function ka(r){let e=()=>{try{let t=Zu(),n=em();r.debug({memory:t,cpu:n},"Got machine cpu usage metrics")}catch{}};return e(),setInterval(e,3e4)}function Zu(){let r=jo.totalmem(),e=jo.freemem(),t=r-e;return{totalMemory:r,freeMemory:e,usedMemory:t}}function em(){let r=jo.cpus(),e=0,t=0,n=0,o=0,s=0,i=0;for(let a of r)e+=a.times.user,t+=a.times.nice,n+=a.times.sys,o+=a.times.idle,s+=a.times.irq;return i=e+t+n+o+s,{user:e/i*100,nice:t/i*100,sys:n/i*100,idle:o/i*100,irq:s/i*100,total:100-o/i*100}}import{randomUUID as cm}from"crypto";import{faker as tm}from"@faker-js/faker";import rm from"assert";import nm from"axios";import om from"moment";import sm,{TimeoutError as im}from"p-timeout";import am from"pg";var lm=Object.getPrototypeOf(async function(){}).constructor;async function Da(r,e,t){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{results:o,env:s,inputs:i}=e.bindings,a=e.tools,l={},c=(f,S)=>{s[f]=S,l[f]=S},u;n.includes("Octokit")&&(u=(await import("@octokit/rest")).Octokit);let d;n.includes("createAppAuth")&&(d=(await import("@octokit/auth-app")).createAppAuth);let m=async()=>await Promise.resolve(new lm("axios","moment","faker","assert","pg","Octokit","createAppAuth","env","results","inputs","setVariable","sendSms","waitForLatestSms","email","sms",n)(nm,om,tm,rm,am,u,d,s,o,i??{},c,S=>a.sms.send(S),S=>a.sms.fetchLatest(S),a.email,a.sms)),h=!0,p,g;try{p=await sm(m(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`}),t.debug(`[${r}] Got execution result: ${JSON.stringify(p)}`),t.debug(`[${r}] Got variable updates: ${JSON.stringify(l)}`)}catch(f){t.error(`[${r}] Error executing code: ${f}`),h=!1,f instanceof im?g=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:g=f instanceof Error?f.message:`${f}`}return{result:p,variableUpdates:l,success:h,error:g}}async function Fa({code:r,fragment:e,context:t,localTools:n,logger:o,timeoutMs:s=Zs}){let i=cm();return Da(i,{code:r,options:{fragment:e,timeoutMs:s},bindings:t.toObjectCopy(),tools:n},o)}var Yv=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT;var Qv=process.env.MAILINATOR_API_KEY;import tA from"p-timeout";import"twilio";var wA=!!(process.env.MAILINATOR_API_KEY&&!1);async function ar(r){let e;if(r.localTools)e=await Fa({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error)throw new Error(`Code evaluation returned error: ${e.error}`);if(e.variableUpdates)for(let[t,n]of Object.entries(e.variableUpdates))r.context.setVariable(t,n);return e.result}async function _r(r){let{s:e,context:t,logger:n,timeoutMs:o=5e3,retries:s=1}=r,i=/{{(.*?)}}/g,a=e.matchAll(i),l=e;for(let c of a){if(c.length<2)continue;let u=c[1].trim(),d;try{d=await ar({code:u,fragment:!0,context:t,timeoutMs:o,logger:n,retries:s,localTools:r.localTools})}catch(h){throw n.error({err:h,value:e},"Error evaluating template string"),h}let m=typeof d=="string"?d:`${d}`;l=l.replace(c[0],m)}return l}import{last as um}from"lodash-es";var Ua=async r=>{let{step:e,resolvedInputs:t}=r.moduleParams,{logger:n,context:o,storage:s,codeEvalTools:i}=r.fixtures,{orgId:a,testMetadata:l}=r.inputs;Object.keys(t).length>0&&(o.setInputs(t),n.debug({inputs:t,moduleId:e.moduleId},"Set module inputs"));let c,u;if(e.cacheConfig){let d=await _r({s:e.cacheConfig.cacheKey||e.defaultCacheKey||"",context:o,logger:n,localTools:i}),m={orgId:a,cacheKeys:[d,...Object.entries(t).map(([p,g])=>`${p}:${g}`)]},h=Date.now();for(;Date.now()-h<vi;){let p=await s.getCacheResult(m);if(p){n.info({cacheResult:p},"Got result from module execution cache"),c=On(e,"SUCCESS"),c.message="Used cached module result.",c.data=JSON.parse(p);break}let g=await s.acquireCacheLock({keyParams:m,clientMetadata:`testId:${l.id}`});if(g.acquired){n.info({cacheKeyPrefix:u},"Acquired cache lock and proceeding with module execution"),u=g.keyPrefix;break}await new Promise(f=>setTimeout(f,2500+Math.random()*1e4))}}try{c||(c=await mm(r))}finally{if(u!==void 0){let d=e.cacheConfig.cacheExpiryMs;d===li&&(d=e.defaultCacheTtl??ci),c&&c.status==="SUCCESS"&&await s.setCacheResult({result:JSON.stringify(c.data===void 0?"":c.data),keyPrefix:u,ttlMs:d}),await s.releaseCacheLock(u)}}return c},mm=async r=>{let{step:e}=r.moduleParams,t=On(e,"SUCCESS"),{status:n,results:o}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:`module ('${e.name}')`}});return t.results=o,t.status=n,t.finishedAt=new Date,t.data=um(t.results)?.data,t};function On(r,e){return{type:"MODULE",id:r.id,moduleId:r.moduleId,moduleName:r.name,startedAt:new Date,inputs:r.inputs,cacheConfig:r.cacheConfig,results:[],finishedAt:new Date,status:e}}async function za(r,e,t,n){let o={};try{for(let s of r.parameters??[]){let i=r.inputs?.[s]??r.defaultParameters?.[s];if(!i){t.warn(`No value or default found for parameter '${s}' that is required by module '${r.name}'`);continue}o[s]=await ar({code:i,fragment:!0,context:e,logger:t,localTools:n})}return o}catch(s){throw new A("UserConfigurationError",`Failed to evaluate module inputs: ${s}`)}}async function Dt(r,e){let t=new Date;try{return await e()}catch(n){let o=new Date,s;if(n instanceof A?s=`${n}`:s=`An unexpected error occurred: ${n.message}`,r.type==="RESOLVED_MODULE"){let i=On(r,"FAILED");return i.message=s,i.startedAt=t,i.finishedAt=o,i}return{...r,startedAt:t,finishedAt:o,status:"FAILED",data:null,message:s,results:[]}}}import{randomUUID as $a}from"crypto";var Ha=async r=>{let e=r.aiStepParams.step,t=e.index,{testMetadata:n,steps:o}=r.inputs,{takeScreenshots:s}=r.options,{controller:i,context:a,logger:l}=r.fixtures,{test:c,step:u}=r.callbacks;if(t===void 0)throw new Error("Attempted to execute AI action step without index");i.resetHistory();let d={...e,startedAt:new Date,finishedAt:new Date,results:[],status:"RUNNING",beforeTestContext:a.toRedactedDisplayCopy()};e.steps=e.steps||[];let m=e.steps&&e.steps.length>0&&e.steps[e.steps.length-1]?.command.type==="SUCCESS";if(m)try{let{status:p,results:g}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"AI action"}});return d.finishedAt=new Date,d.status=p,d.results=g,d}catch(p){l.warn({err:p},"Failed executing saved AI action steps, attempting to re-generate...")}e.steps=[];let h=0;try{for(;;){if(h>12)throw new Error(`Exceeded max number of commands per step (${12})`);let p=t+h+1;if(c.isExecutionCancelled?.())return d.status="CANCELLED",d.finishedAt=new Date,u.onCancelled?.({index:p,message:d.message||"AI step cancelled.",output:d}),d;let g,f=new Date,S=a.toRedactedDisplayCopy(),w;if(s)try{w=await i.browser.screenshot({clearHighlights:!0})}catch(C){l.debug({err:C},"Failed to take screenshot before AI command, likely because the page is still loading. This is non-fatal.")}l.info(`Generating new sub-command ${h} within AI step`);let b;try{if(b=await i.promptToCommand(e.type,e.text,n.advanced.disableAICaching),b.command.type==="FAILURE")throw new Error(b.command.thoughts);g=b.command,l.debug({command:g},"Generated new command")}catch(C){if(l.error({err:C,commandIndex:h},"Failed to generate command within AI step"),h===0)throw C;{let R="Stopping command generation prematurely since no progress can be made";l.info({command:g},R),g={id:$a(),type:"SUCCESS",thoughts:R}}}let E={type:"PRESET_ACTION",index:p,command:g};gm({newStep:E,controller:i,currentStep:e,pageContext:b?.context,logger:l,onCommandExecuted:u.onCommandExecuted,currentIndex:h,globalSubStepIndex:p}),u.onCommandGenerated?.({index:p,step:E,message:Ao[g.type]||`Unknown command (${g.type})`});let v={beforeUrl:i.browser.url(),startedAt:f,viewport:await i.browser.getViewport(),finishedAt:new Date,status:"SUCCESS"};l.info(`Executing sub-command ${h} within AI step: ${ft(g)}`);try{let C=await i.executeCommand(g,a,m&&n.advanced.disableAICaching,m);l.info(`AI sub-command ${h} completed successfully`),v.elementInteracted=C.elementInteracted;let R;if(s)try{R=await i.browser.screenshot({})}catch(L){l.debug({err:L},"Failed to take screenshot after AI command, likely because the page is still loading. This is non-fatal.")}v.afterUrl=i.browser.url(),v.finishedAt=new Date,Nr(v,w,R,c.onSaveScreenshot,l);let x={status:"SUCCESS",startedAt:v.startedAt,finishedAt:v.finishedAt,data:C.data,results:[v],beforeTestContext:S,afterTestContext:a.toRedactedDisplayCopy(),...E};if(d.results.push(x),e.steps[h]=E,hm(o,r.inputs,p),u.onCommandExecuted?.({index:p,output:{...x,message:g.thoughts??C.thoughts??"Successfully executed preset action."},step:E}),g.type==="SUCCESS"){d.finishedAt=new Date,d.status="SUCCESS",d.message=C.thoughts??"All commands completed.",d.afterTestContext=a.toRedactedDisplayCopy();break}if(C.succeedImmediately&&!m){d.finishedAt=new Date,d.status="SUCCESS",d.message=`Marked step as completed due to reason: ${C.succeedImmediatelyReason}`,d.afterTestContext=a.toRedactedDisplayCopy(),g={id:$a(),type:"SUCCESS",thoughts:C.succeedImmediatelyReason};let L={type:"PRESET_ACTION",command:g};e.steps.push(L),u.onCommandExecuted?.({index:p+1,output:{...x,message:d.message},step:L}),d.results.push({...x,...L});break}}catch(C){let R=C instanceof Error?C.message:`${C}`,x=C instanceof A?C.reason:void 0;v.status="FAILED",v.message=R,v.finishedAt=new Date,v.afterUrl=i.browser.url();let L;try{L=await i.browser.screenshot({})}catch(Be){l.debug({err:Be},"Failed to take screenshot after AI command error, likely because the page is still loading. This is non-fatal.")}Nr(v,w,L,c.onSaveScreenshot,l);let q={status:"FAILED",startedAt:v.startedAt,finishedAt:v.finishedAt,type:"PRESET_ACTION",results:[v],message:R,failureReason:x,command:g};d.results.push(q),d.status="FAILED",d.finishedAt=new Date,d.message=R,d.failureReason=x;break}h++}}catch(p){d.message=p instanceof Error?p.message:`${p}`,d.finishedAt=new Date,d.status="FAILED"}return d.status==="SUCCESS"?(d.data=d.results[d.results.length-1]?.data,u.onSuccess?.({index:t,message:d.message||"AI step succeeded.",output:d})):u.onFailure?.({index:t,message:d.message||"AI step errored.",output:d}),d};async function pm(r,e,t){let n=t.id;if(!n||t.id<=0)throw new Error("Attempted to get reverse mapping for command with no a11y id target");return r.getReverseMappedTarget(e,n,!0)}async function gm({controller:r,currentIndex:e,globalSubStepIndex:t,currentStep:n,newStep:o,pageContext:s,onCommandExecuted:i,logger:a}){if(!s)return;let l=o.command;if("target"in l&&l.target&&"cache"in l&&l.cache){await new Promise(c=>setTimeout(()=>c(),100));try{let c=await pm(r,s,l.cache.target);l.target={elementDescriptor:c,type:"description"},n.steps[e]=o,i?.({index:t,step:o})}catch(c){a.warn({err:c,currentIndex:e,currentStep:n},"Failed to generate element description, continuing...")}}}function hm(r,e,t){Cn(r),e.toIndex&&e.toIndex>=t&&e.toIndex++}import{last as fm}from"lodash-es";async function Wa(r){let{step:e}=r.conditionalParams,{logger:t,controller:n,context:o}=r.fixtures,s=new Date,i=e.elseSteps,a=!0,l=bn();for(let m=0;m<e.blocks.length;m++){t.info(`Evaluating condition ${m} in conditional step`);let h=e.blocks[m];try{await n.executePresetStep(l,h.assertion.command,o,!1),t.info(`Condition ${m} resolved to true, executing the corresponding ${h.steps.length} steps`),a=!1,i=h.steps}catch(p){t.info({err:p},`Condition ${m} resolved to false`)}}if(i)a&&t.info("No conditions resolved to true, executing the else block steps");else return t.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped"),{...e,status:"SUCCESS",startedAt:s,results:[],finishedAt:new Date,details:l.details};t.info(`Executing ${i.length} steps in the selected conditional block`);let c=await r.executeStepList({...r,listParams:{steps:i,containerName:"conditional block"}}),d={...e,...c,startedAt:s,finishedAt:new Date};return d.data=fm(c.results)?.data,d}import{last as ym}from"lodash-es";async function Ga(r){let{step:e}=r.frameParams,t=new Date,n=r.fixtures.controller.browser.getActiveFrame();r.fixtures.controller.browser.setActiveFrame(e.identifier);let o;try{o=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"frame step list"}})}finally{r.fixtures.controller.browser.setActiveFrame(n)}let i={...e,...o,startedAt:t,finishedAt:new Date};return i.data=ym(o.results)?.data,i}import{last as Sm}from"lodash-es";async function ja(r){let{step:e}=r.sectionParams,t=new Date,n=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"section step list"}}),s={...e,...n,startedAt:t,finishedAt:new Date};return s.data=Sm(n.results)?.data,s}async function Ft(r){let{results:e=[],containerName:t,steps:n}=r.listParams,{logger:o,context:s,controller:i,codeEvalTools:a}=r.fixtures,{step:l,test:c}=r.callbacks,{fromIndex:u,toIndex:d}=r.inputs,m="SUCCESS",h,p=0;for(p;p<n.length;p++){let g=n[p],f=Qi(g),S=g.index;if(S===void 0)throw new Error(`Executing step without index: ${f}`);if(d&&S>d)break;if(c.isExecutionCancelled?.()){if(m="CANCELLED",l.onCancelled?.({index:S,output:{status:"CANCELLED",message:"Execution cancelled.",startedAt:new Date,finishedAt:new Date}}),e.length){let v=e[e.length-1];v.status="CANCELLED",v.message="Cancelled by user signal.",h=v}break}if(g.skipped)continue;if(u&&S<u&&(g.type==="PRESET_ACTION"||En([g])<u))continue;o.info(`Executing step ${p+1}/${n.length} in ${t}: ${f}`),l.onStarted?.(S);let w=s.toRedactedDisplayCopy(),b,E;switch(g.type){case"PRESET_ACTION":{b="Preset action",E=await Dt(g,()=>_a({...r,step:g}));break}case"AI_ACTION":{b="AI action",E=await Dt(g,()=>Ha({...r,aiStepParams:{step:g},executeStepList:Ft}));break}case"RESOLVED_MODULE":{b=`Module (${g.name})`;let C=new he({baseUrl:i.browser.baseURL,currentUrl:i.browser.url(),dynamicVariables:s.getDynamicVariablesCopy(),variablesFromEnvironment:s.getVariablesFromEnvironmentCopy(),envName:s.getEnvName()});E=await Dt(g,async()=>{let R=await za(g,s,o,a);return Ua({...r,executeStepList:Ft,fixtures:{...r.fixtures,context:C},moduleParams:{step:g,resolvedInputs:R}})});break}case"CONDITIONAL":{b="Conditional step",E=await Dt(g,()=>Wa({...r,conditionalParams:{step:g},executeStepList:Ft}));break}case"IFRAME":{b="Frame step",E=await Dt(g,()=>Ga({...r,frameParams:{step:g},executeStepList:Ft}));break}case"SECTION":{b="Section",E=await Dt(g,()=>ja({...r,sectionParams:{step:g},executeStepList:Ft}));break}default:return(C=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(g)}if(E.beforeTestContext=w,s.setResult(p,E.data),s.setUrl(i.browser.url()),E.afterTestContext=s.toRedactedDisplayCopy(),bm(b,S,E,r.callbacks,o,r.work),e.push(E),E.status!=="SUCCESS"){m=E.status,h=E;break}}return{status:m,results:e,terminalResult:h}}async function wm(r,e,t){if(r)try{await e?.({status:"RUNNING",results:r.results})}catch(n){t.error({err:n},"Error updating global run status")}}function bm(r,e,t,n,o,s){let{step:i,test:a}=n,l=r.toLowerCase(),c=r.charAt(0).toUpperCase()+r.slice(1);switch(t.status){case"SUCCESS":i.onSuccess?.({index:e,command:"command"in t?t.command:void 0,message:t.message??`${c} executed successfully.`,output:mn.parse(t)});break;case"FAILED":i.onFailure?.({index:e,message:t.message??`${c} failed.`,output:mn.parse(t)});break;case"CANCELLED":i.onCancelled?.({index:e,message:t.message??`${c} cancelled.`,output:mn.parse(t)});break;default:throw new Error(`Unexpected ${l} status: ${t.status}`)}t.status==="SUCCESS"&&s&&wm(s,a.onUpdateRun,o)}var kr=async r=>{r.fixtures.logger=r.fixtures.logger.child({orgId:r.inputs.orgId,runId:r.inputs.runId,testId:r.inputs.testMetadata.id});let e;e=ka(r.fixtures.logger),Cn(r.inputs.steps);let t;try{return t=await Cm(r),t}finally{if(clearInterval(e),Ji(r.inputs.steps),await r.callbacks.test.onTestComplete?.(),t?.status==="PASSED")try{await r.callbacks.test.onTestSuccess?.(r.inputs.steps)}catch(n){r.fixtures.logger.warn({err:n},"Error running test success handler, continuing...")}}},Cm=async r=>{let{runId:e,testMetadata:t,fromIndices:n,toIndices:o,indicesFilter:s,steps:i}=r.inputs,{logger:a}=r.fixtures;a.info(`Starting run ${e} for test '${t.name}'`);let l=i,c="test";if(n){let p=Tn(i,n);if(!p)throw new Error(`Could not find starting step using indices: ${n}`);r.inputs.fromIndex=p.index,a.debug({fromIndices:n,fromStep:p},"Identified starting step using fromIndices"),c="partial steps list"}if(o){let p=Tn(i,o);if(!p)throw new Error(`Could not find step at indices: ${o}`);let g=En([p]);r.inputs.toIndex=g,a.debug({toIndices:o,toStep:p,maxIndexUnderToStep:g},"Identified ending step using toIndices"),c="partial steps list"}if(s){let p=Tn(i,s);if(!p)throw new Error(`Could not find ending step at indices: ${r.inputs.indicesFilter}`);l=[p],a.debug({steps:i,indicesFilter:s},"Filtered steps to run based on exact indices filter"),c="filtered step"}await r.callbacks.test.onUpdateRun?.({status:"RUNNING",startedAt:new Date});let u=[],d={results:u},{status:m,terminalResult:h}=await Ft({...r,work:d,listParams:{steps:l,containerName:c,results:u}});if(r.options.takeScreenshots&&await new Promise(p=>setTimeout(p,2e3)),s&&u.length){let p=u[0];if(p.beforeTestContext&&p.afterTestContext){let g=he.fromSnapshot({snapshot:p.beforeTestContext,environmentVariables:r.fixtures.context.getVariablesFromEnvironmentCopy()}),f=r.fixtures.context.getResult(0);g.setResult(s[s.length-1],f),p.afterTestContext={...p.afterTestContext,results:g.getResultsCopy()}}}return await r.callbacks.test.onUpdateRun?.({status:m==="SUCCESS"?"PASSED":"FAILED",finishedAt:new Date,results:u}),m==="FAILED"?{status:"FAILED",results:u,failedStepResult:h}:{status:"PASSED",results:u}};import{cloneDeep as Em}from"lodash-es";var Vo={currentlyExecutingRequests:{}},vm=r=>async(e,t)=>{let n,{testId:o}=r.metadata,{baseUrl:s}=e,i=`${o}|${s}`;try{let a=Vo.currentlyExecutingRequests[i]??0;Vo.currentlyExecutingRequests[i]=a+1,n=await Am({...r,...e,done:t})}finally{r.logger.info({result:n,sessionId:r.metadata.sessionId},"Test execution complete"),Vo.currentlyExecutingRequests[i]--}},Am=async({socket:r,steps:e,baseUrl:t,testMetadata:n,reInitialize:o,indicesFilter:s,toIndices:i,fromIndices:a,storage:l,metadata:c,logger:u,envName:d,environmentVariables:m,authorization:h,done:p})=>{let{testId:g,sessionId:f,orgId:S}=c,w=f,b=N.getSession(f);if(!b)throw new Error("No active session found");N.resumeExecution(f);let{controller:E,context:v}=b;E.setOpen(),u=u.child({testId:g,orgId:S,baseUrl:t,sessionId:f,runId:w}),u.info({steps:e.map(H=>`${H.type}${"command"in H?` - ${H.command.type}`:""}`),indicesFilter:s,fromIndices:a,toIndices:i,reInitialize:o,envName:d,baseUrl:t},"Starting execution"),u.debug({steps:e,context:v,flags:E.flagStore.getAllFlags()},"Execution parameters");let C=async()=>{if(o){let H={url:t,clearCookies:!0,clearStorage:!0};await E.resetState(H),E.setOpen(),v.reset({baseUrl:t,currentUrl:E.browser.url(),variablesFromEnvironment:m??{},envName:d})}},R=async()=>{try{await l.resolveStepCacheEntries({schemaVersion:Ce,organizationId:S,testId:g,steps:e,logger:u})}catch(H){u.error({err:H},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};await Promise.all([C(),R()]);let x=Em(e),L={takeScreenshots:!1},q={orgId:S,runId:w,testMetadata:n,steps:e,indicesFilter:s,fromIndices:a,toIndices:i},Be={controller:E,context:v,storage:l,codeEvalTools:h?.type==="API_KEY"?new rt(h):void 0,logger:u},O=(H,Vt)=>{r.emit(Vt,H)},qe={test:{onTestComplete:async()=>{r.emit("finished")},onSaveScreenshot:Rm,isExecutionCancelled:()=>N.getSession(f)?.executionCancelled||E.browser.closed||E.isClosed()||r.disconnected,onTestSuccess:async H=>{let Vt=Tm(x,H);if(Object.keys(Vt).length>0){u.debug({changes:Vt},"Updating steps post-run success");let{cachesToSave:hr}=await He({steps:e,cacheCreationParams:{testId:g,orgId:S}});try{await l.saveStepCacheEntries(hr,n.id,u)}catch(Xr){u.warn({err:Xr},"Failed to save step cache entries after execution success")}}}},step:{onStarted:H=>r.emit("started",{globalIndex:H}),onSuccess:H=>O(H,"success"),onFailure:H=>O(H,"failure"),onCancelled:H=>O(H,"cancelled"),onCommandGenerated:H=>{r.emit("commandGenerated",{...H,message:H.message??"AI action sub-step generated"})},onCommandExecuted:H=>{r.emit("commandExecuted",H)}}};if(s?.length){u.info({indicesFilter:s},"Starting individual step");let H=b.resultsManager.getContextCopyAtIndices(s)??v.toObjectCopy(),Vt=he.fromSnapshot({snapshot:H,environmentVariables:v.getVariablesFromEnvironmentCopy()}),hr=await kr({fixtures:{...Be,context:Vt},options:L,callbacks:qe,inputs:q}),Xr=hr.results[0];return Xr?b.resultsManager.setIndividualResult(Xr,s):u.warn(hr,"No result found for individual step"),hr.status}let dt=await kr({fixtures:Be,options:L,callbacks:qe,inputs:q});return b.resultsManager.setResults(dt.results),p?.(dt),dt.status},Rm=async r=>r.toString("base64");var Va={event:"execute",createHandler:vm};var xm=({metadata:r,logger:e,storage:t})=>{let{sessionId:n}=r;return async(o,s)=>{let{command:i,testMetadata:a,returnScreenshot:l,indices:c}=o,u=Ar(i,o.description);e.debug({description:u,params:o},"Locate handler params"),e.info({description:u},"Locate handler called");let d=N.getSession(n);if(!d)throw new Error("No active session found");let{controller:m,context:h}=d,p=d.resultsManager.getContextCopyAtIndices(c)??h.toObjectCopy(),g=he.fromSnapshot({snapshot:p,environmentVariables:h.getVariablesFromEnvironmentCopy()}),f=Pt.parse(a.advanced??{}),S={},w;if(u){if("useSelector"in i&&i.useSelector)try{let b=await m.locateElementWithSelector(u,"iframeUrl"in i?i.iframeUrl:void 0);w=b.resolution.locator,S={target:b.target,thoughts:b.thoughts}}catch(b){e.warn({err:b},"Failed resolving target with selector"),s({err:`Failed locating element with CSS selector: ${b.message}`,decisions:b instanceof At?b.decisions:void 0});return}else try{let b=await m.locateElement(null,{description:u,disableCache:f.disableAICaching,iframeUrl:"iframeUrl"in i?i.iframeUrl:void 0,testContext:g,returnConflicts:!0});S={target:b.target,thoughts:b.thoughts},w=b.resolution.locator}catch(b){e.warn({err:b},"Failed locating element with AI"),s({err:`Failed locating element with AI: ${b.message}`});return}if(i.type==="SELECT_OPTION"&&w)try{S.options=await m.browser.getSelectOptions(w)}catch(b){e.warn({err:b},"Failed getting select options"),s({err:`Failed getting select options: ${b.message}`});return}e.info({result:S},"Locate handler result")}if(l)try{let{buffer:b,width:E,height:v}=await m.screenshotWithDimensions({scale:"css",clearHighlights:!0,target:S?.target,hideCaret:!0}),C=await t.uploadScreenshot(b);S.screenshot={data:C,width:E,height:v}}catch(b){e.error({err:b},"Error capturing screenshot during locate"),s({err:`Error taking screenshot: ${b.message}`});return}if(s({result:S}),w)try{await Promise.all([m.browser.scrollIntoView(w),m.browser.highlightTarget(w)])}catch(b){e.warn({err:b},"Error highlighting element, continuing...")}}},qa={event:"locate",createHandler:xm};var Im=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async({percentX:n,percentY:o},s)=>{let i=N.getSession(t);if(!i)throw new Error("No active session found");let a=i.controller.browser;try{await a.clickMouseFromPositionPercentages(n,o)}catch(l){e.error({err:l},"Error performing click during cloud recording in control mode"),s({err:l.message})}}},Ka={event:"cloudClick",createHandler:Im};var Lm=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async(n,o)=>{let s=N.getSession(t);if(!s)throw new Error("No active session found");let{controller:i}=s;s.browserBehavior.showOverlay=!0;try{let a=await i.browser.captureTargetFromClick();o({result:a})}catch(a){e.error({err:a},"Record click failed"),o({err:a instanceof Error?a.message:`${a}`})}finally{s.browserBehavior.showOverlay=!1}}},Ya={event:"recordTargetClick",createHandler:Lm};var Pm=({metadata:r,logger:e})=>{let{sessionId:t}=r,n,o=0,s=(a,l)=>{let c=async()=>{n=void 0;try{await a.highlightFromPositionPercentages(l),o=0}catch(u){e.error({err:u},"Error highlighting element on mouse move"),o++}};clearTimeout(n),n=setTimeout(c,50*(o+1))},i=0;return async a=>{let l=N.getSession(t);if(!l)throw new Error("No active session found");let{controller:c,browserBehavior:u}=l,d=c.browser;if(!d.closed){if(d.getActivePage().isClosed()){e.warn("Ignoring mouse move because the page is closed");return}u.showOverlay&&s(d,a);try{await d.moveMouseFromPositionPercentages(a.percentX,a.percentY),i=0}catch(m){i++,i%5===0&&e.warn({err:m,mouseErrors:i},"Error in socket mouse move handler")}}}},Xa={event:"cloudMouseMove",createHandler:Pm};var Om=({metadata:r})=>{let{sessionId:e}=r;return async({percentDeltaX:t,percentDeltaY:n})=>{let o=N.getSession(e);if(!o)throw new Error("No active session found");let s=o.controller.browser;if(s.closed)return;let i=await s.scrollFromPositionPercentages(t,n);if(!i)return;let a=o.browserBehavior.recordingState?.transformer;a&&a.recordScroll({...i,url:s.url()})}},Ja={event:"cloudScroll",createHandler:Om};var Mm=({metadata:r,generator:e,socket:t,storage:n,logger:o})=>{let{sessionId:s,orgId:i,testId:a}=r;return async({indices:l})=>{let c=N.getSession(s);if(!c)throw new Error("No active session found");let{controller:u,browserBehavior:d}=c;o.info("Starting cloud recording");let m=await u.startRecordMode({generator:e,initialIndices:l,storage:n,logger:o,testId:a,orgId:i,onStepRecord:(h,p)=>{t.emit("stepRecorded",{step:h,indices:p})}});d.recordingState={transformer:m},d.showOverlay=!0}},Qa={event:"cloudStartRecording",createHandler:Mm};var Nm=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async()=>{let n=N.getSession(t);if(!n)throw new Error("No active session found");e.info("Stopping cloud recording"),await n.controller.stopRecordMode(),n.browserBehavior.recordingState=void 0,n.browserBehavior.showOverlay=!1}},Za={event:"cloudStopRecording",createHandler:Nm};var _m=["Dead","Meta","AudioVolumeUp","AudioVolumeDown"],km=({metadata:r})=>{let{sessionId:e}=r;return async({key:t})=>{let n=N.getSession(e);if(!n)throw new Error("No active session found");if(_m.includes(t))return;let{controller:o}=n;t.length>1?await o.browser.press(t):await o.browser.type(t,{clearContent:!1,pressKeysSequentially:!0})}},el={event:"cloudType",createHandler:km};var Dr={vimiumJs:'var K=Object.defineProperty;var P=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var F=(t,e,n)=>e in t?K(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,D=(t,e)=>{for(var n in e||(e={}))z.call(e,n)&&F(t,n,e[n]);if(P)for(var n of P(e))B.call(e,n)&&F(t,n,e[n]);return t};var g=(t,e,n)=>(F(t,typeof e!="symbol"?e+"":e,n),n);var _=(t,e,n)=>new Promise((o,r)=>{var i=s=>{try{d(n.next(s))}catch(l){r(l)}},a=s=>{try{d(n.throw(s))}catch(l){r(l)}},d=s=>s.done?o(s.value):Promise.resolve(s.value).then(i,a);d((n=n.apply(t,e)).next())});var E=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=E);var k={create(t,e,n,o){return{bottom:o,top:e,left:t,right:n,width:n-t,height:o-e}},copy(t){return{bottom:t.bottom,top:t.top,left:t.left,right:t.right,width:t.width,height:t.height}},translate(t,e,n){return e==null&&(e=0),n==null&&(n=0),{bottom:t.bottom+n,top:t.top+n,left:t.left+e,right:t.right+e,width:t.width,height:t.height}},subtract(t,e){return e=this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom)),e.width<0||e.height<0?[k.copy(t)]:[this.create(t.left,t.top,e.left,e.top),this.create(e.left,t.top,e.right,e.top),this.create(e.right,t.top,t.right,e.top),this.create(t.left,e.top,e.left,e.bottom),this.create(e.right,e.top,t.right,e.bottom),this.create(t.left,e.bottom,e.left,t.bottom),this.create(e.left,e.bottom,e.right,t.bottom),this.create(e.right,e.bottom,t.right,t.bottom)].filter(o=>o.height>0&&o.width>0)},intersects(t,e){return t.right>e.left&&t.left<e.right&&t.bottom>e.top&&t.top<e.bottom},intersectsStrict(t,e){return t.right>=e.left&&t.left<=e.right&&t.bottom>=e.top&&t.top<=e.bottom},equals(t,e){for(let n of["top","bottom","left","right","width","height"])if(t[n]!==e[n])return!1;return!0},intersect(t,e){return this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom))}};var N={_browserInfoLoaded:!0,_firefoxVersion:null,_isFirefox:!1,isFirefox(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._isFirefox},firefoxVersion(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._firefoxVersion},isString(t){return typeof t=="string"||t instanceof String}};var f={isReady(){return document.readyState!=="loading"},documentReady:function(){let t=document.readyState!=="loading",e=[];if(!t){let n;globalThis.addEventListener("DOMContentLoaded",n=E(function(){globalThis.removeEventListener("DOMContentLoaded",n,!0),t=!0;for(let o of e)o();e=null}),!0)}return function(n){if(t)return n();e.push(n)}}(),documentComplete:function(){let t=document.readyState==="complete",e=[];if(!t){let n;globalThis.addEventListener("load",n=E(function(o){if(o.target===document){globalThis.removeEventListener("load",n,!0),t=!0;for(let r of e)r();e=null}}),!0)}return function(n){t?n():e.push(n)}}(),createElement(t){let e=document.createElement(t);return e instanceof HTMLElement?(this.createElement=n=>document.createElement(n),e):(this.createElement=n=>document.createElementNS("http://www.w3.org/1999/xhtml",n),this.createElement(t))},addElementsToPage(t,e){let n=this.createElement("div");e.id!=null&&(n.id=e.id),e.className!=null&&(n.className=e.className);for(let o of t)n.appendChild(o);return document.body.appendChild(n),n},removeElement(t){return t.parentNode.removeChild(t)},isTopFrame(){return globalThis.top===globalThis.self},makeXPath(t){let e=[];for(let n of t)e.push(".//"+n,".//xhtml:"+n);return e.join(" | ")},evaluateXPath(t,e){let n=document.webkitIsFullScreen?document.webkitFullscreenElement:document.documentElement,o=function(r){return r==="xhtml"?"http://www.w3.org/1999/xhtml":null};return document.evaluate(t,n,o,e,null)},getVisibleClientRect(t,e){let n;e==null&&(e=!1);let o=(()=>{let i=[];for(n of t.getClientRects())i.push(k.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),a=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>a,a};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let a of Array.from(t.children)){i=window.getComputedStyle(a,null);let d=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(d)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(a,!0);if(!(s===null||s.width<3||s.height<3))return s}else{if(n=this.cropRectToVisible(n),n===null||n.width<3||n.height<3||(i=window.getComputedStyle(t,null),i.getPropertyValue("visibility")!=="visible"))continue;return n}}return null},cropRectToVisible(t){let e=k.create(Math.max(t.left,0),Math.max(t.top,0),t.right,t.bottom);return e.top>=window.innerHeight-4||e.left>=window.innerWidth-4?null:e},getClientRectsForAreas(t,e){let n=[];for(let o of e){let r,i,a,d,s=o.coords.split(",").map(p=>parseInt(p,10)),l=o.shape.toLowerCase();if(["rect","rectangle"].includes(l))s.length==4&&([r,a,i,d]=s);else if(["circle","circ"].includes(l)){if(s.length==3){let[p,w,v]=s,u=v/Math.sqrt(2);r=p-u,i=p+u,a=w-u,d=w+u}}else l==="default"?s.length==2&&([r,a,i,d]=[0,0,t.width,t.height]):s.length>=4&&([r,a,i,d]=s);let c=k.translate(k.create(r,a,i,d),t.left,t.top);c=this.cropRectToVisible(c),c&&!isNaN(c.top)&&!isNaN(c.left)&&!isNaN(c.width)&&!isNaN(c.height)&&n.push({element:o,rect:c})}return n},isSelectable(t){if(!(t instanceof Element))return!1;let e=["button","checkbox","color","file","hidden","image","radio","reset","submit"];return t.nodeName.toLowerCase()==="input"&&e.indexOf(t.type)===-1||t.nodeName.toLowerCase()==="textarea"||t.isContentEditable},isEditable(t){return this.isSelectable(t)||(t.nodeName!=null?t.nodeName.toLowerCase():void 0)==="select"},isEmbed(t){let e=t.nodeName!=null?t.nodeName.toLowerCase():null;return["embed","object"].includes(e)},isFocusable(t){return t&&(this.isEditable(t)||this.isEmbed(t))},isDOMDescendant(t,e){let n=e;for(;n!==null;){if(n===t)return!0;n=n.parentNode}return!1},isSelected(t){let e=document.getSelection();if(t.isContentEditable){let n=e.anchorNode;return n&&this.isDOMDescendant(t,n)}else if(f.getSelectionType(e)==="Range"&&e.isCollapsed){let n=e.anchorNode.childNodes[e.anchorOffset];return t===n}else return!1},simulateSelect(t){if(t===document.activeElement&&f.isEditable(document.activeElement))return handlerStack.bubbleEvent("click",{target:t});if(t.focus(),t.tagName.toLowerCase()!=="textarea"||t.value.indexOf(`\n`)<0)try{if(t.selectionStart===0&&t.selectionEnd===0)return t.setSelectionRange(t.value.length,t.value.length)}catch(e){}},simulateClick(t,e){e==null&&(e={});let n=["mouseover","mousedown","mouseup","click"],o=[];for(let r of n){let i=this.simulateMouseEvent(r,t,e);o.push(i)}return o},simulateMouseEvent(t,e,n){if(n==null&&(n={}),t==="mouseout"){if(e==null&&(e=this.lastHoveredElement),this.lastHoveredElement=void 0,e==null)return}else t==="mouseover"&&(this.simulateMouseEvent("mouseout",void 0,n),this.lastHoveredElement=e);let o=new MouseEvent(t,{bubbles:!0,cancelable:!0,composed:!0,view:window,detail:1,ctrlKey:n.ctrlKey,altKey:n.altKey,shiftKey:n.shiftKey,metaKey:n.metaKey});return e.dispatchEvent(o)},simulateClickDefaultAction(t,e){let n;if(e==null&&(e={}),(t.tagName!=null?t.tagName.toLowerCase():void 0)!=="a"||!t.href)return;let{ctrlKey:o,shiftKey:r,metaKey:i,altKey:a}=e;KeyboardUtils.platform==="Mac"?n=i===!0&&o===!1:n=i===!1&&o===!0,n?chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:r===!0}):r===!0&&i===!1&&o===!1&&a===!1?chrome.runtime.sendMessage({handler:"openUrlInNewWindow",url:t.href}):t.target==="_blank"&&chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:!0})},simulateHover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseover",t,e)},simulateUnhover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseout",t,e)},addFlashRect(t){let e=this.createElement("div");return e.classList.add("vimiumReset"),e.classList.add("vimiumFlash"),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.width=t.width+"px",e.style.height=t.height+"px",document.documentElement.appendChild(e),e},getViewportTopLeft(){let t=document.documentElement,e=getComputedStyle(t),n=t.getBoundingClientRect();if(e.position==="static"&&!/content|paint|strict/.test(e.contain||"")){let o=parseInt(e.marginTop),r=parseInt(e.marginLeft);return{top:-n.top+o,left:-n.left+r}}else{let o,r;return N.isFirefox()?(r=parseInt(e.borderTopWidth),o=parseInt(e.borderLeftWidth)):{clientTop:r,clientLeft:o}=t,{top:-n.top-r,left:-n.left-o}}},suppressPropagation(t){t.stopImmediatePropagation()},suppressEvent(t){t.preventDefault(),this.suppressPropagation(t)},consumeKeyup:function(){let t=null;return function(e,n=null,o){if(!e.repeat){t!=null&&handlerStack.remove(t);let{code:r}=e;t=handlerStack.push({_name:"dom_utils/consumeKeyup",keyup(i){return i.code!==r||(this.remove(),o?f.suppressPropagation(i):f.suppressEvent(i)),handlerStack.continueBubbling},blur(i){return i.target===window&&this.remove(),handlerStack.continueBubbling}})}return typeof n=="function"&&n(),o?(f.suppressPropagation(e),handlerStack.suppressPropagation):(f.suppressEvent(e),handlerStack.suppressEvent)}}(),getSelectionType(t){return t==null&&(t=document.getSelection()),t.type?t.type:t.rangeCount===0?"None":t.isCollapsed?"Caret":"Range"},getElementWithFocus(t,e){let n,o=n=t.getRangeAt(0);f.getSelectionType(t)==="Range"&&(o=n.cloneRange(),o.collapse(e)),n=o.startContainer,n.nodeType===1&&(n=n.childNodes[o.startOffset]);let r=n;for(;r&&r.nodeType!==1;)r=r.previousSibling;return n=r||(n!=null?n.parentNode:void 0),n},getSelectionFocusElement(){let t=window.getSelection(),e=t.focusNode;return e==null?null:(e===t.anchorNode&&t.focusOffset===t.anchorOffset&&(e=e.childNodes[t.focusOffset]||e),e.nodeType!==Node.ELEMENT_NODE?e.parentElement:e)},getContainingElement(t){return(typeof t.getDestinationInsertionPoints=="function"?t.getDestinationInsertionPoints()[0]:void 0)||t.parentElement},windowIsTooSmall(){return window.innerWidth<3||window.innerHeight<3},injectUserCss(){let t=document.createElement("style");t.type="text/css",t.textContent=Settings.get("userDefinedLinkHintCss"),document.head.appendChild(t)}};var O={MAX_CONTENT_LENGTH:1e3,MAX_ATTRIBUTE_LENGTH:500,MAX_NUM_DATA_ATTRIBUTES:10,commonAttributes:["id","className","title","aria-label","aria-labelledby"],attributeNamesMapping:new Map([["a",["href","title","rel","target"]],["label",["for"]],["input",["type","name","placeholder","checked","maximumLength"]],["textarea",["placeholder","maximumLength"]],["button",["type"]],["select",["name","multiple"]],["div",["role"]],["iframe",["src"]],["img",["src","alt"]]]),describe(t){var r,i;let e={};this.addAttributes(t,this.commonAttributes,e);let n=((i=(r=t.tagName).toLowerCase)==null?void 0:i.call(r))||"";this.attributeNamesMapping.has(n)&&this.addAttributes(t,this.attributeNamesMapping.get(n),e),this.addDataAttrs(t,e);let o=this.getContent(t);return this.additionalHandling(t,D({tag:n,attributes:e},o&&{content:o}))},getContent(t){var n,o;let e=((o=(n=t.tagName).toLowerCase)==null?void 0:o.call(n))||"";return["input","textarea"].includes(e)?t.value:["div","iframe","img","body"].includes(e)?null:(["a","button","select","label"].includes(e),t.innerText)},additionalHandling(t,e){var o,r;if((((r=(o=t.tagName).toLowerCase)==null?void 0:r.call(o))||"")=="label"&&t.hasAttribute("for")){let i=t.getAttribute("for"),a=document.getElementById(i);a&&(e.target=this.describe(a))}return e},addAttributes(t,e,n){n||(n={});for(let o of e)t.hasAttribute(o)&&(n[o]=t.getAttribute(o).substring(0,this.MAX_ATTRIBUTE_LENGTH));return n},addDataAttrs(t,e){let n=0;for(let o in t.dataset)if(e[`data-${o}`]=t.dataset[o].substring(0,this.MAX_ATTRIBUTE_LENGTH),n++,n>this.MAX_NUM_DATA_ATTRIBUTES)return e;return e}};var x=null,C=()=>G()||document.scrollingElement||document.body,W=function(t){return t?t<0?-1:1:0},U={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},X=function(t,e,n){if(N.isString(n)){let o=n;return o==="viewSize"&&t===C()?e==="x"?window.innerWidth:window.innerHeight:t[U[e][o]]}else return n},V=function(t,e,n){let o=U[e].axisName,r=t[o];if(t.scrollBy){let i={behavior:"instant"};i[e==="x"?"left":"top"]=n,t.scrollBy(i)}else t[o]+=n;return t[o]!==r},q=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},T=function(t,e,n,o){let r=o*X(t,e,n)||-1;return r=W(r),V(t,e,r)&&V(t,e,-r)},$=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),T(t,e,n,o)&&q(t,e)},j=function(t=null){let e;if(!t){let n=C();if(T(n,"y",1,1)||T(n,"y",-1,1))return n;t=document.body||C()}if(T(t,"y",1,1)||T(t,"y",-1,1))return t;{let n=Array.from(t.children).map(o=>({element:o,rect:f.getVisibleClientRect(o)})).filter(o=>o.rect);n.map(o=>o.area=o.rect.width*o.rect.height);for(e of n.sort((o,r)=>r.area-o.area)){let o=j(e.element);if(o)return o}return null}},L={init(){x=null},isScrollableElement(t){return x||(x=C()&&j()||C()),t!==x&&$(t)}},G=function(){let t=J[window.location.host];if(t)return document.querySelector(t)},J={"twitter.com":"div.permalink-container div.permalink[role=main]","reddit.com":"#overlayScrollContainer","new.reddit.com":"#overlayScrollContainer","www.reddit.com":"#overlayScrollContainer","web.telegram.org":".MessageList"};window.Scroller=L;var A=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",E(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",E(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:A});var R=class{constructor(e){g(this,"element");g(this,"image");g(this,"rect");g(this,"linkText");g(this,"showLinkText");g(this,"reason");g(this,"secondClassCitizen");g(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},M={getLocalHintsForElement(t){var p,w,v;let e=((w=(p=t.tagName).toLowerCase)==null?void 0:w.call(p))||"",n=!1,o=!1,r=!1,i=[],a=[],d=null;if(e==="img"){let u=t.getAttribute("usemap");if(u){let h=t.getClientRects();u=u.replace(/^#/,"").replace(\'"\',\'\\\\"\');let m=document.querySelector(`map[name="${u}"]`);if(m&&h.length>0){n=!0;let y=m.getElementsByTagName("area"),S=f.getClientRectsForAreas(h[0],y);S=S.map(I=>Object.assign(I,{image:t})),a.push(...S)}}}let s=t.getAttribute("aria-disabled");if(s&&["","true"].includes(s.toLowerCase()))return[];if(this.checkForAngularJs||(this.checkForAngularJs=function(){if(document.getElementsByClassName("ng-scope").length===0)return()=>!1;{let h=[];for(let m of["","data-","x-"])for(let y of["-",":","_"])h.push(`${m}ng${y}click`);return function(m){for(let y of h)if(m.hasAttribute(y))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let u=t.getAttribute("role"),h=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(u!=null&&h.includes(u.toLowerCase()))n=!0;else{let m=t.getAttribute("contentEditable");m!=null&&["","contenteditable","true","plaintext-only"].includes(m.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let u=t.getAttribute("jsaction").split(";");for(let h of u){let m=h.trim().split(":");if(m.length>=1&&m.length<=2){let[y,S,I]=m.length===1?["click",...m[0].trim().split("."),"_"]:[m[0],...m[1].trim().split("."),"_"];n||(n=y==="click"&&S!=="none"&&I!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||(n=!t.disabled&&!t.readOnly);break;case"input":n||(n=!(((v=t.getAttribute("type"))==null?void 0:v.toLowerCase())=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t)));break;case"button":case"select":n||(n=!t.disabled);break;case"object":case"embed":n=!0;break;case"label":n||(n=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0);break;case"body":n||(n=t===document.body&&!A()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?d="Frame.":void 0),n||(n=t===document.body&&A()&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"img":n||(n=["zoom-in","zoom-out"].includes(t.style.cursor));break;case"div":case"ol":case"ul":n||(n=t.clientHeight<t.scrollHeight&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"details":n=!0,d="Open.";break}let l=t.getAttribute("class");!n&&(l!=null&&l.toLowerCase().includes("button"))&&(n=!0,r=!0);let c=t.getAttribute("tabindex"),b=c?parseInt(c):-1;if(!n&&!(b<0)&&!isNaN(b)&&(n=!0,o=!0),n)if(a.length>0){let u=a.map(h=>new R({element:h.element,image:t,rect:h.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:d}));i.push(...u)}else{let u=f.getVisibleClientRect(t,!0);if(u!==null){let h=new R({element:t,rect:u,secondClassCitizen:o,possibleFalsePositive:r,reason:d});i.push(h)}}return i},getElementFromPoint(t,e,n,o){n==null&&(n=document),o==null&&(o=[]);let r=n.elementsFromPoint?n.elementsFromPoint(t,e)[0]:n.elementFromPoint(t,e);return o.includes(r)?r:(o.push(r),r&&r.shadowRoot?M.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,l)=>{l==null&&(l=[]);for(let c of Array.from(s.querySelectorAll("*")))l.push(c),c.shadowRoot&&e(c.shadowRoot,l);return l},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let l=this.getLocalHintsForElement(s);o.push(...l)}o=o.reverse();let r=[1,2,3];o=o.filter((s,l)=>{if(!s.possibleFalsePositive)return!0;let b=Math.max(0,l-6);for(;b<l;){let p=o[b].element;for(let w of r)if(p=p==null?void 0:p.parentElement,p===s.element)return!1;b+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let l=s.rect,c=M.getElementFromPoint(l.left+l.width*.5,l.top+l.height*.5);if(c&&(s.element.contains(c)||c.contains(s.element))||s.element.localName=="area"&&c==s.image)return!0;let p=[l.top+.1,l.bottom-.1],w=[l.left+.1,l.right-.1];for(let v of p)for(let u of w){let h=M.getElementFromPoint(u,v);if(h&&(s.element.contains(h)||h.contains(s.element)))return!0}});i.reverse();let{top:a,left:d}=f.getViewportTopLeft();for(let s of i)s.rect.top+=a,s.rect.left+=d;return i}};var H=class{constructor(){this.hints=null;this.hintMarkers=null;this.markersDiv=null;this.enrichedMarkers=null}reset(){this.removeMarkers(),this.hints=null,this.hintMarkers=null,this.markersDiv=null}capture(){return _(this,null,function*(){this.reset(),this.createMarkers(),this.displayMarkers()})}createMarkers(){this.hints=M.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{var i,a;let o=f.createElement("div"),r=(a=(i=e.element.attributes["data-momentic-id"])==null?void 0:i.value)!=null?a:void 0;if(!r){console.warn(`[MOMENTIC] No data-momentic-id found for interactive element ${e.element.outerHTML}`);return}o.style.left=e.rect.left+"px",o.style.top=e.rect.top+"px",o.style.zIndex=214e7+n,o.className="vimiumReset internalVimiumHintMarker vimiumHintMarker",Z(o,r),this.hintMarkers.set(r,{hint:e,marker:o})})}enrichMarkers(){if(this.hintMarkers){this.enrichedMarkers=[];for(let[e,n]of this.hintMarkers)this.enrichedMarkers.push(Object.assign(O.describe(n.hint.element),{hintString:e}))}}displayMarkers(){this.hintMarkers&&(this.markersDiv||(this.markersDiv=f.addElementsToPage(Array.from(this.hintMarkers.values()).map(e=>e.marker),{id:"vimiumHintMarkerContainer",className:"vimiumReset"})))}removeMarkers(){this.markersDiv&&(f.removeElement(this.markersDiv),this.markersDiv=null)}toggleMarkers(){this.markersDiv?this.removeMarkers():this.displayMarkers()}},Z=(t,e)=>{for(let n of e){let o=document.createElement("span");o.className="vimiumReset",o.textContent=n,t.appendChild(o)}};window.HintManager=H;\n',vimiumCss:'.vimiumReset,a.vimiumReset,a:hover.vimiumReset,a:link.vimiumReset,a:visited.vimiumReset,div.vimiumReset,span.vimiumReset,table.vimiumReset,td.vimiumReset,tr.vimiumReset{background:none;border:none;bottom:auto;box-shadow:none;color:#000;cursor:auto;display:inline;float:none;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:inherit;font-style:normal;font-variant:normal;font-weight:400;height:auto;left:auto;letter-spacing:0;line-height:100%;margin:0;max-height:none;max-width:none;min-height:0;min-width:0;opacity:1;padding:0;position:static;right:auto;text-align:left;text-decoration:none;text-indent:0;text-shadow:none;text-transform:none;top:auto;vertical-align:baseline;white-space:normal;width:auto;z-index:2140000000}tbody.vimiumReset,thead.vimiumReset{display:table-header-group}tbody.vimiumReset{display:table-row-group}div.internalVimiumHintMarker{background:linear-gradient(180deg,#fff785 0,#ffc542);border:1px solid #c38a22;border-radius:3px;box-shadow:0 3px 7px 0 rgba(0,0,0,.3);display:block;font-size:11px;left:-1px;overflow:hidden;padding:1px 3px 0;position:absolute;top:-1px;white-space:nowrap}div.internalVimiumHintMarker span{color:#302505;font-family:Helvetica,Arial,sans-serif;font-size:11px;font-weight:700;text-shadow:0 1px 0 hsla(0,0%,100%,.6)}div.internalVimiumHintMarker>.matchingCharacter{color:#d4ac3a}div>.vimiumActiveHintMarker span{color:#a07555!important}div.internalVimiumInputHint{background-color:rgba(255,247,133,.3);border:1px solid #c38a22;display:block;pointer-events:none;position:absolute}div.internalVimiumSelectedInputHint{background-color:hsla(0,100%,70%,.3);border:1px solid #933!important}div.internalVimiumSelectedInputHint span{color:#fff!important}div.vimiumHighlightedFrame{border:5px solid #ff0;box-sizing:border-box;margin:0;pointer-events:none}div.vimiumHighlightedFrame,iframe.vimiumHelpDialogFrame{height:100%;left:0;padding:0;position:fixed;top:0;width:100%}iframe.vimiumHelpDialogFrame{background-color:hsla(0,0%,4%,.6);border:none;display:block;z-index:2139999997}div#vimiumHelpDialogContainer{background-color:#fff;border:2px solid #b3b3b3;border-radius:6px;margin:50px auto;max-height:calc(100% - 100px);max-width:calc(100% - 100px);opacity:1;overflow-x:auto;overflow-y:auto;width:840px}div#vimiumHelpDialog{min-width:600px;padding:8px 12px}span#vimiumTitle,span#vimiumTitle *,span#vimiumTitle span{font-size:20px}#vimiumTitle{display:block;line-height:130%;white-space:nowrap}td.vimiumHelpDialogTopButtons{text-align:right;width:100%}#helpDialogOptionsPage,#helpDialogWikiPage{font-size:14px;padding-left:5px;padding-right:5px}div.vimiumColumn{float:left;font-size:11px;line-height:130%;width:50%}div.vimiumColumn tr{display:table-row}div.vimiumColumn td{display:table-cell;font-size:11px;line-height:130%}div.vimiumColumn table,div.vimiumColumn td,div.vimiumColumn tr{margin:0;padding:0}div.vimiumColumn table{table-layout:auto;width:100%}div.vimiumColumn td{padding:1px;vertical-align:top}div#vimiumHelpDialog div.vimiumColumn tr>td:first-of-type{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;text-align:right;white-space:nowrap}span.vimiumHelpDialogKey{background-color:#f3f3f3;border:1px solid;border-color:#ccc #ccc #bbb;border-radius:3px;box-shadow:inset 0 -1px 0 #bbb;color:#212121;font-family:monospace;font-size:11px;margin-left:2px;padding:1px 4px}div#vimiumHelpDialog div.vimiumColumn tr>td:nth-of-type(3){width:100%}div#vimiumHelpDialog div.vimiumDivider{background-color:#9a9a9a;display:block;height:1px;margin:10px auto;width:100%}div#vimiumHelpDialog td.vimiumHelpSectionTitle{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:16px;font-weight:700;padding-top:3px}div#vimiumHelpDialog td.vimiumHelpDescription{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px}div#vimiumHelpDialog span.vimiumCopyCommandNameName{cursor:pointer;font-size:12px;font-style:italic}div#vimiumHelpDialog tr.advanced{display:none}div#vimiumHelpDialog.showAdvanced tr.advanced{display:table-row}div#vimiumHelpDialog div.advanced td:nth-of-type(3){color:#555}div#vimiumHelpDialog a.closeButton{color:#555;cursor:pointer;font-family:courier new;font-size:24px;font-weight:700;padding-left:5px;position:relative;text-decoration:none;top:3px}div#vimiumHelpDialog a{text-decoration:underline}div#vimiumHelpDialog a.closeButton:hover{color:#000;-webkit-user-select:none}div#vimiumHelpDialogFooter{display:block;margin-bottom:37px;position:relative}table.helpDialogBottom{width:100%}td.helpDialogBottomRight{float:right;text-align:right;width:100%}td.helpDialogBottomLeft,td.helpDialogBottomRight{padding:0}div#vimiumHelpDialogFooter *{font-size:10px}a#toggleAdvancedCommands,span#help-dialog-tip{font-size:10px;position:relative;top:19px;white-space:nowrap}a#toggleAdvancedCommands,a:active.vimiumHelDialogLink,a:hover.vimiumHelDialogLink,a:link.vimiumHelDialogLink,a:visited.vimiumHelDialogLink{color:#2f508e;cursor:pointer;text-decoration:underline}div.vimiumHUD{background:#f1f1f1;border:1px solid #aaa;border-radius:4px;bottom:8px;box-shadow:0 2px 10px rgba(0,0,0,.8);display:block;left:8px;position:fixed;text-align:left;width:calc(100% - 20px);z-index:2139999999}iframe.vimiumHUDFrame{background-color:transparent;border:none;bottom:-14px;display:block;height:58px;margin:0 0 0 -40%;min-width:300px;opacity:0;overflow:hidden;padding:0;position:fixed;right:20px;width:20%;z-index:2139999998}div.vimiumHUD .vimiumHUDSearchArea{background-color:#f1f1f1;border-radius:4px 4px 0 0;display:block;padding:3px}div.vimiumHUD .vimiumHUDSearchAreaInner{border-radius:3px;box-sizing:border-box;color:#777;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;height:30px;line-height:20px;margin-bottom:0;outline:none;padding:2px 4px;width:100%}div.vimiumHUD .hud-find{background:#fff;border:1px solid #ccc}div.vimiumHUD span#hud-find-input,div.vimiumHUD span#hud-match-count{color:#000;display:inline;outline:none;overflow-y:hidden;white-space:nowrap}div.vimiumHUD span#hud-find-input:before{content:"/"}div.vimiumHUD span#hud-match-count{color:#aaa;font-size:12px}div.vimiumHUD span#hud-find-input br{display:none}div.vimiumHUD span#hud-find-input *{display:inline;white-space:nowrap}body.vimiumFindMode ::selection{background:#ff9632}iframe.vomnibarFrame{background-color:transparent;border:none;display:block;font-family:sans-serif;height:calc(100% - 70px);left:50%;margin:0 0 0 -40%;min-width:400px;overflow:hidden;padding:0;position:fixed;top:70px;width:calc(80% + 20px);z-index:2139999998}div.vimiumFlash{background-color:transparent;box-shadow:0 0 4px 2px #4183c4;padding:1px;position:absolute;z-index:2140000000}iframe.vimiumUIComponentHidden{display:none}iframe.vimiumUIComponentVisible{color-scheme:light dark;display:block}iframe.vimiumUIComponentReactivated{border:5px solid #ff0}iframe.vimiumNonClickable{pointer-events:none}@media (prefers-color-scheme:dark){iframe.reverseDarkReaderFilter{-webkit-filter:invert(100%) hue-rotate(180deg)!important;filter:invert(100%) hue-rotate(180deg)!important}body.vimiumBody{background-color:#292a2d;color:#fff}body.vimiumBody a,body.vimiumBody a:visited{color:#8ab4f8}body.vimiumBody input,body.vimiumBody textarea{background-color:#1d1d1f;border-color:#1d1d1f;color:#e8eaed}body.vimiumBody div.example{color:#9aa0a6}body.vimiumBody div#footer,body.vimiumBody div#state,div#vimiumHelpDialogContainer{background-color:#202124;border-color:hsla(0,0%,100%,.1)}div#vimiumHelpDialog{background-color:#292a2d;color:#fff}div#vimiumHelpDialog td.vimiumHelpDescription{color:#c9cccf}div#vimiumHelpDialog td.vimiumHelpSectionTitle,span#vimiumTitle{color:#fff}#vimiumTitle>span:first-child{color:#8ab4f8!important}div#vimiumHelpDialog a{color:#8ab4f8}div#vimiumHelpDialog div.vimiumDivider{background-color:hsla(0,0%,100%,.1)}span.vimiumHelpDialogKey{background-color:#1d1d1f;border:1px solid #000;box-shadow:none;color:#fff}}',htmlUtilsLibJs:`var __defProp = Object.defineProperty;
|
|
9
|
+
`)),console.log(e===0?`${s} `:" ",l)}e===0&&process.stdout.write("\x1B[39m")}setMinLevel(e){this.minLogLevel=e}log(...e){this.info(...e)}info(...e){1<this.minLogLevel||this.logWithLevel(1,...e)}debug(...e){0<this.minLogLevel||this.logWithLevel(0,...e)}warn(...e){2<this.minLogLevel||this.logWithLevel(2,...e)}error(...e){3<this.minLogLevel||this.logWithLevel(3,...e)}child(e){return new r(this.minLogLevel,{...this.logBindings,...e})}flush(){}bindings(){return this.logBindings}},Li=new _o(1,{}),ko={info:()=>{},error:()=>{},debug:()=>{},warn:()=>{},child:()=>ko,flush:()=>{},bindings:()=>({})},Cn={},er=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,s,...i)=>{let a=Cn[e];a?clearTimeout(a.timer):(a={count:0,totalCount:0},Cn[e]=a),a.totalCount++,a.count<t&&(a.count++,r.debug(o,s,...i)),a.timer=setTimeout(()=>{let l=Cn[e];l?.totalCount!==l?.count&&r.debug({logKey:e,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${e}`),delete Cn[e]},n)};import{z as he}from"zod";var wu=he.object({id:he.string(),createdAt:he.coerce.date(),createdBy:he.string(),organizationId:he.string(),name:he.string(),schemaVersion:he.string().describe("Schema version for steps"),parameters:he.string().array().nullish().describe("Parameter list"),defaultParameters:he.record(he.string(),he.string()).nullish(),defaultCacheKey:he.string().nullish(),defaultCacheTtl:he.number().nullish(),numSteps:he.number()}),ww=wu.omit({numSteps:!0}).extend({steps:he.lazy(()=>Me.array())}),Pi=5*60*1e3;var pe=r=>{let e=r.trim().toLowerCase().replace(/[^a-z0-9]/g,"-");for(;e.includes("--");)e=e.replaceAll("--","-");return e.startsWith("-")&&(e=e.slice(1)),e.endsWith("-")&&(e=e.slice(0,e.length-1)),e};import*as E from"zod";import{z as F}from"zod";var xr={WEBHOOK:"WEBHOOK",CRON:"CRON",MANUAL:"MANUAL",CLI:"CLI"},yt=(a=>(a.PENDING="PENDING",a.RUNNING="RUNNING",a.PASSED="PASSED",a.FAILED="FAILED",a.CANCELLED="CANCELLED",a.RETRYING="RETRYING",a.WAITING_FOR_USER="WAITING_FOR_USER",a))(yt||{}),bu={PASSED:"PASSED",FAILED:"FAILED"},et=F.string().pipe(F.coerce.date()).or(F.date()),En=F.object({id:F.string(),runKey:F.string(),organizationId:F.string(),createdAt:et,createdBy:F.string(),scheduledAt:et.or(F.null()),startedAt:et.or(F.null()),updatedAt:et.nullish(),finishedAt:et.or(F.null()),status:F.unknown().transform(r=>F.nativeEnum(yt).parse(r)),expectedStatus:F.nativeEnum(bu).or(F.null()),trigger:F.nativeEnum(xr),attempts:F.number(),failureReason:F.nativeEnum(te).nullish(),failureDetails:Ys.nullish(),testId:F.string().or(F.null()),testName:F.string().or(F.null()).optional(),test:F.object({name:F.string(),id:F.string()}).or(F.null()),suiteId:F.string().or(F.null()).optional()}),xw=En.omit({failureReason:!0,failureDetails:!0}),Ir=En.merge(F.object({results:Pt.array(),test:F.object({name:F.string(),id:F.string(),baseUrl:F.string(),advanced:Ot.optional()}).or(F.null())})),Iw=F.object({id:F.string(),name:F.string()});var Mt=E.object({disableCache:E.boolean()}),Uw=E.object({error:E.boolean(),reason:E.string(),message:E.string()}),zw=gt.merge(Mt),Oi=bo,Bw=gt.merge(Mt).merge(E.object({screenshot:E.string().optional()})),Mi=$s,$w=gt.pick({browserState:!0,goal:!0}).merge(Mt).merge(E.object({screenshot:E.string().optional()})),Hw=gt.pick({goal:!0}).merge(Mt).merge(E.object({screenshot:E.string().describe("base64 encoded image"),hintActivatedScreenshot:E.string().describe("base64 encoded image")})),Ni=Js,Ww=gt.pick({goal:!0,url:!0}).merge(Mt),_i=E.string().array(),Gw=gt.pick({goal:!0,browserState:!0}).merge(Mt),ki=Xs,jw=gt.pick({goal:!0,browserState:!0,returnSchema:!0}).merge(Mt);var Vw=E.object({testPaths:E.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:E.string().optional(),all:E.boolean().optional(),urlOverride:E.string().optional(),customHeaders:E.record(E.string(),E.string()).optional()}),Di=E.object({message:E.string(),queuedTests:E.object({name:E.string(),id:E.string()}).array(),runIds:E.string().uuid().array()}),Fi=bn,Ui=E.string().array(),Kw=E.union([E.object({paths:E.string().array().describe("run specific test paths (e.g. todo-test)"),all:E.boolean().describe("run all tests").optional()}),E.object({path:E.string().describe("deprecated; present for backcompat")})]),zi=E.object({tests:E.record(E.string().describe("Test name"),E.string().describe("Test YAML")),modules:E.record(E.string().describe("Module name"),E.string().describe("Module YAML"))}),Cu=E.object({test:E.string().describe("test YAML"),modules:E.record(E.string().describe("moduleId"),E.string().describe("module YAML"))}),qw=Cu.array(),Yw=E.object({testId:E.string(),schemaVersion:E.string(),steps:E.array(E.record(E.unknown()))}),Xw=E.object({entries:E.array(Lo),testId:E.string()}),Jw=E.object({steps:E.array(E.record(E.unknown())),testId:E.string(),schemaVersion:E.string(),organizationId:E.string()}),Bi=oi;var Qw=E.object({testId:E.string(),testName:E.string(),trigger:E.nativeEnum(xr)}),$i=Ir,Hi=Ir,Eu=Ir.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Wi=Eu.array(),Zw=Ir.pick({startedAt:!0,finishedAt:!0,results:!0,status:!0,failureDetails:!0,failureReason:!0}).partial(),eb=E.object({screenshot:E.string()}),Gi=E.object({key:E.string()}),ji=E.object({orgId:E.string()}),Vi=E.array(Ae),tb=E.array(Ae),Ki=E.record(E.string(),E.union([E.string(),E.boolean()])),rb=E.object({paths:E.string().array(),env:E.string().optional(),urlOverride:E.string().optional(),customHeaders:E.record(E.string(),E.string()).optional()}),qi=E.object({suiteRunIds:E.string().array()});import{z as fe}from"zod";var Tu=fe.object({content:fe.string(),ids:fe.string().array(),tokenLength:fe.number()}),vu=fe.object({chunks:Tu.array(),numRecs:fe.number()}),sb=fe.object({ids:fe.string().array(),score:fe.number(),tokenLength:fe.number()}),ib=fe.object({description:fe.string(),tokenLimit:fe.number()}).merge(vu),Yi=fe.object({ids:fe.number().array()});import{z as se}from"zod";var Ru=se.object({type:se.literal("TARGETING"),name:se.string().optional().describe("Target name for steps with multiple targets"),elementLocationDecisions:Ii.array(),pageState:se.string().optional(),targetSource:se.nativeEnum(Et).optional()}),Au=se.object({type:se.literal("AI_LOCATION"),matched:se.boolean(),pageState:se.string().optional(),ragUsed:se.boolean().optional(),thoughts:se.string().optional()}),xu=se.object({type:se.literal("ASSERTION"),relevantElementsSerialized:se.string().array().optional(),pageState:se.string().optional(),ragUsed:se.boolean().optional()}),ub=se.discriminatedUnion("type",[Ru,Au,xu]);function Tn(){return{details:[]}}import{z as Fe}from"zod";var Xi=Fe.object({id:Fe.string().uuid(),orgId:Fe.string(),createdAt:et,startedAt:et.or(Fe.null()),finishedAt:et.or(Fe.null()),status:Fe.string().transform(r=>Fe.nativeEnum(yt).parse(r)),trigger:Fe.nativeEnum(xr),suite:Fe.object({id:Fe.string(),name:Fe.string()}),runs:En.array()});import{validator as bb}from"@exodus/schemasafe";var Ji=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"];var Qi=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};import{z as tr}from"zod";var Mb=tr.object({goal:tr.string(),completionType:tr.nativeEnum(To)}),Zi=tr.object({keywords:tr.array(tr.string())});var rr=class extends Error{status;constructor(e,t,n={}){super(t,n),this.status=e}},nr=class{baseUrl;apiKey;logger;constructor(e){this.baseUrl=e.baseUrl,this.apiKey=e.apiKey,this.logger=e.logger}async sendRequest(e,t,n=3,o=3e4){let s=new AbortController,i=setTimeout(()=>s.abort(),o),a=await fetch(`${this.baseUrl}${e}`,{method:t.method,body:t.body?JSON.stringify(t.body):void 0,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},signal:s.signal});if(clearTimeout(i),!a.ok){if(a.status>500&&n>0)return await new Promise(c=>setTimeout(c,1500*Math.random())),this.sendRequest(e,t,n-1);throw new rr(a.status,`Request to ${e} failed with status ${a.status}: ${await a.text()}`)}let l;return a.status===204?l=await a.text():l=await a.json(),this.logger&&!t.noLog&&this.logger.debug({result:l,path:e,baseUrl:this.baseUrl,status:a.status},"Got response from Momentic server"),l}};var V="v1",ie=class extends nr{constructor(e){super(e)}getAppUrl(){return this.baseUrl.replace(/\/\/api/,"//app")}async getOrgId(){let e=await this.sendRequest(`/${V}/auth/check`,{method:"GET",noLog:!0}),{orgId:t}=ji.parse(e);return t}async getRun(e){let t=await this.sendRequest(`/${V}/runs/${e}`,{method:"GET",noLog:!0});return Hi.parse(t)}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${V}/runs/status`,{method:"POST",body:e,noLog:!0});return Wi.parse(t)}async createRun(e){let t=await this.sendRequest(`/${V}/runs`,{method:"POST",body:e,noLog:!0});return $i.parse(t)}async updateRun(e,t){await this.sendRequest(`/${V}/runs/${e}`,{method:"PATCH",body:t,noLog:!0})}async getTest(e){let t=await this.sendRequest(`/${V}/tests/${e}`,{method:"GET"});return Fi.parse(t)}async getAllTestIds(){let e=await this.sendRequest(`/${V}/tests`,{method:"GET"});return Ui.parse(e)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${V}/tests/export`,{method:"POST",body:e});return zi.parse(t)}async updateTestWithYAML(e){await this.sendRequest(`/${V}/tests/update`,{method:"POST",body:e})}async updateResolvedTest(e){await this.sendRequest(`/${V}/tests/${e.testId}`,{method:"PATCH",body:e})}async updateStepCaches(e){await this.sendRequest(`/${V}/cache`,{method:"PATCH",body:e})}async getStepCacheForTest(e){let t=await this.sendRequest(`/${V}/cache`,{method:"POST",body:e});return Bi.parse(t)}async queueTests(e){let t=await this.sendRequest(`/${V}/tests/queue`,{method:"POST",body:e});return Di.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${V}/screenshots`,{method:"POST",body:e,noLog:!0});return Gi.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${V}/environments`,{method:"GET"});return Vi.parse(e)}async getEnvironment(e){let t=await this.sendRequest(`/${V}/environments/${e}`,{method:"GET"});return Ae.parse(t)}async updateEnvironments(e){await this.sendRequest(`/${V}/environments`,{method:"POST",body:e})}async getAllFeatureFlags(){let e=await this.sendRequest(`/${V}/auth/flags`,{method:"GET",noLog:!0});return Ki.parse(e)}async acquireCacheLock(e){let t=await this.sendRequest(`/${V}/result-cache/entry`,{method:"POST",body:e});return pi.parse(t)}async releaseCacheLock(e){await this.sendRequest(`/${V}/result-cache/entry`,{method:"DELETE",body:{key:e}})}async setCacheResult(e){await this.sendRequest(`/${V}/result-cache/entry`,{method:"PATCH",body:e})}async getCacheResult(e){try{return await this.sendRequest(`/${V}/result-cache/entry`,{method:"POST",body:e})}catch(t){if(t instanceof Error&&t.message.includes("404"))return null;throw t}}async queueSuiteRuns(e){let t=await this.sendRequest(`/${V}/suites/queue`,{method:"POST",body:e});return qi.parse(t)}async bulkGetSuiteStatus(e){let t={suiteRunIds:e},n=await this.sendRequest(`/${V}/suites/status`,{method:"POST",body:t,noLog:!0});return Xi.array().parse(n)}async updateCacheLastUsedDate(e,t){try{await this.sendRequest(`/${V}/cache/lastUsedAt`,{method:"PATCH",body:e})}catch(n){t.error({err:n},"Failed to update cache last used date")}}};function or({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:s}=t,i=[],a=[],l=0,c=(d,p)=>{try{let g=At.parse(p.value);if(g.type!==d.type){o.warn({parsedCacheEntry:g,command:d},"Not using step cache due to type mismatch"),a.push(p.key);return}d.cache=g.cache,i.push(p.key)}catch(g){a.push(p.key),o.error({err:g,cacheEntry:p},"Not using step cache due to parsing error")}},u=(d,p)=>{let g=Iu(d.id,p),m=g.find(h=>!!n[h]);m?c(d,n[m]):(a.push(g[0]),o.debug({command:d,possibleKeys:g},"Step cache miss"))};for(let d of r)switch(d.type){case"RESOLVED_MODULE":{l+=d.steps.length;let{hits:g,misses:m}=or({...t,steps:d.steps,keyPrefix:s?`${s}:${d.id}`:d.id,topLevel:!1});i=i.concat(g),a=a.concat(m);break}case"IFRAME":case"SECTION":case"AI_ACTION":{if(l+=d.steps?.length??0,!d.steps?.length)break;let{hits:g,misses:m}=or({...t,steps:d.steps,topLevel:!1});i=i.concat(g),a=a.concat(m);break}case"PRESET_ACTION":{if(!Co.includes(d.command.type)||d.command.type==="TYPE"&&!d.command.target||d.command.type==="MOUSE_DRAG"&&!d.command.target||"cache"in d.command&&d.command.cache)continue;l++,u(d.command,s);break}case"CONDITIONAL":{for(let g of d.blocks){l++,u(g.assertion.command,s),l+=g.steps.length;let{hits:m,misses:h}=or({...t,steps:g.steps,topLevel:!1});i=i.concat(m),a=a.concat(h);break}if(d.elseSteps){l+=d.elseSteps.length;let{hits:g,misses:m}=or({...t,steps:d.elseSteps,topLevel:!1});i=i.concat(g),a=a.concat(m)}break}default:return(g=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(d)}return e&&l&&a.length>0&&o.debug({totalSteps:l,cacheMisses:a,cacheHits:i,cacheEntries:n.length},"Step cache did not fully resolve"),{hits:i,misses:a}}function ea(r,e){return e?`${e}:${r}`:r}function Iu(r,e){let t=[],n=e?.split(":")??[];for(let o=n.length;o>=0;o--){let s=[...n.slice(o),r];t.push(s.join(":"))}return t}function ta(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
|
|
10
|
+
${JSON.stringify(t)}`);let n=[];if(!r.skipIntermediateEntries)for(let o=e.length;o>0;o--){let s=t[o-1],i=e.slice(o,e.length).join(":");n.push({key:ea(r.id,i),moduleId:s,organizationId:r.orgId,value:r.value})}return n.push({key:ea(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function ra(r){switch(r.type){case"DRAG":{if(r.fromTarget.type==="coordinates"||r.toTarget.type==="coordinates"||!r.fromTarget?.a11yData||!r.toTarget?.a11yData)return;r.cache={fromTarget:r.fromTarget.a11yData,toTarget:r.toTarget.a11yData},delete r.fromTarget.a11yData,delete r.toTarget.a11yData;return}case"MOUSE_DRAG":case"HOVER":case"SCROLL_UP":case"SCROLL_DOWN":case"SCROLL_LEFT":case"SCROLL_RIGHT":case"SELECT_OPTION":case"TYPE":case"VISUAL_DIFF":case"CLICK":case"FOCUS":case"BLUR":{if(r.target?.type==="coordinates"||!r.target?.a11yData)return;r.cache={target:r.target.a11yData},delete r.target.a11yData;return}default:return}}function na(r,e){return r.length<e?r:r.slice(0,e-3)+"[...]"}var Nt={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with"},_t={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with"},Do={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable"},Fo={EXISTS:"does not exists",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable"};function Lu(r){switch(r.type){case"ELEMENT_CONTENT":return`${r.negated?_t[r.operation]:Nt[r.operation]} '${r.value}'`;case"ELEMENT_ATTRIBUTE":{let t=r.negated?_t[r.operation]:Nt[r.operation];return`attribute '${r.attr}' ${t} '${r.value}'`}case"ELEMENT_EXISTENCE":return r.negated?Fo[r.condition]:Do[r.condition];default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}var QC={CONTENT:"The page"};function Pu(r){switch(r.type){case"CONTENT":return`${r.negated?_t.CONTAINS:Nt.CONTAINS} '${r.value}'`;default:return(t=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.type)}}function St(r){switch(r.type){case"SUCCESS":return r.condition?.assertion?`Check success condition: ${r.condition.assertion}`:"All commands completed";case"AI_EXTRACT":return`Extract data from page: ${r.goal}`;case"NAVIGATE":return`Go to URL: ${na(r.url,30)}`;case"DIALOG":return`Automatically ${r.action.toLowerCase()} the next dialog`;case"CAPTCHA":return"Solve captchas on the page";case"GO_BACK":return"Go back to the previous page";case"GO_FORWARD":return"Go forward to the next page";case"SCROLL_DOWN":return`Scroll down ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${de(r.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${de(r.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${de(r.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${de(r.target)}`:""}`;case"WAIT":return`Wait for ${r.delay} seconds`;case"REFRESH":return"Refresh the page";case"CLICK":{if(r.target?.type==="coordinates")return`Click at coordinates: ${de(r.target)}`;let o="";return r.target?.elementDescriptor.length?o=` on element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(o=` on element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Click${o}`}case"FOCUS":return`Focus ${de(r.target)}`;case"BLUR":return`Focus ${de(r.target)}`;case"DRAG":return`Drag ${de(r.fromTarget)} onto ${de(r.toTarget)}`;case"MOUSE_DRAG":return r.target?`Click and drag ${de(r.target)} by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`:`Click and drag mouse by ${r.deltaX}px horizontally, ${r.deltaY}px vertically`;case"TYPE":{let o="";return r.target?.type==="coordinates"?o=` in element at coordinates: ${de(r.target)}`:r.target?.elementDescriptor.length?o=` in element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(o=` in element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Type '${r.value}'${o||""}`}case"HOVER":{let o="";return r.target.type==="coordinates"?o=` over coordinates: ${de(r.target)}`:r.target.elementDescriptor.length>0?o=` over element: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(o=` over element: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Hover${o}`}case"PRESS":return`Press ${r.value}`;case"SELECT_OPTION":let e="";return r.target.type==="coordinates"?e=` from element at coordinates: ${de(r.target)}`:r.target.elementDescriptor.length>0?e=` from: '${r.target.elementDescriptor}'`:r.cache?.target.nodeOnlySerializedHtml&&(e=` from: '${r.cache?.target.nodeOnlySerializedHtml}'`),`Select option '${r.option}'${e}`;case"TAB":return`Switch to tab with substring: ${r.url}`;case"NEW_TAB":return`Open new tab to: ${r.url}`;case"REQUEST":return`Send ${r.method} request to ${r.url}`;case"COOKIE":return`Set cookie: ${r.value}`;case"LOCAL_STORAGE":return`Set local storage: ${r.key}: ${r.value}`;case"JAVASCRIPT":return`Run JavaScript: ${na(r.code,30)}`;case"AI_ASSERTION":return`Assertion: '${r.assertion}'`;case"AI_WAIT":return`Wait until assertion is true: '${r.assertion}'`;case"VISUAL_DIFF":return`Visual diff against baseline ${r.target?`for element: ${de(r.target)}`:"for entire page"}`;case"FILE_UPLOAD":return`Upload file: ${r.fileSource.url}`;case"AUTH_LOAD":return"Load auth state";case"AUTH_SAVE":return"Save auth state";case"ELEMENT_CHECK":return`Assert the element ${de(r.target)} ${Lu(r.assertion)}`;case"PAGE_CHECK":return`Assert the page ${Pu(r.assertion)}`;case"WAIT_FOR_URL":return`Wait for the page URL to match: ${r.url}`;default:return(o=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}function tt(r){let{onPresetAction:e,onStepContainer:t,onConditional:n}=r;for(let o of r.steps)switch(o.type){case"PRESET_ACTION":e(o);break;case"CONDITIONAL":n?.(o);for(let i of o.blocks)e(i.assertion),tt({...r,steps:i.steps});tt({...r,steps:o.elseSteps??[]});break;case"RESOLVED_MODULE":case"IFRAME":case"SECTION":case"AI_ACTION":t?.(o),o.steps&&tt({...r,steps:o.steps});break;default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(o)}}function vn(r){let e=0;tt({steps:r,onPresetAction:t=>{t.index=e++},onConditional:t=>{t.index=e++},onStepContainer:t=>{t.index=e++}})}function oa(r){tt({steps:r,onPresetAction:e=>{delete e.index},onConditional:e=>{delete e.index},onStepContainer:e=>{delete e.index}})}var Ou=(r,e)=>{switch(r.type){case"RESOLVED_MODULE":return r.steps[e];case"AI_ACTION":return r.steps[e];case"CONDITIONAL":{let n=r.blocks.map(o=>[o.assertion,...o.steps]).flat();return r.elseSteps&&(n=n.concat(r.elseSteps)),n[e]}case"SECTION":case"IFRAME":return r.steps[e];case"PRESET_ACTION":default:throw new Error(`Cannot get a child step from step type ${r.type}`)}};function Rn(r,e){let t=r[e[0]];for(let n=1;n<e.length;n++)t=Ou(t,e[n]);return t}function An(r){let e=0;return tt({steps:r,onPresetAction:t=>{e=Math.max(e,t.index)},onConditional:t=>{e=Math.max(e,t.index)},onStepContainer:t=>{e=Math.max(e,t.index)}}),e}import{cloneDeep as aE,unset as lE}from"lodash-es";function sa(r){switch(r.type){case"AI_ACTION":return`AI action: ${r.text}`;case"PRESET_ACTION":return St(r.command);case"MODULE":return`Module: ${r.id}`;case"RESOLVED_MODULE":return`Module: ${r.name}`;case"CONDITIONAL":return"Conditional";case"IFRAME":return"Frame step";case"SECTION":return"Section"}}function ia(r,e){if(!(!r.envs||!r.envs.length)){for(let t of r.envs)e in t&&(t[e]&&(t.default=!0),delete t.defaultOnCloud,delete t.defaultOnLocal);r.envs.some(t=>t.default)||(r.envs[0].default=!0)}}import _u from"diff-lines";import In,{gte as ku}from"semver";var aa={name:"Migrate to ai step v2",fromVersion:"1.0.4",toVersion:"1.0.5",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>(r=r.filter(e=>!(e.status!==void 0&&e.type==="AI_ACTION")),r=r.map(e=>(e.status===void 0||e.type==="PRESET_ACTION"&&(e.results=e.commands??e.results??[]),e)),r)};var la={name:"Make sure ai step v2 has done command",fromVersion:"1.0.5",toVersion:"1.0.6",recursiveKeys:new Set(["results","commands"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="AI_ACTION"||e.status!==void 0||!e.commands||!e.commands.length)return e;let t=e.commands,n=t[t.length-1];return n&&n.type!=="SUCCESS"&&t.push({type:"SUCCESS"}),e})};var Mu=["target","fromTarget","toTarget"];function ca(r){for(let e of Mu){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var da={name:"Migrate element target to discriminated union",fromVersion:"1.0.6",toVersion:"1.0.7",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":return ca(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])ca(n);return e}default:return e}})};import{v4 as Nu}from"uuid";var ua={name:"Ensure module steps have ids",fromVersion:"1.0.7",toVersion:"1.0.8",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"MODULE":return e.id||(e.id=Nu()),e;default:return e}})};import{v4 as ma}from"uuid";var pa={name:"Ensure module steps have ids",fromVersion:"1.0.8",toVersion:"1.0.9",recursiveKeys:new Set(["results","steps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return t.id=t.id??ma(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??ma()}})),delete e.commands),e;default:return e}})};var ga={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return typeof t.type!="string"||t.type!=="AI_WAIT"||(t.type="AI_ASSERTION",t.timeout||(t.timeout=10)),e}default:return e}})};var ha={name:"Migrate AI assertions to preset actions",fromVersion:"1.0.0",toVersion:"1.0.1",recursiveKeys:new Set,execute:async r=>r.map(e=>{if(e.type!=="AI_ASSERTION")return e;let n={type:"PRESET_ACTION",command:{type:"AI_ASSERTION",assertion:e.text,useVision:!1,disableCache:!0}},o={...e,...n};return delete o.text,o}),stopOnFailure:!0};var xn=new Set(["CLICK","TYPE","SELECT_OPTION"]),fa={name:"Migrate element descriptor to live in a target object",fromVersion:"1.0.3",toVersion:"1.0.4",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type,o=t?.elementDescriptor;return(o!==void 0||xn.has(n))&&(t.target={elementDescriptor:o??""}),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(i=>{let a=i?.elementDescriptor,l=i?.type;(a!==void 0||xn.has(l))&&(i.target={elementDescriptor:a??""})}),e.results&&Array.isArray(e.results)&&e.results.forEach(i=>{let a=i.command,l=a?.elementDescriptor,c=a?.type;(l!==void 0||xn.has(c))&&(a.target={elementDescriptor:l??""}),i.commands&&Array.isArray(i.commands)&&i.commands.forEach(d=>{let p=d?.elementDescriptor,g=d?.type;(p!==void 0||xn.has(g))&&(d.target={elementDescriptor:p??""})})}),e}),stopOnFailure:!0};var ya={name:"Migrate FAILURE status to FAILED",fromVersion:"1.0.1",toVersion:"1.0.2",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e;return t.status==="FAILURE"&&(t.status="FAILED"),typeof t.commands=="object"&&Array.isArray(t.commands)&&t.commands.forEach(n=>{if(n&&typeof n=="object"){let o=n;o?.status==="FAILURE"&&(o.status="FAILED")}}),t}),stopOnFailure:!0};var Sa={name:"Migrate preset step types to use the same",fromVersion:"1.0.2",toVersion:"1.0.3",recursiveKeys:new Set,execute:async r=>r.map(e=>{let t=e.command,n=t?.type;return n?.startsWith("PRESET_")&&(t.type=n.slice(7)),e.commands&&Array.isArray(e.commands)&&e.commands.forEach(s=>{let i=s.type;i?.startsWith("PRESET_")&&(s.type=i.slice(7))}),e.results&&Array.isArray(e.results)&&e.results.forEach(s=>{let i=s.command,a=i?.type;a?.startsWith("PRESET_")&&(i.type=a.slice(7)),s.commands&&Array.isArray(s.commands)&&s.commands.forEach(c=>{let u=c.type;u?.startsWith("PRESET_")&&(c.type=u.slice(7))})}),e}),stopOnFailure:!0};var kt=[ha,ya,Sa,fa,aa,la,da,ua,pa,ga];if(be!==kt[kt.length-1].toVersion)throw new Error("Please bump LATEST_VERSION in types package after adding a migration");kt.forEach((r,e)=>{if(!In.valid(r.toVersion)||!In.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!In.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(kt[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});function Du(r){return r.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var Uo=async({metadata:r,steps:e,logger:t,toVersion:n})=>{let o=e,{schemaVersion:s,id:i}=r,a=kt.findIndex(u=>In.gt(u.toVersion,s));if(a===-1)return{steps:o,newVersion:s};let l=s;for(let u=a;u<kt.length;u++){if(n&&ku(l,n)){t.debug("Stopping migration early because toVersion was reached");break}let d=kt[u],p={id:i,migration:d.name,toVersion:d.toVersion};try{o=await wa(o,d),l=d.toVersion}catch(g){throw t.error({err:g,...p},"Migration failed"),new Error(`Step migration ${d.name} failed: ${g}`)}}let c=_u(JSON.stringify(e,void 0,2),JSON.stringify(o,void 0,2),{n_surrounding:1});return c.trim()&&t.debug({diffs:c,id:i},"Migration diffs"),{newVersion:l,steps:o}};async function wa(r,e){let t=await e.execute(r);for(let n of t)for(let o of Object.keys(n)){if(!e.recursiveKeys.has(o))continue;let s=n[o];!s||!Array.isArray(s)||Du(s)&&(n[o]=await wa(s,e))}return t}async function ba({rawSteps:r,metadata:e,logger:t,callbacks:n}){ia(e,"defaultOnCloud");let o={},{resolvedSteps:s,newSchemaVersion:i}=await zo({rawSteps:r,metadata:e,logger:t,callbacks:n,resolvedModuleCache:o});return{resolvedTest:{...e,steps:s,schemaVersion:i},moduleIds:Array.from(Object.keys(o))}}async function zo({rawSteps:r,metadata:e,logger:t,callbacks:n,resolvedModuleCache:o={}}){let{newVersion:s,steps:i}=await Uo({metadata:e,steps:r,logger:t}),a;try{a=Me.array().parse(i)}catch(c){throw t.error({type:"zod",err:c,newVersion:s,id:e.id,steps:i},"Failed to parse test steps while migrating test"),new dn(`Failed to parse test steps while migrating test: ${c}`,e.id,"entity",{cause:c})}let l=[];for(let c of a)l.push(await Lr({step:c,callbacks:n,logger:t,resolvedModuleCache:o}));return{resolvedSteps:l,newSchemaVersion:s}}async function Lr({step:r,callbacks:e,logger:t,resolvedModuleCache:n}){switch(r.type){case"AI_ACTION":return r;case"PRESET_ACTION":return r;case"MODULE":{let l=r.moduleId,c=n[l];if(c)return{...c,...r,type:"RESOLVED_MODULE"};let u=await e.onFetchModule({id:l,logger:t});if(!u)throw new Error(`Could not find module with id ${l}`);let{newVersion:d,steps:p}=await Uo({metadata:{id:l,schemaVersion:u.schemaVersion},steps:u.steps,logger:t}),g;try{g=Me.array().parse(p)}catch(f){throw t.error({type:"zod",err:f,steps:p,newVersion:d,id:l},"Module failed to parse"),f}let m;try{m=await Promise.all(g.map(f=>Lr({step:f,callbacks:e,logger:t,resolvedModuleCache:n})))}catch(f){throw t.error({err:f,...r},`Failed to recursively resolve module '${u.name}': ${f}`),f}let h={...u,steps:m};return n[l]=h,{...h,...r,type:"RESOLVED_MODULE"}}case"CONDITIONAL":let o=[];for(let l of r.blocks){let c=[];for(let u of l.steps)c.push(await Lr({step:u,callbacks:e,logger:t,resolvedModuleCache:n}));o.push({...l,steps:c})}let s;if(r.elseSteps){s=[];for(let l of r.elseSteps)s.push(await Lr({step:l,callbacks:e,logger:t,resolvedModuleCache:n}))}return{...r,blocks:o,elseSteps:s};case"SECTION":case"IFRAME":let i=[];for(let l of r.steps)i.push(await Lr({step:l,callbacks:e,logger:t,resolvedModuleCache:n}));return{...r,steps:i};default:return(l=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r)}}import{cloneDeep as Fu}from"lodash-es";import{v4 as Ca}from"uuid";async function He(r){let e=Fu(r.steps);return sr({...r,steps:e,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:new Map,seenModules:new Set})}async function sr({steps:r,...e}){let{seenModules:t,cacheCreationParams:n,moduleIdParents:o,moduleStepParents:s,moduleIdReplacements:i,shouldCreateNewModuleId:a}=e,l={cachesToSave:[],stepsToSave:[],moduleUpdates:[]};for(let c of r)switch(delete c.index,c.type){case"PRESET_ACTION":{let d=c.command;d.id=n?.createNewCacheIds?Ca():d.id,ra(d),"cache"in d&&d.cache&&(n&&(l.cachesToSave=l.cachesToSave.concat(ta({id:d.id,orgId:n.orgId,testId:n.testId,value:At.parse(d),moduleIdParents:o,moduleStepParents:s,skipIntermediateEntries:e.skipCacheIntermediateEntries}))),delete d.cache),l.stepsToSave.push({...c,command:d});break}case"RESOLVED_MODULE":{let d=n?.createNewCacheIds?Ca():c.id,p=c.moduleId;if(i.has(p))p=i.get(p);else if(a){let S=await a(c);i.set(c.moduleId,S)}let{cachesToSave:g,stepsToSave:m,moduleUpdates:h}=await sr({...e,steps:c.steps,cacheCreationParams:n?{...n,createNewCacheIds:!1}:void 0,moduleStepParents:[...s,d],moduleIdParents:[...o,p],skipCacheIntermediateEntries:n?.createNewCacheIds});l.moduleUpdates=l.moduleUpdates.concat(h),l.cachesToSave=l.cachesToSave.concat(g),t.has(p)||(t.add(p),l.moduleUpdates.push({...De.parse(c),steps:Me.array().parse(m)}));let f={type:"MODULE",moduleId:p,inputs:c.inputs,id:d,skipped:c.skipped,cacheConfig:c.cacheConfig};l.stepsToSave.push(f);break}case"AI_ACTION":{if(!c.steps){l.stepsToSave.push(c);break}let{stepsToSave:d,cachesToSave:p}=await sr({...e,steps:c.steps});try{c.steps=Pe.array().parse(d)}catch(g){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${g}`)}l.stepsToSave.push(c),l.cachesToSave=l.cachesToSave.concat(p);break}case"CONDITIONAL":{let d=[];for(let g of c.blocks){let{stepsToSave:m,cachesToSave:h,moduleUpdates:f}=await sr({...e,steps:g.steps});d.push({...g,steps:m}),l.cachesToSave=l.cachesToSave.concat(h),l.moduleUpdates=l.moduleUpdates.concat(f)}let p={...c,elseSteps:void 0,blocks:d};if(c.elseSteps){let{stepsToSave:g,cachesToSave:m,moduleUpdates:h}=await sr({...e,steps:c.elseSteps});p.elseSteps=g,l.cachesToSave=l.cachesToSave.concat(m),l.moduleUpdates=l.moduleUpdates.concat(h)}l.stepsToSave.push(p);break}case"IFRAME":case"SECTION":{let{stepsToSave:d,cachesToSave:p,moduleUpdates:g}=await sr({...e,steps:c.steps}),m={...c,steps:d};l.moduleUpdates=l.moduleUpdates.concat(g),l.stepsToSave.push(m),l.cachesToSave=l.cachesToSave.concat(p);break}default:return(d=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(c)}return l}import{cloneDeep as Uu}from"lodash-es";import{stringify as Bo}from"yaml";async function Ea(r,e=new Set){let t={id:r.id,name:r.name,baseUrl:r.baseUrl,schemaVersion:r.schemaVersion,advanced:r.advanced,retries:r.retries,envs:r.envs},n={},o=await zu(r.steps,r.schemaVersion,n,e),s={fileType:"momentic/test",...t,steps:o};return{test:Bo(s),modules:n}}async function zu(r,e,t,n){let o=Uu(r);Bu(o);let{stepsToSave:s,moduleUpdates:i}=await He({steps:o});for(let a of i)n.has(a.name)||(t[a.name]=$u(a),n.add(a.name));return s}function Bu(r){tt({steps:r,onPresetAction:e=>{e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.index=void 0},onStepContainer:e=>{e.index=void 0}})}function $u(r){let e=De.parse(r),t={fileType:"momentic/module",...e,schemaVersion:be,steps:r.steps};return Bo(t)}function $o(r){return Bo({fileType:"momentic/environment",...r})}var ir=class{constructor(e,t){this.client=e;this.orgId=t}inMemoryCache={};async acquireCacheLock(e){return this.client.acquireCacheLock(e)}async releaseCacheLock(e){return this.client.releaseCacheLock(e)}async setCacheResult(e){return this.client.setCacheResult(e)}async getCacheResult(e){return this.client.getCacheResult(e)}async saveStepCacheEntries(e,t,n){try{await this.client.updateStepCaches({entries:e,testId:t})}catch(o){n.error({err:o},"Failed to save step cache entries")}}async resolveStepCacheEntries(e){let t=await this.client.getStepCacheForTest({testId:e.testId,organizationId:e.organizationId,steps:e.steps,schemaVersion:e.schemaVersion}),{hits:n}=or({steps:e.steps,stepCacheEntries:t,logger:e.logger});this.client.updateCacheLastUsedDate(n,e.logger)}async getOrgId(e){return this.orgId}async uploadScreenshot(e){return(await this.client.uploadScreenshot({screenshot:e.toString("base64")})).key}async fetchEnvironment(e,t,n){try{return await this.client.getEnvironment(t)}catch(o){n.warn({err:o},"Error fetching environment, continuing...");return}}};var Ho="v1",rt=class extends nr{type="API_CLIENT";sms={send:this.sendSms.bind(this),fetchLatest:this.fetchLatestSms.bind(this)};email={fetchLatest:this.fetchLatestEmail.bind(this)};constructor(e){super(e)}async sendSms(e){await this.sendRequest(`/${Ho}/tools/sms/send`,{method:"POST",body:e})}async fetchLatestSms(e){try{return await this.sendRequest(`/${Ho}/tools/sms/fetchLatest`,{method:"POST",body:e})}catch(t){throw t instanceof rr&&t.status===404?new Error("No recent SMS messages found."):t}}async fetchLatestEmail(e){try{return this.sendRequest(`/${Ho}/tools/email/fetchLatest`,{method:"POST",body:e})}catch(t){throw t instanceof rr&&t.status===404?new Error("No matching emails found."):new Error(`Failed to fetch latest emails: ${t.message}`)}}};import{Command as Oh,Option as Ve}from"commander";import xg from"body-parser";import Ig from"cors";import ws from"express";import{existsSync as Gu,readFileSync as On,readdirSync as ju,statSync as Vu,writeFileSync as jo}from"fs";import bt from"path";import{parse as Or,stringify as Ku}from"yaml";var ne=process.env.MOMENTIC_DIR??ht;import{readFileSync as Pr,readdirSync as Wo,writeFileSync as va}from"fs";import Hu,{join as Go}from"path";import{v4 as Wu}from"uuid";import{parse as Ln,stringify as Ra}from"yaml";var wt=Go(ne,ft);function Aa(r){let e=Pn(wt,r.moduleId).path,t=Pr(e,"utf-8"),n=Ln(t),o={fileType:"momentic/module",...n,...r},s=Ra(o);va(e,s,"utf-8")}async function xa(r,e){let t=pe(r),n=Go(wt,`${t}.yaml`),o=Wu(),{stepsToSave:s}=await He({steps:e}),i={fileType:"momentic/module",schemaVersion:be,moduleId:o,name:r,steps:s},a=Ra(i);return va(n,a,"utf-8"),{moduleId:o,name:r,steps:e}}function Ia(){let r=[];for(let e in Wo(wt)){if(!e.endsWith(".yaml"))continue;let t=Pr(e,"utf-8"),n=Ln(t),o={name:n.name,moduleId:n.moduleId,numSteps:n.steps.length};r.push(o)}return r}async function La(r){let e=new Set;for(let t of Wo(wt)){if(!t.endsWith(".yaml"))continue;let n=Go(wt,t),o=Pr(n,"utf-8"),s=Ln(o),i;try{i=vr.parse(s)}catch(a){r.warn({err:a,filePath:t,moduleContents:o},`${t} does not parse as a valid module, skipping...`);continue}e.add(i.moduleId)}return Oa(Array.from(e),r)}function Ta(r,e){let t=Pn(wt,r).path,n=Pr(t,"utf-8"),o=Ln(n);try{return vr.parse(o)}catch(s){throw e.error({err:s,moduleFilePath:t,moduleContents:n},`${t} does not parse as a valid module`),s}}async function Pa(r,e){return(await Oa([r],e)).find(n=>n.moduleId===r)}async function Oa(r,e){let t={};return await Promise.all(r.map(async n=>{let o=Ta(n,e),{resolvedSteps:s}=await zo({rawSteps:o.steps,metadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:t,logger:e,callbacks:{onFetchModule:async i=>Ta(i.id,e)}});t[n]={...o,steps:s}})),Array.from(Object.values(t))}function Pn(r,e){let t=Wo(r);for(let n of t){let o=Hu.join(r,n),s=Pr(o,"utf8");if(s.includes(e))return{path:o,content:s}}throw new Error(`Could not find module file for module ${e} in ${r}`)}var Ma=wn,qu=new Set([...Ma,"node_modules","dist","bin",".git","logs",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"]);async function Na(r,e){let t=await Ea(r);for(let[s,i]of Object.entries(t.modules)){let a=pe(s);jo(bt.join(ne,ft,`${a}.yaml`),i,"utf-8")}let n=pe(e),o=bt.join(ne,`${n}.yaml`);return jo(o,t.test,"utf-8"),`${n}.yaml`}function Mn(r,e){if(!Gu(e))throw new Error(`Test not found at path: ${bt}`);let t=On(e,"utf-8"),o={...Or(t),...r},s=me.parse(o),i={fileType:"momentic/test",...s,steps:o.steps},a=Ku(i);jo(e,a,"utf-8")}function Mr(r,e,t=r){let n=r.split(bt.sep).pop()??"";if(qu.has(n))return Ma.includes(n)||e.warn(`Skipping directory '${r}' because it is likely an artifact folder.`),[];let o=ju(r),s=[];return o.forEach(i=>{let a=bt.join(r,i),l;try{l=Vu(a)}catch(c){e.warn({err:c},`Skipping path '${a}' because it could not be read.`);return}if(l.isDirectory())s=s.concat(Mr(a,e,r));else if(i.endsWith(".yaml")){let c=On(a,"utf-8");try{let u=Or(c),d=me.parse(u);s.push({id:d.id,name:d.name,fullFilePath:a,testPath:bt.relative(bt.resolve(t),bt.resolve(a)),fileName:i,lastModified:l.mtime,createdAt:l.ctime})}catch{e.warn(`Skipping file '${a}' because it does not parse as a valid Momentic test.`)}}}),s}function _a(r){let e;try{e=On(r,"utf8"),e=e.replace(/\r\n|\r/g,`
|
|
11
|
+
`)}catch(n){throw new Error(`Could not read test file ${r}: ${n}`)}let t;try{t=Or(e)}catch(n){throw new Error(`Could not parse test file ${r} as YAML: ${n}`)}return me.parse(t)}function Vo(r,e){let t;try{t=On(r,"utf8"),t=t.replace(/\r\n|\r/g,`
|
|
12
|
+
`)}catch(a){throw new Error(`Could not read test file ${r}: ${a}`)}let n=new Set,o=/moduleId: (.*)/g,s;for(;(s=o.exec(t))!==null;)n.add(s[1].trim());let i={};return n.size>0&&n.forEach(a=>{i[a]||(i[a]=Pn(e,a).content)}),{test:t,modules:i}}async function Nn(r,e,t){let{test:n,modules:o}=Vo(r,e),s=Or(n);if(!s.steps||!Array.isArray(s.steps))throw new Error(`Test ${r} is missing steps`);let i;try{i=me.parse(s)}catch(c){throw new Error(`Test ${r} is missing metadata or has invalid metadata: ${c}`)}let a={};for(let[c,u]of Object.entries(o)){let d;try{d=Or(u)}catch(p){throw new Error(`Module ${c} is not valid YAML: ${p}`)}try{let p=vr.parse(d);a[c]=p}catch(p){throw new Error(`Module ${c} is missing metadata or has invalid metadata: ${p}`)}}let{resolvedTest:l}=await ba({rawSteps:s.steps,metadata:i,logger:t,callbacks:{onFetchModule:async({id:c})=>a[c]}});return l}import{existsSync as Yu,readFileSync as Xu,readdirSync as Ju}from"fs";import{join as ka}from"path";import{parse as Qu}from"yaml";var Ko=ka(ne,Qt);function Da(){let r=[];if(!Yu(Ko))return[];for(let e of Ju(Ko)){if(!e.endsWith(".yaml"))continue;let t=ka(Ko,e),n=Xu(t,"utf-8"),o=Qu(n);try{let s=Ae.parse(o);r.push(s)}catch(s){Li.warn({err:s},"Error parsing environment, skipping...")}}return r}import{existsSync as Lg,statSync as Pg}from"fs";import Og from"http";import Mg from"open";import Ng from"path";import{Server as pg}from"socket.io";import{cloneDeep as Zu}from"lodash-es";var qo=r=>{let e=[];for(let t of r){let n;switch(t.type){case"PRESET_ACTION":{n={before:t.beforeTestContext,after:t.afterTestContext};break}case"CONDITIONAL":case"IFRAME":case"SECTION":case"AI_ACTION":case"MODULE":{n={before:t.beforeTestContext,after:t.afterTestContext,nestedResults:qo(t.results)};break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}e.push(n)}return e},Nr=class{results;constructor(){this.results=[]}setResults(e){this.results=qo(e)}setIndividualResult(e,t){let n=qo([e])[0],o=this.results;for(let i=0;i<t.length-1;i++){let a=t[i];o[a]===void 0&&(o[a]={nestedResults:[]});let l=o[a];l.nestedResults===void 0&&(l.nestedResults=[]),o=l.nestedResults}let s=t[t.length-1];o[s]=n}getContextCopyAtIndices(e){let t=this.getContextAtIndicesHelper(e);if(t!==void 0)return Zu(t)}getContextAtIndicesHelper(e){let t=this.results;for(let o=0;o<e.length-1;o++){let s=e[o],i=t[s];if(i===void 0)return t.length>0?t[t.length-1].after:void 0;if(i.nestedResults===void 0)return i.before;t=i.nestedResults}let n=e[e.length-1];if(n>t.length&&(n=t.length),n===0)return t[0]?.before;for(let o=n-1;o>=0;o--)if(t[o]?.after)return t[o].after}};var Fa={showOverlay:!1},Yo=class{sessions=new Map;sessionCountByIp=new Map;getCurrentConnectionsByIp(e){return this.sessionCountByIp.get(e)??0}getCurrentSessionsByIp(){return Object.fromEntries(this.sessionCountByIp)}reserveCapacityByIp(e){e&&this.sessionCountByIp.set(e,(this.sessionCountByIp.get(e)??0)+1)}releaseCapacityByIp(e){e&&this.sessionCountByIp.set(e,Math.max(this.getCurrentConnectionsByIp(e)-1,0))}registerSession({controller:e,context:t,cleanup:n,clientIp:o,sessionId:s,browserbaseSessionId:i}){return this.sessions.set(s,{controller:e,context:t,cleanup:n,clientIp:o,executionCancelled:!1,resultsManager:new Nr,browserbaseSessionId:i,browserBehavior:Fa}),s}removeSession(e,t){(async()=>{try{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:s}=o;await s.browser.cleanup(),await o.cleanup?.(),this.sessions.delete(e)}catch(o){t.error({err:o},"Error cleaning up session in global state manager")}})()}getSession(e){return this.sessions.get(e)}cancelExecution(e){let t=this.sessions.get(e);t&&(t.executionCancelled=!0)}resumeExecution(e){let t=this.sessions.get(e);t&&(t.executionCancelled=!1)}},N=new Yo;var em=200;function Ua(r,e,t){let n=Date.now(),o=-1,s=0,i=Date.now(),a,l,c=async p=>{if(!p.closed){if(s>0&&Math.random()>=1/Math.max(s,8)){s<8&&t.error({sessionId:e},"Dropping screenshot due to previous failures");return}try{(!a||!l||Date.now()-i>=1e3)&&(a=await p.getViewport(),l=await p.getFrameSrcUrls(),i=Date.now()),r.emit("browserState",{viewport:a,buffer:await p.screenshot({retries:0,timeout:1e3,scale:"device",quality:75}),url:p.url(),iframeSrcUrls:l}),n=Date.now(),s=0}catch(g){if(!r.connected)return;let m=g instanceof Error?g.message:`${g}`;if(m.includes("Frame was detached")||m.includes("Not attached to an active page")||m.includes("browser has been closed"))return;s++,t.error({err:g,sessionId:e},"Error taking screenshot")}finally{r.connected&&Date.now()-n>15e3&&Date.now()-o>3e4&&(t.error({sessionId:e},"Screenshots to client are stale"),o=Date.now())}}},u={timer:void 0},d=()=>{let g=N.getSession(e)?.controller?.browser;if(!g||g.closed){t.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(u.timer);return}c(g)};return u.timer=setInterval(d,em),u}var tm=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async()=>{if(e.info({sessionId:t},"Cancel event received"),!N.getSession(t))throw new Error("No active session found");N.cancelExecution(t)}},za={event:"cancel",createHandler:tm};var rm=({metadata:r,logger:e})=>{let{sessionId:t}=r;return n=>{e.info({sessionId:t,reason:n},`Disconnect event received (${n})`),N.removeSession(t,e)}},Ba={event:"disconnect",createHandler:rm};import{diff as xm}from"deep-object-diff";import{spawn as nm}from"child_process";async function $a(r){return new Promise((e,t)=>{let n={stdio:"inherit",env:process.env,detached:!0},o=nm("bash",["-c",r],n),s=!1;process.on("exit",()=>o.pid!==void 0&&!s&&process.kill(-o.pid)),o.on("close",i=>{if(s=!0,i===0){e();return}t(`command exited with code ${i}`)})})}async function _r(r,e,t,n,o){try{let[s,i]=await Promise.all([e?n(e):void 0,t?n(t):void 0]);r.beforeScreenshot=s,r.afterScreenshot=i}catch(s){o.debug({err:s},"Error saving screenshot to S3")}}var Ha=async r=>{let e=r.step,{logger:t,controller:n,context:o}=r.fixtures,{takeScreenshots:s}=r.options,{testMetadata:i}=r.inputs,a=r.callbacks.test,l=n.browser.url(),c=new Date,u;if(s)try{u=await n.browser.screenshot({retries:1,clearHighlights:!0})}catch(h){t.debug({err:h},"Failed to take screenshot before step, likely because the page is still loading. This is non-fatal and does not affect the test.")}let d,p,g,m=Tn();try{let h=await n.executePresetStep(m,e.command,o,i.advanced.disableAICaching,r.callbacks.test.isExecutionCancelled);if(h.beforeScreenshotOverride&&(u=h.beforeScreenshotOverride),g=h.afterScreenshotOverride,h.fail)throw new R("ActionFailureError",h.thoughts||"Preset action failed.");let f=new Date,S=n.browser.url();p={beforeUrl:l,afterUrl:S,startedAt:c,finishedAt:f,viewport:await n.browser.getViewport(),status:"SUCCESS"},d={...e,message:h.thoughts??"Successfully executed preset action.",finishedAt:f,startedAt:c,status:"SUCCESS",data:h.data,results:[p],details:m.details},"assertion"in e.command&&(d.message=h.thoughts||"Assertion passed."),(e.command.type==="AI_EXTRACT"||e.command.type==="JAVASCRIPT")&&e.command.envKey&&o.setVariable(e.command.envKey,d.data)}catch(h){t.error({err:h},`Failed executing preset step ${St(e.command)}`);let f=new Date,S=h instanceof Error?h.message:`${h}`;p={beforeUrl:l,afterUrl:n.browser.url(),startedAt:c,finishedAt:f,viewport:await n.browser.getViewport(),status:h instanceof $e?"CANCELLED":"FAILED",message:S},d={...e,startedAt:c,finishedAt:f,status:h instanceof $e?"CANCELLED":"FAILED",message:S,failureReason:h instanceof R?h.reason:void 0,results:[p],details:m.details}}if(s&&!g)try{g=await n.browser.screenshot({retries:1})}catch(h){t.debug({err:h},"Failed to take screenshot after step, likely because the page is still loading. This is non-fatal and does not affect the test.")}return _r(p,u,g,a.onSaveScreenshot,t),d};import Xo from"os";function Wa(r){let e=()=>{try{let t=om(),n=sm();r.debug({memory:t,cpu:n},"Got machine cpu usage metrics")}catch{}};return e(),setInterval(e,3e4)}function om(){let r=Xo.totalmem(),e=Xo.freemem(),t=r-e;return{totalMemory:r,freeMemory:e,usedMemory:t}}function sm(){let r=Xo.cpus(),e=0,t=0,n=0,o=0,s=0,i=0;for(let a of r)e+=a.times.user,t+=a.times.nice,n+=a.times.sys,o+=a.times.idle,s+=a.times.irq;return i=e+t+n+o+s,{user:e/i*100,nice:t/i*100,sys:n/i*100,idle:o/i*100,irq:s/i*100,total:100-o/i*100}}import{randomUUID as gm}from"crypto";import{faker as im}from"@faker-js/faker";import am from"assert";import lm from"axios";import cm from"moment";import dm,{TimeoutError as um}from"p-timeout";import mm from"pg";var pm=Object.getPrototypeOf(async function(){}).constructor;async function Ga(r,e,t){let n=e.code;e.options.fragment&&(n=`return ${e.code}`);let{results:o,env:s,inputs:i}=e.bindings,a=e.tools,l={},c=(f,S)=>{s[f]=S,l[f]=S},u;n.includes("Octokit")&&(u=(await import("@octokit/rest")).Octokit);let d;n.includes("createAppAuth")&&(d=(await import("@octokit/auth-app")).createAppAuth);let p=async()=>await Promise.resolve(new pm("axios","moment","faker","assert","pg","Octokit","createAppAuth","env","results","inputs","setVariable","sendSms","waitForLatestSms","email","sms",n)(lm,cm,im,am,mm,u,d,s,o,i??{},c,S=>a.sms.send(S),S=>a.sms.fetchLatest(S),a.email,a.sms)),g=!0,m,h;try{m=await dm(p(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`}),t.debug(`[${r}] Got execution result: ${JSON.stringify(m)}`),t.debug(`[${r}] Got variable updates: ${JSON.stringify(l)}`)}catch(f){t.error(`[${r}] Error executing code: ${f}`),g=!1,f instanceof um?h=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:h=f instanceof Error?f.message:`${f}`}return{result:m,variableUpdates:l,success:g,error:h}}async function ja({code:r,fragment:e,context:t,localTools:n,logger:o,timeoutMs:s=si}){let i=gm();return Ga(i,{code:r,options:{fragment:e,timeoutMs:s},bindings:t.toObjectCopy(),tools:n},o)}var cR=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT;var mR=process.env.MAILINATOR_API_KEY;import hR from"p-timeout";import"twilio";var NR=!!(process.env.MAILINATOR_API_KEY&&!1);async function ar(r){let e;if(r.localTools)e=await ja({...r,localTools:r.localTools});else throw new Error("No code evaluation environment available");if(e.error)throw new Error(`Code evaluation returned error: ${e.error}`);if(e.variableUpdates)for(let[t,n]of Object.entries(e.variableUpdates))r.context.setVariable(t,n);return e.result}async function lr(r){let{s:e,context:t,logger:n,timeoutMs:o=5e3,retries:s=1}=r,i=/{{(.*?)}}/g,a=e.matchAll(i),l=e;for(let c of a){if(c.length<2)continue;let u=c[1].trim(),d;try{d=await ar({code:u,fragment:!0,context:t,timeoutMs:o,logger:n,retries:s,localTools:r.localTools})}catch(g){throw n.error({err:g,value:e},"Error evaluating template string"),g}let p=typeof d=="string"?d:`${d}`;l=l.replace(c[0],p)}return l}import{last as fm}from"lodash-es";var Va=async r=>{let{step:e,resolvedInputs:t}=r.moduleParams,{logger:n,context:o,storage:s,codeEvalTools:i}=r.fixtures,{orgId:a,testMetadata:l}=r.inputs;Object.keys(t).length>0&&(o.setInputs(t),n.debug({inputs:t,moduleId:e.moduleId},"Set module inputs"));let c,u;if(e.cacheConfig){let d=await lr({s:e.cacheConfig.cacheKey||e.defaultCacheKey||"",context:o,logger:n,localTools:i}),p={orgId:a,cacheKeys:[d,...Object.entries(t).map(([m,h])=>`${m}:${h}`)]},g=Date.now();for(;Date.now()-g<Pi;){let m=await s.getCacheResult(p);if(m){n.info({cacheResult:m},"Got result from module execution cache"),c=_n(e,"SUCCESS"),c.message="Used cached module result.",c.data=JSON.parse(m);break}let h=await s.acquireCacheLock({keyParams:p,clientMetadata:`testId:${l.id}`});if(h.acquired){n.info({cacheKeyPrefix:u},"Acquired cache lock and proceeding with module execution"),u=h.keyPrefix;break}await new Promise(f=>setTimeout(f,2500+Math.random()*1e4))}}try{c||(c=await ym(r))}finally{if(u!==void 0){let d=e.cacheConfig.cacheExpiryMs;d===gi&&(d=e.defaultCacheTtl??hi),c&&c.status==="SUCCESS"&&await s.setCacheResult({result:JSON.stringify(c.data===void 0?"":c.data),keyPrefix:u,ttlMs:d}),await s.releaseCacheLock(u)}}return c},ym=async r=>{let{step:e}=r.moduleParams,t=_n(e,"SUCCESS"),{status:n,results:o}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:`module ('${e.name}')`}});return t.results=o,t.status=n,t.finishedAt=new Date,t.data=fm(t.results)?.data,t};function _n(r,e){return{type:"MODULE",id:r.id,moduleId:r.moduleId,moduleName:r.name,startedAt:new Date,inputs:r.inputs,cacheConfig:r.cacheConfig,results:[],finishedAt:new Date,status:e}}async function Ka(r,e,t,n){let o={};try{for(let s of r.parameters??[]){let i=r.inputs?.[s]??r.defaultParameters?.[s];if(!i){t.warn(`No value or default found for parameter '${s}' that is required by module '${r.name}'`);continue}o[s]=await ar({code:i,fragment:!0,context:e,logger:t,localTools:n})}return o}catch(s){throw new R("UserConfigurationError",`Failed to evaluate module inputs: ${s}`)}}async function Dt(r,e){let t=new Date;try{return await e()}catch(n){let o=new Date,s;if(n instanceof R?s=`${n}`:s=`An unexpected error occurred: ${n.message}`,r.type==="RESOLVED_MODULE"){let i=_n(r,"FAILED");return i.message=s,i.startedAt=t,i.finishedAt=o,i}return{...r,startedAt:t,finishedAt:o,status:"FAILED",data:null,message:s,results:[]}}}import{randomUUID as Ya}from"crypto";var Xa=async r=>{let e=r.aiStepParams.step,t=e.index,{testMetadata:n,steps:o}=r.inputs,{takeScreenshots:s}=r.options,{controller:i,context:a,logger:l}=r.fixtures,{test:c,step:u}=r.callbacks;if(t===void 0)throw new Error("Attempted to execute AI action step without index");i.resetHistory();let d={...e,startedAt:new Date,finishedAt:new Date,results:[],status:"RUNNING",beforeTestContext:a.toRedactedDisplayCopy()};e.steps=e.steps||[];let p=e.steps&&e.steps.length>0&&e.steps[e.steps.length-1]?.command.type==="SUCCESS";if(p)try{let{status:m,results:h}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"AI action"}});return d.finishedAt=new Date,d.status=m,d.results=h,d}catch(m){l.warn({err:m},"Failed executing saved AI action steps, attempting to re-generate...")}e.steps=[];let g=0;try{for(;;){if(g>12)throw new Error(`Exceeded max number of commands per step (${12})`);let m=t+g+1;if(c.isExecutionCancelled?.())return d.status="CANCELLED",d.finishedAt=new Date,u.onCancelled?.({index:m,message:d.message||"AI step cancelled.",output:d}),d;let h,f=new Date,S=a.toRedactedDisplayCopy(),w;if(s)try{w=await i.browser.screenshot({clearHighlights:!0})}catch(C){l.debug({err:C},"Failed to take screenshot before AI command, likely because the page is still loading. This is non-fatal.")}l.info(`Generating new sub-command ${g} within AI step`);let b;try{if(b=await i.promptToCommand(e.type,e.text,n.advanced.disableAICaching),b.command.type==="FAILURE")throw new Error(b.command.thoughts);h=b.command,l.debug({command:h},"Generated new command")}catch(C){if(l.error({err:C,commandIndex:g},"Failed to generate command within AI step"),g===0)throw C;{let A="Stopping command generation prematurely since no progress can be made";l.info({command:h},A),h={id:Ya(),type:"SUCCESS",thoughts:A}}}let T={type:"PRESET_ACTION",index:m,command:h};wm({newStep:T,controller:i,currentStep:e,pageContext:b?.context,logger:l,onCommandExecuted:u.onCommandExecuted,currentIndex:g,globalSubStepIndex:m}),u.onCommandGenerated?.({index:m,step:T,message:Po[h.type]||`Unknown command (${h.type})`});let v={beforeUrl:i.browser.url(),startedAt:f,viewport:await i.browser.getViewport(),finishedAt:new Date,status:"SUCCESS"};l.info(`Executing sub-command ${g} within AI step: ${St(h)}`);try{let C=await i.executeCommand(h,a,p&&n.advanced.disableAICaching,p);l.info(`AI sub-command ${g} completed successfully`),v.elementInteracted=C.elementInteracted;let A;if(s)try{A=await i.browser.screenshot({})}catch(L){l.debug({err:L},"Failed to take screenshot after AI command, likely because the page is still loading. This is non-fatal.")}v.afterUrl=i.browser.url(),v.finishedAt=new Date,_r(v,w,A,c.onSaveScreenshot,l);let x={status:"SUCCESS",startedAt:v.startedAt,finishedAt:v.finishedAt,data:C.data,results:[v],beforeTestContext:S,afterTestContext:a.toRedactedDisplayCopy(),...T};if(d.results.push(x),e.steps[g]=T,bm(o,r.inputs,m),u.onCommandExecuted?.({index:m,output:{...x,message:h.thoughts??C.thoughts??"Successfully executed preset action."},step:T}),h.type==="SUCCESS"){d.finishedAt=new Date,d.status="SUCCESS",d.message=C.thoughts??"All commands completed.",d.afterTestContext=a.toRedactedDisplayCopy();break}if(C.succeedImmediately&&!p){d.finishedAt=new Date,d.status="SUCCESS",d.message=`Marked step as completed due to reason: ${C.succeedImmediatelyReason}`,d.afterTestContext=a.toRedactedDisplayCopy(),h={id:Ya(),type:"SUCCESS",thoughts:C.succeedImmediatelyReason};let L={type:"PRESET_ACTION",command:h};e.steps.push(L),u.onCommandExecuted?.({index:m+1,output:{...x,message:d.message},step:L}),d.results.push({...x,...L});break}}catch(C){let A=C instanceof Error?C.message:`${C}`,x=C instanceof R?C.reason:void 0;v.status="FAILED",v.message=A,v.finishedAt=new Date,v.afterUrl=i.browser.url();let L;try{L=await i.browser.screenshot({})}catch(ve){l.debug({err:ve},"Failed to take screenshot after AI command error, likely because the page is still loading. This is non-fatal.")}_r(v,w,L,c.onSaveScreenshot,l);let H={status:"FAILED",startedAt:v.startedAt,finishedAt:v.finishedAt,type:"PRESET_ACTION",results:[v],message:A,failureReason:x,command:h};d.results.push(H),d.status="FAILED",d.finishedAt=new Date,d.message=A,d.failureReason=x;break}g++}}catch(m){d.message=m instanceof Error?m.message:`${m}`,d.finishedAt=new Date,d.status="FAILED"}return d.status==="SUCCESS"?(d.data=d.results[d.results.length-1]?.data,u.onSuccess?.({index:t,message:d.message||"AI step succeeded.",output:d})):u.onFailure?.({index:t,message:d.message||"AI step errored.",output:d}),d};async function Sm(r,e,t){let n=t.id;if(!n||t.id<=0)throw new Error("Attempted to get reverse mapping for command with no a11y id target");return r.getReverseMappedTarget(e,n,!0)}async function wm({controller:r,currentIndex:e,globalSubStepIndex:t,currentStep:n,newStep:o,pageContext:s,onCommandExecuted:i,logger:a}){if(!s)return;let l=o.command;if("target"in l&&l.target&&"cache"in l&&l.cache){await new Promise(c=>setTimeout(()=>c(),100));try{let c=await Sm(r,s,l.cache.target);l.target={elementDescriptor:c,type:"description"},n.steps[e]=o,i?.({index:t,step:o})}catch(c){a.warn({err:c,currentIndex:e,currentStep:n},"Failed to generate element description, continuing...")}}}function bm(r,e,t){vn(r),e.toIndex&&e.toIndex>=t&&e.toIndex++}import{last as Cm}from"lodash-es";async function Ja(r){let{step:e}=r.conditionalParams,{logger:t,controller:n,context:o}=r.fixtures,s=new Date,i=e.elseSteps,a=!0,l=Tn();for(let p=0;p<e.blocks.length;p++){t.info(`Evaluating condition ${p} in conditional step`);let g=e.blocks[p];try{await n.executePresetStep(l,g.assertion.command,o,!1),t.info(`Condition ${p} resolved to true, executing the corresponding ${g.steps.length} steps`),a=!1,i=g.steps}catch(m){t.info({err:m},`Condition ${p} resolved to false`)}}if(i)a&&t.info("No conditions resolved to true, executing the else block steps");else return t.warn("No conditions resolved to true and no else block was provided, causing the entire conditional step to be skipped"),{...e,status:"SUCCESS",startedAt:s,results:[],finishedAt:new Date,details:l.details};t.info(`Executing ${i.length} steps in the selected conditional block`);let c=await r.executeStepList({...r,listParams:{steps:i,containerName:"conditional block"}}),d={...e,...c,startedAt:s,finishedAt:new Date};return d.data=Cm(c.results)?.data,d}import{last as Em}from"lodash-es";async function Qa(r){let{step:e}=r.frameParams,t=new Date,n=r.fixtures.controller.browser.getActiveFrame();r.fixtures.controller.browser.setActiveFrame(e.identifier);let o;try{o=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"frame step list"}})}finally{r.fixtures.controller.browser.setActiveFrame(n)}let i={...e,...o,startedAt:t,finishedAt:new Date};return i.data=Em(o.results)?.data,i}import{last as Tm}from"lodash-es";async function Za(r){let{step:e}=r.sectionParams,t=new Date,n=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"section step list"}}),s={...e,...n,startedAt:t,finishedAt:new Date};return s.data=Tm(n.results)?.data,s}async function Ft(r){let{results:e=[],containerName:t,steps:n}=r.listParams,{logger:o,context:s,controller:i,codeEvalTools:a}=r.fixtures,{step:l,test:c}=r.callbacks,{fromIndex:u,toIndex:d}=r.inputs,p="SUCCESS",g,m=0;for(m;m<n.length;m++){let h=n[m],f=sa(h),S=h.index;if(S===void 0)throw new Error(`Executing step without index: ${f}`);if(d&&S>d)break;if(c.isExecutionCancelled?.()){if(p="CANCELLED",l.onCancelled?.({index:S,output:{status:"CANCELLED",message:"Execution cancelled.",startedAt:new Date,finishedAt:new Date}}),e.length){let v=e[e.length-1];v.status="CANCELLED",v.message="Cancelled by user signal.",g=v}break}if(h.skipped)continue;if(u&&S<u&&(h.type==="PRESET_ACTION"||An([h])<u))continue;o.info(`Executing step ${m+1}/${n.length} in ${t}: ${f}`),l.onStarted?.(S);let w=s.toRedactedDisplayCopy(),b,T;switch(h.type){case"PRESET_ACTION":{b="Preset action",T=await Dt(h,()=>Ha({...r,step:h}));break}case"AI_ACTION":{b="AI action",T=await Dt(h,()=>Xa({...r,aiStepParams:{step:h},executeStepList:Ft}));break}case"RESOLVED_MODULE":{b=`Module (${h.name})`;let C=new ge({baseUrl:i.browser.baseURL,currentUrl:i.browser.url(),dynamicVariables:s.getDynamicVariablesCopy(),variablesFromEnvironment:s.getVariablesFromEnvironmentCopy(),envName:s.getEnvName()});T=await Dt(h,async()=>{let A=await Ka(h,s,o,a);return Va({...r,executeStepList:Ft,fixtures:{...r.fixtures,context:C},moduleParams:{step:h,resolvedInputs:A}})});break}case"CONDITIONAL":{b="Conditional step",T=await Dt(h,()=>Ja({...r,conditionalParams:{step:h},executeStepList:Ft}));break}case"IFRAME":{b="Frame step",T=await Dt(h,()=>Qa({...r,frameParams:{step:h},executeStepList:Ft}));break}case"SECTION":{b="Section",T=await Dt(h,()=>Za({...r,sectionParams:{step:h},executeStepList:Ft}));break}default:return(C=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(h)}if(T.beforeTestContext=w,s.setResult(m,T.data),s.setUrl(i.browser.url()),T.afterTestContext=s.toRedactedDisplayCopy(),Rm(b,S,T,r.callbacks,o,r.work),e.push(T),T.status!=="SUCCESS"){p=T.status,g=T;break}}return{status:p,results:e,terminalResult:g}}async function vm(r,e,t){if(r)try{await e?.({status:"RUNNING",results:r.results})}catch(n){t.error({err:n},"Error updating global run status")}}function Rm(r,e,t,n,o,s){let{step:i,test:a}=n,l=r.toLowerCase(),c=r.charAt(0).toUpperCase()+r.slice(1);switch(t.status){case"SUCCESS":i.onSuccess?.({index:e,command:"command"in t?t.command:void 0,message:t.message??`${c} executed successfully.`,output:hn.parse(t)});break;case"FAILED":i.onFailure?.({index:e,message:t.message??`${c} failed.`,output:hn.parse(t)});break;case"CANCELLED":i.onCancelled?.({index:e,message:t.message??`${c} cancelled.`,output:hn.parse(t)});break;default:throw new Error(`Unexpected ${l} status: ${t.status}`)}t.status==="SUCCESS"&&s&&vm(s,a.onUpdateRun,o)}var kr=async r=>{r.fixtures.logger=r.fixtures.logger.child({orgId:r.inputs.orgId,runId:r.inputs.runId,testId:r.inputs.testMetadata.id});let e;e=Wa(r.fixtures.logger),vn(r.inputs.steps);let t;try{return t=await Am(r),t}finally{if(clearInterval(e),oa(r.inputs.steps),await r.callbacks.test.onTestComplete?.(),t?.status==="PASSED")try{await r.callbacks.test.onTestSuccess?.(r.inputs.steps)}catch(n){r.fixtures.logger.warn({err:n},"Error running test success handler, continuing...")}}},Am=async r=>{let{runId:e,testMetadata:t,fromIndices:n,toIndices:o,indicesFilter:s,steps:i}=r.inputs,{logger:a}=r.fixtures;a.info(`Starting run ${e} for test '${t.name}'`);let l=i,c="test";if(n){let m=Rn(i,n);if(!m)throw new Error(`Could not find starting step using indices: ${n}`);r.inputs.fromIndex=m.index,a.debug({fromIndices:n,fromStep:m},"Identified starting step using fromIndices"),c="partial steps list"}if(o){let m=Rn(i,o);if(!m)throw new Error(`Could not find step at indices: ${o}`);let h=An([m]);r.inputs.toIndex=h,a.debug({toIndices:o,toStep:m,maxIndexUnderToStep:h},"Identified ending step using toIndices"),c="partial steps list"}if(s){let m=Rn(i,s);if(!m)throw new Error(`Could not find ending step at indices: ${r.inputs.indicesFilter}`);l=[m],a.debug({steps:i,indicesFilter:s},"Filtered steps to run based on exact indices filter"),c="filtered step"}await r.callbacks.test.onUpdateRun?.({status:"RUNNING",startedAt:new Date});let u=[],d={results:u},{status:p,terminalResult:g}=await Ft({...r,work:d,listParams:{steps:l,containerName:c,results:u}});if(r.options.takeScreenshots&&await new Promise(m=>setTimeout(m,2e3)),s&&u.length){let m=u[0];if(m.beforeTestContext&&m.afterTestContext){let h=ge.fromSnapshot({snapshot:m.beforeTestContext,environmentVariables:r.fixtures.context.getVariablesFromEnvironmentCopy()}),f=r.fixtures.context.getResult(0);h.setResult(s[s.length-1],f),m.afterTestContext={...m.afterTestContext,results:h.getResultsCopy()}}}return await r.callbacks.test.onUpdateRun?.({status:p==="SUCCESS"?"PASSED":"FAILED",finishedAt:new Date,results:u}),p==="FAILED"?{status:"FAILED",results:u,failedStepResult:g}:{status:"PASSED",results:u}};import{cloneDeep as Im}from"lodash-es";var Jo={currentlyExecutingRequests:{}},Lm=r=>async(e,t)=>{let n,{testId:o}=r.metadata,{baseUrl:s}=e,i=`${o}|${s}`;try{let a=Jo.currentlyExecutingRequests[i]??0;Jo.currentlyExecutingRequests[i]=a+1,n=await Pm({...r,...e,done:t})}finally{r.logger.info({result:n,sessionId:r.metadata.sessionId},"Test execution complete"),Jo.currentlyExecutingRequests[i]--}},Pm=async({socket:r,steps:e,baseUrl:t,testMetadata:n,reInitialize:o,indicesFilter:s,toIndices:i,fromIndices:a,storage:l,metadata:c,logger:u,envName:d,environmentVariables:p,authorization:g,done:m})=>{let{testId:h,sessionId:f,orgId:S}=c,w=f,b=N.getSession(f);if(!b)throw new Error("No active session found");N.resumeExecution(f);let{controller:T,context:v}=b;T.setOpen(),u=u.child({testId:h,orgId:S,baseUrl:t,sessionId:f,runId:w}),u.info({steps:e.map(W=>`${W.type}${"command"in W?` - ${W.command.type}`:""}`),indicesFilter:s,fromIndices:a,toIndices:i,reInitialize:o,envName:d,baseUrl:t},"Starting execution"),u.debug({steps:e,context:v,flags:T.flagStore.getAllFlags()},"Execution parameters");let C=async()=>{if(o){let W={url:t,clearCookies:!0,clearStorage:!0};await T.resetState(W),T.setOpen(),v.reset({baseUrl:t,currentUrl:T.browser.url(),variablesFromEnvironment:p??{},envName:d})}},A=async()=>{try{await l.resolveStepCacheEntries({schemaVersion:be,organizationId:S,testId:h,steps:e,logger:u})}catch(W){u.error({err:W},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};await Promise.all([C(),A()]);let x=Im(e),L={takeScreenshots:!1},H={orgId:S,runId:w,testMetadata:n,steps:e,indicesFilter:s,fromIndices:a,toIndices:i},ve={controller:T,context:v,storage:l,codeEvalTools:g?.type==="API_KEY"?new rt(g):void 0,logger:u},O=(W,jt)=>{r.emit(jt,W)},Ke={test:{onTestComplete:async()=>{r.emit("finished")},onSaveScreenshot:Om,isExecutionCancelled:()=>N.getSession(f)?.executionCancelled||T.browser.closed||T.isClosed()||r.disconnected,onTestSuccess:async W=>{let jt=xm(x,W);if(Object.keys(jt).length>0){u.debug({changes:jt},"Updating steps post-run success");let{cachesToSave:fr}=await He({steps:e,cacheCreationParams:{testId:h,orgId:S}});try{await l.saveStepCacheEntries(fr,n.id,u)}catch(Zr){u.warn({err:Zr},"Failed to save step cache entries after execution success")}}}},step:{onStarted:W=>r.emit("started",{globalIndex:W}),onSuccess:W=>O(W,"success"),onFailure:W=>O(W,"failure"),onCancelled:W=>O(W,"cancelled"),onCommandGenerated:W=>{r.emit("commandGenerated",{...W,message:W.message??"AI action sub-step generated"})},onCommandExecuted:W=>{r.emit("commandExecuted",W)}}};if(s?.length){u.info({indicesFilter:s},"Starting individual step");let W=b.resultsManager.getContextCopyAtIndices(s)??v.toObjectCopy(),jt=ge.fromSnapshot({snapshot:W,environmentVariables:v.getVariablesFromEnvironmentCopy()}),fr=await kr({fixtures:{...ve,context:jt},options:L,callbacks:Ke,inputs:H}),Zr=fr.results[0];return Zr?b.resultsManager.setIndividualResult(Zr,s):u.warn(fr,"No result found for individual step"),fr.status}let mt=await kr({fixtures:ve,options:L,callbacks:Ke,inputs:H});return b.resultsManager.setResults(mt.results),m?.(mt),mt.status},Om=async r=>r.toString("base64");var el={event:"execute",createHandler:Lm};var Mm=({metadata:r,logger:e,storage:t})=>{let{sessionId:n}=r;return async(o,s)=>{let{command:i,testMetadata:a,returnScreenshot:l,indices:c}=o,u=Ar(i,o.description);e.debug({description:u,params:o},"Locate handler params"),e.info({description:u},"Locate handler called");let d=N.getSession(n);if(!d)throw new Error("No active session found");let{controller:p,context:g}=d,m=d.resultsManager.getContextCopyAtIndices(c)??g.toObjectCopy(),h=ge.fromSnapshot({snapshot:m,environmentVariables:g.getVariablesFromEnvironmentCopy()}),f=Ot.parse(a.advanced??{}),S={},w;if(u){if("useSelector"in i&&i.useSelector)try{let b=await p.locateElementWithSelector(u,"iframeUrl"in i?i.iframeUrl:void 0);w=b.resolution.locator,S={target:b.target,thoughts:b.thoughts}}catch(b){e.warn({err:b},"Failed resolving target with selector"),s({err:`Failed locating element with CSS selector: ${b.message}`,decisions:b instanceof Ye?b.decisions:void 0});return}else try{let b=await p.locateElement({description:u,disableCache:f.disableAICaching,iframeUrl:"iframeUrl"in i?i.iframeUrl:void 0,testContext:h,returnConflicts:!0});S={target:b.target,thoughts:b.thoughts},w=b.resolution.locator}catch(b){e.warn({err:b},"Failed locating element with AI"),s({err:`Failed locating element with AI: ${b.message}`});return}if(i.type==="SELECT_OPTION"&&w)try{S.options=await p.browser.getSelectOptions(w)}catch(b){e.warn({err:b},"Failed getting select options"),s({err:`Failed getting select options: ${b.message}`});return}e.info({result:S},"Locate handler result")}if(l)try{let{buffer:b,width:T,height:v}=await p.screenshotWithDimensions({scale:"css",clearHighlights:!0,target:S?.target,hideCaret:!0}),C=await t.uploadScreenshot(b);S.screenshot={data:C,width:T,height:v}}catch(b){e.error({err:b},"Error capturing screenshot during locate"),s({err:`Error taking screenshot: ${b.message}`});return}if(s({result:S}),w)try{await Promise.all([p.browser.scrollIntoView(w),p.browser.highlightTarget(w)])}catch(b){e.warn({err:b},"Error highlighting element, continuing...")}}},tl={event:"locate",createHandler:Mm};var Nm=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async({percentX:n,percentY:o},s)=>{let i=N.getSession(t);if(!i)throw new Error("No active session found");let a=i.controller.browser;try{await a.clickMouseFromPositionPercentages(n,o)}catch(l){e.error({err:l},"Error performing click during cloud recording in control mode"),s({err:l.message})}}},rl={event:"cloudClick",createHandler:Nm};var _m=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async(n,o)=>{let s=N.getSession(t);if(!s)throw new Error("No active session found");let{controller:i}=s;s.browserBehavior.showOverlay=!0;try{let a=await i.browser.captureTargetFromClick();o({result:a})}catch(a){e.error({err:a},"Record click failed"),o({err:a instanceof Error?a.message:`${a}`})}finally{s.browserBehavior.showOverlay=!1}}},nl={event:"recordTargetClick",createHandler:_m};var km=({metadata:r,logger:e})=>{let{sessionId:t}=r,n,o=0,s=(a,l)=>{let c=async()=>{n=void 0;try{await a.highlightFromPositionPercentages(l),o=0}catch(u){e.error({err:u},"Error highlighting element on mouse move"),o++}};clearTimeout(n),n=setTimeout(c,50*(o+1))},i=0;return async a=>{let l=N.getSession(t);if(!l)throw new Error("No active session found");let{controller:c,browserBehavior:u}=l,d=c.browser;if(!d.closed){if(d.getActivePage().isClosed()){e.warn("Ignoring mouse move because the page is closed");return}u.showOverlay&&s(d,a);try{await d.moveMouseFromPositionPercentages(a.percentX,a.percentY),i=0}catch(p){i++,i%5===0&&e.warn({err:p,mouseErrors:i},"Error in socket mouse move handler")}}}},ol={event:"cloudMouseMove",createHandler:km};var Dm=({metadata:r})=>{let{sessionId:e}=r;return async({percentDeltaX:t,percentDeltaY:n})=>{let o=N.getSession(e);if(!o)throw new Error("No active session found");let s=o.controller.browser;if(s.closed)return;let i=await s.scrollFromPositionPercentages(t,n);if(!i)return;let a=o.browserBehavior.recordingState?.transformer;a&&a.recordScroll({...i,url:s.url()})}},sl={event:"cloudScroll",createHandler:Dm};var Fm=({metadata:r,generator:e,socket:t,storage:n,logger:o})=>{let{sessionId:s,orgId:i,testId:a}=r;return async({indices:l})=>{let c=N.getSession(s);if(!c)throw new Error("No active session found");let{controller:u,browserBehavior:d}=c;o.info("Starting cloud recording");let p=await u.startRecordMode({generator:e,initialIndices:l,storage:n,logger:o,testId:a,orgId:i,onStepRecord:(g,m)=>{t.emit("stepRecorded",{step:g,indices:m})}});d.recordingState={transformer:p},d.showOverlay=!0}},il={event:"cloudStartRecording",createHandler:Fm};var Um=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async()=>{let n=N.getSession(t);if(!n)throw new Error("No active session found");e.info("Stopping cloud recording"),await n.controller.stopRecordMode(),n.browserBehavior.recordingState=void 0,n.browserBehavior.showOverlay=!1}},al={event:"cloudStopRecording",createHandler:Um};var zm=["Dead","Meta","AudioVolumeUp","AudioVolumeDown"],Bm=({metadata:r})=>{let{sessionId:e}=r;return async({key:t})=>{let n=N.getSession(e);if(!n)throw new Error("No active session found");if(zm.includes(t))return;let{controller:o}=n;t.length>1?await o.browser.press(t):await o.browser.type(t,{clearContent:!1,pressKeysSequentially:!0})}},ll={event:"cloudType",createHandler:Bm};var Dr={vimiumJs:'var K=Object.defineProperty;var P=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var F=(t,e,n)=>e in t?K(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,D=(t,e)=>{for(var n in e||(e={}))z.call(e,n)&&F(t,n,e[n]);if(P)for(var n of P(e))B.call(e,n)&&F(t,n,e[n]);return t};var g=(t,e,n)=>(F(t,typeof e!="symbol"?e+"":e,n),n);var _=(t,e,n)=>new Promise((o,r)=>{var i=s=>{try{d(n.next(s))}catch(l){r(l)}},a=s=>{try{d(n.throw(s))}catch(l){r(l)}},d=s=>s.done?o(s.value):Promise.resolve(s.value).then(i,a);d((n=n.apply(t,e)).next())});var E=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=E);var k={create(t,e,n,o){return{bottom:o,top:e,left:t,right:n,width:n-t,height:o-e}},copy(t){return{bottom:t.bottom,top:t.top,left:t.left,right:t.right,width:t.width,height:t.height}},translate(t,e,n){return e==null&&(e=0),n==null&&(n=0),{bottom:t.bottom+n,top:t.top+n,left:t.left+e,right:t.right+e,width:t.width,height:t.height}},subtract(t,e){return e=this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom)),e.width<0||e.height<0?[k.copy(t)]:[this.create(t.left,t.top,e.left,e.top),this.create(e.left,t.top,e.right,e.top),this.create(e.right,t.top,t.right,e.top),this.create(t.left,e.top,e.left,e.bottom),this.create(e.right,e.top,t.right,e.bottom),this.create(t.left,e.bottom,e.left,t.bottom),this.create(e.left,e.bottom,e.right,t.bottom),this.create(e.right,e.bottom,t.right,t.bottom)].filter(o=>o.height>0&&o.width>0)},intersects(t,e){return t.right>e.left&&t.left<e.right&&t.bottom>e.top&&t.top<e.bottom},intersectsStrict(t,e){return t.right>=e.left&&t.left<=e.right&&t.bottom>=e.top&&t.top<=e.bottom},equals(t,e){for(let n of["top","bottom","left","right","width","height"])if(t[n]!==e[n])return!1;return!0},intersect(t,e){return this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom))}};var N={_browserInfoLoaded:!0,_firefoxVersion:null,_isFirefox:!1,isFirefox(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._isFirefox},firefoxVersion(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._firefoxVersion},isString(t){return typeof t=="string"||t instanceof String}};var f={isReady(){return document.readyState!=="loading"},documentReady:function(){let t=document.readyState!=="loading",e=[];if(!t){let n;globalThis.addEventListener("DOMContentLoaded",n=E(function(){globalThis.removeEventListener("DOMContentLoaded",n,!0),t=!0;for(let o of e)o();e=null}),!0)}return function(n){if(t)return n();e.push(n)}}(),documentComplete:function(){let t=document.readyState==="complete",e=[];if(!t){let n;globalThis.addEventListener("load",n=E(function(o){if(o.target===document){globalThis.removeEventListener("load",n,!0),t=!0;for(let r of e)r();e=null}}),!0)}return function(n){t?n():e.push(n)}}(),createElement(t){let e=document.createElement(t);return e instanceof HTMLElement?(this.createElement=n=>document.createElement(n),e):(this.createElement=n=>document.createElementNS("http://www.w3.org/1999/xhtml",n),this.createElement(t))},addElementsToPage(t,e){let n=this.createElement("div");e.id!=null&&(n.id=e.id),e.className!=null&&(n.className=e.className);for(let o of t)n.appendChild(o);return document.body.appendChild(n),n},removeElement(t){return t.parentNode.removeChild(t)},isTopFrame(){return globalThis.top===globalThis.self},makeXPath(t){let e=[];for(let n of t)e.push(".//"+n,".//xhtml:"+n);return e.join(" | ")},evaluateXPath(t,e){let n=document.webkitIsFullScreen?document.webkitFullscreenElement:document.documentElement,o=function(r){return r==="xhtml"?"http://www.w3.org/1999/xhtml":null};return document.evaluate(t,n,o,e,null)},getVisibleClientRect(t,e){let n;e==null&&(e=!1);let o=(()=>{let i=[];for(n of t.getClientRects())i.push(k.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),a=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>a,a};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let a of Array.from(t.children)){i=window.getComputedStyle(a,null);let d=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(d)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(a,!0);if(!(s===null||s.width<3||s.height<3))return s}else{if(n=this.cropRectToVisible(n),n===null||n.width<3||n.height<3||(i=window.getComputedStyle(t,null),i.getPropertyValue("visibility")!=="visible"))continue;return n}}return null},cropRectToVisible(t){let e=k.create(Math.max(t.left,0),Math.max(t.top,0),t.right,t.bottom);return e.top>=window.innerHeight-4||e.left>=window.innerWidth-4?null:e},getClientRectsForAreas(t,e){let n=[];for(let o of e){let r,i,a,d,s=o.coords.split(",").map(p=>parseInt(p,10)),l=o.shape.toLowerCase();if(["rect","rectangle"].includes(l))s.length==4&&([r,a,i,d]=s);else if(["circle","circ"].includes(l)){if(s.length==3){let[p,w,v]=s,u=v/Math.sqrt(2);r=p-u,i=p+u,a=w-u,d=w+u}}else l==="default"?s.length==2&&([r,a,i,d]=[0,0,t.width,t.height]):s.length>=4&&([r,a,i,d]=s);let c=k.translate(k.create(r,a,i,d),t.left,t.top);c=this.cropRectToVisible(c),c&&!isNaN(c.top)&&!isNaN(c.left)&&!isNaN(c.width)&&!isNaN(c.height)&&n.push({element:o,rect:c})}return n},isSelectable(t){if(!(t instanceof Element))return!1;let e=["button","checkbox","color","file","hidden","image","radio","reset","submit"];return t.nodeName.toLowerCase()==="input"&&e.indexOf(t.type)===-1||t.nodeName.toLowerCase()==="textarea"||t.isContentEditable},isEditable(t){return this.isSelectable(t)||(t.nodeName!=null?t.nodeName.toLowerCase():void 0)==="select"},isEmbed(t){let e=t.nodeName!=null?t.nodeName.toLowerCase():null;return["embed","object"].includes(e)},isFocusable(t){return t&&(this.isEditable(t)||this.isEmbed(t))},isDOMDescendant(t,e){let n=e;for(;n!==null;){if(n===t)return!0;n=n.parentNode}return!1},isSelected(t){let e=document.getSelection();if(t.isContentEditable){let n=e.anchorNode;return n&&this.isDOMDescendant(t,n)}else if(f.getSelectionType(e)==="Range"&&e.isCollapsed){let n=e.anchorNode.childNodes[e.anchorOffset];return t===n}else return!1},simulateSelect(t){if(t===document.activeElement&&f.isEditable(document.activeElement))return handlerStack.bubbleEvent("click",{target:t});if(t.focus(),t.tagName.toLowerCase()!=="textarea"||t.value.indexOf(`\n`)<0)try{if(t.selectionStart===0&&t.selectionEnd===0)return t.setSelectionRange(t.value.length,t.value.length)}catch(e){}},simulateClick(t,e){e==null&&(e={});let n=["mouseover","mousedown","mouseup","click"],o=[];for(let r of n){let i=this.simulateMouseEvent(r,t,e);o.push(i)}return o},simulateMouseEvent(t,e,n){if(n==null&&(n={}),t==="mouseout"){if(e==null&&(e=this.lastHoveredElement),this.lastHoveredElement=void 0,e==null)return}else t==="mouseover"&&(this.simulateMouseEvent("mouseout",void 0,n),this.lastHoveredElement=e);let o=new MouseEvent(t,{bubbles:!0,cancelable:!0,composed:!0,view:window,detail:1,ctrlKey:n.ctrlKey,altKey:n.altKey,shiftKey:n.shiftKey,metaKey:n.metaKey});return e.dispatchEvent(o)},simulateClickDefaultAction(t,e){let n;if(e==null&&(e={}),(t.tagName!=null?t.tagName.toLowerCase():void 0)!=="a"||!t.href)return;let{ctrlKey:o,shiftKey:r,metaKey:i,altKey:a}=e;KeyboardUtils.platform==="Mac"?n=i===!0&&o===!1:n=i===!1&&o===!0,n?chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:r===!0}):r===!0&&i===!1&&o===!1&&a===!1?chrome.runtime.sendMessage({handler:"openUrlInNewWindow",url:t.href}):t.target==="_blank"&&chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:!0})},simulateHover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseover",t,e)},simulateUnhover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseout",t,e)},addFlashRect(t){let e=this.createElement("div");return e.classList.add("vimiumReset"),e.classList.add("vimiumFlash"),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.width=t.width+"px",e.style.height=t.height+"px",document.documentElement.appendChild(e),e},getViewportTopLeft(){let t=document.documentElement,e=getComputedStyle(t),n=t.getBoundingClientRect();if(e.position==="static"&&!/content|paint|strict/.test(e.contain||"")){let o=parseInt(e.marginTop),r=parseInt(e.marginLeft);return{top:-n.top+o,left:-n.left+r}}else{let o,r;return N.isFirefox()?(r=parseInt(e.borderTopWidth),o=parseInt(e.borderLeftWidth)):{clientTop:r,clientLeft:o}=t,{top:-n.top-r,left:-n.left-o}}},suppressPropagation(t){t.stopImmediatePropagation()},suppressEvent(t){t.preventDefault(),this.suppressPropagation(t)},consumeKeyup:function(){let t=null;return function(e,n=null,o){if(!e.repeat){t!=null&&handlerStack.remove(t);let{code:r}=e;t=handlerStack.push({_name:"dom_utils/consumeKeyup",keyup(i){return i.code!==r||(this.remove(),o?f.suppressPropagation(i):f.suppressEvent(i)),handlerStack.continueBubbling},blur(i){return i.target===window&&this.remove(),handlerStack.continueBubbling}})}return typeof n=="function"&&n(),o?(f.suppressPropagation(e),handlerStack.suppressPropagation):(f.suppressEvent(e),handlerStack.suppressEvent)}}(),getSelectionType(t){return t==null&&(t=document.getSelection()),t.type?t.type:t.rangeCount===0?"None":t.isCollapsed?"Caret":"Range"},getElementWithFocus(t,e){let n,o=n=t.getRangeAt(0);f.getSelectionType(t)==="Range"&&(o=n.cloneRange(),o.collapse(e)),n=o.startContainer,n.nodeType===1&&(n=n.childNodes[o.startOffset]);let r=n;for(;r&&r.nodeType!==1;)r=r.previousSibling;return n=r||(n!=null?n.parentNode:void 0),n},getSelectionFocusElement(){let t=window.getSelection(),e=t.focusNode;return e==null?null:(e===t.anchorNode&&t.focusOffset===t.anchorOffset&&(e=e.childNodes[t.focusOffset]||e),e.nodeType!==Node.ELEMENT_NODE?e.parentElement:e)},getContainingElement(t){return(typeof t.getDestinationInsertionPoints=="function"?t.getDestinationInsertionPoints()[0]:void 0)||t.parentElement},windowIsTooSmall(){return window.innerWidth<3||window.innerHeight<3},injectUserCss(){let t=document.createElement("style");t.type="text/css",t.textContent=Settings.get("userDefinedLinkHintCss"),document.head.appendChild(t)}};var O={MAX_CONTENT_LENGTH:1e3,MAX_ATTRIBUTE_LENGTH:500,MAX_NUM_DATA_ATTRIBUTES:10,commonAttributes:["id","className","title","aria-label","aria-labelledby"],attributeNamesMapping:new Map([["a",["href","title","rel","target"]],["label",["for"]],["input",["type","name","placeholder","checked","maximumLength"]],["textarea",["placeholder","maximumLength"]],["button",["type"]],["select",["name","multiple"]],["div",["role"]],["iframe",["src"]],["img",["src","alt"]]]),describe(t){var r,i;let e={};this.addAttributes(t,this.commonAttributes,e);let n=((i=(r=t.tagName).toLowerCase)==null?void 0:i.call(r))||"";this.attributeNamesMapping.has(n)&&this.addAttributes(t,this.attributeNamesMapping.get(n),e),this.addDataAttrs(t,e);let o=this.getContent(t);return this.additionalHandling(t,D({tag:n,attributes:e},o&&{content:o}))},getContent(t){var n,o;let e=((o=(n=t.tagName).toLowerCase)==null?void 0:o.call(n))||"";return["input","textarea"].includes(e)?t.value:["div","iframe","img","body"].includes(e)?null:(["a","button","select","label"].includes(e),t.innerText)},additionalHandling(t,e){var o,r;if((((r=(o=t.tagName).toLowerCase)==null?void 0:r.call(o))||"")=="label"&&t.hasAttribute("for")){let i=t.getAttribute("for"),a=document.getElementById(i);a&&(e.target=this.describe(a))}return e},addAttributes(t,e,n){n||(n={});for(let o of e)t.hasAttribute(o)&&(n[o]=t.getAttribute(o).substring(0,this.MAX_ATTRIBUTE_LENGTH));return n},addDataAttrs(t,e){let n=0;for(let o in t.dataset)if(e[`data-${o}`]=t.dataset[o].substring(0,this.MAX_ATTRIBUTE_LENGTH),n++,n>this.MAX_NUM_DATA_ATTRIBUTES)return e;return e}};var x=null,C=()=>G()||document.scrollingElement||document.body,W=function(t){return t?t<0?-1:1:0},U={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},X=function(t,e,n){if(N.isString(n)){let o=n;return o==="viewSize"&&t===C()?e==="x"?window.innerWidth:window.innerHeight:t[U[e][o]]}else return n},V=function(t,e,n){let o=U[e].axisName,r=t[o];if(t.scrollBy){let i={behavior:"instant"};i[e==="x"?"left":"top"]=n,t.scrollBy(i)}else t[o]+=n;return t[o]!==r},q=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},T=function(t,e,n,o){let r=o*X(t,e,n)||-1;return r=W(r),V(t,e,r)&&V(t,e,-r)},$=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),T(t,e,n,o)&&q(t,e)},j=function(t=null){let e;if(!t){let n=C();if(T(n,"y",1,1)||T(n,"y",-1,1))return n;t=document.body||C()}if(T(t,"y",1,1)||T(t,"y",-1,1))return t;{let n=Array.from(t.children).map(o=>({element:o,rect:f.getVisibleClientRect(o)})).filter(o=>o.rect);n.map(o=>o.area=o.rect.width*o.rect.height);for(e of n.sort((o,r)=>r.area-o.area)){let o=j(e.element);if(o)return o}return null}},L={init(){x=null},isScrollableElement(t){return x||(x=C()&&j()||C()),t!==x&&$(t)}},G=function(){let t=J[window.location.host];if(t)return document.querySelector(t)},J={"twitter.com":"div.permalink-container div.permalink[role=main]","reddit.com":"#overlayScrollContainer","new.reddit.com":"#overlayScrollContainer","www.reddit.com":"#overlayScrollContainer","web.telegram.org":".MessageList"};window.Scroller=L;var A=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",E(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",E(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:A});var R=class{constructor(e){g(this,"element");g(this,"image");g(this,"rect");g(this,"linkText");g(this,"showLinkText");g(this,"reason");g(this,"secondClassCitizen");g(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},M={getLocalHintsForElement(t){var p,w,v;let e=((w=(p=t.tagName).toLowerCase)==null?void 0:w.call(p))||"",n=!1,o=!1,r=!1,i=[],a=[],d=null;if(e==="img"){let u=t.getAttribute("usemap");if(u){let h=t.getClientRects();u=u.replace(/^#/,"").replace(\'"\',\'\\\\"\');let m=document.querySelector(`map[name="${u}"]`);if(m&&h.length>0){n=!0;let y=m.getElementsByTagName("area"),S=f.getClientRectsForAreas(h[0],y);S=S.map(I=>Object.assign(I,{image:t})),a.push(...S)}}}let s=t.getAttribute("aria-disabled");if(s&&["","true"].includes(s.toLowerCase()))return[];if(this.checkForAngularJs||(this.checkForAngularJs=function(){if(document.getElementsByClassName("ng-scope").length===0)return()=>!1;{let h=[];for(let m of["","data-","x-"])for(let y of["-",":","_"])h.push(`${m}ng${y}click`);return function(m){for(let y of h)if(m.hasAttribute(y))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let u=t.getAttribute("role"),h=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(u!=null&&h.includes(u.toLowerCase()))n=!0;else{let m=t.getAttribute("contentEditable");m!=null&&["","contenteditable","true","plaintext-only"].includes(m.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let u=t.getAttribute("jsaction").split(";");for(let h of u){let m=h.trim().split(":");if(m.length>=1&&m.length<=2){let[y,S,I]=m.length===1?["click",...m[0].trim().split("."),"_"]:[m[0],...m[1].trim().split("."),"_"];n||(n=y==="click"&&S!=="none"&&I!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||(n=!t.disabled&&!t.readOnly);break;case"input":n||(n=!(((v=t.getAttribute("type"))==null?void 0:v.toLowerCase())=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t)));break;case"button":case"select":n||(n=!t.disabled);break;case"object":case"embed":n=!0;break;case"label":n||(n=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0);break;case"body":n||(n=t===document.body&&!A()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?d="Frame.":void 0),n||(n=t===document.body&&A()&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"img":n||(n=["zoom-in","zoom-out"].includes(t.style.cursor));break;case"div":case"ol":case"ul":n||(n=t.clientHeight<t.scrollHeight&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"details":n=!0,d="Open.";break}let l=t.getAttribute("class");!n&&(l!=null&&l.toLowerCase().includes("button"))&&(n=!0,r=!0);let c=t.getAttribute("tabindex"),b=c?parseInt(c):-1;if(!n&&!(b<0)&&!isNaN(b)&&(n=!0,o=!0),n)if(a.length>0){let u=a.map(h=>new R({element:h.element,image:t,rect:h.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:d}));i.push(...u)}else{let u=f.getVisibleClientRect(t,!0);if(u!==null){let h=new R({element:t,rect:u,secondClassCitizen:o,possibleFalsePositive:r,reason:d});i.push(h)}}return i},getElementFromPoint(t,e,n,o){n==null&&(n=document),o==null&&(o=[]);let r=n.elementsFromPoint?n.elementsFromPoint(t,e)[0]:n.elementFromPoint(t,e);return o.includes(r)?r:(o.push(r),r&&r.shadowRoot?M.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,l)=>{l==null&&(l=[]);for(let c of Array.from(s.querySelectorAll("*")))l.push(c),c.shadowRoot&&e(c.shadowRoot,l);return l},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let l=this.getLocalHintsForElement(s);o.push(...l)}o=o.reverse();let r=[1,2,3];o=o.filter((s,l)=>{if(!s.possibleFalsePositive)return!0;let b=Math.max(0,l-6);for(;b<l;){let p=o[b].element;for(let w of r)if(p=p==null?void 0:p.parentElement,p===s.element)return!1;b+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let l=s.rect,c=M.getElementFromPoint(l.left+l.width*.5,l.top+l.height*.5);if(c&&(s.element.contains(c)||c.contains(s.element))||s.element.localName=="area"&&c==s.image)return!0;let p=[l.top+.1,l.bottom-.1],w=[l.left+.1,l.right-.1];for(let v of p)for(let u of w){let h=M.getElementFromPoint(u,v);if(h&&(s.element.contains(h)||h.contains(s.element)))return!0}});i.reverse();let{top:a,left:d}=f.getViewportTopLeft();for(let s of i)s.rect.top+=a,s.rect.left+=d;return i}};var H=class{constructor(){this.hints=null;this.hintMarkers=null;this.markersDiv=null;this.enrichedMarkers=null}reset(){this.removeMarkers(),this.hints=null,this.hintMarkers=null,this.markersDiv=null}capture(){return _(this,null,function*(){this.reset(),this.createMarkers(),this.displayMarkers()})}createMarkers(){this.hints=M.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{var i,a;let o=f.createElement("div"),r=(a=(i=e.element.attributes["data-momentic-id"])==null?void 0:i.value)!=null?a:void 0;if(!r){console.warn(`[MOMENTIC] No data-momentic-id found for interactive element ${e.element.outerHTML}`);return}o.style.left=e.rect.left+"px",o.style.top=e.rect.top+"px",o.style.zIndex=214e7+n,o.className="vimiumReset internalVimiumHintMarker vimiumHintMarker",Z(o,r),this.hintMarkers.set(r,{hint:e,marker:o})})}enrichMarkers(){if(this.hintMarkers){this.enrichedMarkers=[];for(let[e,n]of this.hintMarkers)this.enrichedMarkers.push(Object.assign(O.describe(n.hint.element),{hintString:e}))}}displayMarkers(){this.hintMarkers&&(this.markersDiv||(this.markersDiv=f.addElementsToPage(Array.from(this.hintMarkers.values()).map(e=>e.marker),{id:"vimiumHintMarkerContainer",className:"vimiumReset"})))}removeMarkers(){this.markersDiv&&(f.removeElement(this.markersDiv),this.markersDiv=null)}toggleMarkers(){this.markersDiv?this.removeMarkers():this.displayMarkers()}},Z=(t,e)=>{for(let n of e){let o=document.createElement("span");o.className="vimiumReset",o.textContent=n,t.appendChild(o)}};window.HintManager=H;\n',vimiumCss:'.vimiumReset,a.vimiumReset,a:hover.vimiumReset,a:link.vimiumReset,a:visited.vimiumReset,div.vimiumReset,span.vimiumReset,table.vimiumReset,td.vimiumReset,tr.vimiumReset{background:none;border:none;bottom:auto;box-shadow:none;color:#000;cursor:auto;display:inline;float:none;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:inherit;font-style:normal;font-variant:normal;font-weight:400;height:auto;left:auto;letter-spacing:0;line-height:100%;margin:0;max-height:none;max-width:none;min-height:0;min-width:0;opacity:1;padding:0;position:static;right:auto;text-align:left;text-decoration:none;text-indent:0;text-shadow:none;text-transform:none;top:auto;vertical-align:baseline;white-space:normal;width:auto;z-index:2140000000}tbody.vimiumReset,thead.vimiumReset{display:table-header-group}tbody.vimiumReset{display:table-row-group}div.internalVimiumHintMarker{background:linear-gradient(180deg,#fff785 0,#ffc542);border:1px solid #c38a22;border-radius:3px;box-shadow:0 3px 7px 0 rgba(0,0,0,.3);display:block;font-size:11px;left:-1px;overflow:hidden;padding:1px 3px 0;position:absolute;top:-1px;white-space:nowrap}div.internalVimiumHintMarker span{color:#302505;font-family:Helvetica,Arial,sans-serif;font-size:11px;font-weight:700;text-shadow:0 1px 0 hsla(0,0%,100%,.6)}div.internalVimiumHintMarker>.matchingCharacter{color:#d4ac3a}div>.vimiumActiveHintMarker span{color:#a07555!important}div.internalVimiumInputHint{background-color:rgba(255,247,133,.3);border:1px solid #c38a22;display:block;pointer-events:none;position:absolute}div.internalVimiumSelectedInputHint{background-color:hsla(0,100%,70%,.3);border:1px solid #933!important}div.internalVimiumSelectedInputHint span{color:#fff!important}div.vimiumHighlightedFrame{border:5px solid #ff0;box-sizing:border-box;margin:0;pointer-events:none}div.vimiumHighlightedFrame,iframe.vimiumHelpDialogFrame{height:100%;left:0;padding:0;position:fixed;top:0;width:100%}iframe.vimiumHelpDialogFrame{background-color:hsla(0,0%,4%,.6);border:none;display:block;z-index:2139999997}div#vimiumHelpDialogContainer{background-color:#fff;border:2px solid #b3b3b3;border-radius:6px;margin:50px auto;max-height:calc(100% - 100px);max-width:calc(100% - 100px);opacity:1;overflow-x:auto;overflow-y:auto;width:840px}div#vimiumHelpDialog{min-width:600px;padding:8px 12px}span#vimiumTitle,span#vimiumTitle *,span#vimiumTitle span{font-size:20px}#vimiumTitle{display:block;line-height:130%;white-space:nowrap}td.vimiumHelpDialogTopButtons{text-align:right;width:100%}#helpDialogOptionsPage,#helpDialogWikiPage{font-size:14px;padding-left:5px;padding-right:5px}div.vimiumColumn{float:left;font-size:11px;line-height:130%;width:50%}div.vimiumColumn tr{display:table-row}div.vimiumColumn td{display:table-cell;font-size:11px;line-height:130%}div.vimiumColumn table,div.vimiumColumn td,div.vimiumColumn tr{margin:0;padding:0}div.vimiumColumn table{table-layout:auto;width:100%}div.vimiumColumn td{padding:1px;vertical-align:top}div#vimiumHelpDialog div.vimiumColumn tr>td:first-of-type{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;text-align:right;white-space:nowrap}span.vimiumHelpDialogKey{background-color:#f3f3f3;border:1px solid;border-color:#ccc #ccc #bbb;border-radius:3px;box-shadow:inset 0 -1px 0 #bbb;color:#212121;font-family:monospace;font-size:11px;margin-left:2px;padding:1px 4px}div#vimiumHelpDialog div.vimiumColumn tr>td:nth-of-type(3){width:100%}div#vimiumHelpDialog div.vimiumDivider{background-color:#9a9a9a;display:block;height:1px;margin:10px auto;width:100%}div#vimiumHelpDialog td.vimiumHelpSectionTitle{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:16px;font-weight:700;padding-top:3px}div#vimiumHelpDialog td.vimiumHelpDescription{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px}div#vimiumHelpDialog span.vimiumCopyCommandNameName{cursor:pointer;font-size:12px;font-style:italic}div#vimiumHelpDialog tr.advanced{display:none}div#vimiumHelpDialog.showAdvanced tr.advanced{display:table-row}div#vimiumHelpDialog div.advanced td:nth-of-type(3){color:#555}div#vimiumHelpDialog a.closeButton{color:#555;cursor:pointer;font-family:courier new;font-size:24px;font-weight:700;padding-left:5px;position:relative;text-decoration:none;top:3px}div#vimiumHelpDialog a{text-decoration:underline}div#vimiumHelpDialog a.closeButton:hover{color:#000;-webkit-user-select:none}div#vimiumHelpDialogFooter{display:block;margin-bottom:37px;position:relative}table.helpDialogBottom{width:100%}td.helpDialogBottomRight{float:right;text-align:right;width:100%}td.helpDialogBottomLeft,td.helpDialogBottomRight{padding:0}div#vimiumHelpDialogFooter *{font-size:10px}a#toggleAdvancedCommands,span#help-dialog-tip{font-size:10px;position:relative;top:19px;white-space:nowrap}a#toggleAdvancedCommands,a:active.vimiumHelDialogLink,a:hover.vimiumHelDialogLink,a:link.vimiumHelDialogLink,a:visited.vimiumHelDialogLink{color:#2f508e;cursor:pointer;text-decoration:underline}div.vimiumHUD{background:#f1f1f1;border:1px solid #aaa;border-radius:4px;bottom:8px;box-shadow:0 2px 10px rgba(0,0,0,.8);display:block;left:8px;position:fixed;text-align:left;width:calc(100% - 20px);z-index:2139999999}iframe.vimiumHUDFrame{background-color:transparent;border:none;bottom:-14px;display:block;height:58px;margin:0 0 0 -40%;min-width:300px;opacity:0;overflow:hidden;padding:0;position:fixed;right:20px;width:20%;z-index:2139999998}div.vimiumHUD .vimiumHUDSearchArea{background-color:#f1f1f1;border-radius:4px 4px 0 0;display:block;padding:3px}div.vimiumHUD .vimiumHUDSearchAreaInner{border-radius:3px;box-sizing:border-box;color:#777;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;height:30px;line-height:20px;margin-bottom:0;outline:none;padding:2px 4px;width:100%}div.vimiumHUD .hud-find{background:#fff;border:1px solid #ccc}div.vimiumHUD span#hud-find-input,div.vimiumHUD span#hud-match-count{color:#000;display:inline;outline:none;overflow-y:hidden;white-space:nowrap}div.vimiumHUD span#hud-find-input:before{content:"/"}div.vimiumHUD span#hud-match-count{color:#aaa;font-size:12px}div.vimiumHUD span#hud-find-input br{display:none}div.vimiumHUD span#hud-find-input *{display:inline;white-space:nowrap}body.vimiumFindMode ::selection{background:#ff9632}iframe.vomnibarFrame{background-color:transparent;border:none;display:block;font-family:sans-serif;height:calc(100% - 70px);left:50%;margin:0 0 0 -40%;min-width:400px;overflow:hidden;padding:0;position:fixed;top:70px;width:calc(80% + 20px);z-index:2139999998}div.vimiumFlash{background-color:transparent;box-shadow:0 0 4px 2px #4183c4;padding:1px;position:absolute;z-index:2140000000}iframe.vimiumUIComponentHidden{display:none}iframe.vimiumUIComponentVisible{color-scheme:light dark;display:block}iframe.vimiumUIComponentReactivated{border:5px solid #ff0}iframe.vimiumNonClickable{pointer-events:none}@media (prefers-color-scheme:dark){iframe.reverseDarkReaderFilter{-webkit-filter:invert(100%) hue-rotate(180deg)!important;filter:invert(100%) hue-rotate(180deg)!important}body.vimiumBody{background-color:#292a2d;color:#fff}body.vimiumBody a,body.vimiumBody a:visited{color:#8ab4f8}body.vimiumBody input,body.vimiumBody textarea{background-color:#1d1d1f;border-color:#1d1d1f;color:#e8eaed}body.vimiumBody div.example{color:#9aa0a6}body.vimiumBody div#footer,body.vimiumBody div#state,div#vimiumHelpDialogContainer{background-color:#202124;border-color:hsla(0,0%,100%,.1)}div#vimiumHelpDialog{background-color:#292a2d;color:#fff}div#vimiumHelpDialog td.vimiumHelpDescription{color:#c9cccf}div#vimiumHelpDialog td.vimiumHelpSectionTitle,span#vimiumTitle{color:#fff}#vimiumTitle>span:first-child{color:#8ab4f8!important}div#vimiumHelpDialog a{color:#8ab4f8}div#vimiumHelpDialog div.vimiumDivider{background-color:hsla(0,0%,100%,.1)}span.vimiumHelpDialogKey{background-color:#1d1d1f;border:1px solid #000;box-shadow:none;color:#fff}}',htmlUtilsLibJs:`var __defProp = Object.defineProperty;
|
|
10
13
|
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
11
14
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
12
15
|
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
@@ -65,24 +68,33 @@ var __yieldStar = (value) => {
|
|
|
65
68
|
|
|
66
69
|
// src/html/cache.ts
|
|
67
70
|
function generateHtmlCacheAttributes(dataMomenticId) {
|
|
68
|
-
var _a, _b, _c
|
|
71
|
+
var _a, _b, _c;
|
|
69
72
|
const customWindow = window;
|
|
70
|
-
const
|
|
73
|
+
const warnings = [];
|
|
71
74
|
const ele = (_a = customWindow.findElementInBodyOrShadowDom) == null ? void 0 : _a.call(customWindow, dataMomenticId);
|
|
72
75
|
if (!ele) {
|
|
73
|
-
|
|
74
|
-
\`
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
}
|
|
78
|
-
try {
|
|
79
|
-
result.generatedSelectors = (_b = customWindow.generateCssSelectors) == null ? void 0 : _b.call(customWindow, dataMomenticId);
|
|
80
|
-
} catch (err) {
|
|
81
|
-
console.error(\`[MOMENTIC] Error generating CSS selectors: \${err}\`);
|
|
76
|
+
return {
|
|
77
|
+
error: \`Could not find element with data-momentic-id: \${dataMomenticId}\`,
|
|
78
|
+
warnings
|
|
79
|
+
};
|
|
82
80
|
}
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
81
|
+
const {
|
|
82
|
+
selectors,
|
|
83
|
+
error: cssError,
|
|
84
|
+
warnings: cssWarnings
|
|
85
|
+
} = customWindow.generateCssSelectors(dataMomenticId);
|
|
86
|
+
warnings.push(...cssWarnings);
|
|
87
|
+
if (cssError) {
|
|
88
|
+
return { error: cssError, warnings };
|
|
89
|
+
}
|
|
90
|
+
return {
|
|
91
|
+
warnings,
|
|
92
|
+
attributes: {
|
|
93
|
+
generatedSelectors: selectors,
|
|
94
|
+
serializedHtml: (_b = customWindow.serializeElementWithContext) == null ? void 0 : _b.call(customWindow, ele),
|
|
95
|
+
nodeOnlySerializedHtml: (_c = customWindow.serializeElementOnlyWithText) == null ? void 0 : _c.call(customWindow, ele)
|
|
96
|
+
}
|
|
97
|
+
};
|
|
86
98
|
}
|
|
87
99
|
function addGenerateHtmlCacheAttributesScript() {
|
|
88
100
|
const customWindow = window;
|
|
@@ -122,7 +134,13 @@ var momenticConstants = {
|
|
|
122
134
|
"::marker",
|
|
123
135
|
"noscript"
|
|
124
136
|
],
|
|
125
|
-
bannedElementAttributes: [
|
|
137
|
+
bannedElementAttributes: [
|
|
138
|
+
// momentic internal
|
|
139
|
+
"data-momentic-id",
|
|
140
|
+
"aria-keyshortcuts",
|
|
141
|
+
// auto-generated
|
|
142
|
+
"data-ved"
|
|
143
|
+
],
|
|
126
144
|
relevantElementAttributes: [
|
|
127
145
|
"name",
|
|
128
146
|
"id",
|
|
@@ -185,13 +203,15 @@ function addMomenticConstantsToWindow() {
|
|
|
185
203
|
// src/html/css-generation.ts
|
|
186
204
|
function generateCssSelectors(dataMomenticId) {
|
|
187
205
|
var _a, _b, _c, _d, _e;
|
|
206
|
+
const warnings = [];
|
|
188
207
|
const customWindow = window;
|
|
189
208
|
const ele = document.querySelector(\`[data-momentic-id="\${dataMomenticId}"]\`);
|
|
190
209
|
if (!ele) {
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
210
|
+
return {
|
|
211
|
+
selectors: [],
|
|
212
|
+
error: \`Could not find element with data-momentic-id: \${dataMomenticId}\`,
|
|
213
|
+
warnings
|
|
214
|
+
};
|
|
195
215
|
}
|
|
196
216
|
const selectors = [];
|
|
197
217
|
const blacklist = [
|
|
@@ -251,8 +271,8 @@ function generateCssSelectors(dataMomenticId) {
|
|
|
251
271
|
blacklist.push(selector);
|
|
252
272
|
}
|
|
253
273
|
} catch (err) {
|
|
254
|
-
|
|
255
|
-
\`
|
|
274
|
+
warnings.push(
|
|
275
|
+
\`Error generating selectors with CssSelectorGenerator: \${err}\`
|
|
256
276
|
);
|
|
257
277
|
}
|
|
258
278
|
}
|
|
@@ -271,19 +291,25 @@ function generateCssSelectors(dataMomenticId) {
|
|
|
271
291
|
selectors.push(momenticSelector);
|
|
272
292
|
}
|
|
273
293
|
} catch (err) {
|
|
274
|
-
|
|
275
|
-
\`
|
|
294
|
+
warnings.push(
|
|
295
|
+
\`Error generating selectors with CssSelectorGenerator: \${err}\`
|
|
276
296
|
);
|
|
277
297
|
}
|
|
278
298
|
if (selectors.length < 3) {
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
299
|
+
try {
|
|
300
|
+
const allOptionsSelector = (_c = customWindow.CssSelectorGenerator) == null ? void 0 : _c.getCssSelector(ele, {
|
|
301
|
+
blacklist,
|
|
302
|
+
maxCombinations: 50,
|
|
303
|
+
maxCandidates: 50,
|
|
304
|
+
includeTag: true
|
|
305
|
+
});
|
|
306
|
+
if (allOptionsSelector) {
|
|
307
|
+
selectors.push(allOptionsSelector);
|
|
308
|
+
}
|
|
309
|
+
} catch (err) {
|
|
310
|
+
warnings.push(
|
|
311
|
+
\`Error generating all-option selector with CssSelectorGenerator: \${err}\`
|
|
312
|
+
);
|
|
287
313
|
}
|
|
288
314
|
}
|
|
289
315
|
try {
|
|
@@ -292,8 +318,8 @@ function generateCssSelectors(dataMomenticId) {
|
|
|
292
318
|
selectors.push(...result);
|
|
293
319
|
}
|
|
294
320
|
} catch (err) {
|
|
295
|
-
|
|
296
|
-
\`
|
|
321
|
+
warnings.push(
|
|
322
|
+
\`Error generating selectors with Momentic custom library: \${err}\`
|
|
297
323
|
);
|
|
298
324
|
}
|
|
299
325
|
try {
|
|
@@ -302,9 +328,12 @@ function generateCssSelectors(dataMomenticId) {
|
|
|
302
328
|
selectors.push(result);
|
|
303
329
|
}
|
|
304
330
|
} catch (err) {
|
|
305
|
-
|
|
331
|
+
warnings.push(\`Error generating selector with medv: \${err}\`);
|
|
306
332
|
}
|
|
307
|
-
return
|
|
333
|
+
return {
|
|
334
|
+
selectors: Array.from(new Set(selectors)),
|
|
335
|
+
warnings
|
|
336
|
+
};
|
|
308
337
|
}
|
|
309
338
|
function addCssGenerationScript() {
|
|
310
339
|
const customWindow = window;
|
|
@@ -492,6 +521,22 @@ function checkIsNameAutogenerated(text) {
|
|
|
492
521
|
if (consonants / vowels > 5) {
|
|
493
522
|
return true;
|
|
494
523
|
}
|
|
524
|
+
const vowelChars = /* @__PURE__ */ new Set(["a", "e", "i", "o", "u", "y"]);
|
|
525
|
+
let maxVowelCount = 0;
|
|
526
|
+
let currentVowelCount = 0;
|
|
527
|
+
for (const char of text.toLowerCase()) {
|
|
528
|
+
if (char >= "a" && char <= "z" && !vowelChars.has(char)) {
|
|
529
|
+
currentVowelCount++;
|
|
530
|
+
if (currentVowelCount > maxVowelCount) {
|
|
531
|
+
maxVowelCount = currentVowelCount;
|
|
532
|
+
}
|
|
533
|
+
} else {
|
|
534
|
+
currentVowelCount = 0;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
if (maxVowelCount > 4) {
|
|
538
|
+
return true;
|
|
539
|
+
}
|
|
495
540
|
const capitals = ((_g = text.match(/[A-Z]/g)) != null ? _g : []).length;
|
|
496
541
|
const letters = ((_h = text.match(/[a-z]/g)) != null ? _h : []).length;
|
|
497
542
|
const expectedDifference = Math.ceil(text.length * 0.3);
|
|
@@ -505,24 +550,51 @@ function checkIsNameAutogenerated(text) {
|
|
|
505
550
|
}
|
|
506
551
|
|
|
507
552
|
// src/html/html-element-serialization.ts
|
|
508
|
-
function trimElementAttributes(element) {
|
|
509
|
-
var _a;
|
|
510
|
-
const maxAttrValLength = 100;
|
|
553
|
+
function trimElementAttributes(element, removeInputValues = true) {
|
|
554
|
+
var _a, _b, _c, _d, _e;
|
|
511
555
|
const customWindow = window;
|
|
556
|
+
const bannedClassSubstrings = (_b = (_a = customWindow.momenticConstants) == null ? void 0 : _a.bannedClassSubstrings) != null ? _b : [];
|
|
557
|
+
if (!bannedClassSubstrings.length) {
|
|
558
|
+
console.error(
|
|
559
|
+
"[MOMENTIC] Missing global Momentic constants in processClassAttribute"
|
|
560
|
+
);
|
|
561
|
+
}
|
|
562
|
+
const bannedAttrNames = (_d = (_c = customWindow.momenticConstants) == null ? void 0 : _c.bannedElementAttributes) != null ? _d : [];
|
|
563
|
+
if (!bannedAttrNames.length) {
|
|
564
|
+
console.error(
|
|
565
|
+
"[MOMENTIC] Missing global Momentic constants in processClassAttribute"
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
const maxAttrValLength = 100;
|
|
512
569
|
const attrNames = element.getAttributeNames();
|
|
513
570
|
for (const attr of attrNames) {
|
|
514
571
|
let attrVal = element.getAttribute(attr);
|
|
515
572
|
if (!attrVal) {
|
|
516
573
|
continue;
|
|
517
574
|
}
|
|
575
|
+
if (bannedAttrNames.includes(attr)) {
|
|
576
|
+
element.removeAttribute(attr);
|
|
577
|
+
continue;
|
|
578
|
+
}
|
|
518
579
|
if (attrVal.length > maxAttrValLength) {
|
|
519
580
|
attrVal = attrVal.slice(0, maxAttrValLength) + "...";
|
|
581
|
+
element.setAttribute(attr, attrVal);
|
|
520
582
|
}
|
|
521
583
|
switch (attr) {
|
|
522
584
|
case "class": {
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
585
|
+
let classToKeep;
|
|
586
|
+
for (const classVal of attrVal.split(" ")) {
|
|
587
|
+
if (bannedClassSubstrings.some((bad) => classVal.includes(bad))) {
|
|
588
|
+
continue;
|
|
589
|
+
}
|
|
590
|
+
if (checkIsNameAutogenerated(classVal)) {
|
|
591
|
+
continue;
|
|
592
|
+
}
|
|
593
|
+
classToKeep = classVal;
|
|
594
|
+
break;
|
|
595
|
+
}
|
|
596
|
+
if (classToKeep) {
|
|
597
|
+
element.setAttribute("class", classToKeep);
|
|
526
598
|
} else {
|
|
527
599
|
element.removeAttribute("class");
|
|
528
600
|
}
|
|
@@ -535,14 +607,29 @@ function trimElementAttributes(element) {
|
|
|
535
607
|
}
|
|
536
608
|
break;
|
|
537
609
|
}
|
|
610
|
+
case "href": {
|
|
611
|
+
if (attrVal.startsWith("data:") || attrVal.startsWith("/xjs")) {
|
|
612
|
+
element.removeAttribute(attr);
|
|
613
|
+
}
|
|
614
|
+
break;
|
|
615
|
+
}
|
|
616
|
+
case "src": {
|
|
617
|
+
if (attrVal.startsWith("data:")) {
|
|
618
|
+
element.setAttribute(attr, \`\${attrVal.split(";")[0]};TRUNCATED\`);
|
|
619
|
+
}
|
|
620
|
+
break;
|
|
621
|
+
}
|
|
538
622
|
case "value": {
|
|
539
|
-
if (element.getAttribute("type") === "text" || !element.getAttribute("type")) {
|
|
540
|
-
element.removeAttribute(
|
|
623
|
+
if (removeInputValues && (element.getAttribute("type") === "text" || !element.getAttribute("type"))) {
|
|
624
|
+
element.removeAttribute(attr);
|
|
541
625
|
break;
|
|
542
626
|
}
|
|
543
627
|
}
|
|
544
628
|
default: {
|
|
545
|
-
if (
|
|
629
|
+
if ([/data-.*/, /aria-.*/].some((re) => attr.match(re))) {
|
|
630
|
+
continue;
|
|
631
|
+
}
|
|
632
|
+
if (!((_e = customWindow.momenticConstants) == null ? void 0 : _e.relevantElementAttributes.includes(
|
|
546
633
|
attr
|
|
547
634
|
))) {
|
|
548
635
|
element.removeAttribute(attr);
|
|
@@ -568,7 +655,7 @@ function serializeNodeSingleChildLayer(node, includeChildren) {
|
|
|
568
655
|
return "";
|
|
569
656
|
}
|
|
570
657
|
const elementNode = node.cloneNode(true);
|
|
571
|
-
(_a = customWindow.trimElementAttributes) == null ? void 0 : _a.call(customWindow, elementNode);
|
|
658
|
+
(_a = customWindow.trimElementAttributes) == null ? void 0 : _a.call(customWindow, elementNode, true);
|
|
572
659
|
if (elementNode.children.length === 0 && !((_b = elementNode.textContent) == null ? void 0 : _b.trim())) {
|
|
573
660
|
return serializeSelfClosingElement(elementNode);
|
|
574
661
|
}
|
|
@@ -581,7 +668,7 @@ function serializeNodeSingleChildLayer(node, includeChildren) {
|
|
|
581
668
|
const childrenString = Array.from(elementNode.childNodes).map((child) => \` \${serializeNodeSingleChildLayer(child, false)}\`).join("\\n");
|
|
582
669
|
if (childrenString.trim()) {
|
|
583
670
|
result += \`>
|
|
584
|
-
|
|
671
|
+
\${childrenString}
|
|
585
672
|
</\${elementNode.tagName.toLowerCase()}>\`;
|
|
586
673
|
return result;
|
|
587
674
|
}
|
|
@@ -617,7 +704,7 @@ function serializeElementOnlyWithText(element) {
|
|
|
617
704
|
if (originalText) {
|
|
618
705
|
ele.textContent = originalText;
|
|
619
706
|
}
|
|
620
|
-
(_a = customWindow.trimElementAttributes) == null ? void 0 : _a.call(customWindow, ele);
|
|
707
|
+
(_a = customWindow.trimElementAttributes) == null ? void 0 : _a.call(customWindow, ele, true);
|
|
621
708
|
return ele.outerHTML;
|
|
622
709
|
}
|
|
623
710
|
function addElementSerializationScripts() {
|
|
@@ -627,6 +714,146 @@ function addElementSerializationScripts() {
|
|
|
627
714
|
customWindow.serializeElementOnlyWithText = serializeElementOnlyWithText;
|
|
628
715
|
}
|
|
629
716
|
|
|
717
|
+
// src/html/html-page-serialization.ts
|
|
718
|
+
var MAX_TEXT_CONTENT_LINE_LENGTH = 3e3;
|
|
719
|
+
function isNodeInteresting(node) {
|
|
720
|
+
var _a;
|
|
721
|
+
if (node.getAttribute("id") === "momentic_cursor") {
|
|
722
|
+
return false;
|
|
723
|
+
}
|
|
724
|
+
if (node.nodeType !== Node.ELEMENT_NODE) {
|
|
725
|
+
return true;
|
|
726
|
+
}
|
|
727
|
+
if ((_a = node.textContent) == null ? void 0 : _a.trim()) {
|
|
728
|
+
return true;
|
|
729
|
+
}
|
|
730
|
+
if (node.getAttributeNames().length > 1) {
|
|
731
|
+
return true;
|
|
732
|
+
}
|
|
733
|
+
if (node.getAttributeNames().length === 1 && !node.getAttribute("class")) {
|
|
734
|
+
return true;
|
|
735
|
+
}
|
|
736
|
+
return false;
|
|
737
|
+
}
|
|
738
|
+
function shouldFilterNode(node) {
|
|
739
|
+
var _a;
|
|
740
|
+
const customWindow = window;
|
|
741
|
+
if (!((_a = customWindow.momenticConstants) == null ? void 0 : _a.bannedElementTagNames)) {
|
|
742
|
+
throw new Error(
|
|
743
|
+
"Momentic browser library error: Missing global momentic constants in shouldFilterNode"
|
|
744
|
+
);
|
|
745
|
+
}
|
|
746
|
+
if (customWindow.momenticConstants.bannedElementTagNames.includes(
|
|
747
|
+
node.tagName.toLowerCase()
|
|
748
|
+
))
|
|
749
|
+
return true;
|
|
750
|
+
return !isNodeInteresting(node) && node.childNodes.length === 0;
|
|
751
|
+
}
|
|
752
|
+
function processElementNode(node) {
|
|
753
|
+
const customWindow = window;
|
|
754
|
+
if (!customWindow.trimElementAttributes) {
|
|
755
|
+
throw new Error(
|
|
756
|
+
"Momentic browser library error: Missing 'trimElementAttributes' function in processElementNode"
|
|
757
|
+
);
|
|
758
|
+
}
|
|
759
|
+
customWindow.trimElementAttributes(node, false);
|
|
760
|
+
if (node.nodeType === Node.TEXT_NODE) {
|
|
761
|
+
if (node.textContent && node.textContent.length > MAX_TEXT_CONTENT_LINE_LENGTH) {
|
|
762
|
+
node.textContent = node.textContent.slice(
|
|
763
|
+
0,
|
|
764
|
+
MAX_TEXT_CONTENT_LINE_LENGTH
|
|
765
|
+
);
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
return node;
|
|
769
|
+
}
|
|
770
|
+
function walkDOMTree(currentNode, data) {
|
|
771
|
+
if (currentNode.nodeType === Node.TEXT_NODE) {
|
|
772
|
+
return currentNode;
|
|
773
|
+
} else if (currentNode.nodeType !== Node.ELEMENT_NODE) {
|
|
774
|
+
return false;
|
|
775
|
+
}
|
|
776
|
+
const node = processElementNode(currentNode);
|
|
777
|
+
if (shouldFilterNode(node)) {
|
|
778
|
+
return false;
|
|
779
|
+
}
|
|
780
|
+
const children = [...node.childNodes];
|
|
781
|
+
for (let i = 0; i < children.length; i++) {
|
|
782
|
+
const child = children[i];
|
|
783
|
+
const processedChild = walkDOMTree(child, data);
|
|
784
|
+
if (!processedChild) {
|
|
785
|
+
node.removeChild(child);
|
|
786
|
+
child.remove();
|
|
787
|
+
} else {
|
|
788
|
+
node.replaceChild(processedChild, child);
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
const interesting = isNodeInteresting(node);
|
|
792
|
+
if (!interesting && node.childNodes.length === 0) {
|
|
793
|
+
return false;
|
|
794
|
+
} else if (!interesting && node.childNodes.length === 1) {
|
|
795
|
+
return node.childNodes[0];
|
|
796
|
+
}
|
|
797
|
+
return node;
|
|
798
|
+
}
|
|
799
|
+
function getCondensedHtmlTree() {
|
|
800
|
+
var _a;
|
|
801
|
+
const bodyCopy = document.body.cloneNode(true);
|
|
802
|
+
const globalData = {
|
|
803
|
+
classNameCounts: {}
|
|
804
|
+
};
|
|
805
|
+
const allElements = bodyCopy.getElementsByTagName("*");
|
|
806
|
+
if (!allElements || !allElements.length) {
|
|
807
|
+
return {
|
|
808
|
+
result: "",
|
|
809
|
+
error: "This page contains no elements. Are you sure the page is loaded completely?"
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
for (let i = 0; i < allElements.length; i++) {
|
|
813
|
+
const element = allElements[i];
|
|
814
|
+
const classNames = element.getAttribute("class");
|
|
815
|
+
if (classNames) {
|
|
816
|
+
const individualClassNames = classNames.split(" ");
|
|
817
|
+
individualClassNames.forEach((className) => {
|
|
818
|
+
globalData.classNameCounts[className] = (globalData.classNameCounts[className] || 0) + 1;
|
|
819
|
+
});
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
let processedBody;
|
|
823
|
+
try {
|
|
824
|
+
processedBody = walkDOMTree(bodyCopy, globalData);
|
|
825
|
+
} catch (err) {
|
|
826
|
+
return {
|
|
827
|
+
result: "",
|
|
828
|
+
error: err.message
|
|
829
|
+
};
|
|
830
|
+
}
|
|
831
|
+
if (!processedBody) {
|
|
832
|
+
return {
|
|
833
|
+
result: "",
|
|
834
|
+
error: "This page contains no elements. Are you sure the page is loaded completely?"
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
const orphanedNodes = [];
|
|
838
|
+
const bodyNodes = (_a = processedBody.childNodes) != null ? _a : [];
|
|
839
|
+
for (let i = 0; i < bodyNodes.length; i++) {
|
|
840
|
+
const node = bodyNodes[i];
|
|
841
|
+
if (!node.parentNode) {
|
|
842
|
+
orphanedNodes.push(node);
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
for (let i = 0; i < orphanedNodes.length; i++) {
|
|
846
|
+
processedBody.removeChild(orphanedNodes[i]);
|
|
847
|
+
}
|
|
848
|
+
return {
|
|
849
|
+
result: processedBody.outerHTML
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
function addHtmlTreeSerializationFunctions() {
|
|
853
|
+
const customWindow = window;
|
|
854
|
+
customWindow.getCondensedHtmlTree = getCondensedHtmlTree;
|
|
855
|
+
}
|
|
856
|
+
|
|
630
857
|
// src/html/ldist.ts
|
|
631
858
|
function addBrowserLdistScript() {
|
|
632
859
|
const customWindow = window;
|
|
@@ -966,12 +1193,12 @@ function addMedvCssGenerator() {
|
|
|
966
1193
|
seedMinLength: 3,
|
|
967
1194
|
idName: (name) => !checkIsNameAutogenerated(name),
|
|
968
1195
|
attr: (name, value) => {
|
|
969
|
-
return
|
|
1196
|
+
return !["data-momentic-id", "aria-keyshortcuts"].includes(name);
|
|
970
1197
|
},
|
|
971
1198
|
className: (name) => {
|
|
972
1199
|
return name.length < 30 && name.split(" ").every((n) => !checkIsNameAutogenerated(n));
|
|
973
1200
|
},
|
|
974
|
-
optimizedMinLength:
|
|
1201
|
+
optimizedMinLength: 2,
|
|
975
1202
|
threshold: 100,
|
|
976
1203
|
timeoutMs: 250,
|
|
977
1204
|
maxNumberOfTries: 5e3
|
|
@@ -1178,199 +1405,6 @@ function momenticSelectorGenerator(originalElement) {
|
|
|
1178
1405
|
return selectors.slice(0, maxResultsToReturn);
|
|
1179
1406
|
}
|
|
1180
1407
|
|
|
1181
|
-
// src/html/page-serialization.ts
|
|
1182
|
-
function processClassAttribute(attr, classNameCounts) {
|
|
1183
|
-
var _a;
|
|
1184
|
-
const customWindow = window;
|
|
1185
|
-
if (!((_a = customWindow.momenticConstants) == null ? void 0 : _a.bannedClassSubstrings)) {
|
|
1186
|
-
console.error(
|
|
1187
|
-
"[MOMENTIC] Missing global Momentic constants in processClassAttribute"
|
|
1188
|
-
);
|
|
1189
|
-
return "";
|
|
1190
|
-
}
|
|
1191
|
-
const classNames = attr.trim().split(" ");
|
|
1192
|
-
for (const cls of classNames) {
|
|
1193
|
-
if (cls.length <= 4) {
|
|
1194
|
-
continue;
|
|
1195
|
-
}
|
|
1196
|
-
if (classNameCounts[cls] && classNameCounts[cls] > 1) {
|
|
1197
|
-
continue;
|
|
1198
|
-
}
|
|
1199
|
-
if (customWindow.momenticConstants.bannedClassSubstrings.some(
|
|
1200
|
-
(bad) => cls.includes(bad)
|
|
1201
|
-
)) {
|
|
1202
|
-
continue;
|
|
1203
|
-
}
|
|
1204
|
-
return cls;
|
|
1205
|
-
}
|
|
1206
|
-
return "";
|
|
1207
|
-
}
|
|
1208
|
-
function isNodeInteresting(node) {
|
|
1209
|
-
var _a;
|
|
1210
|
-
if (node.getAttribute("id") === "momentic_cursor") {
|
|
1211
|
-
return false;
|
|
1212
|
-
}
|
|
1213
|
-
if (node.nodeType !== Node.ELEMENT_NODE) {
|
|
1214
|
-
return true;
|
|
1215
|
-
}
|
|
1216
|
-
if ((_a = node.textContent) == null ? void 0 : _a.trim()) {
|
|
1217
|
-
return true;
|
|
1218
|
-
}
|
|
1219
|
-
if (node.getAttributeNames().length > 1) {
|
|
1220
|
-
return true;
|
|
1221
|
-
}
|
|
1222
|
-
if (node.getAttributeNames().length === 1 && !node.getAttribute("class")) {
|
|
1223
|
-
return true;
|
|
1224
|
-
}
|
|
1225
|
-
return false;
|
|
1226
|
-
}
|
|
1227
|
-
function shouldFilterNode(node) {
|
|
1228
|
-
var _a;
|
|
1229
|
-
const customWindow = window;
|
|
1230
|
-
if (!((_a = customWindow.momenticConstants) == null ? void 0 : _a.bannedElementTagNames)) {
|
|
1231
|
-
console.error(
|
|
1232
|
-
"[MOMENTIC] Missing global Momentic constants in shouldFilterNode"
|
|
1233
|
-
);
|
|
1234
|
-
return false;
|
|
1235
|
-
}
|
|
1236
|
-
if (customWindow.momenticConstants.bannedElementTagNames.includes(
|
|
1237
|
-
node.tagName.toLowerCase()
|
|
1238
|
-
))
|
|
1239
|
-
return true;
|
|
1240
|
-
return !isNodeInteresting(node) && node.childNodes.length === 0;
|
|
1241
|
-
}
|
|
1242
|
-
function processElementNode(node, data) {
|
|
1243
|
-
var _a, _b, _c;
|
|
1244
|
-
const customWindow = window;
|
|
1245
|
-
if (!((_a = customWindow.momenticConstants) == null ? void 0 : _a.relevantElementAttributes) || !((_b = customWindow.momenticConstants) == null ? void 0 : _b.bannedElementAttributes)) {
|
|
1246
|
-
console.error(
|
|
1247
|
-
"[MOMENTIC] Missing global Momentic constants in processElementNode"
|
|
1248
|
-
);
|
|
1249
|
-
return node;
|
|
1250
|
-
}
|
|
1251
|
-
function decodeHtml(html) {
|
|
1252
|
-
const txt = document.createElement("textarea");
|
|
1253
|
-
txt.innerHTML = html;
|
|
1254
|
-
return txt.value;
|
|
1255
|
-
}
|
|
1256
|
-
const attributes = node.getAttributeNames();
|
|
1257
|
-
for (const attr of attributes) {
|
|
1258
|
-
if (customWindow.momenticConstants.bannedElementAttributes.includes(attr)) {
|
|
1259
|
-
node.removeAttribute(attr);
|
|
1260
|
-
continue;
|
|
1261
|
-
}
|
|
1262
|
-
switch (attr) {
|
|
1263
|
-
case "class": {
|
|
1264
|
-
const classNames = processClassAttribute(
|
|
1265
|
-
(_c = node.getAttribute("class")) != null ? _c : "",
|
|
1266
|
-
data.classNameCounts
|
|
1267
|
-
);
|
|
1268
|
-
if (!classNames) {
|
|
1269
|
-
node.removeAttribute(attr);
|
|
1270
|
-
} else {
|
|
1271
|
-
node.setAttribute(attr, classNames);
|
|
1272
|
-
}
|
|
1273
|
-
break;
|
|
1274
|
-
}
|
|
1275
|
-
case "src": {
|
|
1276
|
-
const src = node.getAttribute(attr);
|
|
1277
|
-
if (src == null ? void 0 : src.startsWith("data:")) {
|
|
1278
|
-
node.setAttribute(attr, \`\${src.split(";")[0]};TRUNCATED\`);
|
|
1279
|
-
}
|
|
1280
|
-
break;
|
|
1281
|
-
}
|
|
1282
|
-
default: {
|
|
1283
|
-
if (!customWindow.momenticConstants.relevantElementAttributes.includes(
|
|
1284
|
-
attr
|
|
1285
|
-
) && ![/data-.*/, /aria-.*/].some((re) => attr.match(re))) {
|
|
1286
|
-
node.removeAttribute(attr);
|
|
1287
|
-
}
|
|
1288
|
-
const attrVal = node.getAttribute(attr);
|
|
1289
|
-
if (attrVal == null ? void 0 : attrVal.includes("&")) {
|
|
1290
|
-
node.setAttribute(attr, decodeHtml(attrVal));
|
|
1291
|
-
}
|
|
1292
|
-
}
|
|
1293
|
-
}
|
|
1294
|
-
}
|
|
1295
|
-
return node;
|
|
1296
|
-
}
|
|
1297
|
-
function walkDOMTree(currentNode, data) {
|
|
1298
|
-
if (currentNode.nodeType === Node.TEXT_NODE) {
|
|
1299
|
-
return currentNode;
|
|
1300
|
-
} else if (currentNode.nodeType !== Node.ELEMENT_NODE) {
|
|
1301
|
-
return false;
|
|
1302
|
-
}
|
|
1303
|
-
const node = processElementNode(currentNode, data);
|
|
1304
|
-
if (shouldFilterNode(node)) {
|
|
1305
|
-
return false;
|
|
1306
|
-
}
|
|
1307
|
-
const children = [...node.childNodes];
|
|
1308
|
-
for (let i = 0; i < children.length; i++) {
|
|
1309
|
-
const child = children[i];
|
|
1310
|
-
const processedChild = walkDOMTree(child, data);
|
|
1311
|
-
if (!processedChild) {
|
|
1312
|
-
node.removeChild(child);
|
|
1313
|
-
child.remove();
|
|
1314
|
-
} else {
|
|
1315
|
-
node.replaceChild(processedChild, child);
|
|
1316
|
-
}
|
|
1317
|
-
}
|
|
1318
|
-
const interesting = isNodeInteresting(node);
|
|
1319
|
-
if (!interesting && node.childNodes.length === 0) {
|
|
1320
|
-
return false;
|
|
1321
|
-
} else if (!interesting && node.childNodes.length === 1) {
|
|
1322
|
-
return node.childNodes[0];
|
|
1323
|
-
}
|
|
1324
|
-
return node;
|
|
1325
|
-
}
|
|
1326
|
-
function getCondensedHtmlTree() {
|
|
1327
|
-
var _a;
|
|
1328
|
-
const bodyCopy = document.body.cloneNode(true);
|
|
1329
|
-
const globalData = {
|
|
1330
|
-
classNameCounts: {}
|
|
1331
|
-
};
|
|
1332
|
-
const allElements = bodyCopy.getElementsByTagName("*");
|
|
1333
|
-
if (!allElements || !allElements.length) {
|
|
1334
|
-
console.error(
|
|
1335
|
-
"[MOMENTIC] This page contains no elements. Are you sure the page is loaded completely?"
|
|
1336
|
-
);
|
|
1337
|
-
return "";
|
|
1338
|
-
}
|
|
1339
|
-
for (let i = 0; i < allElements.length; i++) {
|
|
1340
|
-
const element = allElements[i];
|
|
1341
|
-
const classNames = element.getAttribute("class");
|
|
1342
|
-
if (classNames) {
|
|
1343
|
-
const individualClassNames = classNames.split(" ");
|
|
1344
|
-
individualClassNames.forEach((className) => {
|
|
1345
|
-
globalData.classNameCounts[className] = (globalData.classNameCounts[className] || 0) + 1;
|
|
1346
|
-
});
|
|
1347
|
-
}
|
|
1348
|
-
}
|
|
1349
|
-
const processedBody = walkDOMTree(bodyCopy, globalData);
|
|
1350
|
-
if (!processedBody) {
|
|
1351
|
-
console.error(
|
|
1352
|
-
"[MOMENTIC] This page contains no elements. Are you sure the page is loaded completely?"
|
|
1353
|
-
);
|
|
1354
|
-
return "";
|
|
1355
|
-
}
|
|
1356
|
-
const orphanedNodes = [];
|
|
1357
|
-
const bodyNodes = (_a = processedBody.childNodes) != null ? _a : [];
|
|
1358
|
-
for (let i = 0; i < bodyNodes.length; i++) {
|
|
1359
|
-
const node = bodyNodes[i];
|
|
1360
|
-
if (!node.parentNode) {
|
|
1361
|
-
orphanedNodes.push(node);
|
|
1362
|
-
}
|
|
1363
|
-
}
|
|
1364
|
-
for (let i = 0; i < orphanedNodes.length; i++) {
|
|
1365
|
-
processedBody.removeChild(orphanedNodes[i]);
|
|
1366
|
-
}
|
|
1367
|
-
return processedBody.outerHTML;
|
|
1368
|
-
}
|
|
1369
|
-
function addHtmlTreeSerializationFunctions() {
|
|
1370
|
-
const customWindow = window;
|
|
1371
|
-
customWindow.getCondensedHtmlTree = getCondensedHtmlTree;
|
|
1372
|
-
}
|
|
1373
|
-
|
|
1374
1408
|
// src/html/recording.ts
|
|
1375
1409
|
function areBoundingBoxesSimilar(originalNode, candidate) {
|
|
1376
1410
|
const originalBox = originalNode.getBoundingClientRect();
|
|
@@ -1392,25 +1426,31 @@ function addRecordingTargetResolver() {
|
|
|
1392
1426
|
var _a, _b;
|
|
1393
1427
|
const generateResult = (momenticId, reason) => {
|
|
1394
1428
|
if (!customWindow.generateHtmlCacheAttributes) {
|
|
1395
|
-
|
|
1396
|
-
"
|
|
1397
|
-
|
|
1398
|
-
|
|
1429
|
+
return {
|
|
1430
|
+
error: "Missing generateHtmlCacheAttributes function",
|
|
1431
|
+
warnings: []
|
|
1432
|
+
};
|
|
1399
1433
|
}
|
|
1400
1434
|
const dataMomenticId = parseInt(momenticId);
|
|
1401
|
-
const
|
|
1435
|
+
const { attributes, error, warnings } = customWindow.generateHtmlCacheAttributes(dataMomenticId);
|
|
1402
1436
|
return {
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1437
|
+
target: {
|
|
1438
|
+
dataMomenticId,
|
|
1439
|
+
htmlAttributes: attributes,
|
|
1440
|
+
metadata: { reason }
|
|
1441
|
+
},
|
|
1442
|
+
error,
|
|
1443
|
+
warnings
|
|
1406
1444
|
};
|
|
1407
1445
|
};
|
|
1408
|
-
|
|
1446
|
+
let originalMomenticId = element.getAttribute("data-momentic-id");
|
|
1409
1447
|
if (!originalMomenticId) {
|
|
1410
|
-
|
|
1411
|
-
|
|
1448
|
+
originalMomenticId = \`999\${Math.floor(Math.random() * 100)}\`;
|
|
1449
|
+
element.setAttribute("data-momentic-id", originalMomenticId);
|
|
1450
|
+
return generateResult(
|
|
1451
|
+
originalMomenticId,
|
|
1452
|
+
\`Forced to regenerate momentic id on element (chose \${originalMomenticId})\`
|
|
1412
1453
|
);
|
|
1413
|
-
return void 0;
|
|
1414
1454
|
}
|
|
1415
1455
|
if (!customWindow.momenticIdsInA11yTree) {
|
|
1416
1456
|
return generateResult(
|
|
@@ -1477,23 +1517,23 @@ function addClickListener() {
|
|
|
1477
1517
|
}
|
|
1478
1518
|
customWindow.clickListener = (event) => {
|
|
1479
1519
|
const customWindow2 = window;
|
|
1480
|
-
if (!customWindow2.captureElementEvent) {
|
|
1520
|
+
if (!customWindow2.captureElementEvent || !customWindow2.generateHtmlCacheAttributes || !customWindow2.resolveRecordingTarget) {
|
|
1481
1521
|
return;
|
|
1482
1522
|
}
|
|
1483
|
-
|
|
1484
|
-
|
|
1523
|
+
const element = event.target;
|
|
1524
|
+
console.debug("[MOMENTIC] Window click listener fired", element);
|
|
1525
|
+
if (event.button !== 0) {
|
|
1526
|
+
console.debug("[MOMENTIC] Ignoring click event with non-primary button");
|
|
1485
1527
|
return;
|
|
1486
1528
|
}
|
|
1487
|
-
console.debug("[MOMENTIC] Window click listener fired");
|
|
1488
|
-
const element = event.target;
|
|
1489
1529
|
if (element.tagName.toLowerCase() === "select") {
|
|
1490
|
-
console.
|
|
1530
|
+
console.debug("[MOMENTIC] Ignoring click on select element");
|
|
1491
1531
|
return;
|
|
1492
1532
|
}
|
|
1493
1533
|
let parent = element.parentElement;
|
|
1494
1534
|
while (parent) {
|
|
1495
1535
|
if (parent.tagName.toLowerCase() === "select") {
|
|
1496
|
-
console.
|
|
1536
|
+
console.debug("[MOMENTIC] Ignoring click on child of select element");
|
|
1497
1537
|
return;
|
|
1498
1538
|
}
|
|
1499
1539
|
parent = parent.parentElement;
|
|
@@ -1505,14 +1545,11 @@ function addClickListener() {
|
|
|
1505
1545
|
return;
|
|
1506
1546
|
}
|
|
1507
1547
|
const recordingTarget = customWindow2.resolveRecordingTarget(element);
|
|
1508
|
-
if (!recordingTarget) {
|
|
1509
|
-
return;
|
|
1510
|
-
}
|
|
1511
1548
|
customWindow2.captureElementEvent(__spreadValues({
|
|
1512
1549
|
type: "CLICK"
|
|
1513
1550
|
}, recordingTarget));
|
|
1514
1551
|
};
|
|
1515
|
-
document.addEventListener("
|
|
1552
|
+
document.addEventListener("mousedown", customWindow.clickListener, {
|
|
1516
1553
|
// This flag allows us to process before stuff like navigation actually occurs
|
|
1517
1554
|
capture: true
|
|
1518
1555
|
});
|
|
@@ -1541,30 +1578,35 @@ function addRecordingListeners() {
|
|
|
1541
1578
|
addPressListener();
|
|
1542
1579
|
}
|
|
1543
1580
|
|
|
1581
|
+
// src/html/registration.ts
|
|
1582
|
+
function registerAllMomenticListeners() {
|
|
1583
|
+
addMedvCssGenerator();
|
|
1584
|
+
addMomenticConstantsToWindow();
|
|
1585
|
+
addFindElementInBodyOrShadowDomScript();
|
|
1586
|
+
addBrowserLdistScript();
|
|
1587
|
+
addMomenticSelectorGeneratorLib();
|
|
1588
|
+
addTrackCursorScript();
|
|
1589
|
+
addCssGenerationScript();
|
|
1590
|
+
addEvaluateCssSelectorsScript();
|
|
1591
|
+
addHtmlTreeSerializationFunctions();
|
|
1592
|
+
addElementSerializationScripts();
|
|
1593
|
+
addGenerateHtmlCacheAttributesScript();
|
|
1594
|
+
addRecordingListeners();
|
|
1595
|
+
}
|
|
1596
|
+
|
|
1544
1597
|
// src/html/index.ts
|
|
1545
|
-
|
|
1546
|
-
addMomenticConstantsToWindow();
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
addCssGenerationScript();
|
|
1552
|
-
addEvaluateCssSelectorsScript();
|
|
1553
|
-
addHtmlTreeSerializationFunctions();
|
|
1554
|
-
addElementSerializationScripts();
|
|
1555
|
-
addGenerateHtmlCacheAttributesScript();
|
|
1556
|
-
addRecordingListeners();
|
|
1557
|
-
`,cssGeneratorLibJs:'// Taken from https://cdn.jsdelivr.net/npm/css-selector-generator@3.6.7/build/index.min.js\n!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.CssSelectorGenerator=e():t.CssSelectorGenerator=e()}(self,(()=>(()=>{"use strict";var t={d:(e,n)=>{for(var r in n)t.o(n,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};function n(t){return t&&t instanceof Element}t.r(e),t.d(e,{default:()=>K,getCssSelector:()=>J});const r={NONE:"",DESCENDANT:" ",CHILD:" > "},o={id:"id",class:"class",tag:"tag",attribute:"attribute",nthchild:"nthchild",nthoftype:"nthoftype"},i="CssSelectorGenerator";function c(t="unknown problem",...e){console.warn(`${i}: ${t}`,...e)}const u={selectors:[o.id,o.class,o.tag,o.attribute],includeTag:!1,whitelist:[],blacklist:[],combineWithinSelector:!0,combineBetweenSelectors:!0,root:null,maxCombinations:Number.POSITIVE_INFINITY,maxCandidates:Number.POSITIVE_INFINITY};function s(t){return t instanceof RegExp}function a(t){return["string","function"].includes(typeof t)||s(t)}function l(t){return Array.isArray(t)?t.filter(a):[]}function f(t){const e=[Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE,Node.ELEMENT_NODE];return function(t){return t instanceof Node}(t)&&e.includes(t.nodeType)}function d(t,e){if(f(t))return t.contains(e)||c("element root mismatch","Provided root does not contain the element. This will most likely result in producing a fallback selector using element\'s real root node. If you plan to use the selector using provided root (e.g. `root.querySelector`), it will nto work as intended."),t;const n=e.getRootNode({composed:!1});return f(n)?(n!==document&&c("shadow root inferred","You did not provide a root and the element is a child of Shadow DOM. This will produce a selector using ShadowRoot as a root. If you plan to use the selector using document as a root (e.g. `document.querySelector`), it will not work as intended."),n):e.ownerDocument.querySelector(":root")}function m(t){return"number"==typeof t?t:Number.POSITIVE_INFINITY}function p(t=[]){const[e=[],...n]=t;return 0===n.length?e:n.reduce(((t,e)=>t.filter((t=>e.includes(t)))),e)}function h(t){return[].concat(...t)}function g(t){const e=t.map((t=>{if(s(t))return e=>t.test(e);if("function"==typeof t)return e=>{const n=t(e);return"boolean"!=typeof n?(c("pattern matcher function invalid","Provided pattern matching function does not return boolean. It\'s result will be ignored.",t),!1):n};if("string"==typeof t){const e=new RegExp("^"+t.replace(/[|\\\\{}()[\\]^$+?.]/g,"\\\\$&").replace(/\\*/g,".+")+"$");return t=>e.test(t)}return c("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",t),()=>!1}));return t=>e.some((e=>e(t)))}function b(t,e,n){const r=Array.from(d(n,t[0]).querySelectorAll(e));return r.length===t.length&&t.every((t=>r.includes(t)))}function y(t,e){e=null!=e?e:function(t){return t.ownerDocument.querySelector(":root")}(t);const r=[];let o=t;for(;n(o)&&o!==e;)r.push(o),o=o.parentElement;return r}function N(t,e){return p(t.map((t=>y(t,e))))}const S=", ",E=new RegExp(["^$","\\\\s"].join("|")),w=new RegExp(["^$"].join("|")),I=[o.nthoftype,o.tag,o.id,o.class,o.attribute,o.nthchild],v=g(["class","id","ng-*"]);function C({name:t}){return`[${t}]`}function T({name:t,value:e}){return`[${t}=\'${e}\']`}function O({nodeName:t,nodeValue:e}){return{name:V(t),value:V(e)}}function x(t){const e=Array.from(t.attributes).filter((e=>function({nodeName:t},e){const n=e.tagName.toLowerCase();return!(["input","option"].includes(n)&&"value"===t||v(t))}(e,t))).map(O);return[...e.map(C),...e.map(T)]}function j(t){return(t.getAttribute("class")||"").trim().split(/\\s+/).filter((t=>!w.test(t))).map((t=>`.${V(t)}`))}function A(t){const e=t.getAttribute("id")||"",n=`#${V(e)}`,r=t.getRootNode({composed:!1});return!E.test(e)&&b([t],n,r)?[n]:[]}function $(t){const e=t.parentNode;if(e){const r=Array.from(e.childNodes).filter(n).indexOf(t);if(r>-1)return[`:nth-child(${r+1})`]}return[]}function D(t){return[V(t.tagName.toLowerCase())]}function R(t){const e=[...new Set(h(t.map(D)))];return 0===e.length||e.length>1?[]:[e[0]]}function P(t){const e=R([t])[0],n=t.parentElement;if(n){const r=Array.from(n.children).filter((t=>t.tagName.toLowerCase()===e)),o=r.indexOf(t);if(o>-1)return[`${e}:nth-of-type(${o+1})`]}return[]}function _(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){return Array.from(function*(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){let n=0,r=L(1);for(;r.length<=t.length&&n<e;){n+=1;const e=r.map((e=>t[e]));yield e,r=k(r,t.length-1)}}(t,{maxResults:e}))}function k(t=[],e=0){const n=t.length;if(0===n)return[];const r=[...t];r[n-1]+=1;for(let t=n-1;t>=0;t--)if(r[t]>e){if(0===t)return L(n+1);r[t-1]++,r[t]=r[t-1]+1}return r[n-1]>e?L(n+1):r}function L(t=1){return Array.from(Array(t).keys())}const M=":".charCodeAt(0).toString(16).toUpperCase(),F=/[ !"#$%&\'()\\[\\]{|}<>*+,./;=?@^`~\\\\]/;function V(t=""){var e,n;return null!==(n=null===(e=null===CSS||void 0===CSS?void 0:CSS.escape)||void 0===e?void 0:e.call(CSS,t))&&void 0!==n?n:function(t=""){return t.split("").map((t=>":"===t?`\\\\${M} `:F.test(t)?`\\\\${t}`:escape(t).replace(/%/g,"\\\\"))).join("")}(t)}const Y={tag:R,id:function(t){return 0===t.length||t.length>1?[]:A(t[0])},class:function(t){return p(t.map(j))},attribute:function(t){return p(t.map(x))},nthchild:function(t){return p(t.map($))},nthoftype:function(t){return p(t.map(P))}},q={tag:D,id:A,class:j,attribute:x,nthchild:$,nthoftype:P};function B(t){return t.includes(o.tag)||t.includes(o.nthoftype)?[...t]:[...t,o.tag]}function G(t={}){const e=[...I];return t[o.tag]&&t[o.nthoftype]&&e.splice(e.indexOf(o.tag),1),e.map((e=>{return(r=t)[n=e]?r[n].join(""):"";var n,r})).join("")}function H(t,e,n="",o){const i=function(t,e){return""===e?t:function(t,e){return[...t.map((t=>e+r.DESCENDANT+t)),...t.map((t=>e+r.CHILD+t))]}(t,e)}(function(t,e,n){const r=function(t,e){const{blacklist:n,whitelist:r,combineWithinSelector:o,maxCombinations:i}=e,c=g(n),u=g(r);return function(t){const{selectors:e,includeTag:n}=t,r=[].concat(e);return n&&!r.includes("tag")&&r.push("tag"),r}(e).reduce(((e,n)=>{const r=function(t,e){var n;return(null!==(n=Y[e])&&void 0!==n?n:()=>[])(t)}(t,n),s=function(t=[],e,n){return t.filter((t=>n(t)||!e(t)))}(r,c,u),a=function(t=[],e){return t.sort(((t,n)=>{const r=e(t),o=e(n);return r&&!o?-1:!r&&o?1:0}))}(s,u);return e[n]=o?_(a,{maxResults:i}):a.map((t=>[t])),e}),{})}(t,n),o=function(t,e){return function(t){const{selectors:e,combineBetweenSelectors:n,includeTag:r,maxCandidates:o}=t,i=n?_(e,{maxResults:o}):e.map((t=>[t]));return r?i.map(B):i}(e).map((e=>function(t,e){const n={};return t.forEach((t=>{const r=e[t];r.length>0&&(n[t]=r)})),function(t={}){let e=[];return Object.entries(t).forEach((([t,n])=>{e=n.flatMap((n=>0===e.length?[{[t]:n}]:e.map((e=>Object.assign(Object.assign({},e),{[t]:n})))))})),e}(n).map(G)}(e,t))).filter((t=>t.length>0))}(r,n),i=h(o);return[...new Set(i)]}(t,o.root,o),n);for(const e of i)if(b(t,e,o.root))return e;return null}function W(t){return{value:t,include:!1}}function U({selectors:t,operator:e}){let n=[...I];t[o.tag]&&t[o.nthoftype]&&(n=n.filter((t=>t!==o.tag)));let r="";return n.forEach((e=>{(t[e]||[]).forEach((({value:t,include:e})=>{e&&(r+=t)}))})),e+r}function z(t){return[":root",...y(t).reverse().map((t=>{const e=function(t,e,n=r.NONE){const o={};return e.forEach((e=>{Reflect.set(o,e,function(t,e){return q[e](t)}(t,e).map(W))})),{element:t,operator:n,selectors:o}}(t,[o.nthchild],r.CHILD);return e.selectors.nthchild.forEach((t=>{t.include=!0})),e})).map(U)].join("")}function J(t,e={}){const r=function(t){(t instanceof NodeList||t instanceof HTMLCollection)&&(t=Array.from(t));const e=(Array.isArray(t)?t:[t]).filter(n);return[...new Set(e)]}(t),i=function(t,e={}){const n=Object.assign(Object.assign({},u),e);return{selectors:(r=n.selectors,Array.isArray(r)?r.filter((t=>{return e=o,n=t,Object.values(e).includes(n);var e,n})):[]),whitelist:l(n.whitelist),blacklist:l(n.blacklist),root:d(n.root,t),combineWithinSelector:!!n.combineWithinSelector,combineBetweenSelectors:!!n.combineBetweenSelectors,includeTag:!!n.includeTag,maxCombinations:m(n.maxCombinations),maxCandidates:m(n.maxCandidates)};var r}(r[0],e);let c="",s=i.root;function a(){return function(t,e,n="",r){if(0===t.length)return null;const o=[t.length>1?t:[],...N(t,e).map((t=>[t]))];for(const t of o){const e=H(t,0,n,r);if(e)return{foundElements:t,selector:e}}return null}(r,s,c,i)}let f=a();for(;f;){const{foundElements:t,selector:e}=f;if(b(r,e,i.root))return e;s=t[0],c=e,f=a()}return r.length>1?r.map((t=>J(t,i))).join(S):function(t){return t.map(z).join(S)}(r)}const K=J;return e})()));'};import{randomUUID as bp}from"crypto";import Cp from"dedent";import{distance as Tp}from"fastest-levenshtein";import{readFileSync as Ep,rmSync as Fl}from"fs";import vp from"js-beautify";import{cloneDeep as Ap}from"lodash-es";import{homedir as Rp}from"os";import zn from"p-timeout";import{basename as Ul,join as Bl}from"path";import{chromium as xp,devices as zl}from"playwright";import{errors as Ip}from"playwright";import{addExtra as Lp}from"playwright-extra";import Pp from"puppeteer-extra-plugin-recaptcha";import Op from"sharp";import{v4 as Mp}from"uuid";var Ut=(r,e)=>{try{let{hostname:t,pathname:n}=new URL(r),{hostname:o,pathname:s}=new URL(e);return t!==o||n!==s}catch{return!1}},Mn=r=>{try{return new URL(r),!0}catch{return!1}},tl=r=>!r.toLowerCase().startsWith("http"),Nn=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function zt(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}var rl={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center"],bannedElementTagNames:["html","head","title","meta","iframe","script","style","path","svg","br","::marker","noscript"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","data-value","data-testid","data-cy","data-test-id","data-test","data-role","data-type","data-action","data-aria-hidden","data-hidden","data-handleid","data-handlepos","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden"]};function nl(r){if(r[0]?.match(/[0-9a-zA-Z]/)===null)return!0;if(r.length>10){let l=Math.floor(r.length/8);if((r.match(/[-_:/ ]/g)??[]).length<l)return!0}if((r.match(/[^0-9a-zA-Z.]/g)??[]).length/r.length>.2)return!0;let t=(r.match(/[0-9]/g)??[]).length;if(t/r.length>.3)return!0;let n=(r.toLowerCase().match(/[aeiou]/gi)??[]).length;if((r.toLowerCase().match(/[bcdfghjklmnpqrstvwxyz]/gi)??[]).length/n>5)return!0;let s=(r.match(/[A-Z]/g)??[]).length,i=(r.match(/[a-z]/g)??[]).length,a=Math.ceil(r.length*.3);return!!(i&&t&&Math.abs(i-t)<a||i&&s&&Math.abs(i-s)<a)}import{randomUUID as al}from"crypto";import{distance as Ko}from"fastest-levenshtein";import{cloneDeep as ll}from"lodash-es";import Fm from"p-timeout";var ol=new Set(["about:blank","chrome-error://chromewebdata/"]),sl=3,Ue="data-momentic-id",il=500,qo=["button","image","generic","graphics-symbol","tab","link","menuitem","group"];var Um=["focusable","keyshortcuts","controls","live","relevant","orientation"],zm=["selected","readonly","modal","required","invalid"],Bm=["id","name","role","content"],$m=["textbox","checkbox","combobox","table","caption","columnheader","rowheader","gridcell","row","rowgroup","cell","image","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch"],Hm=["notRendered","notVisible","ariaHiddenElement","ariaHiddenSubtree","activeAriaModalDialog"],Wm=["menulistpopup","statictext","inlinetextbox"],Gm=80,kn=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],jm=["cite"],Vm={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"]},cl={indentLevel:0,noID:!1,noChildren:!1,noProperties:!1,noContent:!1,maxLevel:void 0,neighbors:void 0},Yo=class r{id;role;name;tagName;content;properties;dataMomenticId;pathFromRoot;parent;children;domNode;backendNodeID;ignoredByCDP;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeID=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let t=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(t&&!nl(t)?t:""),this.role=this.role||(e.domNode.attributes.role??""),Jm(this.properties,e.domNode)}}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(){return $m.includes(this.role.toLowerCase())||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||this.children.some(e=>e.role==="StaticText")?!0:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(e=>e.startsWith("data"))}serialize(e=cl){let t=Object.assign({},cl,e),{indentLevel:n,noChildren:o,noProperties:s,noID:i,noContent:a}=t,l=ll(this.properties),c=" ".repeat(n),u=this.role||"",d=this.tagName??"unknown",m=this.name;u==="heading"&&m==="heading"&&(m="");let h=kn.includes(this.role)||jm.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${c}${m}
|
|
1558
|
-
`;let p=`${c}<${d}`;if(!i&&!h&&(p+=` id="${this.id}"`),u&&u!=="generic"&&u!==d&&!(Vm[u]??[]).includes(d)&&(p+=` role=${JSON.stringify(u)}`),m&&(p+=` name=${JSON.stringify(m)}`),this.content&&!a&&(p+=` content=${JSON.stringify(this.content)}`),Object.keys(l).length>0&&!s&&Object.entries(l).forEach(([f,S])=>{if(!Um.includes(f)){if(zm.includes(f)&&(!S||S==="false"))return;if(f==="value"&&a&&(l.type==="text"||this.role==="textbox"))return;if(f==="type"&&S===d)return;typeof S=="string"?p+=` ${f}="${S}"`:typeof S=="boolean"?S?p+=` ${f}`:p+=` ${f}={false}`:typeof S<"u"&&(p+=` ${f}={${JSON.stringify(S)}}`)}}),d==="::before"||d==="::after"){let f="";for(let S of this.children)f+=S.serialize({...e,indentLevel:n,neighbors:0});return f}let g=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||g)p+=` />
|
|
1559
|
-
`;else{let f="";for(let w of this.children)f+=w.serialize({...e,indentLevel:n+2,neighbors:0});let S=f.trim();S.length<=Gm&&!S.includes(`
|
|
1560
|
-
`)?p+=`>${S}</${d}>
|
|
1561
|
-
`:p+=`>
|
|
1598
|
+
registerAllMomenticListeners();
|
|
1599
|
+
`,cssGeneratorLibJs:'// Taken from https://cdn.jsdelivr.net/npm/css-selector-generator@3.6.7/build/index.min.js\n!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.CssSelectorGenerator=e():t.CssSelectorGenerator=e()}(self,(()=>(()=>{"use strict";var t={d:(e,n)=>{for(var r in n)t.o(n,r)&&!t.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:n[r]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};function n(t){return t&&t instanceof Element}t.r(e),t.d(e,{default:()=>K,getCssSelector:()=>J});const r={NONE:"",DESCENDANT:" ",CHILD:" > "},o={id:"id",class:"class",tag:"tag",attribute:"attribute",nthchild:"nthchild",nthoftype:"nthoftype"},i="CssSelectorGenerator";function c(t="unknown problem",...e){console.warn(`${i}: ${t}`,...e)}const u={selectors:[o.id,o.class,o.tag,o.attribute],includeTag:!1,whitelist:[],blacklist:[],combineWithinSelector:!0,combineBetweenSelectors:!0,root:null,maxCombinations:Number.POSITIVE_INFINITY,maxCandidates:Number.POSITIVE_INFINITY};function s(t){return t instanceof RegExp}function a(t){return["string","function"].includes(typeof t)||s(t)}function l(t){return Array.isArray(t)?t.filter(a):[]}function f(t){const e=[Node.DOCUMENT_NODE,Node.DOCUMENT_FRAGMENT_NODE,Node.ELEMENT_NODE];return function(t){return t instanceof Node}(t)&&e.includes(t.nodeType)}function d(t,e){if(f(t))return t.contains(e)||c("element root mismatch","Provided root does not contain the element. This will most likely result in producing a fallback selector using element\'s real root node. If you plan to use the selector using provided root (e.g. `root.querySelector`), it will nto work as intended."),t;const n=e.getRootNode({composed:!1});return f(n)?(n!==document&&c("shadow root inferred","You did not provide a root and the element is a child of Shadow DOM. This will produce a selector using ShadowRoot as a root. If you plan to use the selector using document as a root (e.g. `document.querySelector`), it will not work as intended."),n):e.ownerDocument.querySelector(":root")}function m(t){return"number"==typeof t?t:Number.POSITIVE_INFINITY}function p(t=[]){const[e=[],...n]=t;return 0===n.length?e:n.reduce(((t,e)=>t.filter((t=>e.includes(t)))),e)}function h(t){return[].concat(...t)}function g(t){const e=t.map((t=>{if(s(t))return e=>t.test(e);if("function"==typeof t)return e=>{const n=t(e);return"boolean"!=typeof n?(c("pattern matcher function invalid","Provided pattern matching function does not return boolean. It\'s result will be ignored.",t),!1):n};if("string"==typeof t){const e=new RegExp("^"+t.replace(/[|\\\\{}()[\\]^$+?.]/g,"\\\\$&").replace(/\\*/g,".+")+"$");return t=>e.test(t)}return c("pattern matcher invalid","Pattern matching only accepts strings, regular expressions and/or functions. This item is invalid and will be ignored.",t),()=>!1}));return t=>e.some((e=>e(t)))}function b(t,e,n){const r=Array.from(d(n,t[0]).querySelectorAll(e));return r.length===t.length&&t.every((t=>r.includes(t)))}function y(t,e){e=null!=e?e:function(t){return t.ownerDocument.querySelector(":root")}(t);const r=[];let o=t;for(;n(o)&&o!==e;)r.push(o),o=o.parentElement;return r}function N(t,e){return p(t.map((t=>y(t,e))))}const S=", ",E=new RegExp(["^$","\\\\s"].join("|")),w=new RegExp(["^$"].join("|")),I=[o.nthoftype,o.tag,o.id,o.class,o.attribute,o.nthchild],v=g(["class","id","ng-*"]);function C({name:t}){return`[${t}]`}function T({name:t,value:e}){return`[${t}=\'${e}\']`}function O({nodeName:t,nodeValue:e}){return{name:V(t),value:V(e)}}function x(t){const e=Array.from(t.attributes).filter((e=>function({nodeName:t},e){const n=e.tagName.toLowerCase();return!(["input","option"].includes(n)&&"value"===t||v(t))}(e,t))).map(O);return[...e.map(C),...e.map(T)]}function j(t){return(t.getAttribute("class")||"").trim().split(/\\s+/).filter((t=>!w.test(t))).map((t=>`.${V(t)}`))}function A(t){const e=t.getAttribute("id")||"",n=`#${V(e)}`,r=t.getRootNode({composed:!1});return!E.test(e)&&b([t],n,r)?[n]:[]}function $(t){const e=t.parentNode;if(e){const r=Array.from(e.childNodes).filter(n).indexOf(t);if(r>-1)return[`:nth-child(${r+1})`]}return[]}function D(t){return[V(t.tagName.toLowerCase())]}function R(t){const e=[...new Set(h(t.map(D)))];return 0===e.length||e.length>1?[]:[e[0]]}function P(t){const e=R([t])[0],n=t.parentElement;if(n){const r=Array.from(n.children).filter((t=>t.tagName.toLowerCase()===e)),o=r.indexOf(t);if(o>-1)return[`${e}:nth-of-type(${o+1})`]}return[]}function _(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){return Array.from(function*(t=[],{maxResults:e=Number.POSITIVE_INFINITY}={}){let n=0,r=L(1);for(;r.length<=t.length&&n<e;){n+=1;const e=r.map((e=>t[e]));yield e,r=k(r,t.length-1)}}(t,{maxResults:e}))}function k(t=[],e=0){const n=t.length;if(0===n)return[];const r=[...t];r[n-1]+=1;for(let t=n-1;t>=0;t--)if(r[t]>e){if(0===t)return L(n+1);r[t-1]++,r[t]=r[t-1]+1}return r[n-1]>e?L(n+1):r}function L(t=1){return Array.from(Array(t).keys())}const M=":".charCodeAt(0).toString(16).toUpperCase(),F=/[ !"#$%&\'()\\[\\]{|}<>*+,./;=?@^`~\\\\]/;function V(t=""){var e,n;return null!==(n=null===(e=null===CSS||void 0===CSS?void 0:CSS.escape)||void 0===e?void 0:e.call(CSS,t))&&void 0!==n?n:function(t=""){return t.split("").map((t=>":"===t?`\\\\${M} `:F.test(t)?`\\\\${t}`:escape(t).replace(/%/g,"\\\\"))).join("")}(t)}const Y={tag:R,id:function(t){return 0===t.length||t.length>1?[]:A(t[0])},class:function(t){return p(t.map(j))},attribute:function(t){return p(t.map(x))},nthchild:function(t){return p(t.map($))},nthoftype:function(t){return p(t.map(P))}},q={tag:D,id:A,class:j,attribute:x,nthchild:$,nthoftype:P};function B(t){return t.includes(o.tag)||t.includes(o.nthoftype)?[...t]:[...t,o.tag]}function G(t={}){const e=[...I];return t[o.tag]&&t[o.nthoftype]&&e.splice(e.indexOf(o.tag),1),e.map((e=>{return(r=t)[n=e]?r[n].join(""):"";var n,r})).join("")}function H(t,e,n="",o){const i=function(t,e){return""===e?t:function(t,e){return[...t.map((t=>e+r.DESCENDANT+t)),...t.map((t=>e+r.CHILD+t))]}(t,e)}(function(t,e,n){const r=function(t,e){const{blacklist:n,whitelist:r,combineWithinSelector:o,maxCombinations:i}=e,c=g(n),u=g(r);return function(t){const{selectors:e,includeTag:n}=t,r=[].concat(e);return n&&!r.includes("tag")&&r.push("tag"),r}(e).reduce(((e,n)=>{const r=function(t,e){var n;return(null!==(n=Y[e])&&void 0!==n?n:()=>[])(t)}(t,n),s=function(t=[],e,n){return t.filter((t=>n(t)||!e(t)))}(r,c,u),a=function(t=[],e){return t.sort(((t,n)=>{const r=e(t),o=e(n);return r&&!o?-1:!r&&o?1:0}))}(s,u);return e[n]=o?_(a,{maxResults:i}):a.map((t=>[t])),e}),{})}(t,n),o=function(t,e){return function(t){const{selectors:e,combineBetweenSelectors:n,includeTag:r,maxCandidates:o}=t,i=n?_(e,{maxResults:o}):e.map((t=>[t]));return r?i.map(B):i}(e).map((e=>function(t,e){const n={};return t.forEach((t=>{const r=e[t];r.length>0&&(n[t]=r)})),function(t={}){let e=[];return Object.entries(t).forEach((([t,n])=>{e=n.flatMap((n=>0===e.length?[{[t]:n}]:e.map((e=>Object.assign(Object.assign({},e),{[t]:n})))))})),e}(n).map(G)}(e,t))).filter((t=>t.length>0))}(r,n),i=h(o);return[...new Set(i)]}(t,o.root,o),n);for(const e of i)if(b(t,e,o.root))return e;return null}function W(t){return{value:t,include:!1}}function U({selectors:t,operator:e}){let n=[...I];t[o.tag]&&t[o.nthoftype]&&(n=n.filter((t=>t!==o.tag)));let r="";return n.forEach((e=>{(t[e]||[]).forEach((({value:t,include:e})=>{e&&(r+=t)}))})),e+r}function z(t){return[":root",...y(t).reverse().map((t=>{const e=function(t,e,n=r.NONE){const o={};return e.forEach((e=>{Reflect.set(o,e,function(t,e){return q[e](t)}(t,e).map(W))})),{element:t,operator:n,selectors:o}}(t,[o.nthchild],r.CHILD);return e.selectors.nthchild.forEach((t=>{t.include=!0})),e})).map(U)].join("")}function J(t,e={}){const r=function(t){(t instanceof NodeList||t instanceof HTMLCollection)&&(t=Array.from(t));const e=(Array.isArray(t)?t:[t]).filter(n);return[...new Set(e)]}(t),i=function(t,e={}){const n=Object.assign(Object.assign({},u),e);return{selectors:(r=n.selectors,Array.isArray(r)?r.filter((t=>{return e=o,n=t,Object.values(e).includes(n);var e,n})):[]),whitelist:l(n.whitelist),blacklist:l(n.blacklist),root:d(n.root,t),combineWithinSelector:!!n.combineWithinSelector,combineBetweenSelectors:!!n.combineBetweenSelectors,includeTag:!!n.includeTag,maxCombinations:m(n.maxCombinations),maxCandidates:m(n.maxCandidates)};var r}(r[0],e);let c="",s=i.root;function a(){return function(t,e,n="",r){if(0===t.length)return null;const o=[t.length>1?t:[],...N(t,e).map((t=>[t]))];for(const t of o){const e=H(t,0,n,r);if(e)return{foundElements:t,selector:e}}return null}(r,s,c,i)}let f=a();for(;f;){const{foundElements:t,selector:e}=f;if(b(r,e,i.root))return e;s=t[0],c=e,f=a()}return r.length>1?r.map((t=>J(t,i))).join(S):function(t){return t.map(z).join(S)}(r)}const K=J;return e})()));'};import{randomUUID as wp}from"crypto";import bp from"dedent";import{distance as Cp}from"fastest-levenshtein";import{existsSync as Ep,readFileSync as Tp,rmSync as Hl}from"fs";import vp from"js-beautify";import{cloneDeep as Rp}from"lodash-es";import{homedir as Ap}from"os";import as from"p-timeout";import{basename as Wl,join as jl}from"path";import{chromium as xp,devices as Ip}from"playwright";import{errors as Lp}from"playwright";import{addExtra as Pp}from"playwright-extra";import Op from"puppeteer-extra-plugin-recaptcha";import Mp from"sharp";import{v4 as Np}from"uuid";var Fr=(r,e)=>{try{let{hostname:t,pathname:n}=new URL(r),{hostname:o,pathname:s}=new URL(e);return t!==o||n!==s}catch{return!1}},kn=r=>{try{return new URL(r),!0}catch{return!1}},cl=r=>!r.toLowerCase().startsWith("http"),Dn=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function Ut(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}var dl={bannedClassSubstrings:["relative","flex","center","justify","auto","sticky","absolute","top","right","left","bottom","items-center"],bannedElementTagNames:["html","head","title","meta","iframe","script","style","path","svg","br","::marker","noscript"],bannedElementAttributes:["data-momentic-id","aria-keyshortcuts","data-ved"],relevantElementAttributes:["name","id","value","type","class","height","width","target","title","href","src","alt","role","headers","scope","checked","required","action","min","max","minlength","maxlength","multiple","pattern","placeholder","accept","data-value","data-testid","data-cy","data-test-id","data-test","data-role","data-type","data-action","data-aria-hidden","data-hidden","data-handleid","data-handlepos","aria-label","aria-role","aria-selected","aria-disabled","aria-hidden"]};function ul(r){if(r[0]?.match(/[0-9a-zA-Z]/)===null)return!0;if(r.length>10){let d=Math.floor(r.length/8);if((r.match(/[-_:/ ]/g)??[]).length<d)return!0}if((r.match(/[^0-9a-zA-Z.]/g)??[]).length/r.length>.2)return!0;let t=(r.match(/[0-9]/g)??[]).length;if(t/r.length>.3)return!0;let n=(r.toLowerCase().match(/[aeiou]/gi)??[]).length;if((r.toLowerCase().match(/[bcdfghjklmnpqrstvwxyz]/gi)??[]).length/n>5)return!0;let s=new Set(["a","e","i","o","u","y"]),i=0,a=0;for(let d of r.toLowerCase())d>="a"&&d<="z"&&!s.has(d)?(a++,a>i&&(i=a)):a=0;if(i>4)return!0;let l=(r.match(/[A-Z]/g)??[]).length,c=(r.match(/[a-z]/g)??[]).length,u=Math.ceil(r.length*.3);return!!(c&&t&&Math.abs(c-t)<u||c&&l&&Math.abs(c-l)<u)}import{randomUUID as hl}from"crypto";import{distance as Zo}from"fastest-levenshtein";import{cloneDeep as fl}from"lodash-es";import Hm from"p-timeout";var ml=new Set(["about:blank","chrome-error://chromewebdata/"]),pl=3,Ue="data-momentic-id",gl=500,Qo=["button","image","generic","graphics-symbol","tab","link","menuitem","group"];var Wm=["focusable","keyshortcuts","controls","live","relevant","orientation"],Gm=["selected","readonly","modal","required","invalid"],jm=["id","name","role","content"],Vm=["textbox","checkbox","combobox","table","caption","columnheader","rowheader","gridcell","row","rowgroup","cell","image","svgroot","button","link","list","listitem","tablist","tabpanel","tab","searchbox","menu","menubar","form","dialog","alertdialog","banner","navigation","main","menuitem","menuitemcheckbox","menuitemradio","option","radio","progressbar","switch"],Km=["notRendered","notVisible","ariaHiddenElement","ariaHiddenSubtree","activeAriaModalDialog"],qm=["menulistpopup","statictext","inlinetextbox"],Ym=80,Un=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],Xm=["cite"],Jm={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"]},yl={indentLevel:0,noID:!1,noChildren:!1,noProperties:!1,noContent:!1,maxLevel:void 0,neighbors:void 0},es=class r{id;role;name;tagName;content;properties;dataMomenticId;pathFromRoot;parent;children;domNode;backendNodeID;ignoredByCDP;constructor(e){if(this.id=e.id,this.role=e.role,this.name=e.name,this.content=e.content,this.properties={},this.pathFromRoot=e.pathFromRoot,this.children=e.children,this.backendNodeID=e.backendNodeID,this.ignoredByCDP=e.ignoredByCDP,e.properties&&e.properties.forEach(t=>{t.name==="keyshortcuts"?this.dataMomenticId=parseInt(t.value.value):this.properties[t.name]=t.value.value}),e.domNode){this.domNode=e.domNode,this.tagName=e.domNode.tagName||void 0;let t=e.domNode.attributes.id;this.name=this.name||e.domNode.attributes.name||(t&&!ul(t)?t:""),this.role=this.role||(e.domNode.attributes.role??""),rp(this.properties,e.domNode)}}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(){return Vm.includes(this.role.toLowerCase())||!this.properties.hidden&&(this.properties.focusable||this.properties.settable)||this.children.some(e=>e.role==="StaticText")?!0:!!this.name.trim()||!!this.content||Object.keys(this.properties).some(e=>e.startsWith("data"))}serialize(e=yl){let t=Object.assign({},yl,e),{indentLevel:n,noChildren:o,noProperties:s,noID:i,noContent:a}=t,l=fl(this.properties),c=" ".repeat(n),u=this.role||"",d=this.tagName??"unknown",p=this.name;u==="heading"&&p==="heading"&&(p="");let g=Un.includes(this.role)||Xm.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${c}${p}
|
|
1600
|
+
`;let m=`${c}<${d}`;if(!i&&!g&&(m+=` id="${this.id}"`),u&&u!=="generic"&&u!==d&&!(Jm[u]??[]).includes(d)&&(m+=` role=${JSON.stringify(u)}`),p&&(m+=` name=${JSON.stringify(p)}`),this.content&&!a&&(m+=` content=${JSON.stringify(this.content)}`),Object.keys(l).length>0&&!s&&Object.entries(l).forEach(([f,S])=>{if(!Wm.includes(f)){if(Gm.includes(f)&&(!S||S==="false"))return;if(f==="value"&&a&&(l.type==="text"||this.role==="textbox"))return;if(f==="type"&&S===d)return;typeof S=="string"?m+=` ${f}="${S}"`:typeof S=="boolean"?S?m+=` ${f}`:m+=` ${f}={false}`:typeof S<"u"&&(m+=` ${f}={${JSON.stringify(S)}}`)}}),d==="::before"||d==="::after"){let f="";for(let S of this.children)f+=S.serialize({...e,indentLevel:n,neighbors:0});return f}let h=e.maxLevel!==void 0&&n/2>=e.maxLevel;if(this.children.length===0||o||h)m+=` />
|
|
1601
|
+
`;else{let f="";for(let w of this.children)f+=w.serialize({...e,indentLevel:n+2,neighbors:0});let S=f.trim();S.length<=Ym&&!S.includes(`
|
|
1602
|
+
`)?m+=`>${S}</${d}>
|
|
1603
|
+
`:m+=`>
|
|
1562
1604
|
${f}${c}</${d}>
|
|
1563
1605
|
`}if(e.neighbors!==void 0&&e.neighbors>0&&this.parent){let f=this.parent.children.findIndex(b=>b.id===this.id),S=f>0?this.parent.children[f-1]?.serialize({...e,neighbors:0}):"",w=f<this.parent.children.length-1?this.parent.children[f+1]?.serialize({...e,neighbors:0}):"";return`${S||""}
|
|
1564
|
-
${
|
|
1565
|
-
${w||""}`}return
|
|
1606
|
+
${m}
|
|
1607
|
+
${w||""}`}return m}shallowClone(){let e=new r({id:this.id,role:this.role,name:this.name,content:this.content,properties:[],pathFromRoot:this.pathFromRoot,children:[],backendNodeID:this.backendNodeID,ignoredByCDP:this.ignoredByCDP});return e.tagName=this.tagName,e.dataMomenticId=this.dataMomenticId,e.properties=fl(this.properties),e}},ts=class r{constructor(e,t,n){this.root=e;this.a11yIdNodeMap=t;this.dataMomenticIdMap=n}serialize(){return this.root?this.root.serialize():""}pruneUsingRelevantIds(e){let t=this.root;if(!t)throw new Error("Cannot prune a11y tree with no root");function n(s,i=!1){let a=e.has(s.id)||s.id===t?.id,l=s.shallowClone(),c=s.children,u=!1,d=[];for(let p of c){let g=n(p,a||u);g&&(d.push(g),g.parent=l,u=!0)}if(l.children=d,a||u)return l;if(Un.includes(s.role)&&i)return l}let o=n(t);return new r(o,this.a11yIdNodeMap,this.dataMomenticIdMap)}};function Qm(r){return r.name?.value?`"${r.name.value}"`:r.role?.value&&r.role.value!=="none"&&r.role.value!=="generic"?`"${r.role.value}"`:`"${r.nodeId}"`}function Zm(r,e,t,n){return r.bounds.x===null||r.bounds.y===null||r.bounds.height===null||r.bounds.width===null||r.bounds.width===0||r.bounds.height===0?!0:r.bounds.x+r.bounds.width<e.leftBound||r.bounds.x>e.rightBound?(er({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport horizontally"),!1):r.bounds.y+r.bounds.height<e.upperBound||r.bounds.y>e.lowerBound?(er({logger:t,logKey:n,maxCount:5,intervalMs:3e3},{domNode:r,logKey:n},"Filtering out node since it is not in the viewport vertically"),!1):r.computedStyles.display==="none"?(t.debug({domNode:r},"Filtering out node since it has display none"),!1):!0}async function Sl({node:r,parent:e,domGraph:t,inputNodeMap:n,cdpClient:o,logger:s,callId:i,filterByViewport:a,viewportDetails:l}){if(!e&&r.parentId)throw new Error(`Got no parent for accessibility node ${r.nodeId}: ${JSON.stringify(r)}`);let c=(w,b={})=>{},u=r.backendDOMNodeId,d=qm.includes((r.role?.value).toLowerCase());if(!d&&u===void 0)return c("Filtering out node since it doesn't exist in the DOM"),[];let p=u?t.backendIdToNode[u]:void 0;if(!d&&!p)try{let w=await Hm(o.send("DOM.describeNode",{backendNodeId:u}),{milliseconds:500,fallback:()=>{s.debug("Timeout getting node from CDP while processing a11y tree")}});if(w&&w.node.nodeName.toLowerCase()==="slot"&&w.node.distributedNodes?.length)s.debug({redirectedDomNode:p,parentAXNode:e?.getNodeOnlySerializedForm(),originalAXNode:r,cdpResult:w},"Redirected to assigned slot");else return c("Filtering out node since it doesn't exist in the DOM",{cdpResult:w}),[]}catch(w){return c("Filtering out node since it doesn't exist in the DOM",{err:w}),[]}if(p&&e&&a&&l&&r.backendDOMNodeId&&!Zm(p,l,s,i))return p&&(p.momenticIgnored=!0),[];let g=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",m=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"";if(g==="momentic_cursor"||g.includes("chakra"))return p&&(p.momenticIgnored=!0),[];let h=new es({domNode:p,id:parseInt(r.nodeId),role:r.role?.value||"",name:g,content:m,properties:r.properties,children:[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+Qm(r),backendNodeID:r.backendDOMNodeId,ignoredByCDP:r.ignored});for(let w of r.childIds??[]){if(!w)continue;let b=n.get(parseInt(w));if(!b)continue;let T=await Sl({node:b,parent:h,domGraph:t,inputNodeMap:n,cdpClient:o,logger:s,callId:i,filterByViewport:a,viewportDetails:l});T.length&&(h.children=h.children.concat(T))}if(h.role==="StaticText"&&(h.children=[]),h.children.length===1&&h.children[0].role==="StaticText"){let w=h.name,b=h.children[0]?.name;(w===b||!b)&&(h.children=[])}let f=[];for(let w=h.children.length-1;w>=0;w--){let b=h.children[w];if(b.role!=="StaticText"){f.push(b);continue}if(w===0||h.children[w-1].role!=="StaticText"){f.push(b);continue}h.children[w-1].name+=` ${b.name}`}if(h.children=f.reverse(),h.role==="generic"&&h.children.length===1){let w=h.children[0];if(h.name&&!Un.includes(w.role)&&h.name===w.name)return p&&(p.momenticIgnored=!0),h.children}if(!h.isInteresting()&&r.parentId)return p&&(p.momenticIgnored=!0),h.children;for(let w of h.children)w.parent=h;return[h]}function wl({node:r,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:s=1}){r.id=s,s+=1,e.set(r.id,r),r.dataMomenticId?t.set(r.dataMomenticId,r):Un.includes(r.role);for(let i of r.children)s=wl({node:i,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:s});return s}async function bl({a11yGraph:r,domGraph:e,logger:t,cdpClient:n,filterByViewport:o,viewportDetails:s}){if(!r.root)throw new Error("A11y tree has no root");let i=hl();r.allNodes=r.allNodes.filter(d=>d.ignored?!d.ignoredReasons?.find(g=>Km.includes(g.name)):!0);let a=new Map;for(let d of r.allNodes)a.set(parseInt(d.nodeId),d);let l=await Sl({node:r.root,domGraph:e,parent:null,inputNodeMap:a,cdpClient:n,logger:t,callId:hl(),filterByViewport:o,viewportDetails:s});if(l.length>1)throw new Error(`Something went horribly wrong processing the a11y tree, we got: ${JSON.stringify(l)}`);if(l.length===0)throw new Error("There are no accessible elements on this page or frame. Are you sure this website loads properly?");let c=new Map,u=new Map;return wl({node:l[0],a11yIdNodeMap:c,dataMomenticIdMap:u,logger:t,callId:i}),new ts(l[0],c,u)}var rs=(r,e)=>{let t=1,n=["name","role","content"];for(let o of n){let s=r[o];if(typeof s!="string"||!s.trim()||e[o]===void 0)continue;let i=Zo(s,e[o])/Math.min(s.length,e[o].length);i===0?t+=2:i<=.1&&t++}if(e.numChildren!==void 0&&(r.children.length===e.numChildren&&e.numChildren>0?t++:t--),e.nodeOnlySerializedForm){let o=r.getNodeOnlySerializedForm(),s=Zo(o,e.nodeOnlySerializedForm)/Math.min(o.length,e.nodeOnlySerializedForm.length);s===0?t+=2:s<=.1&&t++}if(e.serializedForm){let o=r.serialize({noID:!0,maxLevel:1,neighbors:1}),s=Zo(o,e.serializedForm)/Math.min(o.length,e.serializedForm.length);s===0?t+=2:s<=.1&&t++}return t},ep=["href","src"];function tp(r,e){if(e==="true")return!0;if(e==="false")return!1;try{let t=parseInt(e);if(!isNaN(t))return t}catch{}return ep.includes(r)&&e.length>60?e.slice(0,50)+"...":r==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e}function rp(r,e){e&&Object.entries(e.attributes).forEach(([t,n])=>{dl.relevantElementAttributes.includes(t)&&!jm.includes(t)&&!r[t]&&!t.startsWith("aria")&&t!=="class"&&(r[t]=tp(t,n))})}function Cl(r,e,t=4e3){let n=[],o=Math.floor(t/2),s=`id="${r}"`,i=0,a=e.indexOf(s,i);for(;a!==-1;){let l=Math.max(i,a-o),c=Math.min(e.length,a+o),u=e.slice(l,c);n.push(u),i=c,a=e.indexOf(s,i)}return n.join(`
|
|
1566
1608
|
...
|
|
1567
|
-
`)}var
|
|
1609
|
+
`)}var zt={r:147,g:196,b:125,a:.55},El={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:zt,paddingColor:zt,borderColor:zt,marginColor:zt,eventTargetColor:zt,shapeColor:zt,shapeMarginColor:zt,showInfo:!0,showAccessibilityInfo:!0};var zn=["display","opacity","visibility","height","max-height","overflow"];function Tl({snapshot:r,devicePixelRatio:e,pageFrameId:t}){let n=r.strings,o=r.documents,s=o[0];t&&(s=o.find(l=>n[l.frameId]===t));let i={};return{root:np(s,n,e,i),backendIdToNode:i}}function np(r,e,t,n){let o=r.layout,s={};o.nodeIndex.forEach((m,h)=>{s[m]=h});let i=o.styles,a=o.bounds??[],l=r.nodes,c=l.backendNodeId??[],u=l.attributes??[],d=l.parentIndex??[],p=l.nodeName??[],g=l.inputChecked??{index:[]};for(let m=0;m<c.length;m++){let h=c[m],f=u[m]??[],S=d[m]&&d[m]>=0?d[m]:null,w=s[m],b;w?b=a[w]??[]:b=[];let T={backendNodeId:h,bounds:{x:b[0]??null,y:b[1]??null,width:b[2]??null,height:b[3]??null},computedStyles:{},attributes:{},parentBackendNodeId:S?c[S]:null,tagName:p[m]!==void 0?e[p[m]]?.toLowerCase():void 0,children:[],momenticIgnored:void 0};T.parentBackendNodeId&&n[T.parentBackendNodeId].children.push(h);for(let C of Object.keys(T.bounds)){let A=C;T.bounds[A]!==null&&(T.bounds[A]/=t)}let v=i[m]??[];for(let C=0;C<v.length&&!(C>=zn.length);C++){let A=v[C];if(!A||isNaN(A))continue;let x=e[A];if(!x)continue;let L=zn[C];T.computedStyles[L]=x}for(let C=0;C<f.length;C+=2){let A=f[C],x=f[C+1];if(!A||!x)continue;let L=e[A],H=e[x];!L||!H||(T.attributes[L]=H)}g.index.includes(m)&&(T.attributes.checked="true"),n[T.backendNodeId]=T}return n[c[0]]}async function zr(r){return r.evaluate(e=>{let t=Array.from(e.attributes).reduce((n,o)=>{let s=`${n} ${o.name}="${o.value}"`;return s.length<=50?s:n},"");return`<${e.tagName.toLowerCase()}${t.length>0?t+" ":""}/>`},void 0,{timeout:750})}var j=(r=1e3)=>new Promise(e=>setTimeout(()=>e(),r));function vl(){return window.lastCursorPos}function Rl(){window.globalHintManager||(window.globalHintManager=new window.HintManager),window.globalHintManager.capture()}function Al(){window.globalHintManager&&window.globalHintManager.reset()}function xl(){let r={addIdsToElement:(e,t)=>{let n="getElementsByTagName"in e?e.getElementsByTagName("*"):e.querySelectorAll("*"),o=t;for(let s=0;s<n.length;s++){let i=n[s];i&&(i.setAttribute("data-momentic-id",`${o}`),i.setAttribute("aria-keyshortcuts",`${o}`),o++,i.shadowRoot&&(o=r.addIdsToElement(i.shadowRoot,o)))}return o}};return r.addIdsToElement(document.body,1)}async function Br(r,e){let t=Date.now();for(;Date.now()-t<8e3;){try{if(await r.evaluate(()=>{let o=window;return!!(o.generateCssSelectors&&o.evaluateCssSelectors&&o.generateHtmlCacheAttributes&&o.ldist)},{timeout:1e3}))return}catch{}e.debug("Waiting for momentic browser scripts to load..."),await j(500)}throw new Error(`Failed to load momentic browser scripts on page ${r.url()}`)}var Il=`(function () {
|
|
1568
1610
|
if (document.__customCookieSetterApplied__) {
|
|
1569
1611
|
return;
|
|
1570
1612
|
}
|
|
@@ -1590,41 +1632,41 @@ ${w||""}`}return p}shallowClone(){let e=new r({id:this.id,role:this.role,name:th
|
|
|
1590
1632
|
originalCookieProperty.set.apply(document, [value]);
|
|
1591
1633
|
},
|
|
1592
1634
|
});
|
|
1593
|
-
})()`;var
|
|
1635
|
+
})()`;var Ll=({nodeOnlySerializedHtml:r})=>{let e=window;if(!e.ldist||!e.serializeElementOnlyWithText||!e.getAllElements)return{error:"Momentic core libraries not found"};let t=e.getAllElements(),n,o,s=1/0,i;for(let a of t){let l=e.serializeElementOnlyWithText(a),c=e.ldist(r,l);c<s?(s=c,o=l,n=a.getAttribute("data-momentic-id")??void 0,i=void 0):c===s&&(i=l)}return i?{error:`[MOMENTIC] Multiple HTML elements with same distance (${s}) found:
|
|
1594
1636
|
${i}
|
|
1595
1637
|
==================
|
|
1596
1638
|
${o}
|
|
1597
|
-
`}:{dataMomenticId:n,closestDistance:s,closestNodeSerialized:o}};var Zm=new Set(["document","script","XMLHttpRequest","fetch","xhr"]),ep=new Set(["script","document"]),tp=["cdn.doubleverify.com","securepubads.g.doubleclick.net","pagead2.googlesyndication.com","googleads.g.doubleclick.net","static.criteo.net","intercom.io","googletagmanager.com","google-analytics.com","gstatic.com","apis.google.com","sentry.io","newrelic.com","p.retool.com","m.stripe.com","m.stripe.network","js.stripe.com","px.ads.linkedin.com","www.clarity.ms","assets.trybento.co","udon.trybento.co","cdn.lr-in-prod.com","r.lr-in-prod.com","content.product-usage.assembledhq.com","data.product-usage.assembledhq.com","static.zdassets.com","o.clarity.ms","app.posthog.com","soraban.com","rs.fullstory.com","api2.amplitude.com"],rp=["youtube.com/api/stats","play.google.com/log","youtube.com/youtubei/v1/log_event","retool.com/api/ddMetric","google.com/xjs/_/js"];function Qo(r){return`${r.resourceType()} ${r.method()} ${r.url()}`}function Tl(r){return r=r.replace(/^www\./,""),r}function El(r,e){if(!Zm.has(r.resourceType()))return!1;let t,n,o;try{t=new URL(e),o=r.url(),n=new URL(o)}catch{return!0}return!n.hostname.trim()||tp.some(s=>n.hostname.includes(s))||rp.some(s=>o.includes(s))?!1:ep.has(r.resourceType())||r.method()!=="GET"?!0:Tl(n.hostname).includes(Tl(t.hostname))}import{mkdirSync as np,rmSync as vl,statSync as op}from"fs";import sp from"nodejs-file-downloader";import{tmpdir as ip}from"os";import ap from"p-timeout";import lr,{basename as Al,dirname as lp}from"path";var Br="file://",Rl=lr.join(ip(),"momentic","downloads"),Zo=5e3,cp=50*1024*1024;async function xl({uri:r,logger:e,orgId:t}){if(r.startsWith(Br)){let p=lr.join(Rl,t,r.slice(Br.length));return{filePath:p,momenticUri:r,cleanup:()=>{vl(lp(p),{recursive:!0,force:!0})}}}let n=new URL(r);n.search&&(n.search="");let o=Al(n.href),s=rs(o),i=lr.extname(s);if(ji.includes(i))throw new Error(`Downloading files with extension ${i} is not allowed.`);let a=ts(t),l=new sp({url:r,fileName:s,directory:a,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:Zo}),{downloadStatus:c,filePath:u}=await ap(l.download(),{milliseconds:Zo,message:`Download timed out after ${Zo}ms`});if(c!=="COMPLETE")throw new Error(`Download ended in non-success status: ${c}`);if(!u)throw new Error("File path of successfully downloaded file was empty");let m=op(u).size;if(m>cp)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:m,filePath:u,fileName:s},"Downloaded file to disk");let h;return{filePath:u,momenticUri:es(Al(a),s),cleanup:()=>{clearTimeout(h),h=setTimeout(()=>vl(a,{recursive:!0,force:!0}),5*60*1e3)}}}function es(r,e){return`${Br}${r}/${e}`}function ts(r){let e=Math.random().toString(36).substring(4),t=lr.join(Rl,r,e);return np(t,{recursive:!0}),t}function rs(r){let e=lr.extname(r),t=lr.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function Ll({locator:r,logger:e}){let[t,n]=await r.evaluate(s=>[s.tagName.toLowerCase(),s.getAttribute("class")??""]);if(t!=="input"||!n.toLowerCase().includes("chakra"))return;let o=await r.boundingBox({timeout:2e3});if(o===null){e.warn({elementDisplayString:await Ur(r)},"Attempting to click on element with no bounding box");return}if(!(o.width!==1||o.height!==1))try{await zr(r.page(),e);let s=await r.evaluate(a=>{let l=window;if(!l.CssSelectorGenerator)return{type:"error",error:"[Momentic] Missing CSS selector libraries"};let c=a.parentElement;if(!c)return{type:"error",error:"Input click target has no parent for redirection"};let u=l.CssSelectorGenerator.getCssSelector(c,{}),d=a.getBoundingClientRect(),m=c.getBoundingClientRect(),h={x:Math.min(Math.max(1,d.left-m.left),m.width-1),y:Math.min(Math.max(1,d.top-m.top),m.height-1)};return{type:"result",selector:u,relativePoint:h,serializedForm:c.outerHTML.slice(0,500)}});if(s.type==="error")throw new Error(s.error);let i=r.page().locator(s.selector);return await i.waitFor({state:"attached",timeout:2e3}),e.info(s,`Redirected click to parent element with selector: ${s.selector}`),{locator:i,relativePoint:s.relativePoint}}catch(s){e.error({err:s},"Failed finding parent label for Chakra element");return}}var Ol=["date","datetime-local","month","time","week"],Pl={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 Ml(r,e,t,n){let o=(await r.evaluate(()=>document.activeElement?.getAttribute("type"))??"").toLowerCase();return Pl[o]&&(Pl[o].test(e)&&n.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`),t.pressKeysSequentially=!0,t.clearContent=!1,n.debug("Transforming datetime input to use sequential key presses")),!1}var Np=Bl(Rp(),"momentic","chromium"),cr=process.env.TWO_CAPTCHA_KEY,Bn=Lp(xp);Bn.use(Pp({provider:{id:"2captcha",token:cr},visualFeedback:!0}));async function ns(r,e){let t,n;for(let o=0;o<4;o++)try{return t=r.pages(),(await Promise.all(t.map(async s=>({title:await s.title(),url:s.url()})))).filter(s=>zt(s.url,e))}catch(s){n=s,await G(500)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}async function _p({context:r,localMode:e,browserSettings:t,logger:n}){t.extraHeaders&&await r.setExtraHTTPHeaders(t.extraHeaders),await r.grantPermissions(["clipboard-read","clipboard-write","microphone","camera"]);let o=[r.addInitScript({content:Dr.cssGeneratorLibJs}),r.addInitScript({content:Dr.htmlUtilsLibJs})];e&&o.push(r.addInitScript({content:bl})),r.on("close",()=>{n.debug("Context was closed")}),await Promise.all(o)}var Ge=class r{contextHandlersCleanup;browser;context;page;systemDevicePixelRatio;userControlledBrowserSettings;pageLoadPromise=null;a11yIdToNodeMap=new Map;dataMomenticIdToNodeMap=new Map;mostRecentA11yTree;domGraph=void 0;cdpClient;enricher;storage;logger;localMode;activeFrame;transformer;baseURL;originsVisited=new Set;viewport;onTabsChange=void 0;constructor({storage:e,enricher:t,browser:n,context:o,page:s,baseUrl:i,logger:a,localMode:l,cdpClient:c,userBrowserSettings:u,viewport:d,onTabsChange:m}){Vi(u),this.storage=e,this.enricher=t,this.browser=n,this.context=o,this.cdpClient=c,this.page=s,this.baseURL=i,this.logger=a,this.userControlledBrowserSettings=u,this.localMode=!!l,this.viewport=d||Xe,this.onTabsChange=m}static USER_AGENT=zl["Desktop Chrome"].userAgent;static async init({baseUrl:e,logger:t,storage:n,enricher:o,userBrowserSettings:s,browserArgs:i,contextArgs:a,onClose:l,waitForLoad:c=!0,localMode:u,localAppUrl:d,extensionPath:m,skipPageSetup:h,timeout:p,browserbaseConnectUrl:g,onTabsChange:f}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let S={headless:!0,handleSIGTERM:!1,chromiumSandbox:!1,...i??{}},w={viewport:Xe,userAgent:zl["Desktop Chrome"].userAgent,geolocation:{latitude:37.7749,longitude:-122.4194},locale:"en-US",timezoneId:"America/Los_Angeles",...a??{}},b=null,E,v;if(u)E=await Bn.launchPersistentContext(Np,{...S,...w,ignoreDefaultArgs:["--enable-automation","--enable-strict-mixed-content-checking"],ignoreHTTPSErrors:!0,bypassCSP:!0,args:["--allow-insecure-localhost","--disable-site-isolation-for-policy","--disable-site-isolation-trials",`--unsafely-treat-insecure-origin-as-secure=${d}`,`--load-extension=${m}`,"--test-type=browser","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream"],baseURL:e}),v=E.pages()[0],l&&v.on("close",()=>{l()});else if(g){b=await Bn.connectOverCDP(g);let L=b.contexts()[0];if(!L)throw new Error("Failed to get browserbase default context");let q=L.pages()[0];if(!q)throw new Error("Failed to get browserbase default page");E=L,v=q}else{b=await Bn.launch({...S,args:["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream"]});let L={...w,baseURL:e};E=await b.newContext(L),t.debug({contextArgs:L},"Browser initialization context args"),v=await E.newPage()}await _p({context:E,logger:t,localMode:!!u,browserSettings:s});let C=await r.initCDPSession(E,v,t,p),R=new r({browser:b,context:E,page:v,baseUrl:e,logger:t,storage:n,enricher:o,localMode:u,userBrowserSettings:s,cdpClient:C,viewport:w.viewport||Xe,onTabsChange:f});R.systemDevicePixelRatio=w.deviceScaleFactor;let x=async()=>{try{await R.navigate({url:e,initialNavigation:!h,loadTimeoutMs:p})}catch(L){if(t.error({err:L},"Failed to initialize Chrome browser"),c)throw L}};return c?await x():x(),R}registerContextHandlers(){if(this.contextHandlersCleanup)return;let e=t=>this.handleNewPageEvent(t);this.context.on("page",e),this.contextHandlersCleanup=()=>{this.context.off("page",e)}}async handleAvailableTabsChange(){try{let e=await ns(this.context,this.logger),t=this.page.url();this.onTabsChange?.(e,t)}catch(e){this.logger.error({err:e},"Error sending available tabs to frontend")}}async handlePageErrorEvent(e){}handlePageClosedEvent(e){if(!this.browser||!this.browser.isConnected())return;(async()=>{try{if(this.page!==e){this.logger.info({url:e.url()},"Detected background page was closed"),this.handleAvailableTabsChange();return}this.logger.info({url:e.url()},"Detected active page was closed, switching to another tab");let n=this.context.pages();for(let o=n.length-1;o>=0;o--){let s=n[o];if(!(!s||s.isClosed()||!zt(s.url()))){this.logger.info(`Automatically switching to tab ${o} after close: ${s.url()}`),await this.switchToPageByIndex(s,o);break}}}catch(n){this.logger.warn({err:n},"Error in page close event handler")}})()}handleNewPageEvent(e){try{this.handleNewPageEventHelper(e),this.handleAvailableTabsChange()}catch(t){this.logger.warn({err:t},"Error handling new page open, continuing....")}}handleNewPageEventHelper(e){e.on("close",n=>this.handlePageClosedEvent(n)),e.on("pageerror",n=>this.handlePageErrorEvent(n));let t=e.url().trim();if(!t){this.logger.debug("Not waiting for blank url that is likely triggered by a download link");return}this.logger.debug({url:t},"Detected new page after action, waiting for load to complete"),this.recordUrlVisited(t),this.pageLoadPromise=(async()=>{await e.waitForLoadState("domcontentloaded",{timeout:this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3});try{await e.waitForLoadState("load",{timeout:this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3})}catch{this.logger.debug({url:this.url()},"Timeout elapsed waiting for load state, continuing anyways...")}finally{this.pageLoadPromise=null}})()}async getLocatorFromCdpFrame(e,t){let n=this.page;for(let a of t)n=n.frameLocator(`iframe[src=${JSON.stringify(a)}]`);let o=this.getAttributeFromStringArray(e.attributes??[],"src");if(!o)throw new Error(`Got iframe without src attribute: ${JSON.stringify(e)}`);let s=n.locator(`iframe[src=${JSON.stringify(o)}]`),i=await(await s.evaluateHandle(a=>a)).asElement().contentFrame();if(!i)throw new Error(`Got null frame from locator: ${s}`);await i.waitForLoadState("domcontentloaded",{timeout:this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3});try{await i.waitForLoadState("load",{timeout:this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3})}catch(a){this.logger.error({err:a,frameSrc:o},"Timeout elapsed waiting for frame to fully load, continuing anyways...")}return i}async getMatchingFrame(e){if(e.type!=="url")throw new Error("Only url frame identifiers are supported now");let t=e.url,o=[{node:(await this.cdpClient.send("DOM.getDocument",{pierce:!0,depth:-1})).root,srcChain:[]}],s=[];for(;o.length>0;){let i=o.pop(),a=i.node,l=i.srcChain;if(a.nodeName.toLowerCase()==="iframe"){let c=this.getAttributeFromStringArray(a.attributes??[],"src");if(!c)continue;t.startsWith("/")&&t.endsWith("/")?new RegExp(t.slice(1,-1)).test(c)&&s.push({node:a,frame:await this.getLocatorFromCdpFrame(a,l)}):t.trim()===c.trim()&&s.push({node:a,frame:await this.getLocatorFromCdpFrame(a,l)}),l=[...l,c]}for(let c of a.children??[])o.push({node:c,srcChain:l});a.contentDocument&&o.push({node:a.contentDocument,srcChain:l})}if(s.length===1)return s[0];throw s.length>1?new Error(`Found multiple frames with src matching '${t}'. Please use a more specific selector.`):new Error(`Failed to find frame with src matching: ${t}`)}async getUserPageOrFrame(){if(!this.activeFrame)return this.page;let e=0,t,n="",o;for(;e<3;){try{if(this.activeFrame.type==="url")n=this.activeFrame.url,t=(await this.getMatchingFrame(this.activeFrame)).frame;else throw new Error(`Frame identifier type ${this.activeFrame.type} is not yet supported`);if(t)return t}catch(s){o=s}await G(250),e++}throw new A("InternalWebAgentError",o?o.message:`Failed to find frame with src matching '${n}' on page`)}static async initCDPSession(e,t,n,o=8e3){let s=2,i=async()=>{try{let l=await e.newCDPSession(t);return l.on("Target.targetCrashed",c=>{n.error({payload:c},"CDP session crashed, Momentic will likely not function correctly")}),l.on("Inspector.targetCrashed",c=>{n.error({payload:c},"CDP inspector session crashed, Momentic will likely not function correctly")}),await l.send("Accessibility.enable"),await l.send("DOM.enable"),await l.send("Overlay.enable"),l}catch(l){if(s>0)return n.debug({err:l},"Failed to initialize CDP session, re-creating CDP client"),await G(500),s--,i();throw l}};return await zn(i(),{milliseconds:o,fallback:()=>{throw new Error(`Failed to initialize session within page load timeout (${t.url()})`)}})}ping(){if(this.closed)throw new Error("Page has been closed");if(this.browser&&!this.browser.isConnected())throw new Error("Browser is not connected")}setActiveFrame(e){e?this.activeFrame=e:this.activeFrame=void 0}async reset(e){this.a11yIdToNodeMap.clear(),this.dataMomenticIdToNodeMap.clear(),e.clearCookies&&(this.logger.debug("Clearing cookies"),await this.context.clearCookies());let t=this.context.pages();for(let n=0;n<t.length;n++){if(e.clearStorage){let o=t[n].url();this.logger.debug(`Clearing local storage for tab ${o}`);try{this.originsVisited.delete(new URL(o).origin)}catch{}try{await t[n].evaluate(async()=>{window.localStorage.clear(),window.sessionStorage.clear(),await indexedDB.databases().then(s=>{s.forEach(i=>{i.name&&indexedDB.deleteDatabase(i.name)})})},{timeout:1e3})}catch(s){this.logger.debug({err:s},"Failed clearing site data, continuing...")}}n!==0&&!this.localMode&&(this.logger.debug(`Closing tab ${t[n].url()}`),await t[n].close())}if(this.page=this.context.pages()[0],this.page.isClosed()){this.logger.debug("Page is closed, exiting reset early");return}if(this.cdpClient=await r.initCDPSession(this.context,this.page,this.logger,e.timeout),e.clearStorage)for(let n of this.originsVisited)this.logger.debug({origin:n},"Clearing data using CDP"),await this.cdpClient.send("Storage.clearDataForOrigin",{origin:n,storageTypes:"all"}),this.originsVisited.delete(n);await this.navigate({url:e.url??this.baseURL,initialNavigation:!0,loadTimeoutMs:e.timeout})}async toggleHints(e){let t=this.page;e.state==="on"?(await t.addStyleTag({content:Dr.vimiumCss}),await t.addScriptTag({content:Dr.vimiumJs}),await t.evaluate(yl,{timeout:1e3})):await t.evaluate(Sl,{timeout:1e3})}async showHints(){await this.toggleHints({state:"on"});let e=async()=>{try{await this.toggleHints({state:"off"})}catch(t){this.logger.debug({err:t},"Failed to remove vision hints")}};setTimeout(()=>{e()},3e3)}async cleanup(){if(!this.browser)return;let e=this.browser;this.browser=null,this.contextHandlersCleanup?.();try{this.originsVisited.clear(),await this.page.close(),await this.context.close(),await e.close()}catch(t){throw new Error(`Error cleaning up browser: ${t}`)}finally{this.browser=null}}get closed(){return!this.browser||!this.browser.isConnected()}async html(){return(await this.getUserPageOrFrame()).content()}url(){return this.page.url()}async screenshotWithHints(e){let t=e.saveToDiskPath?.split("."),n=t?.slice(0,-1).join("."),o=t?.slice(-1)[0],s=Buffer.from("");await this.showHints();let i=await this.screenshot({...e,saveToDiskPath:e.saveToDiskPath?`${n}-after-hint.${o}`:void 0});return{before:s,after:i}}async screenshot(e){let{retries:t=1}=e;try{let n=await this.screenshotHelper({...e,retries:t});if(n.byteLength>5e6)this.logger.error("Page screenshot is greater than 5MB, which may cause performance issues with some AI models");else if(n.length===0)throw new Error("Got empty screenshot");return n}catch(n){if(t>0)return this.logger.debug({err:n},"Failed taking screenshot, retrying..."),await G(500),this.screenshot({...e,retries:t-1});throw n}}async screenshotHelper({target:e,quality:t,scale:n="device",saveToDiskPath:o,hideCaret:s,timeout:i,clearHighlights:a=!1}){a&&await this.removeAllHighlights();let l={fullPage:!1,type:"jpeg",quality:t,scale:n,caret:s?"hide":"initial",path:o,timeout:i??4e3};e&&(l.scale="css");let c;if(l.scale==="css"||l.path)c=await this.page.screenshot(l);else{let u=await this.cdpClient.send("Page.captureScreenshot",{format:"jpeg",quality:t,fromSurface:!0,optimizeForSpeed:!0});c=Buffer.from(u.data,"base64")}if(!e)return c;if(e){let u;"id"in e?u=(await this.resolveTarget(null,e)).locator:u=e;let d=await u.boundingBox();if(!d)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:m,y:h,width:p,height:g}=d;if(!p||!g)throw new Error("Attempted to screenshot an element with zero width or height");if(m<0||h<0)throw new Error("Attempted to screenshot an element with negative coordinates");m=Math.floor(m),h=Math.floor(h),p=Math.ceil(p),g=Math.ceil(g);try{c=await Op(c).extract({left:m,top:h,width:p,height:g}).toBuffer()}catch(f){throw new Error(`Failed taking element screenshot at coordinates (${m}, ${h}) with size (${p}, ${g}): ${f}`)}}return c}async getViewport(){return this.viewport}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n,networkIdleTimeoutMs:o=0}){this.registerContextHandlers();let s=n??this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3;tl(e)&&(e=new URL(e,this.baseURL).toString()),this.logger.debug(`Navigating to ${e}`),this.recordUrlVisited(e);let i=Date.now(),a=async()=>{try{await this.page.goto(e,{timeout:s,waitUntil:"domcontentloaded"})}catch(c){throw new A("ActionFailureError",c.message)}try{await this.page.waitForLoadState("load",{timeout:s})}catch(c){this.logger.debug({err:c},"Timeout elapsed waiting for load state, continuing anyways...")}};try{await this.wrapPossibleNavigation(a,o),this.logger.debug({url:e},`Navigation complete in ${Math.floor(Date.now()-i)}ms`)}catch(c){if(c instanceof Error&&c.message.includes("ERR_ABORTED")){this.logger.error({err:c},"Navigation error, possibly due to user cancellation");return}throw c}let l=this.url();if(ol.has(l))throw new A("ActionFailureError",`${e} took too long to load \u{1F61E}. Please ensure the site and your internet are working.`,{},!0);if(t)try{await this.exposeRecordingBindings()}catch(c){c instanceof Error&&c.message.includes("already registered")||this.logger.error({err:c},"Failed to install Momentic libraries for action recording")}this.handleAvailableTabsChange(),this.logger.info({url:e,urlAfterNav:l},"Navigation complete")}async type(e,t={}){await Ml(await this.getUserPageOrFrame(),e,t,this.logger)||(t.clearContent&&(process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace")),t.pressKeysSequentially?await this.page.keyboard.type(e,{delay:100}):await this.page.keyboard.insertText(e))}async scrollIntoView(e){await e.scrollIntoViewIfNeeded({timeout:4e3})}async highlight(e,t){try{let n=await this.resolveTarget(null,e,{skipFetchTree:!0});return await this.highlightTarget(n.locator,t),!0}catch(n){return this.logger.debug({err:n,target:e},"Failed to highlight target"),!1}}async removeAllHighlights(){await(await this.getUserPageOrFrame()).evaluate(()=>{let e=window,t=e.removeHighlightTimers||[];console.log(`[MOMENTIC] Clearing ${t.length} highlights on request`),t.forEach(n=>{clearTimeout(n)}),Object.values(e.removeHighlightFunctions??{}).forEach(n=>{n()})},{timeout:1e3})}async highlightTarget(e,t){try{return await this.removeAllHighlights(),await e.evaluate((n,o)=>{let s=window;s.momenticIsEligible=u=>{let m=window.getComputedStyle(u,null).getPropertyValue("display");if(m==="none"||m==="contents")return!1;let h=u.getBoundingClientRect();return!(!h.height||!h.width)},s.removeHighlightTimers=s.removeHighlightTimers||[],s.removeHighlightFunctions=s.removeHighlightFunctions||{};let i=0;for(;!s.momenticIsEligible(n)&&i<3;){if(!n.parentElement)throw new Error("No eligible non-empty parent found for highlighting");n=n.parentElement,i++}let a=n.style.getPropertyValue("outline"),l=n.style.getPropertyPriority("outline");n.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let c=`momentic${Math.floor(Math.random()*1e7)}`;s[c]=()=>{n.style.removeProperty("outline"),n.style.setProperty("outline",a,l)},s.removeHighlightTimers.push(setTimeout(()=>{s[c](),s.removeHighlightFunctions?.[c]&&delete s.removeHighlightFunctions[c]},2750)),s.removeHighlightFunctions[c]=s[c]},t?.color,{timeout:1e3}),!0}catch(n){return this.logger.debug({err:n},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}recordUrlVisited(e){try{this.originsVisited.add(new URL(e).origin)}catch(t){this.logger.warn({err:t},"Failed to record origin visited")}}async wrapPossibleNavigation(e,t){if(t||(t=this.userControlledBrowserSettings.smartWaitingTimeoutMs??3e3),t===0)return e();let n=this.url(),o=Date.now(),s=Date.now(),i=new Map,a=new Map,l=p=>{try{let g=Qo(p.request());a.set(g,(a.get(g)??0)+1);let f=p.status();f>=500&&this.logger.warn({request:g,status:f},"Received 500 level response")}catch(g){this.logger.error({err:g},"Failed to process response in wrap navigation listener")}},c=p=>{try{let g=Qo(p);if(!El(p,n))return;i.set(g,(i.get(g)??0)+1),s=Date.now()}catch(g){this.logger.error({err:g},"Failed to process request in wrap navigation listener")}};this.pageLoadPromise=null,this.page.on("response",l),this.page.on("request",c);let u=await e(),d=new Set,m=!1;for(;;){if(Date.now()-o>t){m=!0;break}if(Date.now()-s<500){await G(250);continue}let p=!1;d=new Set;for(let g of i.keys())i.get(g)!==a.get(g)&&(p=!0,d.add(g));if(p){await G(250);continue}break}m?this.logger.debug({requests:Array.from(i.keys()).slice(0,10),unfinishedRequests:Array.from(d),responses:Array.from(a.keys()).slice(0,10)},"Timeout elapsed waiting for network stable"):this.logger.debug({url:this.url(),requests:Array.from(i.entries()).slice(0,10)},`Network stable in ${Math.floor(Date.now()-o)}ms`),this.page.off("request",c),this.page.off("response",l),await zn(Promise.resolve(this.pageLoadPromise),{milliseconds:this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3,fallback:()=>{this.logger.error("Timed out waiting for new page to load")}});let h=this.url();if(this.recordUrlVisited(h),Ut(h,n)){this.logger.debug({startUrl:n,newUrl:h},"Detected same-page url change in wrapPossibleNavigation, waiting for load state");let p;try{p=await this.getUserPageOrFrame()}catch(g){this.logger.debug({err:g},"Could not get frame after url change, defaulting to page instead"),p=this.page}await p.waitForLoadState("domcontentloaded",{timeout:this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3});try{await p.waitForLoadState("load",{timeout:t})}catch{this.logger.debug({url:this.url()},"Timeout elapsed waiting for load state, continuing anyways...")}}return u}async loadAuthState(e){let t=this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3;await this.page.waitForLoadState("domcontentloaded",{timeout:t});try{await this.page.waitForLoadState("load",{timeout:t})}catch{this.logger.debug({url:this.url()},"Timeout elapsed waiting for load event before setting auth state, continuing...")}for(let o of e.cookies)await this.setCookie(o);await this.cdpClient.send("DOMStorage.enable");let n=0;for(let o of e.origins??[])for(let s of o.localStorage)try{await this.cdpClient.send("DOMStorage.setDOMStorageItem",{storageId:{securityOrigin:new URL(o.origin).origin,isLocalStorage:!0},key:s.name,value:s.value}),n++}catch(i){this.logger.warn({err:i,origin:o},"Failed to set local storage entry");break}this.logger.debug({storageState:e},`Loaded ${e.cookies.length} cookies and ${n} local storage entries`),await this.refresh()}async saveAuthState(){return this.context.storageState()}async getOpenPageUrls(){return(await ns(this.context,this.logger)).map(t=>t.url)}saveA11yDetailsToCache(e,t){t.id=e.id,t.content=e.content,t.name=e.name,t.role=e.role,t.numChildren=e.children.length,t.serializedForm=e.getSerializedFormWithContext(),t.nodeOnlySerializedForm=e.getNodeOnlySerializedForm()}async saveNodeDetailsToCache(e,t,n,o,s){if(t&&(this.saveA11yDetailsToCache(t,n),t.properties.hidden&&t.properties.hidden!=="false"&&this.logger.warn({serializedForm:t.getSerializedFormWithContext()},"Chose hidden element for action")),!(n.generatedSelectors&&n.generatedSelectors.length>1)){if(o)n.dataMomenticId=o;else{this.logger.debug("No data-momentic-id found for target, skipping HTML attribute generation");return}try{let i=await this.fetchHtmlAttributes(e,o);Object.assign(n,i)}catch(i){this.logger.debug({err:i},"Failed to fetch HTML attributes for target")}if(qo.includes(n?.role??""))try{await this.saveElementVisualAttributes(n,s)}catch(i){this.logger.debug({err:i},"Failed to get element screenshot while saving node details")}}}async saveElementVisualAttributes(e,t){if(!t)return;await t.scrollIntoViewIfNeeded({timeout:4e3});let n=await t.boundingBox();if(!n||!n.width||!n.height){e.boundingBox=void 0,e.screenshotUrl=void 0;return}let{x:o=0,y:s=0,width:i=0,height:a=0}=n;if(e.boundingBox&&Math.abs(e.boundingBox.width-i)<1&&Math.abs(e.boundingBox.height-a)<1&&Math.abs((e.boundingBox.x??0)-o)<1&&Math.abs((e.boundingBox.y??0)-s)<1)return;this.logger.debug({oldBox:e.boundingBox,newBox:n},"Updating element screenshot");let l=await this.screenshot({target:t,scale:"css",timeout:4e3});e.boundingBox=n,e.screenshotUrl=await this.storage.uploadScreenshot(l)}async resolveTargetUsingCssSelectors(e,t){if(!t.generatedSelectors||t.generatedSelectors.length<2||!t.serializedHtml)throw new Error("Insufficient data to resolve target using CSS selectors");let n;try{n=await e.evaluate(l=>window.evaluateCssSelectors(l),{selectors:t.generatedSelectors,lDistThresholdLax:.5,lDistThresholdStrict:.15,serializedNodeWithContext:t.serializedHtml})}catch(l){throw new Error(`Failed to evaluate CSS selectors in browser: ${l}`)}if(n.result)this.logger.debug(n,"CSS selector evaluation returned an element");else throw new Error("CSS selector evaluation returned no eligible elements");let o=n.result,s=parseInt(o.dataMomenticId),i=this.dataMomenticIdToNodeMap.get(s);if(i&&Jo(i,t)<4){let c="Rejecting best CSS selector candidate due to low similarity score";throw new Error(c)}let a=e.locator(o.workingSelectors[0]);return t.generatedSelectors=void 0,await this.saveNodeDetailsToCache(e,i,t,s,a),t.generatedSelectors=Array.from(new Set([...o.workingSelectors??[],...t.generatedSelectors??[]])),{a11yNode:i,displayString:o.serializedElement,locator:a,decisions:[{type:"CSS_SELECTOR",matched:!0,reason:`${o.workingSelectors.length} CSS selectors matched the following element: ${o.serializedElement}`,selectors:o.workingSelectors}]}}async resolveTarget(e,t,n={}){let{skipFetchTree:o=!1,targetName:s}=n;this.logger.debug({target:t,skipFetchTree:o},"Resolve target called");let i=await this.getUserPageOrFrame();if(await zr(i,this.logger),t.id>0&&!Jr(t)){let l=this.a11yIdToNodeMap.get(t.id);if(!l)throw new A("InternalWebAgentError",`Resolving target failed because id ${t.id} does not exist on the page. This generally indicates an incorrect element was targeted.`);let c=await this.getLocatorFromA11yNode(l);return await this.saveNodeDetailsToCache(i,l,t,l.dataMomenticId,c),{locator:c,a11yNode:l,displayString:l.getNodeOnlySerializedForm(),decisions:[]}}let a;try{a=await this.resolveTargetHelper({root:i,target:t,cssSelectorOnly:!0,skipFetchTreeWait:!0,skipFetchTree:o})}catch(l){this.logger.debug({err:l},"Could not resolve target without waiting, retrying with waiting"),a=await this.resolveTargetHelper({root:i,target:t,cssSelectorOnly:!1,skipFetchTreeWait:!1,skipFetchTree:o})}return e?.details?.push({type:"TARGETING",name:s,elementLocationDecisions:a.decisions,pageState:a.pageState,targetSource:t.targetSource}),a}async resolveTargetHelper({root:e,target:t,cssSelectorOnly:n,skipFetchTree:o,skipFetchTreeWait:s}){let i=[];if(t.id<0&&t.selector){let m=e.locator(t.selector),h;try{h=await Ur(m)}catch(p){throw new At(`'${t.selector}' failed to resolve: ${p}`,[{type:"USER_SELECTOR",matched:!1}])}return i.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${t.selector} matched an element on the page.`}),{locator:m,a11yNode:void 0,pageState:void 0,displayString:h,decisions:i}}let a;o||(a=(await this.getBrowserState({skipWait:s})).serialize(),this.logger.debug({skipFetchTreeWait:s,tree:a},"Got a11y tree before attempting target resolution"));let l=this.a11yIdToNodeMap.get(t.id),c=l?.getNodeOnlySerializedForm();if(l&&t.serializedForm&&c===t.serializedForm){let m=await this.getLocatorFromA11yNode(l);return await this.saveNodeDetailsToCache(e,l,t,l.dataMomenticId,m),i.push({type:"A11Y_ID",matched:!0,reason:`An element with the same Chrome-internal accessibility node ID matched the saved content exactly: ${c}.`}),{locator:m,a11yNode:l,displayString:c,decisions:i,pageState:a}}if(t.generatedSelectors){let m,h;try{m=await this.resolveTargetUsingCssSelectors(e,t)}catch(p){h=p}if(m)return{...m,pageState:a,decisions:[...i,...m.decisions]};if(n)throw new Error("Could not resolve target with CSS selector only");i.push({type:"CSS_SELECTOR",matched:!1,reason:h?.message,selectors:Ap(t.generatedSelectors)}),t.generatedSelectors=void 0}if(t.serializedForm&&t.serializedForm.trim().length<10){let m="Refusing to attempt accessibility node comparison since the saved node is too short.";i.push({type:"A11Y_DISTANCE",matched:!1,reason:m,savedElement:t.serializedForm})}else if(t.serializedForm){let m=1/0,h,p;for(let f of this.a11yIdToNodeMap.values()){let S=f.getSerializedFormWithContext(),w=Tp(t.serializedForm,S);w<m?(m=w,h=f,p=void 0):w===m&&(p=f)}let g=Math.ceil(.1*t.serializedForm.length);if(h&&m<g&&m<25)if(p){let f=Cp`
|
|
1639
|
+
`}:{dataMomenticId:n,closestDistance:s,closestNodeSerialized:o}};import{mkdirSync as op,rmSync as Pl,statSync as sp}from"fs";import ip from"nodejs-file-downloader";import{tmpdir as ap}from"os";import lp from"p-timeout";import cr,{basename as Ol,dirname as cp}from"path";var $r="file://",Ml=cr.join(ap(),"momentic","downloads"),ns=1e4,dp=50*1024*1024;async function Nl({uri:r,logger:e,orgId:t}){if(r.startsWith($r)){let m=cr.join(Ml,t,r.slice($r.length));return{filePath:m,momenticUri:r,cleanup:()=>{Pl(cp(m),{recursive:!0,force:!0})}}}let n=new URL(r);n.search&&(n.search="");let o=Ol(n.href),s=is(o),i=cr.extname(s);if(Ji.includes(i))throw new Error(`Downloading files with extension ${i} is not allowed.`);let a=ss(t),l=new ip({url:r,fileName:s,directory:a,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:ns}),{downloadStatus:c,filePath:u}=await lp(l.download(),{milliseconds:ns,message:`Download timed out after ${ns}ms`});if(c!=="COMPLETE")throw new Error(`Download ended in non-success status: ${c}`);if(!u)throw new Error("File path of successfully downloaded file was empty");let p=sp(u).size;if(p>dp)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:p,filePath:u,fileName:s},"Downloaded file to disk");let g;return{filePath:u,momenticUri:os(Ol(a),s),cleanup:()=>{clearTimeout(g),g=setTimeout(()=>Pl(a,{recursive:!0,force:!0}),10*60*1e3)}}}function os(r,e){return`${$r}${r}/${e}`}function ss(r){let e=Math.random().toString(36).substring(4),t=cr.join(Ml,r,e);return op(t,{recursive:!0}),t}function is(r){let e=cr.extname(r),t=cr.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function kl({locator:r,logger:e}){let[t,n]=await r.evaluate(s=>[s.tagName.toLowerCase(),s.getAttribute("class")??""]);if(t!=="input"||!n.toLowerCase().includes("chakra"))return;let o=await r.boundingBox({timeout:2e3});if(o===null){e.warn({elementDisplayString:await zr(r)},"Attempting to click on element with no bounding box");return}if(!(o.width!==1||o.height!==1))try{await Br(r.page(),e);let s=await r.evaluate(a=>{let l=window;if(!l.CssSelectorGenerator)return{type:"error",error:"[Momentic] Missing CSS selector libraries"};let c=a.parentElement;if(!c)return{type:"error",error:"Input click target has no parent for redirection"};let u=l.CssSelectorGenerator.getCssSelector(c,{}),d=a.getBoundingClientRect(),p=c.getBoundingClientRect(),g={x:Math.min(Math.max(1,d.left-p.left),p.width-1),y:Math.min(Math.max(1,d.top-p.top),p.height-1)};return{type:"result",selector:u,relativePoint:g,serializedForm:c.outerHTML.slice(0,500)}});if(s.type==="error")throw new Error(s.error);let i=r.page().locator(s.selector);return await i.waitFor({state:"attached",timeout:2e3}),e.info(s,`Redirected click to parent element with selector: ${s.selector}`),{locator:i,relativePoint:s.relativePoint}}catch(s){e.error({err:s},"Failed finding parent label for Chakra element");return}}var Fl=["date","datetime-local","month","time","week"],Dl={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 Ul(r,e,t,n){let o=(await r.evaluate(()=>document.activeElement?.getAttribute("type"))??"").toLowerCase();return Dl[o]&&(Dl[o].test(e)&&n.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`),t.pressKeysSequentially=!0,t.clearContent=!1,n.debug("Transforming datetime input to use sequential key presses")),!1}var _p=jl(Ap(),"momentic","chromium"),dr=process.env.TWO_CAPTCHA_KEY,Wn=Pp(xp);Wn.use(Op({provider:{id:"2captcha",token:dr},visualFeedback:!0}));async function ls(r,e){let t,n;for(let o=0;o<4;o++)try{return t=r.pages(),(await Promise.all(t.map(async s=>({title:await s.title(),url:s.url()})))).filter(s=>Ut(s.url,e))}catch(s){n=s,await j(500)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}var Ge=class r{static USER_AGENT=Ip["Desktop Chrome"].userAgent;contextInitialized=!1;browser;context;page;systemDevicePixelRatio;userControlledBrowserSettings;pageLoadPromise=null;lastTabChangeEventTimeout=void 0;a11yIdToNodeMap=new Map;dataMomenticIdToNodeMap=new Map;mostRecentA11yTree;domGraph=void 0;cdpClient;enricher;storage;logger;localMode;activeFrame;transformer;baseURL;originsVisited=new Set;viewport;onTabsChange=void 0;constructor({storage:e,enricher:t,browser:n,context:o,page:s,baseUrl:i,logger:a,localMode:l,cdpClient:c,userBrowserSettings:u,viewport:d,onTabsChange:p,systemDevicePixelRatio:g}){Qi(u),this.storage=e,this.enricher=t,this.browser=n,this.context=o,this.cdpClient=c,this.page=s,this.baseURL=i,this.logger=a,this.userControlledBrowserSettings=u,this.localMode=!!l,this.viewport=d||Xe,this.onTabsChange=p,this.systemDevicePixelRatio=g}async initializeContext(){if(this.contextInitialized)return;this.userControlledBrowserSettings.extraHeaders&&await this.context.setExtraHTTPHeaders(this.userControlledBrowserSettings.extraHeaders),await this.context.grantPermissions(["clipboard-read","clipboard-write","microphone","camera"]);let e=[this.context.addInitScript({content:Dr.cssGeneratorLibJs}),this.context.addInitScript({content:Dr.htmlUtilsLibJs})];this.localMode&&e.push(this.context.addInitScript({content:Il}));let t=n=>this.handleNewPageEvent(n);this.context.on("page",t),await this.handleNewPageEventHelper(this.page),this.context.on("close",()=>{this.logger.debug("Chrome browser context was closed"),this.context.off("page",t)}),await Promise.all(e),this.contextInitialized=!0}static async init({baseUrl:e,logger:t,storage:n,enricher:o,userBrowserSettings:s,browserArgs:i,contextArgs:a,onClose:l,waitForLoad:c=!0,localMode:u,localAppUrl:d,extensionPath:p,skipPageSetup:g,timeout:m,browserbaseConnectUrl:h,onTabsChange:f}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let S={headless:!0,handleSIGTERM:!1,chromiumSandbox:!1,...i??{}},w={viewport:Xe,userAgent:s.userAgent??r.USER_AGENT,geolocation:{latitude:37.7749,longitude:-122.4194},locale:"en-US",timezoneId:"America/Los_Angeles",...a??{}},b=null,T,v;if(u)T=await Wn.launchPersistentContext(_p,{...S,...w,ignoreDefaultArgs:["--enable-automation","--enable-strict-mixed-content-checking"],ignoreHTTPSErrors:!0,bypassCSP:!0,args:["--allow-insecure-localhost","--disable-site-isolation-for-policy","--disable-site-isolation-trials",`--unsafely-treat-insecure-origin-as-secure=${d}`,`--load-extension=${p}`,"--test-type=browser","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream"],baseURL:e}),v=T.pages()[0],l&&v.on("close",()=>{l()});else if(h){b=await Wn.connectOverCDP(h);let L=b.contexts()[0];if(!L)throw new Error("Failed to get browserbase default context");let H=L.pages()[0];if(!H)throw new Error("Failed to get browserbase default page");T=L,v=H}else{b=await Wn.launch({...S,args:["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=3","--disable-site-isolation-for-policy","--disable-site-isolation-trials","--autoplay-policy=user-gesture-required","--disable-add-to-shelf","--disable-desktop-notifications","--use-fake-device-for-media-stream","--use-fake-ui-for-media-stream"]});let L={...w,baseURL:e};T=await b.newContext(L),t.debug({contextArgs:L},"Browser initialization context args"),v=await T.newPage()}let C=await r.initCDPSession(T,v,t,m),A=new r({browser:b,context:T,page:v,baseUrl:e,logger:t,storage:n,enricher:o,localMode:u,userBrowserSettings:s,cdpClient:C,viewport:w.viewport||Xe,onTabsChange:f,systemDevicePixelRatio:w.deviceScaleFactor});await A.initializeContext();let x=async()=>{try{await A.navigate({url:e,initialNavigation:!g,loadTimeoutMs:m})}catch(L){if(t.error({err:L},"Failed to initialize Chrome browser"),c)throw L}};return c?await x():x(),A}async handleAvailableTabsChangeHelper(){try{let e=await ls(this.context,this.logger),t=this.page.url();this.onTabsChange?.(e,t)}catch(e){this.logger.error({err:e},"Error sending available tabs to frontend")}}async handleAvailableTabsChange(){clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),1500)}async handlePageErrorEvent(e){}handlePageClosedEvent(e){if(!this.browser||!this.browser.isConnected())return;let t=async()=>{try{if(this.page!==e){this.logger.info({url:e.url()},"Detected background page was closed"),this.handleAvailableTabsChange();return}this.logger.info({url:e.url()},"Detected active page was closed, switching to another tab");let n=this.context.pages();for(let o=n.length-1;o>=0;o--){let s=n[o];if(!(!s||s.isClosed()||!Ut(s.url()))){this.logger.info(`Automatically switching to tab ${o} after close: ${s.url()}`),await this.switchToPageByIndex(s,o);break}}}catch(n){this.logger.warn({err:n},"Error in page close event handler")}};this.pageLoadPromise=t()}async handleNewPageEvent(e){let t=e.url();if(!(!t.trim()||t==="about:blank"))try{this.logger.debug({url:t},"Detected new page event, registering handlers and waiting for load to complete"),await this.handleNewPageEventHelper(e)}catch(n){this.logger.warn({err:n},"Error handling new page open, continuing....")}}async handleNewPageEventHelper(e){e.on("close",n=>this.handlePageClosedEvent(n)),e.on("pageerror",async n=>this.handlePageErrorEvent(n)),e.on("framenavigated",async n=>{n===e.mainFrame()&&await this.handleFrameNavigationEvent(n)});let t=this.pageLoadPromise;this.pageLoadPromise=(async()=>{try{await Promise.resolve(t),await this.waitForPageOrFrameLoad(e),this.handleAvailableTabsChange()}finally{this.pageLoadPromise=null}})()}async handleFrameNavigationEvent(e){let t=e.url();if(!t||t==="about:blank")return;let n=this.pageLoadPromise;this.pageLoadPromise=(async()=>{try{await Promise.resolve(n),await this.waitForPageOrFrameLoad(e),this.handleAvailableTabsChange()}finally{this.pageLoadPromise=null}})()}async getLocatorFromCdpFrame(e,t){let n=this.page;for(let a of t)n=n.frameLocator(`iframe[src=${JSON.stringify(a)}]`);let o=this.getAttributeFromStringArray(e.attributes??[],"src");if(!o)throw new Error(`Got iframe without src attribute: ${JSON.stringify(e)}`);let s=n.locator(`iframe[src=${JSON.stringify(o)}]`),i=await(await s.evaluateHandle(a=>a)).asElement().contentFrame();if(!i)throw new Error(`Got null frame from locator: ${s}`);return await this.waitForPageOrFrameLoad(i),i}async getMatchingFrame(e){if(e.type!=="url")throw new Error("Only url frame identifiers are supported now");let t=e.url,o=[{node:(await this.cdpClient.send("DOM.getDocument",{pierce:!0,depth:-1})).root,srcChain:[]}],s=[];for(;o.length>0;){let i=o.pop(),a=i.node,l=i.srcChain;if(a.nodeName.toLowerCase()==="iframe"){let c=this.getAttributeFromStringArray(a.attributes??[],"src");if(!c)continue;t.startsWith("/")&&t.endsWith("/")?new RegExp(t.slice(1,-1)).test(c)&&s.push({node:a,frame:await this.getLocatorFromCdpFrame(a,l)}):t.trim()===c.trim()&&s.push({node:a,frame:await this.getLocatorFromCdpFrame(a,l)}),l=[...l,c]}for(let c of a.children??[])o.push({node:c,srcChain:l});a.contentDocument&&o.push({node:a.contentDocument,srcChain:l})}if(s.length===1)return s[0];throw s.length>1?new Error(`Found multiple frames with src matching '${t}'. Please use a more specific selector.`):new Error(`Failed to find frame with src matching: ${t}`)}async getUserPageOrFrame(){if(!this.activeFrame)return this.page;let e=0,t,n="",o;for(;e<3;){try{if(this.activeFrame.type==="url")n=this.activeFrame.url,t=(await this.getMatchingFrame(this.activeFrame)).frame;else throw new Error(`Frame identifier type ${this.activeFrame.type} is not yet supported`);if(t)return t}catch(s){o=s}await j(250),e++}throw new R("InternalWebAgentError",o?o.message:`Failed to find frame with src matching '${n}' on page`)}static async initCDPSession(e,t,n,o=8e3){let s=2,i=async()=>{try{let l=await e.newCDPSession(t);return l.on("Target.targetCrashed",c=>{n.error({payload:c},"CDP session crashed, Momentic will likely not function correctly")}),l.on("Inspector.targetCrashed",c=>{n.error({payload:c},"CDP inspector session crashed, Momentic will likely not function correctly")}),await l.send("Accessibility.enable"),await l.send("DOM.enable"),await l.send("Overlay.enable"),l}catch(l){if(s>0)return n.debug({err:l},"Failed to initialize CDP session, re-creating CDP client"),await j(500),s--,i();throw l}};return await as(i(),{milliseconds:o,fallback:()=>{throw new Error(`Failed to initialize session within page load timeout (${t.url()})`)}})}ping(){if(this.closed)throw new Error("Page has been closed");if(this.browser&&!this.browser.isConnected())throw new Error("Browser is not connected")}setActiveFrame(e){e?this.activeFrame=e:this.activeFrame=void 0}async reset(e){this.a11yIdToNodeMap.clear(),this.dataMomenticIdToNodeMap.clear(),e.clearCookies&&await this.context.clearCookies();let t=this.context.pages();for(let s=0;s<t.length;s++){if(e.clearStorage){let i=t[s].url();try{this.originsVisited.delete(new URL(i).origin)}catch{}try{await t[s].evaluate(async()=>{window.localStorage.clear(),window.sessionStorage.clear(),await indexedDB.databases().then(a=>{a.forEach(l=>{l.name&&indexedDB.deleteDatabase(l.name)})})},{timeout:1e3})}catch(a){this.logger.debug({err:a},"Failed clearing site data, continuing...")}}s!==0&&!this.localMode&&(this.logger.debug(`Closing tab ${t[s].url()}`),await t[s].close())}if(this.page=this.context.pages()[0],this.page.isClosed()){this.logger.debug("Page is closed, exiting reset early");return}let n=await r.initCDPSession(this.context,this.page,this.logger,e.timeout),o=this.cdpClient;if(this.cdpClient=n,o.detach(),e.clearStorage)for(let s of this.originsVisited)this.logger.debug({origin:s},"Clearing data using CDP"),await this.cdpClient.send("Storage.clearDataForOrigin",{origin:s,storageTypes:"all"}),this.originsVisited.delete(s);await this.navigate({url:e.url??this.baseURL,initialNavigation:!0,loadTimeoutMs:e.timeout})}async toggleHints(e){let t=this.page;e.state==="on"?(await t.addStyleTag({content:Dr.vimiumCss}),await t.addScriptTag({content:Dr.vimiumJs}),await t.evaluate(Rl,{timeout:1e3})):await t.evaluate(Al,{timeout:1e3})}async showHints(){await this.toggleHints({state:"on"});let e=async()=>{try{await this.toggleHints({state:"off"})}catch(t){this.logger.debug({err:t},"Failed to remove vision hints")}};setTimeout(()=>{e()},3e3)}async cleanup(){if(!this.browser)return;let e=this.browser;this.browser=null;try{this.originsVisited.clear(),await this.page.close(),await this.context.close(),await e.close()}catch(t){throw new Error(`Error cleaning up browser: ${t}`)}finally{this.browser=null}}get closed(){return!this.browser||!this.browser.isConnected()}async html(){return(await this.getUserPageOrFrame()).content()}url(){return this.page.url()}async screenshotWithHints(e){let t=e.saveToDiskPath?.split("."),n=t?.slice(0,-1).join("."),o=t?.slice(-1)[0],s=Buffer.from("");await this.showHints();let i=await this.screenshot({...e,saveToDiskPath:e.saveToDiskPath?`${n}-after-hint.${o}`:void 0});return{before:s,after:i}}async screenshot(e){let{retries:t=1}=e;try{let n=await this.screenshotHelper({...e,retries:t});if(n.byteLength>5e6)this.logger.error("Page screenshot is greater than 5MB, which may cause performance issues with some AI models");else if(n.length===0)throw new Error("Got empty screenshot");return n}catch(n){if(t>0)return this.logger.debug({err:n},"Failed taking screenshot, retrying..."),await j(500),this.screenshot({...e,retries:t-1});throw n}}async screenshotHelper({target:e,quality:t,scale:n="device",saveToDiskPath:o,hideCaret:s,timeout:i,clearHighlights:a=!1}){a&&await this.removeAllHighlights();let l={fullPage:!1,type:"jpeg",quality:t,scale:n,caret:s?"hide":"initial",path:o,timeout:i??4e3};e&&(l.scale="css");let c;if(l.scale==="css"||l.path)c=await this.page.screenshot(l);else{let u=await this.cdpClient.send("Page.captureScreenshot",{format:"jpeg",quality:t,fromSurface:!0,optimizeForSpeed:!0});c=Buffer.from(u.data,"base64")}if(!e)return c;if(e){let u;"id"in e?u=(await this.resolveTarget(null,e)).locator:u=e;let d=await u.boundingBox();if(!d)throw new Error("Attempted to screenshot an element that is not visible on the page");let{x:p,y:g,width:m,height:h}=d;if(!m||!h)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),m=Math.ceil(m),h=Math.ceil(h);try{c=await Mp(c).extract({left:p,top:g,width:m,height:h}).toBuffer()}catch(f){throw new Error(`Failed taking element screenshot at coordinates (${p}, ${g}) with size (${m}, ${h}): ${f}`)}}return c}async getViewport(){return this.viewport}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){cl(e)&&(e=new URL(e,this.baseURL).toString());let o=Date.now();this.logger.debug(`Navigating to ${e}`);try{t||await this.waitForDOMStability();try{await this.page.goto(e,{timeout:n,waitUntil:"domcontentloaded"})}catch(i){throw new R("ActionFailureError",i.message)}await this.waitForPageOrFrameLoad(this.page),this.logger.debug({url:e},`Navigation complete in ${Math.floor(Date.now()-o)}ms`)}catch(i){if(i instanceof Error&&i.message.includes("ERR_ABORTED")){this.logger.error({err:i},"Navigation error, possibly due to user cancellation");return}throw i}let s=this.url();if(ml.has(s))throw new R("ActionFailureError",`${e} took too long to load \u{1F61E}. Please ensure the site and your internet are working.`,{},!0);if(t)try{await this.exposeRecordingBindings()}catch(i){i instanceof Error&&i.message.includes("already registered")||this.logger.error({err:i},"Failed to install Momentic libraries for action recording")}}async type(e,t={},n=!1){await this.directTypeHelper(e,t,n)}async directTypeHelper(e,t={},n=!1){let o=await this.getUserPageOrFrame();if(!await Ul(o,e,t,this.logger)){if(n){let s=Date.now(),i=!1;for(;Date.now()-s<this.smartWaitingTimeout;){let a=await o.evaluate(()=>document.activeElement&&document.activeElement.tagName.toLowerCase());if(a&&a!=="body"){i=!0;break}await j(250)}i||this.logger.warn("No active element found to type into, attempting anyways")}t.clearContent&&(process.platform==="darwin"?await this.page.keyboard.press("Meta+A"):await this.page.keyboard.press("Control+A"),await this.page.keyboard.press("Backspace")),t.pressKeysSequentially?await this.page.keyboard.type(e,{delay:100}):await this.page.keyboard.insertText(e),t.pressEnter&&await this.page.keyboard.press("Enter")}}async scrollIntoView(e){await e.scrollIntoViewIfNeeded({timeout:4e3})}async highlight(e,t){try{let n=await this.resolveTarget(null,e,{skipFetchTree:!0});return await this.highlightTarget(n.locator,t),!0}catch(n){return this.logger.debug({err:n,target:e},"Failed to highlight target"),!1}}async removeAllHighlights(){await(await this.getUserPageOrFrame()).evaluate(()=>{let e=window,t=e.removeHighlightTimers||[];console.log(`[MOMENTIC] Clearing ${t.length} highlights on request`),t.forEach(n=>{clearTimeout(n)}),Object.values(e.removeHighlightFunctions??{}).forEach(n=>{n()})},{timeout:1e3})}async highlightTarget(e,t){try{return await this.removeAllHighlights(),await e.evaluate((n,o)=>{let s=window;s.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)},s.removeHighlightTimers=s.removeHighlightTimers||[],s.removeHighlightFunctions=s.removeHighlightFunctions||{};let i=0;for(;!s.momenticIsEligible(n)&&i<3;){if(!n.parentElement)throw new Error("No eligible non-empty parent found for highlighting");n=n.parentElement,i++}let a=n.style.getPropertyValue("outline"),l=n.style.getPropertyPriority("outline");n.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let c=`momentic${Math.floor(Math.random()*1e7)}`;s[c]=()=>{n.style.removeProperty("outline"),n.style.setProperty("outline",a,l)},s.removeHighlightTimers.push(setTimeout(()=>{s[c](),s.removeHighlightFunctions?.[c]&&delete s.removeHighlightFunctions[c]},2750)),s.removeHighlightFunctions[c]=s[c]},t?.color,{timeout:1e3}),!0}catch(n){return this.logger.debug({err:n},"Failed to add node highlight, a page navigation likely occurred. This is non-fatal for tests."),!1}}recordUrlVisited(e){try{this.originsVisited.add(new URL(e).origin)}catch(t){this.logger.warn({err:t},"Failed to record origin visited")}}async wrapPageLoad(e){return await Promise.resolve(this.pageLoadPromise),await e()}async loadAuthState(e){await this.waitForPageOrFrameLoad(this.page);for(let n of e.cookies)await this.setCookie(n);await this.cdpClient.send("DOMStorage.enable");let t=0;for(let n of e.origins??[])for(let o of n.localStorage)try{await this.cdpClient.send("DOMStorage.setDOMStorageItem",{storageId:{securityOrigin:new URL(n.origin).origin,isLocalStorage:!0},key:o.name,value:o.value}),t++}catch(s){this.logger.warn({err:s,origin:n},"Failed to set local storage entry");break}this.logger.debug({storageState:e},`Loaded ${e.cookies.length} cookies and ${t} local storage entries`),await this.refresh()}async saveAuthState(){return this.context.storageState()}async getOpenPageUrls(){return(await ls(this.context,this.logger)).map(t=>t.url)}saveA11yDetailsToCache(e,t){t.id=e.id,t.content=e.content,t.name=e.name,t.role=e.role,t.numChildren=e.children.length,t.serializedForm=e.getSerializedFormWithContext(),t.nodeOnlySerializedForm=e.getNodeOnlySerializedForm()}async saveNodeDetailsToCache(e,t,n,o,s){if(t&&(this.saveA11yDetailsToCache(t,n),t.properties.hidden&&t.properties.hidden!=="false"&&this.logger.warn({serializedForm:t.getSerializedFormWithContext()},"Chose hidden element for action")),!(n.generatedSelectors&&n.generatedSelectors.length>1)){if(o)n.dataMomenticId=o;else{this.logger.debug("No data-momentic-id found for target, skipping HTML attribute generation");return}try{let i=await this.fetchHtmlAttributes(e,o);Object.assign(n,i)}catch(i){this.logger.debug({err:i},"Failed to fetch HTML attributes for target")}if(Qo.includes(n?.role??""))try{await this.saveElementVisualAttributes(n,s)}catch(i){this.logger.debug({err:i},"Failed to get element screenshot while saving node details")}}}async saveElementVisualAttributes(e,t){if(!t)return;await t.scrollIntoViewIfNeeded({timeout:4e3});let n=await t.boundingBox();if(!n||!n.width||!n.height){e.boundingBox=void 0,e.screenshotUrl=void 0;return}let{x:o=0,y:s=0,width:i=0,height:a=0}=n;if(e.boundingBox&&Math.abs(e.boundingBox.width-i)<1&&Math.abs(e.boundingBox.height-a)<1&&Math.abs((e.boundingBox.x??0)-o)<1&&Math.abs((e.boundingBox.y??0)-s)<1)return;this.logger.debug({oldBox:e.boundingBox,newBox:n},"Updating element screenshot");let l=await this.screenshot({target:t,scale:"css",timeout:4e3});e.boundingBox=n,e.screenshotUrl=await this.storage.uploadScreenshot(l)}async resolveTargetUsingCssSelectors(e,t){if(!t.generatedSelectors||t.generatedSelectors.length<2||!t.serializedHtml)throw new Error("Insufficient data to resolve target using CSS selectors");let n;try{n=await e.evaluate(l=>window.evaluateCssSelectors(l),{selectors:t.generatedSelectors,lDistThresholdLax:.5,lDistThresholdStrict:.15,serializedNodeWithContext:t.serializedHtml})}catch(l){throw new Error(`Failed to evaluate CSS selectors in browser: ${l}`)}if(n.result)this.logger.debug(n,"CSS selector evaluation returned an element");else throw new Error("CSS selector evaluation returned no eligible elements");let o=n.result,s=parseInt(o.dataMomenticId),i=this.dataMomenticIdToNodeMap.get(s);if(t.nodeOnlySerializedForm&&i){let l=rs(i,t);if(l<4){let c=`Rejecting best CSS selector candidate due to low similarity score (${l})`;throw new Error(c)}}let a=e.locator(o.workingSelectors[0]);return t.generatedSelectors=void 0,await this.saveNodeDetailsToCache(e,i,t,s,a),t.generatedSelectors=Array.from(new Set([...o.workingSelectors??[],...t.generatedSelectors??[]])),{a11yNode:i,displayString:o.serializedElement,locator:a,decisions:[{type:"CSS_SELECTOR",matched:!0,reason:`${o.workingSelectors.length} CSS selectors matched the following element: ${o.serializedElement}`,selectors:o.workingSelectors}]}}async resolveTarget(e,t,n={}){let{skipFetchTree:o=!1,targetName:s}=n;this.logger.debug({target:t,skipFetchTree:o},"Resolve target called");let i=await this.getUserPageOrFrame();if(await Br(i,this.logger),t.id>0&&!en(t)){let p=this.a11yIdToNodeMap.get(t.id);if(!p)throw new R("InternalWebAgentError",`Resolving target failed because id ${t.id} does not exist on the page. This generally indicates an incorrect element was targeted.`);let g=await this.getLocatorFromA11yNode(p);return await this.saveNodeDetailsToCache(i,p,t,p.dataMomenticId,g),{locator:g,a11yNode:p,displayString:p.getNodeOnlySerializedForm(),decisions:[]}}let a=Date.now(),l,c=0,u=this.smartWaitingTimeout,d;for(;!l||l-a<u;){c++;try{l=Date.now(),d=await this.resolveTargetHelper({root:i,target:t,cssSelectorOnly:!0,skipFetchTreeWait:!0,skipFetchTree:o}),this.logger.debug(`Resolution succeeded through CSS selectors only (attempt ${c})`);break}catch(p){this.logger.debug({err:p,decisions:p instanceof Ye?p.decisions:[]},`Could not resolve target through CSS selectors only (x${c})`),await j(500)}}return d||(this.logger.debug("Waiting for page stability and retrying all target matching methods"),d=await this.resolveTargetHelper({root:i,target:t,cssSelectorOnly:!1,skipFetchTreeWait:!1,skipFetchTree:o})),e?.details?.push({type:"TARGETING",name:s,elementLocationDecisions:d.decisions,pageState:d.pageState,targetSource:t.targetSource}),d}async resolveTargetHelper({root:e,target:t,cssSelectorOnly:n,skipFetchTree:o,skipFetchTreeWait:s}){let i=[];if(t.id<0&&t.selector){let p=e.locator(t.selector),g;try{g=await zr(p)}catch(m){throw new Ye(`'${t.selector}' failed to resolve: ${m}`,[{type:"USER_SELECTOR",matched:!1}])}return i.push({type:"USER_SELECTOR",matched:!0,reason:`The user-provided CSS selector ${t.selector} matched an element on the page.`}),{locator:p,a11yNode:void 0,pageState:void 0,displayString:g,decisions:i}}let a;o||(a=(await this.getBrowserState({skipWait:s})).serialize(),this.logger.debug({skipFetchTreeWait:s,tree:a},"Got a11y tree before attempting target resolution"));let l=this.a11yIdToNodeMap.get(t.id),c=l?.getNodeOnlySerializedForm();if(l&&t.serializedForm&&c===t.serializedForm){let p=await this.getLocatorFromA11yNode(l);return await this.saveNodeDetailsToCache(e,l,t,l.dataMomenticId,p),i.push({type:"A11Y_ID",matched:!0,reason:`An element with the same Chrome-internal accessibility node ID matched the saved content exactly: ${c}.`}),{locator:p,a11yNode:l,displayString:c,decisions:i,pageState:a}}if(t.generatedSelectors){let p,g;try{p=await this.resolveTargetUsingCssSelectors(e,t)}catch(m){g=m}if(p)return{...p,pageState:a,decisions:[...i,...p.decisions]};if(n)throw new Ye("Could not resolve target with CSS selector only",i);i.push({type:"CSS_SELECTOR",matched:!1,reason:g?.message,selectors:Rp(t.generatedSelectors)}),t.generatedSelectors=void 0}if(t.serializedForm&&t.serializedForm.trim().length<10){let p="Refusing to attempt accessibility node comparison since the saved node is too short.";i.push({type:"A11Y_DISTANCE",matched:!1,reason:p,savedElement:t.serializedForm})}else if(t.serializedForm){let p=1/0,g,m;for(let f of this.a11yIdToNodeMap.values()){let S=f.getSerializedFormWithContext(),w=Cp(t.serializedForm,S);w<p?(p=w,g=f,m=void 0):w===p&&(m=f)}let h=Math.ceil(.1*t.serializedForm.length);if(g&&p<h&&p<25)if(m){let f=bp`
|
|
1598
1640
|
Multiple accessibility nodes have the same string distance - refusing to pick between them:
|
|
1599
1641
|
Candidate 1:
|
|
1600
|
-
${
|
|
1642
|
+
${g.getSerializedFormWithContext()}
|
|
1601
1643
|
=====================
|
|
1602
1644
|
Candidate 2:
|
|
1603
|
-
${p.getSerializedFormWithContext()}`;i.push({type:"A11Y_DISTANCE",matched:!1,reason:f,distance:m,closestElement:h.getNodeOnlySerializedForm(),savedElement:t.serializedForm})}else{let f=await this.getLocatorFromA11yNode(h);return await this.saveNodeDetailsToCache(e,h,t,h.dataMomenticId,f),i.push({type:"A11Y_DISTANCE",matched:!0,reason:`Found an accessibility node on the page within ${g} distance of the saved element.`,distance:m,closestElement:h.getSerializedFormWithContext()}),{locator:f,pageState:a,a11yNode:h,displayString:h.getNodeOnlySerializedForm(),decisions:i}}else i.push({type:"A11Y_DISTANCE",matched:!1,reason:`Closest accessibility node is still too far away (${m} > ${g}) to be considered a match.`,distance:m,closestElement:h?.getSerializedFormWithContext(),savedElement:t.serializedForm})}if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.trim().length<10){let m="Refusing to attempt HTML comparison since the saved element is too short.";i.push({type:"HTML_DISTANCE",matched:!1,reason:m})}else if(t.nodeOnlySerializedHtml){let m=await e.content();m.length>5e5&&(m=m.slice(5e5)+"...");try{let h=await e.evaluate(Cl,{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml}),p=Math.floor(.15*t.nodeOnlySerializedHtml.length);if(h.closestDistance&&h.closestDistance>=p){let g=`Closest HTML candidate still has too far distance (${h.closestDistance}) from threshold (${p})`;i.push({type:"HTML_DISTANCE",matched:!1,reason:g,distance:h.closestDistance,closestElement:h.closestNodeSerialized})}else{if(h.error)throw new Error(h.error);if(h.dataMomenticId){let g=parseInt(h.dataMomenticId),f=this.dataMomenticIdToNodeMap.get(g),S;f?S=await this.getLocatorFromA11yNode(f):S=e.locator(`[${Ue}="${g}"]`);let w=h.closestNodeSerialized??await Ur(S);return await this.saveNodeDetailsToCache(e,f,t,g,S),i.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${p} string comparison distance of the saved element.`,distance:h.closestDistance,closestElement:w,savedElement:t.nodeOnlySerializedHtml}),this.logger.debug({result:h,originalTarget:t,displayString:w},"Resolved cached target to new node with pure html levenshtein distance"),{locator:S,a11yNode:f,displayString:w,decisions:i,pageState:m}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(h)}`)}}catch(h){this.logger.debug({err:h},"Failed to find closest HTML node using levenshtein distance"),i.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${h}`})}}let u=t.screenshotUrl,d=t.role??"";if(u&&qo.includes(d))try{let m=await this.resolveTargetWithScreenshot({screenshotUrl:u,oldTarget:t});return{...m,decisions:[...i,...m.decisions],pageState:a}}catch(m){i.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${m}`,elementImageUrl:u}),this.logger.error({err:m},"Error finding closest element using saved screenshot")}throw this.logger.debug({target:t,decisions:i},"Failed to find any relevant node"),new At(`Could not find any relevant node given cached target: ${JSON.stringify(t)}`,i)}async resolveTargetWithScreenshot({screenshotUrl:e,oldTarget:t}){let n;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let o=await this.screenshot({scale:"css"}),i=await(await fetch(e)).arrayBuffer(),a=Mp(),l=await this.enricher.runTemplateMatching({searchImageBase64String:Buffer.from(i).toString("base64"),pageImageBase64String:o.toString("base64"),id:a});this.logger.debug({id:a,templateMatch:l},"Template matching got successful result");let{target:c,locator:u}=await this.getTargetFromPositionPercentages({percentX:l.x,percentY:l.y}),d=c.boundingBox?.width,m=c.boundingBox?.height;if(!d||!m)throw n="Rejecting target from screenshot due to no bounding box",new Error(n);let h=t.boundingBox?.width??0,p=t.boundingBox?.height??0;if(Math.abs(d-h)>50)throw n=`Rejecting target from screenshot due to width difference (${d-h})`,new Error(n);if(Math.abs(m-p)>50)throw n=`Rejecting target from screenshot due to height difference (${m-p})`,new Error(n);return{locator:u,a11yNode:this.a11yIdToNodeMap.get(c.id),displayString:c.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:e}]}}async resolveTargetWithXY(e,t=!1){if(this.logger.debug({target:e,skipFetchTree:t},"Resolve target through x / y positioning called"),!t){let i=(await this.getBrowserState({})).serialize();this.logger.debug({tree:i},"Got a11y tree for x / y resolution")}let n=await this.getUserPageOrFrame(),{target:o}=await this.getTargetFromPositionPercentages(e);if((o.generatedSelectors??[]).length>0)return{locator:n.locator(o.generatedSelectors[0]),a11yNode:this.a11yIdToNodeMap.get(o.id),displayString:o.nodeOnlySerializedHtml??o.nodeOnlySerializedForm??"Unknown element",decisions:[]};let s=this.a11yIdToNodeMap.get(o.id);if(s&&s.dataMomenticId)return{locator:n.locator(`[${Ue}="${s.dataMomenticId}"]`),a11yNode:s,displayString:s.getNodeOnlySerializedForm(),decisions:[]};throw new Error("Could not resolve target with x / y through either raw HTML or the accessibility tree")}async saveDownloadToDisk(e,t){this.logger.info("Download detected, saving file to disk");let n=await e,o=await n.path(),s=rs(n.suggestedFilename()),i=t();await n.saveAs(Bl(i,s)),Fl(o,{force:!0}),setTimeout(()=>{Fl(i,{recursive:!0,force:!0})},5*60*1e3);let a=es(Ul(i),s);return this.logger.debug({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}async typeIntoTarget(e,t,n={}){await this.highlightTarget(t);let o=2,s=n.force,i=await t.getAttribute("type",{timeout:1e3})??"",a=Ol.some(l=>l===i.toLowerCase());for(;o>0;)try{await t.click({timeout:4e3,noWaitAfter:!0,force:s,position:a?{x:1,y:1}:void 0});break}catch(l){if(o--,o===0)throw l;this.logger.warn({err:l},"Failed clicking on element for type action, retrying with force enabled"),s=!0}return this.type(e,n)}async click(e,t,n={}){let o,s=await Ll({locator:e,logger:this.logger});s&&(e=s.locator,o=s.relativePoint),await this.highlightTarget(e);let i=this.url(),a=await this.getOpenPageUrls(),l;n.waitForDownload&&(l=(async()=>{try{return await this.page.waitForEvent("download",{timeout:1e4})}catch(d){throw d instanceof Ip.TimeoutError?new A("ActionFailureError",`Download did not complete in ${1e4}ms`):d}})());let c=2,u=n.force;for(;c>0;)try{this.logger.debug("Clicking on element with locator"),n.doubleClick?await this.wrapPossibleNavigation(async()=>{await e.dblclick({button:n.rightClick?"right":"left",timeout:4e3,noWaitAfter:!0,position:o,force:u})}):await this.wrapPossibleNavigation(async()=>{let d=await e.getAttribute("target");if(await e.click({button:n.rightClick?"right":"left",timeout:4e3,noWaitAfter:!0,position:o,force:u}),d==="_blank"){this.logger.debug("Waiting for new page promise due to _blank target");let m=Date.now(),h=this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3;for(;!this.pageLoadPromise&&Date.now()-m<h;)await G(250)}}),this.logger.debug("Click completed on element");break}catch(d){if(c--,c===0)throw d;this.logger.warn({err:d},"Failed clicking on element, retrying with 'disable stability checks' enabled"),u=!0,await G(250)}if(n.waitForUrl&&await this.waitForUrl(i,n.waitForUrl,a,this.userControlledBrowserSettings.pageLoadTimeoutMs),l){if(!t.createIsolatedFolder)throw new A("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");return this.logger.info("Waiting for download to start and complete"),{downloadedFile:await zn(this.saveDownloadToDisk(l,t.createIsolatedFolder),{milliseconds:1e4,fallback:()=>{throw new A("ActionFailureError",`Download timed out after ${1e4}ms`)}})}}}async waitForUrl(e,t,n,o){let s=o??this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3,i=4,a;for(let l=0;l<i;l++){if(a=await this.getOpenPageUrls(),a.length!==n.length)for(let c=a.length-1;c>=0;c--){let u=a[c];if(u!==e&&zt(u,this.logger)){await this.switchToPage(u,c);break}}try{await(await this.getUserPageOrFrame()).waitForURL(t,{timeout:Math.max(s/i,500)});break}catch(c){if(l===i-1)throw c}}}async dragAndDrop(e,t,n={}){let o={timeout:8e3,force:n.force};await e.hover(o),await this.page.mouse.down(),await t.hover(o),await G(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async mouseDrag(e,t,n,o,s={}){let i=Object.assign({timeout:4e3},s);o&&await o.hover(i);let a=await(await this.getUserPageOrFrame()).evaluate(fl);a||(this.logger.debug("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,t+a.top,{steps:n}),await G(250),await this.page.mouse.up()}async hover(e,t){await this.highlightTarget(e),await e.hover({timeout:4e3,force:t})}async focus(e){await this.highlightTarget(e),await e.focus({timeout:4e3})}async blur(e){await this.highlightTarget(e),await e.blur({timeout:4e3})}async selectOption(e,t,n=!1){await this.highlightTarget(e);let o={timeout:4e3,force:n,noWaitAfter:!0},s=2;for(;s>0;)try{await e.selectOption(t,o),this.logger.debug(`Selected '${t}' from dropdown`);break}catch(i){if(s--,s===0)throw i;this.logger.debug({err:i},"Failed selecting option, retrying with force enabled"),o.force=!0}}async press(e){await this.wrapPossibleNavigation(()=>this.page.keyboard.press(e),e==="Enter"?void 0:0)}async refresh(e){let t=e?.loadTimeoutMs??this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3,n=async()=>{await this.page.reload({waitUntil:"domcontentloaded",timeout:t});try{await this.page.waitForLoadState("load",{timeout:t})}catch{this.logger.debug({url:this.page.url()},"Timeout elapsed waiting for load state during refresh action, continuing anyways...")}};await this.wrapPossibleNavigation(n,e?.networkIdleTimeoutMs)}async getBrowserStateHelper({skipWait:e=!1,filterByViewport:t=!1,logger:n=this.logger}){let o=await this.getUserPageOrFrame(),s=await this.getViewportOffsetDetails(o),i;this.activeFrame&&(i=(await this.getMatchingFrame(this.activeFrame)).node.frameId,n.debug({iframeId:i},"Resolved iframe id"));let a=await this.getRawA11yTree({root:o,skipWait:e,iframeId:i,logger:n}),l=await this.getDOMTree(s.devicePixelRatio,i),c=await ml({a11yGraph:a,domGraph:l,logger:n,cdpClient:this.cdpClient,filterByViewport:t,viewportDetails:s});if(!c||!c.root)throw new Error("Accessibility tree appears empty");return this.a11yIdToNodeMap=c.a11yIdNodeMap,this.dataMomenticIdToNodeMap=c.dataMomenticIdMap,this.domGraph=l,c}async getBrowserState(e){let{logger:t=this.logger,maxAttempts:n=2}=e,o=0,s=this.url(),i;for(;o<n;){o++;try{return await zn(this.getBrowserStateHelper(e),{milliseconds:8e3})}catch(a){i=a instanceof Error?a.message:`${a}`,o<n&&(t.debug({err:a,url:s},"Error getting a11y tree, retrying..."),await G(500))}}throw new A("ActionFailureError",`Getting accessibility tree failed after ${n} attempts. Are you sure this page is working? Error: ${i}`)}getA11yIdFromDataMomenticId(e){return this.dataMomenticIdToNodeMap.get(e)?.id}async getViewportOffsetDetails(e){let[t,n,o,s,i]=await e.evaluate(()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio]);return{upperBound:t,lowerBound:t+s,leftBound:n,rightBound:n+o,width:o,height:s,devicePixelRatio:this.systemDevicePixelRatio??i}}async getDOMTree(e,t){let n,o=0;for(;!n&&o<3;)try{if(await this.cdpClient.send("DOMSnapshot.enable"),n=await this.cdpClient.send("DOMSnapshot.captureSnapshot",{computedStyles:Dn}),!n||!n.documents.length)throw new Error("Got empty DOM tree")}catch(s){await G(500),this.logger.debug({err:s},"Error fetching DOM tree"),o++}if(!n||!n.documents.length)throw new A("InternalWebAgentError","Error fetching DOM tree");return hl({snapshot:n,devicePixelRatio:e,pageFrameId:t})}async getRawA11yTree({root:e,skipWait:t=!1,iframeId:n=void 0,logger:o=this.logger}){let s={value:Date.now()},i=()=>{s.value=Date.now()};try{let{root:a}=await this.cdpClient.send("DOM.getDocument",{depth:-1,pierce:!0})}catch(a){o.debug({err:a},"Failed to request root node while getting a11y tree")}this.cdpClient.addListener("Accessibility.nodesUpdated",i),this.cdpClient.addListener("DOM.characterDataModified",i),this.cdpClient.addListener("DOM.attributeModified",i),this.cdpClient.addListener("DOM.childNodeCountUpdated",i),this.cdpClient.addListener("DOM.documentUpdated",i);try{return await this.getRawA11yTreeHelper({root:e,skipWait:t,iframeId:n,logger:o,lastUpdateRef:s})}finally{this.cdpClient.removeListener("Accessibility.nodesUpdated",i),this.cdpClient.removeListener("DOM.characterDataModified",i),this.cdpClient.removeListener("DOM.attributeModified",i),this.cdpClient.removeListener("DOM.childNodeCountUpdated",i),this.cdpClient.removeListener("DOM.documentUpdated",i)}}async getRawA11yTreeHelper({root:e,skipWait:t,iframeId:n,logger:o,lastUpdateRef:s}){let i=this.userControlledBrowserSettings.smartWaitingTimeoutMs??3e3,a=!1;if(!t)try{await e.waitForLoadState("domcontentloaded",{timeout:i}),a=!0}catch(m){o.debug({err:m},"Timed out waiting for domcontentloaded event when getting a11y tree, continuing...")}let l=!1,c=Date.now();for(;!t&&Date.now()-c<i;){if(Date.now()-s.value>=750){l=!0;break}await G(250)}o.debug({duration:Date.now()-c,domContentLoadReceived:a,a11yStableReceived:l,skipWait:t},"A11y wait phase completed"),await e.evaluate(wl);let u;if(n)u=(await this.cdpClient.send("Accessibility.getRootAXNode",{frameId:n})).node.backendDOMNodeId;else{let{node:m}=await this.cdpClient.send("Accessibility.getRootAXNode");u=m.backendDOMNodeId}let{nodes:d}=await this.cdpClient.send("Accessibility.queryAXTree",{backendNodeId:u});if(!d||d.length<=1)throw new A("ActionFailureError","No content in accessibility tree");return{root:d[0],allNodes:d}}async clickUsingVisualCoordinates(e,t){let n=await this.getUserPageOrFrame(),{percentX:o,percentY:s}=e,{width:i,height:a}=await this.getViewportOffsetDetails(n),l=Math.ceil(i*o),c=Math.ceil(a*s),u=this.url(),d=await this.getOpenPageUrls();this.logger.debug({pixelDeltaX:l,pixelDeltaY:c,width:i,height:a},"Executing mouse click with visual coordinates"),await this.wrapPossibleNavigation(async()=>this.page.mouse.click(l,c,{button:t.rightClick?"right":"left",clickCount:t.doubleClick?2:1})),t.waitForUrl&&await this.waitForUrl(u,t.waitForUrl,d,this.userControlledBrowserSettings.pageLoadTimeoutMs)}async dragAndDropUsingVisualCoordinates(e,t,n){let o=await this.getUserPageOrFrame(),{percentX:s,percentY:i}=e,{percentX:a,percentY:l}=t,{width:c,height:u}=await this.getViewportOffsetDetails(o),d=Math.ceil(c*s),m=Math.ceil(u*i),h=Math.ceil(c*a),p=Math.ceil(u*l);await this.page.mouse.move(d,m),await this.page.mouse.down(),await this.page.mouse.move(h,p),await G(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){let t=await this.getUserPageOrFrame(),{percentX:n,percentY:o}=e,{width:s,height:i}=await this.getViewportOffsetDetails(t),a=Math.ceil(s*n),l=Math.ceil(i*o);await this.page.mouse.move(a,l)}getAttributeFromStringArray(e,t){let n=e.findIndex(o=>o===t);if(!(n===-1||!e[n+1]))return e[n+1]}async getIDAttributeUsingCDP(e){await this.cdpClient.send("DOM.getDocument",{depth:0});let t=await this.cdpClient.send("DOM.requestNode",{objectId:e}),o=(await this.cdpClient.send("DOM.getAttributes",{nodeId:t.nodeId})).attributes,s=this.getAttributeFromStringArray(o,Ue);if(!s)throw new Error(`Could not find attribute ${Ue} for object ${e}`);return s}async getLocatorFromA11yNode(e){if(!e.backendNodeID)throw new Error(`Node with a11y id ${e.id} has no backend node ID`);return this.getLocatorFromBackendID(e.backendNodeID)}async getLocatorFromBackendID(e){let t=await this.cdpClient.send("DOM.resolveNode",{backendNodeId:e});if(!t||!t.object.objectId)throw new Error(`Could not resolve backend node ${e}`);let n;try{n=await this.getIDAttributeUsingCDP(t.object.objectId)}catch(o){throw this.logger.debug({err:o,object:JSON.stringify(t.object)},"Failed to get ID attribute"),o}return(await this.getUserPageOrFrame()).locator(`[${Ue}="${n}"]`)}async clickUsingCDP(e,t={}){let n=0,o,s=async l=>{let c=await this.getLocatorFromBackendID(l);t.doubleClick?await c.dblclick({timeout:4e3}):await c.click({timeout:4e3,button:t.rightClick?"right":"left",force:t.force})};for(;n<2;)try{return await s(e.backendNodeID),e}catch(l){this.logger.error({err:l},"Failed clicking on node"),o=l,n++,await G(500)}let i=e.parent?.children??[];for(let l of i){if(l.id===e.id)continue;let c=!1,u=Jo(l,e);if(e.name&&l.name===e.name?c=!0:u>=5&&(this.logger.debug({similarityScore:u},"Sibling qualified for click redirection through comparison score"),c=!0),!!c)try{return await s(l.backendNodeID),l}catch(d){this.logger.debug({err:d,candidate:l.getLogForm()},"Failed clicking on sibling during click redirection")}}let a=e.parent;for(n=0;n<sl;){if(!a||["rootwebarea","main"].includes(a.role.toLowerCase()))throw new A("ActionFailureError",o.message,{cause:o});if(!a.backendNodeID){a=a.parent;continue}try{return await s(a.id),a}catch(c){this.logger.debug({err:c,candidate:a.getLogForm()},"Failed clicking on parent during click redirection"),n++,a=a.parent}}throw new A("ActionFailureError",`Max click attempts exhausted on element ${e.getLogForm()}: ${o.message}`,{cause:o})}async getElementLocation(e){let t=await this.cdpClient.send("DOMSnapshot.captureSnapshot",{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0}),n=await this.page.evaluate(()=>window.devicePixelRatio);process.platform==="darwin"&&n===1&&(n=2);let o=t.documents[0],s=o.layout,i=o.nodes,a=i.nodeName||[],l=i.backendNodeId||[],c=s.nodeIndex,u=s.bounds,d=-1;for(let w=0;w<a.length;w++)if(l[w]===e){d=c.indexOf(w);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[m=0,h=0,p=0,g=0]=u[d];m/=n,h/=n,p/=n,g/=n;let f=m+p/2,S=h+g/2;return{centerX:f,centerY:S}}async scroll(e,t,n,o){let s=t==="left"?-1:1,i=o==="up"?-1:1;if(this.activeFrame)await(await this.getUserPageOrFrame()).evaluate(([l,c,u,d])=>window.scrollTo(window.scrollX+(l??window.innerWidth)*u,window.scrollY+(c??window.innerHeight)*d),[e,n,s,i]);else{let a=this.page.viewportSize()||Xe;await this.page.mouse.wheel((e??a.width)*s,(n??a.height)*i)}}async scrollUp(e){await this.scroll(0,null,e??null,"up")}async scrollDown(e){await this.scroll(0,null,e??null,"down")}async scrollLeft(e){await this.scroll(e??null,"left",0,null)}async scrollRight(e){await this.scroll(e??null,"right",0,null)}async goForward(){await this.wrapPossibleNavigation(async()=>this.page.goForward({waitUntil:"domcontentloaded",timeout:this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}))}async goBack(){await this.wrapPossibleNavigation(async()=>this.page.goBack({waitUntil:"domcontentloaded",timeout:this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}))}async changeActivePage(e,t){this.recordUrlVisited(e.url()),this.page=e,this.cdpClient=await r.initCDPSession(this.context,this.page,this.logger,t??this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3)}async createNewTab(e,t){let n=await this.context.newPage();await this.changeActivePage(n,t?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...t})}async switchToPageByIndex(e,t,n){let o=e.url();if(!zt(o,this.logger)){this.logger.error({tabUrl:o},"Refusing to switch to tab with invalid URL");return}this.logger.debug(`Switching to tab ${t} with url ${o}`),await this.changeActivePage(e,n?.loadTimeoutMs);try{let s=async()=>{let i=n?.loadTimeoutMs??8e3;await e.waitForLoadState("domcontentloaded",{timeout:i}),await e.waitForLoadState("load",{timeout:i}),this.logger.debug({url:o},"Timeout elapsed waiting for load state, continuing anyways...")};await this.wrapPossibleNavigation(s,n?.networkIdleTimeoutMs)}catch{this.logger.debug({url:o},"Timeout elapsed waiting for load state during tab switch, continuing anyways...")}}async switchToPage(e,t,n){let o=this.context.pages(),s=await ns(this.context,this.logger);if(t){await this.switchToPageByIndex(o[t],t,n);let i=s[t].url;this.onTabsChange?.(s,i);return}for(let i=0;i<o.length;i++){let a=o[i];if(a.url().includes(e)){await this.switchToPageByIndex(a,i,n);let l=s[i].url;this.onTabsChange?.(s,l);return}}throw new Error(`Could not find page with url containing ${e}`)}async setCookie(e){let t;typeof e=="string"?t=si(e):t=[e],this.logger.debug({cookieSettings:t},"Adding cookies to session"),await this.context.addCookies(t)}async setLocalStorage(e,t){await(await this.getUserPageOrFrame()).evaluate(([o,s])=>{o&&localStorage.setItem(o,s||"")},[e,t])}async solveCloudflareTurnstile(){let t=(await this.getUserPageOrFrame()).locator(".cf-turnstile").locator("iframe").getAttribute("data-sitekey"),n=await fetch("https://2captcha.com/in.php",{method:"POST",body:JSON.stringify({key:cr,method:"turnstile",sitekey:t,pageurl:this.url(),json:1})});if(!n.ok){let i=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},i),new Error(i)}let{request:o}=await n.json(),s=Date.now();for(;Date.now()-s<6e4;){await G(2500);let i=await fetch(`https://2captcha.com/res.php?key=${cr}&action=get&id=${o}&json=1`,{method:"GET"});if(!i.ok){let l=`Captcha solution API returned error response: ${i.statusText}`;throw this.logger.error({text:await i.text()},l),new Error(l)}if((await i.json()).status===1)break}}async solveCaptcha(){await this.getBrowserState({});let e;for(let a of this.a11yIdToNodeMap.values())if(a.role==="image"&&a.name.toLowerCase().includes("captcha")){if(!a.backendNodeID)continue;e=await this.getLocatorFromBackendID(a.backendNodeID);break}if(!e){let a=await(await this.getUserPageOrFrame()).solveRecaptchas();if(!a.captchas||!a.captchas.length)throw new Error("No captchas found on the page");return}let t=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:4e3}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:cr,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!n.ok){let a=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},a),new Error(a)}let{taskId:o}=await n.json(),s=Date.now(),i="";for(;Date.now()-s<6e4;){await G(2500);let a=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:cr,taskId:o})});if(!a.ok){let c=`Captcha solution API returned error response: ${a.statusText}`;throw this.logger.error({text:await a.text()},c),new Error(c)}let l=await a.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}getActiveFrame(){return this.activeFrame}async captureTargetFromClick(){let e=new AbortController;await this.startTreeRefreshCronForRecording(e.signal);let t;try{t=await(await this.getUserPageOrFrame()).evaluate(async()=>{let n=window;if(!n.resolveRecordingTarget){console.error("[Momentic] Missing Momentic recording library functions");return}let o=null;n.targetCaptureClickListener=async i=>(console.log("[Momentic] Target capture listener fired"),i.preventDefault(),o=i.target,!1),document.addEventListener("click",n.targetCaptureClickListener,{capture:!0,once:!0});let s=Date.now();for(;!o&&Date.now()-s<1e4;)await new Promise(i=>setTimeout(i,250));if(!o)throw new Error("Timed out waiting for user to click on an element");return n.resolveRecordingTarget(o)})}catch(n){throw this.logger.error({err:n},"Error recording target click"),new Error(`Error recording click: ${n.message}`)}finally{e.abort()}if(!t)throw new Error("Got no target from recorded click - please make sure you clicked on an interactive element");return this.getTargetFromRecordedClick(t).target}areDomNodeBoundingBoxesSimilar(e,t,n){if(!t.bounds)return this.logger.debug({candidate:t},"Filtering out click candidate since it has no bounding box"),!1;let o=e.bounds,s=o.x??0,i=o.width??0,a=o.height??0,l=s+i,c=o.y??0,u=c+(o.height??0),d=t.bounds,m=d.width??0,h=d.height??0,p=d.x??0,g=p+(d.width??0),f=d.y??0,S=f+(d.height??0);return p<l&&g>s&&f<u&&S>c?Math.abs(i-m)<200&&Math.abs(a-h)<200?!0:(Ot({logger:this.logger,logKey:n,maxCount:5,intervalMs:3e3},{candidate:t,originalNode:e},"Filtering out click candidate since it has a significantly different area"),!1):(Ot({logger:this.logger,logKey:n,maxCount:5,intervalMs:3e3},{candidate:t},"Filtering out click candidate since it does not intersect with the original node"),!1)}getDomCandidatesInA11yTree(e,t){let n=Object.values(t.backendIdToNode),o,s=bp();for(let c of n)if(c.attributes?.[Ue]===e){o=c;break}if(!o)return[];let i=[],a=t.backendIdToNode[o.parentBackendNodeId??-1];for(;a&&(a?.momenticIgnored||!this.areDomNodeBoundingBoxesSimilar(o,a,s));)a=t.backendIdToNode[a.parentBackendNodeId??-1];a&&i.push(a);let l=[o];for(;l.length;){let c=l.shift();for(let u of c.children??[]){let d=t.backendIdToNode[u];d&&!d.momenticIgnored&&this.areDomNodeBoundingBoxesSimilar(o,d,s)?i.push(d):d&&l.push(d)}}return i}getTargetFromRecordedClick(e){this.logger.debug(e,"Got recorded target from click");let{htmlAttributes:t,dataMomenticId:n}=e,s=this.dataMomenticIdToNodeMap.get(n),i={id:s?.id??-1,dataMomenticId:n,targetSource:"CLICK_TO_FIND",...t};return s?this.saveA11yDetailsToCache(s,i):this.logger.warn({htmlAttributes:t},"Could not find corresponding accessibility node for click. Continuing with HTML attributes only"),{target:i,a11yNode:s}}async exposeRecordingBindings(){let e=({frame:t},n)=>{if(!this.transformer)return;let{type:o,dataMomenticId:s,htmlAttributes:i,selectedValue:a}=n;this.logger.debug(n,`${o} event captured on element`);let l=this.dataMomenticIdToNodeMap,c=this.mostRecentA11yTree,u=t.url(),d=l.get(s),m={id:d?.id??-1,dataMomenticId:s,targetSource:"RECORDING",...i};d||this.logger.debug({url:u,htmlAttributes:i},"Could not find corresponding accessibility node for click, continuing with HTML attributes only"),(async()=>{if(!this.transformer){this.logger.warn("No natural language translation since transformer is not initialized anymore");return}this.logger.debug({target:m,url:u},`Generating description for ${o.toLowerCase()}ed target`);let h=c.serialize();d&&h.length>5e3&&(h=pl(d.id,h),this.logger.debug({serializedTree:h},"Trimmed a11y tree for description transformation"));try{await this.transformer.recordElementAction({type:o,target:m,browserState:h,url:u,selectedValue:a})}catch(p){this.logger.error({err:p},`Failed to record ${o} action`)}})()};await this.context.exposeBinding("captureElementEvent",({frame:t},n)=>{try{e({frame:t},n)}catch(o){this.logger.error({err:o},"Failed to capture element interaction")}},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async({},t)=>{this.transformer&&(this.logger.debug(t,"Captured keypress"),this.transformer.recordKeystroke(t))})}async fetchA11yTreeForRecording(){let e=await this.getBrowserState({skipWait:!0,maxAttempts:1,logger:Po});if(this.mostRecentA11yTree=e,Math.random()<.1){let n=this.mostRecentA11yTree.serialize();this.logger.debug({tree:n.length>4e5?"REDACTED_DUE_TO_SIZE":n},"Refreshed a11y tree during recording")}await(await this.getUserPageOrFrame()).evaluate(n=>{let o=window;o.momenticIdsInA11yTree=new Set(n)},Array.from(this.dataMomenticIdToNodeMap.keys()))}async startTreeRefreshCronForRecording(e){if(await this.fetchA11yTreeForRecording(),e.aborted)return;let t,n=!1,o=0,s=0,i=async()=>{if(!(Date.now()-s<750)&&!n){n=!0;try{await this.fetchA11yTreeForRecording(),o=0}catch(a){if(s=Date.now(),o++,o>=8||a.message.includes("crashed")){clearInterval(t),this.logger.error({err:a},"Fatal errors while refreshing a11y tree during recording, exiting...");return}}finally{n=!1}}};t=setInterval(()=>{!this.transformer||e.aborted||i()},il),e.addEventListener("abort",()=>{clearInterval(t),t=void 0})}async startRecording(e,t){this.logger.debug("Starting passive recording mode in Chrome browser"),this.transformer=t,await this.startTreeRefreshCronForRecording(e),e.addEventListener("abort",async()=>{this.transformer=void 0})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(s=>s.value),{timeout:1e3})}getActivePage(){return this.page}async getCondensedHtml(){let e=await this.getUserPageOrFrame();await zr(e,this.logger);let t=await e.evaluate(()=>window.getCondensedHtmlTree?.(),{timeout:1e3});if(!t)throw new A("InternalWebAgentError","Empty HTML tree");return vp.html(t,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1,wrap_line_length:80})}async registerDialogHandler(e){let t=async n=>e==="ACCEPT"?n.accept():n.dismiss();this.page.once("dialog",t)}async executePageFunction(e,t){return(await this.getUserPageOrFrame()).evaluate(e,t)}async getDomNodeFromPositionPercentages(e,{percentX:t,percentY:n}){if(t<0||t>1||n<0||n>1)throw new A("InternalWebAgentError","Invalid percent passed to percentage location");let{width:o,height:s,upperBound:i,leftBound:a,devicePixelRatio:l}=await this.getViewportOffsetDetails(e),c=Math.round(i),u=Math.round(a),d=Math.ceil(o*t),m=Math.ceil(s*n);await this.cdpClient.send("DOM.getDocument",{depth:0});let h;try{h=await this.cdpClient.send("DOM.getNodeForLocation",{x:d+u,y:m+c})}catch(p){throw this.logger.error({err:p,pixelDeltaX:d,pixelDeltaY:m,leftBoundRounded:u,upperBoundRounded:c,devicePixelRatio:l},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return h}async highlightFromPositionPercentages(e){let t=await this.getUserPageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return n?(await this.cdpClient.send("Overlay.highlightNode",{highlightConfig:gl,backendNodeId:n.backendNodeId}),async()=>{try{await this.cdpClient.send("Overlay.hideHighlight",{backendNodeId:n?.backendNodeId})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send("Overlay.hideHighlight")}catch{}}async getTargetFromPositionPercentages(e){let t=await this.getUserPageOrFrame(),n=await this.getDomNodeFromPositionPercentages(t,e),o=this.domGraph?.backendIdToNode[n.backendNodeId],s=o?.attributes[Ue],i=parseInt(s??"");if(!o||!s||isNaN(i))throw new Error("No HTML node was found at the given location");let a=t.locator(`[${Ue}="${s}"]`);for(let d of this.a11yIdToNodeMap.values()){if(d.backendNodeID!==n.backendNodeId)continue;let m={id:d.id,targetSource:"XY_PERCENT"};return await this.saveNodeDetailsToCache(t,d,m,parseInt(s),a),{target:m,locator:a}}let l=this.getDomCandidatesInA11yTree(`${s}`,this.domGraph);for(let d of l){let m=parseInt(d.attributes?.[Ue]??"");if(isNaN(m))continue;let h=t.locator(`[${Ue}="${m}"]`),p=this.dataMomenticIdToNodeMap.get(m),g=p?.id;if(!g)continue;let f={id:g,targetSource:"XY_PERCENT"};return await this.saveNodeDetailsToCache(t,p,f,parseInt(s),h),this.logger.debug({target:f},"Redirected click on non-accessible element to nearest a11y node"),{target:f,locator:h}}let c=await this.fetchHtmlAttributes(t,i);return{target:{id:-1,dataMomenticId:i,targetSource:"XY_PERCENT",...c},locator:a}}async fetchHtmlAttributes(e,t){let n=await e.evaluate(o=>{let s=window;return s.generateHtmlCacheAttributes?s.generateHtmlCacheAttributes(o):(console.error("[MOMENTIC] generateHtmlCacheAttributes is not defined on the window object"),{})},t);return this.logger.debug(n,"Generated HTML attributes for target"),n}async moveMouseFromPositionPercentages(e,t){let n=await this.getUserPageOrFrame(),o;try{o=await this.getViewportOffsetDetails(n)}catch{return}let{width:s,height:i}=o,a=Math.ceil(s*e),l=Math.ceil(i*t);await this.page.mouse.move(a,l,{steps:3})}async clickMouseFromPositionPercentages(e,t){let n=await this.getUserPageOrFrame(),o;try{o=await this.getViewportOffsetDetails(n)}catch{return}let{width:s,height:i}=o,a=Math.ceil(s*e),l=Math.ceil(i*t);await this.page.mouse.click(a,l,{button:"left"})}async scrollFromPositionPercentages(e,t){let n=await this.getUserPageOrFrame(),o;try{o=await this.getViewportOffsetDetails(n)}catch{return}let{width:s,height:i}=o,a=Math.ceil(s*e),l=Math.ceil(i*t);return await this.page.mouse.wheel(a,l),{deltaX:a,deltaY:l}}canSolveCaptchas(){return!!cr}async getFrameSrcUrls(){let e=this.page.url(),t=this.page.frames(),n=[];for(let s of t)if(!s.isDetached())try{let a=await(await s.frameElement()).evaluate(l=>"src"in l?l.getAttribute("src"):null);a&&a!=="about:blank"&&a!==e&&n.push(a)}catch(i){let a=i.message;["detached","browser has been closed"].some(l=>a.includes(l))||this.logger.debug({err:i},"Error fetching frame src url, continuing...")}return Array.from(new Set(n))}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(t){this.logger.debug({err:t,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}async setFileChooserHandlerHelper({filePath:e}){this.page.once("filechooser",async n=>{this.logger.debug({filePath:e},"File chooser triggered"),await n.setFiles(e,{timeout:8e3})});let t=Ep(e).toString("base64");await(await this.getUserPageOrFrame()).evaluate(({fileName:n,base64Data:o})=>{let s=window;s.MomenticFile=class{async getFile(){let i=atob(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=i.charCodeAt(u);let l=new Uint8Array(a),c=new Blob([l]);return new File([c],n)}},s.showOpenFilePicker=async()=>[new s.MomenticFile]},{fileName:Ul(e),base64Data:t})}getSerializedFormFromA11yId(e){return this.a11yIdToNodeMap.get(e)?.getNodeOnlySerializedForm()}};var kp=({socket:r,metadata:e,logger:t,storage:n})=>async({baseUrl:o,environmentName:s})=>{let{testId:i,sessionId:a,orgId:l}=e;t.info({testId:i,sessionId:a,baseUrl:o},"Reset event received");let c=s?await n.fetchEnvironment(l,s,t):void 0,u=null,d=N.getSession(a);if(!d){r.emit("error",{message:"No session to reset"});return}let{controller:m,context:h}=d;await m.browser.reset({clearCookies:!0,clearStorage:!0,url:o});let p=m.browser.baseURL;h.reset({baseUrl:p,currentUrl:m.browser.url(),variablesFromEnvironment:c?.variables??{},envName:s}),u=await m.browser.getViewport();let g=Ge.USER_AGENT;t.info(`Session reset for test ${i} at ${p}`),r.emit("session",{url:p,userAgent:g,viewport:u,sessionId:a})},$l={event:"reset",createHandler:kp};var Dp=({metadata:r})=>{let{sessionId:e}=r;return async({url:t})=>{let n=N.getSession(e);if(!n)throw new Error("No active session found");await n.controller.browser.switchToPage(t)}},Hl={event:"switchTab",createHandler:Dp};var Fp=({metadata:r})=>{let{sessionId:e}=r;return({indices:t},n)=>{let o=N.getSession(e);if(!o)return;let s=o.resultsManager.getContextCopyAtIndices(t)??o.context.toRedactedDisplayCopy();n(s)}},Wl={event:"getTestContext",createHandler:Fp};import{PostHog as Up}from"posthog-node";var zp=new Up("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://app.posthog.com"}),dr=class r extends gn{static async init(e){let t={},n,o=0,s=3;for(;o<s;)try{t=await zp.getAllFlags(e);break}catch(i){n=i,o++,await new Promise(a=>setTimeout(a,500*o))}if(o===s)throw n;return new r(t)}};var Gl=process.env.GCP_TEMPLATE_MATCHING_FUNCTION_ENDPOINT,$n=class{constructor(e){this.logger=e}async runTemplateMatching({searchImageBase64String:e,pageImageBase64String:t,id:n,timeoutMs:o=3e3}){if(!Gl)throw new Error("GCP_TEMPLATE_MATCHING_FUNCTION_ENDPOINT environment variable not set");let s={search_image:e,page_image:t,request_id:n},i=new AbortController,a=setTimeout(()=>{i.abort()},o),c=await fetch(Gl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),signal:i.signal});if(clearTimeout(a),c.status===422){let u=(await c.json()).error;throw new ln(u)}if(!c.ok)throw new Error(`Template matching server returned error code: ${c.status}`);try{let u=await c.json();return pn.parse(u)}catch(u){throw new Error(`Error parsing template matching response: ${u}`)}}};var Bp={type:"a11y",version:"1.0.0",useHistory:"diff",useGoalSplitter:!0},$r=Bp;import Zp from"dedent";import eg from"diff-lines";import{cloneDeep as tg}from"lodash-es";import tc from"p-timeout";var Hn={"gpt-3.5-turbo-1106":16184,"ft:gpt-3.5-turbo-0125:momentic:locator-0508:9NvTpgSc":16184,"ft:gpt-3.5-turbo-1106:momentic:text-assertions:9CEFjgB4":16184,"ft:gpt-3.5-turbo-1106:momentic::8vgMsQca":16184,"gpt-4o-mini-2024-07-18":128e3,"gpt-4o-2024-05-13":128e3,"claude-3-opus-20240229":2e5,"claude-3-sonnet-20240229":2e5,"claude-3-5-sonnet-20240620":2e5,"claude-3-haiku-20240307":2e5};import{z as ur}from"zod";var jl=ur.object({doubleClick:ur.boolean().optional(),rightClick:ur.boolean().optional(),force:ur.boolean().optional(),waitForDownload:ur.boolean().optional(),waitForUrl:ur.string().optional()});var $p=["Shift","CapsLock","Dead","Meta","AudioVolumeUp","AudioVolumeDown"],Wn=class{recordedSteps=new Map;onStepRecord;signal;generator;testId;orgId;storage;indices;logger;constructor({signal:e,onStepRecord:t,generator:n,initialIndices:o,storage:s,testId:i,orgId:a,logger:l}){this.signal=e,this.storage=s,this.logger=l,this.testId=i,this.orgId=a,this.onStepRecord=(c,u,d)=>{this.recordedSteps.set(JSON.stringify(u),{step:c,url:d}),t(c,u)},this.generator=n,this.indices=o}reserveIndexForCommand(e,t){let n=Array.from(this.indices);return this.recordedSteps.set(JSON.stringify(n),{step:{type:"PRESET_ACTION",command:ut(e)},url:t}),this.indices[this.indices.length-1]++,n}async recordElementAction(e){if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let{type:t,target:n,browserState:o,url:s}=e,{indices:i}=e,a,l,c=n.nodeOnlySerializedHtml?.trim()??n.nodeOnlySerializedForm??"Unknown element - please provide a description manually";switch(t){case"CLICK":a="CLICK";let h=ut(a);l={type:"PRESET_ACTION",command:{...h,target:{type:"description",elementDescriptor:c},cache:{target:n}}};break;case"SELECT":a="SELECT_OPTION";let p=ut(a);l={type:"PRESET_ACTION",command:{...p,type:"SELECT_OPTION",target:{type:"description",elementDescriptor:c},cache:{target:n},option:e.selectedValue??"Unknown option"}};break;default:throw new Error(`Unknown action type: ${t}`)}if(i||(i=Array.from(this.indices),this.indices[this.indices.length-1]++),this.onStepRecord(l,i,s),n.id<=0){this.logger.debug("Skipping reverse mapping for non-accessible element");return}let u;try{u=(await this.generator.getReverseMappedDescription({goal:`${n.id}`,browserState:o},{disableCache:!1,orgId:this.orgId})).phrase}catch(h){this.logger.error({err:h},"Error generating reverse mapping description"),u=c}let d=this.recordedSteps.get(JSON.stringify(i))?.step,m=d?.command;m&&"target"in m&&m.target?(m.target={type:"description",elementDescriptor:u},this.onStepRecord({...d,command:m},i,s)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,url:n,dataMomenticId:o}=e;if($p.includes(t)||this.signal.aborted)return;let s="normal";t.length>1&&(s="special");let i;if(s==="normal"){let h=ut("TYPE");i={type:"PRESET_ACTION",command:{...h,target:void 0,value:t,clearContent:!1}}}else{let h=ut("PRESS");i={type:"PRESET_ACTION",command:{...h,value:t}}}let a,l=Array.from(this.indices);l[this.indices.length-1]--;let c=this.recordedSteps.get(JSON.stringify(l)),u=c?.step,d=u?.command,m=c?.url;if(n===m){if(d?.type===i.command.type){let h=d.value,p=i.command.value;i={type:"PRESET_ACTION",command:{...d,value:i.command.type==="PRESS"?`${h}+${p}`:`${h}${p}`}},a=l}else if(d?.type==="CLICK"&&i.command.type==="TYPE")(!o||d.cache?.target.dataMomenticId===parseInt(o))&&(u.command={...i.command,target:d.target,cache:d.cache},i=c.step,a=l);else if(d?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let h=d.value;i={type:"PRESET_ACTION",command:{...d,value:h.slice(0,h.length-1)}},a=l}}a||(a=Array.from(this.indices),this.indices[this.indices.length-1]++),this.onStepRecord(i,a,n)}recordScroll(e){if(this.signal.aborted)return;let{url:t}=e,n=()=>{let{deltaY:a}=e;if(!a)return;let l=Array.from(this.indices);l[this.indices.length-1]--;let c=this.recordedSteps.get(JSON.stringify(l))?.step.command,u;c?.type==="SCROLL_DOWN"&&c.deltaY?(a+=c.deltaY,u=l):c?.type==="SCROLL_UP"&&c.deltaY?(a-=c.deltaY,u=l):(u=Array.from(this.indices),this.indices[this.indices.length-1]++);let d=a>0?"SCROLL_DOWN":"SCROLL_UP",m=ut(d);m.deltaY=Math.abs(a);let h={type:"PRESET_ACTION",command:m};this.onStepRecord(h,u,t)},o=()=>{let{deltaX:a}=e;if(!a)return;let l=Array.from(this.indices);l[this.indices.length-1]--;let c=this.recordedSteps.get(JSON.stringify(l))?.step.command,u;c?.type==="SCROLL_RIGHT"&&c.deltaX?(a+=c.deltaX,u=l):c?.type==="SCROLL_LEFT"&&c.deltaX?(a-=c.deltaX,u=l):(u=Array.from(this.indices),this.indices[this.indices.length-1]++);let d=a>0?"SCROLL_RIGHT":"SCROLL_LEFT",m=ut(d);m.deltaX=Math.abs(a);let h={type:"PRESET_ACTION",command:m};this.onStepRecord(h,u,t)},s=Array.from(this.indices);s[this.indices.length-1]--;let i=this.recordedSteps.get(JSON.stringify(s));i?.step.command.type==="SCROLL_LEFT"||i?.step.command.type==="SCROLL_RIGHT"?(o(),e.deltaY>=20&&n()):(n(),e.deltaX>=20&&o())}};var Gn=3.1;function Hp(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);!(n>=48&&n<=57)&&!(n>=65&&n<=90)&&!(n>=97&&n<=122)&&e++}return e}function jn(r){return Math.ceil(os(r)/Gn)}function os(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
|
|
1604
|
-
`,""),t=t.replaceAll(" ","");let n=Hp(t);return t.length-n+
|
|
1645
|
+
${m.getSerializedFormWithContext()}`;i.push({type:"A11Y_DISTANCE",matched:!1,reason:f,distance:p,closestElement:g.getNodeOnlySerializedForm(),savedElement:t.serializedForm})}else{let f=await this.getLocatorFromA11yNode(g);return await this.saveNodeDetailsToCache(e,g,t,g.dataMomenticId,f),i.push({type:"A11Y_DISTANCE",matched:!0,reason:`Found an accessibility node on the page within ${h} distance of the saved element.`,distance:p,closestElement:g.getSerializedFormWithContext()}),{locator:f,pageState:a,a11yNode:g,displayString:g.getNodeOnlySerializedForm(),decisions:i}}else i.push({type:"A11Y_DISTANCE",matched:!1,reason:`Closest accessibility node is still too far away (${p} > ${h}) to be considered a match.`,distance:p,closestElement:g?.getSerializedFormWithContext(),savedElement:t.serializedForm})}if(t.nodeOnlySerializedHtml&&t.nodeOnlySerializedHtml.trim().length<10){let p="Refusing to attempt HTML comparison since the saved element is too short.";i.push({type:"HTML_DISTANCE",matched:!1,reason:p})}else if(t.nodeOnlySerializedHtml){let p=await e.content();p.length>5e5&&(p=p.slice(5e5)+"...");try{let g=await e.evaluate(Ll,{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml}),m=Math.floor(.15*t.nodeOnlySerializedHtml.length);if(g.closestDistance&&g.closestDistance>=m){let h=`Closest HTML candidate still has too far distance (${g.closestDistance}) from threshold (${m})`;i.push({type:"HTML_DISTANCE",matched:!1,reason:h,distance:g.closestDistance,closestElement:g.closestNodeSerialized})}else{if(g.error)throw new Error(g.error);if(g.dataMomenticId){let h=parseInt(g.dataMomenticId),f=this.dataMomenticIdToNodeMap.get(h),S;f?S=await this.getLocatorFromA11yNode(f):S=e.locator(`[${Ue}="${h}"]`);let w=g.closestNodeSerialized??await zr(S);return await this.saveNodeDetailsToCache(e,f,t,h,S),i.push({type:"HTML_DISTANCE",matched:!0,reason:`Found an element on the page within ${m} string comparison distance of the saved element.`,distance:g.closestDistance,closestElement:w,savedElement:t.nodeOnlySerializedHtml}),this.logger.debug({result:g,originalTarget:t,displayString:w},"Resolved cached target to new node with pure html levenshtein distance"),{locator:S,a11yNode:f,displayString:w,decisions:i,pageState:p}}else throw new Error(`Got invalid HTML evaluation result: ${JSON.stringify(g)}`)}}catch(g){this.logger.debug({err:g},"Failed to find closest HTML node using levenshtein distance"),i.push({type:"HTML_DISTANCE",matched:!1,reason:`Error finding closest HTML node by string distance: ${g}`})}}let u=t.screenshotUrl,d=t.role??"";if(u&&Qo.includes(d))try{let p=await this.resolveTargetWithScreenshot({screenshotUrl:u,oldTarget:t});return{...p,decisions:[...i,...p.decisions],pageState:a}}catch(p){i.push({type:"TEMPLATE_MATCHING",matched:!1,reason:`Error finding closest element using saved screenshot: ${p}`,elementImageUrl:u}),this.logger.error({err:p},"Error finding closest element using saved screenshot")}throw this.logger.debug({target:t,decisions:i},"Failed to find any relevant node"),new Ye(`Could not find any relevant node given cached target: ${JSON.stringify(t)}`,i)}async resolveTargetWithScreenshot({screenshotUrl:e,oldTarget:t}){let n;if(!this.enricher)throw new Error("Enricher not available for screenshot resolution");let o=await this.screenshot({scale:"css"}),i=await(await fetch(e)).arrayBuffer(),a=Np(),l=await this.enricher.runTemplateMatching({searchImageBase64String:Buffer.from(i).toString("base64"),pageImageBase64String:o.toString("base64"),id:a});this.logger.debug({id:a,templateMatch:l},"Template matching got successful result");let{target:c,locator:u}=await this.getTargetFromPositionPercentages({percentX:l.x,percentY:l.y}),d=c.boundingBox?.width,p=c.boundingBox?.height;if(!d||!p)throw n="Rejecting target from screenshot due to no bounding box",new Error(n);let g=t.boundingBox?.width??0,m=t.boundingBox?.height??0;if(Math.abs(d-g)>50)throw n=`Rejecting target from screenshot due to width difference (${d-g})`,new Error(n);if(Math.abs(p-m)>50)throw n=`Rejecting target from screenshot due to height difference (${p-m})`,new Error(n);return{locator:u,a11yNode:this.a11yIdToNodeMap.get(c.id),displayString:c.nodeOnlySerializedHtml??"",decisions:[{type:"TEMPLATE_MATCHING",matched:!0,reason:"Found element using screenshot",elementImageUrl:e}]}}async resolveTargetWithXY(e,t=!1){if(this.logger.debug({target:e,skipFetchTree:t},"Resolve target through x / y positioning called"),!t){let i=(await this.getBrowserState({})).serialize();this.logger.debug({tree:i},"Got a11y tree for x / y resolution")}let n=await this.getUserPageOrFrame(),{target:o}=await this.getTargetFromPositionPercentages(e);if((o.generatedSelectors??[]).length>0)return{locator:n.locator(o.generatedSelectors[0]),a11yNode:this.a11yIdToNodeMap.get(o.id),displayString:o.nodeOnlySerializedHtml??o.nodeOnlySerializedForm??"Unknown element",decisions:[]};let s=this.a11yIdToNodeMap.get(o.id);if(s&&s.dataMomenticId)return{locator:n.locator(`[${Ue}="${s.dataMomenticId}"]`),a11yNode:s,displayString:s.getNodeOnlySerializedForm(),decisions:[]};throw new Error("Could not resolve target with x / y through either raw HTML or the accessibility tree")}async saveDownloadToDisk(e,t){this.logger.info("Download detected, saving file to disk");let n=await e,o=await n.path(),s=is(n.suggestedFilename()),i=t();await n.saveAs(jl(i,s)),Hl(o,{force:!0}),setTimeout(()=>{Hl(i,{recursive:!0,force:!0})},5*60*1e3);let a=os(Wl(i),s);return this.logger.debug({uri:a,downloadFolder:i},"Saved download to isolated folder"),a}async typeIntoTarget(e,t,n={}){await this.highlightTarget(t);let o=2,s=n.force,i=await t.getAttribute("type",{timeout:1e3})??"",a=Fl.some(l=>l===i.toLowerCase());for(;o>0;)try{await t.click({timeout:4e3,force:s,position:a?{x:1,y:1}:void 0});break}catch(l){if(o--,o===0)throw l;this.logger.warn({err:l},"Failed clicking on element for type action, retrying with force enabled"),s=!0}return this.directTypeHelper(e,n)}async click(e,t,n={}){let o,s=await kl({locator:e,logger:this.logger});s&&(e=s.locator,o=s.relativePoint),await this.highlightTarget(e);let i=this.url(),a=await this.getOpenPageUrls(),l;n.waitForDownload&&(l=(async()=>{try{return await this.page.waitForEvent("download",{timeout:1e4})}catch(d){throw d instanceof Lp.TimeoutError?new R("ActionFailureError",`Download did not complete in ${1e4}ms`):d}})());let c=2,u=n.force;for(;c>0;)try{if(this.logger.debug("Clicking on element with locator"),n.doubleClick)await e.dblclick({button:n.rightClick?"right":"left",timeout:4e3,position:o,force:u});else{let d=await e.getAttribute("target");if(await e.click({button:n.rightClick?"right":"left",timeout:4e3,position:o,force:u}),d==="_blank"){this.logger.debug("Waiting for new page promise due to _blank target");let p=Date.now(),g=this.pageLoadTimeout;for(;!this.pageLoadPromise&&Date.now()-p<g;)await j(250)}}this.logger.debug("Click completed on element");break}catch(d){if(c--,c===0)throw d;this.logger.warn({err:d},"Failed clicking on element, retrying with 'disable stability checks' enabled"),u=!0,await j(250)}if(n.waitForUrl&&await this.waitForUrl(i,n.waitForUrl,a),l){if(!t.createIsolatedFolder)throw new R("InternalWebAgentError","Cannot wait for download without a callback to create an isolated folder");return this.logger.info("Waiting for download to start and complete"),{downloadedFile:await as(this.saveDownloadToDisk(l,t.createIsolatedFolder),{milliseconds:1e4,fallback:()=>{throw new R("ActionFailureError",`Download timed out after ${1e4}ms`)}})}}}async waitForUrl(e,t,n,o){let s=o??this.pageLoadTimeout,i=4;n||(n=await this.getOpenPageUrls());let a;for(let l=0;l<i;l++){if(a=await this.getOpenPageUrls(),a.length!==n.length)for(let c=a.length-1;c>=0;c--){let u=a[c];if(u!==e&&Ut(u,this.logger)){await this.switchToPage(u,c);break}}try{await(await this.getUserPageOrFrame()).waitForURL(t,{timeout:Math.max(s/i,500),waitUntil:"domcontentloaded"});break}catch(c){if(l===i-1)throw c;continue}}try{await this.waitForPageOrFrameLoad(this.page)}catch{}}async dragAndDrop(e,t,n={}){let o={timeout:8e3,force:n.force};await e.hover(o),await this.page.mouse.down(),await t.hover(o),await j(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async mouseDrag(e,t,n,o,s={}){let i=Object.assign({timeout:4e3},s);o&&await o.hover(i);let a=await(await this.getUserPageOrFrame()).evaluate(vl);a||(this.logger.debug("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,t+a.top,{steps:n}),await j(250),await this.page.mouse.up()}async hover(e,t){await this.highlightTarget(e),await e.hover({timeout:4e3,force:t})}async focus(e){await this.highlightTarget(e),await e.focus({timeout:4e3})}async blur(e){await this.highlightTarget(e),await e.blur({timeout:4e3})}async selectOption(e,t,n=!1){await this.highlightTarget(e);let o={timeout:4e3,force:n},s=2;for(;s>0;)try{await e.selectOption(t,o),this.logger.debug(`Selected '${t}' from dropdown`);break}catch(i){if(s--,s===0)throw i;this.logger.debug({err:i},"Failed selecting option, retrying with force enabled"),o.force=!0}}async press(e){await this.page.keyboard.press(e)}async refresh(e){let t=e?.loadTimeoutMs??this.pageLoadTimeout,n=async()=>{await this.page.reload({waitUntil:"domcontentloaded",timeout:t}),await this.waitForPageOrFrameLoad(this.page)};await this.wrapPageLoad(n)}async getBrowserStateHelper({skipWait:e=!1,filterByViewport:t=!1,logger:n=this.logger}){await Promise.resolve(this.pageLoadPromise);let o=await this.getUserPageOrFrame(),s=await this.getViewportOffsetDetails(o),i;this.activeFrame&&(i=(await this.getMatchingFrame(this.activeFrame)).node.frameId,n.debug({iframeId:i},"Resolved iframe id"));let a=await this.getRawA11yTree({root:o,skipWait:e,iframeId:i,logger:n}),l=await this.getDOMTree(s.devicePixelRatio,i),c=await bl({a11yGraph:a,domGraph:l,logger:n,cdpClient:this.cdpClient,filterByViewport:t,viewportDetails:s});if(!c||!c.root)throw new Error("Accessibility tree appears empty");return this.a11yIdToNodeMap=c.a11yIdNodeMap,this.dataMomenticIdToNodeMap=c.dataMomenticIdMap,this.domGraph=l,c}async getBrowserState(e){let{logger:t=this.logger,maxAttempts:n=2}=e,o=0,s;for(;o<n;){o++;try{return await as(this.getBrowserStateHelper(e),{milliseconds:this.pageLoadTimeout})}catch(i){s=i instanceof Error?i.message:`${i}`,o<n&&t.debug({err:i,url:this.url()},"Error getting a11y tree, retrying...")}}throw new R("ActionFailureError",`Getting page content failed after ${n} attempts. Are you sure this page is working? Error: ${s}`)}getA11yIdFromDataMomenticId(e){return this.dataMomenticIdToNodeMap.get(e)?.id}async getViewportOffsetDetails(e){let[t,n,o,s,i]=await e.evaluate(()=>[window.scrollY,window.scrollX,window.screen.width,window.screen.height,window.devicePixelRatio]);return{upperBound:t,lowerBound:t+s,leftBound:n,rightBound:n+o,width:o,height:s,devicePixelRatio:this.systemDevicePixelRatio??i}}async getDOMTree(e,t){let n,o=0;for(;!n&&o<3;)try{if(await this.cdpClient.send("DOMSnapshot.enable"),n=await this.cdpClient.send("DOMSnapshot.captureSnapshot",{computedStyles:zn}),!n||!n.documents.length)throw new Error("Got empty DOM tree")}catch(s){await j(500),this.logger.debug({err:s},"Error fetching DOM tree"),o++}if(!n||!n.documents.length)throw new R("InternalWebAgentError","Error fetching DOM tree");return Tl({snapshot:n,devicePixelRatio:e,pageFrameId:t})}async waitForDOMStability(e){let{logger:t=this.logger}=e??{};try{let{root:s}=await this.cdpClient.send("DOM.getDocument",{depth:-1,pierce:!0})}catch(s){t.debug({err:s},"Failed to request root node while getting a11y tree")}let n={value:Date.now()},o=()=>{n.value=Date.now()};this.cdpClient.addListener("Accessibility.nodesUpdated",o),this.cdpClient.addListener("DOM.characterDataModified",o),this.cdpClient.addListener("DOM.attributeModified",o),this.cdpClient.addListener("DOM.childNodeCountUpdated",o),this.cdpClient.addListener("DOM.documentUpdated",o),this.cdpClient.addListener("Page.frameDetached",o),this.cdpClient.addListener("Page.frameStartedLoading",o),this.cdpClient.addListener("Page.frameRequestedNavigation",o);try{await this.waitForDOMStabilityHelper(n,t)}finally{this.cdpClient.removeListener("Accessibility.nodesUpdated",o),this.cdpClient.removeListener("DOM.characterDataModified",o),this.cdpClient.removeListener("DOM.attributeModified",o),this.cdpClient.removeListener("DOM.childNodeCountUpdated",o),this.cdpClient.removeListener("DOM.documentUpdated",o),this.cdpClient.removeListener("Page.frameDetached",o),this.cdpClient.removeListener("Page.frameStartedLoading",o),this.cdpClient.removeListener("Page.frameRequestedNavigation",o)}}async waitForDOMStabilityHelper(e,t=this.logger){let n=!1,o=Date.now(),s=this.smartWaitingTimeout,i;for(;Date.now()-o<s;){if(await j(500),i)try{let{data:a}=await this.cdpClient.send("Page.captureScreenshot",{optimizeForSpeed:!0,quality:25,format:"jpeg"});if(a!==i){i=a;continue}}catch{}else try{let{data:a}=await this.cdpClient.send("Page.captureScreenshot",{optimizeForSpeed:!0,quality:25,format:"jpeg"});i=a}catch{}if(!(Date.now()-e.value<750)){n=!0;break}}t.debug({duration:Date.now()-o,a11yStableReceived:n},"A11y wait phase completed")}async getRawA11yTree({root:e,skipWait:t=!1,iframeId:n=void 0,logger:o=this.logger}){t||await this.waitForDOMStability({logger:o}),await e.evaluate(xl);let s;if(n)s=(await this.cdpClient.send("Accessibility.getRootAXNode",{frameId:n})).node.backendDOMNodeId;else{let{node:a}=await this.cdpClient.send("Accessibility.getRootAXNode");s=a.backendDOMNodeId}let{nodes:i}=await this.cdpClient.send("Accessibility.queryAXTree",{backendNodeId:s});if(!i||i.length<=1)throw new R("ActionFailureError","The page has no content. Are you sure it is working properly?");return{root:i[0],allNodes:i}}async clickUsingVisualCoordinates(e,t){let n=await this.getUserPageOrFrame(),{percentX:o,percentY:s}=e,{width:i,height:a}=await this.getViewportOffsetDetails(n),l=Math.ceil(i*o),c=Math.ceil(a*s),u=this.url(),d=await this.getOpenPageUrls();this.logger.debug({pixelDeltaX:l,pixelDeltaY:c,width:i,height:a},"Executing mouse click with visual coordinates"),await this.wrapPageLoad(async()=>this.page.mouse.click(l,c,{button:t.rightClick?"right":"left",clickCount:t.doubleClick?2:1})),t.waitForUrl&&await this.waitForUrl(u,t.waitForUrl,d)}async dragAndDropUsingVisualCoordinates(e,t,n){let o=await this.getUserPageOrFrame(),{percentX:s,percentY:i}=e,{percentX:a,percentY:l}=t,{width:c,height:u}=await this.getViewportOffsetDetails(o),d=Math.ceil(c*s),p=Math.ceil(u*i),g=Math.ceil(c*a),m=Math.ceil(u*l);await this.page.mouse.move(d,p),await this.page.mouse.down(),await this.page.mouse.move(g,m),await j(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){let t=await this.getUserPageOrFrame(),{percentX:n,percentY:o}=e,{width:s,height:i}=await this.getViewportOffsetDetails(t),a=Math.ceil(s*n),l=Math.ceil(i*o);await this.page.mouse.move(a,l)}getAttributeFromStringArray(e,t){let n=e.findIndex(o=>o===t);if(!(n===-1||!e[n+1]))return e[n+1]}async getIDAttributeUsingCDP(e){await this.cdpClient.send("DOM.getDocument",{depth:0});let t=await this.cdpClient.send("DOM.requestNode",{objectId:e}),o=(await this.cdpClient.send("DOM.getAttributes",{nodeId:t.nodeId})).attributes,s=this.getAttributeFromStringArray(o,Ue);if(!s)throw new Error(`Could not find attribute ${Ue} for object ${e}`);return s}async getLocatorFromA11yNode(e){if(!e.backendNodeID)throw new Error(`Node with a11y id ${e.id} has no backend node ID`);return this.getLocatorFromBackendID(e.backendNodeID)}async getLocatorFromBackendID(e){let t=await this.cdpClient.send("DOM.resolveNode",{backendNodeId:e});if(!t||!t.object.objectId)throw new Error(`Could not resolve backend node ${e}`);let n;try{n=await this.getIDAttributeUsingCDP(t.object.objectId)}catch(o){throw this.logger.debug({err:o,object:JSON.stringify(t.object)},"Failed to get ID attribute"),o}return(await this.getUserPageOrFrame()).locator(`[${Ue}="${n}"]`)}async clickUsingCDP(e,t={}){let n=0,o,s=async l=>{let c=await this.getLocatorFromBackendID(l);t.doubleClick?await c.dblclick({timeout:4e3}):await c.click({timeout:4e3,button:t.rightClick?"right":"left",force:t.force})};for(;n<2;)try{return await s(e.backendNodeID),e}catch(l){this.logger.error({err:l},"Failed clicking on node"),o=l,n++,await j(500)}let i=e.parent?.children??[];for(let l of i){if(l.id===e.id)continue;let c=!1,u=rs(l,e);if(e.name&&l.name===e.name?c=!0:u>=5&&(this.logger.debug({similarityScore:u},"Sibling qualified for click redirection through comparison score"),c=!0),!!c)try{return await s(l.backendNodeID),l}catch(d){this.logger.debug({err:d,candidate:l.getLogForm()},"Failed clicking on sibling during click redirection")}}let a=e.parent;for(n=0;n<pl;){if(!a||["rootwebarea","main"].includes(a.role.toLowerCase()))throw new R("ActionFailureError",o.message,{cause:o});if(!a.backendNodeID){a=a.parent;continue}try{return await s(a.id),a}catch(c){this.logger.debug({err:c,candidate:a.getLogForm()},"Failed clicking on parent during click redirection"),n++,a=a.parent}}throw new R("ActionFailureError",`Max click attempts exhausted on element ${e.getLogForm()}: ${o.message}`,{cause:o})}async getElementLocation(e){let t=await this.cdpClient.send("DOMSnapshot.captureSnapshot",{computedStyles:[],includeDOMRects:!0,includePaintOrder:!0}),n=await this.page.evaluate(()=>window.devicePixelRatio);process.platform==="darwin"&&n===1&&(n=2);let o=t.documents[0],s=o.layout,i=o.nodes,a=i.nodeName||[],l=i.backendNodeId||[],c=s.nodeIndex,u=s.bounds,d=-1;for(let w=0;w<a.length;w++)if(l[w]===e){d=c.indexOf(w);break}if(d===-1)throw new Error(`Could not find any backend node with ID ${e}`);let[p=0,g=0,m=0,h=0]=u[d];p/=n,g/=n,m/=n,h/=n;let f=p+m/2,S=g+h/2;return{centerX:f,centerY:S}}async scroll(e,t,n,o){let s=t==="left"?-1:1,i=o==="up"?-1:1;if(this.activeFrame)await(await this.getUserPageOrFrame()).evaluate(([l,c,u,d])=>window.scrollTo(window.scrollX+(l??window.innerWidth)*u,window.scrollY+(c??window.innerHeight)*d),[e,n,s,i]);else{let a=this.page.viewportSize()||Xe;await this.page.mouse.wheel((e??a.width)*s,(n??a.height)*i)}}async scrollUp(e){return this.scroll(0,null,e??null,"up")}async scrollDown(e){await this.scroll(0,null,e??null,"down")}async scrollLeft(e){await this.scroll(e??null,"left",0,null)}async scrollRight(e){await this.scroll(e??null,"right",0,null)}async goForward(){await this.wrapPageLoad(async()=>await this.page.goForward({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}))}async goBack(){await this.wrapPageLoad(async()=>this.page.goBack({waitUntil:"domcontentloaded",timeout:this.pageLoadTimeout}))}async changeActivePage(e,t){this.recordUrlVisited(e.url()),this.page=e;let n=await r.initCDPSession(this.context,this.page,this.logger,t??this.pageLoadTimeout),o=this.cdpClient;this.cdpClient=n,o.detach()}async createNewTab(e,t){let n=await this.context.newPage();await this.changeActivePage(n,t?.loadTimeoutMs),await this.navigate({url:e,initialNavigation:!0,...t})}async switchToPageByIndex(e,t,n){let o=e.url();if(!Ut(o,this.logger)){this.logger.error({tabUrl:o},"Refusing to switch to tab with invalid URL");return}this.logger.debug(`Switching to tab ${t} with url ${o}`),await this.changeActivePage(e,n?.loadTimeoutMs),await this.waitForPageOrFrameLoad(e)}async switchToPage(e,t,n){await this.wrapPageLoad(async()=>this.switchToPageHelper(e,t,n))}async switchToPageHelper(e,t,n){let o=this.context.pages(),s=await ls(this.context,this.logger);if(t){await this.switchToPageByIndex(o[t],t,n);let i=s[t].url;this.onTabsChange?.(s,i);return}for(let i=0;i<o.length;i++){let a=o[i];if(a.url().includes(e)){await this.switchToPageByIndex(a,i,n);let l=s[i].url;this.onTabsChange?.(s,l);return}}throw new Error(`Could not find page with url containing ${e}`)}async setCookie(e){let t;typeof e=="string"?t=ui(e):t=[e],this.logger.debug({cookieSettings:t},"Adding cookies to session"),await this.context.addCookies(t)}async setLocalStorage(e,t){await(await this.getUserPageOrFrame()).evaluate(([o,s])=>{o&&localStorage.setItem(o,s||"")},[e,t])}async solveCloudflareTurnstile(){let t=(await this.getUserPageOrFrame()).locator(".cf-turnstile").locator("iframe").getAttribute("data-sitekey"),n=await fetch("https://2captcha.com/in.php",{method:"POST",body:JSON.stringify({key:dr,method:"turnstile",sitekey:t,pageurl:this.url(),json:1})});if(!n.ok){let i=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},i),new Error(i)}let{request:o}=await n.json(),s=Date.now();for(;Date.now()-s<6e4;){await j(2500);let i=await fetch(`https://2captcha.com/res.php?key=${dr}&action=get&id=${o}&json=1`,{method:"GET"});if(!i.ok){let l=`Captcha solution API returned error response: ${i.statusText}`;throw this.logger.error({text:await i.text()},l),new Error(l)}if((await i.json()).status===1)break}}async solveCaptcha(){await this.getBrowserState({});let e;for(let a of this.a11yIdToNodeMap.values())if(a.role==="image"&&a.name.toLowerCase().includes("captcha")){if(!a.backendNodeID)continue;e=await this.getLocatorFromBackendID(a.backendNodeID);break}if(!e){let a=await(await this.getUserPageOrFrame()).solveRecaptchas();if(!a.captchas||!a.captchas.length)throw new Error("No captchas found on the page");return}let t=await e.screenshot({type:"jpeg",animations:"allow",caret:"hide",quality:100,timeout:4e3}),n=await fetch("https://api.2captcha.com/createTask",{method:"POST",body:JSON.stringify({clientKey:dr,task:{type:"ImageToTextTask",body:t.toString("base64"),case:!0},languagePool:"en"})});if(!n.ok){let a=`Captcha solver API returned error response: ${n.statusText}`;throw this.logger.error({text:await n.text()},a),new Error(a)}let{taskId:o}=await n.json(),s=Date.now(),i="";for(;Date.now()-s<6e4;){await j(2500);let a=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:dr,taskId:o})});if(!a.ok){let c=`Captcha solution API returned error response: ${a.statusText}`;throw this.logger.error({text:await a.text()},c),new Error(c)}let l=await a.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}getActiveFrame(){return this.activeFrame}async captureTargetFromClick(){let e=new AbortController;await this.startTreeRefreshCronForRecording(e.signal);let t;try{if(t=await(await this.getUserPageOrFrame()).evaluate(async()=>{let n=window;if(!n.resolveRecordingTarget){console.error("[Momentic] Missing Momentic recording library functions");return}let o=null;n.targetCaptureClickListener=async i=>(console.log("[Momentic] Target capture listener fired"),i.preventDefault(),o=i.target,!1),document.addEventListener("click",n.targetCaptureClickListener,{capture:!0,once:!0});let s=Date.now();for(;!o&&Date.now()-s<1e4;)await new Promise(i=>setTimeout(i,250));if(!o)throw new Error("Timed out waiting for user to click on an element");return n.resolveRecordingTarget(o)}),t?.error)throw new Error(t.error);if(t?.target)t.warnings.length&&this.logger.warn({result:t},"Got warnings while capturing target from click");else throw new Error("No target captured from click")}catch(n){throw this.logger.error({err:n},"Error recording target click"),new Error(`Error recording click: ${n.message}`)}finally{e.abort()}if(!t)throw new Error("Got no target from recorded click - please make sure you clicked on an interactive element");return this.getTargetFromRecordedClick(t.target).target}areDomNodeBoundingBoxesSimilar(e,t,n){if(!t.bounds)return this.logger.debug({candidate:t},"Filtering out click candidate since it has no bounding box"),!1;let o=e.bounds,s=o.x??0,i=o.width??0,a=o.height??0,l=s+i,c=o.y??0,u=c+(o.height??0),d=t.bounds,p=d.width??0,g=d.height??0,m=d.x??0,h=m+(d.width??0),f=d.y??0,S=f+(d.height??0);return m<l&&h>s&&f<u&&S>c?Math.abs(i-p)<200&&Math.abs(a-g)<200?!0:(er({logger:this.logger,logKey:n,maxCount:5,intervalMs:3e3},{candidate:t,originalNode:e},"Filtering out click candidate since it has a significantly different area"),!1):(er({logger:this.logger,logKey:n,maxCount:5,intervalMs:3e3},{candidate:t},"Filtering out click candidate since it does not intersect with the original node"),!1)}getDomCandidatesInA11yTree(e,t){let n=Object.values(t.backendIdToNode),o,s=wp();for(let c of n)if(c.attributes?.[Ue]===e){o=c;break}if(!o)return[];let i=[],a=t.backendIdToNode[o.parentBackendNodeId??-1];for(;a&&(a?.momenticIgnored||!this.areDomNodeBoundingBoxesSimilar(o,a,s));)a=t.backendIdToNode[a.parentBackendNodeId??-1];a&&i.push(a);let l=[o];for(;l.length;){let c=l.shift();for(let u of c.children??[]){let d=t.backendIdToNode[u];d&&!d.momenticIgnored&&this.areDomNodeBoundingBoxesSimilar(o,d,s)?i.push(d):d&&l.push(d)}}return i}getTargetFromRecordedClick(e){this.logger.debug(e,"Got HTML target attributes from click re cording");let{htmlAttributes:t,dataMomenticId:n}=e,s=this.dataMomenticIdToNodeMap.get(n),i={id:s?.id??-1,dataMomenticId:n,targetSource:"CLICK_TO_FIND",...t};return s?this.saveA11yDetailsToCache(s,i):this.logger.warn({htmlAttributes:t},"Could not find corresponding accessibility node for click. Continuing with HTML attributes only"),{target:i,a11yNode:s}}async exposeRecordingBindings(){let e=({frame:t},n)=>{if(!this.transformer)return;let{type:o,target:s,error:i,warnings:a,selectedValue:l}=n,c=t.url();if(this.logger.debug({url:c,...n},`${o} event captured on element`),i){this.logger.error({error:i,warnings:a},"Error while capturing passive element interaction");return}else if(s)a.length&&this.logger.warn({warnings:a},`Warnings while capturing passive element interaction of type ${o}`);else{this.logger.error({event:n},"No target found in passive element interaction event");return}let{dataMomenticId:u,htmlAttributes:d}=s,p=this.dataMomenticIdToNodeMap,g=this.mostRecentA11yTree,m=p.get(u),h={id:m?.id??-1,dataMomenticId:u,targetSource:"RECORDING",...d};m?this.saveA11yDetailsToCache(m,h):this.logger.debug({url:c,htmlAttributes:d},"Could not find corresponding accessibility node for click, continuing with HTML attributes only"),(async()=>{if(!this.transformer){this.logger.warn("No natural language translation since transformer is not initialized anymore");return}this.logger.debug({target:s,url:c},`Generating description for ${o.toLowerCase()}ed target`);let f=g?.serialize();m&&f&&f.length>5e3&&(f=Cl(m.id,f),this.logger.debug({serializedTree:f},"Trimmed a11y tree for description transformation"));try{await this.transformer.recordElementAction({type:o,target:h,browserState:f,url:c,selectedValue:l})}catch(S){this.logger.error({err:S},`Failed to record ${o} action`)}})()};await this.context.exposeBinding("captureElementEvent",({frame:t},n)=>{try{e({frame:t},n)}catch(o){this.logger.error({err:o},"Failed to capture element interaction")}},{handle:!1}),await this.context.exposeBinding("captureKeystroke",async({},t)=>{this.transformer&&this.transformer.recordKeystroke(t)})}async fetchA11yTreeForRecording(){let e=await this.getBrowserState({skipWait:!0,maxAttempts:1,logger:ko});if(this.mostRecentA11yTree=e,Math.random()<.1){let n=this.mostRecentA11yTree.serialize();this.logger.debug({tree:n.length>4e5?"REDACTED_DUE_TO_SIZE":n},"Refreshed a11y tree during recording")}await(await this.getUserPageOrFrame()).evaluate(n=>{let o=window;o.momenticIdsInA11yTree=new Set(n)},Array.from(this.dataMomenticIdToNodeMap.keys()))}async startTreeRefreshCronForRecording(e){if(await this.fetchA11yTreeForRecording(),e.aborted)return;let t,n=!1,o=0,s=0,i=async()=>{if(!(Date.now()-s<=1e3)&&!n){n=!0;try{await this.fetchA11yTreeForRecording(),o=0}catch(a){if(s=Date.now(),o++,o>=8||a.message.includes("crashed")){clearInterval(t),this.logger.error({err:a},"Fatal errors while refreshing a11y tree during recording, exiting...");return}}finally{n=!1}}};t=setInterval(()=>{!this.transformer||e.aborted||i()},gl),e.addEventListener("abort",()=>{clearInterval(t),t=void 0})}async startRecording(e,t){this.logger.debug("Starting passive recording mode in Chrome browser"),await this.startTreeRefreshCronForRecording(e),this.transformer=t,e.addEventListener("abort",async()=>{this.transformer=void 0})}async getSelectOptions(e){return await e.evaluate(n=>Array.from(n.querySelectorAll("option")).map(s=>s.value),{timeout:1e3})}getActivePage(){return this.page}async waitForPageOrFrameLoad(e){let t=this.pageLoadTimeout;await e.waitForLoadState("domcontentloaded",{timeout:t});try{await e.waitForLoadState("load",{timeout:t})}catch(n){this.logger.warn({err:n},"Timeout elapsed waiting for current frame to load, continuing...")}this.recordUrlVisited(e.url())}async getCondensedHtml(){return this.wrapPageLoad(async()=>this.getCondensedHtmlHelper())}async getCondensedHtmlHelper(){await this.waitForDOMStability();let e=await this.getUserPageOrFrame();await Br(e,this.logger);let{result:t,error:n}=await e.evaluate(()=>window.getCondensedHtmlTree(),{timeout:1e3});if(n)throw new Error(`Failed to process page HTML: ${n}`);if(!t)throw new R("InternalWebAgentError","Got empty HTML tree - are you sure the page is fully loaded?");return vp.html(t,{indent_size:1,indent_with_tabs:!1,preserve_newlines:!1,wrap_line_length:100})}async registerDialogHandler(e){let t=async n=>e==="ACCEPT"?n.accept():n.dismiss();this.page.once("dialog",t)}async executePageFunction(e,t){return(await this.getUserPageOrFrame()).evaluate(e,t)}async getDomNodeFromPositionPercentages(e,{percentX:t,percentY:n}){if(t<0||t>1||n<0||n>1)throw new R("InternalWebAgentError","Invalid percent passed to percentage location");let{width:o,height:s,upperBound:i,leftBound:a,devicePixelRatio:l}=await this.getViewportOffsetDetails(e),c=Math.round(i),u=Math.round(a),d=Math.ceil(o*t),p=Math.ceil(s*n);await this.cdpClient.send("DOM.getDocument",{depth:0});let g;try{g=await this.cdpClient.send("DOM.getNodeForLocation",{x:d+u,y:p+c})}catch(m){throw this.logger.error({err:m,pixelDeltaX:d,pixelDeltaY:p,leftBoundRounded:u,upperBoundRounded:c,devicePixelRatio:l},"Failed to get DOM node from position percents"),new Error("No element was found at the given location")}return g}async highlightFromPositionPercentages(e){let t=await this.getUserPageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return n?(await this.cdpClient.send("Overlay.highlightNode",{highlightConfig:El,backendNodeId:n.backendNodeId}),async()=>{try{await this.cdpClient.send("Overlay.hideHighlight",{backendNodeId:n?.backendNodeId})}catch{}}):async()=>{}}async clearAllCdpHighlights(){try{await this.cdpClient.send("Overlay.hideHighlight")}catch{}}async getTargetFromPositionPercentages(e){let t=await this.getUserPageOrFrame(),n=await this.getDomNodeFromPositionPercentages(t,e),o=this.domGraph?.backendIdToNode[n.backendNodeId],s=o?.attributes[Ue],i=parseInt(s??"");if(!o||!s||isNaN(i))throw new Error("No HTML node was found at the given location");let a=t.locator(`[${Ue}="${s}"]`);for(let d of this.a11yIdToNodeMap.values()){if(d.backendNodeID!==n.backendNodeId)continue;let p={id:d.id,targetSource:"XY_PERCENT"};return await this.saveNodeDetailsToCache(t,d,p,parseInt(s),a),{target:p,locator:a}}let l=this.getDomCandidatesInA11yTree(`${s}`,this.domGraph);for(let d of l){let p=parseInt(d.attributes?.[Ue]??"");if(isNaN(p))continue;let g=t.locator(`[${Ue}="${p}"]`),m=this.dataMomenticIdToNodeMap.get(p),h=m?.id;if(!h)continue;let f={id:h,targetSource:"XY_PERCENT"};return await this.saveNodeDetailsToCache(t,m,f,parseInt(s),g),this.logger.debug({target:f},"Redirected click on non-accessible element to nearest a11y node"),{target:f,locator:g}}let c=await this.fetchHtmlAttributes(t,i);return{target:{id:-1,dataMomenticId:i,targetSource:"XY_PERCENT",...c},locator:a}}async fetchHtmlAttributes(e,t){let n=await e.evaluate(o=>{let s=window;return s.generateHtmlCacheAttributes?s.generateHtmlCacheAttributes(o):{warnings:[],error:"generateHtmlCacheAttributes is not defined"}},t);if("error"in n)throw new Error(n.error);if(n.attributes)n.warnings.length&&this.logger.warn(n,"Got warnings while generating HTML attributes for target");else return this.logger.warn(n,"Got no generated HTML attributes for target"),{};return this.logger.debug(n.attributes,"Generated HTML attributes for target"),n.attributes}async moveMouseFromPositionPercentages(e,t){let n=await this.getUserPageOrFrame(),o;try{o=await this.getViewportOffsetDetails(n)}catch{return}let{width:s,height:i}=o,a=Math.ceil(s*e),l=Math.ceil(i*t);await this.page.mouse.move(a,l,{steps:3})}async clickMouseFromPositionPercentages(e,t){let n=await this.getUserPageOrFrame(),o;try{o=await this.getViewportOffsetDetails(n)}catch{return}let{width:s,height:i}=o,a=Math.ceil(s*e),l=Math.ceil(i*t);await this.page.mouse.click(a,l,{button:"left"})}async scrollFromPositionPercentages(e,t){let n=await this.getUserPageOrFrame(),o;try{o=await this.getViewportOffsetDetails(n)}catch{return}let{width:s,height:i}=o,a=Math.ceil(s*e),l=Math.ceil(i*t);return await this.page.mouse.wheel(a,l),{deltaX:a,deltaY:l}}canSolveCaptchas(){return!!dr}async getFrameSrcUrls(){let e=this.page.url(),t=this.page.frames(),n=[];for(let s of t)if(!s.isDetached())try{let a=await(await s.frameElement()).evaluate(l=>"src"in l?l.getAttribute("src"):null);a&&a!=="about:blank"&&a!==e&&n.push(a)}catch(i){let a=i.message;["detached","browser has been closed"].some(l=>a.includes(l))||this.logger.debug({err:i},"Error fetching frame src url, continuing...")}return Array.from(new Set(n))}async setFileChooserHandler(e){setTimeout(()=>{try{e.cleanup()}catch(t){this.logger.debug({err:t,filePath:e.filePath},"Failed cleaning up file after upload")}},3e4),await this.setFileChooserHandlerHelper(e)}async setFileChooserHandlerHelper({filePath:e}){if(!Ep(e)){this.logger.error({filePath:e},"File chooser triggered after the source file has been cleaned up, ignoring...");return}this.page.once("filechooser",async n=>{this.logger.debug({filePath:e},"File chooser triggered"),await n.setFiles(e,{timeout:8e3})});let t=Tp(e).toString("base64");await(await this.getUserPageOrFrame()).evaluate(({fileName:n,base64Data:o})=>{let s=window;s.MomenticFile=class{async getFile(){let i=atob(o),a=new Array(i.length);for(let u=0;u<i.length;u++)a[u]=i.charCodeAt(u);let l=new Uint8Array(a),c=new Blob([l]);return new File([c],n)}},s.showOpenFilePicker=async()=>[new s.MomenticFile]},{fileName:Wl(e),base64Data:t})}getSerializedFormFromA11yId(e){return this.a11yIdToNodeMap.get(e)?.getNodeOnlySerializedForm()}get smartWaitingTimeout(){return this.userControlledBrowserSettings.smartWaitingTimeoutMs??3e3}get pageLoadTimeout(){return this.userControlledBrowserSettings.pageLoadTimeoutMs??8e3}};var kp=({socket:r,metadata:e,logger:t,storage:n})=>async({baseUrl:o,environmentName:s})=>{let{testId:i,sessionId:a,orgId:l}=e;t.info({testId:i,sessionId:a,baseUrl:o},"Reset event received");let c=s?await n.fetchEnvironment(l,s,t):void 0,u=null,d=N.getSession(a);if(!d){r.emit("error",{message:"No session to reset"});return}let{controller:p,context:g}=d;await p.browser.reset({clearCookies:!0,clearStorage:!0,url:o});let m=p.browser.baseURL;g.reset({baseUrl:m,currentUrl:p.browser.url(),variablesFromEnvironment:c?.variables??{},envName:s}),u=await p.browser.getViewport();let h=Ge.USER_AGENT;t.info(`Session reset for test ${i} at ${m}`),r.emit("session",{url:m,userAgent:h,viewport:u,sessionId:a})},Vl={event:"reset",createHandler:kp};var Dp=({metadata:r})=>{let{sessionId:e}=r;return async({url:t})=>{let n=N.getSession(e);if(!n)throw new Error("No active session found");await n.controller.browser.switchToPage(t)}},Kl={event:"switchTab",createHandler:Dp};var Fp=({metadata:r})=>{let{sessionId:e}=r;return({indices:t},n)=>{let o=N.getSession(e);if(!o)return;let s=o.resultsManager.getContextCopyAtIndices(t)??o.context.toRedactedDisplayCopy();n(s)}},ql={event:"getTestContext",createHandler:Fp};import{PostHog as Up}from"posthog-node";var zp=new Up("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://app.posthog.com"}),ur=class r extends yn{static async init(e){let t={},n,o=0,s=3;for(;o<s;)try{t=await zp.getAllFlags(e);break}catch(i){n=i,o++,await new Promise(a=>setTimeout(a,500*o))}if(o===s)throw n;return new r(t)}};var Yl=process.env.GCP_TEMPLATE_MATCHING_FUNCTION_ENDPOINT,Gn=class{constructor(e){this.logger=e}async runTemplateMatching({searchImageBase64String:e,pageImageBase64String:t,id:n,timeoutMs:o=3e3}){if(!Yl)throw new Error("GCP_TEMPLATE_MATCHING_FUNCTION_ENDPOINT environment variable not set");let s={search_image:e,page_image:t,request_id:n},i=new AbortController,a=setTimeout(()=>{i.abort()},o),c=await fetch(Yl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),signal:i.signal});if(clearTimeout(a),c.status===422){let u=(await c.json()).error;throw new un(u)}if(!c.ok)throw new Error(`Template matching server returned error code: ${c.status}`);try{let u=await c.json();return fn.parse(u)}catch(u){throw new Error(`Error parsing template matching response: ${u}`)}}};var Bp={type:"a11y",version:"1.0.0",useHistory:"diff",useGoalSplitter:!0},Wr=Bp;import ig from"dedent";import ag from"diff-lines";import{cloneDeep as lg}from"lodash-es";import{z as mr}from"zod";var Xl=mr.object({doubleClick:mr.boolean().optional(),rightClick:mr.boolean().optional(),force:mr.boolean().optional(),waitForDownload:mr.boolean().optional(),waitForUrl:mr.string().optional()});var $p=["Shift","CapsLock","Dead","Meta","AudioVolumeUp","AudioVolumeDown"],jn=class{recordedSteps=new Map;onStepRecord;signal;generator;testId;orgId;storage;indices;logger;constructor({signal:e,onStepRecord:t,generator:n,initialIndices:o,storage:s,testId:i,orgId:a,logger:l}){this.signal=e,this.storage=s,this.logger=l,this.testId=i,this.orgId=a,this.onStepRecord=(c,u,d)=>{this.recordedSteps.set(JSON.stringify(u),{step:c,url:d}),t(c,u)},this.generator=n,this.indices=o}reserveIndexForCommand(e,t){let n=Array.from(this.indices);return this.recordedSteps.set(JSON.stringify(n),{step:{type:"PRESET_ACTION",command:pt(e)},url:t}),this.indices[this.indices.length-1]++,n}async recordElementAction(e){if(this.signal.aborted){this.logger.debug("Transformer was already cleaned up, ignoring click...");return}let{type:t,target:n,browserState:o,url:s}=e,{indices:i}=e,a,l,c=n.nodeOnlySerializedHtml?.trim()??n.nodeOnlySerializedForm??"Unknown element - please provide a description manually";switch(t){case"CLICK":a="CLICK";let g=pt(a);l={type:"PRESET_ACTION",command:{...g,target:{type:"description",elementDescriptor:c},cache:{target:n}}};break;case"SELECT":a="SELECT_OPTION";let m=pt(a);l={type:"PRESET_ACTION",command:{...m,type:"SELECT_OPTION",target:{type:"description",elementDescriptor:c},cache:{target:n},option:e.selectedValue??"Unknown option"}};break;default:throw new Error(`Unknown action type: ${t}`)}if(i||(i=Array.from(this.indices),this.indices[this.indices.length-1]++),this.onStepRecord(l,i,s),n.id<=0){this.logger.debug("Skipping reverse mapping for non-accessible element");return}else if(!o){this.logger.debug("Skipping reverse mapping since the browser a11y state is not available");return}let u;try{u=(await this.generator.getReverseMappedDescription({goal:`${n.id}`,browserState:o},{disableCache:!1,orgId:this.orgId})).phrase}catch(g){this.logger.error({err:g},"Error generating reverse mapping description"),u=c}let d=this.recordedSteps.get(JSON.stringify(i))?.step,p=d?.command;p&&"target"in p&&p.target?(p.target={type:"description",elementDescriptor:u},this.onStepRecord({...d,command:p},i,s)):this.logger.warn("Could not find existing command to update after description mapping")}recordKeystroke(e){let{key:t,url:n,dataMomenticId:o}=e;if($p.includes(t)||this.signal.aborted)return;let s="normal";t.length>1&&(s="special");let i;if(s==="normal"){let g=pt("TYPE");i={type:"PRESET_ACTION",command:{...g,target:void 0,value:t,clearContent:!1}}}else{let g=pt("PRESS");i={type:"PRESET_ACTION",command:{...g,value:t}}}let a,l=Array.from(this.indices);l[this.indices.length-1]--;let c=this.recordedSteps.get(JSON.stringify(l)),u=c?.step,d=u?.command,p=c?.url;if(n===p){if(d?.type===i.command.type){let g=d.value,m=i.command.value;i={type:"PRESET_ACTION",command:{...d,value:i.command.type==="PRESS"?`${g}+${m}`:`${g}${m}`}},a=l}else if(d?.type==="CLICK"&&i.command.type==="TYPE")(!o||d.cache?.target.dataMomenticId===parseInt(o))&&(u.command={...i.command,target:d.target,cache:d.cache},i=c.step,a=l);else if(d?.type==="TYPE"&&i.command.type==="PRESS"&&i.command.value==="Backspace"){let g=d.value;i={type:"PRESET_ACTION",command:{...d,value:g.slice(0,g.length-1)}},a=l}}a||(a=Array.from(this.indices),this.indices[this.indices.length-1]++),this.onStepRecord(i,a,n)}recordScroll(e){if(this.signal.aborted)return;let{url:t}=e,n=()=>{let{deltaY:a}=e;if(!a)return;let l=Array.from(this.indices);l[this.indices.length-1]--;let c=this.recordedSteps.get(JSON.stringify(l))?.step.command,u;c?.type==="SCROLL_DOWN"&&c.deltaY?(a+=c.deltaY,u=l):c?.type==="SCROLL_UP"&&c.deltaY?(a-=c.deltaY,u=l):(u=Array.from(this.indices),this.indices[this.indices.length-1]++);let d=a>0?"SCROLL_DOWN":"SCROLL_UP",p=pt(d);p.deltaY=Math.abs(a);let g={type:"PRESET_ACTION",command:p};this.onStepRecord(g,u,t)},o=()=>{let{deltaX:a}=e;if(!a)return;let l=Array.from(this.indices);l[this.indices.length-1]--;let c=this.recordedSteps.get(JSON.stringify(l))?.step.command,u;c?.type==="SCROLL_RIGHT"&&c.deltaX?(a+=c.deltaX,u=l):c?.type==="SCROLL_LEFT"&&c.deltaX?(a-=c.deltaX,u=l):(u=Array.from(this.indices),this.indices[this.indices.length-1]++);let d=a>0?"SCROLL_RIGHT":"SCROLL_LEFT",p=pt(d);p.deltaX=Math.abs(a);let g={type:"PRESET_ACTION",command:p};this.onStepRecord(g,u,t)},s=Array.from(this.indices);s[this.indices.length-1]--;let i=this.recordedSteps.get(JSON.stringify(s));i?.step.command.type==="SCROLL_LEFT"||i?.step.command.type==="SCROLL_RIGHT"?(o(),e.deltaY>=20&&n()):(n(),e.deltaX>=20&&o())}};var cs=(r,e,t)=>{let[n,...o]=e.split("."),s=n;return o.length>=1?cs(r[s],o.join("."),t):r[s]=t,r};import Jp from"p-timeout";var Gr={"gpt-3.5-turbo-1106":16184,"ft:gpt-3.5-turbo-0125:momentic:locator-0508:9NvTpgSc":16184,"ft:gpt-3.5-turbo-1106:momentic:text-assertions:9CEFjgB4":16184,"ft:gpt-3.5-turbo-1106:momentic::8vgMsQca":16184,"gpt-4o-mini-2024-07-18":128e3,"gpt-4o-2024-05-13":128e3,"claude-3-opus-20240229":2e5,"claude-3-sonnet-20240229":2e5,"claude-3-5-sonnet-20240620":2e5,"claude-3-haiku-20240307":2e5};var Vn=3.1;function Hp(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);!(n>=48&&n<=57)&&!(n>=65&&n<=90)&&!(n>=97&&n<=122)&&e++}return e}function Kn(r){return Math.ceil(ds(r)/Vn)}function ds(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
|
|
1646
|
+
`,""),t=t.replaceAll(" ","");let n=Hp(t);return t.length-n+Vn*n}if(typeof r>"u")return 0;if(typeof r=="number")return String(r).length;if(Array.isArray(r))return r.forEach(t=>{e+=ds(t)}),e;if(typeof r=="object"){let t=r;return Object.keys(t).forEach(n=>{e+=String(n).length,n==="image_url"?(t[n]??{}).detail==="high"?e+=1105*Vn:e+=85*Vn:e+=ds(t[n])}),e}throw new Error(`Unsupported type passed to token length calculator '${typeof r}': ${r}`)}var Wp=500,Gp=3e3,jp=8e3,Jl=4e3,Ql=/<(\w+) id="(\d+)".*?>/g,Vp=/(<\/(\w+?)>)|(<(\w+?).*?\/>)/g,Zl=["h1","h2","section","footer","nav","aside","form","label","dialog"],Kp=[...Zl,"span","div","h3"],qp=["table","select","form","ul","ol","menu","pre","code","dialog"],Yp=["table","form","dialog","nav","section","ul","select"];function qn({serializedTree:r,tokenLimit:e,logger:t}){let n=Kn(r);if(n<=e)return;let o=[],s=r.split(`
|
|
1605
1647
|
`),i=0,a=[],l=0,c=[],u=[],d=!1;for(;i<s.length;){d&&(o.push({ids:c,content:a.join(`
|
|
1606
|
-
`),tokenLength:l}),a=[],l=0,c=u.length?[u[u.length-1].id]:[],d=!1);let
|
|
1607
|
-
`),tokenLength:l});let m=n/o.length,h=Math.min(o.length,Math.ceil(e*1.5/m));return{chunks:o,numRecs:h}}var is=(r,e,t)=>{let[n,...o]=e.split("."),s=n;return o.length>=1?is(r[s],o.join("."),t):r[s]=t,r};function Yl(r){return{createIsolatedFolder:()=>ts(r)}}async function Xl({assertion:r,element:e,callbacks:t}){switch(await t.highlightTarget(e),r.type){case"ELEMENT_CONTENT":{let n=await e.textContent()??"";if(!as(n,r.value,r.operation,!!r.negated)){let o=r.negated?Nt[r.operation]:_t[r.operation];throw new A("AssertionFailureError",`The content ${o} '${r.value}': ${n}`)}break}case"ELEMENT_ATTRIBUTE":{let n;try{n=await e.getAttribute(r.attr,{timeout:3e3})??""}catch{throw new A("AssertionFailureError",`The element does not have an attribute named ${r.attr}`)}if(!as(n,r.value,r.operation,!!r.negated)){let o=r.negated?Nt[r.operation]:_t[r.operation];throw new A("AssertionFailureError",`The attribute ${r.attr} ${o} '${r.value}': ${n}`)}break}case"ELEMENT_EXISTENCE":{let n;switch(r.condition){case"VISIBLE":{n=await e.isVisible({timeout:Et*1e3});break}case"EDITABLE":{n=await e.isEditable({timeout:Et*1e3});break}case"EXISTS":{n=!0;break}case"ENABLED":{n=await e.isEnabled({timeout:Et*1e3});break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.condition)}if(n=r.negated?!n:n,!n){let o=r.negated?Oo[r.condition]:Mo[r.condition];throw new A("AssertionFailureError",`The element ${o}`)}break}}}async function Jl({timeout:r=Et,...e}){let t=Date.now(),n=r*1e3,o;for(;Date.now()-t<n;)try{await Xp(e);return}catch(s){o=s,await G(1e3)}throw o}async function Xp({assertion:r,page:e}){switch(r.type){case"CONTENT":{let t=await e.content();if(!as(t,r.value??"","CONTAINS",!!r.negated)){let n=r.negated?Nt.CONTAINS:_t.CONTAINS;throw new A("AssertionFailureError",`The page ${n} '${r.value}'`)}break}}}function as(r,e,t,n){let o;switch(t){case"CONTAINS":{o=r.includes(e);break}case"EQUALS":{o=r===e;break}case"STARTS_WITH":{o=r.startsWith(e);break}default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return n?!o:o}import Jp from"sharp";async function Hr(r,e){let t=await r.screenshot(e),n=await Jp(t).metadata();return{buffer:t,width:Math.ceil(n.width??0),height:Math.ceil(n.height??0)}}import ls from"jpeg-js";import Qp from"pixelmatch";import Ql from"sharp";async function Zl({ctx:r,command:e,disableCache:t,browserStateGetter:n,browser:o,targetingWrapper:s}){if(e.target&&!Ke(e.target))throw new Error("Visual Diff with x/y is not supported yet");if(!e.screenshot)throw new A("ActionFailureError","Cannot execute visual diff without saved screenshot");await n({skipWait:!1});let i={clearHighlights:!0,scale:"css",hideCaret:!0},a;if(!e.target)a=await Hr(o,i);else{let x=await s({ctx:r,target:e.target,cache:e.cache?.target??e.target?.a11yData,action:async L=>{},options:{disableCache:!!t,useSelector:!!e.useSelector,iframeUrl:e.iframeUrl}});if(!x.cache)throw new A("ActionFailureError",`Could not find target given description: ${e.target.elementDescriptor}`);a=await Hr(o,{target:x.cache,...i}),e.cache={target:x.cache}}let l;if(e.screenshot.data.startsWith("https://")){let x=await fetch(e.screenshot.data);l=Buffer.from(await x.arrayBuffer())}else l=Buffer.from(e.screenshot.data,"base64");if(Math.abs(a.height-e.screenshot.height)>10||Math.abs(a.width-e.screenshot.width)>10){let x=`${a.width}x${a.height}`,L=`${e.screenshot.width}x${e.screenshot.height}`;return{fail:!0,thoughts:`Current screenshot (${x}) does not match saved screenshot dimensions (${L}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:l,afterScreenshotOverride:a.buffer,succeedImmediately:!1,urlAfterCommand:o.url()}}let c=Ql(a.buffer),u={width:a.width,height:a.height},d=Ql(l),m={width:e.screenshot.width,height:e.screenshot.height},h,p=u.width*u.height,g=m.width*m.height,f=Math.abs(u.height-m.height),S=Math.abs(u.width-m.width);p>g?(a.buffer=await c.resize(m.width,m.height,{fit:"cover"}).toBuffer(),h="current",a.width=m.width,a.height=m.height):g>p&&(l=await d.resize(u.width,u.height,{fit:"cover"}).toBuffer(),h="saved");let w={data:Buffer.alloc(a.width*a.height*4),width:a.width,height:a.height},b=e.threshold??.1,v=Qp(ls.decode(l).data,ls.decode(a.buffer).data,w.data,a.width,a.height,{threshold:b,diffColorAlt:[0,255,0]})/(a.width*a.height)*100,C=v>b*100,R=`Visual diff of ${v.toFixed(2)}% detected, which is ${C?"over":"under"} the threshold of ${b*100}%.`;return h&&(R+=` The ${h} screenshot was cropped since it was taller by ${f} pixels and wider by ${S} pixels.`),{fail:C,thoughts:R,beforeScreenshotOverride:a.buffer,afterScreenshotOverride:ls.encode(w,75).data,succeedImmediately:!1,urlAfterCommand:o.url()}}async function ec({command:r,browser:e,logger:t}){let n=r.timeout??30,o=null,s=new AbortController,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([p,g])=>p&&g)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([p,g])=>p&&g).forEach(([p,g])=>{a.append(p,g)});let l;if(Mn(r.url)&&(l=r.url),Nn(r.url,e.baseURL)&&(l=new URL(r.url,e.baseURL).toString()),!l)throw new A("ActionFailureError",`Invalid URL: ${r.url}`);let c=async()=>{try{o=await fetch(`${l}?${a.toString()}`,{headers:i,method:r.method,body:r.body,signal:s.signal})}catch(p){t.error({err:p},"Failed to make HTTP request")}},u=async()=>{await new Promise(p=>setTimeout(p,n*1e3)),s.abort()};await Promise.race([u(),c()]);let d=o;if(!d)throw new A("ActionFailureError",`Fetch request timed out after ${n} seconds`);if(!d.ok)throw new A("ActionFailureError",`Fetch request failed with status ${d.status}`);let m={};d.headers.forEach((p,g)=>{m[g]=p});let h={status:d.status,headers:m};return d.headers.get("content-type")?.includes("json")?h.json=await d.json():d.headers.get("content-type")?.includes("text")&&(h.text=await d.text()),{succeedImmediately:!1,urlAfterCommand:e.url(),data:h}}var rg=1e4,mr=class{flagStore;orgId;storage;localCodeEvalTools;browser;pendingInstructions;generator;commandHistory;config;closed=!1;logger;recordAbortController=null;constructor({browser:e,config:t,generator:n,logger:o,flagStore:s,storage:i,orgId:a,localCodeEvalTools:l}){this.orgId=a,this.browser=e,this.storage=i,this.localCodeEvalTools=l,this.generator=n,this.config=t,this.logger=o,this.flagStore=s,this.pendingInstructions=[],this.commandHistory=[]}get history(){return this.commandHistory.filter(e=>e.state==="DONE")}get lastExecutedCommand(){let e=this.history;return e.length===0?null:e[e.length-1]}setOpen(){this.closed=!1}isClosed(){return this.closed}setLogger(e){this.logger=e}resetHistory(){this.commandHistory=[],this.pendingInstructions=[]}async resetState(e){this.resetHistory(),this.closed=!0,await this.browser.reset(e)}async getBrowserState(e){let t=await this.browser.getBrowserState(e),n=t.serialize();return this.logger.debug({tree:n.length>4e5?"REDACTED_DUE_TO_LENGTH":n,activeFrame:this.browser.getActiveFrame()},"Got a11y tree"),{serializedTree:n,tree:t}}getSerializedHistory(e,t){let n;return this.config.useHistory==="diff"?n=this.getDiffHistory(e,t):n=this.getListHistory(),n}async splitUserGoal(e,t,n){if(e==="AI_ACTION"&&t.match(/[,!;.]|(?:and)|(?:then)/)&&this.config.useGoalSplitter){let o=await this.generator.getGranularGoals({goal:t,url:this.browser.url()},{disableCache:n,orgId:this.orgId});this.pendingInstructions=o.reverse()}else this.pendingInstructions=[t]}async promptToCommand(e,t,n){try{return await this.promptToCommandHelper(e,t,n)}catch(o){throw o instanceof A?o:new A("InternalWebAgentError",`Error generating command: ${o instanceof Error?o.message:o}`,{cause:o})}}async promptToCommandHelper(e,t,n){if(this.pendingInstructions.length===0){if(!t.trim())throw new Error("Cannot generate commands for empty goal");await this.splitUserGoal(e,t,n)}let o=this.pendingInstructions[this.pendingInstructions.length-1];this.logger.debug({goal:o},"Starting prompt translation");let s=this.browser.url(),{serializedTree:i}=await this.getBrowserState({}),a=this.commandHistory.length;this.commandHistory.push({state:"PENDING",browserStateBeforeCommand:i,urlBeforeCommand:s,type:e});let l=this.getSerializedHistory(s,i),c=(await this.browser.screenshot({scale:"css",clearHighlights:!0})).toString("base64"),u={url:s,numPrevious:a,browserState:i,history:l,goal:o,lastCommand:this.lastExecutedCommand,screenshot:c},d=await this.generator.getProposedCommand(u,{disableCache:n,orgId:this.orgId});if(this.logger.info({type:d.type,thoughts:d.thoughts},"Got proposed command"),d.type==="SUCCESS"){let m=this.pendingInstructions.pop();if(this.logger.debug({finishedInstruction:m,remainingInstructions:this.pendingInstructions},"Removing pending instruction due to SUCCESS"),this.pendingInstructions.length!==0)return this.commandHistory=[],this.promptToCommand(e,"",n)}else d.type==="FAILURE"&&(this.logger.debug({remainingInstructions:this.pendingInstructions},"Removing pending instructions due to FAILURE"),this.pendingInstructions=[]);return{context:u,command:d}}async locateElementWithSelector(e,t){return this.wrapFrameUseCommand(async()=>{let n={id:-1,selector:e,targetSource:"USER_CSS_SELECTOR"},o=await this.browser.resolveTarget(null,n);return{thoughts:"Located element with selector",target:n,resolution:o}},t)}async locateElement(e,t){if(!t.description)throw new A("ActionFailureError","Cannot locate element with empty description");return this.wrapFrameUseCommand(()=>this.locateElementHelper(e,t),t.iframeUrl)}async locateElementHelper(e,{description:t,disableCache:n,testContext:o,filterByViewport:s}){o&&(t=await _r({s:t,context:o,logger:this.logger,localTools:this.localCodeEvalTools}));let i=async()=>{try{return await this.browser.screenshot({scale:"css",clearHighlights:!0})}catch(b){this.logger.debug({err:b},"Failed taking screenshot for element location, continuing...");return}},[{serializedTree:a,tree:l},c]=await Promise.all([this.getBrowserState({filterByViewport:s}),i()]),u=a,d=!1,m=.2*Hn["gpt-4o-2024-05-13"],h=ss({serializedTree:a,tokenLimit:m,logger:this.logger});if(h&&this.flagStore.isBooleanFlagEnabled("locator_rag")){let E=(await this.generator.getRecommendedChunks({...h,description:t,tokenLimit:m})).ids;E.length===0?this.logger.debug("RAG returned no important information"):(u=l.pruneUsingRelevantIds(new Set(E)).serialize(),this.logger.debug({tree:o},"Pruned a11y tree with RAG"),d=!0)}let p=c?.toString("base64");tc(this.uploadScreenshotForDebugging("locator",c),{milliseconds:5e3,fallback:()=>{}});let g=await this.generator.getElementLocation({browserState:u,goal:t,screenshot:p},{disableCache:n,orgId:this.orgId});this.logger.debug({usedRag:d,result:g},"Got locator result");let f=g.id>0;if(e?.details?.push({type:"AI_LOCATION",matched:f,pageState:u,ragUsed:d,thoughts:g.thoughts}),!f)throw new A("ActionFailureError",`Could not find any relevant element: ${g.thoughts}`);let S={id:g.id,inputDescription:t,targetSource:"AI"},w=await this.browser.resolveTarget(null,S);return{thoughts:g.thoughts,target:S,resolution:w}}async uploadScreenshotForDebugging(e,t,n){if(t)try{let o=await this.storage.uploadScreenshot(t);this.logger.debug({screenshotUrl:o,codePath:e},"Saved screenshot for debugging"),n?.(o)}catch(o){this.logger.error({err:o,codePath:e},"Failed to save screenshot for debugging")}}getDiffHistory(e,t){let n=this.history.filter(s=>s.type==="AI_ACTION");if(n.length===0)return"<NONE/>";let o=[`
|
|
1608
|
-
You have already executed the following commands successfully (most recent listed first)`,"-".repeat(10)];return n.reverse().forEach((s,i)=>{if(o.push(`COMMAND ${n.length-i}${i===0?" (command just executed)":""}: ${s.serializedCommand}`),i===0)if(
|
|
1648
|
+
`),tokenLength:l}),a=[],l=0,c=u.length?[u[u.length-1].id]:[],d=!1);let m=s[i],h=m.length;h>Jl&&(m=m.slice(0,Jl),t.warn({lineNumber:i,currentLine:m},`Truncated line with ${h} characters during tree chunking`));let f=Kn(m);a.push(m),l+=f;let w=Array.from(m.matchAll(Ql)).map(O=>O&&O.length>=3?{tagName:O[1],id:O[2]}:void 0).filter(O=>!!O),T=Array.from(m.matchAll(Vp)).map(O=>O&&(O[2]||O[4])).filter(O=>!!O);T.reverse();for(let O of w)c.push(O.id),u.push(O);for(let O of T){let Ke=u[u.length-1];Ke&&Ke.tagName===O&&u.pop()}let v=u.some(O=>qp.includes(O.tagName)),C=s[i+1]??"",A=Kn(C),L=Array.from(C.matchAll(Ql)).map(O=>O&&O.length>2?O[1]:void 0).filter(O=>!!O),H=L.some(O=>Zl.includes(O)),ve=L.some(O=>Kp.includes(O));l+A>=jp&&(d=!0),l>=Wp&&(H&&!v||T.some(O=>Yp.includes(O)))&&(d=!0),l>=Gp&&ve&&!v&&(d=!0),i++}a.length&&o.push({ids:c,content:a.join(`
|
|
1649
|
+
`),tokenLength:l});let p=n/o.length,g=Math.min(o.length,Math.ceil(e*1.5/p));return{chunks:o,numRecs:g}}async function ot(r,e,t={}){let n=await r.getBrowserState(t),o=n.serialize();return e.debug({tree:o.length>4e5?"REDACTED_DUE_TO_LENGTH":o,activeFrame:r.getActiveFrame()},"Got a11y tree"),{serializedTree:o,tree:n}}async function Yn({codePath:r,screenshotBuff:e,callback:t,storage:n,logger:o}){if(e)try{let s=await n.uploadScreenshot(e);o.debug({screenshotUrl:s,codePath:r},"Saved screenshot for debugging"),t?.(s)}catch(s){o.error({err:s,codePath:r},"Failed to save screenshot for debugging")}}async function Bt({frameUrl:r,action:e,browser:t,logger:n}){if(!r)return e();let o=t.getActiveFrame();try{return n.debug({frameUrl:r},"Setting parent iframe target"),t.setActiveFrame({type:"url",url:r}),await e()}finally{t.setActiveFrame(o)}}async function us(r,e){if(!r.description)throw new R("ActionFailureError","Cannot locate element with empty description");return Bt({action:()=>Qp(r,e),frameUrl:r.iframeUrl,browser:e.browser,logger:e.logger})}async function Qp(r,e){let{disableCache:t,testContext:n,filterByViewport:o}=r,{ctx:s,orgId:i,logger:a,browser:l,localCodeEvalTools:c,flagStore:u,generator:d,storage:p}=e,g=r.description;n&&(g=await lr({s:g,context:n,logger:e.logger,localTools:c}));let{serializedTree:m,tree:h}=await ot(l,a,{filterByViewport:o}),f;try{f=await l.screenshot({scale:"css",clearHighlights:!0})}catch(H){a.debug({err:H},"Failed taking screenshot for element location, continuing...")}let S=m,w=!1,b=.2*Gr["gpt-4o-2024-05-13"],T=qn({serializedTree:m,tokenLimit:b,logger:a});if(T&&u.isBooleanFlagEnabled("locator_rag")){let ve=(await d.getRecommendedChunks({...T,description:g,tokenLimit:b})).ids;ve.length===0?a.debug("RAG returned no important information"):(S=h.pruneUsingRelevantIds(new Set(ve)).serialize(),a.debug({tree:n},"Pruned a11y tree with RAG"),w=!0)}let v=f?.toString("base64");Jp(Yn({codePath:"locator",screenshotBuff:f,storage:p,logger:a}),{milliseconds:5e3,fallback:()=>{}});let C=await d.getElementLocation({browserState:S,goal:g,screenshot:v},{disableCache:t,orgId:i});a.debug({usedRag:w,result:C},"Got locator result");let A=C.id>0;if(s?.details?.push({type:"AI_LOCATION",matched:A,pageState:S,ragUsed:w,thoughts:C.thoughts}),!A)throw new R("ActionFailureError",`Could not find any relevant element: ${C.thoughts}`);let x={id:C.id,inputDescription:g,targetSource:"AI"},L=await l.resolveTarget(null,x);return{thoughts:C.thoughts,target:x,resolution:L}}import Zp from"p-timeout";async function ms({command:r,fixtures:e,opts:t={}}){if(!r.assertion.trim())throw new R("ActionFailureError","Assertion command is missing the assertion content");let{browser:n,logger:o}=e,{isExecutionCancelled:s}=t,i=r.timeout?r.timeout*1e3:n.smartWaitingTimeout,a=rg(i),l=0,c=Date.now(),u,d,p,g=()=>{if(s?.())throw new $e(`AI assertion cancelled by user.${p?` Last error: ${p.message}`:""}`)},m;for(;!m||m-c<i;){g(),o.info(`Waiting ${a}ms before ${m?"retrying":"trying"} AI assertion`),await j(a),g();try{let h=await eg(n,o,e.storage);if(m=Date.now(),d&&d.serializedTree===h.serializedTree&&d.screenshotBuff.equals(h.screenshotBuff)){o.debug("A11y tree and page screenshot did not change, skipping assertion attempt");continue}d=h,u=await Bt({action:()=>tg(r,h,e),frameUrl:r.iframeUrl,logger:o,browser:n});break}catch(h){p=h instanceof Error?h:new Error(`${h}`),o.info({err:h},`AI_WAIT assert attempt ${l} failed, retrying...`)}finally{l++}}if(!u){let h=`AI assertion still failing after ${i}ms.`;throw p&&(h+=` Latest result: ${p.message}`),new R("AssertionFailureError",h)}return u}async function eg(r,e,t){let n=await ot(r,e),o=await r.screenshot({clearHighlights:!0,scale:"css",retries:2});return Zp(Yn({codePath:"assertion",screenshotBuff:o,logger:e,storage:t}),{milliseconds:5e3,fallback:()=>{}}),{...n,screenshotBuff:o}}async function tg(r,e,t){let{browser:n,logger:o,generator:s,orgId:i}=t,a={type:"ASSERTION"},{serializedTree:l}=e,c=e.screenshotBuff,{tree:u}=e,d=n.url(),p=.2*Gr["gpt-4o-2024-05-13"],g=qn({serializedTree:l,tokenLimit:p,logger:o});if(g){let S=(await s.getRecommendedChunks({...g,description:r.assertion,tokenLimit:p})).ids;S.length===0?o.debug("RAG returned no important information for assertion"):(l=u.pruneUsingRelevantIds(new Set(S)).serialize(),o.debug({browserState:l},"Pruned a11y tree with RAG"),a.ragUsed=!0)}a.pageState=l;let m={goal:r.assertion,url:d,browserState:l,screenshot:c.toString("base64"),numPrevious:-1,history:"",lastCommand:null},h=await s.getAssertionResult(m,{disableCache:!!r.disableCache,orgId:i});if(h.relevantElements&&(await Promise.all(Array.from(new Set(h.relevantElements)).slice(0,3).map(f=>n.highlight({id:f}))),a.relevantElementsSerialized=h.relevantElements.map(f=>n.getSerializedFormFromA11yId(f)).filter(f=>!!f)),o.debug({usedRag:a.ragUsed,result:h},"Got assertion result"),!h.result)throw new R("AssertionFailureError",h.thoughts);return{succeedImmediately:!1,thoughts:h.thoughts,urlAfterCommand:d,beforeScreenshotOverride:c}}function rg(r){let e;return r>10*60*1e3?e=Math.floor(r/6):r>60*1e3?e=Math.floor(r/5):r>10*1e3?e=Math.floor(r/4):e=500,e}function ec(r){return{createIsolatedFolder:()=>ss(r)}}async function tc({assertion:r,element:e,callbacks:t}){switch(await t.highlightTarget(e),r.type){case"ELEMENT_CONTENT":{let n=await e.textContent()??"";if(!ps(n,r.value,r.operation,!!r.negated)){let o=r.negated?Nt[r.operation]:_t[r.operation];throw new R("AssertionFailureError",`The content ${o} '${r.value}': ${n}`)}break}case"ELEMENT_ATTRIBUTE":{let n;try{n=await e.getAttribute(r.attr,{timeout:3e3})??""}catch{throw new R("AssertionFailureError",`The element does not have an attribute named ${r.attr}`)}if(!ps(n,r.value,r.operation,!!r.negated)){let o=r.negated?Nt[r.operation]:_t[r.operation];throw new R("AssertionFailureError",`The attribute ${r.attr} ${o} '${r.value}': ${n}`)}break}case"ELEMENT_EXISTENCE":{let n;switch(r.condition){case"VISIBLE":{n=await e.isVisible({timeout:Rt*1e3});break}case"EDITABLE":{n=await e.isEditable({timeout:Rt*1e3});break}case"EXISTS":{n=!0;break}case"ENABLED":{n=await e.isEnabled({timeout:Rt*1e3});break}default:return(s=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(r.condition)}if(n=r.negated?!n:n,!n){let o=r.negated?Do[r.condition]:Fo[r.condition];throw new R("AssertionFailureError",`The element ${o}`)}break}}}async function rc({timeout:r=Rt,...e}){let t=Date.now(),n=r*1e3,o;for(;Date.now()-t<n;)try{await ng(e);return}catch(s){o=s,await j(1e3)}throw o}async function ng({assertion:r,page:e}){switch(r.type){case"CONTENT":{let t=await e.content();if(!ps(t,r.value??"","CONTAINS",!!r.negated)){let n=r.negated?Nt.CONTAINS:_t.CONTAINS;throw new R("AssertionFailureError",`The page ${n} '${r.value}'`)}break}}}function ps(r,e,t,n){let o;switch(t){case"CONTAINS":{o=r.includes(e);break}case"EQUALS":{o=r===e;break}case"STARTS_WITH":{o=r.startsWith(e);break}default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return n?!o:o}import og from"sharp";async function jr(r,e){let t=await r.screenshot(e),n=await og(t).metadata();return{buffer:t,width:Math.ceil(n.width??0),height:Math.ceil(n.height??0)}}import gs from"jpeg-js";import sg from"pixelmatch";import nc from"sharp";async function oc({ctx:r,command:e,disableCache:t,browser:n,targetingWrapper:o,logger:s}){if(e.target&&!qe(e.target))throw new Error("Visual Diff with x/y is not supported yet");if(!e.screenshot)throw new R("ActionFailureError","Cannot execute visual diff without saved screenshot");await ot(n,s,{skipWait:!1});let i={clearHighlights:!0,scale:"css",hideCaret:!0},a;if(!e.target)a=await jr(n,i);else{let x=await o({ctx:r,target:e.target,cache:e.cache?.target??e.target?.a11yData,action:async L=>{},options:{disableCache:!!t,useSelector:!!e.useSelector,iframeUrl:e.iframeUrl}});if(!x.cache)throw new R("ActionFailureError",`Could not find target given description: ${e.target.elementDescriptor}`);a=await jr(n,{target:x.cache,...i}),e.cache={target:x.cache}}let l;if(e.screenshot.data.startsWith("https://")){let x=await fetch(e.screenshot.data);l=Buffer.from(await x.arrayBuffer())}else l=Buffer.from(e.screenshot.data,"base64");if(Math.abs(a.height-e.screenshot.height)>10||Math.abs(a.width-e.screenshot.width)>10){let x=`${a.width}x${a.height}`,L=`${e.screenshot.width}x${e.screenshot.height}`;return{fail:!0,thoughts:`Current screenshot (${x}) does not match saved screenshot dimensions (${L}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:l,afterScreenshotOverride:a.buffer,succeedImmediately:!1,urlAfterCommand:n.url()}}let c=nc(a.buffer),u={width:a.width,height:a.height},d=nc(l),p={width:e.screenshot.width,height:e.screenshot.height},g,m=u.width*u.height,h=p.width*p.height,f=Math.abs(u.height-p.height),S=Math.abs(u.width-p.width);m>h?(a.buffer=await c.resize(p.width,p.height,{fit:"cover"}).toBuffer(),g="current",a.width=p.width,a.height=p.height):h>m&&(l=await d.resize(u.width,u.height,{fit:"cover"}).toBuffer(),g="saved");let w={data:Buffer.alloc(a.width*a.height*4),width:a.width,height:a.height},b=e.threshold??.1,v=sg(gs.decode(l).data,gs.decode(a.buffer).data,w.data,a.width,a.height,{threshold:b,diffColorAlt:[0,255,0]})/(a.width*a.height)*100,C=v>b*100,A=`Visual diff of ${v.toFixed(2)}% detected, which is ${C?"over":"under"} the threshold of ${b*100}%.`;return g&&(A+=` The ${g} screenshot was cropped since it was taller by ${f} pixels and wider by ${S} pixels.`),{fail:C,thoughts:A,beforeScreenshotOverride:a.buffer,afterScreenshotOverride:gs.encode(w,75).data,succeedImmediately:!1,urlAfterCommand:n.url()}}async function sc({command:r,browser:e,logger:t}){let n=r.timeout??30,o=null,s=new AbortController,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([m,h])=>m&&h)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([m,h])=>m&&h).forEach(([m,h])=>{a.append(m,h)});let l;if(kn(r.url)&&(l=r.url),Dn(r.url,e.baseURL)&&(l=new URL(r.url,e.baseURL).toString()),!l)throw new R("ActionFailureError",`Invalid URL: ${r.url}`);let c=async()=>{try{o=await fetch(`${l}?${a.toString()}`,{headers:i,method:r.method,body:r.body,signal:s.signal})}catch(m){t.error({err:m},"Failed to make HTTP request")}},u=async()=>{await new Promise(m=>setTimeout(m,n*1e3)),s.abort()};await Promise.race([u(),c()]);let d=o;if(!d)throw new R("ActionFailureError",`Fetch request timed out after ${n} seconds`);if(!d.ok)throw new R("ActionFailureError",`Fetch request failed with status ${d.status}`);let p={};d.headers.forEach((m,h)=>{p[h]=m});let g={status:d.status,headers:p};return d.headers.get("content-type")?.includes("json")?g.json=await d.json():d.headers.get("content-type")?.includes("text")&&(g.text=await d.text()),{succeedImmediately:!1,urlAfterCommand:e.url(),data:g}}var cg=1e4,pr=class{flagStore;orgId;storage;localCodeEvalTools;browser;pendingInstructions;generator;commandHistory;config;closed=!1;logger;recordAbortController=null;constructor({browser:e,config:t,generator:n,logger:o,flagStore:s,storage:i,orgId:a,localCodeEvalTools:l}){this.orgId=a,this.browser=e,this.storage=i,this.localCodeEvalTools=l,this.generator=n,this.config=t,this.logger=o,this.flagStore=s,this.pendingInstructions=[],this.commandHistory=[]}get history(){return this.commandHistory.filter(e=>e.state==="DONE")}get lastExecutedCommand(){let e=this.history;return e.length===0?null:e[e.length-1]}setOpen(){this.closed=!1}isClosed(){return this.closed}setLogger(e){this.logger=e}resetHistory(){this.commandHistory=[],this.pendingInstructions=[]}async resetState(e){this.resetHistory(),this.closed=!0,await this.browser.reset(e)}getSerializedHistory(e,t){let n;return this.config.useHistory==="diff"?n=this.getDiffHistory(e,t):n=this.getListHistory(),n}async splitUserGoal(e,t,n){if(e==="AI_ACTION"&&t.match(/[,!;.]|(?:and)|(?:then)/)&&this.config.useGoalSplitter){let o=await this.generator.getGranularGoals({goal:t,url:this.browser.url()},{disableCache:n,orgId:this.orgId});this.pendingInstructions=o.reverse()}else this.pendingInstructions=[t]}async promptToCommand(e,t,n){try{return await this.promptToCommandHelper(e,t,n)}catch(o){throw o instanceof R?o:new R("InternalWebAgentError",`Error generating command: ${o instanceof Error?o.message:o}`,{cause:o})}}async promptToCommandHelper(e,t,n){if(this.pendingInstructions.length===0){if(!t.trim())throw new Error("Cannot generate commands for empty goal");await this.splitUserGoal(e,t,n)}let o=this.pendingInstructions[this.pendingInstructions.length-1];this.logger.debug({goal:o},"Starting prompt translation");let s=this.browser.url(),{serializedTree:i}=await ot(this.browser,this.logger,{}),a=this.commandHistory.length;this.commandHistory.push({state:"PENDING",browserStateBeforeCommand:i,urlBeforeCommand:s,type:e});let l=this.getSerializedHistory(s,i),c=(await this.browser.screenshot({scale:"css",clearHighlights:!0})).toString("base64"),u={url:s,numPrevious:a,browserState:i,history:l,goal:o,lastCommand:this.lastExecutedCommand,screenshot:c},d=await this.generator.getProposedCommand(u,{disableCache:n,orgId:this.orgId});if(this.logger.info({type:d.type,thoughts:d.thoughts},"Got proposed command"),d.type==="SUCCESS"){let p=this.pendingInstructions.pop();if(this.logger.debug({finishedInstruction:p,remainingInstructions:this.pendingInstructions},"Removing pending instruction due to SUCCESS"),this.pendingInstructions.length!==0)return this.commandHistory=[],this.promptToCommand(e,"",n)}else d.type==="FAILURE"&&(this.logger.debug({remainingInstructions:this.pendingInstructions},"Removing pending instructions due to FAILURE"),this.pendingInstructions=[]);return{context:u,command:d}}async getExtractedKeywords(e,t){return await this.getExtractedKeywordsHelper(e,t)}async getExtractedKeywordsHelper(e,t){return this.logger.debug({goal:e},"Starting keyword extraction"),await this.generator.getExtractedKeywords(e,{disableCache:t,orgId:this.orgId})}async getBrowserState(e){return ot(this.browser,this.logger,e)}async locateElement(e){return us(e,this.getControllerFixtures())}async locateElementWithSelector(e,t){return Bt({action:async()=>{let n={id:-1,selector:e,targetSource:"USER_CSS_SELECTOR"},o=await this.browser.resolveTarget(null,n);return{thoughts:"Located element with selector",target:n,resolution:o}},frameUrl:t,browser:this.browser,logger:this.logger})}getDiffHistory(e,t){let n=this.history.filter(s=>s.type==="AI_ACTION");if(n.length===0)return"<NONE/>";let o=[`
|
|
1650
|
+
You have already executed the following commands successfully (most recent listed first)`,"-".repeat(10)];return n.reverse().forEach((s,i)=>{if(o.push(`COMMAND ${n.length-i}${i===0?" (command just executed)":""}: ${s.serializedCommand}`),i===0)if(Fr(s.urlBeforeCommand,e))o.push(` URL CHANGE: '${s.urlBeforeCommand}' -> '${e}'`);else{let a=ag(s.browserStateBeforeCommand,t,{n_surrounding:1});a?a.length<cg?(o.push("PAGE CONTENT CHANGE:"),a.split(`
|
|
1609
1651
|
`).forEach(l=>o.push(` ${l}`))):o.push("PAGE CONTENT CHANGE: <TOO_LONG_TO_DISPLAY/>"):o.push("PAGE CONTENT CHANGE: <NONE/>")}o.push("-".repeat(10))}),o.push(`STARTING URL: ${this.browser.baseURL}`),o.join(`
|
|
1610
|
-
`)}getListHistory(){return
|
|
1652
|
+
`)}getListHistory(){return ig`Here are the commands that you have successfully executed:
|
|
1611
1653
|
${this.commandHistory.filter(e=>e.type==="AI_ACTION").map(e=>`- ${e.serializedCommand}`).join(`
|
|
1612
|
-
`)}`}async executeCommand(e,t,n,o=!1){let s=this.commandHistory[this.commandHistory.length-1];if(!o&&(!s||s.state!=="PENDING"))throw new A("InternalWebAgentError","Executing command but there is no pending entry in the history");if(this.closed)throw new Error("Attempting to execute command on a closed controller");let i=Date.now(),a=await this.executePresetStep(null,e,t,n),l=Date.now()-i;return this.logger.debug({result:a,duration:l},"Got execution result"),a.succeedImmediately&&!o&&(this.pendingInstructions.pop(),this.pendingInstructions.length>0&&(a.succeedImmediately=!1)),a.elementInteracted&&"target"in e&&e.target&&e.target.type==="description"&&!e.target.elementDescriptor&&(e.target.elementDescriptor=a.elementInteracted.trim()),o||(s.generatedStep=e,s.serializedCommand=ft(e),s.state="DONE"),a}async executeAIAssertion(e,t){let n={type:"ASSERTION"},o=async()=>{try{let g=await this.browser.screenshot({clearHighlights:!0,scale:"css"});return tc(this.uploadScreenshotForDebugging("assertion",g),{milliseconds:5e3,fallback:()=>{}}),g}catch(g){this.logger.warn({err:g},"Failed to take screenshot for assertion, continuing without it")}},s=await this.getBrowserState({}),i=await o(),{serializedTree:a}=s,{tree:l}=s,c=this.browser.url(),u=.2*Hn["gpt-4o-2024-05-13"],d=ss({serializedTree:a,tokenLimit:u,logger:this.logger});if(d){let f=(await this.generator.getRecommendedChunks({...d,description:t.assertion,tokenLimit:u})).ids;f.length===0?this.logger.debug("RAG returned no important information for assertion"):(a=l.pruneUsingRelevantIds(new Set(f)).serialize(),this.logger.debug({browserState:a},"Pruned a11y tree with RAG"),n.ragUsed=!0)}n.pageState=a;let m=this.getSerializedHistory(c,a),h={goal:t.assertion,url:c,browserState:a,history:m,lastCommand:this.lastExecutedCommand,screenshot:i?.toString("base64"),numPrevious:this.commandHistory.length},p=await this.generator.getAssertionResult(h,{disableCache:!!t.disableCache,orgId:this.orgId});if(p.relevantElements&&(await Promise.all(Array.from(new Set(p.relevantElements)).slice(0,3).map(g=>this.browser.highlight({id:g}))),n.relevantElementsSerialized=p.relevantElements.map(g=>this.browser.getSerializedFormFromA11yId(g)).filter(g=>!!g)),this.logger.debug({usedRag:n.ragUsed,result:p},"Got assertion result"),!p.result)throw new A("AssertionFailureError",p.thoughts);return{succeedImmediately:!1,thoughts:p.thoughts,urlAfterCommand:c,beforeScreenshotOverride:i}}async wrapMultiElementTargetingCommand(e,t,n,o,s,i,a=1){let l=await Promise.all(n.map((c,u)=>this.wrapElementTargetingCommand({ctx:e,target:c,cache:o[u],action:async d=>d,options:{...i,targetName:t[u]}})));try{return{result:await s(...l.map(u=>u.result)),caches:l.map(u=>u.cache),elementInteractedDisplayStrings:l.map(u=>u.elementInteractedDisplayString)}}catch(c){if(a>0)return this.logger.debug({err:c},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand(e,t,n,n.map(()=>{}),s,i,a-1);throw new A("ActionFailureError",c.message,{cause:c})}}async wrapFrameUseCommand(e,t){if(!t)return e();let n=this.browser.getActiveFrame();try{return this.logger.debug({frameUrl:t},"Setting parent iframe target"),this.browser.setActiveFrame({type:"url",url:t}),await e()}finally{this.browser.setActiveFrame(n)}}async wrapElementTargetingCommand(e){return this.wrapFrameUseCommand(()=>this.wrapElementTargetingCommandHelper(e),e.options.iframeUrl)}async wrapElementTargetingCommandHelper({ctx:e,target:t,cache:n,action:o,options:s}){let{disableCache:i,useSelector:a,targetName:l="target",targetHealingInProgress:c}=s,u=s.retriesWithAI??1;if((!n||i)&&!ro(t))throw new A("ActionFailureError","Cannot target element with no cached data or element descriptor");if(a){if(t.type!=="description")throw new A("ActionFailureError","Cannot use selector along with non-description target");let m={id:-1,selector:t.elementDescriptor,targetSource:"USER_CSS_SELECTOR"},h=await this.browser.resolveTarget(e,m,{targetName:l});return{result:await o(h.locator),cache:m,elementInteractedDisplayString:h.displayString}}i&&(this.logger.debug("Cache explicitly disabled for this step"),n=void 0),n?.inputDescription&&t.elementDescriptor!==n.inputDescription&&(this.logger.debug({old:n.inputDescription,new:t.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),n=void 0);let d=!!n&&Jr(n);if(!n){this.logger.debug("Prompting AI for an updated element location"),u--;let m=await this.locateElement(e,{description:t.elementDescriptor,disableCache:i,iframeUrl:s.iframeUrl}),h=await o(m.resolution.locator);return c&&(m.target.targetSource="AI_HEALED"),{result:h,cache:m.target,thoughts:m.thoughts,elementInteractedDisplayString:m.resolution.displayString}}try{let m=await this.browser.resolveTarget(e,n,{targetName:l}),h=await o(m.locator);return d?this.logger.debug({cache:n},"Successfully used cached target to perform action"):this.logger.debug({cache:n},"Successfully generated and used new target data"),{result:h,cache:n,thoughts:void 0,elementInteractedDisplayString:m.displayString}}catch(m){if(m instanceof A)throw m;if(u>0&&t)return this.logger.debug({err:m,cache:n},"Failed to execute action with cached target, retrying with AI"),this.wrapElementTargetingCommand({ctx:e,target:t,cache:void 0,action:o,options:{...s,retriesWithAI:u,targetHealingInProgress:!0}});throw new A("ActionFailureError",m.message,{cause:m})}}async screenshotWithDimensions(e){return Hr(this.browser,e)}async executePresetStep(e,t,n,o,s){let i;try{i=await this.resolveCommandTemplateStrings(t,n)}catch(a){throw new A("ActionFailureError",a.message,{cause:a})}try{let a=await this.browser.getOpenPageUrls(),l=this.browser.url(),c=await this.executePresetActionHelper(e,t,n,o,s),u=!0;(t.type==="NAVIGATE"||t.type==="NEW_TAB"||t.type==="TAB"||t.type==="REFRESH")&&(u=!1);let d=await this.browser.getOpenPageUrls(),m=this.browser.url();if(u&&d.length!==a.length)for(let h=d.length-1;h>=0;h--){let p=d[h];if(zt(p,this.logger)&&p!==l&&p!==m){await this.browser.switchToPage(p,h);break}}return c}catch(a){throw this.logger.error({err:a},"Error thrown in action controller"),a}finally{this.restoreCommandTemplateReplacements(t,i)}}restoreCommandTemplateReplacements(e,t={}){for(let[n,o]of Object.entries(t))is(e,n,o)}async resolveCommandTemplateStrings(e,t,n="",o={}){let s=["type","a11yData","thoughts","cache"];for(let i in e){if(s.includes(i))continue;let a=e[i],l=n?`${n}.${i}`:i;if(typeof a=="string"&&a.includes("{{")){let c=await _r({s:a,context:t,logger:this.logger,localTools:this.localCodeEvalTools});if(a===c)continue;o[l]=a,e[i]=c}else typeof a=="object"&&a!==null&&!Array.isArray(a)&&await this.resolveCommandTemplateStrings(a,t,l,o)}return o}async executePresetActionHelper(e,t,n,o,s){if(o=o||"disableCache"in t&&!!t.disableCache,s?.())throw new Ye("Execution cancelled by user");switch(t.type){case"SUCCESS":let i=t.condition;return i?.assertion.trim()?this.wrapFrameUseCommand(()=>this.executeAIAssertion(e,i),i?.iframeUrl):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_ASSERTION":{if(!t.assertion.trim())throw new A("ActionFailureError","Missing assertion");return this.wrapFrameUseCommand(()=>this.executeAIAssertion(e,t),t.iframeUrl)}case"AI_WAIT":{if(!t.assertion.trim())throw new A("ActionFailureError","Missing assertion");let p=Date.now();if(t.timeout&&t.timeout>1800)throw new A("AssertionFailureError",`AI wait timeout of ${t.timeout} exceeds the maximum allowed value of 30 minutes.`);let g=(t.timeout??10)*1e3;g>5e3&&await G(2500);let f;g>10*60*1e3?f=Math.floor(g/6):g>60*1e3?f=Math.floor(g/5):g>10*1e3?f=Math.floor(g/4):f=0;let S=0,w,b,E,v=async()=>{w=await this.wrapFrameUseCommand(()=>this.executeAIAssertion(e,{...t,type:"AI_ASSERTION"}),t.iframeUrl)};for(;!E||E-p<g;){if(s?.())throw new Ye(`AI wait cancelled by user.${b?` Last error: ${b.message}`:""}`);try{E=Date.now(),await v();break}catch(C){b=C instanceof Error?C:new Error(`${C}`),this.logger.info({err:C},`AI_WAIT assert attempt ${S} failed, retrying...`),f&&(this.logger.info(`Waiting ${f}ms before retrying AI wait check`),await G(f))}finally{S++}}if(!w){let C=`AI wait still failing after ${g}ms.`;throw b&&(C+=` Latest result: ${b.message}`),new A("AssertionFailureError",C)}return w}case"AI_EXTRACT":{if(!t.goal.trim())throw new A("ActionFailureError","Cannot perform AI extraction without goal");let p=await this.browser.getCondensedHtml(),g=await this.generator.getTextExtraction({goal:t.goal,browserState:p,returnSchema:t.schema},{disableCache:o,orgId:this.orgId});if(g.result==="NOT_FOUND")throw new A("ActionFailureError","No relevant data found for extraction goal on this page");return{data:g.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"NAVIGATE":if(!Mn(t.url)&&!Nn(t.url,this.browser.baseURL))throw new A("ActionFailureError",`Invalid URL provided to navigate command: ${t.url}`);await this.browser.navigate({url:t.url,loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0,networkIdleTimeoutMs:t.networkTimeout?t.networkTimeout*1e3:5e3});break;case"DIALOG":this.browser.registerDialogHandler(t.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let a=await this.browser.solveCaptcha();a&&(await this.wrapElementTargetingCommand({ctx:e,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:p=>this.browser.click(p,{}),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}}),await this.browser.type(a,{clearContent:!0,pressKeysSequentially:!1}));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":if(t.target&&!Ke(t.target))throw new Error("Scroll with x/y is not supported yet");let l,c;if(t.target&&t.target.elementDescriptor.trim()){let{cache:p,thoughts:g,elementInteractedDisplayString:f}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:S=>this.browser.hover(S,!1),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});l=f,p&&(t.cache={target:p}),c=g}switch(t.type){case"SCROLL_UP":await this.browser.scrollUp(t.deltaY);break;case"SCROLL_DOWN":await this.browser.scrollDown(t.deltaY);break;case"SCROLL_LEFT":await this.browser.scrollLeft(t.deltaX);break;case"SCROLL_RIGHT":await this.browser.scrollRight(t.deltaX);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:l,thoughts:c};case"WAIT":if(t.delay>1800)throw new A("UserConfigurationError",`User requested to wait for ${t.delay} seconds, which exceeds the maximum allowed time of 30 minutes`);let u=t.delay*1e3;for(;u>0;){if(s?.())throw new Ye("Wait cancelled by user");let p=Math.min(u,15e3);u-=p,this.logger.debug(`Sleeping for ${p}ms (with ${u}ms remaining after)`),await G(p)}break;case"REFRESH":await this.browser.refresh({networkIdleTimeoutMs:t.networkTimeout?t.networkTimeout*1e3:void 0,loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0});break;case"CLICK":{let p=jl.parse(t);if(Tt(t.target)){await this.browser.clickUsingVisualCoordinates(t.target.percentXYLocation,p);break}let g=this.browser.url(),f={disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl},{elementInteractedDisplayString:S,cache:w,thoughts:b,result:E}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:C=>this.browser.click(C,Yl(this.orgId),p),options:f});w&&(t.cache={target:w});let v={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:S,thoughts:b,data:E};return Ut(g,v.urlAfterCommand)&&(v.succeedImmediately=!0,v.succeedImmediatelyReason="URL changed"),v}case"DRAG":{if(Tt(t.fromTarget)&&Tt(t.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(t.fromTarget.percentXYLocation,t.toTarget.percentXYLocation,{force:t.force,hoverSeconds:t.hoverSeconds});break}if(Tt(t.fromTarget)||Tt(t.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{caches:p,elementInteractedDisplayStrings:g}=await this.wrapMultiElementTargetingCommand(e,["from target","to target"],[t.fromTarget,t.toTarget],[t.cache?.fromTarget,t.cache?.toTarget],(f,S)=>this.browser.dragAndDrop(f,S,{force:t.force,hoverSeconds:t.hoverSeconds}),{useSelector:!!t.useSelector,disableCache:o});return p&&p.every(f=>f)&&(t.cache={fromTarget:p[0],toTarget:p[1]}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g[0]}}case"MOUSE_DRAG":{if(t.target&&!Ke(t.target))throw new Error("Scroll with x/y is not supported yet");let p,g,f;if(t.target?.elementDescriptor){let{cache:b,thoughts:E,elementInteractedDisplayString:v,result:C}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:async R=>R,options:{useSelector:!!t.useSelector,iframeUrl:t.iframeUrl,disableCache:o}});p=C,g=v,f=E,b&&(t.cache={target:b})}let S=parseInt(t.deltaX),w=parseInt(t.deltaY);if(isNaN(S)||isNaN(w))throw new A("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${t.deltaX}, ${t.deltaY})`);return await this.browser.mouseDrag(S,w,t.steps,p,{force:t.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:f}}case"SELECT_OPTION":{if(!Ke(t.target))throw new Error("Select with x/y is not supported yet");let p=t.target.elementDescriptor,{cache:g,thoughts:f,elementInteractedDisplayString:S}=await this.wrapElementTargetingCommand({ctx:e,target:{type:"description",elementDescriptor:Ar(t,p)},cache:t.cache?.target,action:w=>this.browser.selectOption(w,t.option,t.force),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return g&&(t.cache={target:g}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:S,thoughts:f}}case"TAB":await this.browser.switchToPage(t.url,void 0,{networkIdleTimeoutMs:t.networkTimeout?t.networkTimeout*1e3:void 0,loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0});break;case"NEW_TAB":await this.browser.createNewTab(t.url,{networkIdleTimeoutMs:t.networkTimeout?t.networkTimeout*1e3:void 0,loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0});break;case"COOKIE":if(!t.value)break;await this.browser.setCookie(t.value);break;case"LOCAL_STORAGE":if(!t.value||!t.key)break;await this.browser.setLocalStorage(t.key,t.value);break;case"JAVASCRIPT":{let p;try{t.environment==="BROWSER"?p=await this.browser.executePageFunction(new ni(t.fragment?`return ${t.code}`:t.code),void 0):p=await ar({code:t.code,fragment:!!t.fragment,context:n,timeoutMs:t.timeout?t.timeout*1e3:void 0,logger:this.logger,localTools:this.localCodeEvalTools})}catch(g){throw new A("ActionFailureError",g instanceof Error?g.message:`${g}`,{cause:g})}try{JSON.stringify(p)}catch(g){throw new A("ActionFailureError",`Return value is not serializable: ${g instanceof Error?g.message:`${g}`}`,{cause:g})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:p}}case"TYPE":{let p=this.browser.url(),g,f,S=tg(t.target);if(S){S.elementDescriptor=Ar(t,S.elementDescriptor);let{elementInteractedDisplayString:b,cache:E,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,target:S,cache:t.cache?.target,action:C=>this.browser.typeIntoTarget(t.value,C,{force:t.force,clearContent:t.clearContent,pressKeysSequentially:t.pressKeysSequentially}),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});f=v,g=b,E&&(t.cache={target:E})}else await this.browser.type(t.value,{force:t.force,clearContent:t.clearContent,pressKeysSequentially:t.pressKeysSequentially});t.pressEnter&&await this.browser.press("Enter");let w={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:g,thoughts:f};return Ut(p,w.urlAfterCommand)&&(w.succeedImmediately=!0,w.succeedImmediatelyReason="URL changed"),w}case"HOVER":{if(Tt(t.target)){await this.browser.hoverUsingVisualCoordinates(t.target.percentXYLocation);break}let{cache:p,thoughts:g,elementInteractedDisplayString:f}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:S=>this.browser.hover(S,!!t.force),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return p&&(t.cache={target:p}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:g}}case"FOCUS":{if(!Ke(t.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:p,cache:g,thoughts:f}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:S=>this.browser.focus(S),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return g&&(t.cache={target:g}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:p,thoughts:f}}case"BLUR":{if(!Ke(t.target))throw new Error("Blur with x/y is not supported yet");let{cache:p,thoughts:g,elementInteractedDisplayString:f}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:S=>this.browser.blur(S),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return p&&(t.cache={target:p}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:g}}case"PRESS":let d=this.browser.url();await this.browser.press(t.value);let m={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Ut(d,m.urlAfterCommand)&&(m.succeedImmediately=!0,m.succeedImmediatelyReason="URL changed"),m;case"REQUEST":return ec({command:t,browser:this.browser,logger:this.logger});case"VISUAL_DIFF":return Zl({ctx:e,command:t,disableCache:o,browser:this.browser,browserStateGetter:p=>this.getBrowserState(p),targetingWrapper:p=>this.wrapElementTargetingCommand(p)});case"FILE_UPLOAD":{let p=t.fileSource.url;if(!p.startsWith("http")&&!p.startsWith(Br))throw new A("UserConfigurationError","The source URI for the file upload step must be a valid URL or a previously downloaded file beginning with 'file://'");let g=await xl({uri:p,logger:this.logger,orgId:this.orgId});await this.browser.setFileChooserHandler(g);break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let p=await ar({code:t.storageState,fragment:!1,context:n,logger:this.logger,localTools:this.localCodeEvalTools});if(typeof p!="object")throw new A("ActionFailureError",`Credentials must evaluate to an object (received ${typeof p} instead)`);let g;try{g=ii.parse(p)}catch(f){throw new A("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(g);break}case"ELEMENT_CHECK":{if(t.target&&!Ke(t.target))throw new Error("Element assertion with x/y is not supported yet");let p=Date.now(),g=(t.timeout??Et)*1e3,f=0,S;for(;f<2||Date.now()-p<g;){f++;try{let{cache:w,thoughts:b,elementInteractedDisplayString:E}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:async v=>{await Xl({assertion:t.assertion,element:v,callbacks:{highlightTarget:async C=>this.browser.highlightTarget(C)}})},options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return w&&(t.cache={target:w}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:E,thoughts:b}}catch(w){S=w}}throw new A("AssertionFailureError",`Element check still failing after ${Math.floor((Date.now()-p)/1e3)} seconds: ${S?S.message:""}`)}case"PAGE_CHECK":{await Jl({assertion:t.assertion,page:this.browser.getActivePage(),logger:this.logger,timeout:t.timeout});break}default:return(p=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedTarget(e,t,n){return(await this.generator.getReverseMappedDescription({browserState:e.browserState,goal:`${t}`},{disableCache:n,orgId:this.orgId})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode(e){this.recordAbortController=new AbortController;let t=new Wn({signal:this.recordAbortController.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,t),t}};var ng=2,og=2250;async function rc({socket:r,logger:e,storage:t,devicePixelRatio:n,generator:o,browserbase:s,getCpuUsage:i,authorization:a}){let l=r.id,c=i?.();if(c&&c>og)throw e.error({cpuUsage:c,event:"connect",args:r.handshake.query,sessionId:l},"Socket connection resource rate limit triggered"),new Error("You have reached a Momentic server under heavy load. Please refresh the page to establish a new connection. Automatic scale-up processes can take up to 3 minutes.");let u=r.handshake.query.testId,d=r.handshake.query.baseUrl,m=r.handshake.query.envName,h=r.handshake.query.viewport?JSON.parse(decodeURIComponent(r.handshake.query.viewport)):void 0,p=r.handshake.query.testMetadata?me.parse(JSON.parse(decodeURIComponent(r.handshake.query.testMetadata))):void 0;if(!u||!d)throw new Error("Socket connection request is missing testId or baseUrl");let g=await t.getOrgId(u),f=r.handshake.query.environmentVariables?JSON.parse(decodeURIComponent(r.handshake.query.environmentVariables)):{},S=r.handshake.headers["x-forwarded-for"]?.split(",")[0],w=e.child({testId:u,baseUrl:d,orgId:g,sessionId:l});if(w.info({clientIp:S,event:"connect",args:r.handshake.query,sessionId:l},"Websocket event (connect)"),S&&N.getCurrentConnectionsByIp(S)>=ng)throw e.error({clientIp:S,sessions:N.getCurrentSessionsByIp(),...r.handshake.query},"Socket connection browser creation rate limit triggered"),new Error("You have exceeded the maximum number of connections allowed per client. Momentic limits the number of simultaneously open tabs to uphold browser reliability. Please close another tab and retry or contact Momentic Support if you believe this is in error.");N.reserveCapacityByIp(S);let b;a?.type==="API_KEY"&&(b=new rt(a));try{await sg({socket:r,baseUrl:d,envName:m,viewport:h,testMetadata:p,orgId:g,sessionId:l,logger:w,environmentVariables:f,clientIp:S,devicePixelRatio:n,storage:t,localCodeEvalTools:b,generator:o,browserbase:s})}catch(E){throw w.debug({err:E},"Error setting up socket session"),N.releaseCapacityByIp(S),E}return{sessionId:l,testId:u,orgId:g}}async function sg({socket:r,baseUrl:e,viewport:t,envName:n,devicePixelRatio:o,testMetadata:s,orgId:i,sessionId:a,logger:l,storage:c,localCodeEvalTools:u,generator:d,environmentVariables:m,clientIp:h}){let p={};t&&(p.viewport=t),o&&(p.deviceScaleFactor=o);let g=Cr.parse(s?.advanced??{}),[f,S]=await Promise.all([Ge.init({baseUrl:e,userBrowserSettings:g,waitForLoad:!0,enricher:new $n(l),timeout:g.pageLoadTimeoutMs,storage:c,logger:l,contextArgs:p,onTabsChange:(C,R)=>{r.emit("tabs",{tabs:C,activeTab:R})}}),dr.init(i)]),w=new mr({browser:f,generator:d,config:$r,logger:l,flagStore:S,orgId:i,storage:c,localCodeEvalTools:u}),b=Pa(r,a,l),E=async()=>{clearInterval(b.timer)},v=new he({baseUrl:e,currentUrl:w.browser.url(),variablesFromEnvironment:m,envName:n});if(!r.connected)throw await f.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");r.emit("session",{url:e,userAgent:Ge.USER_AGENT,viewport:await w.browser.getViewport(),sessionId:a}),N.registerSession({controller:w,context:v,sessionId:a,cleanup:E,clientIp:h})}var nc=[Ma,Va,qa,$l,Oa,Wl,Hl,Ya,Qa,Za,Xa,Ka,el,Ja];var oc=r=>{let{logger:e}=r,t=new ig(r.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:3e4,pingInterval:6e4,maxHttpBufferSize:1e7});return t.on("connection",async n=>{let o;try{o=await rc({...r,socket:n})}catch(s){e.error({event:"connection",type:"websocket",err:s},"Failed to setup connection"),n.emit("error",{message:s instanceof Error?s.message:`${s}`}),n.disconnect(!0);return}nc.forEach(s=>ag(s,{socket:n,metadata:o,...r}))}),t};var ag=(r,e)=>{let t=r.createHandler(e),n=(...o)=>{["cloudMouseMove","cloudScroll","cloudType"].includes(r.event)||e.logger.debug({...e.metadata,event:r.event,args:o},`Websocket event (${r.event})`);let s=i=>{e.logger.error({event:r.event,type:"websocket",args:o,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=t.apply(void 0,o);i&&typeof i.catch=="function"&&i.catch(s)}catch(i){s(i)}};e.socket.on(r.event,n)};import{z as dg}from"zod";import lg from"fetch-retry";var cg=lg(global.fetch),ge=class{static API_VERSION="v1";baseURL;apiKey;constructor(e){this.baseURL=e.baseURL,this.apiKey=e.apiKey}async sendRequest(e,t){let n=await cg(`${this.baseURL}${e}`,{retries:1,retryDelay:1e3,method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});if(!n.ok)throw new Error(`Request to ${e} failed with status ${n.status}: ${await n.text()}`);return n.json()}};var Ht=class extends ge{constructor(e){super(e)}async getRecommendedChunks(e){let t=await this.sendRequest(`/${ge.API_VERSION}/web-agent/recommend-chunks`,e);return Wi.parse(t)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${ge.API_VERSION}/s3/visual-diff-screenshot`,{url:e});return dg.string().parse(t)}async getElementLocation(e,t){let n=await this.sendRequest(`/${ge.API_VERSION}/web-agent/locate-element`,{...e,disableCache:t.disableCache});return xi.parse(n)}async getAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache},o=await this.sendRequest(`/${ge.API_VERSION}/web-agent/assertion`,n);return Ri.parse(o)}async getProposedCommand(e,t){let n=await this.sendRequest(`/${ge.API_VERSION}/web-agent/next-command`,{url:e.url,browserState:e.browserState,goal:e.goal,history:e.history,numPrevious:e.numPrevious,lastCommand:e.lastCommand,screenshot:e.screenshot,disableCache:t.disableCache});return Ai.parse(n)}async getGranularGoals(e,t){let n=await this.sendRequest(`/${ge.API_VERSION}/web-agent/split-goal`,{url:e.url,goal:e.goal,disableCache:t.disableCache});return Ii.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${ge.API_VERSION}/web-agent/reverse-mapped-description`,{goal:e.goal,browserState:e.browserState,disableCache:t.disableCache});return Li.parse(n)}async getTextExtraction(e,t){let n={goal:e.goal,browserState:e.browserState,returnSchema:e.returnSchema,disableCache:!!t.disableCache},o=await this.sendRequest(`/${ge.API_VERSION}/web-agent/text-extraction`,n);return wo.parse(o)}async getTestResultClassification(e){let t=await this.sendRequest(`/${ge.API_VERSION}/web-agent/result-classification`,e);return So.parse(t)}};import{Router as ug}from"express";function Ee(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var sc=ug();sc.get("/",Ee((r,e)=>{let t=Ia();e.status(200).json(t)}));var ic=sc;import{Router as fg}from"express";import ac,{multistream as mg}from"pino";import pg from"pino-pretty";var cs=new Map,gg=!0,ds=class r{consoleLogger;ddClientToken;hostname;bindingAttributes;excludeAttributesInConsoleLogs;excludeTimestamps;disableConsoleLogs;site="https://http-intake.logs.us5.datadoghq.com/api/v2/logs";constructor({bindings:e,clientToken:t,hostname:n,excludeAttributesInConsoleLogs:o,excludeTimestamps:s,disableConsoleLogs:i}){this.ddClientToken=t,this.hostname=n,this.excludeAttributesInConsoleLogs=o,this.excludeTimestamps=s,this.disableConsoleLogs=i,this.bindingAttributes={...e,env:"production"};let a={base:o?{}:this.bindingAttributes,errorKey:"err",level:"debug",timestamp:!s};this.consoleLogger=gg?ac(a):ac(a,mg([{stream:pg({colorize:!0})}]))}child(e){return new r({clientToken:this.ddClientToken,bindings:{...this.bindingAttributes,...e},hostname:this.hostname,excludeAttributesInConsoleLogs:this.excludeAttributesInConsoleLogs,disableConsoleLogs:this.disableConsoleLogs})}flush(e){this.disableConsoleLogs||this.consoleLogger.flush(e)}log(e,t,n,...o){if(t&&n===void 0&&(n=`${t}`,t={}),this.disableConsoleLogs||this.consoleLogger[e](e==="error"?t:{testId:t.testId,runId:t.runId},n,...o),typeof t=="object"&&t&&"err"in t&&t.err instanceof Error){let i={};for(let a of Object.getOwnPropertyNames(t.err))i[a]=t.err[a];i.name=t.err.name,t.err=i}let s=Object.assign({},this.bindingAttributes,t&&typeof t=="object"?t:{});o.length>0&&(s.args=o),(async()=>{try{let i=await fetch(this.site,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","DD-API-KEY":this.ddClientToken},body:JSON.stringify([{ddsource:this.bindingAttributes.app,hostname:this.hostname??"vercel",service:"momentic",message:{message:n||"",...s,level:e}}])});if(!i.ok)throw new Error(`Failed to log to Datadog: ${i.statusText})}`)}catch(i){this.disableConsoleLogs||this.consoleLogger.warn({obj:t,msg:n,args:o,err:i},"Failed to log to Datadog")}})()}debug(e,t,...n){this.log("debug",e,t,...n)}info(e,t,...n){this.log("info",e,t,...n)}warn(e,t,...n){this.log("warn",e,t,...n)}error(e,t,...n){this.log("error",e,t,...n)}bindings(){return this.bindingAttributes}setMinLevel(e){this.consoleLogger.level=e}enableConsoleLogs(){this.disableConsoleLogs=!1}},Vn=({app:r,clientToken:e,hostname:t,excludeAttributesInConsoleLogs:n,excludeTimestamps:o,disableConsoleLogs:s})=>{if(!process.env.DD_CLIENT_TOKEN&&!process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN&&!e)throw new Error("Missing DD_CLIENT_TOKEN");return cs.has(r)||cs.set(r,new ds({bindings:{app:r},hostname:t,clientToken:e||process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN||process.env.DD_CLIENT_TOKEN,excludeAttributesInConsoleLogs:n,excludeTimestamps:o,disableConsoleLogs:s})),cs.get(r)};import{hostname as hg}from"os";var ve=Vn({app:"desktop-server",clientToken:"pubcfd7516a5c0ba852b42675cd97bee027",hostname:hg(),excludeAttributesInConsoleLogs:!0,excludeTimestamps:!0,disableConsoleLogs:!0});var Wr=fg();Wr.get("/",Ee(async(r,e)=>{let t=await Ca(ve);e.status(200).json(t)}));Wr.get("/metadata",Ee((r,e)=>{let t=ba();e.status(200).json(t)}));Wr.post("/",Ee(async(r,e)=>{let t;try{t=bi.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}try{Tr(t.name)}catch(o){e.status(400).json({error:`Invalid module name: ${o}`});return}let n=await wa(t.name,t.steps);e.status(201).json(n)}));Wr.get("/:moduleId",Ee(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await Ta(r.params.moduleId,ve);if(!t){e.status(404).json({error:"Module not found."});return}e.json(t)}));var lc=Wr;import{Router as yg}from"express";import{existsSync as Sg}from"fs";import{join as Kn}from"path";import{v4 as wg}from"uuid";var ms="https://api.momentic.ai",cc=r=>{ms=r},Gr=()=>ms,pr,us,dc=async r=>{if(pr)return pr;let e=new ie({baseUrl:ms,apiKey:r});try{return pr=await e.getOrgId(),us=r,pr}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},qn=()=>{if(!pr)throw new Error("Your organization ID appears invalid. Please contact Momentic Support.");return pr},uc=()=>{if(!us)throw new Error("Your API key appears invalid. Please contact Momentic Support.");return us};var Wt=yg();Wt.get("/",Ee((r,e)=>{let t=Or(te,ve);e.status(200).json(t)}));Wt.post("/",Ee(async(r,e)=>{let t;try{t=wi.parse(r.body)}catch(a){e.status(400).json({error:`Invalid request body: ${a}`});return}try{Tr(t.name)}catch(a){e.status(400).json({error:a.message});return}let o={id:wg(),name:t.name,baseUrl:t.baseUrl,schemaVersion:Ce,advanced:{disableAICaching:!1,viewport:t.viewport??Xe},retries:0,steps:[]};t.environment&&(o.envs=[{name:t.environment,default:!0}]);let s=await Aa(o,t.name),i={...o,testPath:s};e.status(201).json(i)}));Wt.get("/:testPath",Ee(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t=Kn(te,r.params.testPath);if(!Sg(t)){e.status(400).json({error:`Test not found at path: ${t}`});return}let n=await Pn(t,yt,ve);e.status(200).json(n)}));Wt.patch("/:testPath/metadata",Ee(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=Si.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}let n=Kn(te,r.params.testPath);Ln(t,n),e.status(201).json({message:"ok"})}));Wt.patch("/:testPath",Ee(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=yi.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}let n=Kn(te,r.params.testPath),o;try{o=Ra(n)}catch(c){e.status(400).json({error:`Existing test file on disk is invalid: ${c}`});return}let{stepsToSave:s,moduleUpdates:i,cachesToSave:a}=await He({steps:t.steps,cacheCreationParams:{testId:o.id,orgId:qn()}});i.forEach(c=>Sa({...c,schemaVersion:Ce})),Ln({schemaVersion:Ce,steps:s},n),await new ie({apiKey:uc(),baseUrl:Gr()}).updateStepCaches({entries:a,testId:o.id}),e.status(201).json({message:"ok"})}));Wt.patch("/:testPath/environments",Ee(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=Ci.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}let n=Kn(te,r.params.testPath);Ln({envs:t.defaultEnv?[{name:t.defaultEnv,default:!0}]:[]},n),e.status(201).json({message:"ok"})}));var mc=Wt;async function pc(r){let{momenticServerUrl:e,apiKey:t,serverPort:n,appPort:o,staticDir:s,devicePixelRatio:i}=r;if(!Tg(te)||!Eg(te).isDirectory()){let f=Rg.isAbsolute(te);throw new Error(`Root folder ${te} does not exist${f?"":` in the current directory ("${process.cwd()}")`}. Please run \`npx momentic init\` if you wish to setup Momentic here for the first time.`)}e&&cc(e),ve.debug(r,"Initializing desktop server");let a=await dc(t);ve.debug({orgId:a},"Checking API key successful");let c=`http://localhost:${n}`;o&&(c=`http://localhost:${o}`);let u=xg(s);await new Promise(f=>{u.listen(n,()=>{ve.info(`Server is running at http://localhost:${n}`),f()})});let m=new Ht({baseURL:Gr(),apiKey:t}),h={type:"API_KEY",baseUrl:Gr(),apiKey:t},p=new ie(h),g=new ir(p,qn());oc({baseServer:u,generator:m,storage:g,logger:ve,devicePixelRatio:i,authorization:h}),await Ag(c)}function xg(r){let e=ps();e.use(Cg()),e.use(bg.json({limit:"50mb"}));let t=ps.Router();if(t.use("/tests",mc),t.use("/modules",lc),t.use("/environments",ic),e.use("/api",t),e.use((o,s,i)=>{o.path!=="/healthcheck"&&ve.debug({url:o.url,path:o.path,query:o.query,method:o.method,body:o.body,headers:o.rawHeaders,client:o.ip},"Received desktop-server request"),s.on("close",()=>{s.statusCode>=400&&ve.error({url:o.url,method:o.method,statusCode:s.statusCode},"Request completed in error")}),i()}),e.use((o,s,i,a)=>{o instanceof Error&&o.message.includes("BadRequestError: request aborted")||(ve.error({stack:o.stack,msg:o.message,url:s.url,method:s.method},"Unhandled exception leading to 500 on desktop-server"),i.status(500).send("Internal Server Error"),a(o))}),r){let o=ps.static(r);e.use("/",o),e.use("*",o)}return vg.createServer(e)}import{existsSync as Ah}from"fs";import Xc,{dirname as Rh,join as xh}from"path";import{chdir as Ih}from"process";import{fileURLToPath as Lh}from"url";var gc="0.0.124";import jr from"chalk";var Gt=(...r)=>{Z(jr.blue(...r))};var je=(...r)=>{Z(jr.dim(...r))};var we=(...r)=>{Z(jr.green(...r))},Z=(...r)=>{console.log(...r)},ae=(...r)=>{console.error(jr.yellow(...r))},P=(...r)=>{console.error(jr.red(...r))};import{hostname as Lg}from"os";var I=Vn({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:Lg(),excludeAttributesInConsoleLogs:!0,excludeTimestamps:!0,disableConsoleLogs:!0});import{execSync as Pg}from"child_process";import{platform as Og}from"os";function gs(){return hc()?(Gt("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),Gt("If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations."),Gt("Confirm your device's pixel-ratio at https://www.mydevice.io."),2):(Gt("Setting device pixel ratio to 1."),Gt("If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations"),Gt("Confirm your device's pixel-ratio at https://www.mydevice.io."),1)}function hc(){return Og()==="darwin"&&Pg("system_profiler SPDisplaysDataType").toString().includes("Retina")}function hs(r){hc()&&r===1&&(ae("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),ae("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import{createHash as Cc}from"crypto";import{existsSync as Tc,readFileSync as Cs,writeFileSync as Ec}from"fs";import{join as vc}from"path";import{parse as qg}from"yaml";import{existsSync as Ss,mkdirSync as yc,readdirSync as $g,statSync as Sc}from"fs";import{homedir as wc}from"os";import{join as nt,resolve as Hg}from"path";import{existsSync as Mg,statSync as Ng}from"fs";var Yn=!!process.env.CI||!process.stdout.isTTY;function bt(r){try{return Mg(r)&&Ng(r).isDirectory()}catch(e){return P({err:e},`Error reading path ${r} during directory existence check`),!1}}import{registry as fs}from"playwright-core/lib/server";function _g(r){let e=[],t=[];for(let n of r){let o=fs.findExecutable(n);!o||o.installType==="none"?e.push(n):t.push(o)}return t}async function Xn(){let r=_g(["chromium"]);await fs.installDeps(r,!1),await fs.install(r,!1)}import{statSync as kg}from"fs";import{existsSync as Dg,mkdirSync as Fg}from"fs";import{dirname as Ug}from"path";import zg from"readline/promises";var ys=!1,Bg=(()=>{try{return kg("/.dockerenv"),!0}catch{return!1}})();async function ze(r,e){if(Yn||ys||Bg)return!0;I.flush(),await new Promise(i=>setTimeout(i,500));let t=zg.createInterface({input:process.stdin,output:process.stdout}),n=r.split("."),o;if(n.length===1)o=r;else{let i=`${n.slice(0,n.length-1).join(". ").trim()}.`;e?ae(i):Z(i),o=n[n.length-1].trim()}let s=await t.question(`${o} ('y' for yes / n for no / 'A' to accept all) `);return t.close(),s==="A"?(ys=!0,setTimeout(()=>{ys=!1},3e3),!0):s.toLowerCase()==="y"}async function Vr(r){let e=Ug(r);return bt(e)?Dg(r)?ze(`File '${fc(r)}' already exists. Overwrite existing content?`,!0):!0:await ze(`Directory '${fc(e)}' doesn't exist. Create it now?`,!0)?(Fg(e,{recursive:!0}),!0):!1}function fc(r){return r.replace(/(\s+)/g,"\\$1")}var Wg=[gt,hn,er],ot=Vg(),jt=nt(ot,gt),bs=nt(ot,hn),st=nt(ot,er),ws=nt(wc(),"momentic",Io),bc=[jt,bs,st];async function it(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<20)&&(P(`Node.js version 20 or higher is required to run the Momentic CLI. Detected: ${process.versions.node}.`),process.exit(1));let n=await r.client.getOrgId();return await Xn(),await jg(r),n}async function Gg(r){bt(ot)||!r&&!await ze(`The root '${pt}' folder was not found in the current directory. You will need to invoke the Momentic CLI from this directory in the future. Proceed?`)&&(P("Setup cancelled."),process.exit(1)),bt(ws)||(!r&&!await ze("The Chrome cache folder was not found in your home directory. Proceed with creation?")&&(P("Setup cancelled."),process.exit(1)),yc(ws,{recursive:!0}));for(let e of bc)bt(e)||(!r&&!await ze(`'${e}' folder was not found in the current directory. Create it now?`)&&(P("Setup cancelled."),process.exit(1)),yc(e,{recursive:!0}))}function qr(r,e,t=new Set){for(let n of r){let o=Hg(n),s=!1;try{s=Ss(o)&&Sc(o).isDirectory()}catch(i){I.error({err:i},`Error reading path ${o} during collect paths`)}if(o&&s){let i=$g(o).map(a=>nt(o,a));qr(i,e,t);continue}if(o.endsWith(".yaml")){try{if(!Ss(o)||!Sc(o).isFile()){I.error(`File not found or unreadable: ${o}`);continue}}catch(i){I.error({err:i},`Error reading file ${o} during collect paths`);continue}if(!e(o))continue;t.add(o)}}return t}async function jg({client:r,createFolders:e,skipPrompts:t,pullEnvs:n}){if(wc()||(P("Your home directory could not be found. Please ensure the HOME environment variable is set for POSIX systems, and the USERPROFILE environment variable is set for Windows systems."),process.exit(1)),e)await Gg(t);else for(let o of[ot,ws,...bc])!bt(o)&&!Yn&&(P(`The '${o}' folder is required to run the Momentic CLI but was not found in the current directory. Please run 'npx momentic@latest init' to create the required folders.`),P(`The current working directory is: ${process.cwd()}`),process.exit(1));n&&(!t&&!await ze("Pull environments from Momentic Cloud? Environment definitions may be required to run tests locally.")&&(P("Setup cancelled."),process.exit(1)),await Jn({client:r,all:!0,skipPrompts:t}))}function Vg(){let r=n=>Ss(nt(n,pt))&&Wg.some(o=>bt(nt(n,pt,o))),e=process.cwd();for(;e!=="/"&&!r(e);)e=nt(e,"..");let t;return r(e)?t=e:t=process.cwd(),t!==process.cwd()?ae(`Current working directory does not contain a ${pt} folder, treating ${t} as the Momentic root folder instead`):I.info(`Identified ${t} as the Momentic root folder`),nt(t,pt)}async function Jn({envNames:r,client:e,all:t,skipPrompts:n}){let o=await e.getAllEnvironments();r&&!t&&(o=o.filter(a=>r?.includes(a.name))),Tc(st)||(P(`${st} does not exist in the current directory. Please run 'npx momentic@latest init' first.`),process.exit(1));let s=[],i=[];for(let a of o){let l=vc(st,`${a.name}.yaml`);if(!n&&!await Vr(l))return;if(!Tc(l))Ec(l,Do(a)),s.push(l);else{let c=Cc("sha256").update(Cs(l)).digest("hex"),u=Do(a),d=Cc("sha256").update(u).digest("hex");c!==d&&(Ec(l,u),i.push(l))}}we("Pulled environments successfully!"),s.length&&(we("Created:"),s.forEach(a=>we(" ",a))),i.length&&(we("Updated:"),i.forEach(a=>we(" ",a)))}function Kg(r){return r.endsWith(".yaml")?Cs(r,"utf8").includes("momentic/environment")?!0:(ae(`Skipping YAML that is not a Momentic environment: ${r}`),!1):!1}async function Ac({client:r,names:e,all:t,yes:n}){let o;t?o=[st]:o=e.map(a=>vc(st,`${a.toLowerCase()}.yaml`));let s=qr(o,Kg);Z(`Found ${s.size} environments to push:`),s.forEach(a=>Z(" ",a));let i=[];for(let a of s){let l=qg(Cs(a,"utf-8"));try{let c=Re.parse(l);i.push(c)}catch(c){P(`${a} failed to parse as a valid environment file.`),P(c),process.exit(1)}}!n&&!await ze("Pushing environments can overwrite variables on cloud and instantly affect scheduled runs. Continue?",!0)||(await r.updateEnvironments(i),we("Pushed environments successfully!"))}import{Argument as Kr,Option as _e}from"commander";import{validateHeaderValue as Yg}from"http";import{cpus as Rc}from"os";import{z as Xg}from"zod";var at=new _e("--api-key <key>","API key for authentication. If not supplied, attempts to read the MOMENTIC_API_KEY env var.").env("MOMENTIC_API_KEY").makeOptionMandatory(!0),lt=new _e("--server <server>","Momentic server to use. Leave unchanged unless using Momentic on-premise.").default("https://api.momentic.ai"),ct=new _e("-y, --yes","Skip all confirmation prompts.").env("CI"),Ts=new _e("-w, --wait","Wait for tests to finish running before exiting. Only applicable when running tests remotely").implies({remote:!0}),Es=new _e("--wait-timeout-seconds <waitTimeoutSeconds>","The maximum number of seconds to wait for tests to complete. Only applicable when the --wait option is specified.").argParser(r=>parseInt(r,10)),vs=new _e("--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.");function As(r){if(r===void 0)return;let e={};for(let t of r){let n=t.indexOf("=");if(n===-1)throw new Error(`Header value pair does not contain '=': ${t}`);let o=t.slice(0,n),s=t.slice(n+1);Yg(o,s),e[o]=s}return e}var Rs=new _e("--no-report","Skip reporting test results to Momentic Cloud when running with the --local flag.").implies({local:!0}),xs=new _e("--pixel-ratio <number>","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(r=>parseInt(r,10)),Is=new _e("--env <env>","Name of the environment to use when running tests."),Ls=new _e("--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."),Ps=new _e("-a, --all","Select all tests in your organization from Momentic Cloud. Cannot be used together with <tests> arguments."),Os=new _e("-a, --all","Select all environments in your organization from Momentic Cloud. Cannot be used together with <paths> arguments."),xc=new Kr("<tests...>",`One or more test paths to pull from Momentic Cloud.
|
|
1654
|
+
`)}`}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}}async executeCommand(e,t,n,o=!1){let s=this.commandHistory[this.commandHistory.length-1];if(!o&&(!s||s.state!=="PENDING"))throw new R("InternalWebAgentError","Executing command but there is no pending entry in the history");if(this.closed)throw new Error("Attempting to execute command on a closed controller");let i=Date.now(),a=await this.executePresetStep(null,e,t,n),l=Date.now()-i;return this.logger.debug({result:a,duration:l},"Got execution result"),a.succeedImmediately&&!o&&(this.pendingInstructions.pop(),this.pendingInstructions.length>0&&(a.succeedImmediately=!1)),a.elementInteracted&&"target"in e&&e.target&&e.target.type==="description"&&!e.target.elementDescriptor&&(e.target.elementDescriptor=a.elementInteracted.trim()),o||(s.generatedStep=e,s.serializedCommand=St(e),s.state="DONE"),a}async wrapMultiElementTargetingCommand(e,t,n,o,s,i,a=1){let l=await Promise.all(n.map((c,u)=>this.wrapElementTargetingCommand({ctx:e,target:c,cache:o[u],action:async d=>d,options:{...i,targetName:t[u]}})));try{return{result:await s(...l.map(u=>u.result)),caches:l.map(u=>u.cache),elementInteractedDisplayStrings:l.map(u=>u.elementInteractedDisplayString)}}catch(c){if(a>0)return this.logger.debug({err:c},"Failed to execute action with multiple cached targets, retrying with AI"),this.wrapMultiElementTargetingCommand(e,t,n,n.map(()=>{}),s,i,a-1);throw new R("ActionFailureError",c.message,{cause:c})}}async wrapElementTargetingCommand(e){return Bt({action:()=>this.wrapElementTargetingCommandHelper(e),frameUrl:e.options.iframeUrl,browser:this.browser,logger:this.logger})}async wrapElementTargetingCommandHelper({ctx:e,target:t,cache:n,action:o,options:s}){let{disableCache:i,useSelector:a,targetName:l="target",targetHealingInProgress:c}=s,u=s.retriesWithAI??1,d=!1;if((!n||i)&&!io(t))throw new R("ActionFailureError","Cannot target element with no cached data or element descriptor");if(a){if(t.type!=="description")throw new R("ActionFailureError","Cannot use selector along with non-description target");let g={id:-1,selector:t.elementDescriptor,targetSource:"USER_CSS_SELECTOR"},m=await this.browser.resolveTarget(e,g,{targetName:l});return{result:await o(m.locator),cache:g,elementInteractedDisplayString:m.displayString}}i&&(this.logger.debug("Cache explicitly disabled for this step"),d=!0,n=void 0),n?.inputDescription&&t.elementDescriptor!==n.inputDescription&&(this.logger.debug({old:n.inputDescription,new:t.elementDescriptor},"Target cache was generated with a different description, clearing it automatically"),d=!0,n=void 0);let p=!!n&&en(n);if(!n){this.logger.debug({targetHealingInProgress:c},"Prompting AI for an updated element location"),d&&await j(this.browser.smartWaitingTimeout);let g=await us({description:t.elementDescriptor,disableCache:i,iframeUrl:s.iframeUrl},this.getControllerFixtures(e));u--;let m=await o(g.resolution.locator);return c&&(g.target.targetSource="AI_HEALED"),{result:m,cache:g.target,thoughts:g.thoughts,elementInteractedDisplayString:g.resolution.displayString}}try{let g=await this.browser.resolveTarget(e,n,{targetName:l}),m=await o(g.locator);return p?this.logger.debug({cache:n},"Successfully used cached target to perform action"):this.logger.debug({cache:n},"Successfully generated and used new target data"),{result:m,cache:n,thoughts:void 0,elementInteractedDisplayString:g.displayString}}catch(g){if(g instanceof R)throw g;if(u>0&&t)return this.logger.debug({err:g,cache:n},"Failed to execute action with cached target, retrying with AI"),this.wrapElementTargetingCommand({ctx:e,target:t,cache:void 0,action:o,options:{...s,retriesWithAI:u,targetHealingInProgress:!0}});throw new R("ActionFailureError",g.message,{cause:g})}}async screenshotWithDimensions(e){return jr(this.browser,e)}async executePresetStep(e,t,n,o,s){let i;try{i=await this.resolveCommandTemplateStrings(t,n)}catch(a){throw new R("ActionFailureError",a.message,{cause:a})}try{let a=await this.browser.getOpenPageUrls(),l=this.browser.url(),c=await this.executePresetActionHelper(e,t,n,o,s),u=!0;(t.type==="NAVIGATE"||t.type==="NEW_TAB"||t.type==="TAB"||t.type==="REFRESH")&&(u=!1);let d=await this.browser.getOpenPageUrls(),p=this.browser.url();if(u&&d.length!==a.length)for(let g=d.length-1;g>=0;g--){let m=d[g];if(Ut(m,this.logger)&&m!==l&&m!==p){await this.browser.switchToPage(m,g);break}}return c}catch(a){throw this.logger.error({err:a},"Error thrown in action controller"),a}finally{this.restoreCommandTemplateReplacements(t,i)}}restoreCommandTemplateReplacements(e,t={}){for(let[n,o]of Object.entries(t))cs(e,n,o)}async resolveCommandTemplateStrings(e,t,n="",o={}){let s=["type","a11yData","thoughts","cache"];for(let i in e){if(s.includes(i))continue;let a=e[i],l=n?`${n}.${i}`:i;if(typeof a=="string"&&a.includes("{{")){let c=await lr({s:a,context:t,logger:this.logger,localTools:this.localCodeEvalTools});if(a===c)continue;o[l]=a,e[i]=c}else typeof a=="object"&&a!==null&&!Array.isArray(a)&&await this.resolveCommandTemplateStrings(a,t,l,o)}return o}async executePresetActionHelper(e,t,n,o,s){if(o=o||"disableCache"in t&&!!t.disableCache,s?.())throw new $e("Execution cancelled by user");switch(t.type){case"SUCCESS":let i=t.condition;return i?.assertion.trim()?ms({command:i,fixtures:this.getControllerFixtures(e)}):{succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AI_WAIT":case"AI_ASSERTION":{if(!t.assertion.trim())throw new R("ActionFailureError","Missing assertion");if(t.timeout&&t.timeout>1800)throw new R("AssertionFailureError",`AI assertion timeout of ${t.timeout} exceeds the maximum allowed value of 30 minutes.`);return ms({command:{...t,type:"AI_ASSERTION"},fixtures:this.getControllerFixtures(e),opts:{isExecutionCancelled:s}})}case"AI_EXTRACT":{if(!t.goal.trim())throw new R("ActionFailureError","Cannot perform AI extraction without goal");let m=await this.browser.getCondensedHtml(),h=await this.generator.getTextExtraction({goal:t.goal,browserState:m,returnSchema:t.schema},{disableCache:o,orgId:this.orgId});if(h.result==="NOT_FOUND")throw new R("ActionFailureError","No relevant data found for extraction goal on this page");return{data:h.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"NAVIGATE":if(!kn(t.url)&&!Dn(t.url,this.browser.baseURL))throw new R("ActionFailureError",`Invalid URL provided to navigate command: ${t.url}`);await this.browser.navigate({url:t.url,loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0});break;case"DIALOG":this.browser.registerDialogHandler(t.action);break;case"CAPTCHA":if(!this.browser.canSolveCaptchas())break;let a=await this.browser.solveCaptcha();a&&(await this.wrapElementTargetingCommand({ctx:e,target:{type:"description",elementDescriptor:"the captcha image solution input"},cache:void 0,action:m=>this.browser.click(m,{}),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}}),await this.browser.type(a,{clearContent:!0,pressKeysSequentially:!1,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":if(t.target&&!qe(t.target))throw new Error("Scroll with x/y is not supported yet");let l,c;if(t.target&&t.target.elementDescriptor.trim()){let{cache:m,thoughts:h,elementInteractedDisplayString:f}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:S=>this.browser.hover(S,!1),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});l=f,m&&(t.cache={target:m}),c=h}switch(t.type){case"SCROLL_UP":await this.browser.scrollUp(t.deltaY);break;case"SCROLL_DOWN":await this.browser.scrollDown(t.deltaY);break;case"SCROLL_LEFT":await this.browser.scrollLeft(t.deltaX);break;case"SCROLL_RIGHT":await this.browser.scrollRight(t.deltaX);break}return{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:l,thoughts:c};case"WAIT_FOR_URL":if(t.timeout&&t.timeout>1800)throw new R("UserConfigurationError",`WAIT_FOR_URL timeout of ${t.timeout} exceeds the maximum allowed value of 30 minutes.`);await this.browser.waitForUrl(this.browser.url(),t.url,void 0,t.timeout?t.timeout*1e3:void 0);break;case"WAIT":if(t.delay>1800)throw new R("UserConfigurationError",`User requested to wait for ${t.delay} seconds, which exceeds the maximum allowed time of 30 minutes`);let u=t.delay*1e3;for(;u>0;){if(s?.())throw new $e("Wait cancelled by user");let m=Math.min(u,15e3);u-=m,this.logger.debug(`Sleeping for ${m}ms (with ${u}ms remaining after)`),await j(m)}break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0});break;case"CLICK":{let m=Xl.parse(t);if(vt(t.target)){await this.browser.clickUsingVisualCoordinates(t.target.percentXYLocation,m);break}let h=this.browser.url(),f={disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl},{elementInteractedDisplayString:S,cache:w,thoughts:b,result:T}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:C=>this.browser.click(C,ec(this.orgId),m),options:f});w&&(t.cache={target:w});let v={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:S,thoughts:b,data:T};return Fr(h,v.urlAfterCommand)&&(v.succeedImmediately=!0,v.succeedImmediatelyReason="URL changed"),v}case"DRAG":{if(vt(t.fromTarget)&&vt(t.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(t.fromTarget.percentXYLocation,t.toTarget.percentXYLocation,{force:t.force,hoverSeconds:t.hoverSeconds});break}if(vt(t.fromTarget)||vt(t.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{caches:m,elementInteractedDisplayStrings:h}=await this.wrapMultiElementTargetingCommand(e,["from target","to target"],[t.fromTarget,t.toTarget],[t.cache?.fromTarget,t.cache?.toTarget],(f,S)=>this.browser.dragAndDrop(f,S,{force:t.force,hoverSeconds:t.hoverSeconds}),{useSelector:!!t.useSelector,disableCache:o});return m&&m.every(f=>f)&&(t.cache={fromTarget:m[0],toTarget:m[1]}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:h[0]}}case"MOUSE_DRAG":{if(t.target&&!qe(t.target))throw new Error("Scroll with x/y is not supported yet");let m,h,f;if(t.target?.elementDescriptor){let{cache:b,thoughts:T,elementInteractedDisplayString:v,result:C}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:async A=>A,options:{useSelector:!!t.useSelector,iframeUrl:t.iframeUrl,disableCache:o}});m=C,h=v,f=T,b&&(t.cache={target:b})}let S=parseInt(t.deltaX),w=parseInt(t.deltaY);if(isNaN(S)||isNaN(w))throw new R("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${t.deltaX}, ${t.deltaY})`);return await this.browser.mouseDrag(S,w,t.steps,m,{force:t.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:h,thoughts:f}}case"SELECT_OPTION":{if(!qe(t.target))throw new Error("Select with x/y is not supported yet");let m=t.target.elementDescriptor,{cache:h,thoughts:f,elementInteractedDisplayString:S}=await this.wrapElementTargetingCommand({ctx:e,target:{type:"description",elementDescriptor:Ar(t,m)},cache:t.cache?.target,action:w=>this.browser.selectOption(w,t.option,t.force),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return h&&(t.cache={target:h}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:S,thoughts:f}}case"TAB":await this.browser.switchToPage(t.url,void 0,{loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0});break;case"NEW_TAB":await this.browser.createNewTab(t.url,{loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0});break;case"COOKIE":if(!t.value)break;await this.browser.setCookie(t.value);break;case"LOCAL_STORAGE":if(!t.value||!t.key)break;await this.browser.setLocalStorage(t.key,t.value);break;case"JAVASCRIPT":{let m;try{t.environment==="BROWSER"?m=await this.browser.executePageFunction(new ci(t.fragment?`return ${t.code}`:t.code),void 0):m=await ar({code:t.code,fragment:!!t.fragment,context:n,timeoutMs:t.timeout?t.timeout*1e3:void 0,logger:this.logger,localTools:this.localCodeEvalTools})}catch(h){throw new R("ActionFailureError",h instanceof Error?h.message:`${h}`,{cause:h})}try{JSON.stringify(m)}catch(h){throw new R("ActionFailureError",`Return value is not serializable: ${h instanceof Error?h.message:`${h}`}`,{cause:h})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:m}}case"TYPE":{let m=this.browser.url(),h,f,S=lg(t.target);if(S){S.elementDescriptor=Ar(t,S.elementDescriptor);let{elementInteractedDisplayString:b,cache:T,thoughts:v}=await this.wrapElementTargetingCommand({ctx:e,target:S,cache:t.cache?.target,action:C=>this.browser.typeIntoTarget(t.value,C,{force:t.force,clearContent:t.clearContent,pressKeysSequentially:t.pressKeysSequentially,pressEnter:t.pressEnter}),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});f=v,h=b,T&&(t.cache={target:T})}else await this.browser.type(t.value,{force:t.force,clearContent:t.clearContent,pressKeysSequentially:t.pressKeysSequentially,pressEnter:t.pressEnter},!0);let w={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:h,thoughts:f};return Fr(m,w.urlAfterCommand)&&(w.succeedImmediately=!0,w.succeedImmediatelyReason="URL changed"),w}case"HOVER":{if(vt(t.target)){await this.browser.hoverUsingVisualCoordinates(t.target.percentXYLocation);break}let{cache:m,thoughts:h,elementInteractedDisplayString:f}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:S=>this.browser.hover(S,!!t.force),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return m&&(t.cache={target:m}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:h}}case"FOCUS":{if(!qe(t.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:m,cache:h,thoughts:f}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:S=>this.browser.focus(S),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return h&&(t.cache={target:h}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:m,thoughts:f}}case"BLUR":{if(!qe(t.target))throw new Error("Blur with x/y is not supported yet");let{cache:m,thoughts:h,elementInteractedDisplayString:f}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:S=>this.browser.blur(S),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return m&&(t.cache={target:m}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:h}}case"PRESS":let d=this.browser.url();await this.browser.press(t.value);let p={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return Fr(d,p.urlAfterCommand)&&(p.succeedImmediately=!0,p.succeedImmediatelyReason="URL changed"),p;case"REQUEST":return sc({command:t,browser:this.browser,logger:this.logger});case"VISUAL_DIFF":return oc({ctx:e,command:t,disableCache:o,browser:this.browser,logger:this.logger,targetingWrapper:m=>this.wrapElementTargetingCommand(m)});case"FILE_UPLOAD":{let m=t.fileSource.url;if(!m.startsWith("http")&&!m.startsWith($r))throw new R("UserConfigurationError","The source URI for the file upload step must be a valid URL or a previously downloaded file beginning with 'file://'");let h=await Nl({uri:m,logger:this.logger,orgId:this.orgId});await this.browser.setFileChooserHandler(h);break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let m=await ar({code:t.storageState,fragment:!1,context:n,logger:this.logger,localTools:this.localCodeEvalTools});if(typeof m!="object")throw new R("ActionFailureError",`Credentials must evaluate to an object (received ${typeof m} instead)`);let h;try{h=mi.parse(m)}catch(f){throw new R("ActionFailureError",`Credentials provided do not follow the required format: ${f}`)}await this.browser.loadAuthState(h);break}case"ELEMENT_CHECK":{if(t.target&&!qe(t.target))throw new Error("Element assertion with x/y is not supported yet");let m=Date.now(),h=(t.timeout??Rt)*1e3,f=0,S;for(;f<2||Date.now()-m<h;){f++;try{let{cache:w,thoughts:b,elementInteractedDisplayString:T}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:async v=>{await tc({assertion:t.assertion,element:v,callbacks:{highlightTarget:async C=>this.browser.highlightTarget(C)}})},options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return w&&(t.cache={target:w}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:T,thoughts:b}}catch(w){S=w}}throw new R("AssertionFailureError",`Element check still failing after ${Math.floor((Date.now()-m)/1e3)} seconds: ${S?S.message:""}`)}case"PAGE_CHECK":{await rc({assertion:t.assertion,page:this.browser.getActivePage(),logger:this.logger,timeout:t.timeout});break}default:return(m=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(t)}return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}async getReverseMappedTarget(e,t,n){return(await this.generator.getReverseMappedDescription({browserState:e.browserState,goal:`${t}`},{disableCache:n,orgId:this.orgId})).phrase}async stopRecordMode(){this.recordAbortController?.abort(),await this.browser.clearAllCdpHighlights()}async startRecordMode(e){this.recordAbortController=new AbortController;let t=new jn({signal:this.recordAbortController.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,t),t}};var dg=2,ug=2250;async function ic({socket:r,logger:e,storage:t,devicePixelRatio:n,generator:o,browserbase:s,getCpuUsage:i,authorization:a}){let l=r.id,c=i?.();if(c&&c>ug)throw e.error({cpuUsage:c,event:"connect",args:r.handshake.query,sessionId:l},"Socket connection resource rate limit triggered"),new Error("You have reached a Momentic server under heavy load. Please refresh the page to establish a new connection. Automatic scale-up processes can take up to 3 minutes.");let u=r.handshake.query.testId,d=r.handshake.query.baseUrl,p=r.handshake.query.envName,g=r.handshake.query.viewport?JSON.parse(decodeURIComponent(r.handshake.query.viewport)):void 0,m=r.handshake.query.testMetadata?me.parse(JSON.parse(decodeURIComponent(r.handshake.query.testMetadata))):void 0;if(!u||!d)throw new Error("Socket connection request is missing testId or baseUrl");let h=await t.getOrgId(u),f=r.handshake.query.environmentVariables?JSON.parse(decodeURIComponent(r.handshake.query.environmentVariables)):{},S=r.handshake.headers["x-forwarded-for"]?.split(",")[0],w=e.child({testId:u,baseUrl:d,orgId:h,sessionId:l});if(w.info({clientIp:S,event:"connect",args:r.handshake.query,sessionId:l},"Websocket event (connect)"),S&&N.getCurrentConnectionsByIp(S)>=dg)throw e.error({clientIp:S,sessions:N.getCurrentSessionsByIp(),...r.handshake.query},"Socket connection browser creation rate limit triggered"),new Error("You have exceeded the maximum number of connections allowed per client. Momentic limits the number of simultaneously open tabs to uphold browser reliability. Please close another tab and retry or contact Momentic Support if you believe this is in error.");N.reserveCapacityByIp(S);let b;a?.type==="API_KEY"&&(b=new rt(a));try{await mg({socket:r,baseUrl:d,envName:p,viewport:g,testMetadata:m,orgId:h,sessionId:l,logger:w,environmentVariables:f,clientIp:S,devicePixelRatio:n,storage:t,localCodeEvalTools:b,generator:o,browserbase:s})}catch(T){throw w.debug({err:T},"Error setting up socket session"),N.releaseCapacityByIp(S),T}return{sessionId:l,testId:u,orgId:h}}async function mg({socket:r,baseUrl:e,viewport:t,envName:n,devicePixelRatio:o,testMetadata:s,orgId:i,sessionId:a,logger:l,storage:c,localCodeEvalTools:u,generator:d,environmentVariables:p,clientIp:g}){let m={};t&&(m.viewport=t),o&&(m.deviceScaleFactor=o);let h=Er.parse(s?.advanced??{}),[f,S]=await Promise.all([Ge.init({baseUrl:e,userBrowserSettings:h,waitForLoad:!0,enricher:new Gn(l),timeout:h.pageLoadTimeoutMs,storage:c,logger:l,contextArgs:m,onTabsChange:(C,A)=>{r.emit("tabs",{tabs:C,activeTab:A})}}),ur.init(i)]),w=new pr({browser:f,generator:d,config:Wr,logger:l,flagStore:S,orgId:i,storage:c,localCodeEvalTools:u}),b=Ua(r,a,l),T=async()=>{clearInterval(b.timer)},v=new ge({baseUrl:e,currentUrl:w.browser.url(),variablesFromEnvironment:p,envName:n});if(!r.connected)throw await f.cleanup(),new Error("Socket not connected anymore, not proceeding with session setup");r.emit("session",{url:e,userAgent:Ge.USER_AGENT,viewport:await w.browser.getViewport(),sessionId:a}),N.registerSession({controller:w,context:v,sessionId:a,cleanup:T,clientIp:g})}var ac=[Ba,el,tl,Vl,za,ql,Kl,nl,il,al,ol,rl,ll,sl];var lc=r=>{let{logger:e}=r,t=new pg(r.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:3e4,pingInterval:6e4,maxHttpBufferSize:1e7});return t.on("connection",async n=>{let o;try{o=await ic({...r,socket:n})}catch(s){e.error({event:"connection",type:"websocket",err:s},"Failed to setup connection"),n.emit("error",{message:s instanceof Error?s.message:`${s}`}),n.disconnect(!0);return}ac.forEach(s=>gg(s,{socket:n,metadata:o,...r}))}),t};var gg=(r,e)=>{let t=r.createHandler(e),n=(...o)=>{["cloudMouseMove","cloudScroll","cloudType"].includes(r.event)||e.logger.debug({...e.metadata,event:r.event,args:o},`Websocket event (${r.event})`);let s=i=>{e.logger.error({event:r.event,type:"websocket",args:o,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=t.apply(void 0,o);i&&typeof i.catch=="function"&&i.catch(s)}catch(i){s(i)}};e.socket.on(r.event,n)};import{z as yg}from"zod";import hg from"fetch-retry";var fg=hg(global.fetch),ae=class{static API_VERSION="v1";baseURL;apiKey;constructor(e){this.baseURL=e.baseURL,this.apiKey=e.apiKey}async sendRequest(e,t){let n=await fg(`${this.baseURL}${e}`,{retries:1,retryDelay:1e3,method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});if(!n.ok)throw new Error(`Request to ${e} failed with status ${n.status}: ${await n.text()}`);return n.json()}};var $t=class extends ae{constructor(e){super(e)}async getRecommendedChunks(e){let t=await this.sendRequest(`/${ae.API_VERSION}/web-agent/recommend-chunks`,e);return Yi.parse(t)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${ae.API_VERSION}/s3/visual-diff-screenshot`,{url:e});return yg.string().parse(t)}async getElementLocation(e,t){let n=await this.sendRequest(`/${ae.API_VERSION}/web-agent/locate-element`,{...e,disableCache:t.disableCache});return Ni.parse(n)}async getAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache},o=await this.sendRequest(`/${ae.API_VERSION}/web-agent/assertion`,n);return Mi.parse(o)}async getProposedCommand(e,t){let n=await this.sendRequest(`/${ae.API_VERSION}/web-agent/next-command`,{url:e.url,browserState:e.browserState,goal:e.goal,history:e.history,numPrevious:e.numPrevious,lastCommand:e.lastCommand,screenshot:e.screenshot,disableCache:t.disableCache});return Oi.parse(n)}async getGranularGoals(e,t){let n=await this.sendRequest(`/${ae.API_VERSION}/web-agent/split-goal`,{url:e.url,goal:e.goal,disableCache:t.disableCache});return _i.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${ae.API_VERSION}/web-agent/reverse-mapped-description`,{goal:e.goal,browserState:e.browserState,disableCache:t.disableCache});return ki.parse(n)}async getTextExtraction(e,t){let n={goal:e.goal,browserState:e.browserState,returnSchema:e.returnSchema,disableCache:!!t.disableCache},o=await this.sendRequest(`/${ae.API_VERSION}/web-agent/text-extraction`,n);return vo.parse(o)}async getTestResultClassification(e){let t=await this.sendRequest(`/${ae.API_VERSION}/web-agent/result-classification`,e);return Eo.parse(t)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${ae.API_VERSION}/web-agent/extract-keywords`,{goal:e,disableCache:t.disableCache});return Zi.parse(n)}};import{Router as Sg}from"express";function Ee(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var cc=Sg();cc.get("/",Ee((r,e)=>{let t=Da();e.status(200).json(t)}));var dc=cc;import{Router as Tg}from"express";import uc,{multistream as wg}from"pino";import bg from"pino-pretty";var hs=new Map,Cg=!0,fs=class r{consoleLogger;ddClientToken;hostname;bindingAttributes;excludeAttributesInConsoleLogs;excludeTimestamps;disableConsoleLogs;site="https://http-intake.logs.us5.datadoghq.com/api/v2/logs";constructor({bindings:e,clientToken:t,hostname:n,excludeAttributesInConsoleLogs:o,excludeTimestamps:s,disableConsoleLogs:i}){this.ddClientToken=t,this.hostname=n,this.excludeAttributesInConsoleLogs=o,this.excludeTimestamps=s,this.disableConsoleLogs=i,this.bindingAttributes={...e,env:"production"};let a={base:o?{}:this.bindingAttributes,errorKey:"err",level:"debug",timestamp:!s};this.consoleLogger=Cg?uc(a):uc(a,wg([{stream:bg({colorize:!0})}]))}child(e){return new r({clientToken:this.ddClientToken,bindings:{...this.bindingAttributes,...e},hostname:this.hostname,excludeAttributesInConsoleLogs:this.excludeAttributesInConsoleLogs,disableConsoleLogs:this.disableConsoleLogs})}flush(e){this.disableConsoleLogs||this.consoleLogger.flush(e)}log(e,t,n,...o){if(t&&n===void 0&&(n=`${t}`,t={}),this.disableConsoleLogs||this.consoleLogger[e](e==="error"?t:{testId:t.testId,runId:t.runId},n,...o),typeof t=="object"&&t&&"err"in t&&t.err instanceof Error){let i={};for(let a of Object.getOwnPropertyNames(t.err))i[a]=t.err[a];i.name=t.err.name,t.err=i}let s=Object.assign({},this.bindingAttributes,t&&typeof t=="object"?t:{});o.length>0&&(s.args=o),(async()=>{try{let i=await fetch(this.site,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json","DD-API-KEY":this.ddClientToken},body:JSON.stringify([{ddsource:this.bindingAttributes.app,hostname:this.hostname??"vercel",service:"momentic",message:{message:n||"",...s,level:e}}])});if(!i.ok)throw new Error(`Failed to log to Datadog: ${i.statusText})}`)}catch(i){this.disableConsoleLogs||this.consoleLogger.warn({obj:t,msg:n,args:o,err:i},"Failed to log to Datadog")}})()}debug(e,t,...n){this.log("debug",e,t,...n)}info(e,t,...n){this.log("info",e,t,...n)}warn(e,t,...n){this.log("warn",e,t,...n)}error(e,t,...n){this.log("error",e,t,...n)}bindings(){return this.bindingAttributes}setMinLevel(e){this.consoleLogger.level=e}enableConsoleLogs(){this.disableConsoleLogs=!1}},Xn=({app:r,clientToken:e,hostname:t,excludeAttributesInConsoleLogs:n,excludeTimestamps:o,disableConsoleLogs:s})=>{if(!process.env.DD_CLIENT_TOKEN&&!process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN&&!e)throw new Error("Missing DD_CLIENT_TOKEN");return hs.has(r)||hs.set(r,new fs({bindings:{app:r},hostname:t,clientToken:e||process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN||process.env.DD_CLIENT_TOKEN,excludeAttributesInConsoleLogs:n,excludeTimestamps:o,disableConsoleLogs:s})),hs.get(r)};import{hostname as Eg}from"os";var Te=Xn({app:"desktop-server",clientToken:"pubcfd7516a5c0ba852b42675cd97bee027",hostname:Eg(),excludeAttributesInConsoleLogs:!0,excludeTimestamps:!0,disableConsoleLogs:!0});var Vr=Tg();Vr.get("/",Ee(async(r,e)=>{let t=await La(Te);e.status(200).json(t)}));Vr.get("/metadata",Ee((r,e)=>{let t=Ia();e.status(200).json(t)}));Vr.post("/",Ee(async(r,e)=>{let t;try{t=Ai.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}try{Tr(t.name)}catch(o){e.status(400).json({error:`Invalid module name: ${o}`});return}let n=await xa(t.name,t.steps);e.status(201).json(n)}));Vr.get("/:moduleId",Ee(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await Pa(r.params.moduleId,Te);if(!t){e.status(404).json({error:"Module not found."});return}e.json(t)}));var mc=Vr;import{Router as vg}from"express";import{existsSync as Rg}from"fs";import{join as Qn}from"path";import{v4 as Ag}from"uuid";var Ss="https://api.momentic.ai",pc=r=>{Ss=r},Kr=()=>Ss,gr,ys,gc=async r=>{if(gr)return gr;let e=new ie({baseUrl:Ss,apiKey:r});try{return gr=await e.getOrgId(),ys=r,gr}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Jn=()=>{if(!gr)throw new Error("Your organization ID appears invalid. Please contact Momentic Support.");return gr},hc=()=>{if(!ys)throw new Error("Your API key appears invalid. Please contact Momentic Support.");return ys};var Ht=vg();Ht.get("/",Ee((r,e)=>{let t=Mr(ne,Te);e.status(200).json(t)}));Ht.post("/",Ee(async(r,e)=>{let t;try{t=Ri.parse(r.body)}catch(a){e.status(400).json({error:`Invalid request body: ${a}`});return}try{Tr(t.name)}catch(a){e.status(400).json({error:a.message});return}let o={id:Ag(),name:t.name,baseUrl:t.baseUrl,schemaVersion:be,advanced:{disableAICaching:!1,viewport:t.viewport??Xe},retries:0,steps:[]};t.environment&&(o.envs=[{name:t.environment,default:!0}]);let s=await Na(o,t.name),i={...o,testPath:s};e.status(201).json(i)}));Ht.get("/:testPath",Ee(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t=Qn(ne,r.params.testPath);if(!Rg(t)){e.status(400).json({error:`Test not found at path: ${t}`});return}let n=await Nn(t,wt,Te);e.status(200).json(n)}));Ht.patch("/:testPath/metadata",Ee(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=vi.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}let n=Qn(ne,r.params.testPath);Mn(t,n),e.status(201).json({message:"ok"})}));Ht.patch("/:testPath",Ee(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=Ti.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}let n=Qn(ne,r.params.testPath),o;try{o=_a(n)}catch(c){e.status(400).json({error:`Existing test file on disk is invalid: ${c}`});return}let{stepsToSave:s,moduleUpdates:i,cachesToSave:a}=await He({steps:t.steps,cacheCreationParams:{testId:o.id,orgId:Jn()}});i.forEach(c=>Aa({...c,schemaVersion:be})),Mn({schemaVersion:be,steps:s},n),await new ie({apiKey:hc(),baseUrl:Kr()}).updateStepCaches({entries:a,testId:o.id}),e.status(201).json({message:"ok"})}));Ht.patch("/:testPath/environments",Ee(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=xi.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}let n=Qn(ne,r.params.testPath);Mn({envs:t.defaultEnv?[{name:t.defaultEnv,default:!0}]:[]},n),e.status(201).json({message:"ok"})}));var fc=Ht;async function yc(r){let{momenticServerUrl:e,apiKey:t,serverPort:n,appPort:o,staticDir:s,devicePixelRatio:i}=r;if(!Lg(ne)||!Pg(ne).isDirectory()){let f=Ng.isAbsolute(ne);throw new Error(`Root folder ${ne} does not exist${f?"":` in the current directory ("${process.cwd()}")`}. Please run \`npx momentic init\` if you wish to setup Momentic here for the first time.`)}e&&pc(e),Te.debug(r,"Initializing desktop server");let a=await gc(t);Te.debug({orgId:a},"Checking API key successful");let c=`http://localhost:${n}`;o&&(c=`http://localhost:${o}`);let u=_g(s);await new Promise(f=>{u.listen(n,()=>{Te.info(`Server is running at http://localhost:${n}`),f()})});let p=new $t({baseURL:Kr(),apiKey:t}),g={type:"API_KEY",baseUrl:Kr(),apiKey:t},m=new ie(g),h=new ir(m,Jn());lc({baseServer:u,generator:p,storage:h,logger:Te,devicePixelRatio:i,authorization:g}),await Mg(c)}function _g(r){let e=ws();e.use(Ig()),e.use(xg.json({limit:"25mb"}));let t=ws.Router();if(t.use("/tests",fc),t.use("/modules",mc),t.use("/environments",dc),e.use("/api",t),e.use((o,s,i)=>{o.path!=="/healthcheck"&&Te.debug({url:o.url,path:o.path,query:o.query,method:o.method,body:o.body,headers:o.rawHeaders,client:o.ip},"Received desktop-server request"),s.on("close",()=>{s.statusCode>=400&&Te.error({url:o.url,method:o.method,statusCode:s.statusCode},"Request completed in error")}),i()}),e.use((o,s,i,a)=>{o instanceof Error&&o.message.includes("BadRequestError: request aborted")||(Te.error({stack:o.stack,msg:o.message,url:s.url,method:s.method},"Unhandled exception leading to 500 on desktop-server"),i.status(500).send("Internal Server Error"),a(o))}),r){let o=ws.static(r);e.use("/",o),e.use("*",o)}return Og.createServer(e)}import{existsSync as Mh}from"fs";import ed,{dirname as Nh,join as _h}from"path";import{chdir as kh}from"process";import{fileURLToPath as Dh}from"url";var Sc="0.0.126";import qr from"chalk";var Wt=(...r)=>{ee(qr.blue(...r))};var je=(...r)=>{ee(qr.dim(...r))};var Se=(...r)=>{ee(qr.green(...r))},ee=(...r)=>{console.log(...r)},le=(...r)=>{console.error(qr.yellow(...r))},P=(...r)=>{console.error(qr.red(...r))};import{hostname as Dg}from"os";var I=Xn({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:Dg(),excludeAttributesInConsoleLogs:!0,excludeTimestamps:!0,disableConsoleLogs:!0});import{execSync as Fg}from"child_process";import{platform as Ug}from"os";function bs(){return wc()?(Wt("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),Wt("If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations."),Wt("Confirm your device's pixel-ratio at https://www.mydevice.io."),2):(Wt("Setting device pixel ratio to 1."),Wt("If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations"),Wt("Confirm your device's pixel-ratio at https://www.mydevice.io."),1)}function wc(){return Ug()==="darwin"&&Fg("system_profiler SPDisplaysDataType").toString().includes("Retina")}function Cs(r){wc()&&r===1&&(le("If you are using Momentic on a Retina screen, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations."),le("Confirm your device's pixel-ratio at https://www.mydevice.io."))}import{createHash as Rc}from"crypto";import{existsSync as Ac,readFileSync as xs,writeFileSync as xc}from"fs";import{join as Ic}from"path";import{parse as eh}from"yaml";import{existsSync as vs,mkdirSync as Cc,readdirSync as qg,statSync as Ec}from"fs";import{homedir as Tc}from"os";import{join as st,resolve as Yg}from"path";import{existsSync as zg,statSync as Bg}from"fs";var Zn=!!process.env.CI||!process.stdout.isTTY;function Ct(r){try{return zg(r)&&Bg(r).isDirectory()}catch(e){return P({err:e},`Error reading path ${r} during directory existence check`),!1}}import{registry as Es}from"playwright-core/lib/server";function $g(r){let e=[],t=[];for(let n of r){let o=Es.findExecutable(n);!o||o.installType==="none"?e.push(n):t.push(o)}return t}async function eo(){let r=$g(["chromium"]);await Es.installDeps(r,!1),await Es.install(r,!1)}import{statSync as Hg}from"fs";import{existsSync as Wg,mkdirSync as Gg}from"fs";import{dirname as jg}from"path";import Vg from"readline/promises";var Ts=!1,Kg=(()=>{try{return Hg("/.dockerenv"),!0}catch{return!1}})();async function ze(r,e){if(Zn||Ts||Kg)return!0;I.flush(),await new Promise(i=>setTimeout(i,500));let t=Vg.createInterface({input:process.stdin,output:process.stdout}),n=r.split("."),o;if(n.length===1)o=r;else{let i=`${n.slice(0,n.length-1).join(". ").trim()}.`;e?le(i):ee(i),o=n[n.length-1].trim()}let s=await t.question(`${o} ('y' for yes / n for no / 'A' to accept all) `);return t.close(),s==="A"?(Ts=!0,setTimeout(()=>{Ts=!1},3e3),!0):s.toLowerCase()==="y"}async function Yr(r){let e=jg(r);return Ct(e)?Wg(r)?ze(`File '${bc(r)}' already exists. Overwrite existing content?`,!0):!0:await ze(`Directory '${bc(e)}' doesn't exist. Create it now?`,!0)?(Gg(e,{recursive:!0}),!0):!1}function bc(r){return r.replace(/(\s+)/g,"\\$1")}var Xg=[ft,Sn,Qt],it=Zg(),Gt=st(it,ft),As=st(it,Sn),at=st(it,Qt),Rs=st(Tc(),"momentic",No),vc=[Gt,As,at];async function lt(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<20)&&(P(`Node.js version 20 or higher is required to run the Momentic CLI. Detected: ${process.versions.node}.`),process.exit(1));let n=await r.client.getOrgId();return await eo(),await Qg(r),n}async function Jg(r){Ct(it)||!r&&!await ze(`The root '${ht}' folder was not found in the current directory. You will need to invoke the Momentic CLI from this directory in the future. Proceed?`)&&(P("Setup cancelled."),process.exit(1)),Ct(Rs)||(!r&&!await ze("The Chrome cache folder was not found in your home directory. Proceed with creation?")&&(P("Setup cancelled."),process.exit(1)),Cc(Rs,{recursive:!0}));for(let e of vc)Ct(e)||(!r&&!await ze(`'${e}' folder was not found in the current directory. Create it now?`)&&(P("Setup cancelled."),process.exit(1)),Cc(e,{recursive:!0}))}function Xr(r,e,t=new Set){for(let n of r){let o=Yg(n),s=!1;try{s=vs(o)&&Ec(o).isDirectory()}catch(i){I.error({err:i},`Error reading path ${o} during collect paths`)}if(o&&s){let i=qg(o).map(a=>st(o,a));Xr(i,e,t);continue}if(o.endsWith(".yaml")){try{if(!vs(o)||!Ec(o).isFile()){I.error(`File not found or unreadable: ${o}`);continue}}catch(i){I.error({err:i},`Error reading file ${o} during collect paths`);continue}if(!e(o))continue;t.add(o)}}return t}async function Qg({client:r,createFolders:e,skipPrompts:t,pullEnvs:n}){if(Tc()||(P("Your home directory could not be found. Please ensure the HOME environment variable is set for POSIX systems, and the USERPROFILE environment variable is set for Windows systems."),process.exit(1)),e)await Jg(t);else for(let o of[it,Rs,...vc])!Ct(o)&&!Zn&&(P(`The '${o}' folder is required to run the Momentic CLI but was not found in the current directory. Please run 'npx momentic@latest init' to create the required folders.`),P(`The current working directory is: ${process.cwd()}`),process.exit(1));n&&(!t&&!await ze("Pull environments from Momentic Cloud? Environment definitions may be required to run tests locally.")&&(P("Setup cancelled."),process.exit(1)),await to({client:r,all:!0,skipPrompts:t}))}function Zg(){let r=n=>vs(st(n,ht))&&Xg.some(o=>Ct(st(n,ht,o))),e=process.cwd();for(;e!=="/"&&!r(e);)e=st(e,"..");let t;return r(e)?t=e:t=process.cwd(),t!==process.cwd()?le(`Current working directory does not contain a ${ht} folder, treating ${t} as the Momentic root folder instead`):I.info(`Identified ${t} as the Momentic root folder`),st(t,ht)}async function to({envNames:r,client:e,all:t,skipPrompts:n}){let o=await e.getAllEnvironments();r&&!t&&(o=o.filter(a=>r?.includes(a.name))),Ac(at)||(P(`${at} does not exist in the current directory. Please run 'npx momentic@latest init' first.`),process.exit(1));let s=[],i=[];for(let a of o){let l=Ic(at,`${a.name}.yaml`);if(!n&&!await Yr(l))return;if(!Ac(l))xc(l,$o(a)),s.push(l);else{let c=Rc("sha256").update(xs(l)).digest("hex"),u=$o(a),d=Rc("sha256").update(u).digest("hex");c!==d&&(xc(l,u),i.push(l))}}Se("Pulled environments successfully!"),s.length&&(Se("Created:"),s.forEach(a=>Se(" ",a))),i.length&&(Se("Updated:"),i.forEach(a=>Se(" ",a)))}function th(r){return r.endsWith(".yaml")?xs(r,"utf8").includes("momentic/environment")?!0:(le(`Skipping YAML that is not a Momentic environment: ${r}`),!1):!1}async function Lc({client:r,names:e,all:t,yes:n}){let o;t?o=[at]:o=e.map(a=>Ic(at,`${a.toLowerCase()}.yaml`));let s=Xr(o,th);ee(`Found ${s.size} environments to push:`),s.forEach(a=>ee(" ",a));let i=[];for(let a of s){let l=eh(xs(a,"utf-8"));try{let c=Ae.parse(l);i.push(c)}catch(c){P(`${a} failed to parse as a valid environment file.`),P(c),process.exit(1)}}!n&&!await ze("Pushing environments can overwrite variables on cloud and instantly affect scheduled runs. Continue?",!0)||(await r.updateEnvironments(i),Se("Pushed environments successfully!"))}import{Argument as Jr,Option as _e}from"commander";import{validateHeaderValue as rh}from"http";import{cpus as Pc}from"os";import{z as nh}from"zod";var ct=new _e("--api-key <key>","API key for authentication. If not supplied, attempts to read the MOMENTIC_API_KEY env var.").env("MOMENTIC_API_KEY").makeOptionMandatory(!0),dt=new _e("--server <server>","Momentic server to use. Leave unchanged unless using Momentic on-premise.").default("https://api.momentic.ai"),ut=new _e("-y, --yes","Skip all confirmation prompts.").env("CI"),Is=new _e("-w, --wait","Wait for tests to finish running before exiting. Only applicable when running tests remotely").implies({remote:!0}),Ls=new _e("--wait-timeout-seconds <waitTimeoutSeconds>","The maximum number of seconds to wait for tests to complete. Only applicable when the --wait option is specified.").argParser(r=>parseInt(r,10)),Ps=new _e("--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.");function Os(r){if(r===void 0)return;let e={};for(let t of r){let n=t.indexOf("=");if(n===-1)throw new Error(`Header value pair does not contain '=': ${t}`);let o=t.slice(0,n),s=t.slice(n+1);rh(o,s),e[o]=s}return e}var Ms=new _e("--no-report","Skip reporting test results to Momentic Cloud when running with the --local flag.").implies({local:!0}),Ns=new _e("--pixel-ratio <number>","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(r=>parseInt(r,10)),_s=new _e("--env <env>","Name of the environment to use when running tests."),ks=new _e("--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."),Ds=new _e("-a, --all","Select all tests in your organization from Momentic Cloud. Cannot be used together with <tests> arguments."),Fs=new _e("-a, --all","Select all environments in your organization from Momentic Cloud. Cannot be used together with <paths> arguments."),Oc=new Jr("<tests...>",`One or more test paths to pull from Momentic Cloud.
|
|
1613
1655
|
|
|
1614
|
-
A test path is a lowercased version of your test name where spaces are replaced with dashes: 'npx momentic pull hello-world'.`).argOptional(),
|
|
1656
|
+
A test path is a lowercased version of your test name where spaces are replaced with dashes: 'npx momentic pull hello-world'.`).argOptional(),Mc=new Jr("<tests...>",`One or more test identifiers.
|
|
1615
1657
|
|
|
1616
1658
|
To use tests stored on your local file system, pass '--local' and specify file paths to Momentic YAML files or folders that exist locally: 'npx momentic run --local momentic/hello-world.yaml'.
|
|
1617
1659
|
|
|
1618
|
-
To use tests stored remotely on Momentic Cloud, pass '--remote' and specify one or more test paths. A test path is a lowercased version of your test name where spaces are replaced with dashes: 'npx momentic run --remote hello-world'.`).argOptional(),
|
|
1660
|
+
To use tests stored remotely on Momentic Cloud, pass '--remote' and specify one or more test paths. A test path is a lowercased version of your test name where spaces are replaced with dashes: 'npx momentic run --remote hello-world'.`).argOptional(),Nc=new Jr("<suites...>",`One or more suite paths that exist on Momentic Cloud.
|
|
1619
1661
|
|
|
1620
|
-
The suite path is a lowercased version of your suite name where spaces and special characters are replaced with dashes, such as 'production-tests'.`),
|
|
1662
|
+
The suite path is a lowercased version of your suite name where spaces and special characters are replaced with dashes, such as 'production-tests'.`),_c=new Jr("<paths...>","File paths pointing to one or more Momentic YAML files. Paths to directories are supported as well."),Us=new Jr("<envs...>","One or more environment names to push").argOptional(),kc=r=>{for(let[e,t]of Object.entries(r))switch(e){case"urlOverride":if(t===void 0)break;try{nh.string().url().parse(t)}catch(n){throw new Error(`Invalid URL provided for ${e}`,{cause:n})}break;case"server":if(typeof t!="string")throw new Error(`Expected a string for ${e}`);if(!t.startsWith("http"))throw new Error("--server option must be a fully qualified URL beginning with http");break;case"parallel":if(typeof t!="number"||isNaN(t))throw new Error(`Expected a number for ${e}`);Pc().length<t*2&&le(`You requested to run ${t} tests in parallel on a machine with ${Pc().length} cores. This may cause performance issues and test failures as Chrome requires at least 2 cores per browser instance.`);break;case"waitTimeoutSeconds":if(typeof t!="number"||isNaN(t))throw new Error(`Expected a number for ${e}`);break;default:break}};import{createHash as Dc}from"crypto";import{writeFileSync as Fc}from"fs";import{join as Uc}from"path";async function Bc({testsToFetch:r,client:e,all:t,yes:n}){let{tests:o,modules:s}=await e.getTestYAMLExport({paths:r,all:t}),i=0;for(let[l,c]of Object.entries(o)){let u=Uc(it,zc(l));!n&&!await Yr(u)||(i+=1,Fc(u,c,"utf-8"),I.info({checksum:Dc("md5").update(c).digest("hex")},`Wrote '${u}'`))}let a=0;for(let[l,c]of Object.entries(s)){let u=Uc(Gt,zc(l));!n&&!await Yr(u)||(a+=1,Fc(u,c,"utf-8"),I.info({checksum:Dc("md5").update(c).digest("hex")},`Wrote '${u}'`))}i===0?Se("Pulled 0 tests."):Se(`Pulled ${i} test${i>1?"s":""}${a?` and ${a} module${a>1?"s":""}`:""}!`)}function zc(r){return`${pe(r)}.yaml`}import{readFileSync as sh}from"fs";async function $c(r){let e=Xr(r.paths,ih);ee(`Found ${e.size} tests to push:`),e.forEach(s=>ee(" ",s));let t=Array.from(e).map(s=>Vo(s,Gt)),n=new Set(t.flatMap(s=>Object.keys(s.modules)));e.size===0&&n.size===0&&(P("Found no valid tests or modules to push."),process.exit(1));let o="Pushing tests overwrites tests on production and will instantly affect scheduled runs. Continue?";!r.yes&&!await ze(o,!0)&&(P("Push cancelled."),process.exit(1)),await r.client.updateTestWithYAML(t),Se("Pushed tests successfully!")}function ih(r){return r.endsWith(".yaml")?sh(r,"utf8").includes("momentic/test")?!0:(I.warn(`Skipping YAML that is not a Momentic test: ${r}`),!1):(I.warn(`Skipping file that does not have YAML extension: ${r}`),!1)}import jc from"log-update";import Gc from"chalk";import{Console as Hc}from"console";import{format as Qr}from"util";var zs=class extends Error{constructor(e,t,n){let o=Error.stackTraceLimit;n&&(Error.stackTraceLimit=Math.max(n,o||10)),super(e),Error.captureStackTrace&&Error.captureStackTrace(this,t),Error.stackTraceLimit=o}},ro=class r extends Hc{_buffer=[];_groupDepth=0;Console=Hc;constructor(){super({write:e=>(r.write(this._buffer,"log",e),!0)})}static write(e,t,n,o=2){let s=new zs(void 0,r.write).stack;if(!s)return e;let i=s.split(`
|
|
1621
1663
|
`).slice(o).filter(Boolean).join(`
|
|
1622
|
-
`);return e.push({message:n,origin:i,type:t}),e}_log(e,t){r.write(this._buffer,e," ".repeat(this._groupDepth)+t,3)}debug(e,...t){this._log("debug",
|
|
1664
|
+
`);return e.push({message:n,origin:i,type:t}),e}_log(e,t){r.write(this._buffer,e," ".repeat(this._groupDepth)+t,3)}debug(e,...t){this._log("debug",Qr(e,...t))}error(e,...t){this._log("error",Qr(e,...t))}info(e,...t){this._log("info",Qr(e,...t))}log(e,...t){this._log("log",Qr(e,...t))}warn(e,...t){this._log("warn",Qr(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function Wc(r){let e=globalThis.console,t=new ro;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(s=>s.message).join(`
|
|
1623
1665
|
`);process.stderr.write(`${o}
|
|
1624
|
-
`),globalThis.console=e}}var
|
|
1625
|
-
`))}catch(o){throw new Error(`Fixture at path ${e} does not parse as valid YAML.`,{cause:o})}let n;try{n=
|
|
1626
|
-
`),await
|
|
1666
|
+
`),globalThis.console=e}}var ah=30*60*1e3;async function no({getResults:r,checkDone:e,name:t,timeoutMs:n=ah}){let o=Date.now(),s=0;for(;Date.now()-o<n;){let i;s>3&&(P(`Failed to fetch ${t} status too many times.`),process.exit(1));try{i=await r(),s=0}catch(c){s++,I.warn({err:c},"Failed to fetch run status"),await new Promise(u=>setTimeout(u,5e3));continue}if(e(i))return i;let l=Math.max(1e4,Math.floor(n/100));await new Promise(c=>setTimeout(c,l))}P(`Timeout elapsed waiting for ${t} to complete (${Math.floor(n/1e3)}s).`),process.exit(1)}function hr({results:r,startTime:e,entity:t,getDisplayLine:n,onFailed:o}){let s=r.filter(l=>l.status==="PASSED"),i=r.filter(l=>l.status==="FAILED"),a=r.filter(l=>l.status==="CANCELLED");Wc(()=>{i.forEach(l=>{ee(""),o(l)}),i.length&&(ee(""),P(`${i.length} ${t}s failed:`),i.forEach(l=>{P(n(l))})),a.length&&(ee(""),le(`${a.length} ${t}s cancelled:`),a.forEach(l=>{le(n(l))})),s.length&&(ee(""),Se(`${s.length} ${t}s passed:`),s.forEach(l=>{Se(n(l))})),ee(""),je(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),i.length>0?process.exit(1):process.exit(0)}var oo=(r,e)=>{if(!r.failureDetails||!r.failureReason)return;let t=Ks[r.failureDetails?.classification?.reason||r.failureReason],n=r.failureDetails?.classification?.summary||qs[r.failureReason];P(e),ee(` Reason: ${Gc.red(t)}`),ee(` Description: ${Gc.red(n)}`)};async function Vc({client:r,suitePaths:e,wait:t,waitTimeoutSeconds:n,...o}){let s=(await r.queueSuiteRuns({paths:e,...o})).suiteRunIds;je(`Queued ${e.length} suites.`),t||process.exit(0);let i=Date.now();je(`Waiting for ${e.length} suites to complete.`);let a=new Set,l=await no({name:"suites",getResults:async()=>r.bulkGetSuiteStatus(s),timeoutMs:n?n*1e3:void 0,checkDone:d=>(d.forEach(p=>{if(p.status==="RUNNING"&&!a.has(p.id)){a.add(p.id);let g=p.suite.name;g&&jc(`${a.size}/${s.length} ${pe(g)}`)}}),d.every(p=>p.runs.every(m=>m.status==="FAILED"&&m.failureReason||m.status==="PASSED"||m.status==="CANCELLED")&&(p.status==="FAILED"||p.status==="PASSED"||p.status==="CANCELLED")))});jc.clear();let c=r.getAppUrl();hr({results:l,startTime:i,onFailed:d=>{let p=d.suite.name?pe(d.suite.name):"Unknown suite",g=d.runs.filter(h=>h.status==="FAILED").length,m=d.runs.length;P(`${p} (${g}/${m} tests failed):`);for(let h of d.runs)if(h.status==="FAILED"){let f=h.testName||h.test?.name;P(` ${f?pe(f):"Unknown test"} (${c}/runs/${h.id})`)}},entity:"suite",getDisplayLine:d=>` ${d.suite.name?pe(d.suite.name):"Unknown suite"} (${c}/results/suite-runs/${d.id})`})}import{existsSync as Yc,statSync as Ih}from"fs";import Xc from"log-update";import Lh from"wait-on";import lh from"@actions/exec";import ch from"@actions/io";import dh from"quote";import uh from"string-argv";async function Kc(r,e=!0){let t=uh(r),n=await ch.which(t[0],!0),o=t.slice(1),s=lh.exec(dh(n),o,{delay:100});if(e)return s}import{diff as yh}from"deep-object-diff";import{readFileSync as Sh}from"fs";import{cloneDeep as wh}from"lodash-es";import{join as bh}from"path";import Ch from"semver";import{debounce as Eh}from"ts-debounce";import{v4 as Th}from"uuid";var so=class extends ae{async runTemplateMatching(e){let t=await this.sendRequest(`/${ae.API_VERSION}/web-agent/template-matching`,e);return fn.parse(t)}};import{parse as vh}from"yaml";import{existsSync as mh,readFileSync as ph}from"fs";import{join as gh}from"path";import{parse as hh}from"yaml";function fh(r){let e=gh(As,`${r}.yaml`);if(!mh(e))throw new Error(`Fixture '${r}' does not exist at expected path ${e}.`);let t;try{t=hh(ph(e,"utf-8").replace(/\r\n|\r/g,`
|
|
1667
|
+
`))}catch(o){throw new Error(`Fixture at path ${e} does not parse as valid YAML.`,{cause:o})}let n;try{n=Ei.parse(t)}catch(o){throw new Error(`Fixture at path ${e} does not conform to expected schema`,{cause:o})}return n}async function Bs(r,e){let t=fh(r),n=e==="setup"?t.setup:t.teardown;if(!n){I.warn(`Fixture '${r}' does not have any steps in the ${e} phase, skipping...`);return}let o=n.timeout,s=async function(){for(let c=0;c<n.steps.length;c++){let u=n.steps[c],d=u.run,p=async g=>{try{await $a(`set -ex; ${d}`)}catch(m){if(g){let h=`Fixture '${r}' ${e} step ${c+1} errored in the background. The test will continue, but this may affect test execution and results: ${m}`;I.error(h)}else throw new Error(`Fixture '${r}' ${e} step ${c+1} errored: ${m}`)}};u.waitForCompletion===!1?p(!0):await p(!1)}};if(I.info(`Running ${e} phase of fixture '${r}'`),!o){await s();return}let i,a,l=async function(){return new Promise((c,u)=>{a=c,i=setTimeout(()=>{a=void 0,u(`Fixture '${r}' ${e} phase timed out after ${o} seconds`)},o*1e3)})};try{await Promise.race([s(),l()])}catch(c){throw c}finally{a&&a(),clearTimeout(i)}}async function qc({path:r,apiClient:e,generator:t,orgId:n,retriesOverride:o,useLocalFiles:s,noReport:i,envName:a,urlOverride:l,devicePixelRatio:c,customHeaders:u}){let d=new ir(e,n),p;if(s?(I.info(`Reading ${r} from local filesystem`),p=await Nn(r,Gt,I),await d.resolveStepCacheEntries({schemaVersion:p.schemaVersion,organizationId:n,steps:p.steps,testId:p.id,logger:I})):(I.info(`Fetching ${r} from Momentic Cloud server (${e.baseUrl})`),p=await e.getTest(r)),Ch.gt(p.schemaVersion,be)&&I.warn(`Test ${r} has schema version ${p.schemaVersion}, which is greater than what is currently supported by this SDK. Please update your momentic package version to avoid unexpected behavior.`),!a){for(let A of p.envs??[])if(A.default){a=A.name;break}}let g,m=[],h={};a&&(g=await xh(e,a,I.child({testId:p.id})),h=g.variables,m=p.envs?.find(x=>x.name===a)?.fixtures??[]);let f=p.baseUrl;if(l?f=l:f||(f=h[Je]),!f){let A=`Cannot run test with no base URL and no ${Je} variable defined in its environment`;throw new Error(A)}let S,w;if(i)w=Th();else try{S=await e.createRun({testId:p.id,testName:p.name,trigger:"CLI"}),w=S.id}catch(A){throw I.error({err:A,testId:p.id},"Error creating run on Momentic Cloud"),new Error("Failed to create test run on server. Please ensure the Momentic Cloud Server is accessible from your environment or pass the --no-report flag.")}let b=I.child({testId:p.id,runId:w}),T=async A=>{if(!i)try{await e.updateRun(w,{...A,finishedAt:new Date})}catch(x){b.warn({err:x},`Failed to update final run status for test ${w}. You may see stale data on the Momentic Cloud Server.`)}},v,C=Math.max(o??p.retries,0);for(let A=0;A<=C;A++)try{let{controller:x,context:L}=await Rh({baseUrl:f,envName:a,apiClient:e,devicePixelRatio:c,logger:b,storageClient:d,test:p,localFixtures:m,generator:t,orgId:n,variables:h,customHeaders:u});if(v=await Ah({logger:b,storageClient:d,apiClient:e,test:p,orgId:n,runId:w,context:L,controller:x,noReport:i}),v.status!=="FAILED")return await T({status:v.status}),{...v,runId:w};let H=v.failedStepResult,ve=H?.message||"Unknown failure";if(A>=C){b.error({errResult:H},`Test '${p.name}' failed after all exhausting ${C+1} attempts: ${ve}
|
|
1668
|
+
`),await T({status:"FAILED",failureReason:H?.failureReason}),b.info(`Classifying failure for test ${p.name}`);let O,Ke;try{let mt=await t.getTestResultClassification({results:v.results,errorMessage:ve});O={classification:mt,errorMessage:ve},Ke=mt.reason,await T({failureDetails:O,failureReason:Ke})}catch(mt){b.debug({err:mt},"Failed to classify test failure with AI, continuing...")}return{...v,runId:w,failureDetails:O,failureReason:Ke}}else b.warn({errResult:H},`Test '${p.name}' failed attempt ${A+1} of ${C+1}, retrying...`)}catch(x){b.error({err:x},`Encountered fatal platform error while running test '${p.name}': ${x}`);let L={errorMessage:x.message,errStack:x.stack},H={status:"FAILED",failureDetails:L,failureReason:"InternalPlatformError"};return await T(H),{...H,runId:w}}finally{try{await Promise.all(m.map(x=>Bs(x,"teardown")))}catch(x){b.error(`Failed to run teardown fixtures, continuing...: ${x}`)}}throw new Error("This code should not be reachable")}async function Rh({baseUrl:r,envName:e,devicePixelRatio:t,apiClient:n,test:o,localFixtures:s,storageClient:i,generator:a,orgId:l,variables:c,logger:u,customHeaders:d}){for(let f of s)await Bs(f,"setup");let p=Er.parse(o.advanced);d&&(p.extraHeaders={...p.extraHeaders??{},...d});let g=await Ge.init({baseUrl:r,logger:u,userBrowserSettings:p,storage:i,enricher:new so({baseURL:n.baseUrl,apiKey:n.apiKey}),timeout:p.pageLoadTimeoutMs,contextArgs:{viewport:o.advanced.viewport??Xe,deviceScaleFactor:t}}),m=new pr({browser:g,generator:a,config:Wr,logger:u,orgId:l,storage:i,flagStore:await ur.init(l),localCodeEvalTools:new rt({baseUrl:n.baseUrl,apiKey:n.apiKey})}),h=new ge({baseUrl:r,currentUrl:m.browser.url(),variablesFromEnvironment:c,envName:e});return{controller:m,context:h}}async function Ah({storageClient:r,apiClient:e,test:t,orgId:n,runId:o,context:s,controller:i,noReport:a,logger:l}){I.info(`Running test '${t.name}' locally${a?"":` and reporting results to https://app.momentic.ai/runs/${o}`}`);let c=wh(t.steps),u=async S=>{try{await e.updateRun(o,S)}catch(w){l.warn({err:w},"Failed to update run data. You may see stale data on the Momentic Cloud Server.")}},d={controller:i,storage:r,context:s,logger:l,codeEvalTools:new rt({baseUrl:e.baseUrl,apiKey:e.apiKey})},p={orgId:n,runId:o,testMetadata:t,steps:t.steps},g={takeScreenshots:!0},m=Eh(async S=>{if(!a){try{JSON.stringify(S)}catch(w){throw new Error(`The test results contain circular references: ${w}`)}await u(S)}},2e3);return await kr({fixtures:d,inputs:p,options:g,callbacks:{step:{},test:{onTestComplete:async()=>{await i.browser.cleanup()},onSaveScreenshot:async S=>{if(a)return"";let{key:w}=await e.uploadScreenshot({screenshot:S.toString("base64")});return w},onUpdateRun:async S=>m(S),onTestSuccess:async S=>{let w=yh(c,S);if(Object.keys(w).length===0){l.debug("No changes to test steps after success");return}l.debug({changes:w},"Updating steps post-run success in worker");try{let{cachesToSave:b}=await He({steps:S,cacheCreationParams:{testId:t.id,orgId:n}});await e.updateStepCaches({testId:t.id,entries:b})}catch(b){l.error({err:b},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}}})}async function xh(r,e,t){t.info(`Attempting to resolve environment '${e}' from local disk`);let n=bh(at,`${e}.yaml`);try{let s=vh(Sh(n,"utf-8"));try{return Ae.parse(s)}catch(i){t.warn({err:i},`${n} failed to parse as a valid environment file, pulling environment from Momentic Cloud instead`)}}catch(s){t.warn({err:s},`Failed to read file '${n}', attempting to pull environment from Momentic Cloud instead`)}return await r.getEnvironment(e)}async function Jc({tests:r,start:e,waitOn:t,waitOnTimeout:n,client:o,all:s,report:i,retriesOverride:a,urlOverride:l,envName:c,orgId:u,devicePixelRatio:d,customHeaders:p,parallel:g=1}){e&&(I.info(`Executing start command: ${e}`),await Kc(e,!1)),t&&(I.info(`Waiting for url: ${t} with timeout: ${n} seconds.`),await Lh({resources:[t],timeout:n*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!0,log:!0,strictSSL:!1}));let m=new $t({baseURL:o.baseUrl,apiKey:o.apiKey}),h=!1;(r.some(C=>C.endsWith(".yaml"))||r.some(C=>Yc(C)))&&(h=!0);let f=new Set;if(h)I.info({tests:r},`Reading tests from the following local file paths:
|
|
1627
1669
|
${r.map(C=>` - ${C}`).join(`
|
|
1628
|
-
`)}`),r.forEach(C=>{if(!
|
|
1670
|
+
`)}`),r.forEach(C=>{if(!Yc(C))throw new Error(`Path '${C}' does not exist.`);let A,x;try{A=Ih(C),x=A.isDirectory()}catch(L){I.error({err:L},`Skipping path ${C} because it cannot be read`);return}if(x)Mr(C,I).map(L=>L.fullFilePath).forEach(L=>f.add(L));else if(C.endsWith(".yaml"))f.add(C);else throw new Error(`Path '${C}' is not a directory or a .yaml file.`)});else if(le("The paths you specified are not files or directories that exist locally."),le(`Fetching tests from Momentic Cloud (${o.baseUrl}) instead...`),s)for(let C of await o.getAllTestIds())f.add(C);else f=new Set(r);let S=Array.from(f);I.info({testsToRun:S},`Running ${S.length} tests using local machine as worker`),je(`Running ${S.length} tests with ${g} workers:
|
|
1629
1671
|
${S.map(C=>` ${C}`).join(`
|
|
1630
|
-
`)}`);let w=[],b=Date.now(),
|
|
1672
|
+
`)}`);let w=[],b=Date.now(),T=new Set;for(let C=0;C<S.length;C+=g){let A=await Promise.all(S.slice(C,C+g).map(async x=>{try{T.add(x),Xc(`${T.size}/${S.length} ${x}`);let L=await qc({path:x,orgId:u,useLocalFiles:h,devicePixelRatio:d,apiClient:o,generator:m,retriesOverride:a,urlOverride:l,envName:c,noReport:!i,customHeaders:p});return{identifier:x,...L}}catch(L){let H=`A fatal error occurred while setting up the test '${x}': ${L.message}`;return I.error({err:L},"A fatal error occurred while setting up the test"),P(H),{identifier:x,status:"FAILED",failureDetails:{errorMessage:H,errorStack:L.stack}}}}));w.push(...A)}Xc.clear();let v=o.getAppUrl();hr({results:w,startTime:b,onFailed:C=>{oo(C,C.identifier)},getDisplayLine:C=>{let A=` ${C.identifier}`;return i&&C.runId&&(A+=` (${v}/runs/${C.runId})`),A},entity:"test"})}import Qc from"log-update";async function Zc({tests:r,client:e,...t}){let{queuedTests:n,runIds:o}=await e.queueTests({testPaths:r,...t});if(je(`Queued ${n.length} tests.`),t.wait){if(!o.length)return;je(`Waiting for ${n.length} tests to complete.`);let s=new Set,i=e.getAppUrl(),a=Date.now(),l=await no({name:"runs",getResults:async()=>e.bulkGetRunStatus(o),timeoutMs:t.waitTimeoutSeconds?t.waitTimeoutSeconds*1e3:void 0,checkDone:c=>(c.forEach(u=>{if(u.status==="RUNNING"&&!s.has(u.id)){s.add(u.id);let d=u.testName||u.test?.name;d&&Qc(`${s.size}/${n.length} ${pe(d)}`)}}),c.every(u=>u.status==="FAILED"&&u.failureReason||u.status==="PASSED"||u.status==="CANCELLED"))});Qc.clear(),hr({results:l,startTime:a,onFailed:c=>{let u=c.testName||c.test?.name;oo(c,u?pe(u):"Unknown test")},getDisplayLine:c=>{let u=c.testName||c.test?.name,d=` ${u?pe(u):"Unknown test"}`;return c.id&&(d+=` (${i}/runs/${c.id})`),d},entity:"test"})}process.exit(0)}var ke=new Oh;ke.name("momentic").description("Momentic CLI").version(Sc);ke.command("install-browsers").action(async()=>{await eo()});ke.addOption(new Ve("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",r=>{I.setMinLevel(r.toLowerCase())});ke.addOption(new Ve("--verbose","Enable verbose logging.")).on("option:verbose",()=>{I.enableConsoleLogs()});ke.command("init").addOption(ut).addOption(ct).addOption(dt).action(async r=>{let{yes:e,apiKey:t,server:n}=r,o=new ie({baseUrl:n,apiKey:t,logger:I});await lt({client:o,skipPrompts:e,pullEnvs:!0,createFolders:!0})});ke.command("app").addOption(ct).addOption(dt).addOption(ut).addOption(Ns).addOption(new Ve("--port <port>","Port to run the app on. Defaults to 58888.").default(58888)).action(async r=>{let{apiKey:e,port:t,yes:n,server:o,pixelRatio:s}=r,i=new ie({baseUrl:o,apiKey:e,logger:I});await lt({client:i,skipPrompts:n,pullEnvs:!1,createFolders:!1}),kh(_h(it,".."));let a=Dh(import.meta.url),l=Nh(a),c=ed.resolve(l,"..","static"),u=ed.resolve(l,"..","assets"),d=s??bs();Cs(d),await yc({momenticServerUrl:o,apiKey:e,serverPort:t,appPort:t,staticDir:c,assetsDir:u,devicePixelRatio:d})});var Fh=ke.command("suite").description("Manage and run suites");Fh.command("run").description("Run one or more suites on Momentic Cloud").addOption(ct).addOption(dt).addOption(Is).addOption(Ls).addOption(ut).addArgument(Nc).addOption(ks).addOption(_s).addOption(Ps).action(async(r,e)=>{let{apiKey:t,server:n,wait:o,waitTimeoutSeconds:s,yes:i,env:a,urlOverride:l,customHeaders:c}=e,u=new ie({baseUrl:n,apiKey:t,logger:I});await lt({client:u,skipPrompts:i,pullEnvs:!1,createFolders:!1}),(!r||!Array.isArray(r)||!r.length)&&(P("Must pass at least one suite to run."),process.exit(1)),await Vc({client:u,wait:o,suitePaths:r,waitTimeoutSeconds:s,env:a,urlOverride:l,customHeaders:Os(c)})});var Uh=ke.command("run").alias("run-tests").description("Run tests, folders, or suites on the local machine or Momentic Cloud");Uh.addOption(ct).addOption(dt).addOption(Ds).addOption(ut).addOption(Ps).addOption(_s).addOption(ks).addOption(new Ve("-r, --remote","Run tests remotely. The production version of this test will be queued for execution.").default(!0).conflicts(["start","waitOn","waitOnTimeout","retries","parallel","no-report","pixel-ratio"])).addOption(Is).addOption(Ls).addOption(Ms).addOption(Ns).addOption(new Ve("-l, --local","Run tests locally. Useful for accessing apps on localhost. This option does not control where tests are read from (see <tests> argument documentation).").conflicts(["remote","wait"])).addOption(new Ve("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new Ve("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new Ve("--wait-on-timeout <waitOnTimeout>","Max time to wait for the --wait-on URL to become accessible.").default(60,"one minute")).addOption(new Ve("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.")).addOption(new Ve("-p, --parallel <parallel>","When running with the --local flag, the number of tests to run in parallel. Defaults to 1.").default(1).argParser(r=>parseInt(r,10))).addOption(Ms).addArgument(Mc).action(async(r,e)=>{kc(e);let{all:t,apiKey:n,customHeaders:o,env:s,local:i,parallel:a,pixelRatio:l,remote:c,report:u,retries:d,server:p,start:g,urlOverride:m,wait:h,waitOn:f,waitOnTimeout:S,waitTimeoutSeconds:w,yes:b}=e,T=Os(o);!t&&(!r||!r.length)&&(P("You must pass at least one test path or use the --all flag."),process.exit(1));let v=new ie({baseUrl:p,apiKey:n,logger:I});if(i){let C=await lt({client:v,skipPrompts:b,pullEnvs:!1,createFolders:!1}),A=l??bs();Cs(A);try{await Jc({tests:r,client:v,customHeaders:T,all:t,start:g,waitOn:f,waitOnTimeout:S,retriesOverride:d,parallel:a,report:u,devicePixelRatio:A,envName:s,orgId:C,urlOverride:m})}catch(x){P("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),P(x),process.exit(1)}return}if(c){for(let C of r)(C.endsWith(".yaml")||Mh(C))&&(P(`Looks like you tried to run a local test remotely: ${C}`),P("Use the --local flag or specify the test path without its file extension to queue tests remotely (e.g. 'hello-world')."),process.exit(1));await Zc({client:v,tests:r,all:t,customHeaders:T,env:s,urlOverride:m,wait:h,waitTimeoutSeconds:w});return}P("One of --remote or --local flag must be specified."),process.exit(1)});ke.command("pull").description("Fetch one or more tests from Momentic Cloud and save it in to local disk in YAML format.").addOption(ct).addOption(dt).addOption(Ds).addOption(ut).addArgument(Oc).action(async(r,e)=>{let{apiKey:t,server:n,all:o,yes:s}=e,i=new ie({baseUrl:n,apiKey:t,logger:I});await lt({client:i,skipPrompts:s,pullEnvs:!1,createFolders:!1}),!o&&!r?.length&&(P("At least one test name or the --all flag must be provided."),process.exit(1)),await Bc({testsToFetch:r??[],client:i,all:o,yes:s}),process.exit(0)});ke.command("push").description("Save one or more tests in YAML format to Momentic Cloud.").addOption(ut).addOption(ct).addOption(dt).addArgument(_c).action(async(r,e)=>{let{apiKey:t,server:n,yes:o}=e,s=new ie({baseUrl:n,apiKey:t,logger:I});await lt({client:s,skipPrompts:o,pullEnvs:!1,createFolders:!1}),await $c({paths:r,client:s,yes:o}),process.exit(0)});var td=ke.command("env").description("Perform operations on Momentic environments");td.command("push").description("Push one or more environments and associated variables to Momentic cloud.").addOption(ut).addOption(ct).addOption(dt).addOption(Fs).addArgument(Us).action(async(r,e)=>{let{apiKey:t,server:n,yes:o,all:s}=e;!r?.length&&!s&&(P("At least one environment name or the --all flag must be provided."),process.exit(1));let i=new ie({baseUrl:n,apiKey:t,logger:I});await lt({client:i,skipPrompts:o,pullEnvs:!1,createFolders:!1}),await Lc({names:r,client:i,yes:o,all:s})});td.command("pull").description("Pull one or more environments and associated variables from Momentic cloud.").addOption(ut).addOption(ct).addOption(dt).addOption(Fs).addArgument(Us).action(async(r,e)=>{let{apiKey:t,server:n,yes:o,all:s}=e;!r?.length&&!s&&(P("At least one environment name or the --all flag must be provided."),process.exit(1));let i=new ie({baseUrl:n,apiKey:t,logger:I});await lt({client:i,skipPrompts:o,pullEnvs:!1,createFolders:!1}),await to({envNames:r,client:i,skipPrompts:o,all:s})});async function zh(){try{await ke.parseAsync(process.argv)}catch(r){let e={};try{e.playwrightVersion=Ph("npx playwright --version").toString()}catch(t){I.error({err:t},"Error fetching debug information")}I.error({err:r,debugInfo:e},"Uncaught error in CLI"),I.flush(),P("Failed to start Momentic CLI."),P(r),process.exit(1)}}zh();
|