momentic 0.0.147 → 0.0.149
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 +15 -15
- package/dist/commonjs/lib/config.d.ts +2 -2
- package/dist/commonjs/lib/config.js +2 -2
- package/dist/esm/lib/config.d.ts +2 -2
- package/dist/esm/lib/config.js +2 -2
- package/package.json +2 -16
- package/src/lib/config.ts +2 -2
package/bin/cli.js
CHANGED
|
@@ -9,7 +9,7 @@ ${this.decisions.map(e=>e.toString()).join(`
|
|
|
9
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}},pa=new is(1,{});var jn={},Sr=({logger:r,logKey:e,maxCount:t,intervalMs:n},o,s,...i)=>{let a=jn[e];a?clearTimeout(a.timer):(a={count:0,totalCount:0},jn[e]=a),a.totalCount++,a.count<t&&(a.count++,r.debug(o,s,...i)),a.timer=setTimeout(()=>{let l=jn[e];l?.totalCount!==l?.count&&r.debug({logKey:e,totalCount:l?.totalCount,count:l?.count},`Debug logs were rate-limited for ${e}`),delete jn[e]},n)};import{z as be}from"zod";var xm=be.object({id:be.string(),createdAt:be.coerce.date(),createdBy:be.string(),organizationId:be.string(),name:be.string(),description:be.string().nullish(),enabled:be.boolean(),schemaVersion:be.string().describe("Schema version for steps"),parameters:be.string().array().nullish().describe("Parameter list"),defaultParameters:be.record(be.string(),be.string()).nullish(),defaultCacheKey:be.string().nullish(),defaultCacheTtl:be.number().nullish()}),VT=xm.extend({steps:be.lazy(()=>Be.array())}),ga=5*60*1e3;import{formatInTimeZone as YT}from"date-fns-tz";var Te=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 C from"zod";var yr=C.object({disableCache:C.boolean().optional()}),aC=C.object({error:C.boolean(),reason:C.string(),message:C.string()}),lC=Xi.merge(yr),ha=Wo,cC=Yi.merge(yr),fa=hi,dC=pr.pick({browserState:!0,goal:!0}).merge(yr).extend({screenshot:C.string()}),Sa=ji,uC=pr.pick({goal:!0,url:!0}).merge(yr),ya=C.string().array(),mC=pr.pick({goal:!0,browserState:!0}).merge(yr),wa=Gi,pC=qi.merge(yr);var gC=C.object({testPaths:C.string().array().describe("can be either hyphenated, lowercase test names or UUIDs"),env:C.string().optional(),all:C.boolean().optional(),urlOverride:C.string().optional(),customHeaders:C.record(C.string(),C.string()).optional(),testInputMatrix:C.record(C.string(),C.string()).array().optional()}),ba=C.object({message:C.string(),queuedTests:C.object({name:C.string(),id:C.string()}).array(),runIds:C.string().uuid().array()}),Ta=Gn,Ca=C.string().array(),hC=C.union([C.object({paths:C.string().array().describe("run specific test paths (e.g. todo-test)"),all:C.boolean().describe("run all tests").optional()}),C.object({path:C.string().describe("deprecated; present for backcompat")})]),Ea=C.object({tests:C.record(C.string().describe("Test name"),C.string().describe("Test YAML")),modules:C.record(C.string().describe("Module name"),C.string().describe("Module YAML"))}),Am=C.object({test:C.string().describe("test YAML"),modules:C.record(C.string().describe("moduleId"),C.string().describe("module YAML"))}),fC=Am.array(),SC=C.object({testId:C.string(),schemaVersion:C.string(),steps:C.array(C.record(C.unknown()))}),yC=C.object({entries:C.array(qo),testId:C.string()}),wC=C.object({steps:C.array(C.record(C.unknown())),testId:C.string(),schemaVersion:C.string(),organizationId:C.string()}),va=vi;var bC=C.object({testId:C.string(),testName:C.string(),resolvedBaseUrl:C.string().optional(),trigger:C.nativeEnum(Yr)}),xa=C.object({id:C.string()}),Rm=ts.pick({id:!0,status:!0,testName:!0,testId:!0,test:!0,failureReason:!0,failureDetails:!0}),Aa=Rm.array(),TC=ts.pick({startedAt:!0,finishedAt:!0,results:!0,status:!0,failureDetails:!0,failureReason:!0,debugData:!0,resolvedBaseUrl:!0,resolvedInputs:!0,attempts:!0,flake:!0}).partial(),CC=C.object({screenshot:C.string()}),Ra=C.object({key:C.string()}),Ia=C.object({orgId:C.string()}),Pa=C.array(De),EC=C.array(De),La=C.record(C.string(),C.union([C.string(),C.boolean()])),vC=C.object({paths:C.string().array(),env:C.string().optional(),urlOverride:C.string().optional(),customHeaders:C.record(C.string(),C.string()).optional()}),Oa=C.object({suiteRunIds:C.string().array()});var Ma=Wi.array();import{validator as LC}from"@exodus/schemasafe";var Na=[".sh",".exe",".app",".bat",".cmd",".msi",".apk",".jar",".py",".js",".cron",".php",".asp"];var _a=r=>{r.extraHeaders&&(r.extraHeaders=Object.fromEntries(Object.entries(r.extraHeaders).filter(([e,t])=>e.trim()&&t.trim())))};import{z as BC}from"zod";var wr=class extends Error{status;constructor(e,t,n={}){super(t,n),this.status=e}},br=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 wr(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 Q="v1",he=class extends br{constructor(e){super(e)}getAppUrl(){return this.baseUrl.replace(/\/\/api/,"//app")}async getOrgId(){let e=await this.sendRequest(`/${Q}/auth/check`,{method:"GET",noLog:!0}),{orgId:t}=Ia.parse(e);return t}async bulkGetRunStatus(e){let t=await this.sendRequest(`/${Q}/runs/status`,{method:"POST",body:e,noLog:!0});return Aa.parse(t)}async createRun(e){let t=await this.sendRequest(`/${Q}/runs`,{method:"POST",body:e,noLog:!0});return xa.parse(t)}async updateRun(e,t){await this.sendRequest(`/${Q}/runs/${e}`,{method:"PATCH",body:t,noLog:!0})}async getTest(e){let t=await this.sendRequest(`/${Q}/tests/${e}`,{method:"GET"});return Ta.parse(t)}async getAllTestIds(){let e=await this.sendRequest(`/${Q}/tests`,{method:"GET"});return Ca.parse(e)}async getTestYAMLExport(e){let t=await this.sendRequest(`/${Q}/tests/export`,{method:"POST",body:e});return Ea.parse(t)}async updateTestWithYAML(e){await this.sendRequest(`/${Q}/tests/update`,{method:"POST",body:e})}async updateStepCaches(e){await this.sendRequest(`/${Q}/cache`,{method:"PATCH",body:e})}async getStepCacheForTest(e){let t=await this.sendRequest(`/${Q}/cache`,{method:"POST",body:e});return va.parse(t)}async queueTests(e){let t=await this.sendRequest(`/${Q}/tests/queue`,{method:"POST",body:e});return ba.parse(t)}async uploadScreenshot(e){let t=await this.sendRequest(`/${Q}/screenshots`,{method:"POST",body:e,noLog:!0});return Ra.parse(t)}async getAllEnvironments(){let e=await this.sendRequest(`/${Q}/environments`,{method:"GET"});return Pa.parse(e)}async getEnvironment(e){let t=await this.sendRequest(`/${Q}/environments/${e}`,{method:"GET"});return De.parse(t)}async updateEnvironments(e){await this.sendRequest(`/${Q}/environments`,{method:"POST",body:e})}async getAllFeatureFlags(){let e=await this.sendRequest(`/${Q}/auth/flags`,{method:"GET",noLog:!0});return La.parse(e)}async acquireCacheLock(e){let t=await this.sendRequest(`/${Q}/result-cache/entry`,{method:"POST",body:e});return ra.parse(t)}async releaseCacheLock(e){await this.sendRequest(`/${Q}/result-cache/entry`,{method:"DELETE",body:{key:e}})}async setCacheResult(e){await this.sendRequest(`/${Q}/result-cache/entry`,{method:"PATCH",body:e})}async getCacheResult(e){try{return await this.sendRequest(`/${Q}/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(`/${Q}/suites/queue`,{method:"POST",body:e});return Oa.parse(t)}async bulkGetSuiteStatus(e){let t={suiteRunIds:e},n=await this.sendRequest(`/${Q}/suites/status`,{method:"POST",body:t,noLog:!0});return Ma.parse(n)}async updateCacheLastUsedDate(e,t){try{await this.sendRequest(`/${Q}/cache/lastUsedAt`,{method:"PATCH",body:e})}catch(n){t.error({err:n},"Failed to update cache last used date")}}async uploadProposedSteps(e,t){try{await this.sendRequest(`/${Q}/runs/proposed-steps`,{method:"POST",body:e})}catch(n){t.error({err:n},"Failed to upload proposed steps")}}};function Tr({steps:r,topLevel:e=!0,...t}){let{stepCacheEntries:n,logger:o,keyPrefix:s}=t,i=[],a=[],l=0,c=(d,m)=>{try{let p=$t.parse(m.value);if(p.type!==d.type){o.warn({parsedCacheEntry:p,command:d},"Not using step cache due to type mismatch"),a.push(m.key);return}d.cache=p.cache,i.push(m.key)}catch(p){a.push(m.key),o.error({err:p,cacheEntry:m},"Not using step cache due to parsing error")}},u=(d,m)=>{let p=Im(d.id,m),h=p.find(g=>!!n[g]);h?c(d,n[h]):(a.push(p[0]),o.debug({command:d,possibleKeys:p},"Step cache miss"))};for(let d of r)switch(d.type){case"RESOLVED_MODULE":{l+=d.steps.length;let{hits:p,misses:h}=Tr({...t,steps:d.steps,keyPrefix:s?`${s}:${d.id}`:d.id,topLevel:!1});i=i.concat(p),a=a.concat(h);break}case"IFRAME":case"SECTION":case"AI_ACTION":{if(l+=d.steps?.length??0,!d.steps?.length)break;let{hits:p,misses:h}=Tr({...t,steps:d.steps,topLevel:!1});i=i.concat(p),a=a.concat(h);break}case"PRESET_ACTION":{if(!Ko.includes(d.command.type)||d.command.type==="TYPE"&&!d.command.target||d.command.type==="MOUSE_DRAG"&&!d.command.target||"cache"in d.command&&d.command.cache)continue;l++,u(d.command,s);break}case"CONDITIONAL":{for(let p of d.blocks){l++,u(p.assertion.command,s),l+=p.steps.length;let{hits:h,misses:g}=Tr({...t,steps:p.steps,topLevel:!1});i=i.concat(h),a=a.concat(g);break}if(d.elseSteps){l+=d.elseSteps.length;let{hits:p,misses:h}=Tr({...t,steps:d.elseSteps,topLevel:!1});i=i.concat(p),a=a.concat(h)}break}default:return(p=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(d)}return e&&l&&a.length>0&&o.debug({totalSteps:l,cacheMisses:a,cacheHits:i,cacheEntries:n.length},"Step cache did not fully resolve"),{hits:i,misses:a}}function Da(r,e){return e?`${e}:${r}`:r}function Im(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 ka(r){let{moduleStepParents:e=[],moduleIdParents:t=[]}=r;if(e.length!==t.length)throw new Error(`Invalid cache entry parent length: ${JSON.stringify(e)}
|
|
10
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:Da(r.id,i),moduleId:s,organizationId:r.orgId,value:r.value})}return n.push({key:Da(r.id,e.join(":")),organizationId:r.orgId,value:r.value,testId:r.testId}),n}function Fa(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 tn(r,e){return r.length<e?r:r.slice(0,e-3)+"[...]"}var Gt={EQUALS:"equals",CONTAINS:"contains",STARTS_WITH:"starts with"},jt={EQUALS:"does not equal",CONTAINS:"does not contain",STARTS_WITH:"does not start with"},as={EXISTS:"exists",VISIBLE:"is visible",ENABLED:"is enabled",EDITABLE:"is editable"},ls={EXISTS:"does not exists",VISIBLE:"is not visible",ENABLED:"is disabled",EDITABLE:"is not editable"};function Pm(r){switch(r.type){case"ELEMENT_CONTENT":return`${r.negated?jt[r.operation]:Gt[r.operation]} '${r.value}'`;case"ELEMENT_ATTRIBUTE":{let t=r.negated?jt[r.operation]:Gt[r.operation];return`attribute '${r.attr}' ${t} '${r.value}'`}case"ELEMENT_EXISTENCE":return r.negated?ls[r.condition]:as[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 ov={CONTENT:"The page"};function Lm(r){switch(r.type){case"CONTENT":return`${r.negated?jt.CONTAINS:Gt.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 Lt(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: ${tn(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: ${Se(r.target)}`:""}`;case"SCROLL_UP":return`Scroll up ${r.deltaY?`${r.deltaY}px`:"1 page height"}${r.target?` in the container of: ${Se(r.target)}`:""}`;case"SCROLL_LEFT":return`Scroll left ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${Se(r.target)}`:""}`;case"SCROLL_RIGHT":return`Scroll right ${r.deltaX?`${r.deltaX}px`:"1 page width"}${r.target?` in the container of: ${Se(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: ${Se(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 ${Se(r.target)}`;case"BLUR":return`Focus ${Se(r.target)}`;case"DRAG":return`Drag ${Se(r.fromTarget)} onto ${Se(r.toTarget)}`;case"MOUSE_DRAG":return r.target?`Click and drag ${Se(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: ${Se(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: ${Se(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: ${Se(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: ${tn(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: ${Se(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 ${Se(r.target)} ${Pm(r.assertion)}`;case"PAGE_CHECK":return`Assert the page ${Lm(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 Ua(r){let e=[];for(let t of r){t.sort((i,a)=>i.timestamp-a.timestamp);let n=[],o,s=1;for(let i of t)o&&o.text===i.text&&o.type===i.type&&JSON.stringify(o.args??null)===JSON.stringify(i.args??null)?s++:(o&&(s>1?o.args&&o.args.length?o.args.push(`(repeated ${s} times)`):o.text+=` (repeated ${s} times)`:n.push(o)),o=i,s=1);o&&n.push(o),e.push(n)}return e}function mt(r){let{onPresetAction:e,onSimpleStepContainer:t,onConditional:n}=r;for(let o of r.steps)switch(o.type){case"PRESET_ACTION":e(o);break;case"CONDITIONAL":n?.(o);for(let i of o.blocks)e(i.assertion),mt({...r,steps:i.steps});mt({...r,steps:o.elseSteps??[]});break;case"RESOLVED_MODULE":case"IFRAME":case"SECTION":case"AI_ACTION":t?.(o),o.steps&&mt({...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;mt({steps:r,onPresetAction:t=>{t.index=e++},onConditional:t=>{t.index=e++},onSimpleStepContainer:t=>{t.index=e++}})}function za(r){mt({steps:r,onPresetAction:e=>{delete e.index},onConditional:e=>{delete e.index},onSimpleStepContainer:e=>{delete e.index}})}var Om=(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 Kn(r,e){let t=r[e[0]];for(let n=1;n<e.length;n++)t=Om(t,e[n]);return t}function qn(r){let e=0;return mt({steps:r,onPresetAction:t=>{e=Math.max(e,t.index)},onConditional:t=>{e=Math.max(e,t.index)},onSimpleStepContainer:t=>{e=Math.max(e,t.index)}}),e}import{cloneDeep as Tv,unset as Cv}from"lodash-es";function cs(r){switch(r.type){case"AI_ACTION":return`AI action: ${tn(r.text,100)}`;case"PRESET_ACTION":return Lt(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${r.description?`with goal: ${tn(r.description,100)}`:""}`;default:return(t=>{throw new Error("You missed a case in the switch above")})(r)}}function Yn(r){for(let e of r)switch(e.type){case"PRESET_ACTION":$a(e);break;case"CONDITIONAL":e.assertion&&$a(e.assertion),Yn(e.results);break;case"AI_ACTION":case"IFRAME":case"MODULE":case"SECTION":{Yn(e.results);break}default:return(n=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}}function $a(r){let e=r.command;"cache"in e&&e.cache&&(e.cache=void 0),r.details&&(r.details=void 0)}function Ba(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 Dm from"diff-lines";import Jn,{gte as km}from"semver";var Ha={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 Wa={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 Mm=["target","fromTarget","toTarget"];function Ga(r){for(let e of Mm){if(r[e]===void 0)continue;let t=r[e];t.elementDescriptor!==void 0?t.type="description":r[e]={type:"description",elementDescriptor:""}}}var ja={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 Ga(e.command),e;case"AI_ACTION":{let t=e.commands;for(let n of t??[])Ga(n);return e}default:return e}})};import{v4 as Nm}from"uuid";var Va={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=Nm()),e;default:return e}})};import{v4 as Ka}from"uuid";var qa={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??Ka(),e}case"AI_ACTION":return e.commands&&(e.steps=e.commands.map(t=>({type:"PRESET_ACTION",command:{...t,id:t.id??Ka()}})),delete e.commands),e;default:return e}})};var Ya={name:"Migrate ai waits to checks",fromVersion:"1.0.9",toVersion:"1.0.10",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{switch(e.type){case"PRESET_ACTION":{if(!e.command)return e;let t=e.command;return typeof t.type!="string"||t.type!=="AI_WAIT"||(t.type="AI_ASSERTION",t.timeout||(t.timeout=10)),e}default:return e}})};import{v4 as _m}from"uuid";var Xa={name:"Add ids to all steps",fromVersion:"1.0.10",toVersion:"1.0.11",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>("id"in e&&typeof e.id=="string"||(e.id=_m()),e))};import{v4 as Ja}from"uuid";var Qa={name:"Add ids to all steps",fromVersion:"1.0.11",toVersion:"1.0.12",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if("id"in e&&typeof e.id=="string")return e;if("condition"in e&&typeof e.condition=="object"&&e.condition){let t=e.condition;t.id||(t.id=Ja())}return e.id=Ja(),e})};var Za={name:"Move env key to steps",fromVersion:"1.0.12",toVersion:"1.0.13",recursiveKeys:new Set(["results","steps","blocks","elseSteps"]),stopOnFailure:!0,execute:async r=>r.map(e=>{if(e.type!=="PRESET_ACTION")return e;let t=e.command;return!t||typeof t.envKey!="string"||(e.envKey=t.envKey,delete t.envKey),e})};var el={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"]),tl={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 m=d?.elementDescriptor,p=d?.type;(m!==void 0||Xn.has(p))&&(d.target={elementDescriptor:m??""})})}),e}),stopOnFailure:!0};var rl={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 nl={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 Vt=[el,rl,nl,tl,Ha,Wa,ja,Va,qa,Ya,Xa,Qa,Za];if(Pe!==Vt[Vt.length-1].toVersion)throw new Error("Please bump LATEST_VERSION in types package after adding a migration");Vt.forEach((r,e)=>{if(!Jn.valid(r.toVersion)||!Jn.valid(r.fromVersion))throw new Error(`Migration '${r.name}' has invalid version`);if(!Jn.gt(r.toVersion,r.fromVersion))throw new Error(`Migration '${r.name}' has toVersion <= fromVersion`);if(e===0)return;if(Vt[e-1].toVersion!==r.fromVersion)throw new Error(`Migration '${r.name}' at index ${e} is not contiguous with previous migration`)});function Fm(r){return r.every(e=>e&&typeof e=="object"&&!Array.isArray(e))}var ds=async({metadata:r,steps:e,logger:t,toVersion:n})=>{let o=e,{schemaVersion:s,id:i}=r,a=Vt.findIndex(u=>Jn.gt(u.toVersion,s));if(a===-1)return{steps:o,newVersion:s};let l=s;for(let u=a;u<Vt.length;u++){if(n&&km(l,n)){t.debug("Stopping migration early because toVersion was reached");break}let d=Vt[u],m={id:i,migration:d.name,toVersion:d.toVersion};try{o=await ol(o,d),l=d.toVersion}catch(p){throw t.error({err:p,...m},"Migration failed"),new Error(`Step migration ${d.name} failed: ${p}`)}}let c=Dm(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 ol(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)||Fm(s)&&(n[o]=await ol(s,e))}return t}async function sl({rawSteps:r,metadata:e,logger:t,callbacks:n}){Ba(e,"defaultOnCloud");let o={},{resolvedSteps:s,newSchemaVersion:i}=await us({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 us({rawSteps:r,metadata:e,logger:t,callbacks:n,resolvedModuleCache:o={}}){let{newVersion:s,steps:i}=await ds({metadata:e,steps:r,logger:t}),a;try{a=Be.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 zn(`Failed to parse test steps while migrating test: ${c}`,e.id,"entity",{cause:c})}let l=[];for(let c of a)l.push(await rn({step:c,callbacks:n,logger:t,resolvedModuleCache:o}));return{resolvedSteps:l,newSchemaVersion:s}}async function rn({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 ds({metadata:{id:l,schemaVersion:u.schemaVersion},steps:u.steps,logger:t}),p;try{p=Be.array().parse(m)}catch(f){throw t.error({type:"zod",err:f,steps:m,newVersion:d,id:l},"Module failed to parse"),f}let h;try{h=await Promise.all(p.map(f=>rn({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:h};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 rn({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 rn({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 rn({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 Um}from"lodash-es";import{v4 as il}from"uuid";async function et(r){let e=Um(r.steps);return Cr({...r,steps:e,moduleStepParents:[],moduleIdParents:[],moduleIdReplacements:new Map,seenModules:new Set})}async function Cr({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?il():d.id,Fa(d),"cache"in d&&d.cache&&(n&&(l.cachesToSave=l.cachesToSave.concat(ka({id:d.id,orgId:n.orgId,testId:n.testId,value:$t.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?il():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:p,stepsToSave:h,moduleUpdates:g}=await Cr({...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(p),t.has(m)||(t.add(m),l.moduleUpdates.push({...je.parse(c),steps:Be.array().parse(h)}));let f={type:"MODULE",moduleId:m,inputs:c.inputs,id:d,skipped:c.skipped,cacheConfig:c.cacheConfig,envKey:c.envKey};l.stepsToSave.push(f);break}case"AI_ACTION":{if(!c.steps){l.stepsToSave.push(c);break}let{stepsToSave:d,cachesToSave:m}=await Cr({...e,steps:c.steps});try{c.steps=Ue.array().parse(d)}catch(p){throw new Error(`Only preset actions are allowed in AI actions at the moment: ${p}`)}l.stepsToSave.push(c),l.cachesToSave=l.cachesToSave.concat(m);break}case"CONDITIONAL":{let d=[];for(let p of c.blocks){let{stepsToSave:h,cachesToSave:g,moduleUpdates:f}=await Cr({...e,steps:p.steps});d.push({...p,steps:h}),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:p,cachesToSave:h,moduleUpdates:g}=await Cr({...e,steps:c.elseSteps});m.elseSteps=p,l.cachesToSave=l.cachesToSave.concat(h),l.moduleUpdates=l.moduleUpdates.concat(g)}l.stepsToSave.push(m);break}case"IFRAME":case"SECTION":{let{stepsToSave:d,cachesToSave:m,moduleUpdates:p}=await Cr({...e,steps:c.steps}),h={...c,steps:d};l.moduleUpdates=l.moduleUpdates.concat(p),l.stepsToSave.push(h),l.cachesToSave=l.cachesToSave.concat(m);break}default:return(d=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(c)}return l}import{cloneDeep as zm}from"lodash-es";import{stringify as ms}from"yaml";async function al(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 $m(r.steps,r.schemaVersion,n,e),s={fileType:"momentic/test",...t,steps:o};return{test:ms(s),modules:n}}async function $m(r,e,t,n){let o=zm(r);Bm(o);let{stepsToSave:s,moduleUpdates:i}=await et({steps:o});for(let a of i)n.has(a.name)||(t[a.name]=Hm(a),n.add(a.name));return s}function Bm(r){mt({steps:r,onPresetAction:e=>{e.index=void 0,e.command.thoughts=void 0},onConditional:e=>{e.index=void 0},onSimpleStepContainer:e=>{e.index=void 0}})}function Hm(r){let e=je.parse(r),t={fileType:"momentic/module",...e,schemaVersion:Pe,steps:r.steps};return ms(t)}function ps(r){return ms({fileType:"momentic/environment",...r})}var Er=class{constructor(e,t){this.client=e;this.orgId=t}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}=Tr({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 gs="v1",pt=class extends br{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(`/${gs}/tools/sms/send`,{method:"POST",body:e})}async fetchLatestSms(e){try{return await this.sendRequest(`/${gs}/tools/sms/fetchLatest`,{method:"POST",body:e})}catch(t){throw t instanceof wr&&t.status===404?new Error("No recent SMS messages found."):t}}async fetchLatestEmail(e){try{return this.sendRequest(`/${gs}/tools/email/fetchLatest`,{method:"POST",body:e})}catch(t){throw t instanceof wr&&t.status===404?new Error("No matching emails found."):new Error(`Failed to fetch latest emails: ${t.message}`)}}};import kh from"body-parser";import Fh from"cors";import Vs from"express";import{existsSync as jm,readFileSync as eo,readdirSync as Vm,statSync as Km,writeFileSync as Ss}from"fs";import gt from"path";import{parse as on,stringify as qm}from"yaml";var me=process.env.MOMENTIC_DIR??It;import{readFileSync as nn,readdirSync as hs,writeFileSync as cl}from"fs";import Wm,{join as fs}from"path";import{v4 as Gm}from"uuid";import{parse as Qn,stringify as dl}from"yaml";var Ot=fs(me,Pt);function ul(r){let e=Zn(Ot,r.moduleId).path,t=nn(e,"utf-8"),n=Qn(t),o={fileType:"momentic/module",...n,...r},s=dl(o);cl(e,s,"utf-8")}async function ml(r,e,t,n){let o=Te(r),s=fs(Ot,`${o}.yaml`),i=Gm(),{stepsToSave:a}=await et({steps:n}),l={fileType:"momentic/module",schemaVersion:Pe,moduleId:i,name:r,description:e,enabled:t,steps:a},c=dl(l);return cl(s,c,"utf-8"),{moduleId:i,name:r,description:e,enabled:t,steps:n}}function pl(){let r=[];for(let e in hs(Ot)){if(!e.endsWith(".yaml"))continue;let t=nn(e,"utf-8"),n=Qn(t),o={name:n.name,moduleId:n.moduleId};r.push(o)}return r}async function gl(r){let e=new Set;for(let t of hs(Ot)){if(!t.endsWith(".yaml"))continue;let n=fs(Ot,t),o=nn(n,"utf-8"),s=Qn(o),i;try{i=Zr.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 fl(Array.from(e),r)}function ll(r,e){let t=Zn(Ot,r).path,n=nn(t,"utf-8"),o=Qn(n);try{return Zr.parse(o)}catch(s){throw e.error({err:s,moduleFilePath:t,moduleContents:n},`${t} does not parse as a valid module`),s}}async function hl(r,e){return(await fl([r],e)).find(n=>n.moduleId===r)}async function fl(r,e){let t={};return await Promise.all(r.map(async n=>{let o=ll(n,e),{resolvedSteps:s}=await us({rawSteps:o.steps,metadata:{id:o.moduleId,schemaVersion:o.schemaVersion},resolvedModuleCache:t,logger:e,callbacks:{onFetchModule:async i=>ll(i.id,e)}});t[n]={...o,steps:s}})),Array.from(Object.values(t))}function Zn(r,e){let t=hs(r);for(let n of t){let o=Wm.join(r,n),s=nn(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 Sl=Wn,Ym=new Set([...Sl,"node_modules","dist","bin",".git","logs",".npm",".next","out",".yarn","__pycache__","build",".env",".venv","venv","env","wheels"]);async function yl(r,e){let t=await al(r);for(let[s,i]of Object.entries(t.modules)){let a=Te(s);Ss(gt.join(me,Pt,`${a}.yaml`),i,"utf-8")}let n=Te(e),o=gt.join(me,`${n}.yaml`);return Ss(o,t.test,"utf-8"),`${n}.yaml`}function to(r,e){if(!jm(e))throw new Error(`Test not found at path: ${gt}`);let t=eo(e,"utf-8"),o={...on(t),...r},s=we.parse(o),i={fileType:"momentic/test",...s,steps:o.steps},a=qm(i);Ss(e,a,"utf-8")}function sn(r,e,t=r){let n=r.split(gt.sep).pop()??"";if(Ym.has(n))return Sl.includes(n)||e.warn(`Skipping directory '${r}' because it is likely an artifact folder.`),[];let o=Vm(r),s=[];return o.forEach(i=>{let a=gt.join(r,i),l;try{l=Km(a)}catch(c){e.warn({err:c},`Skipping path '${a}' because it could not be read.`);return}if(l.isDirectory())s=s.concat(sn(a,e,t));else if(i.endsWith(".yaml")){let c=eo(a,"utf-8"),u=gt.relative(gt.resolve(t),gt.resolve(a));try{let d=on(c),m=we.parse(d);s.push({id:m.id,name:m.name,fullPathSegments:a.split(gt.sep),testPath:u,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 wl(r){let e;try{e=eo(r,"utf8"),e=e.replace(/\r\n|\r/g,`
|
|
11
11
|
`)}catch(n){throw new Error(`Could not read test file ${r}: ${n}`)}let t;try{t=on(e)}catch(n){throw new Error(`Could not parse test file ${r} as YAML: ${n}`)}return we.parse(t)}function ys(r,e){let t;try{t=eo(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]=Zn(e,a).content)}),{test:t,modules:i}}async function ro(r,e,t){let{test:n,modules:o}=ys(r,e),s=on(n);if(!s.steps||!Array.isArray(s.steps))throw new Error(`Test ${r} is missing steps`);let i;try{i=we.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=on(u)}catch(m){throw new Error(`Module ${c} is not valid YAML: ${m}`)}try{let m=Zr.parse(d);a[c]=m}catch(m){throw new Error(`Module ${c} is missing metadata or has invalid metadata: ${m}`)}}let{resolvedTest:l}=await sl({rawSteps:s.steps,metadata:i,logger:t,callbacks:{onFetchModule:async({id:c})=>a[c]}});return l}import{existsSync as Xm,readFileSync as Jm,readdirSync as Qm}from"fs";import{join as bl}from"path";import{parse as Zm}from"yaml";var ws=bl(me,fr);function Tl(){let r=[];if(!Xm(ws))return[];for(let e of Qm(ws)){if(!e.endsWith(".yaml"))continue;let t=bl(ws,e),n=Jm(t,"utf-8"),o=Zm(n);try{let s=De.parse(o);r.push(s)}catch(s){pa.warn({err:s},"Error parsing environment, skipping...")}}return r}import{existsSync as Uh,statSync as zh}from"fs";import $h from"http";import Bh from"open";import Hh from"path";import{Server as Ch}from"socket.io";import{cloneDeep as ep}from"lodash-es";var bs=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:bs(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},no=class{results;constructor(){this.results=[]}setResults(e){this.results=bs(e)}setIndividualResult(e,t){let n=bs([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 ep(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 tp={showOverlay:!1},Ts=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 no,browserbaseSessionId:i,browserBehavior:tp}),s}removeSession(e,t){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:s}=o;try{await s.browser.cleanup()}catch(i){t.error({err:i},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(i){t.error({err:i},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}cancelExecution(e){let t=this.sessions.get(e);t&&(t.executionCancelled=!0)}resumeExecution(e){let t=this.sessions.get(e);t&&(t.executionCancelled=!1)}},_=new Ts;var rp=200;function Cl(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{let p;(!a||!l||Date.now()-i>=1500)&&(a=await m.getViewport(),l=await m.getFrameSrcUrls(),i=Date.now(),p=m.retrieveAndClearConsoleLogs()),r.emit("browserState",{logsPerPage:p,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(p){if(!r.connected)return;let h=p instanceof Error?p.message:`${p}`;if(h.includes("Frame was detached")||h.includes("Not attached to an active page")||h.includes("browser has been closed"))return;s++,t.error({err:p,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 p=_.getSession(e)?.controller?.browser;if(!p||p.closed){t.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(u.timer);return}c(p)};return u.timer=setInterval(d,rp),u}var np=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async()=>{if(e.info({sessionId:t},"Cancel event received"),!_.getSession(t))throw new Error("No active session found");_.cancelExecution(t)}},El={event:"cancel",createHandler:np};var op=({metadata:r,logger:e})=>{let{sessionId:t}=r;return n=>{e.info({sessionId:t,reason:n},`Disconnect event received (${n})`),_.removeSession(t,e)}},vl={event:"disconnect",createHandler:op};import{randomUUID as gp}from"crypto";import{faker as sp}from"@faker-js/faker";import ip from"assert";import ap from"axios";import lp from"moment";import*as cp from"otpauth";import dp,{TimeoutError as up}from"p-timeout";import mp from"pg";var pp=Object.getPrototypeOf(async function(){}).constructor;async function xl(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 pp("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","env","results","inputs","setVariable","sendSms","waitForLatestSms","email","sms",n)(ap,lp,sp,ip,mp,u,d,cp,s,o,i??{},c,S=>a.sms.send(S),S=>a.sms.fetchLatest(S),a.email,a.sms)),p=!0,h,g;try{h=await dp(m(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`}),t.debug(`[${r}] Got execution result: ${JSON.stringify(h)}`),t.debug(`[${r}] Got variable updates: ${JSON.stringify(l)}`)}catch(f){t.error(`[${r}] Error executing code: ${f}`),p=!1,f instanceof up?g=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:g=f instanceof Error?f.message:`${f}`}return{result:h,variableUpdates:l,success:p,error:g}}async function Al({code:r,fragment:e,context:t,localTools:n,logger:o,timeoutMs:s=hr}){let i=gp();return xl(i,{code:r,options:{fragment:e,timeoutMs:s},bindings:t.toObjectCopy(),tools:n},o)}import{randomUUID as hp}from"crypto";import fp from"p-timeout";var Rl=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT;async function Il({code:r,fragment:e,context:t,logger:n,timeoutMs:o=hr,retries:s=1}){if(!Rl)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let i,a,l=0;for(;l<=s;){l++;let u={id:hp(),code:r,fragment:e,state:t.toObjectCopy(),timeoutMs:o};n.debug(u,"Sending request to code evaluation server");try{if(i=await fp(fetch(Rl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`}),!i)throw new Error("Got empty response from code evaluation server");if(!i.ok)throw new Error(`Code evaluation server returned error code ${i.status}`);a=void 0;break}catch(d){a=d}}if(a)throw a;if(!i)throw new Error(`An unexpected code evaluation error occurred${a?`: ${a}`:""}`);let c;try{c=Qi.parse(await i.json()),n.debug({response:c},"Response from code evaluation server")}catch(u){throw new Error(`Code evaluation server returned invalid response: ${u}`)}if(c.error)throw new Error(`Code evaluation server returned error: ${c.error}`);return c}async function vr(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await Il(r);else if(r.localTools)e=await Al({...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 We(r){let{s:e,context:t,logger:n,timeoutMs:o=hr,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 vr({code:u,fragment:!0,context:t,timeoutMs:o,logger:n,retries:s,localTools:r.localTools})}catch(p){throw n.error({err:p,value:e},"Error evaluating template string"),p}let m=typeof d=="string"?d:`${d}`;m=m.replace(/\$/g,"$$$$"),m=m.replace(/\\/g,"\\\\"),l=l.replace(c[0],m)}return n.debug({s:e,result:l},"Substituted template string"),l}var tI=process.env.MAILINATOR_API_KEY;import oI from"p-timeout";import"twilio";import{diff as Dp}from"deep-object-diff";import{spawn as yp}from"child_process";async function Pl(r){return new Promise((e,t)=>{let n={stdio:"inherit",env:process.env,detached:!0},o=yp("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 an(r,e,t,n,o,s){try{let[i,a]=await Promise.all([t?o(t):void 0,n?o(n):void 0]);i&&(r&&(r.beforeScreenshot=i),e.beforeScreenshot=i),a&&(r&&(r.afterScreenshot=a),e.afterScreenshot=a)}catch(i){s.debug({err:i},"Error saving screenshot to S3")}}var oo=async r=>{let e=r.presetParams.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,p,h=Un();try{let g=await n.executePresetStep(h,e.command,o,i.advanced.disableAICaching,r.callbacks.test.isExecutionCancelled);if(g.beforeScreenshotOverride&&(u=g.beforeScreenshotOverride),p=g.afterScreenshotOverride,g.fail)throw new R("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.",beforeUrl:l,afterUrl:S,finishedAt:f,startedAt:c,status:"SUCCESS",data:g.data,results:[m],details:h.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 ${Lt(e.command)}`);let f=n.browser.url(),S=new Date,w=g instanceof Error?g.message:`${g}`;m={beforeUrl:l,afterUrl:f,startedAt:c,finishedAt:S,viewport:await n.browser.getViewport(),status:g instanceof Ke?"CANCELLED":"FAILED",message:w},d={...e,startedAt:c,finishedAt:S,beforeUrl:l,afterUrl:f,status:g instanceof Ke?"CANCELLED":"FAILED",message:w,failureReason:g instanceof R?g.reason:void 0,results:[m],details:h.details}}if(s&&!p)try{p=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 r.work.asyncTasks.push(an(m,d,u,p,a.onSaveScreenshot,t)),d};function tt(r){let{result:e,nestedResults:t}=r;if(!r.nestedResults.length)return;let{firstMetadata:n,lastMetadata:o}=wp(t);bp(e,n,o);let s=[...r.asyncTasks];r.asyncTasks.push((async()=>{try{await Tp(s,e,n,o)}catch(i){r.logger.error({result:r.result,err:i},"Error hoisting scalar result metadata")}})())}function wp(r){let e=r[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertion){t=e;break}break;case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!e.results.length){t=e;break}e=e.results[e.results.length-1];break;default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let n=r[r.length-1],o;for(;;){switch(n.type){case"PRESET_ACTION":{o=n;break}case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!n.results.length){o=n;break}n=n.results[n.results.length-1];break;default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function bp(r,e,t){e&&(r.beforeUrl=e.beforeUrl),t&&(r.afterUrl=t.afterUrl,r.data=t.data,t.status!=="SUCCESS"&&(r.message=t.message))}async function Tp(r,e,t,n){await Promise.allSettled(r),t&&(e.beforeScreenshot=t.beforeScreenshot),n&&(e.afterScreenshot=n.afterScreenshot)}import Cs from"os";function Ll(r){let e=()=>{try{let t=Cp(),n=Ep();r.debug({memory:t,cpu:n},"Got machine cpu usage metrics")}catch{}};return e(),setInterval(e,3e4)}function Cp(){let r=Cs.totalmem(),e=Cs.freemem(),t=r-e;return{totalMemory:r,freeMemory:e,usedMemory:t}}function Ep(){let r=Cs.cpus(),e=0,t=0,n=0,o=0,s=0,i=0;for(let a of r)e+=a.times.user,t+=a.times.nice,n+=a.times.sys,o+=a.times.idle,s+=a.times.irq;return i=e+t+n+o+s,{user:e/i*100,nice:t/i*100,sys:n/i*100,idle:o/i*100,irq:s/i*100,total:100-o/i*100}}var Ol=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=e.cacheConfig.cacheKey||e.defaultCacheKey||"",m=await We({s:d,context:o,logger:n,localTools:i}),p={orgId:a,cacheKeys:[m,...Object.entries(t).map(([g,f])=>`${g}:${f}`)]};n.debug({cacheKey:d,keyParams:p},"Module cache key params");let h=Date.now();for(;Date.now()-h<ga;){let g=await s.getCacheResult(p);if(g){n.info({cacheResult:g},"Got result from module execution cache"),c=so(e,t,"SUCCESS"),c.message="Used cached module result.",c.data=JSON.parse(g);break}let f=await s.acquireCacheLock({keyParams:p,clientMetadata:`testId:${l.id}`});if(f.acquired){u=f.keyPrefix,n.info({cacheKeyPrefix:u,cacheKey:d,keyParams:p},"Acquired cache lock and proceeding with module execution");break}await new Promise(S=>setTimeout(S,2500+Math.random()*1e4))}}try{c||(c=await vp(r))}finally{if(u!==void 0){let d=e.cacheConfig.cacheExpiryMs;d===na&&(d=e.defaultCacheTtl??oa),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},vp=async r=>{let{step:e}=r.moduleParams,t=so(e,r.moduleParams.resolvedInputs,"SUCCESS"),{status:n,results:o}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:`module ('${e.name}')`}});return t.results=o,t.status=n,t.finishedAt=new Date,tt({asyncTasks:r.work.asyncTasks,nestedResults:o,result:t,logger:r.fixtures.logger}),t};function so(r,e,t){let n={};return Object.entries(e).forEach(([s,i])=>{n[s]=JSON.stringify(i)}),{type:"MODULE",id:r.id,moduleId:r.moduleId,moduleName:r.name,startedAt:new Date,cacheConfig:r.cacheConfig,inputs:n,results:[],finishedAt:new Date,status:t}}async function Ml(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 vr({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 Kt(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=so(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:[]}}}async function io(r,e){let t=!1;try{return r&&!r.healingDisabled&&(r.healingDisabled=!0,t=!0),await e()}finally{r&&t&&(r.healingDisabled=void 0)}}import{randomUUID as ao}from"crypto";var _l=async r=>{let e=await xp(r);return tt({asyncTasks:r.work.asyncTasks,result:e,nestedResults:e.results,logger:r.fixtures.logger}),e},xp=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:h,results:g}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"AI action"}});return d.finishedAt=new Date,d.status=h,d.results=g,d}catch(h){l.warn({err:h},"Failed executing saved AI action steps, attempting to re-generate...")}e.steps=[];let p=0;try{for(;;){if(p>12)throw new Error(`Exceeded max number of commands per step (${12})`);let h=t+p+1;if(c.isExecutionCancelled?.())return d.status="CANCELLED",d.finishedAt=new Date,u.onCancelled?.({index:h,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(E){l.debug({err:E},"Failed to take screenshot before AI command, likely because the page is still loading. This is non-fatal.")}l.info(`Generating new sub-command ${p} 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(E){if(l.error({err:E,commandIndex:p},"Failed to generate command within AI step"),p===0)throw E;{let I="Stopping command generation prematurely since no progress can be made";l.info({command:g},I),g={id:ao(),type:"SUCCESS",thoughts:I}}}let T={id:ao(),type:"PRESET_ACTION",index:h,command:g};Rp({newStep:T,controller:i,currentStep:e,pageContext:b?.context,logger:l,onCommandExecuted:u.onCommandExecuted,currentIndex:p,globalSubStepIndex:h}),u.onCommandGenerated?.({index:h,step:T,message:os[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 ${p} within AI step: ${Lt(g)}`);try{let E=await i.executeCommand(g,a,m&&n.advanced.disableAICaching,m);l.info(`AI sub-command ${p} completed successfully`),v.elementInteracted=E.elementInteracted;let I;if(s)try{I=await i.browser.screenshot({})}catch(P){l.debug({err:P},"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;let A={status:"SUCCESS",startedAt:v.startedAt,finishedAt:v.finishedAt,data:E.data,results:[v],beforeTestContext:S,afterTestContext:a.toRedactedDisplayCopy(),...T};if(r.work.asyncTasks.push(an(v,A,w,I,c.onSaveScreenshot,l)),d.results.push(A),e.steps[p]=T,Ip(o,r.inputs,h),u.onCommandExecuted?.({index:h,output:{...A,message:g.thoughts??E.thoughts??"Successfully executed preset action."},step:T}),g.type==="SUCCESS"){d.finishedAt=new Date,d.status="SUCCESS",d.message=E.thoughts??"All commands completed.",d.afterTestContext=a.toRedactedDisplayCopy();break}if(E.succeedImmediately&&!m){d.finishedAt=new Date,d.status="SUCCESS",d.message=`Marked step as completed due to reason: ${E.succeedImmediatelyReason}`,d.afterTestContext=a.toRedactedDisplayCopy(),g={id:ao(),type:"SUCCESS",thoughts:E.succeedImmediatelyReason};let P={id:ao(),type:"PRESET_ACTION",command:g};e.steps.push(P),u.onCommandExecuted?.({index:h+1,output:{...A,message:d.message},step:P}),d.results.push({...A,...P});break}}catch(E){let I=E instanceof Error?E.message:`${E}`,A=E instanceof R?E.reason:void 0;v.status="FAILED",v.message=I,v.finishedAt=new Date,v.afterUrl=i.browser.url();let P;try{P=await i.browser.screenshot({})}catch(W){l.debug({err:W},"Failed to take screenshot after AI command error, likely because the page is still loading. This is non-fatal.")}let D={id:g.id,status:"FAILED",startedAt:v.startedAt,finishedAt:v.finishedAt,type:"PRESET_ACTION",results:[v],message:I,failureReason:A,command:g};r.work.asyncTasks.push(an(v,D,w,P,c.onSaveScreenshot,l)),d.results.push(D),d.status="FAILED",d.finishedAt=new Date,d.message=I,d.failureReason=A;break}p++}}catch(h){d.message=h instanceof Error?h.message:`${h}`,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 Ap(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 Rp({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 Ap(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 Ip(r,e,t){Vn(r),e.toIndex&&e.toIndex>=t&&e.toIndex++}async function Dl(r){let{step:e}=r.conditionalParams,{logger:t}=r.fixtures,n=new Date,o=e.elseSteps,s=!0,i=[],a,l=Un();for(let m=0;m<e.blocks.length;m++){t.info(`Evaluating condition ${m} in conditional step`);let p=e.blocks[m];try{let h=await oo({...r,presetParams:{step:p.assertion}});i.push(h),t.info(`Condition ${m} resolved to true, executing the corresponding ${p.steps.length} steps`),s=!1,o=p.steps,a=h}catch(h){t.info({err:h},`Condition ${m} resolved to false`)}}if(o)s&&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:n,data:i[i.length-1]?.data,message:i[i.length-1]?.message,results:[],finishedAt:new Date,details:l.details};t.info(`Executing ${o.length} steps in the selected conditional block`);let c=await r.executeStepList({...r,listParams:{steps:o,containerName:"conditional block"}}),d={...e,assertion:a,...c,startedAt:n,finishedAt:new Date};return tt({asyncTasks:r.work.asyncTasks,nestedResults:[...i,...c.results],result:d,logger:t}),d}async function kl(r){let{step:e}=r.frameParams,{logger:t,controller:n}=r.fixtures,o=new Date,s=n.browser.getActiveFrame();n.browser.setActiveFrame(e.identifier);let i;try{i=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"frame step list"}})}finally{n.browser.setActiveFrame(s)}let l={...e,...i,startedAt:o,finishedAt:new Date};return tt({asyncTasks:r.work.asyncTasks,nestedResults:i.results,result:l,logger:t}),l}import{randomUUID as lo}from"crypto";import Pp from"fast-json-patch";import{cloneDeep as Lp}from"lodash-es";async function Fl(r){let e=r.failedResults,t=[],{sectionParams:n,fixtures:o,work:s,startingUrl:i,startingContextSnapshot:a}=r,{step:l}=n,{controller:c}=o,u=l?.autohealingConfig,d=u?.restartBehavior??{type:"GO_TO_SECTION_START"},m=u?.attempts??1;for(let p=0;p<m;p++){if(!e.terminalResult?.message)throw new Error("No error message in terminal result");let h=Lp(l.steps);await Promise.allSettled(s.asyncTasks??[]);let g=await c.runSectionAutohealing({results:e.results,errorMessage:e.terminalResult?.message,goal:l.description});for(let w of g.patches)h=Pp.applyOperation(h,w).newDocument;let f=se.fromSnapshot({snapshot:a,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await Op({controller:c,context:f,restartConfig:d,startingUrl:i});let S=await io(r.work,()=>r.executeStepList({...r,fixtures:{...r.fixtures,context:f},listParams:{steps:h,containerName:"auto-healed step list"}}));if(t.push(S.results),S.status==="SUCCESS")return{successfulHealing:{proposedStep:{...l,steps:h},listResult:S,context:f},healingAttempts:t};e=S}return{healingAttempts:t}}async function Op({controller:r,restartConfig:e,context:t,startingUrl:n}){switch(e.type){case"NAVIGATE_URL":{let o={id:lo(),type:"PRESET_ACTION",command:{id:lo(),type:"NAVIGATE",url:e.url}};await r.executePresetStep(null,o.command,t,!1);break}case"GO_TO_SECTION_START":{let o={id:lo(),type:"PRESET_ACTION",command:{id:lo(),type:"NAVIGATE",url:n}};await r.executePresetStep(null,o.command,t,!1);break}}}function Ul(r,e){switch(r||(r="ON_FAILURE"),r){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&Ei(e.command.type))}}async function zl(r){let{step:e}=r.sectionParams,{logger:t,controller:n,context:o}=r.fixtures,s=new Date,i=n.browser.url(),a=o.toObjectCopy(),l=async()=>r.executeStepList({...r,listParams:{steps:e.steps,containerName:"section step list"}}),c=e.autohealingConfig?await io(r.work,l):await l(),u,d;if(c.status==="FAILED"&&e.autohealingConfig&&!r.work.healingDisabled&&Ul(e.autohealingConfig.trigger,c.terminalResult)){let p=await Fl({...r,startingContextSnapshot:a,startingUrl:i,failedResults:c});p.successfulHealing&&(u=p.successfulHealing.proposedStep,c=p.successfulHealing.listResult,r.fixtures.context=p.successfulHealing.context),d=p.healingAttempts}let m={...e,...c,startedAt:s,finishedAt:new Date,proposedStep:u,healingAttempts:d};return tt({asyncTasks:r.work.asyncTasks,nestedResults:c.results,result:m,logger:t}),m}async function qt(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=r.work,p=[],h="SUCCESS",g,f=0;for(f;f<n.length;f++){let S=n[f],w,b=cs(S),T=S.index;if(T===void 0)throw new Error(`Executing step without index: ${b}`);if(d&&T>d)break;if(c.isExecutionCancelled?.()){if(h="CANCELLED",l.onCancelled?.({index:T,output:{status:"CANCELLED",message:"Execution cancelled.",startedAt:new Date,finishedAt:new Date}}),e.length){let D=e[e.length-1];D.status="CANCELLED",D.message="Cancelled by user signal.",g=D}break}if(S.skipped)continue;if(u&&T<u&&(S.type==="PRESET_ACTION"||qn([S])<u))continue;o.info(`Executing step ${f+1}/${n.length} in ${t}: ${b}`),l.onStarted?.(T);let v=s.toRedactedDisplayCopy(),E=i.browser.url(),I,A;switch(S.type){case"PRESET_ACTION":{I="Preset action",A=await Kt(S,()=>oo({...r,presetParams:{step:S}}));break}case"AI_ACTION":{I="AI action",A=await Kt(S,()=>_l({...r,aiStepParams:{step:S},executeStepList:qt}));break}case"RESOLVED_MODULE":{I=`Module (${S.name})`;let D=new se({baseUrl:i.browser.baseUrl,currentUrl:i.browser.url(),dynamicVariables:s.getDynamicVariablesCopy(),variablesFromEnvironment:s.getVariablesFromEnvironmentCopy(),envName:s.getEnvName()});A=await Kt(S,async()=>{let W=await Ml(S,s,o,a);return Ol({...r,executeStepList:qt,fixtures:{...r.fixtures,context:D},moduleParams:{step:S,resolvedInputs:W}})});break}case"CONDITIONAL":{I="Conditional step",A=await Kt(S,()=>Dl({...r,conditionalParams:{step:S},executeStepList:qt}));break}case"IFRAME":{I="Frame step",A=await Kt(S,()=>kl({...r,frameParams:{step:S},executeStepList:qt}));break}case"SECTION":{I="Section";let D=await Kt(S,()=>zl({...r,sectionParams:{step:S},executeStepList:qt}));"proposedStep"in D&&D.proposedStep&&(w=D.proposedStep,D.proposedStep=void 0,m&&(m.autoHealed=!0)),A=D;break}default:return(W=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(S)}w?p.push(w):p.push(S),A.beforeUrl=A.beforeUrl??E,A.beforeTestContext=v,s.setResult(f,A.data),S.envKey&&s.setVariable(S.envKey,A.data);let P=i.browser.url();if(s.setCurrentUrl(P),A.afterUrl=A.afterUrl??P,A.afterTestContext=s.toRedactedDisplayCopy(),Np(I,T,A,r.callbacks,o,r.work),e.push(A),A.status!=="SUCCESS"){h=A.status,g=A;break}}return{status:h,results:e,terminalResult:g,proposedSteps:p}}async function Mp(r,e){r&&e?.({results:r.results})}function Np(r,e,t,n,o,s){let{step:i,test:a}=n,l=r.toLowerCase(),c=r.charAt(0).toUpperCase()+r.slice(1);switch(t.status){case"SUCCESS":i.onSuccess?.({index:e,step:"command"in t?t:void 0,message:t.message??`${c} executed successfully.`,output:Fn.parse(t)});break;case"FAILED":i.onFailure?.({index:e,message:t.message??`${c} failed.`,output:Fn.parse(t)});break;case"CANCELLED":i.onCancelled?.({index:e,message:t.message??`${c} cancelled.`,output:Fn.parse(t)});break;default:throw new Error(`Unexpected ${l} status: ${t.status}`)}t.status==="SUCCESS"&&s&&Mp(s,a.onUpdateRun)}var ln=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=Ll(r.fixtures.logger),Vn(r.inputs.steps);let t;try{return t=await _p(r),t}finally{if(clearInterval(e),za(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...")}}},_p=async r=>{let{runId:e,testMetadata:t,fromIndices:n,toIndices:o,indicesFilter:s,steps:i}=r.inputs,{logger:a,controller:l}=r.fixtures;a.info(`Starting run ${e} for test '${t.name}'`);let c=i,u="test";if(n){let S=Kn(i,n);if(!S)throw new Error(`Could not find starting step using indices: ${n}`);r.inputs.fromIndex=S.index,a.debug({fromIndices:n,fromStep:S},"Identified starting step using fromIndices"),u="partial steps list"}if(o){let S=Kn(i,o);if(!S)throw new Error(`Could not find step at indices: ${o}`);let w=qn([S]);r.inputs.toIndex=w,a.debug({toIndices:o,toStep:S,maxIndexUnderToStep:w},"Identified ending step using toIndices"),u="partial steps list"}if(s){let S=Kn(i,s);if(!S)throw new Error(`Could not find ending step at indices: ${r.inputs.indicesFilter}`);c=[S],a.debug({steps:i,indicesFilter:s},"Filtered steps to run based on exact indices filter"),u="filtered step"}let d=[],m={results:d,healingDisabled:!!s||!!n||!!o||void 0,asyncTasks:[]},{status:p,terminalResult:h,proposedSteps:g}=await qt({...r,work:m,listParams:{steps:c,containerName:u,results:d}});if(r.options.takeScreenshots&&await Promise.allSettled(m.asyncTasks),s&&d.length){let S=d[0];if(S.beforeTestContext&&S.afterTestContext){let w=se.fromSnapshot({snapshot:S.beforeTestContext,environmentVariables:r.fixtures.context.getVariablesFromEnvironmentCopy()}),b=r.fixtures.context.getResult(0);w.setResult(s[s.length-1],b),S.afterTestContext={...S.afterTestContext,results:w.getResultsCopy()}}}let f;return r.options.consumeDebuggingData&&(f={logsPerPage:Ua(l.browser.retrieveAndClearConsoleLogs())}),r.callbacks.test.onUpdateRun?.({results:d,debugData:f}),p==="FAILED"?{status:"FAILED",results:d,failedStepResult:h}:(g&&m.autoHealed&&await r.callbacks.test.onProposedTestSteps?.({testId:t.id,orgId:r.inputs.orgId,runId:r.inputs.runId,steps:g}),{status:"PASSED",results:d})};import{cloneDeep as kp}from"lodash-es";var Es={currentlyExecutingRequests:{}},Fp=r=>async(e,t)=>{let n,{testId:o}=r.metadata,{baseUrl:s}=e,i=`${o}|${s}`;try{let a=Es.currentlyExecutingRequests[i]??0;Es.currentlyExecutingRequests[i]=a+1,n=await Up({...r,...e,done:t})}finally{r.logger.info({result:n,sessionId:r.metadata.sessionId},"Test execution complete"),Es.currentlyExecutingRequests[i]--}},Up=async({socket:r,steps:e,baseUrl:t,testMetadata:n,reInitialize:o,indicesFilter:s,toIndices:i,fromIndices:a,storage:l,metadata:c,logger:u,envName:d,environmentVariables:m,testInputs:p,authorization:h,done:g})=>{let{testId:f,sessionId:S,orgId:w}=c,b=S,T=_.getSession(S);if(!T)throw new Error("No active session found");_.resumeExecution(S);let{controller:v,context:E}=T;v.setOpen();let I=h?.type==="API_KEY"?new pt(h):void 0;u=u.child({testId:f,orgId:w,baseUrl:t,sessionId:S,runId:b}),u.info({steps:e.map(G=>`${G.type}${"command"in G?` - ${G.command.type}`:""}`),indicesFilter:s,fromIndices:a,toIndices:i,reInitialize:o,envName:d,baseUrl:t},"Starting execution"),u.debug({steps:e,context:E,flags:v.flagStore.getAllFlags()},"Execution parameters");let A=m??{};await Promise.all((n.parameters??[]).map(async G=>{let st=(p??{})[G.name]??G.defaultValue;if(st===void 0)return;let Dt=await We({s:st,context:se.dummyContext(d),logger:u,localTools:I});A[G.name]=Dt}));let P=async()=>{if(o){let G={url:t,clearCookies:!0,clearStorage:!0};await v.resetState(G),v.setOpen(),E.reset({baseUrl:t,currentUrl:v.browser.url(),variablesFromEnvironment:A,envName:d})}},D=async()=>{try{await l.resolveStepCacheEntries({schemaVersion:Pe,organizationId:w,testId:f,steps:e,logger:u})}catch(G){u.error({err:G},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};await Promise.all([P(),D()]);let W=kp(e),x={takeScreenshots:!1,consumeDebuggingData:!1},H={orgId:w,runId:b,testMetadata:n,steps:e,indicesFilter:s,fromIndices:a,toIndices:i},J={controller:v,context:E,storage:l,codeEvalTools:I,logger:u},Z=(G,st)=>{r.emit(st,G)},At={test:{onTestComplete:async()=>{r.emit("finished")},onSaveScreenshot:zp,isExecutionCancelled:()=>_.getSession(S)?.executionCancelled||v.browser.closed||v.isClosed()||r.disconnected,onTestSuccess:async G=>{let st=Dp(W,G);if(Object.keys(st).length>0){u.debug({changes:st},"Updating steps post-run success");let{cachesToSave:Dt}=await et({steps:e,cacheCreationParams:{testId:f,orgId:w}});try{await l.saveStepCacheEntries(Dt,n.id,u)}catch(N){u.warn({err:N},"Failed to save step cache entries after execution success")}}}},step:{onStarted:G=>r.emit("started",{globalIndex:G}),onSuccess:G=>Z(G,"success"),onFailure:G=>Z(G,"failure"),onCancelled:G=>Z(G,"cancelled"),onCommandGenerated:G=>{r.emit("commandGenerated",{...G,message:G.message??"AI action sub-step generated"})},onCommandExecuted:G=>{r.emit("commandExecuted",G)}}};if(s?.length){u.info({indicesFilter:s},"Starting individual step");let G=T.resultsManager.getContextCopyAtIndices(s)??E.toObjectCopy(),st=se.fromSnapshot({snapshot:G,environmentVariables:E.getVariablesFromEnvironmentCopy()}),Dt=await ln({fixtures:{...J,context:st},options:x,callbacks:At,inputs:H}),N=Dt.results[0];return N?T.resultsManager.setIndividualResult(N,s):u.warn(Dt,"No result found for individual step"),Dt.status}let er=await ln({fixtures:J,options:x,callbacks:At,inputs:H});return T.resultsManager.setResults(er.results),g?.(er),er.status},zp=async r=>r.toString("base64");var $l={event:"execute",createHandler:Fp};var $p=({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=Jr(i,o.description);e.debug({description:u,params:o},"Locate handler params"),e.info({description:u},"Locate handler called");let d=_.getSession(n);if(!d)throw new Error("No active session found");let{controller:m,context:p}=d,h=d.resultsManager.getContextCopyAtIndices(c)??p.toObjectCopy(),g=se.fromSnapshot({snapshot:h,environmentVariables:p.getVariablesFromEnvironmentCopy()}),f=ar.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 ut?b.decisions:void 0});return}else try{let b=await m.locateElement({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:T,height:v}=await m.screenshotWithDimensions({scale:"css",clearHighlights:!0,target:S?.target,hideCaret:!0}),E=await t.uploadScreenshot(b);S.screenshot={data:E,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([m.browser.scrollIntoView(w),m.browser.highlightTarget(w)])}catch(b){e.warn({err:b},"Error highlighting element, continuing...")}}},Bl={event:"locate",createHandler:$p};var Bp=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async({percentX:n,percentY:o},s)=>{let i=_.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})}}},Hl={event:"cloudClick",createHandler:Bp};var Hp=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async(n,o)=>{let s=_.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}}},Wl={event:"recordTargetClick",createHandler:Hp};var Wp=({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=_.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")}}}},Gl={event:"cloudMouseMove",createHandler:Wp};var Gp=({metadata:r})=>{let{sessionId:e}=r;return async({percentDeltaX:t,percentDeltaY:n})=>{let o=_.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()})}},jl={event:"cloudScroll",createHandler:Gp};var jp=({metadata:r,generator:e,socket:t,storage:n,logger:o})=>{let{sessionId:s,orgId:i,testId:a}=r;return async({indices:l})=>{let c=_.getSession(s);if(!c)throw new Error("No active session found");let{controller:u,browserBehavior:d}=c;o.info("Starting cloud recording");let m=await u.startRecordMode({generator:e,initialIndices:l,storage:n,logger:o,testId:a,orgId:i,onStepRecord:(p,h)=>{t.emit("stepRecorded",{step:p,indices:h})}});d.recordingState={transformer:m},d.showOverlay=!0}},Vl={event:"cloudStartRecording",createHandler:jp};var Vp=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async()=>{let 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}},Kl={event:"cloudStopRecording",createHandler:Vp};var Kp=["Dead","Meta","AudioVolumeUp","AudioVolumeDown"],qp=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async({key:n})=>{let o=_.getSession(t);if(!o)throw new Error("No active session found");if(Kp.includes(n))return;let{controller:s}=o;if(s.browser.closed||s.browser.getActivePage().isClosed()){e.debug({sessionId:t},"Browser is closed, ignoring typing action");return}n.length>1?await s.browser.press(n):await s.browser.type(n,{clearContent:!1,pressKeysSequentially:!0})}},ql={event:"cloudType",createHandler:qp};var cn={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;
|
|
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]=Zn(e,a).content)}),{test:t,modules:i}}async function ro(r,e,t){let{test:n,modules:o}=ys(r,e),s=on(n);if(!s.steps||!Array.isArray(s.steps))throw new Error(`Test ${r} is missing steps`);let i;try{i=we.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=on(u)}catch(m){throw new Error(`Module ${c} is not valid YAML: ${m}`)}try{let m=Zr.parse(d);a[c]=m}catch(m){throw new Error(`Module ${c} is missing metadata or has invalid metadata: ${m}`)}}let{resolvedTest:l}=await sl({rawSteps:s.steps,metadata:i,logger:t,callbacks:{onFetchModule:async({id:c})=>a[c]}});return l}import{existsSync as Xm,readFileSync as Jm,readdirSync as Qm}from"fs";import{join as bl}from"path";import{parse as Zm}from"yaml";var ws=bl(me,fr);function Tl(){let r=[];if(!Xm(ws))return[];for(let e of Qm(ws)){if(!e.endsWith(".yaml"))continue;let t=bl(ws,e),n=Jm(t,"utf-8"),o=Zm(n);try{let s=De.parse(o);r.push(s)}catch(s){pa.warn({err:s},"Error parsing environment, skipping...")}}return r}import{existsSync as Uh,statSync as zh}from"fs";import $h from"http";import Bh from"open";import Hh from"path";import{Server as Ch}from"socket.io";import{cloneDeep as ep}from"lodash-es";var bs=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:bs(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},no=class{results;constructor(){this.results=[]}setResults(e){this.results=bs(e)}setIndividualResult(e,t){let n=bs([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 ep(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 tp={showOverlay:!1},Ts=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 no,browserbaseSessionId:i,browserBehavior:tp}),s}removeSession(e,t){(async()=>{let o=this.sessions.get(e);if(!o)return;this.releaseCapacityByIp(o.clientIp);let{controller:s}=o;try{await s.browser.cleanup()}catch(i){t.error({err:i},"Error cleaning up browser in global state manager")}try{await o.cleanup?.()}catch(i){t.error({err:i},"Error running cleanup function in global state manager")}this.sessions.delete(e)})()}getSession(e){return this.sessions.get(e)}cancelExecution(e){let t=this.sessions.get(e);t&&(t.executionCancelled=!0)}resumeExecution(e){let t=this.sessions.get(e);t&&(t.executionCancelled=!1)}},_=new Ts;var rp=200;function Cl(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{let p;(!a||!l||Date.now()-i>=1500)&&(a=await m.getViewport(),l=await m.getFrameSrcUrls(),i=Date.now(),p=m.retrieveAndClearConsoleLogs()),r.emit("browserState",{logsPerPage:p,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(p){if(!r.connected)return;let h=p instanceof Error?p.message:`${p}`;if(h.includes("Frame was detached")||h.includes("Not attached to an active page")||h.includes("browser has been closed"))return;s++,t.error({err:p,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 p=_.getSession(e)?.controller?.browser;if(!p||p.closed){t.debug("Clearing browser state socket cron due to the browser being closed"),clearInterval(u.timer);return}c(p)};return u.timer=setInterval(d,rp),u}var np=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async()=>{if(e.info({sessionId:t},"Cancel event received"),!_.getSession(t))throw new Error("No active session found");_.cancelExecution(t)}},El={event:"cancel",createHandler:np};var op=({metadata:r,logger:e})=>{let{sessionId:t}=r;return n=>{e.info({sessionId:t,reason:n},`Disconnect event received (${n})`),_.removeSession(t,e)}},vl={event:"disconnect",createHandler:op};import{randomUUID as gp}from"crypto";import{faker as sp}from"@faker-js/faker";import ip from"assert";import ap from"axios";import lp from"moment";import*as cp from"otpauth";import dp,{TimeoutError as up}from"p-timeout";import mp from"pg";var pp=Object.getPrototypeOf(async function(){}).constructor;async function xl(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 pp("axios","moment","faker","assert","pg","Octokit","createAppAuth","OTPAuth","env","results","inputs","setVariable","sendSms","waitForLatestSms","email","sms",n)(ap,lp,sp,ip,mp,u,d,cp,s,o,i??{},c,S=>a.sms.send(S),S=>a.sms.fetchLatest(S),a.email,a.sms)),p=!0,h,g;try{h=await dp(m(),{milliseconds:e.options.timeoutMs,message:`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`}),t.debug(`[${r}] Got execution result: ${JSON.stringify(h)}`),t.debug(`[${r}] Got variable updates: ${JSON.stringify(l)}`)}catch(f){t.error(`[${r}] Error executing code: ${f}`),p=!1,f instanceof up?g=`Timeout of ${e.options.timeoutMs}ms exceeded for code execution`:g=f instanceof Error?f.message:`${f}`}return{result:h,variableUpdates:l,success:p,error:g}}async function Al({code:r,fragment:e,context:t,localTools:n,logger:o,timeoutMs:s=hr}){let i=gp();return xl(i,{code:r,options:{fragment:e,timeoutMs:s},bindings:t.toObjectCopy(),tools:n},o)}import{randomUUID as hp}from"crypto";import fp from"p-timeout";var Rl=process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT;async function Il({code:r,fragment:e,context:t,logger:n,timeoutMs:o=hr,retries:s=1}){if(!Rl)throw new Error("GCP_JS_EVAL_FUNCTION_ENDPOINT environment variable not set");let i,a,l=0;for(;l<=s;){l++;let u={id:hp(),code:r,fragment:e,state:t.toObjectCopy(),timeoutMs:o};n.debug(u,"Sending request to code evaluation server");try{if(i=await fp(fetch(Rl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)}),{milliseconds:o,message:`Timeout of ${o}ms exceeded for code execution`}),!i)throw new Error("Got empty response from code evaluation server");if(!i.ok)throw new Error(`Code evaluation server returned error code ${i.status}`);a=void 0;break}catch(d){a=d}}if(a)throw a;if(!i)throw new Error(`An unexpected code evaluation error occurred${a?`: ${a}`:""}`);let c;try{c=Qi.parse(await i.json()),n.debug({response:c},"Response from code evaluation server")}catch(u){throw new Error(`Code evaluation server returned invalid response: ${u}`)}if(c.error)throw new Error(`Code evaluation server returned error: ${c.error}`);return c}async function vr(r){let e;if(process.env.GCP_JS_EVAL_FUNCTION_ENDPOINT)e=await Il(r);else if(r.localTools)e=await Al({...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 We(r){let{s:e,context:t,logger:n,timeoutMs:o=hr,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 vr({code:u,fragment:!0,context:t,timeoutMs:o,logger:n,retries:s,localTools:r.localTools})}catch(p){throw n.error({err:p,value:e},"Error evaluating template string"),p}let m=typeof d=="string"?d:`${d}`;m=m.replace(/\$/g,"$$$$"),m=m.replace(/\\/g,"\\\\"),l=l.replace(c[0],m)}return n.debug({s:e,result:l},"Substituted template string"),l}var tI=process.env.MAILINATOR_API_KEY;import oI from"p-timeout";import"twilio";import{diff as Dp}from"deep-object-diff";import{spawn as yp}from"child_process";async function Pl(r){return new Promise((e,t)=>{let n={stdio:"inherit",env:process.env,detached:!0},o=yp("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 an(r,e,t,n,o,s){try{let[i,a]=await Promise.all([t?o(t):void 0,n?o(n):void 0]);i&&(r&&(r.beforeScreenshot=i),e.beforeScreenshot=i),a&&(r&&(r.afterScreenshot=a),e.afterScreenshot=a)}catch(i){s.debug({err:i},"Error saving screenshot to S3")}}var oo=async r=>{let e=r.presetParams.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,p,h=Un();try{let g=await n.executePresetStep(h,e.command,o,i.advanced.disableAICaching,r.callbacks.test.isExecutionCancelled);if(g.beforeScreenshotOverride&&(u=g.beforeScreenshotOverride),p=g.afterScreenshotOverride,g.fail)throw new R("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.",beforeUrl:l,afterUrl:S,finishedAt:f,startedAt:c,status:"SUCCESS",data:g.data,results:[m],details:h.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 ${Lt(e.command)}`);let f=n.browser.url(),S=new Date,w=g instanceof Error?g.message:`${g}`;m={beforeUrl:l,afterUrl:f,startedAt:c,finishedAt:S,viewport:await n.browser.getViewport(),status:g instanceof Ke?"CANCELLED":"FAILED",message:w},d={...e,startedAt:c,finishedAt:S,beforeUrl:l,afterUrl:f,status:g instanceof Ke?"CANCELLED":"FAILED",message:w,failureReason:g instanceof R?g.reason:void 0,results:[m],details:h.details}}if(s&&!p)try{p=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 r.work.asyncTasks.push(an(m,d,u,p,a.onSaveScreenshot,t)),d};function tt(r){let{result:e,nestedResults:t}=r;if(!r.nestedResults.length)return;let{firstMetadata:n,lastMetadata:o}=wp(t);bp(e,n,o);let s=[...r.asyncTasks];r.asyncTasks.push((async()=>{try{await Tp(s,e,n,o)}catch(i){r.logger.error({result:r.result,err:i},"Error hoisting scalar result metadata")}})())}function wp(r){let e=r[0],t;for(;;){switch(e.type){case"PRESET_ACTION":{t=e;break}case"CONDITIONAL":if(e.assertion){t=e;break}break;case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!e.results.length){t=e;break}e=e.results[e.results.length-1];break;default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(e)}if(t)break}let n=r[r.length-1],o;for(;;){switch(n.type){case"PRESET_ACTION":{o=n;break}case"CONDITIONAL":case"AI_ACTION":case"MODULE":case"SECTION":case"IFRAME":if(!n.results.length){o=n;break}n=n.results[n.results.length-1];break;default:return(i=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(n)}if(o)break}return{firstMetadata:t,lastMetadata:o}}function bp(r,e,t){e&&(r.beforeUrl=e.beforeUrl),t&&(r.afterUrl=t.afterUrl,r.data=t.data,t.status!=="SUCCESS"&&(r.message=t.message))}async function Tp(r,e,t,n){await Promise.allSettled(r),t&&(e.beforeScreenshot=t.beforeScreenshot),n&&(e.afterScreenshot=n.afterScreenshot)}import Cs from"os";function Ll(r){let e=()=>{try{let t=Cp(),n=Ep();r.debug({memory:t,cpu:n},"Got machine cpu usage metrics")}catch{}};return e(),setInterval(e,3e4)}function Cp(){let r=Cs.totalmem(),e=Cs.freemem(),t=r-e;return{totalMemory:r,freeMemory:e,usedMemory:t}}function Ep(){let r=Cs.cpus(),e=0,t=0,n=0,o=0,s=0,i=0;for(let a of r)e+=a.times.user,t+=a.times.nice,n+=a.times.sys,o+=a.times.idle,s+=a.times.irq;return i=e+t+n+o+s,{user:e/i*100,nice:t/i*100,sys:n/i*100,idle:o/i*100,irq:s/i*100,total:100-o/i*100}}var Ol=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=e.cacheConfig.cacheKey||e.defaultCacheKey||"",m=await We({s:d,context:o,logger:n,localTools:i}),p={orgId:a,cacheKeys:[m,...Object.entries(t).map(([g,f])=>`${g}:${f}`)]};n.debug({cacheKey:d,keyParams:p},"Module cache key params");let h=Date.now();for(;Date.now()-h<ga;){let g=await s.getCacheResult(p);if(g){n.info({cacheResult:g},"Got result from module execution cache"),c=so(e,t,"SUCCESS"),c.message="Used cached module result.",c.data=JSON.parse(g);break}let f=await s.acquireCacheLock({keyParams:p,clientMetadata:`testId:${l.id}`});if(f.acquired){u=f.keyPrefix,n.info({cacheKeyPrefix:u,cacheKey:d,keyParams:p},"Acquired cache lock and proceeding with module execution");break}await new Promise(S=>setTimeout(S,2500+Math.random()*1e4))}}try{c||(c=await vp(r))}finally{if(u!==void 0){let d=e.cacheConfig.cacheExpiryMs;d===na&&(d=e.defaultCacheTtl??oa),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},vp=async r=>{let{step:e}=r.moduleParams,t=so(e,r.moduleParams.resolvedInputs,"SUCCESS"),{status:n,results:o}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:`module ('${e.name}')`}});return t.results=o,t.status=n,t.finishedAt=new Date,tt({asyncTasks:r.work.asyncTasks,nestedResults:o,result:t,logger:r.fixtures.logger}),t};function so(r,e,t){let n={};return Object.entries(e).forEach(([s,i])=>{n[s]=JSON.stringify(i)}),{type:"MODULE",id:r.id,moduleId:r.moduleId,moduleName:r.name,startedAt:new Date,cacheConfig:r.cacheConfig,inputs:n,results:[],finishedAt:new Date,status:t}}async function Ml(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 vr({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 Kt(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=so(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:[]}}}async function io(r,e){let t=!1;try{return r&&!r.healingDisabled&&(r.healingDisabled=!0,t=!0),await e()}finally{r&&t&&(r.healingDisabled=void 0)}}import{randomUUID as ao}from"crypto";var _l=async r=>{let e=await xp(r);return tt({asyncTasks:r.work.asyncTasks,result:e,nestedResults:e.results,logger:r.fixtures.logger}),e},xp=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:h,results:g}=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"AI action"}});return d.finishedAt=new Date,d.status=h,d.results=g,d}catch(h){l.warn({err:h},"Failed executing saved AI action steps, attempting to re-generate...")}e.steps=[];let p=0;try{for(;;){if(p>12)throw new Error(`Exceeded max number of commands per step (${12})`);let h=t+p+1;if(c.isExecutionCancelled?.())return d.status="CANCELLED",d.finishedAt=new Date,u.onCancelled?.({index:h,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(E){l.debug({err:E},"Failed to take screenshot before AI command, likely because the page is still loading. This is non-fatal.")}l.info(`Generating new sub-command ${p} 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(E){if(l.error({err:E,commandIndex:p},"Failed to generate command within AI step"),p===0)throw E;{let I="Stopping command generation prematurely since no progress can be made";l.info({command:g},I),g={id:ao(),type:"SUCCESS",thoughts:I}}}let T={id:ao(),type:"PRESET_ACTION",index:h,command:g};Rp({newStep:T,controller:i,currentStep:e,pageContext:b?.context,logger:l,onCommandExecuted:u.onCommandExecuted,currentIndex:p,globalSubStepIndex:h}),u.onCommandGenerated?.({index:h,step:T,message:os[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 ${p} within AI step: ${Lt(g)}`);try{let E=await i.executeCommand(g,a,m&&n.advanced.disableAICaching,m);l.info(`AI sub-command ${p} completed successfully`),v.elementInteracted=E.elementInteracted;let I;if(s)try{I=await i.browser.screenshot({})}catch(P){l.debug({err:P},"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;let x={status:"SUCCESS",startedAt:v.startedAt,finishedAt:v.finishedAt,data:E.data,results:[v],beforeTestContext:S,afterTestContext:a.toRedactedDisplayCopy(),...T};if(r.work.asyncTasks.push(an(v,x,w,I,c.onSaveScreenshot,l)),d.results.push(x),e.steps[p]=T,Ip(o,r.inputs,h),u.onCommandExecuted?.({index:h,output:{...x,message:g.thoughts??E.thoughts??"Successfully executed preset action."},step:T}),g.type==="SUCCESS"){d.finishedAt=new Date,d.status="SUCCESS",d.message=E.thoughts??"All commands completed.",d.afterTestContext=a.toRedactedDisplayCopy();break}if(E.succeedImmediately&&!m){d.finishedAt=new Date,d.status="SUCCESS",d.message=`Marked step as completed due to reason: ${E.succeedImmediatelyReason}`,d.afterTestContext=a.toRedactedDisplayCopy(),g={id:ao(),type:"SUCCESS",thoughts:E.succeedImmediatelyReason};let P={id:ao(),type:"PRESET_ACTION",command:g};e.steps.push(P),u.onCommandExecuted?.({index:h+1,output:{...x,message:d.message},step:P}),d.results.push({...x,...P});break}}catch(E){let I=E instanceof Error?E.message:`${E}`,x=E instanceof R?E.reason:void 0;v.status="FAILED",v.message=I,v.finishedAt=new Date,v.afterUrl=i.browser.url();let P;try{P=await i.browser.screenshot({})}catch(W){l.debug({err:W},"Failed to take screenshot after AI command error, likely because the page is still loading. This is non-fatal.")}let D={id:g.id,status:"FAILED",startedAt:v.startedAt,finishedAt:v.finishedAt,type:"PRESET_ACTION",results:[v],message:I,failureReason:x,command:g};r.work.asyncTasks.push(an(v,D,w,P,c.onSaveScreenshot,l)),d.results.push(D),d.status="FAILED",d.finishedAt=new Date,d.message=I,d.failureReason=x;break}p++}}catch(h){d.message=h instanceof Error?h.message:`${h}`,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 Ap(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 Rp({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 Ap(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 Ip(r,e,t){Vn(r),e.toIndex&&e.toIndex>=t&&e.toIndex++}async function Dl(r){let{step:e}=r.conditionalParams,{logger:t}=r.fixtures,n=new Date,o=e.elseSteps,s=!0,i=[],a,l=Un();for(let m=0;m<e.blocks.length;m++){t.info(`Evaluating condition ${m} in conditional step`);let p=e.blocks[m];try{let h=await oo({...r,presetParams:{step:p.assertion}});i.push(h),t.info(`Condition ${m} resolved to true, executing the corresponding ${p.steps.length} steps`),s=!1,o=p.steps,a=h}catch(h){t.info({err:h},`Condition ${m} resolved to false`)}}if(o)s&&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:n,data:i[i.length-1]?.data,message:i[i.length-1]?.message,results:[],finishedAt:new Date,details:l.details};t.info(`Executing ${o.length} steps in the selected conditional block`);let c=await r.executeStepList({...r,listParams:{steps:o,containerName:"conditional block"}}),d={...e,assertion:a,...c,startedAt:n,finishedAt:new Date};return tt({asyncTasks:r.work.asyncTasks,nestedResults:[...i,...c.results],result:d,logger:t}),d}async function kl(r){let{step:e}=r.frameParams,{logger:t,controller:n}=r.fixtures,o=new Date,s=n.browser.getActiveFrame();n.browser.setActiveFrame(e.identifier);let i;try{i=await r.executeStepList({...r,listParams:{steps:e.steps,containerName:"frame step list"}})}finally{n.browser.setActiveFrame(s)}let l={...e,...i,startedAt:o,finishedAt:new Date};return tt({asyncTasks:r.work.asyncTasks,nestedResults:i.results,result:l,logger:t}),l}import{randomUUID as lo}from"crypto";import Pp from"fast-json-patch";import{cloneDeep as Lp}from"lodash-es";async function Fl(r){let e=r.failedResults,t=[],{sectionParams:n,fixtures:o,work:s,startingUrl:i,startingContextSnapshot:a}=r,{step:l}=n,{controller:c}=o,u=l?.autohealingConfig,d=u?.restartBehavior??{type:"GO_TO_SECTION_START"},m=u?.attempts??1;for(let p=0;p<m;p++){if(!e.terminalResult?.message)throw new Error("No error message in terminal result");let h=Lp(l.steps);await Promise.allSettled(s.asyncTasks??[]);let g=await c.runSectionAutohealing({results:e.results,errorMessage:e.terminalResult?.message,goal:l.description});for(let w of g.patches)h=Pp.applyOperation(h,w).newDocument;let f=se.fromSnapshot({snapshot:a,environmentVariables:o.context.getVariablesFromEnvironmentCopy()});await Op({controller:c,context:f,restartConfig:d,startingUrl:i});let S=await io(r.work,()=>r.executeStepList({...r,fixtures:{...r.fixtures,context:f},listParams:{steps:h,containerName:"auto-healed step list"}}));if(t.push(S.results),S.status==="SUCCESS")return{successfulHealing:{proposedStep:{...l,steps:h},listResult:S,context:f},healingAttempts:t};e=S}return{healingAttempts:t}}async function Op({controller:r,restartConfig:e,context:t,startingUrl:n}){switch(e.type){case"NAVIGATE_URL":{let o={id:lo(),type:"PRESET_ACTION",command:{id:lo(),type:"NAVIGATE",url:e.url}};await r.executePresetStep(null,o.command,t,!1);break}case"GO_TO_SECTION_START":{let o={id:lo(),type:"PRESET_ACTION",command:{id:lo(),type:"NAVIGATE",url:n}};await r.executePresetStep(null,o.command,t,!1);break}}}function Ul(r,e){switch(r||(r="ON_FAILURE"),r){case"ALWAYS":return!0;case"ON_FAILURE":return!0;case"ON_ACTION_FAILURE":return!(!e||e.type==="PRESET_ACTION"&&Ei(e.command.type))}}async function zl(r){let{step:e}=r.sectionParams,{logger:t,controller:n,context:o}=r.fixtures,s=new Date,i=n.browser.url(),a=o.toObjectCopy(),l=async()=>r.executeStepList({...r,listParams:{steps:e.steps,containerName:"section step list"}}),c=e.autohealingConfig?await io(r.work,l):await l(),u,d;if(c.status==="FAILED"&&e.autohealingConfig&&!r.work.healingDisabled&&Ul(e.autohealingConfig.trigger,c.terminalResult)){let p=await Fl({...r,startingContextSnapshot:a,startingUrl:i,failedResults:c});p.successfulHealing&&(u=p.successfulHealing.proposedStep,c=p.successfulHealing.listResult,r.fixtures.context=p.successfulHealing.context),d=p.healingAttempts}let m={...e,...c,startedAt:s,finishedAt:new Date,proposedStep:u,healingAttempts:d};return tt({asyncTasks:r.work.asyncTasks,nestedResults:c.results,result:m,logger:t}),m}async function qt(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=r.work,p=[],h="SUCCESS",g,f=0;for(f;f<n.length;f++){let S=n[f],w,b=cs(S),T=S.index;if(T===void 0)throw new Error(`Executing step without index: ${b}`);if(d&&T>d)break;if(c.isExecutionCancelled?.()){if(h="CANCELLED",l.onCancelled?.({index:T,output:{status:"CANCELLED",message:"Execution cancelled.",startedAt:new Date,finishedAt:new Date}}),e.length){let D=e[e.length-1];D.status="CANCELLED",D.message="Cancelled by user signal.",g=D}break}if(S.skipped)continue;if(u&&T<u&&(S.type==="PRESET_ACTION"||qn([S])<u))continue;o.info(`Executing step ${f+1}/${n.length} in ${t}: ${b}`),l.onStarted?.(T);let v=s.toRedactedDisplayCopy(),E=i.browser.url(),I,x;switch(S.type){case"PRESET_ACTION":{I="Preset action",x=await Kt(S,()=>oo({...r,presetParams:{step:S}}));break}case"AI_ACTION":{I="AI action",x=await Kt(S,()=>_l({...r,aiStepParams:{step:S},executeStepList:qt}));break}case"RESOLVED_MODULE":{I=`Module (${S.name})`;let D=new se({baseUrl:i.browser.baseUrl,currentUrl:i.browser.url(),dynamicVariables:s.getDynamicVariablesCopy(),variablesFromEnvironment:s.getVariablesFromEnvironmentCopy(),envName:s.getEnvName()});x=await Kt(S,async()=>{let W=await Ml(S,s,o,a);return Ol({...r,executeStepList:qt,fixtures:{...r.fixtures,context:D},moduleParams:{step:S,resolvedInputs:W}})});break}case"CONDITIONAL":{I="Conditional step",x=await Kt(S,()=>Dl({...r,conditionalParams:{step:S},executeStepList:qt}));break}case"IFRAME":{I="Frame step",x=await Kt(S,()=>kl({...r,frameParams:{step:S},executeStepList:qt}));break}case"SECTION":{I="Section";let D=await Kt(S,()=>zl({...r,sectionParams:{step:S},executeStepList:qt}));"proposedStep"in D&&D.proposedStep&&(w=D.proposedStep,D.proposedStep=void 0,m&&(m.autoHealed=!0)),x=D;break}default:return(W=>{throw"If Typescript complains about the line below, you missed a case or break in the switch above"})(S)}w?p.push(w):p.push(S),x.beforeUrl=x.beforeUrl??E,x.beforeTestContext=v,s.setResult(f,x.data),S.envKey&&s.setVariable(S.envKey,x.data);let P=i.browser.url();if(s.setCurrentUrl(P),x.afterUrl=x.afterUrl??P,x.afterTestContext=s.toRedactedDisplayCopy(),Np(I,T,x,r.callbacks,o,r.work),e.push(x),x.status!=="SUCCESS"){h=x.status,g=x;break}}return{status:h,results:e,terminalResult:g,proposedSteps:p}}async function Mp(r,e){r&&e?.({results:r.results})}function Np(r,e,t,n,o,s){let{step:i,test:a}=n,l=r.toLowerCase(),c=r.charAt(0).toUpperCase()+r.slice(1);switch(t.status){case"SUCCESS":i.onSuccess?.({index:e,step:"command"in t?t:void 0,message:t.message??`${c} executed successfully.`,output:Fn.parse(t)});break;case"FAILED":i.onFailure?.({index:e,message:t.message??`${c} failed.`,output:Fn.parse(t)});break;case"CANCELLED":i.onCancelled?.({index:e,message:t.message??`${c} cancelled.`,output:Fn.parse(t)});break;default:throw new Error(`Unexpected ${l} status: ${t.status}`)}t.status==="SUCCESS"&&s&&Mp(s,a.onUpdateRun)}var ln=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=Ll(r.fixtures.logger),Vn(r.inputs.steps);let t;try{return t=await _p(r),t}finally{if(clearInterval(e),za(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...")}}},_p=async r=>{let{runId:e,testMetadata:t,fromIndices:n,toIndices:o,indicesFilter:s,steps:i}=r.inputs,{logger:a,controller:l}=r.fixtures;a.info(`Starting run ${e} for test '${t.name}'`);let c=i,u="test";if(n){let S=Kn(i,n);if(!S)throw new Error(`Could not find starting step using indices: ${n}`);r.inputs.fromIndex=S.index,a.debug({fromIndices:n,fromStep:S},"Identified starting step using fromIndices"),u="partial steps list"}if(o){let S=Kn(i,o);if(!S)throw new Error(`Could not find step at indices: ${o}`);let w=qn([S]);r.inputs.toIndex=w,a.debug({toIndices:o,toStep:S,maxIndexUnderToStep:w},"Identified ending step using toIndices"),u="partial steps list"}if(s){let S=Kn(i,s);if(!S)throw new Error(`Could not find ending step at indices: ${r.inputs.indicesFilter}`);c=[S],a.debug({steps:i,indicesFilter:s},"Filtered steps to run based on exact indices filter"),u="filtered step"}let d=[],m={results:d,healingDisabled:!!s||!!n||!!o||void 0,asyncTasks:[]},{status:p,terminalResult:h,proposedSteps:g}=await qt({...r,work:m,listParams:{steps:c,containerName:u,results:d}});if(r.options.takeScreenshots&&await Promise.allSettled(m.asyncTasks),s&&d.length){let S=d[0];if(S.beforeTestContext&&S.afterTestContext){let w=se.fromSnapshot({snapshot:S.beforeTestContext,environmentVariables:r.fixtures.context.getVariablesFromEnvironmentCopy()}),b=r.fixtures.context.getResult(0);w.setResult(s[s.length-1],b),S.afterTestContext={...S.afterTestContext,results:w.getResultsCopy()}}}let f;return r.options.consumeDebuggingData&&(f={logsPerPage:Ua(l.browser.retrieveAndClearConsoleLogs())}),r.callbacks.test.onUpdateRun?.({results:d,debugData:f}),p==="FAILED"?{status:"FAILED",results:d,failedStepResult:h}:(g&&m.autoHealed&&await r.callbacks.test.onProposedTestSteps?.({testId:t.id,orgId:r.inputs.orgId,runId:r.inputs.runId,steps:g}),{status:"PASSED",results:d})};import{cloneDeep as kp}from"lodash-es";var Es={currentlyExecutingRequests:{}},Fp=r=>async(e,t)=>{let n,{testId:o}=r.metadata,{baseUrl:s}=e,i=`${o}|${s}`;try{let a=Es.currentlyExecutingRequests[i]??0;Es.currentlyExecutingRequests[i]=a+1,n=await Up({...r,...e,done:t})}finally{r.logger.info({result:n,sessionId:r.metadata.sessionId},"Test execution complete"),Es.currentlyExecutingRequests[i]--}},Up=async({socket:r,steps:e,baseUrl:t,testMetadata:n,reInitialize:o,indicesFilter:s,toIndices:i,fromIndices:a,storage:l,metadata:c,logger:u,envName:d,environmentVariables:m,testInputs:p,authorization:h,done:g})=>{let{testId:f,sessionId:S,orgId:w}=c,b=S,T=_.getSession(S);if(!T)throw new Error("No active session found");_.resumeExecution(S);let{controller:v,context:E}=T;v.setOpen();let I=h?.type==="API_KEY"?new pt(h):void 0;u=u.child({testId:f,orgId:w,baseUrl:t,sessionId:S,runId:b}),u.info({steps:e.map(G=>`${G.type}${"command"in G?` - ${G.command.type}`:""}`),indicesFilter:s,fromIndices:a,toIndices:i,reInitialize:o,envName:d,baseUrl:t},"Starting execution"),u.debug({steps:e,context:E,flags:v.flagStore.getAllFlags()},"Execution parameters");let x=m??{};await Promise.all((n.parameters??[]).map(async G=>{let st=(p??{})[G.name]??G.defaultValue;if(st===void 0)return;let Dt=await We({s:st,context:se.dummyContext(d),logger:u,localTools:I});x[G.name]=Dt}));let P=async()=>{if(o){let G={url:t,clearCookies:!0,clearStorage:!0};await v.resetState(G),v.setOpen(),E.reset({baseUrl:t,currentUrl:v.browser.url(),variablesFromEnvironment:x,envName:d})}},D=async()=>{try{await l.resolveStepCacheEntries({schemaVersion:Pe,organizationId:w,testId:f,steps:e,logger:u})}catch(G){u.error({err:G},"Failed to fetch step cache entries from Momentic server. This can drastically reduce test reliability and performance.")}};await Promise.all([P(),D()]);let W=kp(e),A={takeScreenshots:!1,consumeDebuggingData:!1},H={orgId:w,runId:b,testMetadata:n,steps:e,indicesFilter:s,fromIndices:a,toIndices:i},J={controller:v,context:E,storage:l,codeEvalTools:I,logger:u},Z=(G,st)=>{r.emit(st,G)},At={test:{onTestComplete:async()=>{r.emit("finished")},onSaveScreenshot:zp,isExecutionCancelled:()=>_.getSession(S)?.executionCancelled||v.browser.closed||v.isClosed()||r.disconnected,onTestSuccess:async G=>{let st=Dp(W,G);if(Object.keys(st).length>0){u.debug({changes:st},"Updating steps post-run success");let{cachesToSave:Dt}=await et({steps:e,cacheCreationParams:{testId:f,orgId:w}});try{await l.saveStepCacheEntries(Dt,n.id,u)}catch(N){u.warn({err:N},"Failed to save step cache entries after execution success")}}}},step:{onStarted:G=>r.emit("started",{globalIndex:G}),onSuccess:G=>Z(G,"success"),onFailure:G=>Z(G,"failure"),onCancelled:G=>Z(G,"cancelled"),onCommandGenerated:G=>{r.emit("commandGenerated",{...G,message:G.message??"AI action sub-step generated"})},onCommandExecuted:G=>{r.emit("commandExecuted",G)}}};if(s?.length){u.info({indicesFilter:s},"Starting individual step");let G=T.resultsManager.getContextCopyAtIndices(s)??E.toObjectCopy(),st=se.fromSnapshot({snapshot:G,environmentVariables:E.getVariablesFromEnvironmentCopy()}),Dt=await ln({fixtures:{...J,context:st},options:A,callbacks:At,inputs:H}),N=Dt.results[0];return N?T.resultsManager.setIndividualResult(N,s):u.warn(Dt,"No result found for individual step"),Dt.status}let er=await ln({fixtures:J,options:A,callbacks:At,inputs:H});return T.resultsManager.setResults(er.results),g?.(er),er.status},zp=async r=>r.toString("base64");var $l={event:"execute",createHandler:Fp};var $p=({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=Jr(i,o.description);e.debug({description:u,params:o},"Locate handler params"),e.info({description:u},"Locate handler called");let d=_.getSession(n);if(!d)throw new Error("No active session found");let{controller:m,context:p}=d,h=d.resultsManager.getContextCopyAtIndices(c)??p.toObjectCopy(),g=se.fromSnapshot({snapshot:h,environmentVariables:p.getVariablesFromEnvironmentCopy()}),f=ar.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 ut?b.decisions:void 0});return}else try{let b=await m.locateElement({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:T,height:v}=await m.screenshotWithDimensions({scale:"css",clearHighlights:!0,target:S?.target,hideCaret:!0}),E=await t.uploadScreenshot(b);S.screenshot={data:E,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([m.browser.scrollIntoView(w),m.browser.highlightTarget(w)])}catch(b){e.warn({err:b},"Error highlighting element, continuing...")}}},Bl={event:"locate",createHandler:$p};var Bp=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async({percentX:n,percentY:o},s)=>{let i=_.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})}}},Hl={event:"cloudClick",createHandler:Bp};var Hp=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async(n,o)=>{let s=_.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}}},Wl={event:"recordTargetClick",createHandler:Hp};var Wp=({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=_.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")}}}},Gl={event:"cloudMouseMove",createHandler:Wp};var Gp=({metadata:r})=>{let{sessionId:e}=r;return async({percentDeltaX:t,percentDeltaY:n})=>{let o=_.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()})}},jl={event:"cloudScroll",createHandler:Gp};var jp=({metadata:r,generator:e,socket:t,storage:n,logger:o})=>{let{sessionId:s,orgId:i,testId:a}=r;return async({indices:l})=>{let c=_.getSession(s);if(!c)throw new Error("No active session found");let{controller:u,browserBehavior:d}=c;o.info("Starting cloud recording");let m=await u.startRecordMode({generator:e,initialIndices:l,storage:n,logger:o,testId:a,orgId:i,onStepRecord:(p,h)=>{t.emit("stepRecorded",{step:p,indices:h})}});d.recordingState={transformer:m},d.showOverlay=!0}},Vl={event:"cloudStartRecording",createHandler:jp};var Vp=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async()=>{let 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}},Kl={event:"cloudStopRecording",createHandler:Vp};var Kp=["Dead","Meta","AudioVolumeUp","AudioVolumeDown"],qp=({metadata:r,logger:e})=>{let{sessionId:t}=r;return async({key:n})=>{let o=_.getSession(t);if(!o)throw new Error("No active session found");if(Kp.includes(n))return;let{controller:s}=o;if(s.browser.closed||s.browser.getActivePage().isClosed()){e.debug({sessionId:t},"Browser is closed, ignoring typing action");return}n.length>1?await s.browser.press(n):await s.browser.type(n,{clearContent:!1,pressKeysSequentially:!0})}},ql={event:"cloudType",createHandler:qp};var cn={vimiumJs:'var K=Object.defineProperty;var P=Object.getOwnPropertySymbols;var z=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable;var F=(t,e,n)=>e in t?K(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,D=(t,e)=>{for(var n in e||(e={}))z.call(e,n)&&F(t,n,e[n]);if(P)for(var n of P(e))B.call(e,n)&&F(t,n,e[n]);return t};var g=(t,e,n)=>(F(t,typeof e!="symbol"?e+"":e,n),n);var _=(t,e,n)=>new Promise((o,r)=>{var i=s=>{try{d(n.next(s))}catch(l){r(l)}},a=s=>{try{d(n.throw(s))}catch(l){r(l)}},d=s=>s.done?o(s.value):Promise.resolve(s.value).then(i,a);d((n=n.apply(t,e)).next())});var E=t=>function(e){return e&&e.isTrusted?t.apply(this,arguments):!0};globalThis.forTrusted==null&&(globalThis.forTrusted=E);var k={create(t,e,n,o){return{bottom:o,top:e,left:t,right:n,width:n-t,height:o-e}},copy(t){return{bottom:t.bottom,top:t.top,left:t.left,right:t.right,width:t.width,height:t.height}},translate(t,e,n){return e==null&&(e=0),n==null&&(n=0),{bottom:t.bottom+n,top:t.top+n,left:t.left+e,right:t.right+e,width:t.width,height:t.height}},subtract(t,e){return e=this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom)),e.width<0||e.height<0?[k.copy(t)]:[this.create(t.left,t.top,e.left,e.top),this.create(e.left,t.top,e.right,e.top),this.create(e.right,t.top,t.right,e.top),this.create(t.left,e.top,e.left,e.bottom),this.create(e.right,e.top,t.right,e.bottom),this.create(t.left,e.bottom,e.left,t.bottom),this.create(e.left,e.bottom,e.right,t.bottom),this.create(e.right,e.bottom,t.right,t.bottom)].filter(o=>o.height>0&&o.width>0)},intersects(t,e){return t.right>e.left&&t.left<e.right&&t.bottom>e.top&&t.top<e.bottom},intersectsStrict(t,e){return t.right>=e.left&&t.left<=e.right&&t.bottom>=e.top&&t.top<=e.bottom},equals(t,e){for(let n of["top","bottom","left","right","width","height"])if(t[n]!==e[n])return!1;return!0},intersect(t,e){return this.create(Math.max(t.left,e.left),Math.max(t.top,e.top),Math.min(t.right,e.right),Math.min(t.bottom,e.bottom))}};var N={_browserInfoLoaded:!0,_firefoxVersion:null,_isFirefox:!1,isFirefox(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._isFirefox},firefoxVersion(){if(!this._browserInfoLoaded)throw Error("browserInfo has not yet loaded.");return this._firefoxVersion},isString(t){return typeof t=="string"||t instanceof String}};var f={isReady(){return document.readyState!=="loading"},documentReady:function(){let t=document.readyState!=="loading",e=[];if(!t){let n;globalThis.addEventListener("DOMContentLoaded",n=E(function(){globalThis.removeEventListener("DOMContentLoaded",n,!0),t=!0;for(let o of e)o();e=null}),!0)}return function(n){if(t)return n();e.push(n)}}(),documentComplete:function(){let t=document.readyState==="complete",e=[];if(!t){let n;globalThis.addEventListener("load",n=E(function(o){if(o.target===document){globalThis.removeEventListener("load",n,!0),t=!0;for(let r of e)r();e=null}}),!0)}return function(n){t?n():e.push(n)}}(),createElement(t){let e=document.createElement(t);return e instanceof HTMLElement?(this.createElement=n=>document.createElement(n),e):(this.createElement=n=>document.createElementNS("http://www.w3.org/1999/xhtml",n),this.createElement(t))},addElementsToPage(t,e){let n=this.createElement("div");e.id!=null&&(n.id=e.id),e.className!=null&&(n.className=e.className);for(let o of t)n.appendChild(o);return document.body.appendChild(n),n},removeElement(t){return t.parentNode.removeChild(t)},isTopFrame(){return globalThis.top===globalThis.self},makeXPath(t){let e=[];for(let n of t)e.push(".//"+n,".//xhtml:"+n);return e.join(" | ")},evaluateXPath(t,e){let n=document.webkitIsFullScreen?document.webkitFullscreenElement:document.documentElement,o=function(r){return r==="xhtml"?"http://www.w3.org/1999/xhtml":null};return document.evaluate(t,n,o,e,null)},getVisibleClientRect(t,e){let n;e==null&&(e=!1);let o=(()=>{let i=[];for(n of t.getClientRects())i.push(k.copy(n));return i})(),r=function(){let i=window.getComputedStyle(t,null),a=i.getPropertyValue("display").indexOf("inline")===0&&i.getPropertyValue("font-size")==="0px";return r=()=>a,a};for(n of o){let i;if((n.width===0||n.height===0)&&e)for(let a of Array.from(t.children)){i=window.getComputedStyle(a,null);let d=i.getPropertyValue("position");if(i.getPropertyValue("float")==="none"&&!["absolute","fixed"].includes(d)&&!(n.height===0&&r()&&i.getPropertyValue("display").indexOf("inline")===0))continue;let s=this.getVisibleClientRect(a,!0);if(!(s===null||s.width<3||s.height<3))return s}else{if(n=this.cropRectToVisible(n),n===null||n.width<3||n.height<3||(i=window.getComputedStyle(t,null),i.getPropertyValue("visibility")!=="visible"))continue;return n}}return null},cropRectToVisible(t){let e=k.create(Math.max(t.left,0),Math.max(t.top,0),t.right,t.bottom);return e.top>=window.innerHeight-4||e.left>=window.innerWidth-4?null:e},getClientRectsForAreas(t,e){let n=[];for(let o of e){let r,i,a,d,s=o.coords.split(",").map(p=>parseInt(p,10)),l=o.shape.toLowerCase();if(["rect","rectangle"].includes(l))s.length==4&&([r,a,i,d]=s);else if(["circle","circ"].includes(l)){if(s.length==3){let[p,w,v]=s,u=v/Math.sqrt(2);r=p-u,i=p+u,a=w-u,d=w+u}}else l==="default"?s.length==2&&([r,a,i,d]=[0,0,t.width,t.height]):s.length>=4&&([r,a,i,d]=s);let c=k.translate(k.create(r,a,i,d),t.left,t.top);c=this.cropRectToVisible(c),c&&!isNaN(c.top)&&!isNaN(c.left)&&!isNaN(c.width)&&!isNaN(c.height)&&n.push({element:o,rect:c})}return n},isSelectable(t){if(!(t instanceof Element))return!1;let e=["button","checkbox","color","file","hidden","image","radio","reset","submit"];return t.nodeName.toLowerCase()==="input"&&e.indexOf(t.type)===-1||t.nodeName.toLowerCase()==="textarea"||t.isContentEditable},isEditable(t){return this.isSelectable(t)||(t.nodeName!=null?t.nodeName.toLowerCase():void 0)==="select"},isEmbed(t){let e=t.nodeName!=null?t.nodeName.toLowerCase():null;return["embed","object"].includes(e)},isFocusable(t){return t&&(this.isEditable(t)||this.isEmbed(t))},isDOMDescendant(t,e){let n=e;for(;n!==null;){if(n===t)return!0;n=n.parentNode}return!1},isSelected(t){let e=document.getSelection();if(t.isContentEditable){let n=e.anchorNode;return n&&this.isDOMDescendant(t,n)}else if(f.getSelectionType(e)==="Range"&&e.isCollapsed){let n=e.anchorNode.childNodes[e.anchorOffset];return t===n}else return!1},simulateSelect(t){if(t===document.activeElement&&f.isEditable(document.activeElement))return handlerStack.bubbleEvent("click",{target:t});if(t.focus(),t.tagName.toLowerCase()!=="textarea"||t.value.indexOf(`\n`)<0)try{if(t.selectionStart===0&&t.selectionEnd===0)return t.setSelectionRange(t.value.length,t.value.length)}catch(e){}},simulateClick(t,e){e==null&&(e={});let n=["mouseover","mousedown","mouseup","click"],o=[];for(let r of n){let i=this.simulateMouseEvent(r,t,e);o.push(i)}return o},simulateMouseEvent(t,e,n){if(n==null&&(n={}),t==="mouseout"){if(e==null&&(e=this.lastHoveredElement),this.lastHoveredElement=void 0,e==null)return}else t==="mouseover"&&(this.simulateMouseEvent("mouseout",void 0,n),this.lastHoveredElement=e);let o=new MouseEvent(t,{bubbles:!0,cancelable:!0,composed:!0,view:window,detail:1,ctrlKey:n.ctrlKey,altKey:n.altKey,shiftKey:n.shiftKey,metaKey:n.metaKey});return e.dispatchEvent(o)},simulateClickDefaultAction(t,e){let n;if(e==null&&(e={}),(t.tagName!=null?t.tagName.toLowerCase():void 0)!=="a"||!t.href)return;let{ctrlKey:o,shiftKey:r,metaKey:i,altKey:a}=e;KeyboardUtils.platform==="Mac"?n=i===!0&&o===!1:n=i===!1&&o===!0,n?chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:r===!0}):r===!0&&i===!1&&o===!1&&a===!1?chrome.runtime.sendMessage({handler:"openUrlInNewWindow",url:t.href}):t.target==="_blank"&&chrome.runtime.sendMessage({handler:"openUrlInNewTab",url:t.href,active:!0})},simulateHover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseover",t,e)},simulateUnhover(t,e){return e==null&&(e={}),this.simulateMouseEvent("mouseout",t,e)},addFlashRect(t){let e=this.createElement("div");return e.classList.add("vimiumReset"),e.classList.add("vimiumFlash"),e.style.left=t.left+"px",e.style.top=t.top+"px",e.style.width=t.width+"px",e.style.height=t.height+"px",document.documentElement.appendChild(e),e},getViewportTopLeft(){let t=document.documentElement,e=getComputedStyle(t),n=t.getBoundingClientRect();if(e.position==="static"&&!/content|paint|strict/.test(e.contain||"")){let o=parseInt(e.marginTop),r=parseInt(e.marginLeft);return{top:-n.top+o,left:-n.left+r}}else{let o,r;return N.isFirefox()?(r=parseInt(e.borderTopWidth),o=parseInt(e.borderLeftWidth)):{clientTop:r,clientLeft:o}=t,{top:-n.top-r,left:-n.left-o}}},suppressPropagation(t){t.stopImmediatePropagation()},suppressEvent(t){t.preventDefault(),this.suppressPropagation(t)},consumeKeyup:function(){let t=null;return function(e,n=null,o){if(!e.repeat){t!=null&&handlerStack.remove(t);let{code:r}=e;t=handlerStack.push({_name:"dom_utils/consumeKeyup",keyup(i){return i.code!==r||(this.remove(),o?f.suppressPropagation(i):f.suppressEvent(i)),handlerStack.continueBubbling},blur(i){return i.target===window&&this.remove(),handlerStack.continueBubbling}})}return typeof n=="function"&&n(),o?(f.suppressPropagation(e),handlerStack.suppressPropagation):(f.suppressEvent(e),handlerStack.suppressEvent)}}(),getSelectionType(t){return t==null&&(t=document.getSelection()),t.type?t.type:t.rangeCount===0?"None":t.isCollapsed?"Caret":"Range"},getElementWithFocus(t,e){let n,o=n=t.getRangeAt(0);f.getSelectionType(t)==="Range"&&(o=n.cloneRange(),o.collapse(e)),n=o.startContainer,n.nodeType===1&&(n=n.childNodes[o.startOffset]);let r=n;for(;r&&r.nodeType!==1;)r=r.previousSibling;return n=r||(n!=null?n.parentNode:void 0),n},getSelectionFocusElement(){let t=window.getSelection(),e=t.focusNode;return e==null?null:(e===t.anchorNode&&t.focusOffset===t.anchorOffset&&(e=e.childNodes[t.focusOffset]||e),e.nodeType!==Node.ELEMENT_NODE?e.parentElement:e)},getContainingElement(t){return(typeof t.getDestinationInsertionPoints=="function"?t.getDestinationInsertionPoints()[0]:void 0)||t.parentElement},windowIsTooSmall(){return window.innerWidth<3||window.innerHeight<3},injectUserCss(){let t=document.createElement("style");t.type="text/css",t.textContent=Settings.get("userDefinedLinkHintCss"),document.head.appendChild(t)}};var O={MAX_CONTENT_LENGTH:1e3,MAX_ATTRIBUTE_LENGTH:500,MAX_NUM_DATA_ATTRIBUTES:10,commonAttributes:["id","className","title","aria-label","aria-labelledby"],attributeNamesMapping:new Map([["a",["href","title","rel","target"]],["label",["for"]],["input",["type","name","placeholder","checked","maximumLength"]],["textarea",["placeholder","maximumLength"]],["button",["type"]],["select",["name","multiple"]],["div",["role"]],["iframe",["src"]],["img",["src","alt"]]]),describe(t){var r,i;let e={};this.addAttributes(t,this.commonAttributes,e);let n=((i=(r=t.tagName).toLowerCase)==null?void 0:i.call(r))||"";this.attributeNamesMapping.has(n)&&this.addAttributes(t,this.attributeNamesMapping.get(n),e),this.addDataAttrs(t,e);let o=this.getContent(t);return this.additionalHandling(t,D({tag:n,attributes:e},o&&{content:o}))},getContent(t){var n,o;let e=((o=(n=t.tagName).toLowerCase)==null?void 0:o.call(n))||"";return["input","textarea"].includes(e)?t.value:["div","iframe","img","body"].includes(e)?null:(["a","button","select","label"].includes(e),t.innerText)},additionalHandling(t,e){var o,r;if((((r=(o=t.tagName).toLowerCase)==null?void 0:r.call(o))||"")=="label"&&t.hasAttribute("for")){let i=t.getAttribute("for"),a=document.getElementById(i);a&&(e.target=this.describe(a))}return e},addAttributes(t,e,n){n||(n={});for(let o of e)t.hasAttribute(o)&&(n[o]=t.getAttribute(o).substring(0,this.MAX_ATTRIBUTE_LENGTH));return n},addDataAttrs(t,e){let n=0;for(let o in t.dataset)if(e[`data-${o}`]=t.dataset[o].substring(0,this.MAX_ATTRIBUTE_LENGTH),n++,n>this.MAX_NUM_DATA_ATTRIBUTES)return e;return e}};var x=null,C=()=>G()||document.scrollingElement||document.body,W=function(t){return t?t<0?-1:1:0},U={x:{axisName:"scrollLeft",max:"scrollWidth",viewSize:"clientWidth"},y:{axisName:"scrollTop",max:"scrollHeight",viewSize:"clientHeight"}},X=function(t,e,n){if(N.isString(n)){let o=n;return o==="viewSize"&&t===C()?e==="x"?window.innerWidth:window.innerHeight:t[U[e][o]]}else return n},V=function(t,e,n){let o=U[e].axisName,r=t[o];if(t.scrollBy){let i={behavior:"instant"};i[e==="x"?"left":"top"]=n,t.scrollBy(i)}else t[o]+=n;return t[o]!==r},q=function(t,e){let n=window.getComputedStyle(t);return!(n.getPropertyValue(`overflow-${e}`)==="hidden"||["hidden","collapse"].includes(n.getPropertyValue("visibility"))||n.getPropertyValue("display")==="none")},T=function(t,e,n,o){let r=o*X(t,e,n)||-1;return r=W(r),V(t,e,r)&&V(t,e,-r)},$=function(t,e,n,o){return e==null&&(e="y"),n==null&&(n=1),o==null&&(o=1),T(t,e,n,o)&&q(t,e)},j=function(t=null){let e;if(!t){let n=C();if(T(n,"y",1,1)||T(n,"y",-1,1))return n;t=document.body||C()}if(T(t,"y",1,1)||T(t,"y",-1,1))return t;{let n=Array.from(t.children).map(o=>({element:o,rect:f.getVisibleClientRect(o)})).filter(o=>o.rect);n.map(o=>o.area=o.rect.width*o.rect.height);for(e of n.sort((o,r)=>r.area-o.area)){let o=j(e.element);if(o)return o}return null}},L={init(){x=null},isScrollableElement(t){return x||(x=C()&&j()||C()),t!==x&&$(t)}},G=function(){let t=J[window.location.host];if(t)return document.querySelector(t)},J={"twitter.com":"div.permalink-container div.permalink[role=main]","reddit.com":"#overlayScrollContainer","new.reddit.com":"#overlayScrollContainer","www.reddit.com":"#overlayScrollContainer","web.telegram.org":".MessageList"};window.Scroller=L;var A=function(){let t=null;return f.documentReady(()=>t=document.hasFocus()),globalThis.addEventListener("focus",E(function(e){return e.target===window&&(t=!0),!0}),!0),globalThis.addEventListener("blur",E(function(e){return e.target===window&&(t=!1),!0}),!0),()=>t}();Object.assign(globalThis,{windowIsFocused:A});var R=class{constructor(e){g(this,"element");g(this,"image");g(this,"rect");g(this,"linkText");g(this,"showLinkText");g(this,"reason");g(this,"secondClassCitizen");g(this,"possibleFalsePositive");Object.seal(this),e&&Object.assign(this,e)}},M={getLocalHintsForElement(t){var p,w,v;let e=((w=(p=t.tagName).toLowerCase)==null?void 0:w.call(p))||"",n=!1,o=!1,r=!1,i=[],a=[],d=null;if(e==="img"){let u=t.getAttribute("usemap");if(u){let h=t.getClientRects();u=u.replace(/^#/,"").replace(\'"\',\'\\\\"\');let m=document.querySelector(`map[name="${u}"]`);if(m&&h.length>0){n=!0;let y=m.getElementsByTagName("area"),S=f.getClientRectsForAreas(h[0],y);S=S.map(I=>Object.assign(I,{image:t})),a.push(...S)}}}let s=t.getAttribute("aria-disabled");if(s&&["","true"].includes(s.toLowerCase()))return[];if(this.checkForAngularJs||(this.checkForAngularJs=function(){if(document.getElementsByClassName("ng-scope").length===0)return()=>!1;{let h=[];for(let m of["","data-","x-"])for(let y of["-",":","_"])h.push(`${m}ng${y}click`);return function(m){for(let y of h)if(m.hasAttribute(y))return!0;return!1}}}()),n||(n=this.checkForAngularJs(t)),t.hasAttribute("onclick"))n=!0;else{let u=t.getAttribute("role"),h=["button","tab","link","checkbox","menuitem","menuitemcheckbox","menuitemradio","radio"];if(u!=null&&h.includes(u.toLowerCase()))n=!0;else{let m=t.getAttribute("contentEditable");m!=null&&["","contenteditable","true","plaintext-only"].includes(m.toLowerCase())&&(n=!0)}}if(!n&&t.hasAttribute("jsaction")){let u=t.getAttribute("jsaction").split(";");for(let h of u){let m=h.trim().split(":");if(m.length>=1&&m.length<=2){let[y,S,I]=m.length===1?["click",...m[0].trim().split("."),"_"]:[m[0],...m[1].trim().split("."),"_"];n||(n=y==="click"&&S!=="none"&&I!=="_")}}}switch(e){case"a":n=!0;break;case"textarea":n||(n=!t.disabled&&!t.readOnly);break;case"input":n||(n=!(((v=t.getAttribute("type"))==null?void 0:v.toLowerCase())=="hidden"||t.disabled||t.readOnly&&f.isSelectable(t)));break;case"button":case"select":n||(n=!t.disabled);break;case"object":case"embed":n=!0;break;case"label":n||(n=t.control!=null&&!t.control.disabled&&this.getLocalHintsForElement(t.control).length===0);break;case"body":n||(n=t===document.body&&!A()&&window.innerWidth>3&&window.innerHeight>3&&(document.body!=null?document.body.tagName.toLowerCase():void 0)!=="frameset"?d="Frame.":void 0),n||(n=t===document.body&&A()&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"img":n||(n=["zoom-in","zoom-out"].includes(t.style.cursor));break;case"div":case"ol":case"ul":n||(n=t.clientHeight<t.scrollHeight&&L.isScrollableElement(t)?d="Scroll.":void 0);break;case"details":n=!0,d="Open.";break}let l=t.getAttribute("class");!n&&(l!=null&&l.toLowerCase().includes("button"))&&(n=!0,r=!0);let c=t.getAttribute("tabindex"),b=c?parseInt(c):-1;if(!n&&!(b<0)&&!isNaN(b)&&(n=!0,o=!0),n)if(a.length>0){let u=a.map(h=>new R({element:h.element,image:t,rect:h.rect,secondClassCitizen:o,possibleFalsePositive:r,reason:d}));i.push(...u)}else{let u=f.getVisibleClientRect(t,!0);if(u!==null){let h=new R({element:t,rect:u,secondClassCitizen:o,possibleFalsePositive:r,reason:d});i.push(h)}}return i},getElementFromPoint(t,e,n,o){n==null&&(n=document),o==null&&(o=[]);let r=n.elementsFromPoint?n.elementsFromPoint(t,e)[0]:n.elementFromPoint(t,e);return o.includes(r)?r:(o.push(r),r&&r.shadowRoot?M.getElementFromPoint(t,e,r.shadowRoot,o):r)},getLocalHints(t){if(!document.body)return[];let e=(s,l)=>{l==null&&(l=[]);for(let c of Array.from(s.querySelectorAll("*")))l.push(c),c.shadowRoot&&e(c.shadowRoot,l);return l},n=e(document.body),o=[];for(let s of Array.from(n))if(!t||s.href){let l=this.getLocalHintsForElement(s);o.push(...l)}o=o.reverse();let r=[1,2,3];o=o.filter((s,l)=>{if(!s.possibleFalsePositive)return!0;let b=Math.max(0,l-6);for(;b<l;){let p=o[b].element;for(let w of r)if(p=p==null?void 0:p.parentElement,p===s.element)return!1;b+=1}return!0});let i=o.filter(s=>{if(s.secondClassCitizen)return!1;let l=s.rect,c=M.getElementFromPoint(l.left+l.width*.5,l.top+l.height*.5);if(c&&(s.element.contains(c)||c.contains(s.element))||s.element.localName=="area"&&c==s.image)return!0;let p=[l.top+.1,l.bottom-.1],w=[l.left+.1,l.right-.1];for(let v of p)for(let u of w){let h=M.getElementFromPoint(u,v);if(h&&(s.element.contains(h)||h.contains(s.element)))return!0}});i.reverse();let{top:a,left:d}=f.getViewportTopLeft();for(let s of i)s.rect.top+=a,s.rect.left+=d;return i}};var H=class{constructor(){this.hints=null;this.hintMarkers=null;this.markersDiv=null;this.enrichedMarkers=null}reset(){this.removeMarkers(),this.hints=null,this.hintMarkers=null,this.markersDiv=null}capture(){return _(this,null,function*(){this.reset(),this.createMarkers(),this.displayMarkers()})}createMarkers(){this.hints=M.getLocalHints(),this.hintMarkers=new Map,this.hints.forEach((e,n)=>{var i,a;let o=f.createElement("div"),r=(a=(i=e.element.attributes["data-momentic-id"])==null?void 0:i.value)!=null?a:void 0;if(!r){console.warn(`[MOMENTIC] No data-momentic-id found for interactive element ${e.element.outerHTML}`);return}o.style.left=e.rect.left+"px",o.style.top=e.rect.top+"px",o.style.zIndex=214e7+n,o.className="vimiumReset internalVimiumHintMarker vimiumHintMarker",Z(o,r),this.hintMarkers.set(r,{hint:e,marker:o})})}enrichMarkers(){if(this.hintMarkers){this.enrichedMarkers=[];for(let[e,n]of this.hintMarkers)this.enrichedMarkers.push(Object.assign(O.describe(n.hint.element),{hintString:e}))}}displayMarkers(){this.hintMarkers&&(this.markersDiv||(this.markersDiv=f.addElementsToPage(Array.from(this.hintMarkers.values()).map(e=>e.marker),{id:"vimiumHintMarkerContainer",className:"vimiumReset"})))}removeMarkers(){this.markersDiv&&(f.removeElement(this.markersDiv),this.markersDiv=null)}toggleMarkers(){this.markersDiv?this.removeMarkers():this.displayMarkers()}},Z=(t,e)=>{for(let n of e){let o=document.createElement("span");o.className="vimiumReset",o.textContent=n,t.appendChild(o)}};window.HintManager=H;\n',vimiumCss:'.vimiumReset,a.vimiumReset,a:hover.vimiumReset,a:link.vimiumReset,a:visited.vimiumReset,div.vimiumReset,span.vimiumReset,table.vimiumReset,td.vimiumReset,tr.vimiumReset{background:none;border:none;bottom:auto;box-shadow:none;color:#000;cursor:auto;display:inline;float:none;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:inherit;font-style:normal;font-variant:normal;font-weight:400;height:auto;left:auto;letter-spacing:0;line-height:100%;margin:0;max-height:none;max-width:none;min-height:0;min-width:0;opacity:1;padding:0;position:static;right:auto;text-align:left;text-decoration:none;text-indent:0;text-shadow:none;text-transform:none;top:auto;vertical-align:baseline;white-space:normal;width:auto;z-index:2140000000}tbody.vimiumReset,thead.vimiumReset{display:table-header-group}tbody.vimiumReset{display:table-row-group}div.internalVimiumHintMarker{background:linear-gradient(180deg,#fff785 0,#ffc542);border:1px solid #c38a22;border-radius:3px;box-shadow:0 3px 7px 0 rgba(0,0,0,.3);display:block;font-size:11px;left:-1px;overflow:hidden;padding:1px 3px 0;position:absolute;top:-1px;white-space:nowrap}div.internalVimiumHintMarker span{color:#302505;font-family:Helvetica,Arial,sans-serif;font-size:11px;font-weight:700;text-shadow:0 1px 0 hsla(0,0%,100%,.6)}div.internalVimiumHintMarker>.matchingCharacter{color:#d4ac3a}div>.vimiumActiveHintMarker span{color:#a07555!important}div.internalVimiumInputHint{background-color:rgba(255,247,133,.3);border:1px solid #c38a22;display:block;pointer-events:none;position:absolute}div.internalVimiumSelectedInputHint{background-color:hsla(0,100%,70%,.3);border:1px solid #933!important}div.internalVimiumSelectedInputHint span{color:#fff!important}div.vimiumHighlightedFrame{border:5px solid #ff0;box-sizing:border-box;margin:0;pointer-events:none}div.vimiumHighlightedFrame,iframe.vimiumHelpDialogFrame{height:100%;left:0;padding:0;position:fixed;top:0;width:100%}iframe.vimiumHelpDialogFrame{background-color:hsla(0,0%,4%,.6);border:none;display:block;z-index:2139999997}div#vimiumHelpDialogContainer{background-color:#fff;border:2px solid #b3b3b3;border-radius:6px;margin:50px auto;max-height:calc(100% - 100px);max-width:calc(100% - 100px);opacity:1;overflow-x:auto;overflow-y:auto;width:840px}div#vimiumHelpDialog{min-width:600px;padding:8px 12px}span#vimiumTitle,span#vimiumTitle *,span#vimiumTitle span{font-size:20px}#vimiumTitle{display:block;line-height:130%;white-space:nowrap}td.vimiumHelpDialogTopButtons{text-align:right;width:100%}#helpDialogOptionsPage,#helpDialogWikiPage{font-size:14px;padding-left:5px;padding-right:5px}div.vimiumColumn{float:left;font-size:11px;line-height:130%;width:50%}div.vimiumColumn tr{display:table-row}div.vimiumColumn td{display:table-cell;font-size:11px;line-height:130%}div.vimiumColumn table,div.vimiumColumn td,div.vimiumColumn tr{margin:0;padding:0}div.vimiumColumn table{table-layout:auto;width:100%}div.vimiumColumn td{padding:1px;vertical-align:top}div#vimiumHelpDialog div.vimiumColumn tr>td:first-of-type{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;text-align:right;white-space:nowrap}span.vimiumHelpDialogKey{background-color:#f3f3f3;border:1px solid;border-color:#ccc #ccc #bbb;border-radius:3px;box-shadow:inset 0 -1px 0 #bbb;color:#212121;font-family:monospace;font-size:11px;margin-left:2px;padding:1px 4px}div#vimiumHelpDialog div.vimiumColumn tr>td:nth-of-type(3){width:100%}div#vimiumHelpDialog div.vimiumDivider{background-color:#9a9a9a;display:block;height:1px;margin:10px auto;width:100%}div#vimiumHelpDialog td.vimiumHelpSectionTitle{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:16px;font-weight:700;padding-top:3px}div#vimiumHelpDialog td.vimiumHelpDescription{font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px}div#vimiumHelpDialog span.vimiumCopyCommandNameName{cursor:pointer;font-size:12px;font-style:italic}div#vimiumHelpDialog tr.advanced{display:none}div#vimiumHelpDialog.showAdvanced tr.advanced{display:table-row}div#vimiumHelpDialog div.advanced td:nth-of-type(3){color:#555}div#vimiumHelpDialog a.closeButton{color:#555;cursor:pointer;font-family:courier new;font-size:24px;font-weight:700;padding-left:5px;position:relative;text-decoration:none;top:3px}div#vimiumHelpDialog a{text-decoration:underline}div#vimiumHelpDialog a.closeButton:hover{color:#000;-webkit-user-select:none}div#vimiumHelpDialogFooter{display:block;margin-bottom:37px;position:relative}table.helpDialogBottom{width:100%}td.helpDialogBottomRight{float:right;text-align:right;width:100%}td.helpDialogBottomLeft,td.helpDialogBottomRight{padding:0}div#vimiumHelpDialogFooter *{font-size:10px}a#toggleAdvancedCommands,span#help-dialog-tip{font-size:10px;position:relative;top:19px;white-space:nowrap}a#toggleAdvancedCommands,a:active.vimiumHelDialogLink,a:hover.vimiumHelDialogLink,a:link.vimiumHelDialogLink,a:visited.vimiumHelDialogLink{color:#2f508e;cursor:pointer;text-decoration:underline}div.vimiumHUD{background:#f1f1f1;border:1px solid #aaa;border-radius:4px;bottom:8px;box-shadow:0 2px 10px rgba(0,0,0,.8);display:block;left:8px;position:fixed;text-align:left;width:calc(100% - 20px);z-index:2139999999}iframe.vimiumHUDFrame{background-color:transparent;border:none;bottom:-14px;display:block;height:58px;margin:0 0 0 -40%;min-width:300px;opacity:0;overflow:hidden;padding:0;position:fixed;right:20px;width:20%;z-index:2139999998}div.vimiumHUD .vimiumHUDSearchArea{background-color:#f1f1f1;border-radius:4px 4px 0 0;display:block;padding:3px}div.vimiumHUD .vimiumHUDSearchAreaInner{border-radius:3px;box-sizing:border-box;color:#777;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;font-size:14px;height:30px;line-height:20px;margin-bottom:0;outline:none;padding:2px 4px;width:100%}div.vimiumHUD .hud-find{background:#fff;border:1px solid #ccc}div.vimiumHUD span#hud-find-input,div.vimiumHUD span#hud-match-count{color:#000;display:inline;outline:none;overflow-y:hidden;white-space:nowrap}div.vimiumHUD span#hud-find-input:before{content:"/"}div.vimiumHUD span#hud-match-count{color:#aaa;font-size:12px}div.vimiumHUD span#hud-find-input br{display:none}div.vimiumHUD span#hud-find-input *{display:inline;white-space:nowrap}body.vimiumFindMode ::selection{background:#ff9632}iframe.vomnibarFrame{background-color:transparent;border:none;display:block;font-family:sans-serif;height:calc(100% - 70px);left:50%;margin:0 0 0 -40%;min-width:400px;overflow:hidden;padding:0;position:fixed;top:70px;width:calc(80% + 20px);z-index:2139999998}div.vimiumFlash{background-color:transparent;box-shadow:0 0 4px 2px #4183c4;padding:1px;position:absolute;z-index:2140000000}iframe.vimiumUIComponentHidden{display:none}iframe.vimiumUIComponentVisible{color-scheme:light dark;display:block}iframe.vimiumUIComponentReactivated{border:5px solid #ff0}iframe.vimiumNonClickable{pointer-events:none}@media (prefers-color-scheme:dark){iframe.reverseDarkReaderFilter{-webkit-filter:invert(100%) hue-rotate(180deg)!important;filter:invert(100%) hue-rotate(180deg)!important}body.vimiumBody{background-color:#292a2d;color:#fff}body.vimiumBody a,body.vimiumBody a:visited{color:#8ab4f8}body.vimiumBody input,body.vimiumBody textarea{background-color:#1d1d1f;border-color:#1d1d1f;color:#e8eaed}body.vimiumBody div.example{color:#9aa0a6}body.vimiumBody div#footer,body.vimiumBody div#state,div#vimiumHelpDialogContainer{background-color:#202124;border-color:hsla(0,0%,100%,.1)}div#vimiumHelpDialog{background-color:#292a2d;color:#fff}div#vimiumHelpDialog td.vimiumHelpDescription{color:#c9cccf}div#vimiumHelpDialog td.vimiumHelpSectionTitle,span#vimiumTitle{color:#fff}#vimiumTitle>span:first-child{color:#8ab4f8!important}div#vimiumHelpDialog a{color:#8ab4f8}div#vimiumHelpDialog div.vimiumDivider{background-color:hsla(0,0%,100%,.1)}span.vimiumHelpDialogKey{background-color:#1d1d1f;border:1px solid #000;box-shadow:none;color:#fff}}',htmlUtilsLibJs:`var __defProp = Object.defineProperty;
|
|
13
13
|
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
14
14
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
15
15
|
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
@@ -1724,7 +1724,7 @@ function registerAllMomenticListeners() {
|
|
|
1724
1724
|
|
|
1725
1725
|
// src/html/index.ts
|
|
1726
1726
|
registerAllMomenticListeners();
|
|
1727
|
-
`,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 Ig}from"crypto";import Pg from"dedent";import{distance as Lg}from"fastest-levenshtein";import{existsSync as Ic,readFileSync as Og,rmSync as Pc}from"fs";import Mg from"js-beautify";import{cloneDeep as Ng}from"lodash-es";import{homedir as _g}from"os";import wo from"p-timeout";import{basename as Lc,join as Mc}from"path";import{chromium as Dg,devices as kg,errors as Fg}from"playwright";import{addExtra as Ug}from"playwright-extra";import zg from"puppeteer-extra-plugin-recaptcha";import $g from"sharp";import{v4 as Bg}from"uuid";var dn=(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}},co=r=>{try{return new URL(r),!0}catch{return!1}},Yl=r=>!r.toLowerCase().startsWith("http"),uo=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function Yt(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}var Xl={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","aria-controls"],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","aria-valuenow","aria-valuemin","aria-valuemax"]};function Jl(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 tc}from"crypto";import{distance as As}from"fastest-levenshtein";import{cloneDeep as rc}from"lodash-es";import Xp from"p-timeout";var Ql=new Set(["about:blank","chrome-error://chromewebdata/"]),Zl=3,qe="data-momentic-id",ec=1e3,vs=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],xs=1e4,un=500;var Jp=["focusable","keyshortcuts","controls","live","relevant","orientation"],Qp=["selected","readonly","modal","required","invalid"],Zp=["id","name","role","content"],eg=["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"],tg=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog","ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],rg=["menulistpopup","statictext","inlinetextbox"],ng=80,mo=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],og=["cite"],sg={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"]},nc={indentLevel:0,noID:!1,noChildren:!1,noProperties:!1,noContent:!1,maxLevel:void 0,neighbors:void 0},Rs=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&&!Jl(t)?t:""),this.role=this.role||(e.domNode.attributes.role??""),dg(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 eg.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=nc){let t=Object.assign({},nc,e),{indentLevel:n,noChildren:o,noProperties:s,noID:i,noContent:a}=t,l=rc(this.properties),c=" ".repeat(n),u=this.role||"",d=this.tagName??"unknown",m=this.name;u==="heading"&&m==="heading"&&(m="");let p=mo.includes(this.role)||og.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${c}${m}
|
|
1727
|
+
`,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 Ig}from"crypto";import Pg from"dedent";import{distance as Lg}from"fastest-levenshtein";import{existsSync as Ic,readFileSync as Og,rmSync as Pc}from"fs";import{Jimp as Mg}from"jimp";import Ng from"js-beautify";import{cloneDeep as _g}from"lodash-es";import{homedir as Dg}from"os";import wo from"p-timeout";import{basename as Lc,join as Mc}from"path";import{chromium as kg,devices as Fg,errors as Ug}from"playwright";import{addExtra as zg}from"playwright-extra";import $g from"puppeteer-extra-plugin-recaptcha";import{v4 as Bg}from"uuid";var dn=(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}},co=r=>{try{return new URL(r),!0}catch{return!1}},Yl=r=>!r.toLowerCase().startsWith("http"),uo=(r,e)=>{try{return new URL(r,e),!0}catch{return!1}};function Yt(r,e){try{return!!new URL(r).origin.trim()}catch(t){return e?.error({url:r,err:t},"Invalid URL in check"),!1}}var Xl={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","aria-controls"],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","aria-valuenow","aria-valuemin","aria-valuemax"]};function Jl(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 tc}from"crypto";import{distance as As}from"fastest-levenshtein";import{cloneDeep as rc}from"lodash-es";import Xp from"p-timeout";var Ql=new Set(["about:blank","chrome-error://chromewebdata/"]),Zl=3,qe="data-momentic-id",ec=1e3,vs=["button","image","generic","graphics-symbol","tab","link","menuitem","group"],xs=1e4,un=500;var Jp=["focusable","keyshortcuts","controls","live","relevant","orientation"],Qp=["selected","readonly","modal","required","invalid"],Zp=["id","name","role","content"],eg=["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"],tg=["activeAriaModalDialog","activeFullscreenElement","activeModalDialog","ariaHiddenElement","ariaHiddenSubtree","hiddenByChildTree","inertElement","inertSubtree","notRendered","notVisible"],rg=["menulistpopup","statictext","inlinetextbox"],ng=80,mo=["StaticText","ListMarker","RootWebArea","LineBreak","emphasis","::before","::after"],og=["cite"],sg={LabelText:["label"],listitem:["li"],image:["img","svg"],link:["a"],RootWebArea:["#document"],paragraph:["p"],LineBreak:["br"],separator:["hr"]},nc={indentLevel:0,noID:!1,noChildren:!1,noProperties:!1,noContent:!1,maxLevel:void 0,neighbors:void 0},Rs=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&&!Jl(t)?t:""),this.role=this.role||(e.domNode.attributes.role??""),dg(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 eg.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=nc){let t=Object.assign({},nc,e),{indentLevel:n,noChildren:o,noProperties:s,noID:i,noContent:a}=t,l=rc(this.properties),c=" ".repeat(n),u=this.role||"",d=this.tagName??"unknown",m=this.name;u==="heading"&&m==="heading"&&(m="");let p=mo.includes(this.role)||og.includes(this.tagName||"");if(this.role==="StaticText"||this.role==="ListMarker")return`${c}${m}
|
|
1728
1728
|
`;let h=`${c}<${d}`;if(!i&&!p&&(h+=` id="${this.id}"`),u&&u!=="generic"&&u!==d&&!(sg[u]??[]).includes(d)&&(h+=` role=${JSON.stringify(u)}`),m&&(h+=` name=${JSON.stringify(m)}`),this.content&&!a&&(h+=` content=${JSON.stringify(this.content)}`),Object.keys(l).length>0&&!s&&Object.entries(l).forEach(([f,S])=>{if(!Jp.includes(f)){if(Qp.includes(f)&&(!S||S==="false"))return;if(f==="value"&&a&&(l.type==="text"||this.role==="textbox"))return;if(f==="editable"&&S==="plaintext")return;if(f==="type"&&S===d)return;typeof S=="string"?h+=` ${f}="${S}"`:typeof S=="boolean"?S?h+=` ${f}`:h+=` ${f}={false}`:typeof S<"u"&&(h+=` ${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)h+=` />
|
|
1729
1729
|
`;else{let f="";for(let w of this.children)f+=w.serialize({...e,indentLevel:n+2,neighbors:0});let S=f.trim();S.length<=ng&&!S.includes(`
|
|
1730
1730
|
`)?h+=`>${S}</${d}>
|
|
@@ -1734,7 +1734,7 @@ ${f}${c}</${d}>
|
|
|
1734
1734
|
${h}
|
|
1735
1735
|
${w||""}`}return h}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=rc(this.properties),e}},Is=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 m of c){let p=n(m,a||u);p&&(d.push(p),p.parent=l,u=!0)}if(l.children=d,a||u)return l;if(mo.includes(s.role)&&i)return l}let o=n(t);return new r(o,this.a11yIdNodeMap,this.dataMomenticIdMap)}};function ig(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 ag(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?(Sr({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?(Sr({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 oc({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=rg.includes((r.role?.value).toLowerCase());if(!d&&u===void 0)return c("Filtering out node since it doesn't exist in the DOM"),[];let m=u?t.backendIdToNode[u]:void 0;if(!d&&!m)try{let w=await Xp(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:m,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(m&&e&&a&&l&&r.backendDOMNodeId&&!ag(m,l,s,i))return m&&(m.momenticIgnored=!0),[];let p=r.name?.value?typeof r.name.value=="string"?r.name.value:`${r.name.value}`:"",h=r.value?.value?typeof r.value.value=="string"?r.value.value:`${r.value.value}`:"";if(p==="momentic_cursor"||p.includes("chakra"))return m&&(m.momenticIgnored=!0),[];let g=new Rs({domNode:m,id:parseInt(r.nodeId),role:r.role?.value||"",name:p,content:h,properties:r.properties,children:[],pathFromRoot:(e?`${e.pathFromRoot} `:"")+ig(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 oc({node:b,parent:g,domGraph:t,inputNodeMap:n,cdpClient:o,logger:s,callId:i,filterByViewport:a,viewportDetails:l});T.length&&(g.children=g.children.concat(T))}if(g.role==="StaticText"&&(g.children=[]),g.children.length===1&&g.children[0].role==="StaticText"){let w=g.name,b=g.children[0]?.name;(w===b||!b)&&(g.children=[])}let f=[];for(let w=g.children.length-1;w>=0;w--){let b=g.children[w];if(b.role!=="StaticText"){f.push(b);continue}if(w===0||g.children[w-1].role!=="StaticText"){f.push(b);continue}g.children[w-1].name+=` ${b.name}`}if(g.children=f.reverse(),g.role==="generic"&&g.children.length===1){let w=g.children[0];if(g.name&&!mo.includes(w.role)&&g.name===w.name)return m&&(m.momenticIgnored=!0),g.children}if(!g.isInteresting()&&r.parentId)return m&&(m.momenticIgnored=!0),g.children;for(let w of g.children)w.parent=g;return[g]}function sc({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):mo.includes(r.role);for(let i of r.children)s=sc({node:i,a11yIdNodeMap:e,dataMomenticIdMap:t,logger:n,callId:o,startId:s});return s}async function ic({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=tc();r.allNodes=r.allNodes.filter(d=>d.ignored?!d.ignoredReasons?.find(p=>tg.includes(p.name)):!0);let a=new Map;for(let d of r.allNodes)a.set(parseInt(d.nodeId),d);let l=await oc({node:r.root,domGraph:e,parent:null,inputNodeMap:a,cdpClient:n,logger:t,callId:tc(),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 sc({node:l[0],a11yIdNodeMap:c,dataMomenticIdMap:u,logger:t,callId:i}),new Is(l[0],c,u)}var Ps=(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=As(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=As(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=As(o,e.serializedForm)/Math.min(o.length,e.serializedForm.length);s===0?t+=2:s<=.1&&t++}return t},lg=["href","src"];function cg(r,e){if(e==="true")return!0;if(e==="false")return!1;try{let t=parseInt(e);if(!isNaN(t))return t}catch{}return lg.includes(r)&&e.length>60?e.slice(0,50)+"...":r==="src"&&e.includes("base64")?e.slice(0,e.indexOf("base64")+6)+"...":e}function dg(r,e){e&&Object.entries(e.attributes).forEach(([t,n])=>{Xl.relevantElementAttributes.includes(t)&&!Zp.includes(t)&&!r[t]&&!t.startsWith("aria")&&t!=="class"&&(r[t]=cg(t,n))})}function ac(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(`
|
|
1736
1736
|
...
|
|
1737
|
-
`)}var Xt={r:147,g:196,b:125,a:.55},lc={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:Xt,paddingColor:Xt,borderColor:Xt,marginColor:Xt,eventTargetColor:Xt,shapeColor:Xt,shapeMarginColor:Xt,showInfo:!0,showAccessibilityInfo:!0};var po=["display","opacity","visibility","height","max-height","overflow"];function cc({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:ug(s,n,e,i),backendIdToNode:i}}function ug(r,e,t,n){let o=r.layout,s={};o.nodeIndex.forEach((h,g)=>{s[h]=g});let i=o.styles,a=o.bounds??[],l=r.nodes,c=l.backendNodeId??[],u=l.attributes??[],d=l.parentIndex??[],m=l.nodeName??[],p=l.inputChecked??{index:[]};for(let h=0;h<c.length;h++){let g=c[h],f=u[h]??[],S=d[h]&&d[h]>=0?d[h]:null,w=s[h],b;w?b=a[w]??[]:b=[];let T={backendNodeId:g,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:m[h]!==void 0?e[m[h]]?.toLowerCase():void 0,children:[],momenticIgnored:void 0};T.parentBackendNodeId&&n[T.parentBackendNodeId].children.push(g);for(let E of Object.keys(T.bounds)){let I=E;T.bounds[I]!==null&&(T.bounds[I]/=t)}let v=i[h]??[];for(let E=0;E<v.length&&!(E>=po.length);E++){let I=v[E];if(!I||isNaN(I))continue;let
|
|
1737
|
+
`)}var Xt={r:147,g:196,b:125,a:.55},lc={showRulers:!1,showStyles:!1,showExtensionLines:!1,contrastAlgorithm:"aa",contentColor:Xt,paddingColor:Xt,borderColor:Xt,marginColor:Xt,eventTargetColor:Xt,shapeColor:Xt,shapeMarginColor:Xt,showInfo:!0,showAccessibilityInfo:!0};var po=["display","opacity","visibility","height","max-height","overflow"];function cc({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:ug(s,n,e,i),backendIdToNode:i}}function ug(r,e,t,n){let o=r.layout,s={};o.nodeIndex.forEach((h,g)=>{s[h]=g});let i=o.styles,a=o.bounds??[],l=r.nodes,c=l.backendNodeId??[],u=l.attributes??[],d=l.parentIndex??[],m=l.nodeName??[],p=l.inputChecked??{index:[]};for(let h=0;h<c.length;h++){let g=c[h],f=u[h]??[],S=d[h]&&d[h]>=0?d[h]:null,w=s[h],b;w?b=a[w]??[]:b=[];let T={backendNodeId:g,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:m[h]!==void 0?e[m[h]]?.toLowerCase():void 0,children:[],momenticIgnored:void 0};T.parentBackendNodeId&&n[T.parentBackendNodeId].children.push(g);for(let E of Object.keys(T.bounds)){let I=E;T.bounds[I]!==null&&(T.bounds[I]/=t)}let v=i[h]??[];for(let E=0;E<v.length&&!(E>=po.length);E++){let I=v[E];if(!I||isNaN(I))continue;let x=e[I];if(!x)continue;let P=po[E];T.computedStyles[P]=x}for(let E=0;E<f.length;E+=2){let I=f[E],x=f[E+1];if(!I||!x)continue;let P=e[I],D=e[x];!P||!D||(T.attributes[P]=D)}p.index.includes(h)&&(T.attributes.checked="true"),n[T.backendNodeId]=T}return n[c[0]]}async function gn(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 X=async(r=1e3,e)=>{for(;r>0;){if(e?.())throw new Ke("Operation cancelled by user");let t=Math.min(r,15e3);r-=t,await new Promise(n=>setTimeout(()=>n(),t))}};function dc(){return window.lastCursorPos}function uc(){window.globalHintManager||(window.globalHintManager=new window.HintManager),window.globalHintManager.capture()}function mc(){window.globalHintManager&&window.globalHintManager.reset()}async function hn(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 X(500)}throw new Error(`Failed to load momentic browser scripts on page ${r.url()}`)}var pc=`(function () {
|
|
1738
1738
|
if (document.__customCookieSetterApplied__) {
|
|
1739
1739
|
return;
|
|
1740
1740
|
}
|
|
@@ -1764,24 +1764,24 @@ ${w||""}`}return h}shallowClone(){let e=new r({id:this.id,role:this.role,name:th
|
|
|
1764
1764
|
${i}
|
|
1765
1765
|
==================
|
|
1766
1766
|
${o}
|
|
1767
|
-
`}:{dataMomenticId:n,closestDistance:s,closestNodeSerialized:o}};import{mkdirSync as mg,rmSync as hc,statSync as pg}from"fs";import gg from"nodejs-file-downloader";import{tmpdir as hg}from"os";import fg from"p-timeout";import xr,{basename as fc,dirname as Sg}from"path";var fn="file://",Sc=xr.join(hg(),"momentic","downloads"),Ls=1e4,yg=50*1024*1024;async function yc({uri:r,logger:e,orgId:t}){if(r.startsWith(fn)){let h=xr.join(Sc,t,r.slice(fn.length));return{filePath:h,momenticUri:r,cleanup:()=>{hc(Sg(h),{recursive:!0,force:!0})}}}let n=new URL(r);n.search&&(n.search="");let o=fc(n.href),s=Ns(o),i=xr.extname(s);if(Na.includes(i))throw new Error(`Downloading files with extension ${i} is not allowed.`);let a=Ms(t),l=new gg({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:Ls}),{downloadStatus:c,filePath:u}=await fg(l.download(),{milliseconds:Ls,message:`Download timed out after ${Ls}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=pg(u).size;if(m>yg)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:m,filePath:u,fileName:s},"Downloaded file to disk");let p;return{filePath:u,momenticUri:Os(fc(a),s),cleanup:()=>{clearTimeout(p),p=setTimeout(()=>hc(a,{recursive:!0,force:!0}),10*60*1e3)}}}function Os(r,e){return`${fn}${r}/${e}`}function Ms(r){let e=Math.random().toString(36).substring(4),t=xr.join(Sc,r,e);return mg(t,{recursive:!0}),t}function Ns(r){let e=xr.extname(r),t=xr.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function wc({locator:r,logger:e}){let[t,n]=await r.evaluate(s=>[s.tagName.toLowerCase(),s.getAttribute("class")??""],{timeout:1e3});if(t!=="input"||!n.toLowerCase().includes("chakra"))return;let o=await r.boundingBox({timeout:2e3});if(o===null){e.warn({elementDisplayString:await gn(r)},"Attempting to click on element with no bounding box");return}if(!(o.width!==1||o.height!==1))try{await hn(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(),p={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:p,serializedForm:c.outerHTML.slice(0,500)}},{timeout:1e3});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 Tc=["date","datetime-local","month","time","week"],bc={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 Cc(r,e,t,n){let o=(await r.evaluate(()=>document.activeElement?.getAttribute("type"))??"").toLowerCase();return bc[o]&&(bc[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}async function Ec(r,e,t,n,o){try{await wg(r,e,t,n)}catch(s){o.error({err:s,tabIndex:e},"Error handling new console log")}}async function wg(r,e,t,n){let o=n.text();o.length>un&&(o=o.slice(0,un)+"...(TRUNCATED)");let s=[];for(let i of n.args())try{let a=await i.jsonValue(),l=JSON.stringify(a);l.length>un?s.push(l.slice(0,un)+"...(TRUNCATED)"):(typeof a!="object"||Object.keys(a).length>0)&&s.push(a)}catch{}_s(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:s})}function _s(r,e,t,n){let o=Date.now(),s=e.logsPerPage;if(s.length<=t||s[t]===void 0){s[t]=[];for(let i=0;i<t;i++)s[i]===void 0&&(s[i]=[])}s[t].length>xs&&(s[t]=s[t].slice(Math.floor(xs/2)),s[t]?.push({url:r.url(),timestamp:o,type:"warning",text:"[MOMENTIC] Truncated console logs due to buffer overflow",tabIndex:t})),s[t].push({...n,tabIndex:t,timestamp:o})}async function nt(r,e,t){let n=Date.now(),o=await r(),s=Date.now();return t[e]=s-n,o}function vc(){return async r=>{let{fragment:e,code:t,context:n}=r,{env:o,results:s,inputs:i}=n||{},a=Object.getPrototypeOf(async function(){}).constructor;return{result:await Promise.resolve(new a("env","results","inputs",e?`return ${t}`:t)(o,s,i))}}}var Hg=Mc(_g(),"momentic","chromium"),Ar=process.env.TWO_CAPTCHA_KEY,bo=Ug(Dg);bo.use(zg({provider:{id:"2captcha",token:Ar},visualFeedback:!0}));async function Ds(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=>Yt(s.url,e))}catch(s){n=s,await X(500)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}var ot=class r{static USER_AGENT=kg["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;debugData={logsPerPage:[]};enricher;storage;logger;localMode;activeFrame;activeFrameCache;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,systemDevicePixelRatio:p}){_a(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||lt,this.onTabsChange=m,this.systemDevicePixelRatio=p}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:cn.cssGeneratorLibJs}),this.context.addInitScript({content:cn.htmlUtilsLibJs}),this.context.addInitScript({content:"window._MOMENTIC_BROWSER = true;"})];this.localMode&&e.push(this.context.addInitScript({content:pc}));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:m,skipPageSetup:p,timeout:h,browserbaseConnectUrl:g,onTabsChange:f}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let S={headless:!0,handleSIGTERM:!1,chromiumSandbox:!1,...i??{}},w={viewport:lt,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 bo.launchPersistentContext(Hg,{...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=T.pages()[0],l&&v.on("close",()=>{l()});else if(g){b=await bo.connectOverCDP(g);let P=b.contexts()[0];if(!P)throw new Error("Failed to get browserbase default context");let D=P.pages()[0];if(!D)throw new Error("Failed to get browserbase default page");T=P,v=D}else{b=await bo.launch({...S,args:["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=4","--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 P={...w,baseURL:e};T=await b.newContext(P),t.debug({contextArgs:P},"Browser initialization context args"),v=await T.newPage()}let E=await r.initCDPSession(T,v,t,h),I=new r({browser:b,context:T,page:v,baseUrl:e,logger:t,storage:n,enricher:o,localMode:u,userBrowserSettings:s,cdpClient:E,viewport:w.viewport||lt,onTabsChange:f,systemDevicePixelRatio:w.deviceScaleFactor});await I.initializeContext();let A=async()=>{try{await I.navigate({url:e,initialNavigation:!p,loadTimeoutMs:h})}catch(P){if(t.error({err:P},"Failed to initialize Chrome browser"),c)throw P}};return c?await A():A(),I}async handleAvailableTabsChangeHelper(){try{let e=await Ds(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(){try{clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),1500)}catch(e){this.logger.warn({err:e},"Error handling available tabs change")}}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()||!Yt(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",o=>this.handlePageClosedEvent(o)),e.on("pageerror",async o=>this.handlePageErrorEvent(o)),e.on("framenavigated",async o=>{o===e.mainFrame()&&await this.handleFrameNavigationEvent(o)});let t=this.context.pages().indexOf(e);e.on("console",o=>{Ec(e,t,this.debugData,o,this.logger)});let n=this.pageLoadPromise;this.pageLoadPromise=(async()=>{try{await Promise.resolve(n),await this.loadFrameAndRecordUrl(e),this.handleAvailableTabsChange()}catch(o){this.logger.error({err:o},"Failed to wait for new page to load")}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.loadFrameAndRecordUrl(e),this.handleAvailableTabsChange()}catch(o){this.logger.error({err:o},"Failed to wait for frame navigation to finish")}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,{timeout:1e3})).asElement().contentFrame();if(!i)throw new Error(`Got null frame from locator: ${s}`);return await this.loadFrameAndRecordUrl(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 getActivePageOrFrameHelper(){if(!this.activeFrame)return this.page;let e,t="";if(this.activeFrame.type==="url")t=this.activeFrame.url,e=(await this.getMatchingFrame(this.activeFrame)).frame;else throw new Error(`Frame identifier type ${this.activeFrame.type} is not yet supported`);if(e)return e;throw new R("InternalWebAgentError",`Failed to find frame with src matching '${t}' 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 X(500),s--,i();throw l}};return await wo(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.activeFrameCache=void 0):(this.activeFrame=void 0,this.activeFrameCache=void 0)}async reset(e){this.debugData.logsPerPage=[],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;this.cdpClient=n;try{await o.detach()}catch{}if(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:cn.vimiumCss}),await t.addScriptTag({content:cn.vimiumJs}),await t.evaluate(uc,{timeout:1e3})):await t.evaluate(mc,{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.getActivePageOrFrame()).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 X(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:p,width:h,height:g}=d;if(!h||!g)throw new Error("Attempted to screenshot an element with zero width or height");if(m<0||p<0)throw new Error("Attempted to screenshot an element with negative coordinates");m=Math.floor(m),p=Math.floor(p),h=Math.ceil(h),g=Math.ceil(g);try{c=await $g(c).extract({left:m,top:p,width:h,height:g}).toBuffer()}catch(f){throw new Error(`Failed taking element screenshot at coordinates (${m}, ${p}) with size (${h}, ${g}): ${f}`)}}return c}async getViewport(){return this.viewport}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){Yl(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.loadFrameAndRecordUrl(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(Ql.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.getActivePageOrFrame();if(!await Cc(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 X(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.waitForTimeout(25),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.getActivePageOrFrame()).evaluate(()=>{let e=window,t=e.removeHighlightTimers||[];for(;t.length;){let n=t.pop();clearTimeout(n)}Object.values(e.removeHighlightFunctions??{}).forEach(n=>{n()})},{timeout:1e3})}async highlightTarget(e,t){try{return await this.removeAllHighlights(),await e.evaluate(n=>{let o=window;o.momenticIsEligible=c=>{let d=window.getComputedStyle(c,null).getPropertyValue("display");if(d==="none"||d==="contents")return!1;let m=c.getBoundingClientRect();return!(!m.height||!m.width)},o.removeHighlightTimers=o.removeHighlightTimers||[],o.removeHighlightFunctions=o.removeHighlightFunctions||{};let s=0;for(;!o.momenticIsEligible(n)&&s<3;){if(!n.parentElement)throw new Error("No eligible non-empty parent found for highlighting");n=n.parentElement,s++}let i=n.style.getPropertyValue("outline"),a=n.style.getPropertyPriority("outline");n.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let l=`momentic${Math.floor(Math.random()*1e7)}`;o[l]=()=>{n.style.removeProperty("outline"),n.style.setProperty("outline",i,a)},o.removeHighlightTimers.push(setTimeout(()=>{o[l](),o.removeHighlightFunctions?.[l]&&delete o.removeHighlightFunctions[l]},5e3)),o.removeHighlightFunctions[l]=o[l]},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.wrapPageLoad(async()=>{await this.waitForDOMStability(),await this.loadAuthStateHelper(e)})}async loadAuthStateHelper(e){let t=[];for(let o of e.cookies){let s=await this.setCookie(o);t=t.concat(s)}this.logger.info({cookiesSet:t},"Loaded cookies"),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 Ds(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),!(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.warn({err:i},"Failed to fetch HTML attributes for target")}if(vs.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:.1,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=Ps(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.slice(0,5)}]}}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.getActivePageOrFrame();if(await hn(i,this.logger),t.id>0&&!Rn(t)){let m=this.a11yIdToNodeMap.get(t.id);if(!m)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 p=await this.getLocatorFromA11yNode(m);return await this.saveNodeDetailsToCache(i,m,t,m.dataMomenticId,p),{locator:p,a11yNode:m,displayString:m.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(m){this.logger.debug({err:m,decisions:m instanceof ut?m.decisions:[]},`Could not resolve target through CSS selectors only (x${c})`),await X(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}),this.logger.debug({decisions:d.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:s,elementLocationDecisions:d.decisions,pageState:d.pageState,targetSource:t.targetSource,targetUpdateTime:t.targetUpdateTime}),d}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),p;try{p=await gn(m)}catch(h){throw new ut(`'${t.selector}' failed to resolve: ${h}`,[{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:p,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,p;try{m=await this.resolveTargetUsingCssSelectors(e,t)}catch(h){p=h}if(m)return{...m,pageState:a,decisions:[...i,...m.decisions]};n||(i.push({type:"CSS_SELECTOR",matched:!1,reason:p?.message,selectors:Ng(t.generatedSelectors)}),t.generatedSelectors=void 0)}if(n)throw new ut("Could not resolve target with CSS selector only",i);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,p,h;for(let f of this.a11yIdToNodeMap.values()){let S=f.getSerializedFormWithContext(),w=Lg(t.serializedForm,S);w<m?(m=w,p=f,h=void 0):w===m&&(h=f)}let g=Math.ceil(.1*t.serializedForm.length);if(p&&m<g&&m<25)if(h){let f=Pg`
|
|
1767
|
+
`}:{dataMomenticId:n,closestDistance:s,closestNodeSerialized:o}};import{mkdirSync as mg,rmSync as hc,statSync as pg}from"fs";import gg from"nodejs-file-downloader";import{tmpdir as hg}from"os";import fg from"p-timeout";import xr,{basename as fc,dirname as Sg}from"path";var fn="file://",Sc=xr.join(hg(),"momentic","downloads"),Ls=1e4,yg=50*1024*1024;async function yc({uri:r,logger:e,orgId:t}){if(r.startsWith(fn)){let h=xr.join(Sc,t,r.slice(fn.length));return{filePath:h,momenticUri:r,cleanup:()=>{hc(Sg(h),{recursive:!0,force:!0})}}}let n=new URL(r);n.search&&(n.search="");let o=fc(n.href),s=Ns(o),i=xr.extname(s);if(Na.includes(i))throw new Error(`Downloading files with extension ${i} is not allowed.`);let a=Ms(t),l=new gg({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:Ls}),{downloadStatus:c,filePath:u}=await fg(l.download(),{milliseconds:Ls,message:`Download timed out after ${Ls}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=pg(u).size;if(m>yg)throw new Error("File size exceeds the maximum limit of 50MB");e.info({fileSizeInBytes:m,filePath:u,fileName:s},"Downloaded file to disk");let p;return{filePath:u,momenticUri:Os(fc(a),s),cleanup:()=>{clearTimeout(p),p=setTimeout(()=>hc(a,{recursive:!0,force:!0}),10*60*1e3)}}}function Os(r,e){return`${fn}${r}/${e}`}function Ms(r){let e=Math.random().toString(36).substring(4),t=xr.join(Sc,r,e);return mg(t,{recursive:!0}),t}function Ns(r){let e=xr.extname(r),t=xr.basename(r,e);return r=(t.length>100?t.slice(t.length-100):t)+e,r=r.trim().replaceAll(" ","_"),r}async function wc({locator:r,logger:e}){let[t,n]=await r.evaluate(s=>[s.tagName.toLowerCase(),s.getAttribute("class")??""],{timeout:1e3});if(t!=="input"||!n.toLowerCase().includes("chakra"))return;let o=await r.boundingBox({timeout:2e3});if(o===null){e.warn({elementDisplayString:await gn(r)},"Attempting to click on element with no bounding box");return}if(!(o.width!==1||o.height!==1))try{await hn(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(),p={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:p,serializedForm:c.outerHTML.slice(0,500)}},{timeout:1e3});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 Tc=["date","datetime-local","month","time","week"],bc={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 Cc(r,e,t,n){let o=(await r.evaluate(()=>document.activeElement?.getAttribute("type"))??"").toLowerCase();return bc[o]&&(bc[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}async function Ec(r,e,t,n,o){try{await wg(r,e,t,n)}catch(s){o.error({err:s,tabIndex:e},"Error handling new console log")}}async function wg(r,e,t,n){let o=n.text();o.length>un&&(o=o.slice(0,un)+"...(TRUNCATED)");let s=[];for(let i of n.args())try{let a=await i.jsonValue(),l=JSON.stringify(a);l.length>un?s.push(l.slice(0,un)+"...(TRUNCATED)"):(typeof a!="object"||Object.keys(a).length>0)&&s.push(a)}catch{}_s(r,t,e,{url:r.url(),location:n.location(),type:n.type(),text:n.text(),args:s})}function _s(r,e,t,n){let o=Date.now(),s=e.logsPerPage;if(s.length<=t||s[t]===void 0){s[t]=[];for(let i=0;i<t;i++)s[i]===void 0&&(s[i]=[])}s[t].length>xs&&(s[t]=s[t].slice(Math.floor(xs/2)),s[t]?.push({url:r.url(),timestamp:o,type:"warning",text:"[MOMENTIC] Truncated console logs due to buffer overflow",tabIndex:t})),s[t].push({...n,tabIndex:t,timestamp:o})}async function nt(r,e,t){let n=Date.now(),o=await r(),s=Date.now();return t[e]=s-n,o}function vc(){return async r=>{let{fragment:e,code:t,context:n}=r,{env:o,results:s,inputs:i}=n||{},a=Object.getPrototypeOf(async function(){}).constructor;return{result:await Promise.resolve(new a("env","results","inputs",e?`return ${t}`:t)(o,s,i))}}}var Hg=Mc(Dg(),"momentic","chromium"),Ar=process.env.TWO_CAPTCHA_KEY,bo=zg(kg);bo.use($g({provider:{id:"2captcha",token:Ar},visualFeedback:!0}));async function Ds(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=>Yt(s.url,e))}catch(s){n=s,await X(500)}throw new Error(`Failed to get tab titles after all retries: ${n?.message}`)}var ot=class r{static USER_AGENT=Fg["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;debugData={logsPerPage:[]};enricher;storage;logger;localMode;activeFrame;activeFrameCache;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,systemDevicePixelRatio:p}){_a(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||lt,this.onTabsChange=m,this.systemDevicePixelRatio=p}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:cn.cssGeneratorLibJs}),this.context.addInitScript({content:cn.htmlUtilsLibJs}),this.context.addInitScript({content:"window._MOMENTIC_BROWSER = true;"})];this.localMode&&e.push(this.context.addInitScript({content:pc}));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:m,skipPageSetup:p,timeout:h,browserbaseConnectUrl:g,onTabsChange:f}){process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY="1";let S={headless:!0,handleSIGTERM:!1,chromiumSandbox:!1,...i??{}},w={viewport:lt,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 bo.launchPersistentContext(Hg,{...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=T.pages()[0],l&&v.on("close",()=>{l()});else if(g){b=await bo.connectOverCDP(g);let P=b.contexts()[0];if(!P)throw new Error("Failed to get browserbase default context");let D=P.pages()[0];if(!D)throw new Error("Failed to get browserbase default page");T=P,v=D}else{b=await bo.launch({...S,args:["--disable-dev-shm-usage","--no-first-run","--renderer-process-limit=4","--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 P={...w,baseURL:e};T=await b.newContext(P),t.debug({contextArgs:P},"Browser initialization context args"),v=await T.newPage()}let E=await r.initCDPSession(T,v,t,h),I=new r({browser:b,context:T,page:v,baseUrl:e,logger:t,storage:n,enricher:o,localMode:u,userBrowserSettings:s,cdpClient:E,viewport:w.viewport||lt,onTabsChange:f,systemDevicePixelRatio:w.deviceScaleFactor});await I.initializeContext();let x=async()=>{try{await I.navigate({url:e,initialNavigation:!p,loadTimeoutMs:h})}catch(P){if(t.error({err:P},"Failed to initialize Chrome browser"),c)throw P}};return c?await x():x(),I}async handleAvailableTabsChangeHelper(){try{let e=await Ds(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(){try{clearTimeout(this.lastTabChangeEventTimeout),this.lastTabChangeEventTimeout=setTimeout(()=>this.handleAvailableTabsChangeHelper(),1500)}catch(e){this.logger.warn({err:e},"Error handling available tabs change")}}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()||!Yt(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",o=>this.handlePageClosedEvent(o)),e.on("pageerror",async o=>this.handlePageErrorEvent(o)),e.on("framenavigated",async o=>{o===e.mainFrame()&&await this.handleFrameNavigationEvent(o)});let t=this.context.pages().indexOf(e);e.on("console",o=>{Ec(e,t,this.debugData,o,this.logger)});let n=this.pageLoadPromise;this.pageLoadPromise=(async()=>{try{await Promise.resolve(n),await this.loadFrameAndRecordUrl(e),this.handleAvailableTabsChange()}catch(o){this.logger.error({err:o},"Failed to wait for new page to load")}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.loadFrameAndRecordUrl(e),this.handleAvailableTabsChange()}catch(o){this.logger.error({err:o},"Failed to wait for frame navigation to finish")}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,{timeout:1e3})).asElement().contentFrame();if(!i)throw new Error(`Got null frame from locator: ${s}`);return await this.loadFrameAndRecordUrl(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 getActivePageOrFrameHelper(){if(!this.activeFrame)return this.page;let e,t="";if(this.activeFrame.type==="url")t=this.activeFrame.url,e=(await this.getMatchingFrame(this.activeFrame)).frame;else throw new Error(`Frame identifier type ${this.activeFrame.type} is not yet supported`);if(e)return e;throw new R("InternalWebAgentError",`Failed to find frame with src matching '${t}' 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 X(500),s--,i();throw l}};return await wo(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.activeFrameCache=void 0):(this.activeFrame=void 0,this.activeFrameCache=void 0)}async reset(e){this.debugData.logsPerPage=[],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;this.cdpClient=n;try{await o.detach()}catch{}if(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:cn.vimiumCss}),await t.addScriptTag({content:cn.vimiumJs}),await t.evaluate(uc,{timeout:1e3})):await t.evaluate(mc,{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.getActivePageOrFrame()).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 X(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:p,width:h,height:g}=d;if(!h||!g)throw new Error("Attempted to screenshot an element with zero width or height");if(m<0||p<0)throw new Error("Attempted to screenshot an element with negative coordinates");m=Math.floor(m),p=Math.floor(p),h=Math.ceil(h),g=Math.ceil(g);try{c=await(await Mg.fromBuffer(c)).crop({x:m,y:p,w:h,h:g}).getBuffer("image/jpeg")}catch(f){throw new Error(`Failed taking element screenshot at coordinates (${m}, ${p}) with size (${h}, ${g}): ${f}`)}}return c}async getViewport(){return this.viewport}async navigate({url:e,initialNavigation:t=!1,loadTimeoutMs:n=this.pageLoadTimeout}){Yl(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.loadFrameAndRecordUrl(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(Ql.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.getActivePageOrFrame();if(!await Cc(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 X(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.waitForTimeout(25),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.getActivePageOrFrame()).evaluate(()=>{let e=window,t=e.removeHighlightTimers||[];for(;t.length;){let n=t.pop();clearTimeout(n)}Object.values(e.removeHighlightFunctions??{}).forEach(n=>{n()})},{timeout:1e3})}async highlightTarget(e,t){try{return await this.removeAllHighlights(),await e.evaluate(n=>{let o=window;o.momenticIsEligible=c=>{let d=window.getComputedStyle(c,null).getPropertyValue("display");if(d==="none"||d==="contents")return!1;let m=c.getBoundingClientRect();return!(!m.height||!m.width)},o.removeHighlightTimers=o.removeHighlightTimers||[],o.removeHighlightFunctions=o.removeHighlightFunctions||{};let s=0;for(;!o.momenticIsEligible(n)&&s<3;){if(!n.parentElement)throw new Error("No eligible non-empty parent found for highlighting");n=n.parentElement,s++}let i=n.style.getPropertyValue("outline"),a=n.style.getPropertyPriority("outline");n.style.setProperty("outline","5px dashed rgb(255, 0, 153)","important");let l=`momentic${Math.floor(Math.random()*1e7)}`;o[l]=()=>{n.style.removeProperty("outline"),n.style.setProperty("outline",i,a)},o.removeHighlightTimers.push(setTimeout(()=>{o[l](),o.removeHighlightFunctions?.[l]&&delete o.removeHighlightFunctions[l]},5e3)),o.removeHighlightFunctions[l]=o[l]},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.wrapPageLoad(async()=>{await this.waitForDOMStability(),await this.loadAuthStateHelper(e)})}async loadAuthStateHelper(e){let t=[];for(let o of e.cookies){let s=await this.setCookie(o);t=t.concat(s)}this.logger.info({cookiesSet:t},"Loaded cookies"),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 Ds(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),!(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.warn({err:i},"Failed to fetch HTML attributes for target")}if(vs.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:.1,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=Ps(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.slice(0,5)}]}}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.getActivePageOrFrame();if(await hn(i,this.logger),t.id>0&&!Rn(t)){let m=this.a11yIdToNodeMap.get(t.id);if(!m)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 p=await this.getLocatorFromA11yNode(m);return await this.saveNodeDetailsToCache(i,m,t,m.dataMomenticId,p),{locator:p,a11yNode:m,displayString:m.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(m){this.logger.debug({err:m,decisions:m instanceof ut?m.decisions:[]},`Could not resolve target through CSS selectors only (x${c})`),await X(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}),this.logger.debug({decisions:d.decisions},"Target resolution succeeded after waiting")),e?.details?.push({type:"TARGETING",name:s,elementLocationDecisions:d.decisions,pageState:d.pageState,targetSource:t.targetSource,targetUpdateTime:t.targetUpdateTime}),d}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),p;try{p=await gn(m)}catch(h){throw new ut(`'${t.selector}' failed to resolve: ${h}`,[{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:p,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,p;try{m=await this.resolveTargetUsingCssSelectors(e,t)}catch(h){p=h}if(m)return{...m,pageState:a,decisions:[...i,...m.decisions]};n||(i.push({type:"CSS_SELECTOR",matched:!1,reason:p?.message,selectors:_g(t.generatedSelectors)}),t.generatedSelectors=void 0)}if(n)throw new ut("Could not resolve target with CSS selector only",i);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,p,h;for(let f of this.a11yIdToNodeMap.values()){let S=f.getSerializedFormWithContext(),w=Lg(t.serializedForm,S);w<m?(m=w,p=f,h=void 0):w===m&&(h=f)}let g=Math.ceil(.1*t.serializedForm.length);if(p&&m<g&&m<25)if(h){let f=Pg`
|
|
1768
1768
|
Multiple accessibility nodes have the same string distance - refusing to pick between them:
|
|
1769
1769
|
Candidate 1:
|
|
1770
1770
|
${p.getSerializedFormWithContext()}
|
|
1771
1771
|
=====================
|
|
1772
1772
|
Candidate 2:
|
|
1773
|
-
${h.getSerializedFormWithContext()}`;i.push({type:"A11Y_DISTANCE",matched:!1,reason:f,distance:m,closestElement:p.getNodeOnlySerializedForm(),savedElement:t.serializedForm})}else{let f=await this.getLocatorFromA11yNode(p);return await this.saveNodeDetailsToCache(e,p,t,p.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:p.getSerializedFormWithContext()}),{locator:f,pageState:a,a11yNode:p,displayString:p.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:p?.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 p=await e.evaluate(gc,{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml}),h=Math.floor(.1*t.nodeOnlySerializedHtml.length);if(p.closestDistance&&p.closestDistance>=h){let g=`Closest HTML candidate still has too far distance (${p.closestDistance}) from threshold (${h})`;i.push({type:"HTML_DISTANCE",matched:!1,reason:g,distance:p.closestDistance,closestElement:p.closestNodeSerialized})}else{if(p.error)throw new Error(p.error);if(p.dataMomenticId){let g=parseInt(p.dataMomenticId),f=this.dataMomenticIdToNodeMap.get(g),S;f?S=await this.getLocatorFromA11yNode(f):S=e.locator(`[${qe}="${g}"]`);let w=p.closestNodeSerialized??await gn(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 ${h} string comparison distance of the saved element.`,distance:p.closestDistance,closestElement:w,savedElement:t.nodeOnlySerializedHtml}),this.logger.debug({result:p,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(p)}`)}}catch(p){this.logger.debug({err:p},"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: ${p}`})}}let u=t.screenshotUrl,d=t.role??"";if(u&&vs.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.warn({err:m},"Did not find any close element using saved screenshot")}throw this.logger.debug({target:t,decisions:i},"Failed to find any relevant node"),new ut(`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=Bg(),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 p=t.boundingBox?.width??0,h=t.boundingBox?.height??0;if(Math.abs(d-p)>50)throw n=`Rejecting target from screenshot due to width difference (${d-p})`,new Error(n);if(Math.abs(m-h)>50)throw n=`Rejecting target from screenshot due to height difference (${m-h})`,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.getActivePageOrFrame(),{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(`[${qe}="${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=Ns(n.suggestedFilename()),i=t();await n.saveAs(Mc(i,s)),Pc(o,{force:!0}),setTimeout(()=>{Pc(i,{recursive:!0,force:!0})},5*60*1e3);let a=Os(Lc(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=1,s=await t.getAttribute("type",{timeout:1e3})??"",i=Tc.some(a=>a===s.toLowerCase());for(;o>0;)try{await t.click({timeout:4e3,force:n.force,noWaitAfter:!0,position:i?{x:1,y:1}:void 0});break}catch(a){if(o--,o===0)throw new R("ActionFailureError",a.message,{cause:a});this.logger.warn({err:a},"Failed clicking on element for type action, retrying...")}return this.directTypeHelper(e,n)}async click(e,t,n={}){let o,s=await wc({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
|
|
1773
|
+
${h.getSerializedFormWithContext()}`;i.push({type:"A11Y_DISTANCE",matched:!1,reason:f,distance:m,closestElement:p.getNodeOnlySerializedForm(),savedElement:t.serializedForm})}else{let f=await this.getLocatorFromA11yNode(p);return await this.saveNodeDetailsToCache(e,p,t,p.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:p.getSerializedFormWithContext()}),{locator:f,pageState:a,a11yNode:p,displayString:p.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:p?.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 p=await e.evaluate(gc,{nodeOnlySerializedHtml:t.nodeOnlySerializedHtml}),h=Math.floor(.1*t.nodeOnlySerializedHtml.length);if(p.closestDistance&&p.closestDistance>=h){let g=`Closest HTML candidate still has too far distance (${p.closestDistance}) from threshold (${h})`;i.push({type:"HTML_DISTANCE",matched:!1,reason:g,distance:p.closestDistance,closestElement:p.closestNodeSerialized})}else{if(p.error)throw new Error(p.error);if(p.dataMomenticId){let g=parseInt(p.dataMomenticId),f=this.dataMomenticIdToNodeMap.get(g),S;f?S=await this.getLocatorFromA11yNode(f):S=e.locator(`[${qe}="${g}"]`);let w=p.closestNodeSerialized??await gn(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 ${h} string comparison distance of the saved element.`,distance:p.closestDistance,closestElement:w,savedElement:t.nodeOnlySerializedHtml}),this.logger.debug({result:p,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(p)}`)}}catch(p){this.logger.debug({err:p},"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: ${p}`})}}let u=t.screenshotUrl,d=t.role??"";if(u&&vs.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.warn({err:m},"Did not find any close element using saved screenshot")}throw this.logger.debug({target:t,decisions:i},"Failed to find any relevant node"),new ut(`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=Bg(),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 p=t.boundingBox?.width??0,h=t.boundingBox?.height??0;if(Math.abs(d-p)>50)throw n=`Rejecting target from screenshot due to width difference (${d-p})`,new Error(n);if(Math.abs(m-h)>50)throw n=`Rejecting target from screenshot due to height difference (${m-h})`,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.getActivePageOrFrame(),{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(`[${qe}="${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=Ns(n.suggestedFilename()),i=t();await n.saveAs(Mc(i,s)),Pc(o,{force:!0}),setTimeout(()=>{Pc(i,{recursive:!0,force:!0})},5*60*1e3);let a=Os(Lc(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=1,s=await t.getAttribute("type",{timeout:1e3})??"",i=Tc.some(a=>a===s.toLowerCase());for(;o>0;)try{await t.click({timeout:4e3,force:n.force,noWaitAfter:!0,position:i?{x:1,y:1}:void 0});break}catch(a){if(o--,o===0)throw new R("ActionFailureError",a.message,{cause:a});this.logger.warn({err:a},"Failed clicking on element for type action, retrying...")}return this.directTypeHelper(e,n)}async click(e,t,n={}){let o,s=await wc({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 Ug.TimeoutError?new R("ActionFailureError",`Download did not complete in ${1e4}ms`):d}})());let c=1,u=Date.now();for(;c>0;)try{if(n.doubleClick)await e.dblclick({button:n.rightClick?"right":"left",timeout:4e3,position:o,force:n.force,noWaitAfter:!0});else{let d=null;try{d=await e.getAttribute("target",{timeout:1e3})}catch(m){this.logger.warn({err:m},"Failed to get target attribute of element to be clicked, continuing...")}if(await e.click({button:n.rightClick?"right":"left",timeout:4e3,position:o,force:n.force,noWaitAfter:!0}),d==="_blank"){this.logger.debug("Waiting for new page promise due to _blank target");let m=Date.now(),p=this.pageLoadTimeout;for(;!this.pageLoadPromise&&Date.now()-m<p;)await X(250)}}this.logger.debug({duration:Date.now()-u},"Click completed on element");break}catch(d){if(c--,c===0)throw new R("ActionFailureError",d.message,{cause:d});this.logger.warn({err:d},"Failed clicking on element, retrying..."),await X(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 wo(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&&Yt(u,this.logger)){await this.switchToPage(u,c);break}}try{await(await this.getActivePageOrFrame()).waitForURL(t,{timeout:Math.max(s/i,500),waitUntil:"domcontentloaded"});break}catch{if(l===i-1)throw new Error(`The browser did not navigate to '${t}' in the allocated timeout of ${s}ms. Current tabs:
|
|
1774
1774
|
${a.join(`
|
|
1775
|
-
`)}`);continue}}try{await this.loadFrameAndRecordUrl(this.page)}catch(l){this.logger.debug({err:l},"Failed waiting for page load after URL change, continuing...")}}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 X(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.getActivePageOrFrame()).evaluate(dc);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 X(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.warn({err:i},"Failed selecting option, retrying...")}}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.loadFrameAndRecordUrl(this.page)};await this.wrapPageLoad(n)}async getBrowserStateHelper({skipWait:e=!1,filterByViewport:t=!1,logger:n=this.logger}){let o={};await nt(()=>Promise.resolve(this.pageLoadPromise),"pageLoad",o);let s=await this.getActivePageOrFrameHelper(),i=await this.getViewportOffsetDetails(s),a;if(this.activeFrame){let d=this.activeFrame;a=(await nt(()=>this.getMatchingFrame(d),"frameFetch",o)).node.frameId,n.debug({iframeId:a},"Resolved iframe id")}let l=await nt(()=>this.getRawA11yTree({root:s,skipWait:e,iframeId:a,logger:n}),"a11yFetch",o),c=await nt(()=>this.getDOMTree(i.devicePixelRatio,a),"domFetch",o),u=await nt(()=>ic({a11yGraph:l,domGraph:c,logger:n,cdpClient:this.cdpClient,filterByViewport:t,viewportDetails:i}),"a11yProcess",o);if(!u||!u.root)throw new Error("Accessibility tree appears empty");return this.a11yIdToNodeMap=u.a11yIdNodeMap,this.dataMomenticIdToNodeMap=u.dataMomenticIdMap,this.domGraph=c,this.logger.debug(o,"Fetched browser state"),u}async getBrowserState(e){let{logger:t=this.logger,maxAttempts:n=2}=e,o=0,s;for(;o<n;){o++;try{return await wo(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:po}),!n||!n.documents.length)throw new Error("Got empty DOM tree")}catch(s){await X(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 cc({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 X(500),i)try{let{data:l}=await this.cdpClient.send("Page.captureScreenshot",{optimizeForSpeed:!0,quality:25,format:"jpeg"});if(l!==i){i=l;continue}}catch{}else try{let{data:l}=await this.cdpClient.send("Page.captureScreenshot",{optimizeForSpeed:!0,quality:25,format:"jpeg"});i=l}catch{}if(!(Date.now()-e.value<750)){n=!0;break}}let a={duration:Date.now()-o,a11yStableReceived:n};n?t.debug(a,"A11y wait phase completed"):t.warn(a,"A11y wait phase completed due to timeout, continuing...")}async getRawA11yTree({root:e,skipWait:t=!1,iframeId:n=void 0,logger:o=this.logger}){let s={};t||await this.waitForDOMStability({logger:o}),await nt(async()=>e.evaluate("window.addIdsToElement(document.body, 1)"),"addIdsToElement",s);let i;if(n)i=(await nt(()=>this.cdpClient.send("Accessibility.getRootAXNode",{frameId:n}),"getRootAXNodeWithIframe",s)).node.backendDOMNodeId;else{let{node:l}=await nt(()=>this.cdpClient.send("Accessibility.getRootAXNode"),"getRootAXNode",s);i=l.backendDOMNodeId}let{nodes:a}=await nt(()=>this.cdpClient.send("Accessibility.queryAXTree",{backendNodeId:i}),"queryAXTree",s);if(!a||a.length<=1)throw new R("ActionFailureError","The page has no content. Are you sure it is working properly?");return Object.values(s).some(l=>typeof l=="number"&&l>500)&&o.warn({logTimings:s,numNodes:a.length},"Getting raw a11y tree took a long time"),{root:a[0],allNodes:a}}async clickUsingVisualCoordinates(e,t){let n=await this.getActivePageOrFrame(),{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.getActivePageOrFrame(),{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),p=Math.ceil(c*a),h=Math.ceil(u*l);await this.page.mouse.move(d,m),await this.page.mouse.down(),await this.page.mouse.move(p,h),await X(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){let t=await this.getActivePageOrFrame(),{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,qe);if(!s)throw new Error(`Could not find attribute ${qe} 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.getActivePageOrFrame()).locator(`[${qe}="${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,noWaitAfter:!0})};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 X(500)}let i=e.parent?.children??[];for(let l of i){if(l.id===e.id)continue;let c=!1,u=Ps(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<Zl;){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[m=0,p=0,h=0,g=0]=u[d];m/=n,p/=n,h/=n,g/=n;let f=m+h/2,S=p+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.getActivePageOrFrame()).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()||lt;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;try{await o.detach()}catch{}}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(!Yt(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.loadFrameAndRecordUrl(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 Ds(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;return typeof e=="string"?t=ea(e):t=[e],await this.context.addCookies(t),t}async setLocalStorage(e,t){await(await this.getActivePageOrFrame()).evaluate(([o,s])=>{o&&localStorage.setItem(o,s||"")},[e,t])}async solveCloudflareTurnstile(){let t=(await this.getActivePageOrFrame()).locator(".cf-turnstile").locator("iframe").getAttribute("data-sitekey"),n=await fetch("https://2captcha.com/in.php",{method:"POST",body:JSON.stringify({key:Ar,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 X(2500);let i=await fetch(`https://2captcha.com/res.php?key=${Ar}&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.getActivePageOrFrame()).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:Ar,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 X(2500);let a=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:Ar,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.getActivePageOrFrame()).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.debug("[MOMENTIC] Target capture listener fired"),i.preventDefault(),i.stopImmediatePropagation(),o=i.target,!1),document.addEventListener("mousedown",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,m=d.width??0,p=d.height??0,h=d.x??0,g=h+(d.width??0),f=d.y??0,S=f+(d.height??0);return h<l&&g>s&&f<u&&S>c?Math.abs(i-m)<200&&Math.abs(a-p)<200?!0:(Sr({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):(Sr({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=Ig();for(let c of n)if(c.attributes?.[qe]===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 recording");let{htmlAttributes:t,dataMomenticId:n}=e,s=this.dataMomenticIdToNodeMap.get(n),i={id:s?.id??-1,dataMomenticId:n,targetSource:"CLICK_TO_FIND",targetUpdateTime:new Date().toUTCString(),...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,m=this.dataMomenticIdToNodeMap,p=this.mostRecentA11yTree,h=m.get(u),g={id:h?.id??-1,dataMomenticId:u,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),...d};h?this.saveA11yDetailsToCache(h,g):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=p?.serialize();h&&f&&f.length>5e3&&(f=ac(h.id,f),this.logger.debug({serializedTree:f},"Trimmed a11y tree for description transformation"));try{await this.transformer.recordElementAction({type:o,target:g,browserState:f,url:c,selectedValue:l})}catch(S){this.logger.error({err:S},`Failed to record ${o} action`)}})()};await this.context.exposeBinding("isRecordingActive",()=>!!this.transformer),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,n)=>{this.transformer&&this.transformer.recordKeystroke(n)})}async fetchA11yTreeForRecording(){let e=await this.getBrowserState({skipWait:!0,maxAttempts:1});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.getActivePageOrFrame()).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()},ec),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 getActivePageOrFrame(){if(!this.activeFrame)return this.page;if(this.activeFrameCache)if(JSON.stringify(this.activeFrame)!==this.activeFrameCache.frameIdentifierStringified)this.activeFrameCache=void 0;else if("isDetached"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isDetached())this.activeFrameCache=void 0;else if("isClosed"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isClosed())this.activeFrameCache=void 0;else return this.activeFrameCache.frame;let e=Date.now(),t,n;for(;Date.now()-e<this.smartWaitingTimeout;)try{t=await this.getActivePageOrFrameHelper();break}catch(o){n=o,await X(500)}if(t)return this.activeFrameCache={frame:t,frameIdentifierStringified:JSON.stringify(this.activeFrame),cacheTime:Date.now()},t;throw n}async loadFrameAndRecordUrl(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.getActivePageOrFrame();await hn(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 Mg.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 evaluateFunctionInPage(e,t){return this.page.evaluate(t,e)}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=2e3}){let s=vc(),i={code:e,fragment:t,context:n},{result:a}=await wo(this.page.evaluate(s,i),{milliseconds:o,fallback:()=>{throw new R("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)}});return a}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),m=Math.ceil(s*n);await this.cdpClient.send("DOM.getDocument",{depth:0});let p;try{p=await this.cdpClient.send("DOM.getNodeForLocation",{x:d+u,y:m+c})}catch(h){throw this.logger.error({err:h,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 p}async highlightFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return n?(await this.cdpClient.send("Overlay.highlightNode",{highlightConfig:lc,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.getActivePageOrFrame(),n=await this.getDomNodeFromPositionPercentages(t,e),o=this.domGraph?.backendIdToNode[n.backendNodeId],s=o?.attributes[qe],i=parseInt(s??"");if(!o||!s||isNaN(i))throw new Error("No HTML node was found at the given location");let a=t.locator(`[${qe}="${s}"]`);for(let d of this.a11yIdToNodeMap.values()){if(d.backendNodeID!==n.backendNodeId)continue;let m={id:d.id,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString()};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?.[qe]??"");if(isNaN(m))continue;let p=t.locator(`[${qe}="${m}"]`),h=this.dataMomenticIdToNodeMap.get(m),g=h?.id;if(!g)continue;let f={id:g,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString()};return await this.saveNodeDetailsToCache(t,h,f,parseInt(s),p),this.logger.debug({target:f},"Redirected click on non-accessible element to nearest a11y node"),{target:f,locator:p}}let c=await this.fetchHtmlAttributes(t,i);return{target:{id:-1,dataMomenticId:i,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...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.getActivePageOrFrame(),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.getActivePageOrFrame(),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.getActivePageOrFrame(),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!!Ar}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)}logToUserConsole(e,t,n,...o){let s=this.context.pages().indexOf(e);s=s===-1?0:s,_s(e,this.debugData,s,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e}){if(!Ic(e)){let n=`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`;this.logger.error(n),this.logToUserConsole(this.page,"error",n);return}this.page.once("filechooser",async n=>{this.logger.debug({filePath:e},"File chooser triggered");try{if(!Ic(e))throw new Error(`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`);await n.setFiles(e,{timeout:8e3})}catch(o){this.logger.error({err:o},"Error handling file chooser"),this.logToUserConsole(this.page,"error",o.message)}});let t=Og(e).toString("base64");await(await this.getActivePageOrFrame()).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:Lc(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}retrieveAndClearConsoleLogs(){let e=this.debugData.logsPerPage;return this.debugData.logsPerPage=[],e}};var Wg=({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=_.getSession(a);if(!d){r.emit("error",{message:"No session to reset"});return}let{controller:m,context:p}=d;await m.browser.reset({clearCookies:!0,clearStorage:!0,url:o});let h=m.browser.baseUrl;p.reset({baseUrl:h,currentUrl:m.browser.url(),variablesFromEnvironment:c?.variables??{},envName:s}),u=await m.browser.getViewport();let g=ot.USER_AGENT;t.info(`Session reset for test ${i} at ${h}`),r.emit("session",{url:h,userAgent:g,viewport:u,sessionId:a})},Nc={event:"reset",createHandler:Wg};var Gg=({metadata:r})=>{let{sessionId:e}=r;return async({url:t})=>{let n=_.getSession(e);if(!n)throw new Error("No active session found");await n.controller.browser.switchToPage(t)}},_c={event:"switchTab",createHandler:Gg};var jg=({metadata:r})=>{let{sessionId:e}=r;return({indices:t},n)=>{let o=_.getSession(e);if(!o)return;let s=o.resultsManager.getContextCopyAtIndices(t)??o.context.toRedactedDisplayCopy();Qo(s),n(s)}},Dc={event:"getTestContext",createHandler:jg};import{PostHog as Vg}from"posthog-node";var Kg=new Vg("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://app.posthog.com"}),Rr=class r extends Bn{static async init(e){let t={},n,o=0,s=3;for(;o<s;)try{t=await Kg.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 kc=process.env.GCP_TEMPLATE_MATCHING_FUNCTION_ENDPOINT,To=class{constructor(e){this.logger=e}async runTemplateMatching({searchImageBase64String:e,pageImageBase64String:t,id:n,timeoutMs:o=3e3}){if(!kc)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(kc,{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 $n(u)}if(!c.ok)throw new Error(`Template matching server returned error code: ${c.status}`);try{let u=await c.json();return Nn.parse(u)}catch(u){throw new Error(`Error parsing template matching response: ${u}`)}}};var qg={type:"a11y",version:"1.0.0",useHistory:"diff",useGoalSplitter:!0},Sn=qg;import fh from"dedent";import Sh from"diff-lines";import{cloneDeep as yh}from"lodash-es";import{z as Ir}from"zod";var Fc=Ir.object({doubleClick:Ir.boolean().optional(),rightClick:Ir.boolean().optional(),force:Ir.boolean().optional(),waitForDownload:Ir.boolean().optional(),waitForUrl:Ir.string().optional()});import{randomUUID as ht}from"crypto";var Yg=["Shift","CapsLock","Dead","Meta","AudioVolumeUp","AudioVolumeDown"],Co=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:{id:ht(),type:"PRESET_ACTION",command:Rt(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 p=Rt(a);l={id:ht(),type:"PRESET_ACTION",command:{...p,target:{type:"description",elementDescriptor:c},cache:{target:n}}};break;case"SELECT":a="SELECT_OPTION";let h=Rt(a);l={id:ht(),type:"PRESET_ACTION",command:{...h,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(p){this.logger.error({err:p},"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(Yg.includes(t)||this.signal.aborted)return;let s="normal";t.length>1&&(s="special");let i;if(s==="normal"){let p=Rt("TYPE");i={id:ht(),type:"PRESET_ACTION",command:{...p,target:void 0,value:t,clearContent:!1}}}else{let p=Rt("PRESS");i={id:ht(),type:"PRESET_ACTION",command:{...p,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 p=d.value,h=i.command.value;i={id:ht(),type:"PRESET_ACTION",command:{...d,value:i.command.type==="PRESS"?`${p}+${h}`:`${p}${h}`}},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 p=d.value;i={id:ht(),type:"PRESET_ACTION",command:{...d,value:p.slice(0,p.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=Rt(d);m.deltaY=Math.abs(a);let p={id:ht(),type:"PRESET_ACTION",command:m};this.onStepRecord(p,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=Rt(d);m.deltaX=Math.abs(a);let p={id:ht(),type:"PRESET_ACTION",command:m};this.onStepRecord(p,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 ks=(r,e,t)=>{let[n,...o]=e.split("."),s=n;return o.length>=1?ks(r[s],o.join("."),t):r[s]=t,r};import ah from"p-timeout";var yn={"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 Eo=3.1;function Xg(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 vo(r){return Math.ceil(Fs(r)/Eo)}function Fs(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
|
|
1775
|
+
`)}`);continue}}try{await this.loadFrameAndRecordUrl(this.page)}catch(l){this.logger.debug({err:l},"Failed waiting for page load after URL change, continuing...")}}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 X(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.getActivePageOrFrame()).evaluate(dc);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 X(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.warn({err:i},"Failed selecting option, retrying...")}}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.loadFrameAndRecordUrl(this.page)};await this.wrapPageLoad(n)}async getBrowserStateHelper({skipWait:e=!1,filterByViewport:t=!1,logger:n=this.logger}){let o={};await nt(()=>Promise.resolve(this.pageLoadPromise),"pageLoad",o);let s=await this.getActivePageOrFrameHelper(),i=await this.getViewportOffsetDetails(s),a;if(this.activeFrame){let d=this.activeFrame;a=(await nt(()=>this.getMatchingFrame(d),"frameFetch",o)).node.frameId,n.debug({iframeId:a},"Resolved iframe id")}let l=await nt(()=>this.getRawA11yTree({root:s,skipWait:e,iframeId:a,logger:n}),"a11yFetch",o),c=await nt(()=>this.getDOMTree(i.devicePixelRatio,a),"domFetch",o),u=await nt(()=>ic({a11yGraph:l,domGraph:c,logger:n,cdpClient:this.cdpClient,filterByViewport:t,viewportDetails:i}),"a11yProcess",o);if(!u||!u.root)throw new Error("Accessibility tree appears empty");return this.a11yIdToNodeMap=u.a11yIdNodeMap,this.dataMomenticIdToNodeMap=u.dataMomenticIdMap,this.domGraph=c,this.logger.debug(o,"Fetched browser state"),u}async getBrowserState(e){let{logger:t=this.logger,maxAttempts:n=2}=e,o=0,s;for(;o<n;){o++;try{return await wo(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:po}),!n||!n.documents.length)throw new Error("Got empty DOM tree")}catch(s){await X(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 cc({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 X(500),i)try{let{data:l}=await this.cdpClient.send("Page.captureScreenshot",{optimizeForSpeed:!0,quality:25,format:"jpeg"});if(l!==i){i=l;continue}}catch{}else try{let{data:l}=await this.cdpClient.send("Page.captureScreenshot",{optimizeForSpeed:!0,quality:25,format:"jpeg"});i=l}catch{}if(!(Date.now()-e.value<750)){n=!0;break}}let a={duration:Date.now()-o,a11yStableReceived:n};n?t.debug(a,"A11y wait phase completed"):t.warn(a,"A11y wait phase completed due to timeout, continuing...")}async getRawA11yTree({root:e,skipWait:t=!1,iframeId:n=void 0,logger:o=this.logger}){let s={};t||await this.waitForDOMStability({logger:o}),await nt(async()=>e.evaluate("window.addIdsToElement(document.body, 1)"),"addIdsToElement",s);let i;if(n)i=(await nt(()=>this.cdpClient.send("Accessibility.getRootAXNode",{frameId:n}),"getRootAXNodeWithIframe",s)).node.backendDOMNodeId;else{let{node:l}=await nt(()=>this.cdpClient.send("Accessibility.getRootAXNode"),"getRootAXNode",s);i=l.backendDOMNodeId}let{nodes:a}=await nt(()=>this.cdpClient.send("Accessibility.queryAXTree",{backendNodeId:i}),"queryAXTree",s);if(!a||a.length<=1)throw new R("ActionFailureError","The page has no content. Are you sure it is working properly?");return Object.values(s).some(l=>typeof l=="number"&&l>500)&&o.warn({logTimings:s,numNodes:a.length},"Getting raw a11y tree took a long time"),{root:a[0],allNodes:a}}async clickUsingVisualCoordinates(e,t){let n=await this.getActivePageOrFrame(),{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.getActivePageOrFrame(),{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),p=Math.ceil(c*a),h=Math.ceil(u*l);await this.page.mouse.move(d,m),await this.page.mouse.down(),await this.page.mouse.move(p,h),await X(n.hoverSeconds?Math.min(n.hoverSeconds*1e3,8e3):500),await this.page.mouse.up()}async hoverUsingVisualCoordinates(e){let t=await this.getActivePageOrFrame(),{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,qe);if(!s)throw new Error(`Could not find attribute ${qe} 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.getActivePageOrFrame()).locator(`[${qe}="${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,noWaitAfter:!0})};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 X(500)}let i=e.parent?.children??[];for(let l of i){if(l.id===e.id)continue;let c=!1,u=Ps(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<Zl;){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[m=0,p=0,h=0,g=0]=u[d];m/=n,p/=n,h/=n,g/=n;let f=m+h/2,S=p+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.getActivePageOrFrame()).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()||lt;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;try{await o.detach()}catch{}}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(!Yt(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.loadFrameAndRecordUrl(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 Ds(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;return typeof e=="string"?t=ea(e):t=[e],await this.context.addCookies(t),t}async setLocalStorage(e,t){await(await this.getActivePageOrFrame()).evaluate(([o,s])=>{o&&localStorage.setItem(o,s||"")},[e,t])}async solveCloudflareTurnstile(){let t=(await this.getActivePageOrFrame()).locator(".cf-turnstile").locator("iframe").getAttribute("data-sitekey"),n=await fetch("https://2captcha.com/in.php",{method:"POST",body:JSON.stringify({key:Ar,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 X(2500);let i=await fetch(`https://2captcha.com/res.php?key=${Ar}&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.getActivePageOrFrame()).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:Ar,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 X(2500);let a=await fetch("https://api.2captcha.com/getTaskResult",{method:"POST",body:JSON.stringify({clientKey:Ar,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.getActivePageOrFrame()).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.debug("[MOMENTIC] Target capture listener fired"),i.preventDefault(),i.stopImmediatePropagation(),o=i.target,!1),document.addEventListener("mousedown",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,m=d.width??0,p=d.height??0,h=d.x??0,g=h+(d.width??0),f=d.y??0,S=f+(d.height??0);return h<l&&g>s&&f<u&&S>c?Math.abs(i-m)<200&&Math.abs(a-p)<200?!0:(Sr({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):(Sr({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=Ig();for(let c of n)if(c.attributes?.[qe]===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 recording");let{htmlAttributes:t,dataMomenticId:n}=e,s=this.dataMomenticIdToNodeMap.get(n),i={id:s?.id??-1,dataMomenticId:n,targetSource:"CLICK_TO_FIND",targetUpdateTime:new Date().toUTCString(),...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,m=this.dataMomenticIdToNodeMap,p=this.mostRecentA11yTree,h=m.get(u),g={id:h?.id??-1,dataMomenticId:u,targetSource:"RECORDING",targetUpdateTime:new Date().toUTCString(),...d};h?this.saveA11yDetailsToCache(h,g):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=p?.serialize();h&&f&&f.length>5e3&&(f=ac(h.id,f),this.logger.debug({serializedTree:f},"Trimmed a11y tree for description transformation"));try{await this.transformer.recordElementAction({type:o,target:g,browserState:f,url:c,selectedValue:l})}catch(S){this.logger.error({err:S},`Failed to record ${o} action`)}})()};await this.context.exposeBinding("isRecordingActive",()=>!!this.transformer),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,n)=>{this.transformer&&this.transformer.recordKeystroke(n)})}async fetchA11yTreeForRecording(){let e=await this.getBrowserState({skipWait:!0,maxAttempts:1});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.getActivePageOrFrame()).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()},ec),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 getActivePageOrFrame(){if(!this.activeFrame)return this.page;if(this.activeFrameCache)if(JSON.stringify(this.activeFrame)!==this.activeFrameCache.frameIdentifierStringified)this.activeFrameCache=void 0;else if("isDetached"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isDetached())this.activeFrameCache=void 0;else if("isClosed"in this.activeFrameCache.frame&&this.activeFrameCache.frame.isClosed())this.activeFrameCache=void 0;else return this.activeFrameCache.frame;let e=Date.now(),t,n;for(;Date.now()-e<this.smartWaitingTimeout;)try{t=await this.getActivePageOrFrameHelper();break}catch(o){n=o,await X(500)}if(t)return this.activeFrameCache={frame:t,frameIdentifierStringified:JSON.stringify(this.activeFrame),cacheTime:Date.now()},t;throw n}async loadFrameAndRecordUrl(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.getActivePageOrFrame();await hn(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 Ng.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 evaluateFunctionInPage(e,t){return this.page.evaluate(t,e)}async evaluateCodeInPage({code:e,fragment:t,context:n,timeoutMs:o=2e3}){let s=vc(),i={code:e,fragment:t,context:n},{result:a}=await wo(this.page.evaluate(s,i),{milliseconds:o,fallback:()=>{throw new R("ActionFailureError",`Code evaluation in browser exceeded the allowed timeout of ${o/1e3} seconds`)}});return a}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),m=Math.ceil(s*n);await this.cdpClient.send("DOM.getDocument",{depth:0});let p;try{p=await this.cdpClient.send("DOM.getNodeForLocation",{x:d+u,y:m+c})}catch(h){throw this.logger.error({err:h,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 p}async highlightFromPositionPercentages(e){let t=await this.getActivePageOrFrame(),n;try{n=await this.getDomNodeFromPositionPercentages(t,e)}catch{}return n?(await this.cdpClient.send("Overlay.highlightNode",{highlightConfig:lc,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.getActivePageOrFrame(),n=await this.getDomNodeFromPositionPercentages(t,e),o=this.domGraph?.backendIdToNode[n.backendNodeId],s=o?.attributes[qe],i=parseInt(s??"");if(!o||!s||isNaN(i))throw new Error("No HTML node was found at the given location");let a=t.locator(`[${qe}="${s}"]`);for(let d of this.a11yIdToNodeMap.values()){if(d.backendNodeID!==n.backendNodeId)continue;let m={id:d.id,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString()};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?.[qe]??"");if(isNaN(m))continue;let p=t.locator(`[${qe}="${m}"]`),h=this.dataMomenticIdToNodeMap.get(m),g=h?.id;if(!g)continue;let f={id:g,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString()};return await this.saveNodeDetailsToCache(t,h,f,parseInt(s),p),this.logger.debug({target:f},"Redirected click on non-accessible element to nearest a11y node"),{target:f,locator:p}}let c=await this.fetchHtmlAttributes(t,i);return{target:{id:-1,dataMomenticId:i,targetSource:"XY_PERCENT",targetUpdateTime:new Date().toUTCString(),...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.getActivePageOrFrame(),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.getActivePageOrFrame(),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.getActivePageOrFrame(),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!!Ar}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)}logToUserConsole(e,t,n,...o){let s=this.context.pages().indexOf(e);s=s===-1?0:s,_s(e,this.debugData,s,{type:t,text:`[MOMENTIC] ${n}`,args:o})}async setFileChooserHandlerHelper({filePath:e}){if(!Ic(e)){let n=`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`;this.logger.error(n),this.logToUserConsole(this.page,"error",n);return}this.page.once("filechooser",async n=>{this.logger.debug({filePath:e},"File chooser triggered");try{if(!Ic(e))throw new Error(`File chooser triggered after the source file ${e} has been cleaned up, ignoring...`);await n.setFiles(e,{timeout:8e3})}catch(o){this.logger.error({err:o},"Error handling file chooser"),this.logToUserConsole(this.page,"error",o.message)}});let t=Og(e).toString("base64");await(await this.getActivePageOrFrame()).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:Lc(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}retrieveAndClearConsoleLogs(){let e=this.debugData.logsPerPage;return this.debugData.logsPerPage=[],e}};var Wg=({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=_.getSession(a);if(!d){r.emit("error",{message:"No session to reset"});return}let{controller:m,context:p}=d;await m.browser.reset({clearCookies:!0,clearStorage:!0,url:o});let h=m.browser.baseUrl;p.reset({baseUrl:h,currentUrl:m.browser.url(),variablesFromEnvironment:c?.variables??{},envName:s}),u=await m.browser.getViewport();let g=ot.USER_AGENT;t.info(`Session reset for test ${i} at ${h}`),r.emit("session",{url:h,userAgent:g,viewport:u,sessionId:a})},Nc={event:"reset",createHandler:Wg};var Gg=({metadata:r})=>{let{sessionId:e}=r;return async({url:t})=>{let n=_.getSession(e);if(!n)throw new Error("No active session found");await n.controller.browser.switchToPage(t)}},_c={event:"switchTab",createHandler:Gg};var jg=({metadata:r})=>{let{sessionId:e}=r;return({indices:t},n)=>{let o=_.getSession(e);if(!o)return;let s=o.resultsManager.getContextCopyAtIndices(t)??o.context.toRedactedDisplayCopy();Qo(s),n(s)}},Dc={event:"getTestContext",createHandler:jg};import{PostHog as Vg}from"posthog-node";var Kg=new Vg("phc_WRWd8LYIv6rolgDsyCdrPpxtZhsu6qXAkEwPicl44bI",{host:"https://app.posthog.com"}),Rr=class r extends Bn{static async init(e){let t={},n,o=0,s=3;for(;o<s;)try{t=await Kg.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 kc=process.env.GCP_TEMPLATE_MATCHING_FUNCTION_ENDPOINT,To=class{constructor(e){this.logger=e}async runTemplateMatching({searchImageBase64String:e,pageImageBase64String:t,id:n,timeoutMs:o=3e3}){if(!kc)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(kc,{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 $n(u)}if(!c.ok)throw new Error(`Template matching server returned error code: ${c.status}`);try{let u=await c.json();return Nn.parse(u)}catch(u){throw new Error(`Error parsing template matching response: ${u}`)}}};var qg={type:"a11y",version:"1.0.0",useHistory:"diff",useGoalSplitter:!0},Sn=qg;import fh from"dedent";import Sh from"diff-lines";import{cloneDeep as yh}from"lodash-es";import{z as Ir}from"zod";var Fc=Ir.object({doubleClick:Ir.boolean().optional(),rightClick:Ir.boolean().optional(),force:Ir.boolean().optional(),waitForDownload:Ir.boolean().optional(),waitForUrl:Ir.string().optional()});import{randomUUID as ht}from"crypto";var Yg=["Shift","CapsLock","Dead","Meta","AudioVolumeUp","AudioVolumeDown"],Co=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:{id:ht(),type:"PRESET_ACTION",command:Rt(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 p=Rt(a);l={id:ht(),type:"PRESET_ACTION",command:{...p,target:{type:"description",elementDescriptor:c},cache:{target:n}}};break;case"SELECT":a="SELECT_OPTION";let h=Rt(a);l={id:ht(),type:"PRESET_ACTION",command:{...h,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(p){this.logger.error({err:p},"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(Yg.includes(t)||this.signal.aborted)return;let s="normal";t.length>1&&(s="special");let i;if(s==="normal"){let p=Rt("TYPE");i={id:ht(),type:"PRESET_ACTION",command:{...p,target:void 0,value:t,clearContent:!1}}}else{let p=Rt("PRESS");i={id:ht(),type:"PRESET_ACTION",command:{...p,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 p=d.value,h=i.command.value;i={id:ht(),type:"PRESET_ACTION",command:{...d,value:i.command.type==="PRESS"?`${p}+${h}`:`${p}${h}`}},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 p=d.value;i={id:ht(),type:"PRESET_ACTION",command:{...d,value:p.slice(0,p.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=Rt(d);m.deltaY=Math.abs(a);let p={id:ht(),type:"PRESET_ACTION",command:m};this.onStepRecord(p,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=Rt(d);m.deltaX=Math.abs(a);let p={id:ht(),type:"PRESET_ACTION",command:m};this.onStepRecord(p,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 ks=(r,e,t)=>{let[n,...o]=e.split("."),s=n;return o.length>=1?ks(r[s],o.join("."),t):r[s]=t,r};import ah from"p-timeout";var yn={"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 Eo=3.1;function Xg(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 vo(r){return Math.ceil(Fs(r)/Eo)}function Fs(r){let e=0;if(typeof r=="string"){let t=r;t=t.replaceAll(`
|
|
1776
1776
|
`,""),t=t.replaceAll(" ","");let n=Xg(t);return t.length-n+Eo*n}if(typeof r>"u")return 0;if(typeof r=="number")return String(r).length;if(Array.isArray(r))return r.forEach(t=>{e+=Fs(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*Eo:e+=85*Eo:e+=Fs(t[n])}),e}throw new Error(`Unsupported type passed to token length calculator '${typeof r}': ${r}`)}var Jg=500,Qg=3e3,Zg=8e3,Uc=4e3,zc=/<(\w+) id="(\d+)".*?>/g,eh=/(<\/(\w+?)>)|(<(\w+?).*?\/>)/g,$c=["h1","h2","section","footer","nav","aside","form","label","dialog"],th=[...$c,"span","div","h3"],rh=["table","select","form","ul","ol","menu","pre","code","dialog"],nh=["table","form","dialog","nav","section","ul","select"];function xo({serializedTree:r,tokenLimit:e,logger:t}){let n=vo(r);if(n<=e)return;let o=[],s=r.split(`
|
|
1777
1777
|
`),i=0,a=[],l=0,c=[],u=[],d=!1;for(;i<s.length;){d&&(o.push({ids:c,content:a.join(`
|
|
1778
|
-
`),tokenLength:l}),a=[],l=0,c=u.length?[u[u.length-1].id]:[],d=!1);let h=s[i],g=h.length;g>Uc&&(h=h.slice(0,Uc),t.warn({lineNumber:i,currentLine:h},`Truncated line with ${g} characters during tree chunking`));let f=vo(h);a.push(h),l+=f;let w=Array.from(h.matchAll(zc)).map(
|
|
1779
|
-
`),tokenLength:l});let m=n/o.length,p=Math.min(o.length,Math.ceil(e*1.5/m));return{chunks:o,numRecs:p}}async function ft(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 Ao({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 Mt({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 Mt({action:()=>lh(r,e),frameUrl:r.iframeUrl,browser:e.browser,logger:e.logger})}async function lh(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:m}=e,p=r.description;n&&(p=await We({s:p,context:n,logger:e.logger,localTools:c}));let{serializedTree:h,tree:g}=await ft(l,a,{filterByViewport:o}),f,S=Date.now(),w;for(;!f&&Date.now()-S<3e3;)try{f=await l.screenshot({scale:"css",clearHighlights:!0,retries:0})}catch(x){w=x}if(!f)throw new R("InternalWebAgentError",`Failed to take screenshot of page to locate element: ${w?.message}`);let b=h,T=!1,v=.2*yn["gpt-4o-2024-05-13"],E=xo({serializedTree:h,tokenLimit:v,logger:a});if(E&&u.isBooleanFlagEnabled("locator_rag")){try{u.isBooleanFlagEnabled("rag_keyword_optimization")&&(p=(await d.getExtractedKeywords({goal:p,completionType:"locator"},{disableCache:t,orgId:i})).keywords.join(", "),a.debug({description:p},"Extracted keywords for locator RAG"))}catch(J){a.warn({err:J},"Failed to extract keywords for locator, continuing with original description...")}let H=(await d.getRecommendedChunks({...E,description:p,tokenLimit:v})).ids;H.length===0?a.debug("RAG returned no important information"):(b=g.pruneUsingRelevantIds(new Set(H)).serialize(),a.debug({tree:n},"Pruned a11y tree with RAG"),T=!0)}let I=f.toString("base64");ah(Ao({codePath:"locator",screenshotBuff:f,storage:m,logger:a}),{milliseconds:5e3,fallback:()=>{}});let A=await d.getElementLocation({browserState:b,goal:p,screenshot:I,feedback:void 0},{disableCache:t,orgId:i});a.debug({usedRag:T,result:A},"Got locator result");let P=A.id>0;if(s?.details?.push({type:"AI_LOCATION",matched:P,pageState:b,ragUsed:T,thoughts:A.thoughts}),!P)throw new R("ActionFailureError",`Could not find any relevant element: ${A.thoughts}`);let D={id:A.id,inputDescription:p,targetSource:"AI",targetUpdateTime:new Date().toUTCString()},W=await l.resolveTarget(null,D);if(W.a11yNode?.properties?.hidden&&W.a11yNode?.properties?.hidden!=="false")throw new R("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${W.displayString}`);return{thoughts:A.thoughts,target:D,resolution:W}}import ch from"p-timeout";async function zs({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=mh(i),l=0,c=Date.now(),u,d,m,p=()=>{if(s?.())throw new Ke(`AI assertion cancelled by user.${m?` Last error: ${m.message}`:""}`)},h;for(;!h||h-c<i;){p(),o.info(`Waiting ${a}ms before ${h?"retrying":"trying"} AI assertion`),await X(a,s);try{let g=await dh(n,o,e.storage);if(h=Date.now(),d&&d.serializedTree===g.serializedTree&&d.screenshotBuff.equals(g.screenshotBuff)){o.debug("A11y tree and page screenshot did not change, skipping assertion attempt");continue}d=g,u=await Mt({action:()=>uh(r,g,e),frameUrl:r.iframeUrl,logger:o,browser:n});break}catch(g){m=g instanceof Error?g:new Error(`${g}`),o.info({err:g},`AI_WAIT assert attempt ${l} failed, retrying...`)}finally{l++}}if(!u){let g=`AI assertion still failing after ${i}ms.`;throw m&&(g+=` Latest result: ${m.message}`),new R("AssertionFailureError",g)}return u}async function dh(r,e,t){let n=await ft(r,e),o=await r.screenshot({clearHighlights:!0,scale:"css",retries:2});return ch(Ao({codePath:"assertion",screenshotBuff:o,logger:e,storage:t}),{milliseconds:5e3,fallback:()=>{}}),{...n,screenshotBuff:o}}async function uh(r,e,t){let{browser:n,logger:o,generator:s,orgId:i,flagStore:a}=t,l={type:"ASSERTION"},{serializedTree:c}=e,u=e.screenshotBuff,{tree:d}=e,m=n.url(),p=.2*yn["gpt-4o-2024-05-13"],h=xo({serializedTree:c,tokenLimit:p,logger:o});if(h){let S=r.assertion;try{a.isBooleanFlagEnabled("rag_keyword_optimization")&&(S=(await s.getExtractedKeywords({goal:r.assertion,completionType:"assertion"},{disableCache:!!r.disableCache,orgId:i})).keywords.join(", "),o.debug({description:S},"Extracted keywords for assertion RAG"))}catch(T){o.warn({err:T},"Failed to extract keywords for assertion, continuing with original description...")}let b=(await s.getRecommendedChunks({...h,description:S,tokenLimit:p})).ids;b.length===0?o.debug("RAG returned no important information for assertion"):(c=d.pruneUsingRelevantIds(new Set(b)).serialize(),o.debug({browserState:c},"Pruned a11y tree with RAG"),l.ragUsed=!0)}l.pageState=c;let g={goal:r.assertion,url:m,browserState:c,screenshot:u.toString("base64")},f=await s.getAssertionResult(g,{disableCache:!!r.disableCache,orgId:i});if(f.relevantElements&&(await Promise.all(Array.from(new Set(f.relevantElements)).slice(0,3).map(S=>n.highlight({id:S}))),l.relevantElementsSerialized=f.relevantElements.map(S=>n.getSerializedFormFromA11yId(S)).filter(S=>!!S)),o.debug({usedRag:l.ragUsed,result:f},"Got assertion result"),!f.result)throw new R("AssertionFailureError",f.thoughts);return{succeedImmediately:!1,thoughts:f.thoughts,urlAfterCommand:m,beforeScreenshotOverride:u}}function mh(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 Bc(r){return{createIsolatedFolder:()=>Ms(r)}}async function Hc({assertion:r,element:e,callbacks:t}){switch(await t.highlightTarget(e),r.type){case"ELEMENT_CONTENT":{let n=await e.textContent()??"";if(!$s(n,r.value,r.operation,!!r.negated)){let o=r.negated?Gt[r.operation]:jt[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(!$s(n,r.value,r.operation,!!r.negated)){let o=r.negated?Gt[r.operation]:jt[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:zt*1e3});break}case"EDITABLE":{n=await e.isEditable({timeout:zt*1e3});break}case"EXISTS":{n=!0;break}case"ENABLED":{n=await e.isEnabled({timeout:zt*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?as[r.condition]:ls[r.condition];throw new R("AssertionFailureError",`The element ${o}`)}break}}}async function Wc({timeout:r=zt,...e}){let t=Date.now(),n=r*1e3,o;for(;Date.now()-t<n;)try{await ph(e);return}catch(s){o=s,await X(1e3)}throw o}async function ph({assertion:r,page:e}){switch(r.type){case"CONTENT":{let t=await e.content();if(!$s(t,r.value??"","CONTAINS",!!r.negated)){let n=r.negated?Gt.CONTAINS:jt.CONTAINS;throw new R("AssertionFailureError",`The page ${n} '${r.value}'`)}break}}}function $s(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 gh from"sharp";async function wn(r,e){let t=await r.screenshot(e),n=await gh(t).metadata();return{buffer:t,width:Math.ceil(n.width??0),height:Math.ceil(n.height??0)}}import Bs from"jpeg-js";import hh from"pixelmatch";import Gc from"sharp";async function jc({ctx:r,command:e,disableCache:t,browser:n,targetingWrapper:o,logger:s}){if(e.target&&!it(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 ft(n,s,{skipWait:!1});let i={clearHighlights:!0,scale:"css",hideCaret:!0},a;if(!e.target)a=await wn(n,i);else{let A=await o({ctx:r,target:e.target,cache:e.cache?.target??e.target?.a11yData,action:async P=>{},options:{disableCache:!!t,useSelector:!!e.useSelector,iframeUrl:e.iframeUrl}});if(!A.cache)throw new R("ActionFailureError",`Could not find target given description: ${e.target.elementDescriptor}`);a=await wn(n,{target:A.cache,...i}),e.cache={target:A.cache}}let l;if(e.screenshot.data.startsWith("https://")){let A=await fetch(e.screenshot.data);l=Buffer.from(await A.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 A=`${a.width}x${a.height}`,P=`${e.screenshot.width}x${e.screenshot.height}`;return{fail:!0,thoughts:`Current screenshot (${A}) does not match saved screenshot dimensions (${P}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:l,afterScreenshotOverride:a.buffer,succeedImmediately:!1,urlAfterCommand:n.url()}}let c=Gc(a.buffer),u={width:a.width,height:a.height},d=Gc(l),m={width:e.screenshot.width,height:e.screenshot.height},p,h=u.width*u.height,g=m.width*m.height,f=Math.abs(u.height-m.height),S=Math.abs(u.width-m.width);h>g?(a.buffer=await c.resize(m.width,m.height,{fit:"cover"}).toBuffer(),p="current",a.width=m.width,a.height=m.height):g>h&&(l=await d.resize(u.width,u.height,{fit:"cover"}).toBuffer(),p="saved");let w={data:Buffer.alloc(a.width*a.height*4),width:a.width,height:a.height},b=e.threshold??.1,v=hh(Bs.decode(l).data,Bs.decode(a.buffer).data,w.data,a.width,a.height,{threshold:b,diffColorAlt:[0,255,0]})/(a.width*a.height)*100,E=v>b*100,I=`Visual diff of ${v.toFixed(2)}% detected, which is ${E?"over":"under"} the threshold of ${b*100}%.`;return p&&(I+=` The ${p} screenshot was cropped since it was taller by ${f} pixels and wider by ${S} pixels.`),{fail:E,thoughts:I,beforeScreenshotOverride:a.buffer,afterScreenshotOverride:Bs.encode(w,75).data,succeedImmediately:!1,urlAfterCommand:n.url()}}async function Vc({command:r,browser:e,logger:t}){let n=r.timeout??30,o=null,s=new AbortController,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([h,g])=>h&&g)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([h,g])=>h&&g).forEach(([h,g])=>{a.append(h,g)});let l;if(co(r.url)&&(l=r.url),uo(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(h){t.error({err:h},"Failed to make HTTP request")}},u=async()=>{await new Promise(h=>setTimeout(h,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 m={};d.headers.forEach((h,g)=>{m[g]=h});let p={status:d.status,headers:m};return d.headers.get("content-type")?.includes("json")?p.json=await d.json():d.headers.get("content-type")?.includes("text")&&(p.text=await d.text()),{succeedImmediately:!1,urlAfterCommand:e.url(),data:p}}var wh=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 ft(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 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 getBrowserState(e){return ft(this.browser,this.logger,e)}async locateElement(e){return Us(e,this.getControllerFixtures())}async locateElementWithSelector(e,t){return Mt({action:async()=>{let n={id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},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=[`
|
|
1778
|
+
`),tokenLength:l}),a=[],l=0,c=u.length?[u[u.length-1].id]:[],d=!1);let h=s[i],g=h.length;g>Uc&&(h=h.slice(0,Uc),t.warn({lineNumber:i,currentLine:h},`Truncated line with ${g} characters during tree chunking`));let f=vo(h);a.push(h),l+=f;let w=Array.from(h.matchAll(zc)).map(A=>A&&A.length>=3?{tagName:A[1],id:A[2]}:void 0).filter(A=>!!A),T=Array.from(h.matchAll(eh)).map(A=>A&&(A[2]||A[4])).filter(A=>!!A);T.reverse();for(let A of w)c.push(A.id),u.push(A);for(let A of T){let H=u[u.length-1];H&&H.tagName===A&&u.pop()}let v=u.some(A=>rh.includes(A.tagName)),E=s[i+1]??"",I=vo(E),P=Array.from(E.matchAll(zc)).map(A=>A&&A.length>2?A[1]:void 0).filter(A=>!!A),D=P.some(A=>$c.includes(A)),W=P.some(A=>th.includes(A));l+I>=Zg&&(d=!0),l>=Jg&&(D&&!v||T.some(A=>nh.includes(A)))&&(d=!0),l>=Qg&&W&&!v&&(d=!0),i++}a.length&&o.push({ids:c,content:a.join(`
|
|
1779
|
+
`),tokenLength:l});let m=n/o.length,p=Math.min(o.length,Math.ceil(e*1.5/m));return{chunks:o,numRecs:p}}async function ft(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 Ao({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 Mt({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 Mt({action:()=>lh(r,e),frameUrl:r.iframeUrl,browser:e.browser,logger:e.logger})}async function lh(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:m}=e,p=r.description;n&&(p=await We({s:p,context:n,logger:e.logger,localTools:c}));let{serializedTree:h,tree:g}=await ft(l,a,{filterByViewport:o}),f,S=Date.now(),w;for(;!f&&Date.now()-S<3e3;)try{f=await l.screenshot({scale:"css",clearHighlights:!0,retries:0})}catch(A){w=A}if(!f)throw new R("InternalWebAgentError",`Failed to take screenshot of page to locate element: ${w?.message}`);let b=h,T=!1,v=.2*yn["gpt-4o-2024-05-13"],E=xo({serializedTree:h,tokenLimit:v,logger:a});if(E&&u.isBooleanFlagEnabled("locator_rag")){try{u.isBooleanFlagEnabled("rag_keyword_optimization")&&(p=(await d.getExtractedKeywords({goal:p,completionType:"locator"},{disableCache:t,orgId:i})).keywords.join(", "),a.debug({description:p},"Extracted keywords for locator RAG"))}catch(J){a.warn({err:J},"Failed to extract keywords for locator, continuing with original description...")}let H=(await d.getRecommendedChunks({...E,description:p,tokenLimit:v})).ids;H.length===0?a.debug("RAG returned no important information"):(b=g.pruneUsingRelevantIds(new Set(H)).serialize(),a.debug({tree:n},"Pruned a11y tree with RAG"),T=!0)}let I=f.toString("base64");ah(Ao({codePath:"locator",screenshotBuff:f,storage:m,logger:a}),{milliseconds:5e3,fallback:()=>{}});let x=await d.getElementLocation({browserState:b,goal:p,screenshot:I,feedback:void 0},{disableCache:t,orgId:i});a.debug({usedRag:T,result:x},"Got locator result");let P=x.id>0;if(s?.details?.push({type:"AI_LOCATION",matched:P,pageState:b,ragUsed:T,thoughts:x.thoughts}),!P)throw new R("ActionFailureError",`Could not find any relevant element: ${x.thoughts}`);let D={id:x.id,inputDescription:p,targetSource:"AI",targetUpdateTime:new Date().toUTCString()},W=await l.resolveTarget(null,D);if(W.a11yNode?.properties?.hidden&&W.a11yNode?.properties?.hidden!=="false")throw new R("ActionFailureError",`Momentic's AI found a relevant element to interact with, but it is explicitly marked with an 'aria-hidden' attribute. Please remove this attribute or adjust the element description to locate a different element. Element chosen: ${W.displayString}`);return{thoughts:x.thoughts,target:D,resolution:W}}import ch from"p-timeout";async function zs({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=mh(i),l=0,c=Date.now(),u,d,m,p=()=>{if(s?.())throw new Ke(`AI assertion cancelled by user.${m?` Last error: ${m.message}`:""}`)},h;for(;!h||h-c<i;){p(),o.info(`Waiting ${a}ms before ${h?"retrying":"trying"} AI assertion`),await X(a,s);try{let g=await dh(n,o,e.storage);if(h=Date.now(),d&&d.serializedTree===g.serializedTree&&d.screenshotBuff.equals(g.screenshotBuff)){o.debug("A11y tree and page screenshot did not change, skipping assertion attempt");continue}d=g,u=await Mt({action:()=>uh(r,g,e),frameUrl:r.iframeUrl,logger:o,browser:n});break}catch(g){m=g instanceof Error?g:new Error(`${g}`),o.info({err:g},`AI_WAIT assert attempt ${l} failed, retrying...`)}finally{l++}}if(!u){let g=`AI assertion still failing after ${i}ms.`;throw m&&(g+=` Latest result: ${m.message}`),new R("AssertionFailureError",g)}return u}async function dh(r,e,t){let n=await ft(r,e),o=await r.screenshot({clearHighlights:!0,scale:"css",retries:2});return ch(Ao({codePath:"assertion",screenshotBuff:o,logger:e,storage:t}),{milliseconds:5e3,fallback:()=>{}}),{...n,screenshotBuff:o}}async function uh(r,e,t){let{browser:n,logger:o,generator:s,orgId:i,flagStore:a}=t,l={type:"ASSERTION"},{serializedTree:c}=e,u=e.screenshotBuff,{tree:d}=e,m=n.url(),p=.2*yn["gpt-4o-2024-05-13"],h=xo({serializedTree:c,tokenLimit:p,logger:o});if(h){let S=r.assertion;try{a.isBooleanFlagEnabled("rag_keyword_optimization")&&(S=(await s.getExtractedKeywords({goal:r.assertion,completionType:"assertion"},{disableCache:!!r.disableCache,orgId:i})).keywords.join(", "),o.debug({description:S},"Extracted keywords for assertion RAG"))}catch(T){o.warn({err:T},"Failed to extract keywords for assertion, continuing with original description...")}let b=(await s.getRecommendedChunks({...h,description:S,tokenLimit:p})).ids;b.length===0?o.debug("RAG returned no important information for assertion"):(c=d.pruneUsingRelevantIds(new Set(b)).serialize(),o.debug({browserState:c},"Pruned a11y tree with RAG"),l.ragUsed=!0)}l.pageState=c;let g={goal:r.assertion,url:m,browserState:c,screenshot:u.toString("base64")},f=await s.getAssertionResult(g,{disableCache:!!r.disableCache,orgId:i});if(f.relevantElements&&(await Promise.all(Array.from(new Set(f.relevantElements)).slice(0,3).map(S=>n.highlight({id:S}))),l.relevantElementsSerialized=f.relevantElements.map(S=>n.getSerializedFormFromA11yId(S)).filter(S=>!!S)),o.debug({usedRag:l.ragUsed,result:f},"Got assertion result"),!f.result)throw new R("AssertionFailureError",f.thoughts);return{succeedImmediately:!1,thoughts:f.thoughts,urlAfterCommand:m,beforeScreenshotOverride:u}}function mh(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 Bc(r){return{createIsolatedFolder:()=>Ms(r)}}async function Hc({assertion:r,element:e,callbacks:t}){switch(await t.highlightTarget(e),r.type){case"ELEMENT_CONTENT":{let n=await e.textContent()??"";if(!$s(n,r.value,r.operation,!!r.negated)){let o=r.negated?Gt[r.operation]:jt[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(!$s(n,r.value,r.operation,!!r.negated)){let o=r.negated?Gt[r.operation]:jt[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:zt*1e3});break}case"EDITABLE":{n=await e.isEditable({timeout:zt*1e3});break}case"EXISTS":{n=!0;break}case"ENABLED":{n=await e.isEnabled({timeout:zt*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?as[r.condition]:ls[r.condition];throw new R("AssertionFailureError",`The element ${o}`)}break}}}async function Wc({timeout:r=zt,...e}){let t=Date.now(),n=r*1e3,o;for(;Date.now()-t<n;)try{await ph(e);return}catch(s){o=s,await X(1e3)}throw o}async function ph({assertion:r,page:e}){switch(r.type){case"CONTENT":{let t=await e.content();if(!$s(t,r.value??"","CONTAINS",!!r.negated)){let n=r.negated?Gt.CONTAINS:jt.CONTAINS;throw new R("AssertionFailureError",`The page ${n} '${r.value}'`)}break}}}function $s(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{Jimp as gh}from"jimp";async function wn(r,e){let t=await r.screenshot(e),n=await gh.fromBuffer(t);return{buffer:t,width:Math.ceil(n.width??0),height:Math.ceil(n.height??0)}}import{Jimp as Gc}from"jimp";import Bs from"jpeg-js";import hh from"pixelmatch";async function jc({ctx:r,command:e,disableCache:t,browser:n,targetingWrapper:o,logger:s}){if(e.target&&!it(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 ft(n,s,{skipWait:!1});let i={clearHighlights:!0,scale:"css",hideCaret:!0},a;if(!e.target)a=await wn(n,i);else{let x=await o({ctx:r,target:e.target,cache:e.cache?.target??e.target?.a11yData,action:async P=>{},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 wn(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}`,P=`${e.screenshot.width}x${e.screenshot.height}`;return{fail:!0,thoughts:`Current screenshot (${x}) does not match saved screenshot dimensions (${P}) - did you change the size of the target or the viewport?`,beforeScreenshotOverride:l,afterScreenshotOverride:a.buffer,succeedImmediately:!1,urlAfterCommand:n.url()}}let c=await Gc.fromBuffer(a.buffer),u={width:a.width,height:a.height},d=await Gc.fromBuffer(l),m={width:e.screenshot.width,height:e.screenshot.height},p,h=u.width*u.height,g=m.width*m.height,f=Math.abs(u.height-m.height),S=Math.abs(u.width-m.width);if(h>g){let x=c.cover({w:m.width,h:m.height});a.buffer=await x.getBuffer("image/jpeg"),p="current",a.width=m.width,a.height=m.height}else g>h&&(l=await d.cover({w:u.width,h:u.height}).getBuffer("image/jpeg"),p="saved");let w={data:Buffer.alloc(a.width*a.height*4),width:a.width,height:a.height},b=e.threshold??.1,v=hh(Bs.decode(l).data,Bs.decode(a.buffer).data,w.data,a.width,a.height,{threshold:b,diffColorAlt:[0,255,0]})/(a.width*a.height)*100,E=v>b*100,I=`Visual diff of ${v.toFixed(2)}% detected, which is ${E?"over":"under"} the threshold of ${b*100}%.`;return p&&(I+=` The ${p} screenshot was cropped since it was taller by ${f} pixels and wider by ${S} pixels.`),{fail:E,thoughts:I,beforeScreenshotOverride:a.buffer,afterScreenshotOverride:Bs.encode(w,75).data,succeedImmediately:!1,urlAfterCommand:n.url()}}async function Vc({command:r,browser:e,logger:t}){let n=r.timeout??30,o=null,s=new AbortController,i=Object.fromEntries(Object.entries(r.headers||{}).filter(([h,g])=>h&&g)),a=new URLSearchParams;Object.entries(r.params||{}).filter(([h,g])=>h&&g).forEach(([h,g])=>{a.append(h,g)});let l;if(co(r.url)&&(l=r.url),uo(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(h){t.error({err:h},"Failed to make HTTP request")}},u=async()=>{await new Promise(h=>setTimeout(h,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 m={};d.headers.forEach((h,g)=>{m[g]=h});let p={status:d.status,headers:m};return d.headers.get("content-type")?.includes("json")?p.json=await d.json():d.headers.get("content-type")?.includes("text")&&(p.text=await d.text()),{succeedImmediately:!1,urlAfterCommand:e.url(),data:p}}var wh=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 ft(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 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 getBrowserState(e){return ft(this.browser,this.logger,e)}async locateElement(e){return Us(e,this.getControllerFixtures())}async locateElementWithSelector(e,t){return Mt({action:async()=>{let n={id:-1,selector:e,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},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=[`
|
|
1780
1780
|
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(dn(s.urlBeforeCommand,e))o.push(` URL CHANGE: '${s.urlBeforeCommand}' -> '${e}'`);else{let a=Sh(s.browserStateBeforeCommand,t,{n_surrounding:1});a?a.length<wh?(o.push("PAGE CONTENT CHANGE:"),a.split(`
|
|
1781
1781
|
`).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(`
|
|
1782
1782
|
`)}getListHistory(){return fh`Here are the commands that you have successfully executed:
|
|
1783
1783
|
${this.commandHistory.filter(e=>e.type==="AI_ACTION").map(e=>`- ${e.serializedCommand}`).join(`
|
|
1784
|
-
`)}`}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=Lt(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 Mt({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)&&!Uo(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 p={id:-1,selector:t.elementDescriptor,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},h=await this.browser.resolveTarget(e,p,{targetName:l});return{result:await o(h.locator),cache:p,elementInteractedDisplayString:h.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 m=!!n&&Rn(n);if(!n){this.logger.debug({targetHealingInProgress:c},"Prompting AI for an updated element location"),d&&await X(this.browser.smartWaitingTimeout);let p=await Us({description:t.elementDescriptor,disableCache:i,iframeUrl:s.iframeUrl},this.getControllerFixtures(e));u--;let h=await o(p.resolution.locator);return c&&(p.target={...p.target,targetSource:"AI_HEALED",targetUpdateTime:new Date().toUTCString()}),{result:h,cache:p.target,thoughts:p.thoughts,elementInteractedDisplayString:p.resolution.displayString}}try{let p=await this.browser.resolveTarget(e,n,{targetName:l}),h=await o(p.locator);return m?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:p.displayString}}catch(p){if(p instanceof R)throw p;if(u>0&&t)return this.logger.debug({err:p,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",p.message,{cause:p})}}async screenshotWithDimensions(e){return wn(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(),m=this.browser.url();if(u&&d.length!==a.length)for(let p=d.length-1;p>=0;p--){let h=d[p];if(Yt(h,this.logger)&&h!==l&&h!==m){await this.browser.switchToPage(h,p);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))ks(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 We({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 Ke("Execution cancelled by user");switch(t.type){case"SUCCESS":let i=t.condition;return i?.assertion.trim()?zs({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 zs({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 g=await this.browser.getCondensedHtml(),f=await this.generator.getTextExtraction({goal:t.goal,browserState:g,returnSchema:t.schema},{disableCache:o,orgId:this.orgId});if(f.result==="NOT_FOUND")throw new R("ActionFailureError","No relevant data found for extraction goal on this page");return{data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"NAVIGATE":if(!co(t.url)&&!uo(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:g=>this.browser.click(g,{}),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&&!it(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:g,thoughts:f,elementInteractedDisplayString:S}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:w=>this.browser.hover(w,!1),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});l=S,g&&(t.cache={target:g}),c=f}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;await X(u,s);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0});break;case"CLICK":{let g=Fc.parse(t);if(Ut(t.target)){await this.browser.clickUsingVisualCoordinates(t.target.percentXYLocation,g);break}let f=this.browser.url(),S={disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl},{elementInteractedDisplayString:w,cache:b,thoughts:T,result:v}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:I=>this.browser.click(I,Bc(this.orgId),g),options:S});b&&(t.cache={target:b});let E={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:w,thoughts:T,data:v};return dn(f,E.urlAfterCommand)&&(E.succeedImmediately=!0,E.succeedImmediatelyReason="URL changed"),E}case"DRAG":{if(Ut(t.fromTarget)&&Ut(t.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(t.fromTarget.percentXYLocation,t.toTarget.percentXYLocation,{force:t.force,hoverSeconds:t.hoverSeconds});break}if(Ut(t.fromTarget)||Ut(t.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{caches:g,elementInteractedDisplayStrings:f}=await this.wrapMultiElementTargetingCommand(e,["from target","to target"],[t.fromTarget,t.toTarget],[t.cache?.fromTarget,t.cache?.toTarget],(S,w)=>this.browser.dragAndDrop(S,w,{force:t.force,hoverSeconds:t.hoverSeconds}),{useSelector:!!t.useSelector,disableCache:o});return g&&g.every(S=>S)&&(t.cache={fromTarget:g[0],toTarget:g[1]}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f[0]}}case"MOUSE_DRAG":{if(t.target&&!it(t.target))throw new Error("Scroll with x/y is not supported yet");let g,f,S;if(t.target?.elementDescriptor){let{cache:T,thoughts:v,elementInteractedDisplayString:E,result:I}=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}});g=I,f=E,S=v,T&&(t.cache={target:T})}let w=parseInt(t.deltaX),b=parseInt(t.deltaY);if(isNaN(w)||isNaN(b))throw new R("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${t.deltaX}, ${t.deltaY})`);return await this.browser.mouseDrag(w,b,t.steps,g,{force:t.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:S}}case"SELECT_OPTION":{if(!it(t.target))throw new Error("Select with x/y is not supported yet");let g=t.target.elementDescriptor,{cache:f,thoughts:S,elementInteractedDisplayString:w}=await this.wrapElementTargetingCommand({ctx:e,target:{type:"description",elementDescriptor:Jr(t,g)},cache:t.cache?.target,action:b=>this.browser.selectOption(b,t.option,t.force),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return f&&(t.cache={target:f}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:w,thoughts:S}}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;let d=await this.browser.setCookie(t.value);this.logger.debug({results:d},"Set cookies");break;case"LOCAL_STORAGE":if(!t.value||!t.key)break;await this.browser.setLocalStorage(t.key,t.value);break;case"JAVASCRIPT":{let g;try{t.environment==="BROWSER"?g=await this.browser.evaluateCodeInPage({code:t.code,fragment:t.fragment??!1,context:n.toObjectCopy(),timeoutMs:t.timeout?t.timeout*1e3:void 0}):g=await vr({code:t.code,fragment:!!t.fragment,context:n,timeoutMs:t.timeout?t.timeout*1e3:void 0,logger:this.logger,localTools:this.localCodeEvalTools})}catch(f){throw new R("ActionFailureError",f instanceof Error?f.message:`${f}`,{cause:f})}try{JSON.stringify(g)}catch(f){throw new R("ActionFailureError",`Return value is not serializable: ${f instanceof Error?f.message:`${f}`}`,{cause:f})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:g}}case"TYPE":{let g=this.browser.url(),f,S,w=yh(t.target);if(w){w.elementDescriptor=Jr(t,w.elementDescriptor);let{elementInteractedDisplayString:T,cache:v,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,target:w,cache:t.cache?.target,action:I=>this.browser.typeIntoTarget(t.value,I,{force:t.force,clearContent:t.clearContent,pressKeysSequentially:t.pressKeysSequentially,pressEnter:t.pressEnter}),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});S=E,f=T,v&&(t.cache={target:v})}else await this.browser.type(t.value,{force:t.force,clearContent:t.clearContent,pressKeysSequentially:t.pressKeysSequentially,pressEnter:t.pressEnter},!0);let b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:f,thoughts:S};return dn(g,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}case"HOVER":{if(Ut(t.target)){await this.browser.hoverUsingVisualCoordinates(t.target.percentXYLocation);break}let{cache:g,thoughts:f,elementInteractedDisplayString:S}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:w=>this.browser.hover(w,!!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"FOCUS":{if(!it(t.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:g,cache:f,thoughts:S}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:w=>this.browser.focus(w),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return f&&(t.cache={target:f}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:S}}case"BLUR":{if(!it(t.target))throw new Error("Blur with x/y is not supported yet");let{cache:g,thoughts:f,elementInteractedDisplayString:S}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:w=>this.browser.blur(w),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"PRESS":let m=this.browser.url();await this.browser.press(t.value);let p={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return dn(m,p.urlAfterCommand)&&(p.succeedImmediately=!0,p.succeedImmediatelyReason="URL changed"),p;case"REQUEST":return Vc({command:t,browser:this.browser,logger:this.logger});case"VISUAL_DIFF":return jc({ctx:e,command:t,disableCache:o,browser:this.browser,logger:this.logger,targetingWrapper:g=>this.wrapElementTargetingCommand(g)});case"FILE_UPLOAD":{let g=t.fileSource.url;if(!g.startsWith("http")&&!g.startsWith(fn))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 f=await yc({uri:g,logger:this.logger,orgId:this.orgId});await this.browser.setFileChooserHandler(f);break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let g=await vr({code:t.storageState,fragment:!1,context:n,logger:this.logger,localTools:this.localCodeEvalTools});if(typeof g!="object")throw new R("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let f;try{f=ta.parse(g)}catch(S){throw new R("ActionFailureError",`Credentials provided do not follow the required format: ${S}`)}await this.browser.loadAuthState(f);break}case"ELEMENT_CHECK":{if(t.target&&!it(t.target))throw new Error("Element assertion with x/y is not supported yet");let g=Date.now(),f=(t.timeout??zt)*1e3,S=0,w;for(;S<2||Date.now()-g<f;){S++;try{let{cache:b,thoughts:T,elementInteractedDisplayString:v}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:async E=>{await Hc({assertion:t.assertion,element:E,callbacks:{highlightTarget:async I=>this.browser.highlightTarget(I)}})},options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return b&&(t.cache={target:b}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:v,thoughts:T}}catch(b){if(w=b,t.assertion.type==="ELEMENT_EXISTENCE"&&t.assertion.negated)return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}}throw new R("AssertionFailureError",`Element check still failing after ${Math.floor((Date.now()-g)/1e3)} seconds: ${w?w.message:""}`)}case"PAGE_CHECK":{await Mt({frameUrl:t.iframeUrl,browser:this.browser,logger:this.logger,action:async()=>Wc({assertion:t.assertion,page:await this.browser.getActivePageOrFrame(),logger:this.logger,timeout:t.timeout})});break}default:return(g=>{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 Co({signal:this.recordAbortController.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,t),t}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,orgId:this.orgId})}};var bh=4;async function Kc({socket:r,logger:e,storage:t,devicePixelRatio:n,generator:o,browserbase:s,authorization:i}){let a=r.id,l=r.handshake.query.testId,c=r.handshake.query.baseUrl,u=r.handshake.query.envName,d=r.handshake.query.viewport?JSON.parse(decodeURIComponent(r.handshake.query.viewport)):void 0,m=we.parse(JSON.parse(decodeURIComponent(r.handshake.query.testMetadata)));if(!l||!c)throw new Error("Socket connection request is missing testId or baseUrl");let p=await t.getOrgId(l);e=e.child({testId:l,baseUrl:c,orgId:p});let h=r.handshake.query.environmentVariables?JSON.parse(decodeURIComponent(r.handshake.query.environmentVariables)):{};if(await Promise.all((m.parameters??[]).map(async w=>{let b=await We({s:w.defaultValue,context:se.dummyContext(u,h),logger:e,localTools:S});h[w.name]=b})),_.getSession(a))return e.info("Associating connection with existing session (likely reconnect)"),{sessionId:a,orgId:p,testId:l};let f=r.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:f,event:"connect",args:r.handshake.query},"Websocket event (connect)"),f&&_.getCurrentConnectionsByIp(f)>=bh)throw e.error({clientIp:f,sessions:_.getCurrentSessionsByIp(),...r.handshake.query},"Socket connection browser creation rate limit triggered"),new Error("You have exceeded the maximum number of connections allowed. Momentic limits the number of simultaneously open tabs to uphold browser reliability. Please close duplicate tabs and retry or contact Momentic support if you believe this is in error.");_.reserveCapacityByIp(f);let S;i?.type==="API_KEY"&&(S=new pt(i));try{await Th({socket:r,baseUrl:c,envName:u,viewport:d,testMetadata:m,orgId:p,sessionId:a,logger:e,environmentVariables:h,clientIp:f,devicePixelRatio:n,storage:t,localCodeEvalTools:S,generator:o,browserbase:s})}catch(w){throw e.warn({err:w},"Error setting up socket session, possibly due to client closing the connection"),_.releaseCapacityByIp(f),w}return{sessionId:a,testId:l,orgId:p}}async function Th({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:p}){let h={};t&&(h.viewport=t),o&&(h.deviceScaleFactor=o);let g=qr.parse(s?.advanced??{}),[f,S]=await Promise.all([ot.init({baseUrl:e,userBrowserSettings:g,waitForLoad:!0,enricher:new To(l),timeout:g.pageLoadTimeoutMs,storage:c,logger:l,contextArgs:h,onTabsChange:(E,I)=>{r.emit("tabs",{tabs:E,activeTab:I})}}),Rr.init(i)]),w=new Pr({browser:f,generator:d,config:Sn,logger:l,flagStore:S,orgId:i,storage:c,localCodeEvalTools:u}),b=Cl(r,a,l),T=async()=>{clearInterval(b.timer)},v=new se({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:ot.USER_AGENT,viewport:await w.browser.getViewport(),sessionId:a}),_.registerSession({controller:w,context:v,sessionId:a,cleanup:T,clientIp:p})}var qc=[vl,$l,Bl,Nc,El,Dc,_c,Wl,Vl,Kl,Gl,Hl,ql,jl];var Yc=r=>{let{logger:e}=r,t=new Ch(r.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:3e4,pingInterval:6e4,maxHttpBufferSize:1e7});return t.on("connection",async n=>{let o=e.child({socketId:n.id}),s;try{o.info({event:"connection",transport:n.conn.transport.name},"Websocket connection established"),s=await Kc({...r,socket:n,logger:o}),o=o.child(s)}catch(i){o.error({event:"connection",type:"websocket",err:i},"Failed to setup connection"),n.emit("error",{message:i instanceof Error?i.message:`${i}`}),n.disconnect(!0);return}qc.forEach(i=>Eh(i,{socket:n,metadata:s,...r,logger:o}))}),t},Eh=(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 Ah}from"zod";import vh from"fetch-retry";var xh=vh(global.fetch),pe=class{static API_VERSION="v1";baseURL;apiKey;constructor(e){this.baseURL=e.baseURL,this.apiKey=e.apiKey}async sendRequest(e,t){let n=await xh(`${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 Jt=class extends pe{constructor(e){super(e)}async getRecommendedChunks(e){let t=await this.sendRequest(`/${pe.API_VERSION}/web-agent/recommend-chunks`,e);return Ki.parse(t)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${pe.API_VERSION}/s3/visual-diff-screenshot`,{url:e});return Ah.string().parse(t)}async getElementLocation(e,t){let n=await this.sendRequest(`/${pe.API_VERSION}/web-agent/locate-element`,{...e,disableCache:t.disableCache});return Sa.parse(n)}async getAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache},o=await this.sendRequest(`/${pe.API_VERSION}/web-agent/assertion`,{...n,history:"",numPrevious:0,lastCommand:null});return fa.parse(o)}async getProposedCommand(e,t){let n=await this.sendRequest(`/${pe.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 ha.parse(n)}async getGranularGoals(e,t){let n=await this.sendRequest(`/${pe.API_VERSION}/web-agent/split-goal`,{url:e.url,goal:e.goal,disableCache:t.disableCache});return ya.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${pe.API_VERSION}/web-agent/reverse-mapped-description`,{goal:e.goal,browserState:e.browserState,disableCache:t.disableCache});return wa.parse(n)}async getTextExtraction(e,t){let n={goal:e.goal,browserState:e.browserState,returnSchema:e.returnSchema,disableCache:t.disableCache},o=await this.sendRequest(`/${pe.API_VERSION}/web-agent/text-extraction`,n);return rs.parse(o)}async getTestResultClassification(e){let t=await this.sendRequest(`/${pe.API_VERSION}/web-agent/result-classification`,e);return Zo.parse(t)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${pe.API_VERSION}/web-agent/extract-keywords`,{goal:e,disableCache:t.disableCache});return Ji.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${pe.API_VERSION}/web-agent/autoheal-section`,e);return Vi.parse(n)}};import{Router as Rh}from"express";function Me(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Xc=Rh();Xc.get("/",Me((r,e)=>{let t=Tl();e.status(200).json(t)}));var Jc=Xc;import{Router as Mh}from"express";import Qc,{multistream as Ih}from"pino";import Ph from"pino-pretty";var Hs=new Map,Lh=!0,Ws=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=Lh?Qc(a):Qc(a,Ih([{stream:Ph({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}},Ro=({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 Ws({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 Oh}from"os";var Ne=Ro({app:"desktop-server",clientToken:"pubcfd7516a5c0ba852b42675cd97bee027",hostname:Oh(),excludeAttributesInConsoleLogs:!0,excludeTimestamps:!0,disableConsoleLogs:!0});var bn=Mh();bn.get("/",Me(async(r,e)=>{let n=(await gl(Ne)).filter(o=>o.enabled??!0);e.status(200).json(n)}));bn.get("/metadata",Me((r,e)=>{let t=pl();e.status(200).json(t)}));bn.post("/",Me(async(r,e)=>{let t;try{t=ua.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}try{Qr(t.name)}catch(o){e.status(400).json({error:`Invalid module name: ${o}`});return}let n=await ml(t.name,t.description,t.enabled,t.steps);e.status(201).json(n)}));bn.get("/:moduleId",Me(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await hl(r.params.moduleId,Ne);if(!t){e.status(404).json({error:"Module not found."});return}e.json(t)}));var Zc=bn;import{Router as Nh}from"express";import{existsSync as _h}from"fs";import{join as Po}from"path";import{v4 as Dh}from"uuid";var js="https://api.momentic.ai",ed=r=>{js=r},Tn=()=>js,Lr,Gs,td=async r=>{if(Lr)return Lr;let e=new he({baseUrl:js,apiKey:r});try{return Lr=await e.getOrgId(),Gs=r,Lr}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Io=()=>{if(!Lr)throw new Error("Your organization ID appears invalid. Please contact Momentic support.");return Lr},rd=()=>{if(!Gs)throw new Error("Your API key appears invalid. Please contact Momentic support.");return Gs};var Qt=Nh();Qt.get("/",Me((r,e)=>{let t=sn(me,Ne);e.status(200).json(t)}));Qt.post("/",Me(async(r,e)=>{let t;try{t=da.parse(r.body)}catch(a){e.status(400).json({error:`Invalid request body: ${a}`});return}try{Qr(t.name)}catch(a){e.status(400).json({error:a.message});return}let o={id:Dh(),name:t.name,baseUrl:t.baseUrl,schemaVersion:Pe,advanced:{disableAICaching:!1,viewport:t.viewport??lt},retries:0,steps:[]};t.environment&&(o.envs=[{name:t.environment,default:!0}]);let s=await yl(o,t.name),i={...o,testPath:s};e.status(201).json(i)}));Qt.get("/:testPath",Me(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t=Po(me,r.params.testPath);if(!_h(t)){e.status(400).json({error:`Test not found at path: ${t}`});return}let n=await ro(t,Ot,Ne);e.status(200).json(n)}));Qt.patch("/:testPath/metadata",Me(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=ca.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}let n=Po(me,r.params.testPath);to(t,n),e.status(201).json({message:"ok"})}));Qt.patch("/:testPath",Me(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=la.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}let n=Po(me,r.params.testPath),o;try{o=wl(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 et({steps:t.steps,cacheCreationParams:{testId:o.id,orgId:Io()}});i.forEach(c=>ul({...c,schemaVersion:Pe})),to({schemaVersion:Pe,steps:s},n),await new he({apiKey:rd(),baseUrl:Tn()}).updateStepCaches({entries:a,testId:o.id}),e.status(201).json({message:"ok"})}));Qt.patch("/:testPath/environments",Me(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=ma.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}let n=Po(me,r.params.testPath);to({envs:t.defaultEnv?[{name:t.defaultEnv,default:!0}]:[]},n),e.status(201).json({message:"ok"})}));var nd=Qt;async function od(r){let{momenticServerUrl:e,apiKey:t,serverPort:n,appPort:o,staticDir:s,devicePixelRatio:i}=r;if(!Uh(me)||!zh(me).isDirectory()){let f=Hh.isAbsolute(me);throw new Error(`Root folder ${me} does not exist${f?"":` in the current directory ("${process.cwd()}")`}. Please run \`npx momentic@latest init\` if you wish to setup Momentic here for the first time.`)}e&&ed(e),Ne.debug(r,"Initializing desktop server");let a=await td(t);Ne.debug({orgId:a},"Checking API key successful");let c=`http://localhost:${n}`;o&&(c=`http://localhost:${o}`);let u=Wh(s);await new Promise(f=>{u.listen(n,()=>{Ne.info(`Server is running at http://localhost:${n}`),f()})});let m=new Jt({baseURL:Tn(),apiKey:t}),p={type:"API_KEY",baseUrl:Tn(),apiKey:t},h=new he(p),g=new Er(h,Io());Yc({baseServer:u,generator:m,storage:g,logger:Ne,devicePixelRatio:i,authorization:p}),await Bh(c)}function Wh(r){let e=Vs();e.use(Fh()),e.use(kh.json({limit:"25mb"}));let t=Vs.Router();if(t.use("/tests",nd),t.use("/modules",Zc),t.use("/environments",Jc),e.use("/api",t),e.use((o,s,i)=>{o.path!=="/healthcheck"&&Ne.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&&Ne.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")||(Ne.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=Vs.static(r);e.use("/",o),e.use("*",o)}return $h.createServer(e)}import{existsSync as Yf}from"fs";import jd,{dirname as Xf,join as Jf}from"path";import{chdir as Qf}from"process";import{fileURLToPath as Zf}from"url";import Cn from"chalk";var Nt=(...r)=>{ae(Cn.blue(...r))};var Re=(...r)=>{ae(Cn.dim(...r))};var Ie=(...r)=>{ae(Cn.green(...r))},ae=(...r)=>{console.log(...r)},le=(...r)=>{console.error(Cn.yellow(...r))},M=(...r)=>{console.error(Cn.red(...r))};import{hostname as Gh}from"os";var L=Ro({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:Gh(),excludeAttributesInConsoleLogs:!0,excludeTimestamps:!0,disableConsoleLogs:!0});import{execSync as jh}from"child_process";import{platform as Vh}from"os";function Ks(){return sd()?(Nt("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),Nt("If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations."),Nt("Confirm your device's pixel-ratio at https://www.mydevice.io."),2):(Nt("Setting device pixel ratio to 1."),Nt("If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations"),Nt("Confirm your device's pixel-ratio at https://www.mydevice.io."),1)}function sd(){return Vh()==="darwin"&&jh("system_profiler SPDisplaysDataType").toString().includes("Retina")}function qs(r){sd()&&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 ud}from"crypto";import{existsSync as md,readFileSync as ei,writeFileSync as pd}from"fs";import{join as gd}from"path";import{parse as cf}from"yaml";import{existsSync as Js,mkdirSync as ad,readdirSync as rf,statSync as ld}from"fs";import{homedir as cd}from"os";import{join as St,resolve as nf}from"path";import{existsSync as Kh,statSync as qh}from"fs";var Lo=!!process.env.CI||!process.stdout.isTTY;function _t(r){try{return Kh(r)&&qh(r).isDirectory()}catch(e){return M({err:e},`Error reading path ${r} during directory existence check`),!1}}import{registry as Ys}from"playwright-core/lib/server";function Yh(r){let e=[],t=[];for(let n of r){let o=Ys.findExecutable(n);!o||o.installType==="none"?e.push(n):t.push(o)}return t}async function Oo(){let r=Yh(["chromium"]);await Ys.installDeps(r,!1),await Ys.install(r,!1)}import{existsSync as Xh,mkdirSync as Jh,statSync as Qh}from"fs";import{dirname as Zh}from"path";import ef from"readline/promises";var Xs=!1,tf=(()=>{try{return Qh("/.dockerenv"),!0}catch{return!1}})();async function Ye(r,e){if(Lo||Xs||tf)return!0;L.flush(),await new Promise(i=>setTimeout(i,500));let t=ef.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):ae(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"?(Xs=!0,setTimeout(()=>{Xs=!1},3e3),!0):s.toLowerCase()==="y"}async function En(r){let e=Zh(r);return _t(e)?Xh(r)?Ye(`File '${id(r)}' already exists. Overwrite existing content?`,!0):!0:await Ye(`Directory '${id(e)}' doesn't exist. Create it now?`,!0)?(Jh(e,{recursive:!0}),!0):!1}function id(r){return r.replace(/(\s+)/g,"\\$1")}var of=[Pt,Hn,fr],yt=lf(),Zt=St(yt,Pt),Zs=St(yt,Hn),wt=St(yt,fr),Qs=St(cd(),"momentic",ss),dd=[Zt,Zs,wt];async function bt(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<20)&&(M(`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 r.installBrowsers&&await Oo(),await af(r),n}async function sf(r){_t(yt)||!r&&!await Ye(`The root '${It}' folder was not found in the current directory. You will need to invoke the Momentic CLI from this directory in the future. Proceed?`)&&(M("Setup cancelled."),process.exit(1)),_t(Qs)||(!r&&!await Ye("The Chrome cache folder was not found in your home directory. Proceed with creation?")&&(M("Setup cancelled."),process.exit(1)),ad(Qs,{recursive:!0}));for(let e of dd)_t(e)||(!r&&!await Ye(`'${e}' folder was not found in the current directory. Create it now?`)&&(M("Setup cancelled."),process.exit(1)),ad(e,{recursive:!0}))}function vn(r,e,t=new Set){for(let n of r){let o=nf(n),s=!1;try{s=Js(o)&&ld(o).isDirectory()}catch(i){L.error({err:i},`Error reading path ${o} during collect paths`)}if(o&&s){let i=rf(o).map(a=>St(o,a));vn(i,e,t);continue}if(o.endsWith(".yaml")){try{if(!Js(o)||!ld(o).isFile()){L.error(`File not found or unreadable: ${o}`);continue}}catch(i){L.error({err:i},`Error reading file ${o} during collect paths`);continue}if(!e(o))continue;t.add(o)}}return t}async function af({client:r,createFolders:e,skipPrompts:t,pullEnvs:n}){if(cd()||(M("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 sf(t);else for(let o of[yt,Qs,...dd])!_t(o)&&!Lo&&(M(`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.`),M(`The current working directory is: ${process.cwd()}`),process.exit(1));n&&(!t&&!await Ye("Pull environments from Momentic Cloud? Environment definitions may be required to run tests locally.")&&(M("Setup cancelled."),process.exit(1)),await Mo({client:r,all:!0,skipPrompts:t}))}function lf(){let r=n=>Js(St(n,It))&&of.some(o=>_t(St(n,It,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 ${It} folder, treating ${t} as the Momentic root folder instead`):L.info(`Identified ${t} as the Momentic root folder`),St(t,It)}async function Mo({envNames:r,client:e,all:t,skipPrompts:n}){let o=await e.getAllEnvironments();r&&!t&&(o=o.filter(a=>r?.includes(a.name))),md(wt)||(M(`${wt} 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=gd(wt,`${a.name}.yaml`);if(!n&&!await En(l))return;if(!md(l))pd(l,ps(a)),s.push(l);else{let c=ud("sha256").update(ei(l)).digest("hex"),u=ps(a),d=ud("sha256").update(u).digest("hex");c!==d&&(pd(l,u),i.push(l))}}Ie("Pulled environments successfully!"),s.length&&(Ie("Created:"),s.forEach(a=>Ie(" ",a))),i.length&&(Ie("Updated:"),i.forEach(a=>Ie(" ",a)))}function df(r){return r.endsWith(".yaml")?ei(r,"utf8").includes("momentic/environment")?!0:(le(`Skipping YAML that is not a Momentic environment: ${r}`),!1):!1}async function hd({client:r,names:e,all:t,yes:n}){let o;t?o=[wt]:o=e.map(a=>gd(wt,`${a.toLowerCase()}.yaml`));let s=vn(o,df);ae(`Found ${s.size} environments to push:`),s.forEach(a=>ae(" ",a));let i=[];for(let a of s){let l=cf(ei(a,"utf-8"));try{let c=De.parse(l);i.push(c)}catch(c){M(`${a} failed to parse as a valid environment file.`),M(c),process.exit(1)}}!n&&!await Ye("Pushing environments can overwrite variables on cloud and instantly affect scheduled runs. Continue?",!0)||(await r.updateEnvironments(i),Ie("Pushed environments successfully!"))}import{Argument as xn,Option as Ce}from"@commander-js/extra-typings";import{validateHeaderValue as uf}from"http";import{cpus as fd}from"os";import{parse as mf}from"yaml";import{z as $}from"zod";var No=58888,Tt=new Ce("--api-key <key>","API key for authentication. If not supplied, attempts to read the MOMENTIC_API_KEY env var."),Ct=new Ce("--server <server>","Momentic server to use. Leave unchanged unless using Momentic on-premise."),Et=new Ce("-y, --yes","Skip all confirmation prompts."),ri=new Ce("-w, --wait","Wait for tests to finish running before exiting. Only applicable when running tests remotely").implies({remote:!0}),ni=new Ce("--wait-timeout <waitTimeout>","The maximum number of seconds to wait for tests to complete. Only applicable when the --wait option is specified."),oi=new Ce("--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 si(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);uf(o,s),e[o]=s}return e}var ii=new Ce("--no-report","Skip reporting test results to Momentic Cloud when running with the --local flag.").implies({local:!0}),ai=new Ce("--pixel-ratio <pixelRatio>","Device pixel ratio of your screen or monitor. Mac OS Retina displays and machines marketed as 'HiDPI' should set this to 2. Visit https://www.mydevice.io/ to find your device's pixel ratio."),Sd=new Ce("--port <port>",`Port to run the app on. Defaults to ${No}.`),yd=new Ce("--input-csv <inputCsv>","Path to a CSV file on disk where each row represents a set of inputs that will be made available to all tests that are ran. Only applicable when running locally. The first line of the CSV must be the input names."),li=new Ce("--env <env>","Name of the environment to use when running tests."),ci=new Ce("--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."),di=new Ce("-a, --all","Select all tests in your organization from Momentic Cloud. Cannot be used together with <tests> arguments."),ui=new Ce("-a, --all","Select all environments in your organization from Momentic Cloud. Cannot be used together with <paths> arguments."),wd=new xn("<tests...>",`One or more test paths to pull from Momentic Cloud.
|
|
1784
|
+
`)}`}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=Lt(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 Mt({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)&&!Uo(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 p={id:-1,selector:t.elementDescriptor,targetSource:"USER_CSS_SELECTOR",targetUpdateTime:new Date().toUTCString()},h=await this.browser.resolveTarget(e,p,{targetName:l});return{result:await o(h.locator),cache:p,elementInteractedDisplayString:h.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 m=!!n&&Rn(n);if(!n){this.logger.debug({targetHealingInProgress:c},"Prompting AI for an updated element location"),d&&await X(this.browser.smartWaitingTimeout);let p=await Us({description:t.elementDescriptor,disableCache:i,iframeUrl:s.iframeUrl},this.getControllerFixtures(e));u--;let h=await o(p.resolution.locator);return c&&(p.target={...p.target,targetSource:"AI_HEALED",targetUpdateTime:new Date().toUTCString()}),{result:h,cache:p.target,thoughts:p.thoughts,elementInteractedDisplayString:p.resolution.displayString}}try{let p=await this.browser.resolveTarget(e,n,{targetName:l}),h=await o(p.locator);return m?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:p.displayString}}catch(p){if(p instanceof R)throw p;if(u>0&&t)return this.logger.debug({err:p,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",p.message,{cause:p})}}async screenshotWithDimensions(e){return wn(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(),m=this.browser.url();if(u&&d.length!==a.length)for(let p=d.length-1;p>=0;p--){let h=d[p];if(Yt(h,this.logger)&&h!==l&&h!==m){await this.browser.switchToPage(h,p);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))ks(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 We({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 Ke("Execution cancelled by user");switch(t.type){case"SUCCESS":let i=t.condition;return i?.assertion.trim()?zs({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 zs({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 g=await this.browser.getCondensedHtml(),f=await this.generator.getTextExtraction({goal:t.goal,browserState:g,returnSchema:t.schema},{disableCache:o,orgId:this.orgId});if(f.result==="NOT_FOUND")throw new R("ActionFailureError","No relevant data found for extraction goal on this page");return{data:f.result,succeedImmediately:!1,urlAfterCommand:this.browser.url()}}case"NAVIGATE":if(!co(t.url)&&!uo(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:g=>this.browser.click(g,{}),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&&!it(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:g,thoughts:f,elementInteractedDisplayString:S}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:w=>this.browser.hover(w,!1),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});l=S,g&&(t.cache={target:g}),c=f}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;await X(u,s);break;case"REFRESH":await this.browser.refresh({loadTimeoutMs:t.loadTimeout?t.loadTimeout*1e3:void 0});break;case"CLICK":{let g=Fc.parse(t);if(Ut(t.target)){await this.browser.clickUsingVisualCoordinates(t.target.percentXYLocation,g);break}let f=this.browser.url(),S={disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl},{elementInteractedDisplayString:w,cache:b,thoughts:T,result:v}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:I=>this.browser.click(I,Bc(this.orgId),g),options:S});b&&(t.cache={target:b});let E={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:w,thoughts:T,data:v};return dn(f,E.urlAfterCommand)&&(E.succeedImmediately=!0,E.succeedImmediatelyReason="URL changed"),E}case"DRAG":{if(Ut(t.fromTarget)&&Ut(t.toTarget)){await this.browser.dragAndDropUsingVisualCoordinates(t.fromTarget.percentXYLocation,t.toTarget.percentXYLocation,{force:t.force,hoverSeconds:t.hoverSeconds});break}if(Ut(t.fromTarget)||Ut(t.toTarget))throw new Error("Drag and drop targets must be both coordinates or both descriptions");let{caches:g,elementInteractedDisplayStrings:f}=await this.wrapMultiElementTargetingCommand(e,["from target","to target"],[t.fromTarget,t.toTarget],[t.cache?.fromTarget,t.cache?.toTarget],(S,w)=>this.browser.dragAndDrop(S,w,{force:t.force,hoverSeconds:t.hoverSeconds}),{useSelector:!!t.useSelector,disableCache:o});return g&&g.every(S=>S)&&(t.cache={fromTarget:g[0],toTarget:g[1]}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f[0]}}case"MOUSE_DRAG":{if(t.target&&!it(t.target))throw new Error("Scroll with x/y is not supported yet");let g,f,S;if(t.target?.elementDescriptor){let{cache:T,thoughts:v,elementInteractedDisplayString:E,result:I}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:async x=>x,options:{useSelector:!!t.useSelector,iframeUrl:t.iframeUrl,disableCache:o}});g=I,f=E,S=v,T&&(t.cache={target:T})}let w=parseInt(t.deltaX),b=parseInt(t.deltaY);if(isNaN(w)||isNaN(b))throw new R("ActionFailureError",`Invalid pixel values passed to mouse drag command: (${t.deltaX}, ${t.deltaY})`);return await this.browser.mouseDrag(w,b,t.steps,g,{force:t.force}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:f,thoughts:S}}case"SELECT_OPTION":{if(!it(t.target))throw new Error("Select with x/y is not supported yet");let g=t.target.elementDescriptor,{cache:f,thoughts:S,elementInteractedDisplayString:w}=await this.wrapElementTargetingCommand({ctx:e,target:{type:"description",elementDescriptor:Jr(t,g)},cache:t.cache?.target,action:b=>this.browser.selectOption(b,t.option,t.force),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return f&&(t.cache={target:f}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:w,thoughts:S}}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;let d=await this.browser.setCookie(t.value);this.logger.debug({results:d},"Set cookies");break;case"LOCAL_STORAGE":if(!t.value||!t.key)break;await this.browser.setLocalStorage(t.key,t.value);break;case"JAVASCRIPT":{let g;try{t.environment==="BROWSER"?g=await this.browser.evaluateCodeInPage({code:t.code,fragment:t.fragment??!1,context:n.toObjectCopy(),timeoutMs:t.timeout?t.timeout*1e3:void 0}):g=await vr({code:t.code,fragment:!!t.fragment,context:n,timeoutMs:t.timeout?t.timeout*1e3:void 0,logger:this.logger,localTools:this.localCodeEvalTools})}catch(f){throw new R("ActionFailureError",f instanceof Error?f.message:`${f}`,{cause:f})}try{JSON.stringify(g)}catch(f){throw new R("ActionFailureError",`Return value is not serializable: ${f instanceof Error?f.message:`${f}`}`,{cause:f})}return{urlAfterCommand:this.browser.url(),succeedImmediately:!1,data:g}}case"TYPE":{let g=this.browser.url(),f,S,w=yh(t.target);if(w){w.elementDescriptor=Jr(t,w.elementDescriptor);let{elementInteractedDisplayString:T,cache:v,thoughts:E}=await this.wrapElementTargetingCommand({ctx:e,target:w,cache:t.cache?.target,action:I=>this.browser.typeIntoTarget(t.value,I,{force:t.force,clearContent:t.clearContent,pressKeysSequentially:t.pressKeysSequentially,pressEnter:t.pressEnter}),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});S=E,f=T,v&&(t.cache={target:v})}else await this.browser.type(t.value,{force:t.force,clearContent:t.clearContent,pressKeysSequentially:t.pressKeysSequentially,pressEnter:t.pressEnter},!0);let b={urlAfterCommand:this.browser.url(),succeedImmediately:!1,elementInteracted:f,thoughts:S};return dn(g,b.urlAfterCommand)&&(b.succeedImmediately=!0,b.succeedImmediatelyReason="URL changed"),b}case"HOVER":{if(Ut(t.target)){await this.browser.hoverUsingVisualCoordinates(t.target.percentXYLocation);break}let{cache:g,thoughts:f,elementInteractedDisplayString:S}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:w=>this.browser.hover(w,!!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"FOCUS":{if(!it(t.target))throw new Error("Focus with x/y is not supported yet");let{elementInteractedDisplayString:g,cache:f,thoughts:S}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:w=>this.browser.focus(w),options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return f&&(t.cache={target:f}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:g,thoughts:S}}case"BLUR":{if(!it(t.target))throw new Error("Blur with x/y is not supported yet");let{cache:g,thoughts:f,elementInteractedDisplayString:S}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:w=>this.browser.blur(w),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"PRESS":let m=this.browser.url();await this.browser.press(t.value);let p={urlAfterCommand:this.browser.url(),succeedImmediately:!1};return dn(m,p.urlAfterCommand)&&(p.succeedImmediately=!0,p.succeedImmediatelyReason="URL changed"),p;case"REQUEST":return Vc({command:t,browser:this.browser,logger:this.logger});case"VISUAL_DIFF":return jc({ctx:e,command:t,disableCache:o,browser:this.browser,logger:this.logger,targetingWrapper:g=>this.wrapElementTargetingCommand(g)});case"FILE_UPLOAD":{let g=t.fileSource.url;if(!g.startsWith("http")&&!g.startsWith(fn))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 f=await yc({uri:g,logger:this.logger,orgId:this.orgId});await this.browser.setFileChooserHandler(f);break}case"AUTH_SAVE":return{data:await this.browser.saveAuthState(),succeedImmediately:!1,urlAfterCommand:this.browser.url()};case"AUTH_LOAD":{let g=await vr({code:t.storageState,fragment:!1,context:n,logger:this.logger,localTools:this.localCodeEvalTools});if(typeof g!="object")throw new R("ActionFailureError",`Credentials must evaluate to an object (received ${typeof g} instead)`);let f;try{f=ta.parse(g)}catch(S){throw new R("ActionFailureError",`Credentials provided do not follow the required format: ${S}`)}await this.browser.loadAuthState(f);break}case"ELEMENT_CHECK":{if(t.target&&!it(t.target))throw new Error("Element assertion with x/y is not supported yet");let g=Date.now(),f=(t.timeout??zt)*1e3,S=0,w;for(;S<2||Date.now()-g<f;){S++;try{let{cache:b,thoughts:T,elementInteractedDisplayString:v}=await this.wrapElementTargetingCommand({ctx:e,target:t.target,cache:t.cache?.target,action:async E=>{await Hc({assertion:t.assertion,element:E,callbacks:{highlightTarget:async I=>this.browser.highlightTarget(I)}})},options:{disableCache:o,useSelector:!!t.useSelector,iframeUrl:t.iframeUrl}});return b&&(t.cache={target:b}),{succeedImmediately:!1,urlAfterCommand:this.browser.url(),elementInteracted:v,thoughts:T}}catch(b){if(w=b,t.assertion.type==="ELEMENT_EXISTENCE"&&t.assertion.negated)return{succeedImmediately:!1,urlAfterCommand:this.browser.url()}}}throw new R("AssertionFailureError",`Element check still failing after ${Math.floor((Date.now()-g)/1e3)} seconds: ${w?w.message:""}`)}case"PAGE_CHECK":{await Mt({frameUrl:t.iframeUrl,browser:this.browser,logger:this.logger,action:async()=>Wc({assertion:t.assertion,page:await this.browser.getActivePageOrFrame(),logger:this.logger,timeout:t.timeout})});break}default:return(g=>{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 Co({signal:this.recordAbortController.signal,...e});return await this.browser.startRecording(this.recordAbortController.signal,t),t}async runSectionAutohealing(e){return this.generator.getAutohealingProposal(e,{disableCache:!0,orgId:this.orgId})}};var bh=4;async function Kc({socket:r,logger:e,storage:t,devicePixelRatio:n,generator:o,browserbase:s,authorization:i}){let a=r.id,l=r.handshake.query.testId,c=r.handshake.query.baseUrl,u=r.handshake.query.envName,d=r.handshake.query.viewport?JSON.parse(decodeURIComponent(r.handshake.query.viewport)):void 0,m=we.parse(JSON.parse(decodeURIComponent(r.handshake.query.testMetadata)));if(!l||!c)throw new Error("Socket connection request is missing testId or baseUrl");let p=await t.getOrgId(l);e=e.child({testId:l,baseUrl:c,orgId:p});let h=r.handshake.query.environmentVariables?JSON.parse(decodeURIComponent(r.handshake.query.environmentVariables)):{};if(await Promise.all((m.parameters??[]).map(async w=>{let b=await We({s:w.defaultValue,context:se.dummyContext(u,h),logger:e,localTools:S});h[w.name]=b})),_.getSession(a))return e.info("Associating connection with existing session (likely reconnect)"),{sessionId:a,orgId:p,testId:l};let f=r.handshake.headers["x-forwarded-for"]?.split(",")[0];if(e.info({clientIp:f,event:"connect",args:r.handshake.query},"Websocket event (connect)"),f&&_.getCurrentConnectionsByIp(f)>=bh)throw e.error({clientIp:f,sessions:_.getCurrentSessionsByIp(),...r.handshake.query},"Socket connection browser creation rate limit triggered"),new Error("You have exceeded the maximum number of connections allowed. Momentic limits the number of simultaneously open tabs to uphold browser reliability. Please close duplicate tabs and retry or contact Momentic support if you believe this is in error.");_.reserveCapacityByIp(f);let S;i?.type==="API_KEY"&&(S=new pt(i));try{await Th({socket:r,baseUrl:c,envName:u,viewport:d,testMetadata:m,orgId:p,sessionId:a,logger:e,environmentVariables:h,clientIp:f,devicePixelRatio:n,storage:t,localCodeEvalTools:S,generator:o,browserbase:s})}catch(w){throw e.warn({err:w},"Error setting up socket session, possibly due to client closing the connection"),_.releaseCapacityByIp(f),w}return{sessionId:a,testId:l,orgId:p}}async function Th({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:p}){let h={};t&&(h.viewport=t),o&&(h.deviceScaleFactor=o);let g=qr.parse(s?.advanced??{}),[f,S]=await Promise.all([ot.init({baseUrl:e,userBrowserSettings:g,waitForLoad:!0,enricher:new To(l),timeout:g.pageLoadTimeoutMs,storage:c,logger:l,contextArgs:h,onTabsChange:(E,I)=>{r.emit("tabs",{tabs:E,activeTab:I})}}),Rr.init(i)]),w=new Pr({browser:f,generator:d,config:Sn,logger:l,flagStore:S,orgId:i,storage:c,localCodeEvalTools:u}),b=Cl(r,a,l),T=async()=>{clearInterval(b.timer)},v=new se({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:ot.USER_AGENT,viewport:await w.browser.getViewport(),sessionId:a}),_.registerSession({controller:w,context:v,sessionId:a,cleanup:T,clientIp:p})}var qc=[vl,$l,Bl,Nc,El,Dc,_c,Wl,Vl,Kl,Gl,Hl,ql,jl];var Yc=r=>{let{logger:e}=r,t=new Ch(r.baseServer,{cors:{origin:"*",methods:["GET","POST"]},pingTimeout:3e4,pingInterval:6e4,maxHttpBufferSize:1e7});return t.on("connection",async n=>{let o=e.child({socketId:n.id}),s;try{o.info({event:"connection",transport:n.conn.transport.name},"Websocket connection established"),s=await Kc({...r,socket:n,logger:o}),o=o.child(s)}catch(i){o.error({event:"connection",type:"websocket",err:i},"Failed to setup connection"),n.emit("error",{message:i instanceof Error?i.message:`${i}`}),n.disconnect(!0);return}qc.forEach(i=>Eh(i,{socket:n,metadata:s,...r,logger:o}))}),t},Eh=(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 Ah}from"zod";import vh from"fetch-retry";var xh=vh(global.fetch),pe=class{static API_VERSION="v1";baseURL;apiKey;constructor(e){this.baseURL=e.baseURL,this.apiKey=e.apiKey}async sendRequest(e,t){let n=await xh(`${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 Jt=class extends pe{constructor(e){super(e)}async getRecommendedChunks(e){let t=await this.sendRequest(`/${pe.API_VERSION}/web-agent/recommend-chunks`,e);return Ki.parse(t)}async getScreenshotFromS3(e){let t=await this.sendRequest(`/${pe.API_VERSION}/s3/visual-diff-screenshot`,{url:e});return Ah.string().parse(t)}async getElementLocation(e,t){let n=await this.sendRequest(`/${pe.API_VERSION}/web-agent/locate-element`,{...e,disableCache:t.disableCache});return Sa.parse(n)}async getAssertionResult(e,t){let n={...e,disableCache:!!t.disableCache},o=await this.sendRequest(`/${pe.API_VERSION}/web-agent/assertion`,{...n,history:"",numPrevious:0,lastCommand:null});return fa.parse(o)}async getProposedCommand(e,t){let n=await this.sendRequest(`/${pe.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 ha.parse(n)}async getGranularGoals(e,t){let n=await this.sendRequest(`/${pe.API_VERSION}/web-agent/split-goal`,{url:e.url,goal:e.goal,disableCache:t.disableCache});return ya.parse(n)}async getReverseMappedDescription(e,t){let n=await this.sendRequest(`/${pe.API_VERSION}/web-agent/reverse-mapped-description`,{goal:e.goal,browserState:e.browserState,disableCache:t.disableCache});return wa.parse(n)}async getTextExtraction(e,t){let n={goal:e.goal,browserState:e.browserState,returnSchema:e.returnSchema,disableCache:t.disableCache},o=await this.sendRequest(`/${pe.API_VERSION}/web-agent/text-extraction`,n);return rs.parse(o)}async getTestResultClassification(e){let t=await this.sendRequest(`/${pe.API_VERSION}/web-agent/result-classification`,e);return Zo.parse(t)}async getExtractedKeywords(e,t){let n=await this.sendRequest(`/${pe.API_VERSION}/web-agent/extract-keywords`,{goal:e,disableCache:t.disableCache});return Ji.parse(n)}async getAutohealingProposal(e,t){let n=await this.sendRequest(`/${pe.API_VERSION}/web-agent/autoheal-section`,e);return Vi.parse(n)}};import{Router as Rh}from"express";function Me(r){return function(...e){let t=e[e.length-1],n=r(...e);Promise.resolve(n).catch(t)}}var Xc=Rh();Xc.get("/",Me((r,e)=>{let t=Tl();e.status(200).json(t)}));var Jc=Xc;import{Router as Mh}from"express";import Qc,{multistream as Ih}from"pino";import Ph from"pino-pretty";var Hs=new Map,Lh=!0,Ws=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=Lh?Qc(a):Qc(a,Ih([{stream:Ph({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}},Ro=({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 Ws({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 Oh}from"os";var Ne=Ro({app:"desktop-server",clientToken:"pubcfd7516a5c0ba852b42675cd97bee027",hostname:Oh(),excludeAttributesInConsoleLogs:!0,excludeTimestamps:!0,disableConsoleLogs:!0});var bn=Mh();bn.get("/",Me(async(r,e)=>{let n=(await gl(Ne)).filter(o=>o.enabled??!0);e.status(200).json(n)}));bn.get("/metadata",Me((r,e)=>{let t=pl();e.status(200).json(t)}));bn.post("/",Me(async(r,e)=>{let t;try{t=ua.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}try{Qr(t.name)}catch(o){e.status(400).json({error:`Invalid module name: ${o}`});return}let n=await ml(t.name,t.description,t.enabled,t.steps);e.status(201).json(n)}));bn.get("/:moduleId",Me(async(r,e)=>{if(!r.params.moduleId){e.status(400).json({error:"Missing moduleId in url path."});return}let t=await hl(r.params.moduleId,Ne);if(!t){e.status(404).json({error:"Module not found."});return}e.json(t)}));var Zc=bn;import{Router as Nh}from"express";import{existsSync as _h}from"fs";import{join as Po}from"path";import{v4 as Dh}from"uuid";var js="https://api.momentic.ai",ed=r=>{js=r},Tn=()=>js,Lr,Gs,td=async r=>{if(Lr)return Lr;let e=new he({baseUrl:js,apiKey:r});try{return Lr=await e.getOrgId(),Gs=r,Lr}catch(t){throw new Error(`Error checking API key against server: ${t}`)}},Io=()=>{if(!Lr)throw new Error("Your organization ID appears invalid. Please contact Momentic support.");return Lr},rd=()=>{if(!Gs)throw new Error("Your API key appears invalid. Please contact Momentic support.");return Gs};var Qt=Nh();Qt.get("/",Me((r,e)=>{let t=sn(me,Ne);e.status(200).json(t)}));Qt.post("/",Me(async(r,e)=>{let t;try{t=da.parse(r.body)}catch(a){e.status(400).json({error:`Invalid request body: ${a}`});return}try{Qr(t.name)}catch(a){e.status(400).json({error:a.message});return}let o={id:Dh(),name:t.name,baseUrl:t.baseUrl,schemaVersion:Pe,advanced:{disableAICaching:!1,viewport:t.viewport??lt},retries:0,steps:[]};t.environment&&(o.envs=[{name:t.environment,default:!0}]);let s=await yl(o,t.name),i={...o,testPath:s};e.status(201).json(i)}));Qt.get("/:testPath",Me(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t=Po(me,r.params.testPath);if(!_h(t)){e.status(400).json({error:`Test not found at path: ${t}`});return}let n=await ro(t,Ot,Ne);e.status(200).json(n)}));Qt.patch("/:testPath/metadata",Me(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=ca.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}let n=Po(me,r.params.testPath);to(t,n),e.status(201).json({message:"ok"})}));Qt.patch("/:testPath",Me(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=la.parse(r.body)}catch(c){e.status(400).json({error:`Invalid request body: ${c}`});return}let n=Po(me,r.params.testPath),o;try{o=wl(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 et({steps:t.steps,cacheCreationParams:{testId:o.id,orgId:Io()}});i.forEach(c=>ul({...c,schemaVersion:Pe})),to({schemaVersion:Pe,steps:s},n),await new he({apiKey:rd(),baseUrl:Tn()}).updateStepCaches({entries:a,testId:o.id}),e.status(201).json({message:"ok"})}));Qt.patch("/:testPath/environments",Me(async(r,e)=>{if(!r.params.testPath){e.status(400).json({error:"Missing testPath in url path."});return}let t;try{t=ma.parse(r.body)}catch(o){e.status(400).json({error:`Invalid request body: ${o}`});return}let n=Po(me,r.params.testPath);to({envs:t.defaultEnv?[{name:t.defaultEnv,default:!0}]:[]},n),e.status(201).json({message:"ok"})}));var nd=Qt;async function od(r){let{momenticServerUrl:e,apiKey:t,serverPort:n,appPort:o,staticDir:s,devicePixelRatio:i}=r;if(!Uh(me)||!zh(me).isDirectory()){let f=Hh.isAbsolute(me);throw new Error(`Root folder ${me} does not exist${f?"":` in the current directory ("${process.cwd()}")`}. Please run \`npx momentic@latest init\` if you wish to setup Momentic here for the first time.`)}e&&ed(e),Ne.debug(r,"Initializing desktop server");let a=await td(t);Ne.debug({orgId:a},"Checking API key successful");let c=`http://localhost:${n}`;o&&(c=`http://localhost:${o}`);let u=Wh(s);await new Promise(f=>{u.listen(n,()=>{Ne.info(`Server is running at http://localhost:${n}`),f()})});let m=new Jt({baseURL:Tn(),apiKey:t}),p={type:"API_KEY",baseUrl:Tn(),apiKey:t},h=new he(p),g=new Er(h,Io());Yc({baseServer:u,generator:m,storage:g,logger:Ne,devicePixelRatio:i,authorization:p}),await Bh(c)}function Wh(r){let e=Vs();e.use(Fh()),e.use(kh.json({limit:"25mb"}));let t=Vs.Router();if(t.use("/tests",nd),t.use("/modules",Zc),t.use("/environments",Jc),e.use("/api",t),e.use((o,s,i)=>{o.path!=="/healthcheck"&&Ne.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&&Ne.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")||(Ne.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=Vs.static(r);e.use("/",o),e.use("*",o)}return $h.createServer(e)}import{existsSync as Yf}from"fs";import jd,{dirname as Xf,join as Jf}from"path";import{chdir as Qf}from"process";import{fileURLToPath as Zf}from"url";import Cn from"chalk";var Nt=(...r)=>{ae(Cn.blue(...r))};var Re=(...r)=>{ae(Cn.dim(...r))};var Ie=(...r)=>{ae(Cn.green(...r))},ae=(...r)=>{console.log(...r)},le=(...r)=>{console.error(Cn.yellow(...r))},M=(...r)=>{console.error(Cn.red(...r))};import{hostname as Gh}from"os";var L=Ro({app:"cli",clientToken:"pub7eb923f18fb3f1d42ac5eba8c5ea13a5",hostname:Gh(),excludeAttributesInConsoleLogs:!0,excludeTimestamps:!0,disableConsoleLogs:!0});import{execSync as jh}from"child_process";import{platform as Vh}from"os";function Ks(){return sd()?(Nt("Setting device pixel ratio to 2 automatically since a Mac OS Retina screen was detected."),Nt("If you are using a low pixel-density monitor, you should manually set --pixel-ratio to 1 to avoid incorrect viewport calculations."),Nt("Confirm your device's pixel-ratio at https://www.mydevice.io."),2):(Nt("Setting device pixel ratio to 1."),Nt("If you are using Momentic on a high-pixel density (HiDPI) monitor, relaunch with the --pixel-ratio option to avoid incorrect viewport calculations"),Nt("Confirm your device's pixel-ratio at https://www.mydevice.io."),1)}function sd(){return Vh()==="darwin"&&jh("system_profiler SPDisplaysDataType").toString().includes("Retina")}function qs(r){sd()&&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 ud}from"crypto";import{existsSync as md,readFileSync as ei,writeFileSync as pd}from"fs";import{join as gd}from"path";import{parse as cf}from"yaml";import{existsSync as Js,mkdirSync as ad,readdirSync as rf,statSync as ld}from"fs";import{homedir as cd}from"os";import{join as St,resolve as nf}from"path";import{existsSync as Kh,statSync as qh}from"fs";var Lo=!!process.env.CI||!process.stdout.isTTY;function _t(r){try{return Kh(r)&&qh(r).isDirectory()}catch(e){return M({err:e},`Error reading path ${r} during directory existence check`),!1}}import{registry as Ys}from"playwright-core/lib/server";function Yh(r){let e=[],t=[];for(let n of r){let o=Ys.findExecutable(n);!o||o.installType==="none"?e.push(n):t.push(o)}return t}async function Oo(){let r=Yh(["chromium"]);await Ys.installDeps(r,!1),await Ys.install(r,!1)}import{existsSync as Xh,mkdirSync as Jh,statSync as Qh}from"fs";import{dirname as Zh}from"path";import ef from"readline/promises";var Xs=!1,tf=(()=>{try{return Qh("/.dockerenv"),!0}catch{return!1}})();async function Ye(r,e){if(Lo||Xs||tf)return!0;L.flush(),await new Promise(i=>setTimeout(i,500));let t=ef.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):ae(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"?(Xs=!0,setTimeout(()=>{Xs=!1},3e3),!0):s.toLowerCase()==="y"}async function En(r){let e=Zh(r);return _t(e)?Xh(r)?Ye(`File '${id(r)}' already exists. Overwrite existing content?`,!0):!0:await Ye(`Directory '${id(e)}' doesn't exist. Create it now?`,!0)?(Jh(e,{recursive:!0}),!0):!1}function id(r){return r.replace(/(\s+)/g,"\\$1")}var of=[Pt,Hn,fr],yt=lf(),Zt=St(yt,Pt),Zs=St(yt,Hn),wt=St(yt,fr),Qs=St(cd(),"momentic",ss),dd=[Zt,Zs,wt];async function bt(r){let e=process.versions.node,t=parseInt(e.split(".")[0]);(isNaN(t)||t<20)&&(M(`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 r.installBrowsers&&await Oo(),await af(r),n}async function sf(r){_t(yt)||!r&&!await Ye(`The root '${It}' folder was not found in the current directory. You will need to invoke the Momentic CLI from this directory in the future. Proceed?`)&&(M("Setup cancelled."),process.exit(1)),_t(Qs)||(!r&&!await Ye("The Chrome cache folder was not found in your home directory. Proceed with creation?")&&(M("Setup cancelled."),process.exit(1)),ad(Qs,{recursive:!0}));for(let e of dd)_t(e)||(!r&&!await Ye(`'${e}' folder was not found in the current directory. Create it now?`)&&(M("Setup cancelled."),process.exit(1)),ad(e,{recursive:!0}))}function vn(r,e,t=new Set){for(let n of r){let o=nf(n),s=!1;try{s=Js(o)&&ld(o).isDirectory()}catch(i){L.error({err:i},`Error reading path ${o} during collect paths`)}if(o&&s){let i=rf(o).map(a=>St(o,a));vn(i,e,t);continue}if(o.endsWith(".yaml")){try{if(!Js(o)||!ld(o).isFile()){L.error(`File not found or unreadable: ${o}`);continue}}catch(i){L.error({err:i},`Error reading file ${o} during collect paths`);continue}if(!e(o))continue;t.add(o)}}return t}async function af({client:r,createFolders:e,skipPrompts:t,pullEnvs:n}){if(cd()||(M("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 sf(t);else for(let o of[yt,Qs,...dd])!_t(o)&&!Lo&&(M(`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.`),M(`The current working directory is: ${process.cwd()}`),process.exit(1));n&&(!t&&!await Ye("Pull environments from Momentic Cloud? Environment definitions may be required to run tests locally.")&&(M("Setup cancelled."),process.exit(1)),await Mo({client:r,all:!0,skipPrompts:t}))}function lf(){let r=n=>Js(St(n,It))&&of.some(o=>_t(St(n,It,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 ${It} folder, treating ${t} as the Momentic root folder instead`):L.info(`Identified ${t} as the Momentic root folder`),St(t,It)}async function Mo({envNames:r,client:e,all:t,skipPrompts:n}){let o=await e.getAllEnvironments();r&&!t&&(o=o.filter(a=>r?.includes(a.name))),md(wt)||(M(`${wt} 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=gd(wt,`${a.name}.yaml`);if(!n&&!await En(l))return;if(!md(l))pd(l,ps(a)),s.push(l);else{let c=ud("sha256").update(ei(l)).digest("hex"),u=ps(a),d=ud("sha256").update(u).digest("hex");c!==d&&(pd(l,u),i.push(l))}}Ie("Pulled environments successfully!"),s.length&&(Ie("Created:"),s.forEach(a=>Ie(" ",a))),i.length&&(Ie("Updated:"),i.forEach(a=>Ie(" ",a)))}function df(r){return r.endsWith(".yaml")?ei(r,"utf8").includes("momentic/environment")?!0:(le(`Skipping YAML that is not a Momentic environment: ${r}`),!1):!1}async function hd({client:r,names:e,all:t,yes:n}){let o;t?o=[wt]:o=e.map(a=>gd(wt,`${a.toLowerCase()}.yaml`));let s=vn(o,df);ae(`Found ${s.size} environments to push:`),s.forEach(a=>ae(" ",a));let i=[];for(let a of s){let l=cf(ei(a,"utf-8"));try{let c=De.parse(l);i.push(c)}catch(c){M(`${a} failed to parse as a valid environment file.`),M(c),process.exit(1)}}!n&&!await Ye("Pushing environments can overwrite variables on cloud and instantly affect scheduled runs. Continue?",!0)||(await r.updateEnvironments(i),Ie("Pushed environments successfully!"))}import{Argument as xn,Option as Ce}from"@commander-js/extra-typings";import{validateHeaderValue as uf}from"http";import{cpus as fd}from"os";import{parse as mf}from"yaml";import{z as $}from"zod";var No=58888,Tt=new Ce("--api-key <key>","API key for authentication. If not supplied, attempts to read the MOMENTIC_API_KEY env var."),Ct=new Ce("--server <server>","Momentic server to use. Leave unchanged unless using Momentic on-premise."),Et=new Ce("-y, --yes","Skip all confirmation prompts."),ri=new Ce("-w, --wait","Wait for tests to finish running before exiting. Only applicable when running tests remotely").implies({remote:!0}),ni=new Ce("--wait-timeout <waitTimeout>","The maximum number of seconds to wait for tests to complete. Only applicable when the --wait option is specified."),oi=new Ce("--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 si(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);uf(o,s),e[o]=s}return e}var ii=new Ce("--no-report","Skip reporting test results to Momentic Cloud when running with the --local flag.").implies({local:!0}),ai=new Ce("--pixel-ratio <pixelRatio>","Device pixel ratio of your screen or monitor. Mac OS Retina displays and machines marketed as 'HiDPI' should set this to 2. Visit https://www.mydevice.io/ to find your device's pixel ratio."),Sd=new Ce("--port <port>",`Port to run the app on. Defaults to ${No}.`),yd=new Ce("--input-csv <inputCsv>","Path to a CSV file on disk where each row represents a set of inputs that will be made available to all tests that are ran. Only applicable when running locally. The first line of the CSV must be the input names."),li=new Ce("--env <env>","Name of the environment to use when running tests."),ci=new Ce("--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."),di=new Ce("-a, --all","Select all tests in your organization from Momentic Cloud. Cannot be used together with <tests> arguments."),ui=new Ce("-a, --all","Select all environments in your organization from Momentic Cloud. Cannot be used together with <paths> arguments."),wd=new xn("<tests...>",`One or more test paths to pull from Momentic Cloud.
|
|
1785
1785
|
|
|
1786
1786
|
A test path is a lowercased version of your test name where spaces are replaced with dashes: 'npx momentic@latest pull hello-world'.`).argOptional(),bd=new xn("<tests...>",`One or more test identifiers.
|
|
1787
1787
|
|
|
@@ -1794,9 +1794,9 @@ The suite path is a lowercased version of your suite name where spaces and speci
|
|
|
1794
1794
|
`);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",An(e,...t))}error(e,...t){this._log("error",An(e,...t))}info(e,...t){this._log("info",An(e,...t))}log(e,...t){this._log("log",An(e,...t))}warn(e,...t){this._log("warn",An(e,...t))}getBuffer(){return this._buffer.length>0?this._buffer:void 0}};function Md(r){let e=globalThis.console,t=new _o;globalThis.console=t;try{r()}finally{let o=t.getBuffer()?.map(s=>s.message).join(`
|
|
1795
1795
|
`);process.stderr.write(`${o}
|
|
1796
1796
|
`),globalThis.console=e}}var bf=30*60*1e3,Tf=5;async function Do({getResults:r,checkDone:e,name:t,timeoutMs:n=bf}){let o=Date.now(),s=0;for(;Date.now()-o<n;){let i;s>Tf&&(M(`Failed to fetch ${t} status too many times.`),process.exit(1));try{i=await r(),s=0}catch(c){s++,L.warn({err:c},"Failed to fetch run status, retrying..."),le({err:c},"Failed to fetch run status, retrying..."),await new Promise(u=>setTimeout(u,1500*s));continue}if(e(i))return i;let l=Math.max(1e4,Math.floor(n/100));await new Promise(c=>setTimeout(c,l))}M(`Timeout elapsed waiting for ${t} to complete (${Math.floor(n/1e3)}s).`),process.exit(1)}function Or({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");return Md(()=>{i.forEach(l=>{ae(""),o(l)}),i.length&&(ae(""),M(`${i.length} ${t}s failed:`),i.forEach(l=>{M(n(l))})),a.length&&(ae(""),le(`${a.length} ${t}s cancelled:`),a.forEach(l=>{le(n(l))})),s.length&&(ae(""),Ie(`${s.length} ${t}s passed:`),s.forEach(l=>{Ie(n(l))})),ae(""),Re(`Total time: ${Math.round((Date.now()-e)/1e3)}s`)}),{passed:s.length,failed:i.length,cancelled:a.length}}var ko=(r,e)=>{if(!r.failureDetails||!r.failureReason)return;let t=Di[r.failureDetails?.classification?.reason||r.failureReason],n=r.failureDetails?.classification?.summary||ki[r.failureReason];M(e),ae(` Reason: ${Nd.red(t)}`),ae(` Description: ${Nd.red(n)}`)};async function Dd({client:r,suitePaths:e,wait:t,waitTimeout:n,...o}){let s=(await r.queueSuiteRuns({paths:e,...o})).suiteRunIds;Re(`Queued ${e.length} suites.`),t||process.exit(0);let i=Date.now();Re(`Waiting for ${e.length} suites to complete.`);let a=new Set,l=await Do({name:"suites",getResults:async()=>r.bulkGetSuiteStatus(s),timeoutMs:n?n*1e3:void 0,checkDone:m=>(m.forEach(p=>{if(p.status==="RUNNING"&&!a.has(p.id)){a.add(p.id);let h=p.suite?.name??"Unknown suite";h&&_d(`${a.size}/${s.length} ${Te(h)}`)}}),m.every(p=>p.runs.every(g=>g.status==="FAILED"&&g.failureReason||g.status==="PASSED"||g.status==="CANCELLED")&&(p.status==="FAILED"||p.status==="PASSED"||p.status==="CANCELLED")))});_d.clear();let c=r.getAppUrl(),d=Or({results:l,startTime:i,onFailed:m=>{let p=m.suite?.name?Te(m.suite.name):"Unknown suite",h=m.runs.filter(f=>f.status==="FAILED").length,g=m.runs.length;M(`${p} (${h}/${g} tests failed):`);for(let f of m.runs)if(f.status==="FAILED"){let S=f.testName||f.test?.name;M(` ${S?Te(S):"Unknown test"} (${c}/runs/${f.id})`)}},entity:"suite",getDisplayLine:m=>` ${m.suite?.name?Te(m.suite.name):"Unknown suite"} (${c}/suite-runs/${m.id})`});process.exit(d.failed>0?1:0)}import{existsSync as zd,statSync as Bf}from"fs";import $d from"log-update";import Hf from"path";import Wf from"wait-on";import Cf from"@actions/exec";import Ef from"@actions/io";import vf from"quote";import xf from"string-argv";async function kd(r,e=!0){let t=xf(r),n=await Ef.which(t[0],!0),o=t.slice(1),s=Cf.exec(vf(n),o,{delay:100});if(e)return s}import{diff as Of}from"deep-object-diff";import{readFileSync as Mf}from"fs";import{cloneDeep as Fd}from"lodash-es";import{join as Nf}from"path";import _f from"semver";import{debounce as Df}from"ts-debounce";import{v4 as kf}from"uuid";var Fo=class extends pe{async runTemplateMatching(e){let t=await this.sendRequest(`/${pe.API_VERSION}/web-agent/template-matching`,e);return Nn.parse(t)}};import{parse as Ff}from"yaml";import{existsSync as Af,readFileSync as Rf}from"fs";import{join as If}from"path";import{parse as Pf}from"yaml";function Lf(r){let e=If(Zs,`${r}.yaml`);if(!Af(e))throw new Error(`Fixture '${r}' does not exist at expected path ${e}.`);let t;try{t=Pf(Rf(e,"utf-8").replace(/\r\n|\r/g,`
|
|
1797
|
-
`))}catch(o){throw new Error(`Fixture at path ${e} does not parse as valid YAML.`,{cause:o})}let n;try{n=aa.parse(t)}catch(o){throw new Error(`Fixture at path ${e} does not conform to expected schema`,{cause:o})}return n}async function gi(r,e){let t=Lf(r),n=e==="setup"?t.setup:t.teardown;if(!n){L.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,m=async p=>{try{await Pl(`set -ex; ${d}`)}catch(h){if(p){let g=`Fixture '${r}' ${e} step ${c+1} errored in the background. The test will continue, but this may affect test execution and results: ${h}`;L.error(g)}else throw new Error(`Fixture '${r}' ${e} step ${c+1} errored: ${h}`)}};u.waitForCompletion===!1?m(!0):await m(!1)}};if(L.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 Ud({path:r,apiClient:e,generator:t,orgId:n,retriesOverride:o,useLocalFiles:s,noReport:i,envName:a,urlOverride:l,devicePixelRatio:c,customHeaders:u,testInputs:d}){let m=new Er(e,n),p;if(s?(L.info(`Reading ${r} from local filesystem`),p=await ro(r,Zt,L),await m.resolveStepCacheEntries({schemaVersion:p.schemaVersion,organizationId:n,steps:p.steps,testId:p.id,logger:L})):(L.info(`Fetching ${r} from Momentic Cloud server (${e.baseUrl})`),p=await e.getTest(r)),_f.gt(p.schemaVersion,Pe)&&L.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
|
|
1798
|
-
`),await T({status:"FAILED",failureReason:W?.failureReason,finishedAt:new Date});let H,J;b.info(`Classifying failure for test ${p.name}`);try{let Z=await t.getTestResultClassification({results:v.results,errorMessage:
|
|
1799
|
-
${e.map(
|
|
1800
|
-
`)}`),e.forEach(
|
|
1801
|
-
${E.map(
|
|
1802
|
-
`)}`);let I=[],
|
|
1797
|
+
`))}catch(o){throw new Error(`Fixture at path ${e} does not parse as valid YAML.`,{cause:o})}let n;try{n=aa.parse(t)}catch(o){throw new Error(`Fixture at path ${e} does not conform to expected schema`,{cause:o})}return n}async function gi(r,e){let t=Lf(r),n=e==="setup"?t.setup:t.teardown;if(!n){L.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,m=async p=>{try{await Pl(`set -ex; ${d}`)}catch(h){if(p){let g=`Fixture '${r}' ${e} step ${c+1} errored in the background. The test will continue, but this may affect test execution and results: ${h}`;L.error(g)}else throw new Error(`Fixture '${r}' ${e} step ${c+1} errored: ${h}`)}};u.waitForCompletion===!1?m(!0):await m(!1)}};if(L.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 Ud({path:r,apiClient:e,generator:t,orgId:n,retriesOverride:o,useLocalFiles:s,noReport:i,envName:a,urlOverride:l,devicePixelRatio:c,customHeaders:u,testInputs:d}){let m=new Er(e,n),p;if(s?(L.info(`Reading ${r} from local filesystem`),p=await ro(r,Zt,L),await m.resolveStepCacheEntries({schemaVersion:p.schemaVersion,organizationId:n,steps:p.steps,testId:p.id,logger:L})):(L.info(`Fetching ${r} from Momentic Cloud server (${e.baseUrl})`),p=await e.getTest(r)),_f.gt(p.schemaVersion,Pe)&&L.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 x of p.envs??[])if(x.default){a=x.name;break}}let h,g=[],f={};a&&(h=await $f(e,a,L.child({testId:p.id})),f=h.variables,g=p.envs?.find(P=>P.name===a)?.fixtures??[]);let S=p.baseUrl;if(l?S=l:S||(S=f[ct]),!S){let x=`Cannot run test with no base URL and no ${ct} variable defined in its environment`;throw new Error(x)}let w;if(i)w=kf();else try{w=(await e.createRun({testId:p.id,testName:p.name,trigger:"CLI",resolvedBaseUrl:S})).id}catch(x){throw L.error({err:x,testId:p.id},"Error creating run on Momentic Cloud"),new Error("Error creating run on Momentic Cloud. Please ensure Momentic is accessible from your environment or pass the --no-report flag.")}let b=L.child({testId:p.id,runId:w}),T=async x=>{if(!i)try{await e.updateRun(w,x)}catch(P){b.warn({err:P},`Failed to update run status for test ${w}. You may see stale data on the Momentic Cloud Server.`)}},v,E=Math.max(o??p.retries,0),I=[];for(let x=0;x<=E;x++)try{await T({status:"RUNNING",attempts:x+1});let{controller:P,context:D}=await Uf({baseUrl:S,envName:a,apiClient:e,devicePixelRatio:c,logger:b,storageClient:m,test:p,localFixtures:g,generator:t,orgId:n,variables:f,customHeaders:u});if(v=await zf({testInputs:d,logger:b,storageClient:m,apiClient:e,test:p,orgId:n,runId:w,context:D,controller:P,noReport:i}),I.unshift(v.status),v.status!=="FAILED")return await T({status:v.status,finishedAt:new Date,flake:$i(I)}),{...v,runId:w};let W=v.failedStepResult,A=W?.message||"Unknown failure";if(x<E){b.warn({errResult:W},`Test '${p.name}' failed attempt ${x+1} of ${E+1}, retrying...`);continue}b.error({errResult:W},`Test '${p.name}' failed after all exhausting ${E+1} attempts: ${A}
|
|
1798
|
+
`),await T({status:"FAILED",failureReason:W?.failureReason,finishedAt:new Date});let H,J;b.info(`Classifying failure for test ${p.name}`);try{let Z=await t.getTestResultClassification({results:v.results,errorMessage:A});H={classification:Z,errorMessage:A},J=Z.reason,await T({status:"FAILED",finishedAt:new Date,failureDetails:H,failureReason:J})}catch(Z){b.debug({err:Z},"Failed to classify test failure with AI, continuing...")}return{...v,runId:w,failureDetails:H,failureReason:J}}catch(P){b.error({err:P},`Encountered fatal platform error while running test '${p.name}': ${P}`);let D={errorMessage:P.message,errStack:P.stack},W={status:"FAILED",failureDetails:D,failureReason:"InternalPlatformError",finishedAt:new Date};return await T(W),{...W,runId:w}}finally{try{await Promise.all(g.map(P=>gi(P,"teardown")))}catch(P){b.error(`Failed to run teardown fixtures, continuing...: ${P}`)}}throw new Error("This code should not be reachable")}async function Uf({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 gi(f,"setup");let m=qr.parse(o.advanced);d&&(m.extraHeaders={...m.extraHeaders??{},...d});let p=await ot.init({baseUrl:r,logger:u,userBrowserSettings:m,storage:i,enricher:new Fo({baseURL:n.baseUrl,apiKey:n.apiKey}),timeout:m.pageLoadTimeoutMs,contextArgs:{viewport:o.advanced.viewport??lt,deviceScaleFactor:t}}),h=new Pr({browser:p,generator:a,config:Sn,logger:u,orgId:l,storage:i,flagStore:await Rr.init(l),localCodeEvalTools:new pt({baseUrl:n.baseUrl,apiKey:n.apiKey})}),g=new se({baseUrl:r,currentUrl:h.browser.url(),variablesFromEnvironment:c,envName:e});return{controller:h,context:g}}async function zf({storageClient:r,apiClient:e,test:t,orgId:n,runId:o,context:s,controller:i,noReport:a,logger:l,testInputs:c}){L.info(`Running test '${t.name}' locally${a?"":` and reporting results to https://app.momentic.ai/runs/${o}`}`);let u=Fd(t.steps),d=async T=>{try{if(T.results){let v=Fd(T.results);Yn(v),T.results=v}await e.updateRun(o,T)}catch(v){l.warn({err:v},"Failed to update run data. You may see stale data on the Momentic Cloud Server.")}},m,p=Df(async T=>{if(!a){try{JSON.stringify(T)}catch(v){throw new Error(`The test results contain circular references: ${v}`)}await d(T)}},1e4,{maxWait:3e4}),h=new pt({baseUrl:e.baseUrl,apiKey:e.apiKey});t.parameters&&await Promise.all(t.parameters.map(async T=>{let{name:v,defaultValue:E,required:I}=T,x=c?.[v];I&&x===void 0&&(M(`Required parameter '${v}' is required by test '${t.name}' but not provided`),process.exit(1));let P=await We({s:x??E,localTools:h,logger:l,context:se.dummyContext(s.getEnvName())});s.setMomenticSystemVariable(v,P)}));let g={controller:i,storage:r,context:s,logger:l,codeEvalTools:h},f={orgId:n,runId:o,testMetadata:t,steps:t.steps},b=await ln({fixtures:g,inputs:f,options:{takeScreenshots:!0,consumeDebuggingData:!0},callbacks:{step:{},test:{onTestComplete:async()=>{await i.browser.cleanup()},onSaveScreenshot:async T=>{if(a)return"";let{key:v}=await e.uploadScreenshot({screenshot:T.toString("base64")});return v},onUpdateRun:async T=>{m=Promise.resolve(p(T))},onProposedTestSteps:async T=>e.uploadProposedSteps(T,l),onTestSuccess:async T=>{let v=Of(u,T);if(Object.keys(v).length===0){l.debug("No changes to test steps after success");return}l.debug({changes:v},"Updating steps post-run success in worker");try{let{cachesToSave:E}=await et({steps:T,cacheCreationParams:{testId:t.id,orgId:n}});await e.updateStepCaches({testId:t.id,entries:E})}catch(E){l.error({err:E},"Failed to save step caches after successful execution. This is not critical, but can impact future performance.")}}}}});return m&&(l.info("Waiting for last run update to finish"),await Promise.resolve(m)),b}async function $f(r,e,t){t.info(`Attempting to resolve environment '${e}' from local disk`);let n=Nf(wt,`${e}.yaml`);try{let s=Ff(Mf(n,"utf-8"));try{return De.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 Bd(r){let{tests:e,start:t,waitOn:n,client:o,all:s,report:i,retriesOverride:a,urlOverride:l,envName:c,orgId:u,devicePixelRatio:d,customHeaders:m,testInputMatrix:p,waitOnTimeout:h=60,parallel:g=1,shardIndex:f=1,shardCount:S=1}=r;t&&(L.info(`Executing start command: ${t}`),await kd(t,!1)),n&&(L.info(`Waiting for url: ${n} with timeout: ${h} seconds.`),await Wf({resources:[n],timeout:h*1e3,headers:{Accept:"*/*"},followRedirect:!0,verbose:!0,log:!0,strictSSL:!1}));let w=new Jt({baseURL:o.baseUrl,apiKey:o.apiKey}),b=!1;(e.some(A=>A.endsWith(".yaml"))||e.some(A=>zd(A)))&&(b=!0);let T=new Set;if(b)L.info({tests:e},`Reading tests from the following local file paths:
|
|
1799
|
+
${e.map(A=>` - ${A}`).join(`
|
|
1800
|
+
`)}`),e.forEach(A=>{if(!zd(A))throw new Error(`Path '${A}' does not exist.`);let H,J;try{H=Bf(A),J=H.isDirectory()}catch(Z){L.error({err:Z},`Skipping path ${A} because it cannot be read`);return}if(J)sn(A,L).map(Z=>Z.fullPathSegments.join(Hf.sep)).forEach(Z=>T.add(Z));else if(A.endsWith(".yaml"))T.add(A);else throw new Error(`Path '${A}' 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 A of await o.getAllTestIds())T.add(A);else T=new Set(e);let v=Array.from(T),E=[];if(v.forEach((A,H)=>{p?p.forEach((J,Z)=>{E.push({path:A,testIndex:H,inputs:J,inputIndex:Z})}):E.push({path:A,testIndex:H,inputs:void 0,inputIndex:void 0})}),S&&S>1){E=Gf(E,f,S);let A=E[0],H=E[E.length-1];if(Re(`Assigned shard ${f} of ${S} of all available tests:`),A){let J=`(test ${A.testIndex+1}/${v.length})`,Z=A.inputIndex===void 0?"":` (input set ${A.inputIndex+1}/${p.length})`;Re(` - First test assigned to this worker ${J}${Z}: ${A.path}`)}if(H){let J=`(test ${H.testIndex+1}/${v.length})`,Z=H.inputIndex===void 0?"":` (input set ${H.inputIndex+1}/${p.length})`;Re(` - Last test assigned to this worker ${J}${Z}: ${H.path}`)}Re()}L.info({allTestsToRunWithInputs:E,shardCount:S,shardIndex:f},`Running ${E.length} tests with ${g} workers`),Re(`Running ${E.length} tests with ${g} workers:
|
|
1801
|
+
${E.map(A=>` - ${A.path}${A.inputIndex?` with input set ${A.inputIndex}`:""}`).join(`
|
|
1802
|
+
`)}`);let I=[],x=Date.now(),P=new Set;for(let A=0;A<E.length;A+=g){let H=await Promise.all(E.slice(A,A+g).map(async({path:J,inputs:Z})=>{try{P.add(J),$d(`${P.size}/${E.length} ${J}`);let At=await Ud({path:J,testInputs:Z,orgId:u,useLocalFiles:b,devicePixelRatio:d,apiClient:o,generator:w,retriesOverride:a,urlOverride:l,envName:c,noReport:!i,customHeaders:m});return{identifier:J,...At}}catch(At){let er=`A fatal error occurred while setting up the test '${J}': ${At.message}`;return L.error({err:At},"A fatal error occurred while setting up the test"),M(er),{identifier:J,status:"FAILED",failureDetails:{errorMessage:er,errorStack:At.stack}}}}));I.push(...H)}$d.clear();let D=o.getAppUrl(),W=Or({results:I,startTime:x,onFailed:A=>{ko(A,A.identifier)},getDisplayLine:A=>{let H=` ${A.identifier}`;return i&&A.runId&&(H+=` (${D}/runs/${A.runId})`),H},entity:"test"});return W.failed>0&&process.exit(1),W}function Gf(r,e,t){if(t>r.length&&(le(`Shard count ${t} is greater than the number of tests ${r.length}! Some workers won't have any tests to run.`),t=Math.max(t,r.length),e>t))return[];let n=Math.floor((e-1)*(r.length/t)),o=Math.floor(e*(r.length/t));return r.toSorted().filter((s,i)=>i>=n&&i<o)}import Hd from"log-update";async function Wd({tests:r,client:e,...t}){let{queuedTests:n,runIds:o}=await e.queueTests({testPaths:r,...t});if(Re(`Queued ${n.length} tests.`),t.wait||process.exit(0),!o.length)return;Re(`Waiting for ${n.length} tests to complete.`);let s=new Set,i=e.getAppUrl(),a=Date.now(),l=await Do({name:"runs",getResults:async()=>e.bulkGetRunStatus(o),timeoutMs:t.waitTimeout?t.waitTimeout*1e3:void 0,checkDone:u=>(u.forEach(d=>{if(d.status==="RUNNING"&&!s.has(d.id)){s.add(d.id);let m=d.testName||d.test?.name;m&&Hd(`${s.size}/${n.length} ${Te(m)}`)}}),u.every(d=>d.status==="FAILED"&&d.failureReason||d.status==="PASSED"||d.status==="CANCELLED"))});Hd.clear();let c=Or({results:l,startTime:a,onFailed:u=>{let d=u.testName||u.test?.name;ko(u,d?Te(d):"Unknown test")},getDisplayLine:u=>{let d=u.testName||u.test?.name,m=` ${d?Te(d):"Unknown test"}`;return u.id&&(m+=` (${i}/runs/${u.id})`),m},entity:"test"});process.exit(c.failed>0?1:0)}import jf from"csv-parser";import{createReadStream as Vf}from"fs";function Gd(r){return new Promise((e,t)=>{let n=[];Vf(r).pipe(jf()).on("data",o=>n.push(o)).on("end",()=>e(n)).on("error",o=>t(o))})}var Ge=new Kf;Ge.name("momentic").description("Momentic CLI");Ge.command("install-browsers").action(async()=>{await Oo()});Ge.addOption(new xt("--log-level <level>").choices(["debug","info","warn","error"]).default("info")).on("option:log-level",r=>{L.setMinLevel(r.toLowerCase())});Ge.addOption(new xt("--verbose","enable verbose logging")).on("option:verbose",()=>{L.enableConsoleLogs()});Ge.command("init").addOption(Et).addOption(Tt).addOption(Ct).action(async r=>{let e=await vt(r),{yes:t,apiKey:n,server:o}=e,s=new he({baseUrl:o,apiKey:n,logger:L});await bt({client:s,skipPrompts:t,pullEnvs:!0,createFolders:!0,installBrowsers:!0})});Ge.command("app").addOption(Tt).addOption(Ct).addOption(Et).addOption(ai).addOption(Sd).action(async r=>{let e=await vt(r),{apiKey:t,port:n=No,yes:o,server:s,pixelRatio:i}=e,a=new he({baseUrl:s,apiKey:t,logger:L});await bt({client:a,skipPrompts:o,pullEnvs:!1,createFolders:!1,installBrowsers:!0}),Qf(Jf(yt,".."));let l=Zf(import.meta.url),c=Xf(l),u=jd.resolve(c,"..","static"),d=jd.resolve(c,"..","assets"),m=i??Ks();qs(m),await od({momenticServerUrl:s,apiKey:t,serverPort:n,appPort:n,staticDir:u,assetsDir:d,devicePixelRatio:m})});var eS=Ge.command("suite").description("Manage and run suites");eS.command("run").description("Run one or more suites on Momentic Cloud").addOption(Tt).addOption(Ct).addOption(ri).addOption(ni).addOption(Et).addArgument(Td).addOption(ci).addOption(li).addOption(oi).action(async(r,e)=>{let{apiKey:t,server:n,wait:o,waitTimeout:s,yes:i,env:a,urlOverride:l,customHeaders:c}=await vt(e),u=new he({baseUrl:n,apiKey:t,logger:L});await bt({client:u,skipPrompts:i,pullEnvs:!1,createFolders:!1,installBrowsers:!1}),(!r||!Array.isArray(r)||!r.length)&&(M("Must pass at least one suite to run."),process.exit(1)),await Dd({client:u,wait:o,suitePaths:r,waitTimeout:s,env:a,urlOverride:l,customHeaders:si(c)})});var tS=Ge.command("run").alias("run-tests").description("Run tests, folders, or suites on the local machine or Momentic Cloud");tS.addOption(Tt).addOption(Ct).addOption(di).addOption(Et).addOption(oi).addOption(yd).addOption(li).addOption(ci).addOption(new xt("-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","shard-count","shard-index"])).addOption(ri).addOption(ni).addOption(ii).addOption(ai).addOption(new xt("-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 xt("--start <start>","Arbitrary setup command that will run before Momentic steps begin.")).addOption(new xt("--wait-on <waitOn>","URL to wait to become accessible before Momentic tests begin.")).addOption(new xt("--wait-on-timeout <waitOnTimeout>","Max time in seconds to wait for the --wait-on URL to become accessible.")).addOption(new xt("--retries <retries>","Number of retries to attempt when running tests locally. Defaults to each test's own retry configuration.")).addOption(new xt("-p, --parallel <parallel>","When running with the --local flag, the number of tests to run in parallel. Defaults to 1.")).addOption(ii).addOption(Ed).addOption(vd).addArgument(bd).action(async(r,e)=>{let t=await vt(e),{all:n,apiKey:o,customHeaders:s,env:i,local:a,parallel:l,pixelRatio:c,remote:u,report:d,retries:m,server:p,start:h,inputCsv:g,urlOverride:f,wait:S,waitOn:w,waitOnTimeout:b,waitTimeout:T,yes:v,shardIndex:E,shardCount:I}=t,x=si(s);!n&&(!r||!r.length)&&(M("You must pass at least one test path or use the --all flag."),process.exit(1));let P=new he({baseUrl:p,apiKey:o,logger:L}),D;if(g&&(D=await Gd(g)),a){let W=await bt({client:P,skipPrompts:v,pullEnvs:!1,createFolders:!1,installBrowsers:!0}),A=c??Ks();qs(A);try{let H=await Bd({tests:r,client:P,customHeaders:x,all:n,start:h,waitOn:w,waitOnTimeout:b,retriesOverride:m,parallel:l,report:d,devicePixelRatio:A,envName:i,orgId:W,urlOverride:f,shardIndex:E,shardCount:I,testInputMatrix:D})}catch(H){M("Failed to run tests locally. Please check the error message below or run with the --verbose flag."),M(H),process.exit(1)}process.exit(0)}if(u){for(let W of r)(W.endsWith(".yaml")||Yf(W))&&(M(`Looks like you tried to run a local test remotely: ${W}`),M("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 Wd({client:P,tests:r,all:n,customHeaders:x,env:i,urlOverride:f,wait:S,waitTimeout:T,testInputMatrix:D}),process.exit(0)}M("One of --remote or --local options must be specified."),process.exit(1)});Ge.command("pull").description("Fetch one or more tests from Momentic Cloud and save it in to local disk in YAML format.").addOption(Tt).addOption(Ct).addOption(di).addOption(Et).addArgument(wd).action(async(r,e)=>{let t=await vt(e),{apiKey:n,server:o,all:s,yes:i}=t,a=new he({baseUrl:o,apiKey:n,logger:L});await bt({client:a,skipPrompts:i,pullEnvs:!1,createFolders:!1,installBrowsers:!1}),!s&&!r?.length&&(M("At least one test name or the --all flag must be provided."),process.exit(1)),await Pd({testsToFetch:r??[],client:a,all:s,yes:i}),process.exit(0)});Ge.command("push").description("Save one or more tests in YAML format to Momentic Cloud.").addOption(Et).addOption(Tt).addOption(Ct).addArgument(Cd).action(async(r,e)=>{let t=await vt(e),{apiKey:n,server:o,yes:s}=t,i=new he({baseUrl:o,apiKey:n,logger:L});await bt({client:i,skipPrompts:s,pullEnvs:!1,createFolders:!1,installBrowsers:!1}),await Ld({paths:r,client:i,yes:s}),process.exit(0)});var Vd=Ge.command("env").description("Perform operations on Momentic environments");Vd.command("push").description("Push one or more environments and associated variables to Momentic cloud.").addOption(Et).addOption(Tt).addOption(Ct).addOption(ui).addArgument(mi).action(async(r,e)=>{let t=await vt(e),{apiKey:n,server:o,yes:s,all:i}=t;!r?.length&&!i&&(M("At least one environment name or the --all flag must be provided."),process.exit(1));let a=new he({baseUrl:o,apiKey:n,logger:L});await bt({client:a,skipPrompts:s,pullEnvs:!1,createFolders:!1,installBrowsers:!1}),await hd({names:r,client:a,yes:s,all:i})});Vd.command("pull").description("Pull one or more environments and associated variables from Momentic cloud.").addOption(Et).addOption(Tt).addOption(Ct).addOption(ui).addArgument(mi).action(async(r,e)=>{let t=await vt(e),{apiKey:n,server:o,yes:s,all:i}=t;!r?.length&&!i&&(M("At least one environment name or the --all flag must be provided."),process.exit(1));let a=new he({baseUrl:o,apiKey:n,logger:L});await bt({client:a,skipPrompts:s,pullEnvs:!1,createFolders:!1,installBrowsers:!1}),await Mo({envNames:r,client:a,skipPrompts:s,all:i})});async function rS(){try{await Ge.parseAsync(process.argv)}catch(r){let e={};try{e.playwrightVersion=qf("npx playwright --version").toString()}catch(t){L.error({err:t},"Error fetching debug information")}L.error({err:r,debugInfo:e},"Uncaught error in CLI"),L.flush(),M("Failed to start Momentic CLI."),M(r),process.exit(1)}}rS();
|