@checksum-ai/runtime 1.1.66 → 1.1.67-alpha

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/index.js CHANGED
@@ -1834,7 +1834,7 @@ Please see the 3.x to 4.x migration guide for details on how to update your app.
1834
1834
  </body>
1835
1835
  </html>
1836
1836
  `}e(GAn,"createHtmlDocument");function KAn(){return e(function(){this.error(404)},"notFound")}e(KAn,"createNotFoundDirectoryListener");function YAn(){return e(function(l){if(this.hasTrailingSlash()){this.error(404);return}var _=unr.original(this.req);_.path=null,_.pathname=HAn(_.pathname+"/");var g=UAn(WAn.format(_)),C=GAn("Redirecting","Redirecting to "+VAn(g));l.statusCode=301,l.setHeader("Content-Type","text/html; charset=UTF-8"),l.setHeader("Content-Length",Buffer.byteLength(C)),l.setHeader("Content-Security-Policy","default-src 'none'"),l.setHeader("X-Content-Type-Options","nosniff"),l.setHeader("Location",g),l.end(C)},"redirect")}e(YAn,"createRedirectDirectoryListener")});var cAr=es((dce,oAr)=>{"use strict";var bRt=lrr(),XAn=require("events").EventEmitter,nAr=VEr(),iAr=f5r(),QAn=Srr(),ZAn=Drr(),aAr=B5r(),sAr=eAr();dce=oAr.exports=e9n;function e9n(){var p=e(function(l,_,g){p.handle(l,_,g)},"app");return nAr(p,XAn.prototype,!1),nAr(p,iAr,!1),p.request=Object.create(aAr,{app:{configurable:!0,enumerable:!0,writable:!0,value:p}}),p.response=Object.create(sAr,{app:{configurable:!0,enumerable:!0,writable:!0,value:p}}),p.init(),p}e(e9n,"createApplication");dce.application=iAr;dce.request=aAr;dce.response=sAr;dce.Route=QAn;dce.Router=ZAn;dce.json=bRt.json;dce.query=Frr();dce.raw=bRt.raw;dce.static=rAr();dce.text=bRt.text;dce.urlencoded=bRt.urlencoded;var t9n=["bodyParser","compress","cookieSession","session","logger","cookieParser","favicon","responseTime","errorHandler","timeout","methodOverride","vhost","csrf","directory","limit","multipart","staticCache"];t9n.forEach(function(p){Object.defineProperty(dce,p,{get:e(function(){throw new Error("Most middleware (like "+p+") is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.")},"get"),configurable:!0})})});var lAr=es((Iii,uAr)=>{"use strict";uAr.exports=cAr()});var _Ar=es((Oii,fAr)=>{"use strict";var pAr=Object.getOwnPropertySymbols,r9n=Object.prototype.hasOwnProperty,n9n=Object.prototype.propertyIsEnumerable;function i9n(p){if(p==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(p)}e(i9n,"toObject");function a9n(){try{if(!Object.assign)return!1;var p=new String("abc");if(p[5]="de",Object.getOwnPropertyNames(p)[0]==="5")return!1;for(var l={},_=0;_<10;_++)l["_"+String.fromCharCode(_)]=_;var g=Object.getOwnPropertyNames(l).map(function(P){return l[P]});if(g.join("")!=="0123456789")return!1;var C={};return"abcdefghijklmnopqrst".split("").forEach(function(P){C[P]=P}),Object.keys(Object.assign({},C)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}e(a9n,"shouldUseNative");fAr.exports=a9n()?Object.assign:function(p,l){for(var _,g=i9n(p),C,P=1;P<arguments.length;P++){_=Object(arguments[P]);for(var F in _)r9n.call(_,F)&&(g[F]=_[F]);if(pAr){C=pAr(_);for(var M=0;M<C.length;M++)n9n.call(_,C[M])&&(g[C[M]]=_[C[M]])}}return g}});var mAr=es((Mii,dAr)=>{(function(){"use strict";var p=_Ar(),l=onr(),_={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function g(ne){return typeof ne=="string"||ne instanceof String}e(g,"isString");function C(ne,ue){if(Array.isArray(ue)){for(var qe=0;qe<ue.length;++qe)if(C(ne,ue[qe]))return!0;return!1}else return g(ue)?ne===ue:ue instanceof RegExp?ue.test(ne):!!ue}e(C,"isOriginAllowed");function P(ne,ue){var qe=ue.headers.origin,Xe=[],rt;return!ne.origin||ne.origin==="*"?Xe.push([{key:"Access-Control-Allow-Origin",value:"*"}]):g(ne.origin)?(Xe.push([{key:"Access-Control-Allow-Origin",value:ne.origin}]),Xe.push([{key:"Vary",value:"Origin"}])):(rt=C(qe,ne.origin),Xe.push([{key:"Access-Control-Allow-Origin",value:rt?qe:!1}]),Xe.push([{key:"Vary",value:"Origin"}])),Xe}e(P,"configureOrigin");function F(ne){var ue=ne.methods;return ue.join&&(ue=ne.methods.join(",")),{key:"Access-Control-Allow-Methods",value:ue}}e(F,"configureMethods");function M(ne){return ne.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}e(M,"configureCredentials");function V(ne,ue){var qe=ne.allowedHeaders||ne.headers,Xe=[];return qe?qe.join&&(qe=qe.join(",")):(qe=ue.headers["access-control-request-headers"],Xe.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),qe&&qe.length&&Xe.push([{key:"Access-Control-Allow-Headers",value:qe}]),Xe}e(V,"configureAllowedHeaders");function W(ne){var ue=ne.exposedHeaders;if(ue)ue.join&&(ue=ue.join(","));else return null;return ue&&ue.length?{key:"Access-Control-Expose-Headers",value:ue}:null}e(W,"configureExposedHeaders");function Q(ne){var ue=(typeof ne.maxAge=="number"||ne.maxAge)&&ne.maxAge.toString();return ue&&ue.length?{key:"Access-Control-Max-Age",value:ue}:null}e(Q,"configureMaxAge");function ae(ne,ue){for(var qe=0,Xe=ne.length;qe<Xe;qe++){var rt=ne[qe];rt&&(Array.isArray(rt)?ae(rt,ue):rt.key==="Vary"&&rt.value?l(ue,rt.value):rt.value&&ue.setHeader(rt.key,rt.value))}}e(ae,"applyHeaders");function G(ne,ue,qe,Xe){var rt=[],Tt=ue.method&&ue.method.toUpperCase&&ue.method.toUpperCase();Tt==="OPTIONS"?(rt.push(P(ne,ue)),rt.push(M(ne,ue)),rt.push(F(ne,ue)),rt.push(V(ne,ue)),rt.push(Q(ne,ue)),rt.push(W(ne,ue)),ae(rt,qe),ne.preflightContinue?Xe():(qe.statusCode=ne.optionsSuccessStatus,qe.setHeader("Content-Length","0"),qe.end())):(rt.push(P(ne,ue)),rt.push(M(ne,ue)),rt.push(W(ne,ue)),ae(rt,qe),Xe())}e(G,"cors");function _e(ne){var ue=null;return typeof ne=="function"?ue=ne:ue=e(function(qe,Xe){Xe(null,ne)},"optionsCallback"),e(function(Xe,rt,Tt){ue(Xe,function(Nt,er){if(Nt)Tt(Nt);else{var jt=p({},_,er),Lt=null;jt.origin&&typeof jt.origin=="function"?Lt=jt.origin:jt.origin&&(Lt=e(function(zt,Yt){Yt(null,jt.origin)},"originCallback")),Lt?Lt(Xe.headers.origin,function(zt,Yt){zt||!Yt?Tt(zt):(jt.origin=Yt,G(jt,Xe,rt,Tt))}):Tt()}})},"corsMiddleware")}e(_e,"middlewareWrapper"),dAr.exports=_e})()});var N9n={};SVt(N9n,{RunMode:()=>Yet,getChecksumConfig:()=>NVt,getLogin:()=>U9e,init:()=>A9n});module.exports=Uae(N9n);var rPe=x7(require("path"));var k_r="checksum",Yet=(g=>(g.Normal="normal",g.Heal="heal",g.Refactor="refactor",g))(Yet||{});var Xet=(W=>(W.Locator="locator",W.GetByRole="getByRole",W.GetByText="getByText",W.GetByLabel="getByLabel",W.GetByPlaceholder="getByPlaceholder",W.GetByAltText="getByAltText",W.GetByTitle="getByTitle",W.GetByTestId="getByTestId",W.FrameLocator="frameLocator",W))(Xet||{}),Qet=(F=>(F.First="first",F.Last="last",F.Nth="nth",F.Filter="filter",F.Or="or",F.And="and",F))(Qet||{});var eI=x7(require("path")),J9e=require("fs");var TVt=(g=>(g.Alert="alert",g.Confirm="confirm",g.Prompt="prompt",g))(TVt||{});var WC=e(p=>new Promise(l=>setTimeout(l,p)),"awaitSleep"),qL=e(async(p,l=1e3,_)=>{if(l===null)return p;let g="guard-timed-out",C=e(async()=>(await WC(l+1e3),g),"guard"),P=await Promise.race([p,C()]);if(typeof P=="string"&&P===g)throw typeof _=="function"?new Error(_()):new Error(_??"guardReturnTimedOut");return P},"guardReturn");function j9e(p=5,l="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"){let _="";for(let g=p;g>0;--g)_+=l[Math.floor(Math.random()*l.length)];return _}e(j9e,"randomString");function DVt(p){return!!p&&!["navigation","keystroke","wait","get_more_items","custom_code","native_accept","native_dismiss","login"].includes(p)}e(DVt,"isActionOnElement");function w_r(p){return{click:"click",fill:"input",click_and_type:"click_and_type",clear_and_type:"clear_and_type",double_click:"double_click",drag_and_drop:"drag_and_drop",upload_files:"upload_files",hover:"hover",navigate:"navigation",keystroke:"keystroke",selectoption:"selectoption",reset:void 0,save:void 0,fail:void 0,wait:void 0,finish:void 0,dismiss_modal:void 0,vision_help:void 0,get_more_items:void 0,switch_tab:"switch_tab",expand_interactable_elements:void 0,approve_release:void 0}[p]}e(w_r,"getActionEventCode");var B0e=e((p,l="page")=>l+"."+jPt(p,l),"injectBaseToLocatorString"),jPt=e((p,l="page")=>p.replace(".and(locator(",`.and(${l}.locator(`).replace(".or(locator(",`.or(${l}.locator(`),"injectBaseToLogicalLocatorString");async function qPt(p,l){let g=e(()=>{let V=CVt(p,l);if((0,J9e.existsSync)(V)||V.endsWith(".data")&&(V=V.replace(".data",".esra"),(0,J9e.existsSync)(V)))return V;throw new Error(`Could not find metadata file for test ${l}`)},"getFilePath")(),{ungzip:C}=JPt(),P=await C((0,J9e.readFileSync)(g)),F=JSON.parse(P),M=Object.keys(F);return M.length>0&&!F[M[0]].esraMetadata?M.reduce((V,W)=>({...V,[W]:{esraMetadata:F[W]}}),{}):F}e(qPt,"getMetadataForTestId");function Zet(p){return eI.join(eI.dirname(p),"..")}e(Zet,"getTestBaseDir");function CVt(p,l){return eI.join(stn(p),`${l}.checksum.data`)}e(CVt,"getMetadataFilePath");function stn(p){return eI.join(ett(p),"esra")}e(stn,"getMetadataFolderPath");function EVt(p){return eI.join(ett(p),"bin")}e(EVt,"getBinFolderPath");function kVt(p){return eI.join(ett(p),"har")}e(kVt,"getHARFolderPath");function F_r(p,l){return eI.join(kVt(p),`${l}.har.zip`)}e(F_r,"getHARFilePath");function I_r(p,l){return eI.join(ett(p),"trace",`${l}.playwright-trace.zip`)}e(I_r,"getTraceFilePath");function ett(p){return eI.join(p,"test-data")}e(ett,"getTestDataPath");var N_r=e(async p=>{try{await qL(p,5e3)}catch{}},"guardAwait"),wVt=e(p=>{let l=/\/\/.*/,_=/\/\*[\s\S]*?\*\//g;return p.replace(l,"").replace(_,"")},"stripJavascriptComments"),AVt=e(p=>{console.log("\x1B[31m%s\x1B[0m",p)},"printError"),PVt=e((p,l,_)=>{if(!l)return p;if(!_||!_.length)return p.locator(l);let g=p.frameLocator(_[0]);for(let C of _.slice(1))g=g.frameLocator(C);return g.locator(l)},"makeLocator");async function O_r(p,l,_){let C=e(async()=>p.evaluate(async({selector:F,parentFramesSelectors:M})=>await window.checksum.testGenerator.getSelectionDataForSelector(F,M),{selector:l,parentFramesSelectors:_}),"getSelectionDataForSelector"),P=await C();if(P||(await N_r(p.waitForLoadState("networkidle")),P=await C(),P)||(await N_r(PVt(p,l,_).waitFor({state:"visible"})),P=await C(),P)||(await WC(5e3),P=await C(),P))return P}e(O_r,"selectionDataForSelector");function q9e(){return process.env.CHECKSUM_ROOT_FOLDER?process.env.CHECKSUM_ROOT_FOLDER:eI.join(__dirname,"..","..","..","checksum")}e(q9e,"checksumFolder");function UPt(p,l){try{let _=p.filter(g=>g.endsWith("checksum.config.ts")&&eI.dirname(g).endsWith("checksum"));return _.find(g=>g==="checksum/checksum.config.ts")?"checksum":_.length===1?eI.dirname(_[0]):l?eI.dirname(otn(_,l)):eI.dirname(_.sort((g,C)=>C.length-g.length)[0])}catch{return"checksum"}}e(UPt,"findChecksumRootFolder");function otn(p,l){let _=e(M=>M.split(eI.sep).filter(V=>V.length>0),"splitPath"),g=e((M,V)=>{let W=_(M),Q=_(V),ae=Math.min(W.length,Q.length),G=Math.abs(W.length-Q.length);for(let _e=0;_e<ae;_e++)if(W[_e]!==Q[_e]){G+=2*(ae-_e);break}return G},"directoryDistance"),C=null,P=1/0,F=eI.dirname(l);return p.forEach(M=>{let V=g(F,M);V<P&&(P=V,C=M)}),C}e(otn,"getClosestPath");function VPt(p,l=2){let _=[],g=[],C=e(F=>{if(_.includes(F))return;_.push(F);let M=(0,J9e.readdirSync)(F);for(let V of M){let W=eI.join(F,V),Q=(0,J9e.statSync)(W);if(!(Q.isSymbolicLink()||W.includes("node_modules"))){if(Q.isDirectory())C(W);else if(V==="checksum.config.ts"){g.push(W);return}}}},"searchDirectory"),P=eI.dirname(p);try{for(let F=0;F<l&&(C(P),P=eI.join(P,".."),F===l-1&&F<9&&!g.length&&(l+=2),!(eI.resolve(P)==="/"||!P||eI.resolve(P)===eI.resolve(process.cwd())));F++);return g}catch{return g}}e(VPt,"findChecksumRootQualifyingPathsForTestFile");var zPt=require("fs");var L_r=!1;function WPt(p){L_r=p}e(WPt,"setLogToConsole");function gT(...p){L_r&&console.log(...p)}e(gT,"log");async function M_r(p,l,_,g=6e4){if(!(l in p))return p;let C=e(()=>p[l](..._),"executor");return g===null?C():qL(C(),g,"Execution timeout")}e(M_r,"executePlaywrightMethodWithTimeout");function RCt(p,{role:l,environment:_}={},g=!1){var M,V;let C;if(_&&(C=(M=p.environments)==null?void 0:M.find(({name:W})=>_===W)),C||(C=(V=p.environments)==null?void 0:V.find(({default:W})=>W)),!C)throw new Error("Environment not found. Please make sure your environments are properly defined in the checksum.config.ts file.");let P=C.users,F;if(P&&(l!==void 0&&(F=P.find(W=>W.role===l)),F||(F=P.find(W=>W.default))),!F)throw new Error(`User not found. Please make sure the users array for the "${C.name}" environment is properly defined in the checksum.config.ts file.`);if(_&&C.name!==_){if(g)throw new Error(`Could not find environment with name "${_}" in config file`);console.warn(`Could not find environment with name "${_}" in config file, trying to use default environment`)}if(l&&F.role!==l){if(g)throw new Error(`Could not find user with role "${l}" for environment "${_}" in config file`);console.warn(`Could not find user with role "${l}" for environment "${_}" in config file, trying to login with environment's default user`)}return{environment:C,user:F}}e(RCt,"resolveEnvironment");function ctn(p){let l=`${p??q9e()}/login.ts`;if(!(0,zPt.existsSync)(l))throw console.warn(`Could not locate the login.ts file. Please make sure your login file exists at ${l}`),new Error("Could not find login.ts file");try{return require(l).default}catch(_){throw console.warn("Error loading login.ts file",_),_}}e(ctn,"requireLogin");async function utn(p,l,{environment:_,user:g,config:C}){try{let P=e(()=>l(p,{environment:_,user:g,config:C}),"performLogin");"checksumAI"in p?await p.checksumAI(`Log in${g!=null&&g.role?` using ${g.role} role`:""}${_!=null&&_.name?` in ${_.name} environment`:""}`,P):await P()}catch(P){throw console.warn(`The login method threw an exception, please check the login.ts file for the following error:
1837
- `,P),P}}e(utn,"proceedWithLogin");function U9e(p){let{config:l,folder:_,throwIfAuthFailed:g}=p,C=ctn(_);return async(P,{role:F,environment:M}={})=>{let{environment:V,user:W}=RCt(l,{role:F,environment:M},p.throwIfEnvInfoInvalid);if(g&&!W)throw new Error("Could not find user credentials matching the provided role and/or environment");await utn(P,C,{environment:V,user:W,config:l})}}e(U9e,"makeUnboundLogin");function R_r(p,{environmentName:l,userRole:_}){let g=U9e(p);return C=>g(C,{environment:l,role:_})}e(R_r,"makeBoundLogin");var ttt;function B_r(){if(ttt)return ttt;try{let p=(0,zPt.existsSync)(`${q9e()}/checksum.config.ts`)?"checksum.config.ts":(0,zPt.existsSync)(`${q9e()}/checksum.config.tmp.ts`)?"checksum.config.tmp.ts":void 0;if(p)return require(`${q9e()}/${p}`).default}catch{console.warn("Could not find checksum config file, will run with defaults")}return NVt()}e(B_r,"loadChecksumConfig");function NVt(p={}){var g,C;let l={apiKey:void 0,runMode:"normal",apiURL:"https://api.checksum.ai",options:{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:!0,useMockData:!1,printLogs:!1,hideReports:process.env.AUTHORIZE_REPORTS==="true"}};return ttt={...l,...p,options:{...l.options,...p.options}},((g=ttt.environments)==null?void 0:g.length)>0&&((C=ttt.environments)==null?void 0:C.some(P=>{var F;return((F=P.users)==null?void 0:F.length)>0}))||console.warn("Environments array is empty or invalid (does not include valid users)"),ttt}e(NVt,"getChecksumConfig");var hNe="Checksum failed connecting to the server";var $Pt=(g=>(g[g.Element=0]="Element",g[g.VisibleElement=1]="VisibleElement",g[g.AtPointElement=2]="AtPointElement",g))($Pt||{});var ltn={generateSelectionData:!1,navigationTimeout:30*1e3,actionTimeout:5*1e3},FVt=class FVt{constructor(l,_,g,C,P,F){this.page=l;this.evaluateWithChecksum=_;this.checksumPage=g;this.pageInteractor=C;this.trace=P;this.options=F;this.API_BASE_DOMAIN="https://api.checksum.ai";this.didCancel=!1;this.timeout=15*60*1e3;this.canResolveAssertion=!1;this.page=l,this.options={...ltn,...F}}canResolve(l){return!(l.type==="assertion"&&!this.canResolveAssertion)}addMetadata(l){}cancel(){this.didCancel=!0}async execute(l,_,g,C=6e4){return M_r(l,_,g,C)}log(...l){gT(...l)}setThought(l){this.thought=l}setVariables(l){this.variables=l}get shouldSendToAnalytics(){return!0}getAnalyticsPayload(){return{}}toString(){return this.constructor.name}};e(FVt,"AbstractFallback");var gNe=FVt;var IVt=class IVt extends gNe{constructor(){super(...arguments);this.API_BASE_ROUTE="/client-api/runtime/esra-fallback"}init(_){let{apiKey:g,testId:C,apiURL:P,checksumId:F,fileName:M,timeout:V}=_;return this.data={...this.data,testId:C,checksumId:F,fileName:M},this.apiKey=g,P&&(this.API_BASE_DOMAIN=P.replace(/\/$/,"")),V&&(this.timeout=V),this.checksumRootFolder=process.env.CHECKSUM_ROOT_FOLDER??UPt(VPt(this.data.fileName),this.data.fileName),this}getRecoveryAttemptTitle(_){return`Checksum auto-heal: trying to locate the element using checksumSelector("${this.data.checksumId}")...`}async sendLog(_){let g=this.getLogPayload(_);try{fetch(`${this.getAPIBaseURL()}/log`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.apiKey},body:JSON.stringify(g)}).catch(C=>this.log("[ESRAFallback] Error sending log"))}catch(C){this.log("[ESRAFallback] Error sending log",C)}}getLogPayload(_){let g=process.env.CHECKSUM_TEST_SUITE_ID??"",{selector:C}=_,{checksumId:P,testId:F}=this.data;return this.logPayload={testSuiteId:g,testId:F,selector:C,checksumId:P,thought:this.thought},this.logPayload}async getMetadataForTestId(){return qPt(this.checksumRootFolder,this.data.testId)}getAPIBaseURL(){return this.API_BASE_DOMAIN+this.API_BASE_ROUTE}};e(IVt,"MetadataBaseFallback");var yNe=IVt;var OVt=class OVt extends yNe{constructor(){super(...arguments);this.API_BASE_ROUTE="/client-api/runtime/esra-fallback";this.timeout=30*1e3;this.locatorTypeEnumToFieldMap={0:"element",1:"visibleElement",2:"atPointElement"}}init(_){return super.init(_),this.data.minSelectionScore=.7,this}async resolve(_){try{let{method:g,args:C}=_,{checksumId:P}=this.data,F=await this.getActionIdToESRAMap();if(!(P in F))throw this.errorMessage=`No ESRA metadata found for id ${P}`,new Error(this.errorMessage);let M=await this.getTestIdsForLocator(F[P].esraMetadata),{elementDataMap:V}=await this.getSelectors(M);if(this.didCancel)return;let W=await this.executeWithSelectors(Object.values(V),g,C);return W?(this.sendLog(W),this.checksumPage.addErrorMessage(_.error,`${this.thought?`"${this.thought}" auto-healed`:"Auto-healed"} using alternative selector "${W.selector}"`),{steps:[{type:"action",...W}]}):void 0}catch(g){this.errorMessage=g.message,this.log(this.errorMessage);return}}async getActionIdToESRAMap(){try{this.actionIdToESRAMap||(this.actionIdToESRAMap=await this.getMetadataForTestId())}catch(_){return super.log("Could not read ESRA metadata file, ",_),{}}return this.actionIdToESRAMap}async getSelectors(_){let g=[],C={};if(!_)return{selectors:g,elementDataMap:C};for(let P in Object.keys($Pt)){let F=_.testIds[this.locatorTypeEnumToFieldMap[P]];if(!F)continue;let M=`[data-checksum-testid="${F}"]`;g.push(M),C[M]={..._.elementData[this.locatorTypeEnumToFieldMap[P]],selector:_.selectors[this.locatorTypeEnumToFieldMap[P]],parentFramesSelectors:_.parentFramesSelectors[this.locatorTypeEnumToFieldMap[P]]}}for(let P in Object.keys($Pt)){let F=_.selectors[this.locatorTypeEnumToFieldMap[P]];F&&(g.push(F),C[F]={..._.elementData[this.locatorTypeEnumToFieldMap[P]],selector:F})}return this.log("Selectors for ESRA metadata:",g),{selectors:g,elementDataMap:C}}async getTestIdsForLocator(_,g={}){let{cachedSelector:C=void 0,retriesLeft:P=3,retryMaxTimeout:F=3e3,staticMetadata:M}=g,V=await this.evaluateWithChecksum(async({esraMetadata:W,cachedSelector:Q,staticMetadata:ae,minSelectionScore:G})=>await window.checksum.testGenerator.getMatchingElementSelectionData(W,{minSelectionScore:G,cachedSelector:Q,staticMetadata:ae}),{esraMetadata:_,cachedSelector:C,staticMetadata:M,minSelectionScore:this.data.minSelectionScore});if(!V){if(P>0)return this.log("[getTestIdsForLocator] no match found, waiting and retrying..."),await WC(F/P),this.getTestIdsForLocator(_,{...g,retriesLeft:P-1});this.errorMessage="failed to locate",this.log(`[getTestIdsForLocator] ${this.errorMessage}`)}return V}async executeWithSelectors(_,g,C){for(let{selector:P,tag:F,parentFramesSelectors:M}of _){let V=this.pageInteractor.makeLocator(P,M);this.log(`Running with selector=${P};${M!=null&&M.length?` parentFramesSelectors=${M};`:""}`);let W=!1;["check","uncheck"].includes(g)&&F!=="input"&&(W=!0);let Q=this.generateSelectionDataForSelector(P,M);if(await this.checksumPage.wrapNoLocationSteps(async()=>this.execute(V,W?"click":g,C))===!1){this.log("Fallback selector timeout");continue}return Q}}async generateSelectionDataForSelector(_,g){let{generateSelectionData:C}=this.options;if(!C)return{selector:_,generatedLocator:void 0,esraMetadata:void 0,parentFramesSelectors:void 0};try{let P=await O_r(this.page,_,g);if(!P)throw this.errorMessage=`[generateSelectionDataForSelector] Failed to generate selection data for selector ${_}`,new Error(this.errorMessage);return P}catch(P){throw this.log(P.message),P}}getAnalyticsPayload(){return{fallbackType:"esra",...this.logPayload??{checksumId:this.data.checksumId,error:this.errorMessage}}}toString(){return`Checksum selector (${this.data.checksumId})`}};e(OVt,"ESRAfallback");var BCt=OVt;var LVt=class LVt extends gNe{init(){return this}canResolve(l){return["check","uncheck"].includes(l.method)}getRecoveryAttemptTitle(l){return"Checksum auto-heal: Trying force click for check/uncheck action..."}async resolve(l){try{let{locator:_,method:g}=l;if(!_)return;let{args:C}=l;if(!["check","uncheck"].includes(g))return;let P=!1;for(let M of Array.from(C))if(typeof M=="object"){M.force=!0,P=!0;break}if(P||(C=Array.from(C),C.push({force:!0})),await this.execute(_,g,C)!==!1)return{steps:[{type:"action",selector:_._selector,generatedLocator:void 0,esraMetadata:void 0}]};this.log("Locator timed out, ")}catch(_){this.log("initiateFallbackSequence exception, ",_);return}}get shouldSendToAnalytics(){return!1}toString(){return"Force click check/uncheck"}};e(LVt,"ForceFallback");var jCt=LVt;var szt=require("crypto"),nNt=require("fs"),ozt=x7(require("path")),E7e=x7(azt());function vdr(p){return p.filter((l,_)=>!p.slice(_+1).some(P=>Ktn(l,P)))}e(vdr,"filterNestedNodes");function Ktn(p,l){if(p.getSourceFile()!==l.getSourceFile())return!1;let _=p.getStart(),g=p.getEnd(),C=l.getStart(),P=l.getEnd();return _>=C&&g<=P}e(Ktn,"isNodeNested");var Ytn=e(p=>{let l=(0,nNt.readFileSync)(p,"utf8");return E7e.default.createSourceFile(p,l,E7e.default.ScriptTarget.Latest,!0)},"createSourceFile"),Xtn=e(p=>{let _=/at\s+(?:.*\s+\()?(.+):(\d+):(\d+)\)?/.exec(p);if(!_)return null;let g=ozt.default.isAbsolute(_[1])?_[1]:ozt.default.resolve(process.cwd(),_[1]);return!(0,nNt.existsSync)(g)||["node_modules","dist","build"].some(C=>g.includes(C))?null:{filePath:g,lineNumber:parseInt(_[2],10),columnNumber:parseInt(_[3],10),sourceFile:Ytn(g)}},"getLineInfo"),czt=e(p=>!E7e.default.isFunctionDeclaration(p),"isExecutableStatement"),Qtn=e(p=>{for(;p;){if(E7e.default.isStatement(p)&&czt(p)&&p.parent&&(E7e.default.isBlock(p.parent)||E7e.default.isSourceFile(p.parent)))return p;p=p.parent}},"findCallSiteStatement"),Ztn=e(p=>{let{filePath:l,lineNumber:_,sourceFile:g}=p,C,P=Number.MAX_SAFE_INTEGER,F=e(M=>{let{line:V}=g.getLineAndCharacterOfPosition(M.getStart()),{line:W}=g.getLineAndCharacterOfPosition(M.getEnd());if(V<=_-1&&W>=_-1){let Q=M.getEnd()-M.getStart();Q<P&&(P=Q,C=M)}E7e.default.forEachChild(M,F)},"visit");return F(g),C},"findEnclosingStatement"),ern=e(p=>{if(!p.parent||!E7e.default.isBlock(p.parent)&&!E7e.default.isSourceFile(p.parent))return{before:[],after:[]};let l=p.parent.statements,_=l.findIndex(g=>g===p);return _<0?{before:[],after:[]}:{before:l.slice(0,_+1).filter(czt),after:l.slice(_+1).filter(czt)}},"getSurroundingStatements"),trn=e(p=>{let l=[],_=[],g;return p.forEach(C=>{let P=Xtn(C);if(!P)return;let F=Ztn(P);if(!F)return;let M=Qtn(F);if(!M)return;g||(g=M);let V=ern(M),W=V.before,Q=V.after;l.push(...W.reverse()),_.push(...Q)}),{before:l.reverse(),after:_,error:g}},"getCodeTraceNodes");function rrn(p){let l=e(P=>({start:P.getStart(),end:P.getEnd()}),"getRange"),_=new Map;p.forEach(P=>{let F=null,M=l(P.node);p.forEach(V=>{if(V===P||V.node.getSourceFile().fileName!==P.node.getSourceFile().fileName)return;let W=l(V.node);M.start>=W.start&&M.end<=W.end&&(!F||W.end-W.start<l(F.node).end-l(F.node).start)&&(F=V)}),_.set(P,F)});let g=new Map;p.forEach(P=>g.set(P,[])),p.forEach(P=>{let F=_.get(P);F&&g.get(F).push(P)});let C=1;return p.forEach(P=>{let F=g.get(P);if(F.length>0){let M=`FUNC ${C++}`;P.text=P.text.replace(/\{[\s\S]*\}/,`{ ${M} }`),F.sort((V,W)=>V.node.getStart()-W.node.getStart()),F[0].text=`START OF ${M}
1837
+ `,P),P}}e(utn,"proceedWithLogin");function U9e(p){let{config:l,folder:_,throwIfAuthFailed:g}=p,C=ctn(_);return async(P,{role:F,environment:M}={})=>{let{environment:V,user:W}=RCt(l,{role:F,environment:M},p.throwIfEnvInfoInvalid);if(g&&!W)throw new Error("Could not find user credentials matching the provided role and/or environment");await utn(P,C,{environment:V,user:W,config:l})}}e(U9e,"makeUnboundLogin");function R_r(p,{environmentName:l,userRole:_}){let g=U9e(p);return C=>g(C,{environment:l,role:_})}e(R_r,"makeBoundLogin");var ttt;function B_r(){if(ttt)return ttt;try{let p=(0,zPt.existsSync)(`${q9e()}/checksum.config.ts`)?"checksum.config.ts":(0,zPt.existsSync)(`${q9e()}/checksum.config.tmp.ts`)?"checksum.config.tmp.ts":void 0;if(p)return require(`${q9e()}/${p}`).default}catch{console.warn("Could not find checksum config file, will run with defaults")}return NVt()}e(B_r,"loadChecksumConfig");function NVt(p={}){var g,C;let l={apiKey:void 0,runMode:"normal",apiURL:"https://api.checksum.ai",options:{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:!0,useMockData:!1,printLogs:!1,hideReports:process.env.AUTHORIZE_REPORTS==="true"}};return ttt={...l,...p,options:{...l.options,...p.options}},((g=ttt.environments)==null?void 0:g.length)>0&&((C=ttt.environments)==null?void 0:C.some(P=>{var F;return((F=P.users)==null?void 0:F.length)>0}))||console.warn("Environments array is empty or invalid (does not include valid users)"),ttt}e(NVt,"getChecksumConfig");var hNe="Checksum failed connecting to the server";var $Pt=(g=>(g[g.Element=0]="Element",g[g.VisibleElement=1]="VisibleElement",g[g.AtPointElement=2]="AtPointElement",g))($Pt||{});var ltn={generateSelectionData:!1,navigationTimeout:30*1e3,actionTimeout:5*1e3},FVt=class FVt{constructor(l,_,g,C,P,F){this.page=l;this.evaluateWithChecksum=_;this.checksumPage=g;this.pageInteractor=C;this.trace=P;this.options=F;this.API_BASE_DOMAIN="https://api.checksum.ai";this.didCancel=!1;this.timeout=15*60*1e3;this.canResolveAssertion=!1;this.page=l,this.options={...ltn,...F}}canResolve(l){return!(l.type==="assertion"&&!this.canResolveAssertion)}addMetadata(l){}cancel(){this.didCancel=!0}async execute(l,_,g,C=6e4){return M_r(l,_,g,C)}log(...l){gT(...l)}setThought(l){this.thought=l}setVariables(l){this.variables=l}get shouldSendToAnalytics(){return!0}getAnalyticsPayload(){return{}}toString(){return this.constructor.name}};e(FVt,"AbstractFallback");var gNe=FVt;var IVt=class IVt extends gNe{constructor(){super(...arguments);this.API_BASE_ROUTE="/client-api/runtime/esra-fallback"}init(_){let{apiKey:g,testId:C,apiURL:P,checksumId:F,fileName:M,timeout:V}=_;return this.data={...this.data,testId:C,checksumId:F,fileName:M},this.apiKey=g,P&&(this.API_BASE_DOMAIN=P.replace(/\/$/,"")),V&&(this.timeout=V),this.checksumRootFolder=process.env.CHECKSUM_ROOT_FOLDER??UPt(VPt(this.data.fileName),this.data.fileName),this}getRecoveryAttemptTitle(_){return`Checksum auto-heal: trying to locate the element using checksumSelector("${this.data.checksumId}")...`}async sendLog(_){let g=this.getLogPayload(_);try{fetch(`${this.getAPIBaseURL()}/log`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.apiKey},body:JSON.stringify(g)}).catch(C=>this.log("[ESRAFallback] Error sending log"))}catch(C){this.log("[ESRAFallback] Error sending log",C)}}getLogPayload(_){let g=process.env.CHECKSUM_TEST_SUITE_ID??"",{selector:C}=_,{checksumId:P,testId:F}=this.data;return this.logPayload={testSuiteId:g,testId:F,selector:C,checksumId:P,thought:this.thought},this.logPayload}async getMetadataForTestId(){return qPt(this.checksumRootFolder,this.data.testId)}getAPIBaseURL(){return this.API_BASE_DOMAIN+this.API_BASE_ROUTE}};e(IVt,"MetadataBaseFallback");var yNe=IVt;var OVt=class OVt extends yNe{constructor(){super(...arguments);this.API_BASE_ROUTE="/client-api/runtime/esra-fallback";this.timeout=30*1e3;this.locatorTypeEnumToFieldMap={0:"element",1:"visibleElement",2:"atPointElement"}}init(_){return super.init(_),this.data.minSelectionScore=.7,this}async resolve(_){try{let{method:g,args:C}=_,{checksumId:P}=this.data,F=await this.getActionIdToESRAMap();if(!(P in F))throw this.errorMessage=`No ESRA metadata found for id ${P}`,new Error(this.errorMessage);let M=await this.getTestIdsForLocator(F[P].esraMetadata),{elementDataMap:V}=await this.getSelectors(M);if(this.didCancel)return;let W=await this.executeWithSelectors(Object.values(V),g,C);return W?(this.sendLog(W),this.checksumPage.addErrorMessage(_.error,`${this.thought?`"${this.thought}" auto-recovered`:"Auto-recovered"} using alternative selector "${W.selector}"`),{steps:[{type:"action",...W}]}):void 0}catch(g){this.errorMessage=g.message,this.log(this.errorMessage);return}}async getActionIdToESRAMap(){try{this.actionIdToESRAMap||(this.actionIdToESRAMap=await this.getMetadataForTestId())}catch(_){return super.log("Could not read ESRA metadata file, ",_),{}}return this.actionIdToESRAMap}async getSelectors(_){let g=[],C={};if(!_)return{selectors:g,elementDataMap:C};for(let P in Object.keys($Pt)){let F=_.testIds[this.locatorTypeEnumToFieldMap[P]];if(!F)continue;let M=`[data-checksum-testid="${F}"]`;g.push(M),C[M]={..._.elementData[this.locatorTypeEnumToFieldMap[P]],selector:_.selectors[this.locatorTypeEnumToFieldMap[P]],parentFramesSelectors:_.parentFramesSelectors[this.locatorTypeEnumToFieldMap[P]]}}for(let P in Object.keys($Pt)){let F=_.selectors[this.locatorTypeEnumToFieldMap[P]];F&&(g.push(F),C[F]={..._.elementData[this.locatorTypeEnumToFieldMap[P]],selector:F})}return this.log("Selectors for ESRA metadata:",g),{selectors:g,elementDataMap:C}}async getTestIdsForLocator(_,g={}){let{cachedSelector:C=void 0,retriesLeft:P=3,retryMaxTimeout:F=3e3,staticMetadata:M}=g,V=await this.evaluateWithChecksum(async({esraMetadata:W,cachedSelector:Q,staticMetadata:ae,minSelectionScore:G})=>await window.checksum.testGenerator.getMatchingElementSelectionData(W,{minSelectionScore:G,cachedSelector:Q,staticMetadata:ae}),{esraMetadata:_,cachedSelector:C,staticMetadata:M,minSelectionScore:this.data.minSelectionScore});if(!V){if(P>0)return this.log("[getTestIdsForLocator] no match found, waiting and retrying..."),await WC(F/P),this.getTestIdsForLocator(_,{...g,retriesLeft:P-1});this.errorMessage="failed to locate",this.log(`[getTestIdsForLocator] ${this.errorMessage}`)}return V}async executeWithSelectors(_,g,C){for(let{selector:P,tag:F,parentFramesSelectors:M}of _){let V=this.pageInteractor.makeLocator(P,M);this.log(`Running with selector=${P};${M!=null&&M.length?` parentFramesSelectors=${M};`:""}`);let W=!1;["check","uncheck"].includes(g)&&F!=="input"&&(W=!0);let Q=this.generateSelectionDataForSelector(P,M);if(await this.checksumPage.wrapNoLocationSteps(async()=>this.execute(V,W?"click":g,C))===!1){this.log("Fallback selector timeout");continue}return Q}}async generateSelectionDataForSelector(_,g){let{generateSelectionData:C}=this.options;if(!C)return{selector:_,generatedLocator:void 0,esraMetadata:void 0,parentFramesSelectors:void 0};try{let P=await O_r(this.page,_,g);if(!P)throw this.errorMessage=`[generateSelectionDataForSelector] Failed to generate selection data for selector ${_}`,new Error(this.errorMessage);return P}catch(P){throw this.log(P.message),P}}getAnalyticsPayload(){return{fallbackType:"esra",...this.logPayload??{checksumId:this.data.checksumId,error:this.errorMessage}}}toString(){return`Checksum selector (${this.data.checksumId})`}};e(OVt,"ESRAfallback");var BCt=OVt;var LVt=class LVt extends gNe{init(){return this}canResolve(l){return["check","uncheck"].includes(l.method)}getRecoveryAttemptTitle(l){return"Checksum auto-heal: Trying force click for check/uncheck action..."}async resolve(l){try{let{locator:_,method:g}=l;if(!_)return;let{args:C}=l;if(!["check","uncheck"].includes(g))return;let P=!1;for(let M of Array.from(C))if(typeof M=="object"){M.force=!0,P=!0;break}if(P||(C=Array.from(C),C.push({force:!0})),await this.execute(_,g,C)!==!1)return{steps:[{type:"action",selector:_._selector,generatedLocator:void 0,esraMetadata:void 0}]};this.log("Locator timed out, ")}catch(_){this.log("initiateFallbackSequence exception, ",_);return}}get shouldSendToAnalytics(){return!1}toString(){return"Force click check/uncheck"}};e(LVt,"ForceFallback");var jCt=LVt;var szt=require("crypto"),nNt=require("fs"),ozt=x7(require("path")),E7e=x7(azt());function vdr(p){return p.filter((l,_)=>!p.slice(_+1).some(P=>Ktn(l,P)))}e(vdr,"filterNestedNodes");function Ktn(p,l){if(p.getSourceFile()!==l.getSourceFile())return!1;let _=p.getStart(),g=p.getEnd(),C=l.getStart(),P=l.getEnd();return _>=C&&g<=P}e(Ktn,"isNodeNested");var Ytn=e(p=>{let l=(0,nNt.readFileSync)(p,"utf8");return E7e.default.createSourceFile(p,l,E7e.default.ScriptTarget.Latest,!0)},"createSourceFile"),Xtn=e(p=>{let _=/at\s+(?:.*\s+\()?(.+):(\d+):(\d+)\)?/.exec(p);if(!_)return null;let g=ozt.default.isAbsolute(_[1])?_[1]:ozt.default.resolve(process.cwd(),_[1]);return!(0,nNt.existsSync)(g)||["node_modules","dist","build"].some(C=>g.includes(C))?null:{filePath:g,lineNumber:parseInt(_[2],10),columnNumber:parseInt(_[3],10),sourceFile:Ytn(g)}},"getLineInfo"),czt=e(p=>!E7e.default.isFunctionDeclaration(p),"isExecutableStatement"),Qtn=e(p=>{for(;p;){if(E7e.default.isStatement(p)&&czt(p)&&p.parent&&(E7e.default.isBlock(p.parent)||E7e.default.isSourceFile(p.parent)))return p;p=p.parent}},"findCallSiteStatement"),Ztn=e(p=>{let{filePath:l,lineNumber:_,sourceFile:g}=p,C,P=Number.MAX_SAFE_INTEGER,F=e(M=>{let{line:V}=g.getLineAndCharacterOfPosition(M.getStart()),{line:W}=g.getLineAndCharacterOfPosition(M.getEnd());if(V<=_-1&&W>=_-1){let Q=M.getEnd()-M.getStart();Q<P&&(P=Q,C=M)}E7e.default.forEachChild(M,F)},"visit");return F(g),C},"findEnclosingStatement"),ern=e(p=>{if(!p.parent||!E7e.default.isBlock(p.parent)&&!E7e.default.isSourceFile(p.parent))return{before:[],after:[]};let l=p.parent.statements,_=l.findIndex(g=>g===p);return _<0?{before:[],after:[]}:{before:l.slice(0,_+1).filter(czt),after:l.slice(_+1).filter(czt)}},"getSurroundingStatements"),trn=e(p=>{let l=[],_=[],g;return p.forEach(C=>{let P=Xtn(C);if(!P)return;let F=Ztn(P);if(!F)return;let M=Qtn(F);if(!M)return;g||(g=M);let V=ern(M),W=V.before,Q=V.after;l.push(...W.reverse()),_.push(...Q)}),{before:l.reverse(),after:_,error:g}},"getCodeTraceNodes");function rrn(p){let l=e(P=>({start:P.getStart(),end:P.getEnd()}),"getRange"),_=new Map;p.forEach(P=>{let F=null,M=l(P.node);p.forEach(V=>{if(V===P||V.node.getSourceFile().fileName!==P.node.getSourceFile().fileName)return;let W=l(V.node);M.start>=W.start&&M.end<=W.end&&(!F||W.end-W.start<l(F.node).end-l(F.node).start)&&(F=V)}),_.set(P,F)});let g=new Map;p.forEach(P=>g.set(P,[])),p.forEach(P=>{let F=_.get(P);F&&g.get(F).push(P)});let C=1;return p.forEach(P=>{let F=g.get(P);if(F.length>0){let M=`FUNC ${C++}`;P.text=P.text.replace(/\{[\s\S]*\}/,`{ ${M} }`),F.sort((V,W)=>V.node.getStart()-W.node.getStart()),F[0].text=`START OF ${M}
1838
1838
  ${F[0].text}`}}),p}e(rrn,"annotateNestedBodies");var nrn=e(p=>{var P;let l=vdr(p.before).map(F=>({node:F,text:F.getText(),id:(0,szt.randomUUID)().slice(0,8)})).slice(0,-1),_=vdr(p.after).map(F=>({node:F,text:F.getText(),id:(0,szt.randomUUID)().slice(0,8)})),g=[...l,..._];g=rrn(g);let C={node:p.error,text:(P=p.error)==null?void 0:P.getText()};return{before:l,after:_,error:C}},"processNodes"),rNt=class rNt{constructor(l,_,g,C){this.stackTraceLines=l;this.before=_;this.after=g;this.error=C}static analyze(l){var P;let _=l.split(`
1839
1839
  `),g=trn(_);console.log((P=g.error)==null?void 0:P.getText());let C=nrn(g);return new rNt(_,C.before,C.after,C.error)}toString(){let l=this.before.map(C=>C.text).join(`
1840
1840
  `),_=this.error.text,g=this.after.map(C=>C.text).join(`
@@ -1851,12 +1851,12 @@ ${_}
1851
1851
  \`\`\`ts
1852
1852
  ${g}
1853
1853
  \`\`\`
1854
- `}};e(rNt,"CodeTracer");var tNt=rNt;var bdr=require("jsdom");var uzt=class uzt extends gNe{constructor(){super(...arguments);this.API_BASE_ROUTE="/client-api/runtime/ai-fallback";this.CLIENT_MAX_ITERATIONS=10;this.thoughts=[];this.withChecksumAI=!1;this.executedSteps=[];this.stepsPayload=[];this.currentChecksumId="0";this.hasPreviousActionFailed=!1;this.canResolveAssertion=!0;this.finish=!1;this.actionsCounter=1;this.mockServer=!1;this.actionEventCodeToMethodName={click:"click",double_click:"dblclick",drag_and_drop:"dragTo",input:"fill",click_and_type:"fill",clear_and_type:"fill",hover:"hover",keystroke:"keyboard.press",navigation:"goto",check:"check",uncheck:"uncheck",selectoption:"selectOption",upload_files:"upload_files",get_more_items:"get_more_items",wait:"wait",switch_tab:"switch_tab",custom_code:"custom_code",logout_and_login:"logout_and_login",canvas_click:"canvas_click",native_accept:"native_accept",native_dismiss:"native_dismiss",login:"login"}}init(_){let{goal:g,apiKey:C,testId:P,apiURL:F,thoughts:M}=_;return this.goal=g,this.apiKey=C,this.testId=P,this.testSuiteId=process.env.CHECKSUM_TEST_SUITE_ID??"",this.thoughts=M,this.withChecksumAI=!1,this.testFile=_.testFile,F&&(this.API_BASE_DOMAIN=F.replace(/\/$/,"")),this}getRecoveryAttemptTitle(_){switch(_.type){case"action":return`Checksum auto-heal: trying to achieve action "${this.getFailedThought()}"...`;case"assertion":return`Checksum auto-heal: trying to verify assertion "${this.getFailedThought()}"...`}}async resolve(_){this.fallbackData=_,this.withChecksumAI=_.withChecksumAI;let g=this.getFailedThought();if(g!=="_fail_")try{if(await this.initSession(),!await this.iterate()){this.log("[AIFallback] AIFallback failed");return}return this.addAutoHealErrorToReport(_,g),{steps:this.executedSteps.map(P=>{switch(P.type){case"action":return this.translateExecutedActionToFallbackAction(P);case"assertion":return P}})}}catch(C){if(this.errorMessage=C.message,this.withChecksumAI&&C.message==="fetch failed")throw C;this.log("[AIFallback] Error",C);return}}addAutoHealErrorToReport(_,g){this.withChecksumAI||this.checksumPage.addErrorMessage(_.error,`"${g}" auto-healed:
1854
+ `}};e(rNt,"CodeTracer");var tNt=rNt;var bdr=require("jsdom");var uzt=class uzt extends gNe{constructor(){super(...arguments);this.API_BASE_ROUTE="/client-api/runtime/ai-fallback";this.CLIENT_MAX_ITERATIONS=10;this.thoughts=[];this.withChecksumAI=!1;this.executedSteps=[];this.stepsPayload=[];this.currentChecksumId="0";this.hasPreviousActionFailed=!1;this.canResolveAssertion=!0;this.finish=!1;this.actionsCounter=1;this.mockServer=!1;this.actionEventCodeToMethodName={click:"click",double_click:"dblclick",drag_and_drop:"dragTo",input:"fill",click_and_type:"fill",clear_and_type:"fill",hover:"hover",keystroke:"keyboard.press",navigation:"goto",check:"check",uncheck:"uncheck",selectoption:"selectOption",upload_files:"upload_files",get_more_items:"get_more_items",wait:"wait",switch_tab:"switch_tab",custom_code:"custom_code",logout_and_login:"logout_and_login",canvas_click:"canvas_click",native_accept:"native_accept",native_dismiss:"native_dismiss",login:"login"}}init(_){let{goal:g,apiKey:C,testId:P,apiURL:F,thoughts:M}=_;return this.goal=g,this.apiKey=C,this.testId=P,this.testSuiteId=process.env.CHECKSUM_TEST_SUITE_ID??"",this.thoughts=M,this.withChecksumAI=!1,this.testFile=_.testFile,F&&(this.API_BASE_DOMAIN=F.replace(/\/$/,"")),this}getRecoveryAttemptTitle(_){switch(_.type){case"action":return`Checksum auto-heal: trying to achieve action "${this.getFailedThought()}"...`;case"assertion":return`Checksum auto-heal: trying to verify assertion "${this.getFailedThought()}"...`}}async resolve(_){this.fallbackData=_,this.withChecksumAI=_.withChecksumAI;let g=this.getFailedThought();if(g!=="_fail_")try{if(await this.initSession(),!await this.iterate()){this.log("[AIFallback] AIFallback failed");return}return this.addAutoHealErrorToReport(_,g),{steps:this.executedSteps.map(P=>{switch(P.type){case"action":return this.translateExecutedActionToFallbackAction(P);case"assertion":return P}})}}catch(C){if(this.errorMessage=C.message,this.withChecksumAI&&C.message==="fetch failed")throw C;this.log("[AIFallback] Error",C);return}}addAutoHealErrorToReport(_,g){this.withChecksumAI||this.checksumPage.addErrorMessage(_.error,`"${g}" auto-recovered:
1855
1855
  ${this.executedSteps.map(C=>{switch(C.type){case"action":return C.thought;case"assertion":return C.feedback}}).join(`,
1856
- `)}`)}async getReductionComponents(_){var g,C;return _.interruptionEvent==="didRequestMoreItemsEvent"?{reducedHTML:(C=(g=_.payload)==null?void 0:g.promptData)==null?void 0:C.reducedHTML,reducedDomHTMLElement:this.lastReducedDOM,flashingHTML:[],elementsForNodeInterpretation:[],currentChecksumId:this.currentChecksumId}:this.pageInteractor.getCurrentReducedHTML({stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:this.currentChecksumId})}getStackTrace(){try{return tNt.analyze(this.fallbackData.error.stack).toString()}catch(_){this.log("[AIFallback] Error getting stack trace",_);return}}async getPageScreenshot(){try{return(await this.page.screenshot({fullPage:!0})).toString("base64")}catch{return}}async iterate(){var g,C;this.hasPreviousActionFailed=!1;let _=this.CLIENT_MAX_ITERATIONS;do{if(this.didCancel)return!1;let P=await this.getPreviousActionOverview(),{reducedHTML:F,flashingHTML:M,elementsForNodeInterpretation:V,currentChecksumId:W}=await this.getReductionComponents(P),Q=await this.getPageScreenshot();this.lastReducedDOM=new bdr.JSDOM(F),this.currentChecksumId=W;let ae=await this.getNextAction({reducedHTML:F,flashingHTML:M,elementsForNodeInterpretation:V,previousActionOverview:P,screenshot:Q});if(this.didCancel)return!1;if(["failed","fail"].includes(ae.thought)||["failed","fail"].includes((g=ae.action)==null?void 0:g.type))return this.log("[AIFallback] Received failed signal, will quit"),this.errorMessage="Received failed signal",!1;if((ae.changedVariables??[]).forEach(({name:ne,value:ue})=>{this.checksumPage.variableStore.setVariable(ne,ue)}),this.fallbackData.type==="assertion"){let ne=ae.thought;this.log(`[AIFallback] for assertion returned with value: ${ae.action.value}, feedback: ${ne}`);let ue=["irrelevant","pass","soft_reject"].includes(ae.action.value);this.checksumPage.step(`AI: ${ne}`,async()=>{}),this.executedSteps.push({type:"assertion",feedback:ne,response:ae.action.value});let qe={feedback:ne,response:ae.action.value};return this.stepsPayload.push(qe),this.trace.aiFallbackStep(this.sessionId,qe),ue}if(ae.thought==="finish"||((C=ae.action)==null?void 0:C.type)==="finish")return this.log("[AIFallback] Received finish step"),!0;let _e=await this.pageInteractor.translateActionResponseToAgentPotentialAction(ae);try{try{await this.checksumPage.step(`AI: ${_e.thought}`,async()=>{await this.pageInteractor.performAction(_e)})}catch(ne){throw this.fallbackData.error=ne,new Error("Action failed")}this.hasPreviousActionFailed=!1,this.executedSteps.push({type:"action",..._e}),this.addActionStepPayload(ae,_e),await WC(1e3)}catch(ne){this.log("[AIFallback] Error while executing selector",ne.message),this.hasPreviousActionFailed=!0;continue}if(--_<=0){this.errorMessage="maximum repetition reached",this.log(`[AIFallback] ${this.errorMessage}`);break}}while(!0);return!1}addActionStepPayload(_,g){let{thought:C,action:{checksumid:P,type:F}}=_,{selector:M,locator:V,fillValue:W,getMoreItemsId:Q}=g,ae={thought:C,checksumid:P,type:F,selector:M,locator:V,fillValue:W,getMoreItemsId:Q};this.stepsPayload.push(ae),this.trace.aiFallbackStep(this.sessionId,ae)}async getNextAction({reducedHTML:_,flashingHTML:g,elementsForNodeInterpretation:C,previousActionOverview:P,screenshot:F,codeTrace:M}){let{apiKey:V}=this;if(this.mockServer)return this.finish?{thought:"finish"}:(--this.actionsCounter===0&&(this.finish=!0),{thought:"mock-thought",action:{type:"click",checksumid:"10"}});let W={reduction:{reducedHTML:_,flashingHTML:g,elementsForNodeInterpretation:C},currentURL:this.page.url(),previousActionOverview:P,resolvesSmartAssertion:this.withChecksumAI,variables:this.variables,screenshot:F};try{let ae=await(await fetch(`${this.getAPIBaseURL()}/iterate`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.apiKey},body:JSON.stringify({appName:V,sessionId:this.sessionId,iterationData:W})})).json();return this.log("[AIFallback] Received next action",ae),ae}catch(Q){throw this.log("[AIFallback] Error calling iterate",Q),Q}}async getPreviousActionOverview(){let _=await this.pageInteractor.handleFileChooserEvent();return{success:!this.hasPreviousActionFailed,...this.hasPreviousActionFailed?{failureEvent:"generalExecutionFailureError"}:{},...this.getPreviousWaitActionOverview(),..._,...await this.getPreviousGetMoreItemsActionOverview()}}getExecutedActions(){return this.executedSteps.filter(_=>_.type==="action")}async getPreviousGetMoreItemsActionOverview(){let _=this.getExecutedActions(),g=_[_.length-1];if((g==null?void 0:g.eventCode)!=="get_more_items"||!this.lastReducedDOM)return{};try{return await this.pageInteractor.addMoreItemsToDom(this.lastReducedDOM.window.document.body,g.getMoreItemsId),{interruptionEvent:"didRequestMoreItemsEvent",payload:{promptData:{reducedHTML:this.lastReducedDOM.serialize()},getMoreItemsId:g.getMoreItemsId}}}catch{return{}}}getPreviousWaitActionOverview(){var C;let _=this.getExecutedActions();if(((C=_[_.length-1])==null?void 0:C.eventCode)!=="wait")return{};let g=0;return _.slice().reverse().every(P=>P.eventCode==="wait"?(g++,!0):!1,0),{payload:{waitCount:g}}}async initSession(){let{apiKey:_,goal:g,thoughts:C}=this;if(this.log("[AIFallback] Calling init session...",{appName:_,goal:g,thoughts:C}),!_){let M="Missing Checksum API key, will not run AI fallback";throw AVt(M),new Error(M)}if(this.mockServer){this.sessionId="mock-session-id";return}let P=this.getStackTrace();if(!P)throw new Error("Failed to get code trace");let F={type:this.fallbackData.type,resolveSmartAssertion:this.withChecksumAI,storyTitle:g,testSuiteId:this.testSuiteId,testId:this.testId,thoughtsAndActions:{previous:C.slice(0,Math.max(C.length-1,0)).map(M=>({thought:M})),failing:{thought:C[C.length-1]},next:[]},testFileName:this.testFile.split("/").pop()??"",codeTrace:P};try{let M=await fetch(`${this.getAPIBaseURL()}/init`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.apiKey},body:JSON.stringify({appName:_,data:F})});this.sessionId=await M.text(),this.log("[AIFallback] Session ID",this.sessionId)}catch(M){throw this.withChecksumAI&&M.message==="fetch failed"&&(this.checksumPage.step(hNe,async()=>{throw new Error(hNe)}),AVt(hNe)),this.log("[AIFallback] Error calling init session",M),M}}translateExecutedActionToFallbackAction(_){return{type:"action",esraMetadata:_.esraMetadata,generatedLocator:_.locator,selector:_.selector,parentFramesSelectors:_.parentFramesSelectors,method:this.getMethodForPotentialAction(_),thought:_.thought}}getMethodForPotentialAction(_){return{name:this.actionEventCodeToMethodName[_.eventCode],args:e(()=>{switch(_.eventCode){case"click":case"double_click":return[{position:_.clickOffset}];case"drag_and_drop":return[this.pageInteractor.makeLocator(_.dropTarget.selector,_.dropTarget.parentFramesSelectors)];case"input":case"click_and_type":case"clear_and_type":case"selectoption":case"keystroke":case"navigation":return[this.pageInteractor.getActionFillValue(_,!1)];case"upload_files":return _.files;default:return}},"makeArgs")()}}getAPIBaseURL(){return this.API_BASE_DOMAIN+this.API_BASE_ROUTE}getAnalyticsPayload(){return{fallbackType:"ai",error:this.errorMessage,thought:this.getFailedThought(),sessionId:this.sessionId,steps:this.stepsPayload.map(_=>JSON.stringify(_))}}getFailedThought(){return this.thoughts[this.thoughts.length-1]}toString(){return`Checksum AI ("${this.getFailedThought()}")`}};e(uzt,"AIFallback");var xNe=uzt;var Wae=require("fs");var egr=x7(ZWt());var Fhr=!1,t$t=class t$t{constructor(l,_,g,C){this.page=l;this.checksumPage=_;this.executeLocatorAction=g;this.base=C;this.LOCATORS_TIMEOUT=Fhr?9999999:5e3;this.HANDLES_TIMEOUT=Fhr?9999999:5e3;this.HANDLES_INTERVAL=300;this.locatorsChain=[];this.base||(this.base=this.page)}setBase(l){this.base=l}init(...l){return this.sanitizeArgs(...l),new Proxy(this,{get:e((_,g)=>g==="setBase"?function(...C){this.setBase(C[0])}.bind(this):this.handleLocatorChain(_,g),"get")})}getLocatorSelector(l){if(l)return l._selector}sanitizeArgs(...l){if(l.length===1&&typeof l[0]=="object"){if(!l[0].anchors||typeof l[0].anchors!="function")throw new Error("Invalid compound selector format. Object must contain anchors property with a method value");this.anchorLocatorMethod=l[0].anchors,this.targetLocatorMethod=l[0].target;return}if(typeof l[0]!="function")throw new Error("Invalid compound selector format. First argument must be an object or a function");if(this.anchorLocatorMethod=l[0],l.length===2){if(typeof l[1]!="function")throw new Error("Invalid compound selector format. Second argument must be a function");this.targetLocatorMethod=l[1]}}async resolveLocator(){if(this.resolvedLocator)return this.resolvedLocator;gT("Waiting for locators..");let l=this.getLocatorsFromMethods();try{await Promise.all(l.map(async M=>qL(M.first().waitFor({bypassChecksum:!0}),this.LOCATORS_TIMEOUT,"Waiting for compound selector locators timeout")))}catch(M){throw new Error(`Error while waiting for locators - ${M.message}`)}let _=await qL(this.getElementHandles(l),this.HANDLES_TIMEOUT);gT(`Resolved to ${e$t(_)} elements from ${l.length} locators`);let g=this.getLocatorSelector(this.getLocatorsFromMethods(!1,!0,this.page)[0]),C=await this.checksumPage.evaluateWithChecksum(async({handles:M,targetSelector:V})=>window.checksum.testGenerator.getCompoundSelector().select(M,V),{handles:_,targetSelector:g});if(!C||C.length===0)throw new Error("Could not generate selectors from handles");gT(`Resolved compound selector to ${C.length} selectors`);let P=this.getBase(),F=P.locator(C[0]);return C.slice(1,50).forEach(M=>{F=F.or(P.locator(M))}),this.locatorsChain.length&&this.locatorsChain.forEach(({name:M,args:V})=>{F=F[M](...V)}),gT(`Compound locator selector: ${this.getLocatorSelector(F)}`),this.resolvedLocator=F,F}handleLocatorChain(l,_){if(typeof _=="symbol")return;if(_==="constructor")return e(function(...F){return this[_](...F)},"Locator");if(_==="toString")return()=>this.toString();let g=e(()=>new Proxy(l,{get:e((P,F)=>P.handleLocatorChain(P,F),"get")}),"createLocatorProxy");return _==="valueOf"?e(function(){return g()},"Locator"):Object.values([...Object.values(Xet),...Object.values(Qet)]).includes(_)?e(function(...F){return l.locatorsChain.push({name:_,args:F}),g()},"Locator"):e(async function(...F){return this.handleAction(_,F)},"Locator").bind(this)}async handleAction(l,_){try{if(typeof l=="symbol")return;if(!this.anchorLocatorMethod)throw new Error("Compound selection is missing anchor locators");let g=await this.resolveLocator();return await this.executeLocatorAction(g,l,_)}catch(g){throw gT(`Failed to execute compound selection action: ${g}`),this.checksumPage.analytics.compoundSelectionFailure(g.toString(),this.toString()),g}}async getElementHandles(l){gT("Resolving compound selector elements");let _,g,C,P,F,M=e(()=>{F=2},"resetSameHandlesCount");do _=g,g=[],await Promise.all(l.map(async V=>{let W=await V.elementHandles({bypassChecksum:!0});if(W.length===0)throw new Error(`No elements found for locator: ${this.getLocatorSelector(V)}`);g.push(W)})),C=e$t(g),P=_?e$t(_):0,gT(`Handles itteration, previous: ${_?P:"-"}, current: ${C}`),P!==C&&M(),await WC(this.HANDLES_INTERVAL);while(!_||P!==C||--F>0);return g}getLocatorsFromMethods(l=!0,_=!0,g=this.getBase()){return(l?this.anchorLocatorMethod(g):[]).concat(_&&this.targetLocatorMethod?[this.targetLocatorMethod(g)]:[]).map(C=>typeof C=="string"?g.getByText(C):C)}getBase(){return this.base}toString(){var l;return`CompoundSelection(${this.resolvedLocator?this.getLocatorSelector(this.resolvedLocator):`${this.anchorLocatorMethod.toString()}, ${(l=this.targetLocatorMethod)==null?void 0:l.toString()})`})`}};e(t$t,"CompoundSelectorLocator");var KNt=t$t,e$t=e(p=>p.reduce((l,_)=>l+_.length,0),"countHandleElements");var r$t=class r$t extends yNe{constructor(){super(...arguments);this.timeout=5*1e3}init(_){return super.init(_),this}async resolve(_){try{let{method:g,args:C}=_,{checksumId:P}=this.data,F;try{let G=await this.getMetadataForTestId();if(!(P in G)||!G[P].compoundSelector)throw new Error(`No compound selection metadata found for id ${P}`);F=G[P].compoundSelector}catch(G){super.log("Could not read compound selector metadata file, ",G)}let M=await this.generateCompoundSelector(F);if(!(M!=null&&M.length))throw new Error("No compound locators found");let V=M[0],W=this.pageInteractor.makeLocator(V.selector),Q=F.targetSelection.featuresMetadata.tag,ae=["check","uncheck"].includes(g)&&Q!=="input"?"click":g;try{await this.checksumPage.wrapNoLocationSteps(async()=>this.execute(W,ae,C));let G={selector:V.selector,generatedLocator:V.locator,esraMetadata:void 0};return this.sendLog(G),this.checksumPage.addErrorMessage(_.error,`${this.thought?`"${this.thought}" auto-healed`:"Auto-healed"} using alternative selector "${V.selector}"`),{steps:[{type:"action",...G}]}}catch(G){throw new Error(`Failed to execute compound selection fallback action: ${G.message}`)}}catch(g){this.errorMessage=g.message,this.log(g.message);return}}async generateCompoundSelector(_){let g=await this.evaluateWithChecksum(async C=>{var F;return await((F=window.checksum)==null?void 0:F.testGenerator.getCompoundSelector().selectFromMetadata(C))},_);return super.log("Resolved compound selector fallback to",g),g}getAnalyticsPayload(){return{fallbackType:"compound-selector",...this.logPayload??{checksumId:this.data.checksumId,error:this.errorMessage}}}toString(){return`Checksum compound selector fallback (${this.data.checksumId})`}};e(r$t,"CompoundSelectorFallback");var EEt=r$t;var Ohr=x7(Ihr());var a$t=class a$t{constructor(l){this.toJSON=e(()=>this.data,"toJSON");this.data=l}getSimilar(l){let _=null,g=-1/0;for(let C of Object.keys(this.data)){let P=(0,Ohr.levenshtein)([...l],[...C]);P>g&&(g=P,_=C)}return _?this.data[_]:null}};e(a$t,"SimilarityRecord");var i$t=a$t,INe=class INe extends i$t{constructor(l){super(INe.preprocessRectangles(l))}getRectangleByTextAndSizeRanking(l,_){_=!_||!Number(_)?0:Number(_);let g=this.getSimilar(l);if(!g||g.length===0)return null;let C=Math.min(Math.max(_,0),g.length-1);return g[C]}};e(INe,"RectangleIndex"),INe.preprocessRectangles=e(l=>{let _=[...new Map([...l].map(C=>[JSON.stringify(C.vertices),C])).values()],g={};return _.forEach(C=>{g[C.text]||(g[C.text]=[]),g[C.text].push(C),g[C.text].sort((P,F)=>{let M=INe.calculateArea(P.vertices),V=INe.calculateArea(F.vertices);return M-V})}),g},"preprocessRectangles"),INe.calculateArea=e(l=>{let _=Math.abs(l[1].x-l[0].x),g=Math.abs(l[3].y-l[0].y);return _*g},"calculateArea");var XNt=INe;var qhr=require("fs"),Uhr=require("path");function wQ(p){return p._guid}e(wQ,"getPageOrFrameGuid");async function QNt(p,l,_){let g=p,C=g._mainFrame;try{g._mainFrame=l,await _(g)}finally{g._mainFrame=C}}e(QNt,"executeOnPageWithFrame");var Lhr={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html"},s$t={click:"click",fill:"input",click_and_type:"click_and_type",clear_and_type:"clear_and_type",double_click:"double_click",drag_and_drop:"drag_and_drop",hover:"hover",navigate:"navigation",keystroke:"keystroke",selectoption:"selectoption",upload_files:"upload_files",wait:"wait",get_more_items:"get_more_items",reset:void 0,save:void 0,fail:void 0,finish:void 0,dismiss_modal:void 0,vision_help:void 0,switch_tab:"switch_tab",expand_interactable_elements:void 0,approve_release:void 0,logout_and_login:"logout_and_login",canvas_click:"canvas_click",native_accept:"native_accept",native_dismiss:"native_dismiss"},Mhr=Object.fromEntries(Object.entries(s$t).map(p=>p.reverse())),o$t={goto:"navigation",click:"click",dblclick:"double_click",dragTo:"drag_and_drop",check:"check",uncheck:"uncheck",fill:"input",hover:"hover",selectOption:"selectoption",waitForTimeout:"wait","keyboard.press":"keystroke",setInputFiles:"upload_files",getPage:"switch_tab",reauthenticate:"logout_and_login",canvasClick:"canvas_click"},Rhr=Object.fromEntries(Object.entries(o$t).map(p=>p.reverse()));var Bhr={input:[1,2],selectoption:[1,2],keystroke:[1,2],wait:[1,2],navigation:[1,2],click:[0,1],double_click:[0,1],drag_and_drop:[1,2],upload_files:[1,2],canvas_click:[1,2],logout_and_login:[1],login:[1,2],click_and_type:[1,2],clear_and_type:[1,2],check:[0,1],uncheck:[0,1],hover:[0,1]},Ltt={input:1,selectoption:1,keystroke:1,wait:-1,navigation:1,click:0,double_click:0,drag_and_drop:1,upload_files:1,canvas_click:-1,logout_and_login:-1,login:1,click_and_type:0,clear_and_type:0,check:0,uncheck:0,hover:0,native_accept:-1,native_dismiss:-1};var Rsn=e(p=>p.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\${/g,"\\${"),"escapeStringForTemplateLiteral"),jhr="variableStore",ONe=jhr+".",Jhr=e((p,{alwaysIncludeInitializationLine:l=!1,onlyValueExpression:_=!1}={})=>[l?`const ${jhr} = {};`:"",...p.map(({name:C,value:P,valueExpression:F})=>{let M=typeof P=="string"&&!_?`\`${Rsn(P)}\``:F;return`${ONe}${C} = ${M};`})].join(`
1857
- `),"variablesToString");var Bsn=!0,_TestGenerationPageInteractor=class _TestGenerationPageInteractor{constructor(p,l,_,g,C,P,F){this.evaluateWithChecksum=p;this.getFrame=l;this.getTimeMachine=_;this.logger=g;this.options=C;this.pageInteractorAPI=P;this.loginFunction=F;this.activeDialog=null;this.newPagesIds=[];this.listeners={dialog:null,filechooser:null,page:null};this.listenToContextPage=e(()=>{this.getPage().context().on("page",p=>{this.newPagesIds.push(p._guid)})},"listenToContextPage");this.listenToFileChooser=e(()=>{this.listeners.filechooser=async p=>{this.logger.log("File chooser event detected"),this.fileChooser=p},this.getPage().on("filechooser",this.listeners.filechooser)},"listenToFileChooser");this.waitForDialog=e((p=!0,l=1e4)=>new Promise(_=>{let C=0,P=e(()=>{if(this.activeDialog){let F=this.activeDialog;p&&(this.activeDialog=null),_(F)}else C>=l?_(null):(C+=1e3,setTimeout(P,1e3))},"checkDialog");P()}),"waitForDialog");this.performFileUploadAction=e(async(p,l)=>{if(!await p.evaluate(g=>g.tagName==="INPUT"&&g.getAttribute("type")==="file"))throw new Error("File upload action performed on non-file input element");let _=l.files.map(g=>(0,Uhr.join)(this.options.testAssetsDir,g)).filter(g=>(0,qhr.existsSync)(g)?!0:(this.logger.log(`Upload file not found: ${g}. Filtering out.`),!1));if(!_.length)throw new Error("No files to upload");await this.actionGuardReturn(p.setInputFiles(_),"Set input files timeout")},"performFileUploadAction");this.getSelectionDataForAction=e(async(p,l)=>p.checksumid?this.getSelectionDataForChecksumId(p.checksumid,l):p.position?await this.evaluateWithChecksum(async([_,g])=>window.checksum.testGenerator.getSelectorByPosition(_,g),[p.position.x,p.position.y]):p.selector?{selector:p.selector,locator:`locator("${p.selector}")`}:{selector:"",locator:""},"getSelectionDataForAction")}getPage(){return this.getFrame().page()}init(){this.listenToContextPage(),this.options.listenToFileChooser!==!1&&this.listenToFileChooser(),this.options.listenToDialog&&this.listenToDialog()}listenToDialog(){this.listeners.dialog=async p=>{this.activeDialog=p},this.getPage().on("dialog",this.listeners.dialog)}removeListener(p){try{switch(p){case"dialog":this.listeners.dialog&&(this.getPage().removeListener(p,this.listeners.dialog),this.listeners.dialog=null);break;case"filechooser":this.getPage().off(p,this.listeners.filechooser),this.listeners.filechooser=null;break;case"page":this.getPage().context().off(p,this.listeners.page),this.listeners.page=null;break}}catch(l){this.logger.logError(`Error removing listener: ${p}`,l)}}getOpenedFileChooser(){if(this.fileChooser){let p=this.fileChooser;return this.fileChooser=void 0,p}return null}async handleFileChooserEvent(p=[]){let l=this.getOpenedFileChooser();if(!l)return{};let _="fc_"+Math.random().toString(36).slice(2,4);return await this.evaluateWithChecksum(async([g,C])=>{window.checksum.testGenerator.addForceIncludeElement(C,g)},[_,l.element()]),{interruptionEvent:"fileUploadOpenedEvent",payload:{checksumid:_,customFiles:p}}}async addMoreItemsToDom(p,l){let _=p.querySelector(`[checksum-get-more-items='${l}']`);if(!_)throw new Error("Get more items root not found");let{items:g,hasMoreItems:C}=await this.getMoreItemsForTemplate(l);_.innerHTML=_.innerHTML+g,C||_.removeAttribute("checksum-get-more-items")}async getPageInfo(p){let l=wQ(p);return{id:l,url:p.url(),title:await p.title(),new:this.newPagesIds.includes(l),active:l===wQ(this.getPage())}}async getTabsInfo(){var g;let p=this.getPage(),l=await Promise.all(p.context().pages().map(C=>this.getPageInfo(C))),_=(g=this.getTimeMachine())==null?void 0:g.getPage();return _&&_!==p&&(l=l.filter(C=>C.id!==wQ(_))),this.newPagesIds=[],l}async getSelectionDataFromSelectorGenerator(p,l,_={}){if(_={useCompoundSelector:!0,useCSSExtraction:!0,useVariables:!0,useArbitrarySelector:!0,..._},!p||!DVt(w_r(l.action.type))||!l.action.checksumid)return{};let g=await p.generateSelectionForAction(l,_);return g?{locator:`locator("${g.selector}")`,...g}:{}}async translateActionResponseToAgentPotentialAction(p,l=void 0,{pageId:_,makeStaticMetadataForESRA:g}={}){let C=structuredClone(p.actionHiddenOverride??p.action),{selector:P,selectorWithVars:F,locator:M,locatorWithVars:V,clickOffset:W,selectOptionValue:Q,compoundSelector:ae,alternateLocators:G,parentFramesSelectors:_e}={...await this.getSelectionDataForAction(C,p.actionHiddenOverride),...await this.getSelectionDataFromSelectorGenerator(l,p)},ne=await this.getESRAForSelector(P,_e,g);if(!ne&&P&&this.logger.logError("Error getting ESRA metadata"),(ne==null?void 0:ne.tag)==="select")switch(this.getActionEventCode(C.type)){case"input":C.type="selectoption";break;case"click":Q&&(C.type="selectoption",C.value=Q);break}let ue={eventCode:this.getActionEventCode(C.type),selector:P,selectorWithVars:F,parentFramesSelectors:_e,locator:M,locatorWithVars:V,clickOffset:W,pageId:_,compoundSelector:ae,alternateLocators:G,fillValue:C.value,fillValueName:C.valueName?`${ONe}${C.valueName}`:"",variables:p.variables,getMoreItemsId:C.getMoreItemsId,esraMetadata:ne,thought:p.thought,userRole:C.userRole,canvas:C.canvas,id:C.id};switch(ue.eventCode){case"drag_and_drop":{let{selector:qe,selectorWithVars:Xe,locator:rt,locatorWithVars:Tt,parentFramesSelectors:Nt}={...await this.getSelectionDataForAction({type:p.action.type,checksumid:p.action.dropTargetChecksumid}),...await this.getSelectionDataFromSelectorGenerator(l,{...p,action:{type:p.action.type,checksumid:p.action.dropTargetChecksumid}},{useCompoundSelector:!1})};ue.dropTarget={selector:qe,locator:rt,parentFramesSelectors:Nt,esraMetadata:await this.getESRAForSelector(qe,Nt,g)}}break;case"upload_files":ue.files=this.mapFileMIMETypeToFilename(C.files);break;case"switch_tab":{let qe=this.getPage();ue.switchToTab={id:C.tabId,index:qe.context().pages().findIndex(Xe=>wQ(Xe)===C.tabId)};break}case"keystroke":ue.fillValue=C.value}return ue}async reauthenticate(p,l){let _=this.getPage();this.loginFunction&&(await Promise.all([_.context().clearCookies(),_.evaluate(()=>localStorage.clear())]),await this.loginFunction(l??_,{role:p}))}mapFileMIMETypeToFilename(p){return p.map(l=>{if(l.fileName)return l.fileName;switch(l.mimeType){case"image/png":return"image_200x200.png";case"image/jpeg":return"image_200x200.jpg";case"application/pdf":return"document.pdf";case"text/csv":return"data.csv";default:return"file.txt"}})}async performAction(p,{useLocator:l=!1,handleActionFailed:_,monitorFlashingHTML:g=!0,timeout:C,allowForceClick:P=!0}={}){try{if(p.executed){this.logger.log("[performAction] Action marked as executed, skipping...");return}let F=l?!!p.locator:!!p.selector;if(DVt(p.eventCode)&&!F)throw new Error("No selector provided for action. Try changing app rules preMapReducedHTMLSelectors to true");g&&(this.logger.log("starting flashing elements detection"),await this.evaluateWithChecksum(async()=>window.checksum.testGenerator.startFlashingElementsDetection())),this.logger.log(`Performing action: ${p.eventCode}. Selector: ${p.selector}, Position: ${p.clickOffset}, Parent frame: ${p.parentFramesSelectors}`);let M=e(()=>l?this.makeLocatorFromLocator(p.locator):this.makeLocator(p.selector,p.parentFramesSelectors),"getLocator"),V=e(async(W,Q,ae={})=>this.actionGuardReturn(W,Q,{timeout:C,...ae}),"performWithActionGuard");switch(p.eventCode){case"click":try{await V(M().click({position:p.clickOffset,timeout:C??this.options.actionTimeout}),"Click timeout")}catch(W){if(!P)throw W;this.logger.log("Error performing click, will attempt a force click",W.message),p.force=!0,await V(M().click({position:p.clickOffset,force:!0,timeout:C??this.options.actionTimeout}),"Force Click timeout")}break;case"double_click":try{await V(M().dblclick({position:p.clickOffset,timeout:C??this.options.actionTimeout}),"DoubleClick timeout")}catch(W){if(!P)throw W;this.logger.log("Error performing double click, will attempt a force double click",W),p.force=!0,await V(M().dblclick({position:p.clickOffset,timeout:C??this.options.actionTimeout,force:!0}),"Force DoubleClick timeout")}break;case"check":await V(M().check({timeout:C??this.options.actionTimeout}),"Check timeout");break;case"uncheck":await V(M().uncheck({timeout:C??this.options.actionTimeout}),"UnCheck timeout");break;case"drag_and_drop":await V(M().dragTo(l?this.makeLocatorFromLocator(p.dropTarget.locator):this.makeLocator(p.dropTarget.selector,p.dropTarget.parentFramesSelectors),{timeout:C??this.options.actionTimeout}),"DragAndDrop timeout");break;case"input":await V(M().fill(this.getActionFillValue(p),{timeout:C??this.options.actionTimeout}),"Fill timeout");break;case"click_and_type":await qL(M().click({position:p.clickOffset,timeout:C??this.options.actionTimeout}),1e4,"Click before type timeout"),await qL(M().pressSequentially(this.getActionFillValue(p),{timeout:C??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"clear_and_type":await qL(M().clear({timeout:C??this.options.actionTimeout}),1e4,"Clear before type timeout"),await qL(M().pressSequentially(this.getActionFillValue(p),{timeout:C??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"selectoption":await V(M().selectOption(this.getActionFillValue(p),{timeout:C??this.options.actionTimeout}),"SelectOption timeout");break;case"hover":await V(M().hover({timeout:C??this.options.actionTimeout}),"Hover timeout");break;case"navigation":await V(this.getFrame().goto(p.fillValue,{timeout:C??this.options.navigationTimeout}),"Navigation timeout",{isNavigation:!0});break;case"keystroke":{let W=this.getPage();await V(W.keyboard.press(p.fillValue),"Keystroke timeout");break}case"upload_files":await this.performFileUploadAction(M(),p);break;case"wait":await WC(this.options.waitActionDelay??1e3);break;case"custom_code":await QNt(this.getPage(),this.getFrame(),async W=>{let Q=`async (page) => {${p.fillValue}}`;await(0,eval)(Q)(W)});break;case"logout_and_login":await this.reauthenticate(p.userRole);break;case"canvas_click":await this.canvasClick(M(),p.canvas);break}}catch(F){throw this.logger.log(`Error performing action: ${p.eventCode}, will attempt a correction template`,F),await(_==null?void 0:_()),F}this.logger.log(`Successfully performed action ${p.eventCode} with description "${p.thought}"`)}async getTextDetection(p){return new XNt(await this.pageInteractorAPI.getTextDetection(p))}async canvasClick(p,l){try{if(!await p.evaluate(P=>P.tagName.toLowerCase()==="canvas"))throw new Error("Click attempted on a non-canvas element");let C=(await this.getTextDetection(await p.screenshot())).getRectangleByTextAndSizeRanking(l.canvasText,l.rectSizeIndex);if(!C)throw new Error(`Canvas click target not found for ${l.canvasText}`);this.logger.log(`Canvas click target: ${C}`),await this.actionGuardReturn(p.click({position:C.center}),"Canvas click could not be performed")}catch(_){throw this.logger.logError("Canvas click:",_.message),new Error("Canvas click action failed")}}getActionFillValue(p,l=!0){let _=p.fillValue;if(!_){let g=p.selector.match(/(?<=value.*)('|").*/);g&&(_=g[0].slice(1,-1))}return typeof _!="string"&&(_="X"),l&&(p.fillValue=_),_}actionGuardReturn(p,l,{isNavigation:_=!1,timeout:g}={}){return qL(p,g??(_?this.options.navigationTimeout:this.options.actionTimeout),l)}makeLocator(p,l=[]){return PVt(this.getFrame(),p,l)}makeLocatorFromLocator(locator){return eval("this.getFrame()."+locator)}getCurrentURL(){return this.getFrame().url()}async getSelectionDataForChecksumId(p,l){if(l!=null&&l.selector)return{...l,selector:l.selector,locator:l.locator,clickOffset:l.position};if(!p)return this.logger.log(`[getSelectionDataForChecksumId] checksumid not provided (${p})`),{...l,selector:p,locator:`locator("${p}")`};let _=await this.evaluateWithChecksum(async g=>{let{selector:C,locator:P,clickOffset:F,parentFramesSelectors:M,invalid:V,rrwebId:W}=await window.checksum.testGenerator.getSelectorForChecksumId(g),Q=await window.checksum.testGenerator.getElementForChecksumId(g),ae=Q instanceof HTMLOptionElement&&Q.value?Q.value:void 0;return{selector:C,locator:P,clickOffset:F,selectOptionValue:ae,parentFramesSelectors:M,invalid:V,rrwebId:W}},p);if(Bsn&&_.invalid&&_.rrwebId){this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${p}. Trying to use time machine...`);try{let g=await this.getSelectionDataForRRwebIdAtReduceHTMLTime(_.rrwebId);_={..._,...g}}catch{this.logger.log(`[getSelectionDataForChecksumId] error using time machine to get selector for checksumid: ${p}`)}this.logger.log(`[getSelectionDataForChecksumId] got selector: ${_.selector} for checksumid: ${p} from time machine`)}return _!=null&&_.selector||this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${p}. If checksumid is correct, try to change app rules preMapReducedHTMLSelectors to true`),_}async getSelectionDataForRRwebIdAtReduceHTMLTime(p){if(!this.rrwebEventAtLastReducedHTML)return;let l=this.getTimeMachine();if(l)return l.executeTask(_=>_.evaluate(async({rrwebId:g})=>await window.checksum.testGenerator.getInspectedElementSelectionResultByRRwebId(g,{ignoredIframesSelectors:[".replayer-wrapper > iframe"],fromTimeMachine:!0}),{rrwebId:p}),this.rrwebEventAtLastReducedHTML.timestamp,{name:"getSelectionDataForRRwebIdAtReduceHTMLTime"})}async getESRAForSelector(p,l,_){let g=await this.evaluateWithChecksum(async({selector:C,parentFramesSelectors:P})=>window.checksum.testGenerator.getSelectionDataForSelector(C,P),{selector:p,parentFramesSelectors:l});return g!=null&&g.esraMetadata&&_&&(g.esraMetadata.staticMetadata=await _(g.esraMetadata,p)),g==null?void 0:g.esraMetadata}async getMoreItemsForTemplate(p){return await this.evaluateWithChecksum(async l=>window.checksum.testGenerator.getMoreItemsForTemplate(l,{}),p)??{items:"",hasMoreItems:!1}}async getCurrentReducedHTML({retriesLeft:p=3,retryWaitMS:l=2e3,initialChecksumId:_="0",extractESRAForInterpretationRequiredElements:g=!1,stopFlashingElementsDetection:C=!1,assignChecksumIdsToAllElements:P}={}){let F=new Date;this.logger.log("[getCurrentReducedHTML] Fetching reduced HTML...");try{let{reducedHTML:M,currentChecksumId:V,flashingHTML:W,elementsForNodeInterpretation:Q,lastRRwebEvent:ae}=await this.evaluateWithChecksum(async _e=>window.checksum.testGenerator.reduceHTML({},_e),{initialChecksumId:_,extractESRAForInterpretationRequiredElements:g,stopFlashingElementsDetection:C,assignChecksumIdsToAllElements:P}),G=new Date;return this.logger.log(`[getCurrentReducedHTML] Fetched reduced HTML in ${G.getTime()-F.getTime()}ms`),this.rrwebEventAtLastReducedHTML=ae,{reducedHTML:M,flashingHTML:W,elementsForNodeInterpretation:Q,currentChecksumId:V}}catch(M){if(p>0)return this.logger.logError(`[getCurrentReducedHTML] Error: ${M.message}`),this.logger.logError(`Failed do obtain reduced HTML, trying again in ${l/1e3} seconds, ${p-1} to go.`),await WC(l),this.getCurrentReducedHTML({retriesLeft:p-1,retryWaitMS:l});throw M}}getActionEventCode(p){return s$t[p]}};e(_TestGenerationPageInteractor,"TestGenerationPageInteractor");var Mtt=_TestGenerationPageInteractor;var _AlternateSelectorFallback=class _AlternateSelectorFallback extends yNe{constructor(){super(...arguments);this.timeout=5*1e3}init(l){return super.init(l),this}async resolve(params){var l;try{let{method,args}=params,{checksumId}=this.data,alternateLocators=[];try{let _=await this.getMetadataForTestId();if(!(checksumId in _)||!_[checksumId].alternateLocators)throw new Error(`No alternate selection metadata found for id ${checksumId}`);alternateLocators=_[checksumId].alternateLocators.locators}catch(_){throw super.log(`Could not read alternate selector metadata file, ${_.message}`),_}try{this.log("Resolving alternate selectors locators");let elementsMap=new Map;await Promise.all(alternateLocators.map(async locatorExpression=>{let locator=eval(B0e(locatorExpression,"this.page"));try{await qL(locator.first().waitFor({bypassChecksum:!0}),5e3),(await qL(locator.elementHandles({bypassChecksum:!0}),1e3)).forEach(g=>{elementsMap.has(g)?elementsMap.set(g,elementsMap.get(g)+1):elementsMap.set(g,1)})}catch(_){return}}));let majorityElementHandle=(l=Array.from(elementsMap.entries()))==null?void 0:l.reduce((_,g)=>_[1]>g[1]?_:g)[0];if(!majorityElementHandle)throw this.errorMessage="No alternate element found",new Error(this.errorMessage);let totalElements=Array.from(elementsMap.values()).reduce((_,g)=>_+g,0),elementSelector=await this.evaluateWithChecksum(async({element:_})=>window.playwright.selector(_),{element:majorityElementHandle});this.log(`Resolved alternate selector: ${elementSelector}' With majority vote of ${elementsMap.get(majorityElementHandle)} out of ${totalElements} elements`),await this.checksumPage.wrapNoLocationSteps(async()=>this.execute(this.page.locator(elementSelector),method,args));let fallbackResult={selector:elementSelector,generatedLocator:`locator("${elementSelector}")`,esraMetadata:void 0};return this.sendLog(fallbackResult),this.logPayload=this.logPayload.concat({mejorityVote:`${elementsMap.get(majorityElementHandle)}/${totalElements}`}),this.checksumPage.addErrorMessage(params.error,`${this.thought?`"${this.thought}" auto-healed`:"Auto-healed"} using alternative selector "${elementSelector}"`),{steps:[{type:"action",...fallbackResult}]}}catch(_){throw new Error(`Failed to execute compound selection fallback action: ${_.message}`)}}catch(_){this.errorMessage=_.message,this.log(this.errorMessage);return}}getAnalyticsPayload(){return{fallbackType:"alternative-selector",...this.logPayload??{checksumId:this.data.checksumId,error:this.errorMessage}}}toString(){return`Checksum alternative selector (${this.data.checksumId})`}};e(_AlternateSelectorFallback,"AlternateSelectorFallback");var AEt=_AlternateSelectorFallback;var p$t=class p$t{constructor(l){this.options=l}async handleError(l,_,g){let C=`Error in ${_} action during ${l} execution: ${g.message}`;throw new Error(C)}async guardedExecute(){try{return await(this.options.timeout!=null?qL(this.execute(),this.options.timeout,"Execution timeout"):this.execute())}catch(l){return this.handleError(this.options.method,this.constructor.name,l)}}};e(p$t,"Action");var eFt=p$t,f$t=class f$t extends eFt{async execute(){return this.options.method in this.options.locator?this.options.locator[this.options.method](...this.options.args):this.options.locator}};e(f$t,"PlaywrightAction");var c$t=f$t,_$t=class _$t extends eFt{constructor(_,g){super(_);this.pageInteractor=g}};e(_$t,"APIAction");var u$t=_$t,d$t=class d$t extends u$t{constructor(l,_){super(l,_.pageInteractor)}async execute(){try{let{locator:l,args:_}=this.options,[g,C]=_,P=await l.screenshot({timeout:3e4}),M=(await this.pageInteractor.getTextDetection(P)).getRectangleByTextAndSizeRanking(g,C);if(!M)throw new Error("No matching text found");await l.click({position:M.center})}catch(l){throw new Error(`Error in canvas click action: ${l.message}`)}}};e(d$t,"CanvasClickAction");var l$t=d$t,rFt=class rFt{static createAction(l,_){return l.method in this.customActionMap?new this.customActionMap[l.method]({...l,timeout:15e3},_):new c$t(l)}};e(rFt,"ActionFactory"),rFt.customActionMap={canvasClick:l$t};var tFt=rFt;var m$t=class m$t{constructor(l){this.options=l;this.health=e(async()=>await fetch(`${this.options.apiURL}/client-api/runtime/api/health`,{headers:{ChecksumAppCode:this.options.apiKey}}).catch(l=>(console.log(l),null)),"health");this.getCanvasDetection=e(async l=>{try{let _=l.toString("base64");return await(await fetch(`${this.options.apiURL}/client-api/runtime/vision/text-detection`,{body:JSON.stringify({imageBuffer:_}),method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.options.apiKey}})).json()}catch(_){return console.log(_),null}},"getCanvasDetection")}};e(m$t,"ChecksumClient");var Rtt=m$t;var h$t=class h$t{constructor(){this.config={}}};e(h$t,"PageInteractorAPI");var nFt=h$t;var g$t=class g$t extends nFt{constructor(_){super();this.config=_;this.getTextDetection=e(async _=>{let g=await this.api.getCanvasDetection(_);if(!g)throw new Error("No data returned from canvas detection");return g},"getTextDetection");this.config=_,this.api=new Rtt({apiKey:_.apiKey,apiURL:_.apiURL})}};e(g$t,"RuntimePageInteractorAPI");var Btt=g$t;var Vhr=require("path");var y$t=class y$t{constructor(l){this.options=l;this.navigatingFrames={};this.trackedFramesGuid=[];this.frameNavigationPromises={};this.onFrameNavigated=e(async l=>{let _=wQ(l);if(this.trackedFramesGuid.includes(_))return this.frameNavigationPromises[_]=new Promise(async g=>{await this.loadScript(l),g()}),this.frameNavigationPromises[_]},"onFrameNavigated");this.loadScript=e(async(l,{retriesLeft:_=3,retryWaitMS:g=2e3,useWrapper:C=!0}={})=>{var V,W;if(C&&this.scriptLoadWrapper)return this.scriptLoadWrapper(()=>this.loadScript(l,{retriesLeft:_,retryWaitMS:g,useWrapper:!1}),l);if(!this.addScriptTagOptions){console.warn("[InjectedScriptManager] addScriptTagOptions not set, skipping loadScript");return}if(this.isFrameClosed(l))return;let P=!1;try{P=this.scriptLoadCheck?await((V=this.scriptLoadCheck)==null?void 0:V.call(this,l)):!1}catch{}if(P||this.isFrameClosed(l))return;try{await l.addScriptTag(this.addScriptTagOptions)}catch(Q){if(_>0)return console.warn(`[InjectedScriptManager] Failed to add script to frame ${wQ(l)}, trying again in ${g/1e3} seconds, ${_-1} retries left.`,Q.message),await WC(g),this.loadScript(l,{retriesLeft:_-1,retryWaitMS:g,useWrapper:C});throw Q}let F=wQ(l),M=Date.now().toString(36)+Math.random().toString(36).substr(2);if(this.navigatingFrames[F]=M,this.options.scriptInitWait&&(console.log(`Waiting ${this.options.scriptInitWait}[ms] before onScriptLoad...`),await WC(this.options.scriptInitWait),console.log("Done waiting before onScriptLoad")),!this.isFrameClosed(l)){if(this.navigatingFrames[F]&&this.navigatingFrames[F]!==M)return console.log("Page navigated again, waiting on new promise..."),this.frameNavigationPromises[F];try{await((W=this.scriptLoadCallback)==null?void 0:W.call(this,l))}catch(Q){console.error("[WebDriver] onScriptLoad error",Q)}}},"loadScript");this.addScriptTagOptions=this.makeFrameInjectedScriptOptions()}setScriptLoadCallback(l){return this.scriptLoadCallback=l,this}setScriptLoadCheck(l){return this.scriptLoadCheck=l,this}setScriptLoadWrapper(l){return this.scriptLoadWrapper=l,this}async addTrackedFrame(l,_=!0){let g="mainFrame"in l?l.mainFrame():l,C=wQ(g);if(this.trackedFramesGuid.includes(C)||this.trackedFramesGuid.push(C),_)return this.onFrameNavigated(g)}getNavigationPromise(l){if(!l){console.warn("[InjectedScriptManager] getNavigationPromise called with undefined argument");return}let _=typeof l=="string"?l:"mainFrame"in l?wQ(l.mainFrame()):wQ(l);return this.frameNavigationPromises[_]}makeFrameInjectedScriptOptions(){switch(this.options.scriptSource){case"file":return this.options.scriptFile?{path:this.options.isScriptFileAbsolute?this.options.scriptFile:(0,Vhr.join)(process.cwd(),this.options.scriptFile)}:void 0;case"url":return this.options.scriptURL?{url:this.options.scriptURL}:void 0;default:return}}isFrameClosed(l){return l.isDetached()||l.page().isClosed()}};e(y$t,"InjectedScriptManager");var jtt=y$t;var mZe=x7(require("path")),S$t=require("fs");var eon=__dirname,Khr=mZe.join(__dirname,".."),ton=(0,S$t.existsSync)(Khr)?Khr:eon;Ghr().config({path:mZe.resolve(ton,".env")});var aFt=process.env.DEV_MODE==="true";function Xhr(){let p=__dirname;for(;!(0,S$t.existsSync)(mZe.join(p,"package.json"));)p=mZe.join(p,"..");return p}e(Xhr,"findRoot");var Yhr=mZe.join(Xhr(),"vtg-build","index.html"),XS={isDevMode:aFt,logLevel:process.env.LOG_LEVEL??"warnings",checksumScript:{source:aFt?"url":"file",url:process.env.SCRIPT_URL,path:Xhr()+"/checksumlib.js"},vtg:{writeLogFile:process.env.WRITE_LOG_FILE==="true",localBuildPath:Yhr,appURL:aFt?process.env.VTG_APP_URL:`file://${Yhr}`,useFakeStory:process.env.USE_FAKE_STORY==="true",recordEvents:process.env.RECORD_EVENTS==="true",fakeStory:{goal:process.env.FAKE_STORY_GOAL??"Send email via outreach list",instructions:process.env.FAKE_STORY_INSTRUCTIONS??"Make sure to select a user from the list first"},fakeTestGeneration:{internalTestId:process.env.FAKE_STORY_INTERNAL_TEST_ID??`tempID${Date.now().toString().slice(-5)}`,generationBatchId:process.env.FAKE_GENERATION_BATCH_ID??`tempID${Date.now().toString().slice(-5)}`},remoteDebugging:process.env.REMOTE_DEBUGGING==="true",taskTimeMachine:{showTaskTimeMachine:process.env.SHOW_TASK_TIME_MACHINE==="true",taskTimeout:parseInt(process.env.TASK_TIME_MACHINE_TIMEOUT??"240000")},aiAssertions:{disabled:process.env.AI_ASSERTIONS_DISABLED==="true",allowRefactoring:process.env.ALLOW_AI_ASSERTIONS_REFACTORING==="true"},aiLocators:{disabled:process.env.AI_LOCATORS_DISABLED==="true",useFakeAILocators:process.env.USE_FAKE_AI_LOCATORS==="true"}},testRun:{timeMachine:{active:!0,headless:!0},monitoring:{segment:{writeKey:process.env.MONITORING_SEGMENT_WRITE_KEY??"MfFJgdVFaFaD3NrBrgX3A9Blwfxs0pSD"}}},buildTime:process.env.BUILD_TIME??"unknown"};aFt&&console.log("Build",XS.buildTime);var T$t=class T$t{constructor(){this.frames={};this.pages=[];this.channels={};this.events=[]}register(l,_,g){if(this.frames[l])return;this.frames[l]=_;let C=_.page();this.pages.includes(C)||(this.pages.push(C),C.exposeFunction("checksumSendMessage",async(P,F)=>{let M=this.frames[P];if(!M)throw new Error(`Frame ${P} not found`);try{await M.evaluate(({message:V})=>{window.postMessage(V,"*")},{message:F})}catch{}}),C.exposeFunction("checksumSendBroadcastMessage",async(P,F)=>{let M=this.channels[P]??[];if(g){let V=require("fs"),W=require("path");this.events.push(...F),this.events.length%10===0&&V.writeFileSync(W.join(process.cwd(),"rrweb-player","events.json"),JSON.stringify(this.events))}M.forEach(async V=>{if(!(V.originFrameGuid&&V.originFrameGuid!==wQ(_)))try{V.handler?await V.handler(F):await _.evaluate(({message:W})=>{window.postMessage(W,"*")},{message:F})}catch{}})}),C.exposeFunction("checksumBringPageToFront",async P=>{let F=this.frames[P];F&&await F.page().bringToFront()}))}subscribeToChannel(l,_,{originFrame:g,handler:C}={}){var P;(P=this.channels)[l]??(P[l]=[]),this.channels[l].push({frame:_,originFrameGuid:g?wQ(g):void 0,handler:C})}unsubscribeFromChannel(l,_){var g;(g=this.channels)[l]??(g[l]=[]),this.channels[l]=this.channels[l].filter(C=>C.frame!==_)}};e(T$t,"FramesMsgBroker");var Jtt=T$t;var Zhr=require("@playwright/test");var PEt=require("jsdom");var D$t=class D$t{constructor(l){this.activeDOMType="checksumIds";this.rawReducedHTMLDom=new PEt.JSDOM(l),this.process()}process(){this.expandedChecksumIdsReducedDom=new PEt.JSDOM(this.rawReducedHTMLDom.serialize()),this.reducedHTMLDom=new PEt.JSDOM(this.rawReducedHTMLDom.serialize()),this.rrwebIdsReducedDom=new PEt.JSDOM(this.rawReducedHTMLDom.serialize());let l=e(F=>{F.window.document.body.querySelectorAll("[checksumid]:not([checksuminteractable])").forEach(V=>{V.removeAttribute("checksumid")})},"removeChecksumIdAttributeFromNonInteractable"),_=e((F,M)=>M.window.document.body.querySelectorAll(`[${F}]`).forEach(V=>V.removeAttribute(F)),"removeAttributeFromAllElements"),g=e(F=>_("checksuminteractable",F),"removeChecksumInteractableAttribute"),C=e(F=>_("checksumid",F),"removeChecksumIdAttribute"),P=e(F=>_("rrwebid",F),"removeRrwebIdAttribute");l(this.reducedHTMLDom),g(this.expandedChecksumIdsReducedDom),g(this.reducedHTMLDom),g(this.rrwebIdsReducedDom),P(this.expandedChecksumIdsReducedDom),P(this.reducedHTMLDom),C(this.rrwebIdsReducedDom)}getDOMForType(l){switch(l){default:case"checksumIds":return this.reducedHTMLDom;case"expandedChecksumIds":return this.expandedChecksumIdsReducedDom;case"rrwebIds":return this.rrwebIdsReducedDom}}async enrich(l){return await l(this.rawReducedHTMLDom),this.process(),this}setActiveDomType(l){this.activeDOMType=l}getActiveDom(){return this.getDOMForType(this.activeDOMType)}getActiveDOMString(){return this.getActiveDom().serialize()}getRrwebIdsReducedDomString(){return this.rrwebIdsReducedDom.serialize()}getDOMStringForType(l){return this.getDOMForType(l).serialize()}get raw(){return this.rawReducedHTMLDom}};e(D$t,"ReducedHTMLDOM");var NEt=D$t;var Qhr=x7(require("path"));var E$t=class E$t{constructor(l="all"){this.listeners=[];this.logLevel=l}log(...l){try{let g=new Error().stack.split(`
1856
+ `)}`)}async getReductionComponents(_){var g,C;return _.interruptionEvent==="didRequestMoreItemsEvent"?{reducedHTML:(C=(g=_.payload)==null?void 0:g.promptData)==null?void 0:C.reducedHTML,reducedDomHTMLElement:this.lastReducedDOM,flashingHTML:[],elementsForNodeInterpretation:[],currentChecksumId:this.currentChecksumId}:this.pageInteractor.getCurrentReducedHTML({stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:this.currentChecksumId})}getStackTrace(){try{return tNt.analyze(this.fallbackData.error.stack).toString()}catch(_){this.log("[AIFallback] Error getting stack trace",_);return}}async getPageScreenshot(){try{return(await this.page.screenshot({fullPage:!0})).toString("base64")}catch{return}}async iterate(){var g,C;this.hasPreviousActionFailed=!1;let _=this.CLIENT_MAX_ITERATIONS;do{if(this.didCancel)return!1;let P=await this.getPreviousActionOverview(),{reducedHTML:F,flashingHTML:M,elementsForNodeInterpretation:V,currentChecksumId:W}=await this.getReductionComponents(P),Q=await this.getPageScreenshot();this.lastReducedDOM=new bdr.JSDOM(F),this.currentChecksumId=W;let ae=await this.getNextAction({reducedHTML:F,flashingHTML:M,elementsForNodeInterpretation:V,previousActionOverview:P,screenshot:Q});if(this.didCancel)return!1;if(["failed","fail"].includes(ae.thought)||["failed","fail"].includes((g=ae.action)==null?void 0:g.type))return this.log("[AIFallback] Received failed signal, will quit"),this.errorMessage="Received failed signal",!1;if((ae.changedVariables??[]).forEach(({name:ne,value:ue})=>{this.checksumPage.variableStore.setVariable(ne,ue)}),this.fallbackData.type==="assertion"){let ne=ae.thought;this.log(`[AIFallback] for assertion returned with value: ${ae.action.value}, feedback: ${ne}`);let ue=["irrelevant","pass","soft_reject"].includes(ae.action.value);this.checksumPage.step(`AI: ${ne}`,async()=>{}),this.executedSteps.push({type:"assertion",feedback:ne,response:ae.action.value});let qe={feedback:ne,response:ae.action.value};return this.stepsPayload.push(qe),this.trace.aiFallbackStep(this.sessionId,qe),ue}if(ae.thought==="finish"||((C=ae.action)==null?void 0:C.type)==="finish")return this.log("[AIFallback] Received finish step"),!0;let _e=await this.pageInteractor.translateActionResponseToAgentPotentialAction(ae);try{try{await this.checksumPage.step(`AI: ${_e.thought}`,async()=>{await this.pageInteractor.performAction(_e)})}catch(ne){throw this.fallbackData.error=ne,new Error("Action failed")}this.hasPreviousActionFailed=!1,this.executedSteps.push({type:"action",..._e}),this.addActionStepPayload(ae,_e),await WC(1e3)}catch(ne){this.log("[AIFallback] Error while executing selector",ne.message),this.hasPreviousActionFailed=!0;continue}if(--_<=0){this.errorMessage="maximum repetition reached",this.log(`[AIFallback] ${this.errorMessage}`);break}}while(!0);return!1}addActionStepPayload(_,g){let{thought:C,action:{checksumid:P,type:F}}=_,{selector:M,locator:V,fillValue:W,getMoreItemsId:Q}=g,ae={thought:C,checksumid:P,type:F,selector:M,locator:V,fillValue:W,getMoreItemsId:Q};this.stepsPayload.push(ae),this.trace.aiFallbackStep(this.sessionId,ae)}async getNextAction({reducedHTML:_,flashingHTML:g,elementsForNodeInterpretation:C,previousActionOverview:P,screenshot:F,codeTrace:M}){let{apiKey:V}=this;if(this.mockServer)return this.finish?{thought:"finish"}:(--this.actionsCounter===0&&(this.finish=!0),{thought:"mock-thought",action:{type:"click",checksumid:"10"}});let W={reduction:{reducedHTML:_,flashingHTML:g,elementsForNodeInterpretation:C},currentURL:this.page.url(),previousActionOverview:P,resolvesSmartAssertion:this.withChecksumAI,variables:this.variables,screenshot:F};try{let ae=await(await fetch(`${this.getAPIBaseURL()}/iterate`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.apiKey},body:JSON.stringify({appName:V,sessionId:this.sessionId,iterationData:W})})).json();return this.log("[AIFallback] Received next action",ae),ae}catch(Q){throw this.log("[AIFallback] Error calling iterate",Q),Q}}async getPreviousActionOverview(){let _=await this.pageInteractor.handleFileChooserEvent();return{success:!this.hasPreviousActionFailed,...this.hasPreviousActionFailed?{failureEvent:"generalExecutionFailureError"}:{},...this.getPreviousWaitActionOverview(),..._,...await this.getPreviousGetMoreItemsActionOverview()}}getExecutedActions(){return this.executedSteps.filter(_=>_.type==="action")}async getPreviousGetMoreItemsActionOverview(){let _=this.getExecutedActions(),g=_[_.length-1];if((g==null?void 0:g.eventCode)!=="get_more_items"||!this.lastReducedDOM)return{};try{return await this.pageInteractor.addMoreItemsToDom(this.lastReducedDOM.window.document.body,g.getMoreItemsId),{interruptionEvent:"didRequestMoreItemsEvent",payload:{promptData:{reducedHTML:this.lastReducedDOM.serialize()},getMoreItemsId:g.getMoreItemsId}}}catch{return{}}}getPreviousWaitActionOverview(){var C;let _=this.getExecutedActions();if(((C=_[_.length-1])==null?void 0:C.eventCode)!=="wait")return{};let g=0;return _.slice().reverse().every(P=>P.eventCode==="wait"?(g++,!0):!1,0),{payload:{waitCount:g}}}async initSession(){let{apiKey:_,goal:g,thoughts:C}=this;if(this.log("[AIFallback] Calling init session...",{appName:_,goal:g,thoughts:C}),!_){let M="Missing Checksum API key, will not run AI fallback";throw AVt(M),new Error(M)}if(this.mockServer){this.sessionId="mock-session-id";return}let P=this.getStackTrace();if(!P)throw new Error("Failed to get code trace");let F={type:this.fallbackData.type,resolveSmartAssertion:this.withChecksumAI,storyTitle:g,testSuiteId:this.testSuiteId,testId:this.testId,thoughtsAndActions:{previous:C.slice(0,Math.max(C.length-1,0)).map(M=>({thought:M})),failing:{thought:C[C.length-1]},next:[]},testFileName:this.testFile.split("/").pop()??"",codeTrace:P};try{let M=await fetch(`${this.getAPIBaseURL()}/init`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.apiKey},body:JSON.stringify({appName:_,data:F})});this.sessionId=await M.text(),this.log("[AIFallback] Session ID",this.sessionId)}catch(M){throw this.withChecksumAI&&M.message==="fetch failed"&&(this.checksumPage.step(hNe,async()=>{throw new Error(hNe)}),AVt(hNe)),this.log("[AIFallback] Error calling init session",M),M}}translateExecutedActionToFallbackAction(_){return{type:"action",esraMetadata:_.esraMetadata,generatedLocator:_.locator,selector:_.selector,parentFramesSelectors:_.parentFramesSelectors,method:this.getMethodForPotentialAction(_),thought:_.thought}}getMethodForPotentialAction(_){return{name:this.actionEventCodeToMethodName[_.eventCode],args:e(()=>{switch(_.eventCode){case"click":case"double_click":return[{position:_.clickOffset}];case"drag_and_drop":return[this.pageInteractor.makeLocator(_.dropTarget.selector,_.dropTarget.parentFramesSelectors)];case"input":case"click_and_type":case"clear_and_type":case"selectoption":case"keystroke":case"navigation":return[this.pageInteractor.getActionFillValue(_,!1)];case"upload_files":return _.files;default:return}},"makeArgs")()}}getAPIBaseURL(){return this.API_BASE_DOMAIN+this.API_BASE_ROUTE}getAnalyticsPayload(){return{fallbackType:"ai",error:this.errorMessage,thought:this.getFailedThought(),sessionId:this.sessionId,steps:this.stepsPayload.map(_=>JSON.stringify(_))}}getFailedThought(){return this.thoughts[this.thoughts.length-1]}toString(){return`Checksum AI ("${this.getFailedThought()}")`}};e(uzt,"AIFallback");var xNe=uzt;var Wae=require("fs");var egr=x7(ZWt());var Fhr=!1,t$t=class t$t{constructor(l,_,g,C){this.page=l;this.checksumPage=_;this.executeLocatorAction=g;this.base=C;this.LOCATORS_TIMEOUT=Fhr?9999999:5e3;this.HANDLES_TIMEOUT=Fhr?9999999:5e3;this.HANDLES_INTERVAL=300;this.locatorsChain=[];this.base||(this.base=this.page)}setBase(l){this.base=l}init(...l){return this.sanitizeArgs(...l),new Proxy(this,{get:e((_,g)=>g==="setBase"?function(...C){this.setBase(C[0])}.bind(this):this.handleLocatorChain(_,g),"get")})}getLocatorSelector(l){if(l)return l._selector}sanitizeArgs(...l){if(l.length===1&&typeof l[0]=="object"){if(!l[0].anchors||typeof l[0].anchors!="function")throw new Error("Invalid compound selector format. Object must contain anchors property with a method value");this.anchorLocatorMethod=l[0].anchors,this.targetLocatorMethod=l[0].target;return}if(typeof l[0]!="function")throw new Error("Invalid compound selector format. First argument must be an object or a function");if(this.anchorLocatorMethod=l[0],l.length===2){if(typeof l[1]!="function")throw new Error("Invalid compound selector format. Second argument must be a function");this.targetLocatorMethod=l[1]}}async resolveLocator(){if(this.resolvedLocator)return this.resolvedLocator;gT("Waiting for locators..");let l=this.getLocatorsFromMethods();try{await Promise.all(l.map(async M=>qL(M.first().waitFor({bypassChecksum:!0}),this.LOCATORS_TIMEOUT,"Waiting for compound selector locators timeout")))}catch(M){throw new Error(`Error while waiting for locators - ${M.message}`)}let _=await qL(this.getElementHandles(l),this.HANDLES_TIMEOUT);gT(`Resolved to ${e$t(_)} elements from ${l.length} locators`);let g=this.getLocatorSelector(this.getLocatorsFromMethods(!1,!0,this.page)[0]),C=await this.checksumPage.evaluateWithChecksum(async({handles:M,targetSelector:V})=>window.checksum.testGenerator.getCompoundSelector().select(M,V),{handles:_,targetSelector:g});if(!C||C.length===0)throw new Error("Could not generate selectors from handles");gT(`Resolved compound selector to ${C.length} selectors`);let P=this.getBase(),F=P.locator(C[0]);return C.slice(1,50).forEach(M=>{F=F.or(P.locator(M))}),this.locatorsChain.length&&this.locatorsChain.forEach(({name:M,args:V})=>{F=F[M](...V)}),gT(`Compound locator selector: ${this.getLocatorSelector(F)}`),this.resolvedLocator=F,F}handleLocatorChain(l,_){if(typeof _=="symbol")return;if(_==="constructor")return e(function(...F){return this[_](...F)},"Locator");if(_==="toString")return()=>this.toString();let g=e(()=>new Proxy(l,{get:e((P,F)=>P.handleLocatorChain(P,F),"get")}),"createLocatorProxy");return _==="valueOf"?e(function(){return g()},"Locator"):Object.values([...Object.values(Xet),...Object.values(Qet)]).includes(_)?e(function(...F){return l.locatorsChain.push({name:_,args:F}),g()},"Locator"):e(async function(...F){return this.handleAction(_,F)},"Locator").bind(this)}async handleAction(l,_){try{if(typeof l=="symbol")return;if(!this.anchorLocatorMethod)throw new Error("Compound selection is missing anchor locators");let g=await this.resolveLocator();return await this.executeLocatorAction(g,l,_)}catch(g){throw gT(`Failed to execute compound selection action: ${g}`),this.checksumPage.analytics.compoundSelectionFailure(g.toString(),this.toString()),g}}async getElementHandles(l){gT("Resolving compound selector elements");let _,g,C,P,F,M=e(()=>{F=2},"resetSameHandlesCount");do _=g,g=[],await Promise.all(l.map(async V=>{let W=await V.elementHandles({bypassChecksum:!0});if(W.length===0)throw new Error(`No elements found for locator: ${this.getLocatorSelector(V)}`);g.push(W)})),C=e$t(g),P=_?e$t(_):0,gT(`Handles itteration, previous: ${_?P:"-"}, current: ${C}`),P!==C&&M(),await WC(this.HANDLES_INTERVAL);while(!_||P!==C||--F>0);return g}getLocatorsFromMethods(l=!0,_=!0,g=this.getBase()){return(l?this.anchorLocatorMethod(g):[]).concat(_&&this.targetLocatorMethod?[this.targetLocatorMethod(g)]:[]).map(C=>typeof C=="string"?g.getByText(C):C)}getBase(){return this.base}toString(){var l;return`CompoundSelection(${this.resolvedLocator?this.getLocatorSelector(this.resolvedLocator):`${this.anchorLocatorMethod.toString()}, ${(l=this.targetLocatorMethod)==null?void 0:l.toString()})`})`}};e(t$t,"CompoundSelectorLocator");var KNt=t$t,e$t=e(p=>p.reduce((l,_)=>l+_.length,0),"countHandleElements");var r$t=class r$t extends yNe{constructor(){super(...arguments);this.timeout=5*1e3}init(_){return super.init(_),this}async resolve(_){try{let{method:g,args:C}=_,{checksumId:P}=this.data,F;try{let G=await this.getMetadataForTestId();if(!(P in G)||!G[P].compoundSelector)throw new Error(`No compound selection metadata found for id ${P}`);F=G[P].compoundSelector}catch(G){super.log("Could not read compound selector metadata file, ",G)}let M=await this.generateCompoundSelector(F);if(!(M!=null&&M.length))throw new Error("No compound locators found");let V=M[0],W=this.pageInteractor.makeLocator(V.selector),Q=F.targetSelection.featuresMetadata.tag,ae=["check","uncheck"].includes(g)&&Q!=="input"?"click":g;try{await this.checksumPage.wrapNoLocationSteps(async()=>this.execute(W,ae,C));let G={selector:V.selector,generatedLocator:V.locator,esraMetadata:void 0};return this.sendLog(G),this.checksumPage.addErrorMessage(_.error,`${this.thought?`"${this.thought}" auto-recovered`:"Auto-recovered"} using alternative selector "${V.selector}"`),{steps:[{type:"action",...G}]}}catch(G){throw new Error(`Failed to execute compound selection fallback action: ${G.message}`)}}catch(g){this.errorMessage=g.message,this.log(g.message);return}}async generateCompoundSelector(_){let g=await this.evaluateWithChecksum(async C=>{var F;return await((F=window.checksum)==null?void 0:F.testGenerator.getCompoundSelector().selectFromMetadata(C))},_);return super.log("Resolved compound selector fallback to",g),g}getAnalyticsPayload(){return{fallbackType:"compound-selector",...this.logPayload??{checksumId:this.data.checksumId,error:this.errorMessage}}}toString(){return`Checksum compound selector fallback (${this.data.checksumId})`}};e(r$t,"CompoundSelectorFallback");var EEt=r$t;var Ohr=x7(Ihr());var a$t=class a$t{constructor(l){this.toJSON=e(()=>this.data,"toJSON");this.data=l}getSimilar(l){let _=null,g=-1/0;for(let C of Object.keys(this.data)){let P=(0,Ohr.levenshtein)([...l],[...C]);P>g&&(g=P,_=C)}return _?this.data[_]:null}};e(a$t,"SimilarityRecord");var i$t=a$t,INe=class INe extends i$t{constructor(l){super(INe.preprocessRectangles(l))}getRectangleByTextAndSizeRanking(l,_){_=!_||!Number(_)?0:Number(_);let g=this.getSimilar(l);if(!g||g.length===0)return null;let C=Math.min(Math.max(_,0),g.length-1);return g[C]}};e(INe,"RectangleIndex"),INe.preprocessRectangles=e(l=>{let _=[...new Map([...l].map(C=>[JSON.stringify(C.vertices),C])).values()],g={};return _.forEach(C=>{g[C.text]||(g[C.text]=[]),g[C.text].push(C),g[C.text].sort((P,F)=>{let M=INe.calculateArea(P.vertices),V=INe.calculateArea(F.vertices);return M-V})}),g},"preprocessRectangles"),INe.calculateArea=e(l=>{let _=Math.abs(l[1].x-l[0].x),g=Math.abs(l[3].y-l[0].y);return _*g},"calculateArea");var XNt=INe;var qhr=require("fs"),Uhr=require("path");function wQ(p){return p._guid}e(wQ,"getPageOrFrameGuid");async function QNt(p,l,_){let g=p,C=g._mainFrame;try{g._mainFrame=l,await _(g)}finally{g._mainFrame=C}}e(QNt,"executeOnPageWithFrame");var Lhr={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html"},s$t={click:"click",fill:"input",click_and_type:"click_and_type",clear_and_type:"clear_and_type",double_click:"double_click",drag_and_drop:"drag_and_drop",hover:"hover",navigate:"navigation",keystroke:"keystroke",selectoption:"selectoption",upload_files:"upload_files",wait:"wait",get_more_items:"get_more_items",reset:void 0,save:void 0,fail:void 0,finish:void 0,dismiss_modal:void 0,vision_help:void 0,switch_tab:"switch_tab",expand_interactable_elements:void 0,approve_release:void 0,logout_and_login:"logout_and_login",canvas_click:"canvas_click",native_accept:"native_accept",native_dismiss:"native_dismiss"},Mhr=Object.fromEntries(Object.entries(s$t).map(p=>p.reverse())),o$t={goto:"navigation",click:"click",dblclick:"double_click",dragTo:"drag_and_drop",check:"check",uncheck:"uncheck",fill:"input",hover:"hover",selectOption:"selectoption",waitForTimeout:"wait","keyboard.press":"keystroke",setInputFiles:"upload_files",getPage:"switch_tab",reauthenticate:"logout_and_login",canvasClick:"canvas_click"},Rhr=Object.fromEntries(Object.entries(o$t).map(p=>p.reverse()));var Bhr={input:[1,2],selectoption:[1,2],keystroke:[1,2],wait:[1,2],navigation:[1,2],click:[0,1],double_click:[0,1],drag_and_drop:[1,2],upload_files:[1,2],canvas_click:[1,2],logout_and_login:[1],login:[1,2],click_and_type:[1,2],clear_and_type:[1,2],check:[0,1],uncheck:[0,1],hover:[0,1]},Ltt={input:1,selectoption:1,keystroke:1,wait:-1,navigation:1,click:0,double_click:0,drag_and_drop:1,upload_files:1,canvas_click:-1,logout_and_login:-1,login:1,click_and_type:0,clear_and_type:0,check:0,uncheck:0,hover:0,native_accept:-1,native_dismiss:-1};var Rsn=e(p=>p.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\${/g,"\\${"),"escapeStringForTemplateLiteral"),jhr="variableStore",ONe=jhr+".",Jhr=e((p,{alwaysIncludeInitializationLine:l=!1,onlyValueExpression:_=!1}={})=>[l?`const ${jhr} = {};`:"",...p.map(({name:C,value:P,valueExpression:F})=>{let M=typeof P=="string"&&!_?`\`${Rsn(P)}\``:F;return`${ONe}${C} = ${M};`})].join(`
1857
+ `),"variablesToString");var Bsn=!0,_TestGenerationPageInteractor=class _TestGenerationPageInteractor{constructor(p,l,_,g,C,P,F){this.evaluateWithChecksum=p;this.getFrame=l;this.getTimeMachine=_;this.logger=g;this.options=C;this.pageInteractorAPI=P;this.loginFunction=F;this.activeDialog=null;this.newPagesIds=[];this.listeners={dialog:null,filechooser:null,page:null};this.listenToContextPage=e(()=>{this.getPage().context().on("page",p=>{this.newPagesIds.push(p._guid)})},"listenToContextPage");this.listenToFileChooser=e(()=>{this.listeners.filechooser=async p=>{this.logger.log("File chooser event detected"),this.fileChooser=p},this.getPage().on("filechooser",this.listeners.filechooser)},"listenToFileChooser");this.waitForDialog=e((p=!0,l=1e4)=>new Promise(_=>{let C=0,P=e(()=>{if(this.activeDialog){let F=this.activeDialog;p&&(this.activeDialog=null),_(F)}else C>=l?_(null):(C+=1e3,setTimeout(P,1e3))},"checkDialog");P()}),"waitForDialog");this.performFileUploadAction=e(async(p,l)=>{if(!await p.evaluate(g=>g.tagName==="INPUT"&&g.getAttribute("type")==="file"))throw new Error("File upload action performed on non-file input element");let _=l.files.map(g=>(0,Uhr.join)(this.options.testAssetsDir,g)).filter(g=>(0,qhr.existsSync)(g)?!0:(this.logger.log(`Upload file not found: ${g}. Filtering out.`),!1));if(!_.length)throw new Error("No files to upload");await this.actionGuardReturn(p.setInputFiles(_),"Set input files timeout")},"performFileUploadAction");this.getSelectionDataForAction=e(async(p,l)=>p.checksumid?this.getSelectionDataForChecksumId(p.checksumid,l):p.position?await this.evaluateWithChecksum(async([_,g])=>window.checksum.testGenerator.getSelectorByPosition(_,g),[p.position.x,p.position.y]):p.selector?{selector:p.selector,locator:`locator("${p.selector}")`}:{selector:"",locator:""},"getSelectionDataForAction")}getPage(){return this.getFrame().page()}init(){this.listenToContextPage(),this.options.listenToFileChooser!==!1&&this.listenToFileChooser(),this.options.listenToDialog&&this.listenToDialog()}listenToDialog(){this.listeners.dialog=async p=>{this.activeDialog=p},this.getPage().on("dialog",this.listeners.dialog)}removeListener(p){try{switch(p){case"dialog":this.listeners.dialog&&(this.getPage().removeListener(p,this.listeners.dialog),this.listeners.dialog=null);break;case"filechooser":this.getPage().off(p,this.listeners.filechooser),this.listeners.filechooser=null;break;case"page":this.getPage().context().off(p,this.listeners.page),this.listeners.page=null;break}}catch(l){this.logger.logError(`Error removing listener: ${p}`,l)}}getOpenedFileChooser(){if(this.fileChooser){let p=this.fileChooser;return this.fileChooser=void 0,p}return null}async handleFileChooserEvent(p=[]){let l=this.getOpenedFileChooser();if(!l)return{};let _="fc_"+Math.random().toString(36).slice(2,4);return await this.evaluateWithChecksum(async([g,C])=>{window.checksum.testGenerator.addForceIncludeElement(C,g)},[_,l.element()]),{interruptionEvent:"fileUploadOpenedEvent",payload:{checksumid:_,customFiles:p}}}async addMoreItemsToDom(p,l){let _=p.querySelector(`[checksum-get-more-items='${l}']`);if(!_)throw new Error("Get more items root not found");let{items:g,hasMoreItems:C}=await this.getMoreItemsForTemplate(l);_.innerHTML=_.innerHTML+g,C||_.removeAttribute("checksum-get-more-items")}async getPageInfo(p){let l=wQ(p);return{id:l,url:p.url(),title:await p.title(),new:this.newPagesIds.includes(l),active:l===wQ(this.getPage())}}async getTabsInfo(){var g;let p=this.getPage(),l=await Promise.all(p.context().pages().map(C=>this.getPageInfo(C))),_=(g=this.getTimeMachine())==null?void 0:g.getPage();return _&&_!==p&&(l=l.filter(C=>C.id!==wQ(_))),this.newPagesIds=[],l}async getSelectionDataFromSelectorGenerator(p,l,_={}){if(_={useCompoundSelector:!0,useCSSExtraction:!0,useVariables:!0,useArbitrarySelector:!0,..._},!p||!DVt(w_r(l.action.type))||!l.action.checksumid)return{};let g=await p.generateSelectionForAction(l,_);return g?{locator:`locator("${g.selector}")`,...g}:{}}async translateActionResponseToAgentPotentialAction(p,l=void 0,{pageId:_,makeStaticMetadataForESRA:g}={}){let C=structuredClone(p.actionHiddenOverride??p.action),{selector:P,selectorWithVars:F,locator:M,locatorWithVars:V,clickOffset:W,selectOptionValue:Q,compoundSelector:ae,alternateLocators:G,parentFramesSelectors:_e}={...await this.getSelectionDataForAction(C,p.actionHiddenOverride),...await this.getSelectionDataFromSelectorGenerator(l,p)},ne=await this.getESRAForSelector(P,_e,g);if(!ne&&P&&this.logger.logError("Error getting ESRA metadata"),(ne==null?void 0:ne.tag)==="select")switch(this.getActionEventCode(C.type)){case"input":C.type="selectoption";break;case"click":Q&&(C.type="selectoption",C.value=Q);break}let ue={eventCode:this.getActionEventCode(C.type),selector:P,selectorWithVars:F,parentFramesSelectors:_e,locator:M,locatorWithVars:V,clickOffset:W,pageId:_,compoundSelector:ae,alternateLocators:G,fillValue:C.value,fillValueName:C.valueName?`${ONe}${C.valueName}`:"",variables:p.variables,getMoreItemsId:C.getMoreItemsId,esraMetadata:ne,thought:p.thought,userRole:C.userRole,canvas:C.canvas,id:C.id};switch(ue.eventCode){case"drag_and_drop":{let{selector:qe,selectorWithVars:Xe,locator:rt,locatorWithVars:Tt,parentFramesSelectors:Nt}={...await this.getSelectionDataForAction({type:p.action.type,checksumid:p.action.dropTargetChecksumid}),...await this.getSelectionDataFromSelectorGenerator(l,{...p,action:{type:p.action.type,checksumid:p.action.dropTargetChecksumid}},{useCompoundSelector:!1})};ue.dropTarget={selector:qe,locator:rt,parentFramesSelectors:Nt,esraMetadata:await this.getESRAForSelector(qe,Nt,g)}}break;case"upload_files":ue.files=this.mapFileMIMETypeToFilename(C.files);break;case"switch_tab":{let qe=this.getPage();ue.switchToTab={id:C.tabId,index:qe.context().pages().findIndex(Xe=>wQ(Xe)===C.tabId)};break}case"keystroke":ue.fillValue=C.value}return ue}async reauthenticate(p,l){let _=this.getPage();this.loginFunction&&(await Promise.all([_.context().clearCookies(),_.evaluate(()=>localStorage.clear())]),await this.loginFunction(l??_,{role:p}))}mapFileMIMETypeToFilename(p){return p.map(l=>{if(l.fileName)return l.fileName;switch(l.mimeType){case"image/png":return"image_200x200.png";case"image/jpeg":return"image_200x200.jpg";case"application/pdf":return"document.pdf";case"text/csv":return"data.csv";default:return"file.txt"}})}async performAction(p,{useLocator:l=!1,handleActionFailed:_,monitorFlashingHTML:g=!0,timeout:C,allowForceClick:P=!0}={}){try{if(p.executed){this.logger.log("[performAction] Action marked as executed, skipping...");return}let F=l?!!p.locator:!!p.selector;if(DVt(p.eventCode)&&!F)throw new Error("No selector provided for action. Try changing app rules preMapReducedHTMLSelectors to true");g&&(this.logger.log("starting flashing elements detection"),await this.evaluateWithChecksum(async()=>window.checksum.testGenerator.startFlashingElementsDetection())),this.logger.log(`Performing action: ${p.eventCode}. Selector: ${p.selector}, Position: ${p.clickOffset}, Parent frame: ${p.parentFramesSelectors}`);let M=e(()=>l?this.makeLocatorFromLocator(p.locator):this.makeLocator(p.selector,p.parentFramesSelectors),"getLocator"),V=e(async(W,Q,ae={})=>this.actionGuardReturn(W,Q,{timeout:C,...ae}),"performWithActionGuard");switch(p.eventCode){case"click":try{await V(M().click({position:p.clickOffset,timeout:C??this.options.actionTimeout}),"Click timeout")}catch(W){if(!P)throw W;this.logger.log("Error performing click, will attempt a force click",W.message),p.force=!0,await V(M().click({position:p.clickOffset,force:!0,timeout:C??this.options.actionTimeout}),"Force Click timeout")}break;case"double_click":try{await V(M().dblclick({position:p.clickOffset,timeout:C??this.options.actionTimeout}),"DoubleClick timeout")}catch(W){if(!P)throw W;this.logger.log("Error performing double click, will attempt a force double click",W),p.force=!0,await V(M().dblclick({position:p.clickOffset,timeout:C??this.options.actionTimeout,force:!0}),"Force DoubleClick timeout")}break;case"check":await V(M().check({timeout:C??this.options.actionTimeout}),"Check timeout");break;case"uncheck":await V(M().uncheck({timeout:C??this.options.actionTimeout}),"UnCheck timeout");break;case"drag_and_drop":await V(M().dragTo(l?this.makeLocatorFromLocator(p.dropTarget.locator):this.makeLocator(p.dropTarget.selector,p.dropTarget.parentFramesSelectors),{timeout:C??this.options.actionTimeout}),"DragAndDrop timeout");break;case"input":await V(M().fill(this.getActionFillValue(p),{timeout:C??this.options.actionTimeout}),"Fill timeout");break;case"click_and_type":await qL(M().click({position:p.clickOffset,timeout:C??this.options.actionTimeout}),1e4,"Click before type timeout"),await qL(M().pressSequentially(this.getActionFillValue(p),{timeout:C??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"clear_and_type":await qL(M().clear({timeout:C??this.options.actionTimeout}),1e4,"Clear before type timeout"),await qL(M().pressSequentially(this.getActionFillValue(p),{timeout:C??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"selectoption":await V(M().selectOption(this.getActionFillValue(p),{timeout:C??this.options.actionTimeout}),"SelectOption timeout");break;case"hover":await V(M().hover({timeout:C??this.options.actionTimeout}),"Hover timeout");break;case"navigation":await V(this.getFrame().goto(p.fillValue,{timeout:C??this.options.navigationTimeout}),"Navigation timeout",{isNavigation:!0});break;case"keystroke":{let W=this.getPage();await V(W.keyboard.press(p.fillValue),"Keystroke timeout");break}case"upload_files":await this.performFileUploadAction(M(),p);break;case"wait":await WC(this.options.waitActionDelay??1e3);break;case"custom_code":await QNt(this.getPage(),this.getFrame(),async W=>{let Q=`async (page) => {${p.fillValue}}`;await(0,eval)(Q)(W)});break;case"logout_and_login":await this.reauthenticate(p.userRole);break;case"canvas_click":await this.canvasClick(M(),p.canvas);break}}catch(F){throw this.logger.log(`Error performing action: ${p.eventCode}, will attempt a correction template`,F),await(_==null?void 0:_()),F}this.logger.log(`Successfully performed action ${p.eventCode} with description "${p.thought}"`)}async getTextDetection(p){return new XNt(await this.pageInteractorAPI.getTextDetection(p))}async canvasClick(p,l){try{if(!await p.evaluate(P=>P.tagName.toLowerCase()==="canvas"))throw new Error("Click attempted on a non-canvas element");let C=(await this.getTextDetection(await p.screenshot())).getRectangleByTextAndSizeRanking(l.canvasText,l.rectSizeIndex);if(!C)throw new Error(`Canvas click target not found for ${l.canvasText}`);this.logger.log(`Canvas click target: ${C}`),await this.actionGuardReturn(p.click({position:C.center}),"Canvas click could not be performed")}catch(_){throw this.logger.logError("Canvas click:",_.message),new Error("Canvas click action failed")}}getActionFillValue(p,l=!0){let _=p.fillValue;if(!_){let g=p.selector.match(/(?<=value.*)('|").*/);g&&(_=g[0].slice(1,-1))}return typeof _!="string"&&(_="X"),l&&(p.fillValue=_),_}actionGuardReturn(p,l,{isNavigation:_=!1,timeout:g}={}){return qL(p,g??(_?this.options.navigationTimeout:this.options.actionTimeout),l)}makeLocator(p,l=[]){return PVt(this.getFrame(),p,l)}makeLocatorFromLocator(locator){return eval("this.getFrame()."+locator)}getCurrentURL(){return this.getFrame().url()}async getSelectionDataForChecksumId(p,l){if(l!=null&&l.selector)return{...l,selector:l.selector,locator:l.locator,clickOffset:l.position};if(!p)return this.logger.log(`[getSelectionDataForChecksumId] checksumid not provided (${p})`),{...l,selector:p,locator:`locator("${p}")`};let _=await this.evaluateWithChecksum(async g=>{let{selector:C,locator:P,clickOffset:F,parentFramesSelectors:M,invalid:V,rrwebId:W}=await window.checksum.testGenerator.getSelectorForChecksumId(g),Q=await window.checksum.testGenerator.getElementForChecksumId(g),ae=Q instanceof HTMLOptionElement&&Q.value?Q.value:void 0;return{selector:C,locator:P,clickOffset:F,selectOptionValue:ae,parentFramesSelectors:M,invalid:V,rrwebId:W}},p);if(Bsn&&_.invalid&&_.rrwebId){this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${p}. Trying to use time machine...`);try{let g=await this.getSelectionDataForRRwebIdAtReduceHTMLTime(_.rrwebId);_={..._,...g}}catch{this.logger.log(`[getSelectionDataForChecksumId] error using time machine to get selector for checksumid: ${p}`)}this.logger.log(`[getSelectionDataForChecksumId] got selector: ${_.selector} for checksumid: ${p} from time machine`)}return _!=null&&_.selector||this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${p}. If checksumid is correct, try to change app rules preMapReducedHTMLSelectors to true`),_}async getSelectionDataForRRwebIdAtReduceHTMLTime(p){if(!this.rrwebEventAtLastReducedHTML)return;let l=this.getTimeMachine();if(l)return l.executeTask(_=>_.evaluate(async({rrwebId:g})=>await window.checksum.testGenerator.getInspectedElementSelectionResultByRRwebId(g,{ignoredIframesSelectors:[".replayer-wrapper > iframe"],fromTimeMachine:!0}),{rrwebId:p}),this.rrwebEventAtLastReducedHTML.timestamp,{name:"getSelectionDataForRRwebIdAtReduceHTMLTime"})}async getESRAForSelector(p,l,_){let g=await this.evaluateWithChecksum(async({selector:C,parentFramesSelectors:P})=>window.checksum.testGenerator.getSelectionDataForSelector(C,P),{selector:p,parentFramesSelectors:l});return g!=null&&g.esraMetadata&&_&&(g.esraMetadata.staticMetadata=await _(g.esraMetadata,p)),g==null?void 0:g.esraMetadata}async getMoreItemsForTemplate(p){return await this.evaluateWithChecksum(async l=>window.checksum.testGenerator.getMoreItemsForTemplate(l,{}),p)??{items:"",hasMoreItems:!1}}async getCurrentReducedHTML({retriesLeft:p=3,retryWaitMS:l=2e3,initialChecksumId:_="0",extractESRAForInterpretationRequiredElements:g=!1,stopFlashingElementsDetection:C=!1,assignChecksumIdsToAllElements:P}={}){let F=new Date;this.logger.log("[getCurrentReducedHTML] Fetching reduced HTML...");try{let{reducedHTML:M,currentChecksumId:V,flashingHTML:W,elementsForNodeInterpretation:Q,lastRRwebEvent:ae}=await this.evaluateWithChecksum(async _e=>window.checksum.testGenerator.reduceHTML({},_e),{initialChecksumId:_,extractESRAForInterpretationRequiredElements:g,stopFlashingElementsDetection:C,assignChecksumIdsToAllElements:P}),G=new Date;return this.logger.log(`[getCurrentReducedHTML] Fetched reduced HTML in ${G.getTime()-F.getTime()}ms`),this.rrwebEventAtLastReducedHTML=ae,{reducedHTML:M,flashingHTML:W,elementsForNodeInterpretation:Q,currentChecksumId:V}}catch(M){if(p>0)return this.logger.logError(`[getCurrentReducedHTML] Error: ${M.message}`),this.logger.logError(`Failed do obtain reduced HTML, trying again in ${l/1e3} seconds, ${p-1} to go.`),await WC(l),this.getCurrentReducedHTML({retriesLeft:p-1,retryWaitMS:l});throw M}}getActionEventCode(p){return s$t[p]}};e(_TestGenerationPageInteractor,"TestGenerationPageInteractor");var Mtt=_TestGenerationPageInteractor;var _AlternateSelectorFallback=class _AlternateSelectorFallback extends yNe{constructor(){super(...arguments);this.timeout=5*1e3}init(l){return super.init(l),this}async resolve(params){var l;try{let{method,args}=params,{checksumId}=this.data,alternateLocators=[];try{let _=await this.getMetadataForTestId();if(!(checksumId in _)||!_[checksumId].alternateLocators)throw new Error(`No alternate selection metadata found for id ${checksumId}`);alternateLocators=_[checksumId].alternateLocators.locators}catch(_){throw super.log(`Could not read alternate selector metadata file, ${_.message}`),_}try{this.log("Resolving alternate selectors locators");let elementsMap=new Map;await Promise.all(alternateLocators.map(async locatorExpression=>{let locator=eval(B0e(locatorExpression,"this.page"));try{await qL(locator.first().waitFor({bypassChecksum:!0}),5e3),(await qL(locator.elementHandles({bypassChecksum:!0}),1e3)).forEach(g=>{elementsMap.has(g)?elementsMap.set(g,elementsMap.get(g)+1):elementsMap.set(g,1)})}catch(_){return}}));let majorityElementHandle=(l=Array.from(elementsMap.entries()))==null?void 0:l.reduce((_,g)=>_[1]>g[1]?_:g)[0];if(!majorityElementHandle)throw this.errorMessage="No alternate element found",new Error(this.errorMessage);let totalElements=Array.from(elementsMap.values()).reduce((_,g)=>_+g,0),elementSelector=await this.evaluateWithChecksum(async({element:_})=>window.playwright.selector(_),{element:majorityElementHandle});this.log(`Resolved alternate selector: ${elementSelector}' With majority vote of ${elementsMap.get(majorityElementHandle)} out of ${totalElements} elements`),await this.checksumPage.wrapNoLocationSteps(async()=>this.execute(this.page.locator(elementSelector),method,args));let fallbackResult={selector:elementSelector,generatedLocator:`locator("${elementSelector}")`,esraMetadata:void 0};return this.sendLog(fallbackResult),this.logPayload=this.logPayload.concat({mejorityVote:`${elementsMap.get(majorityElementHandle)}/${totalElements}`}),this.checksumPage.addErrorMessage(params.error,`${this.thought?`"${this.thought}" auto-recovered`:"Auto-recovered"} using alternative selector "${elementSelector}"`),{steps:[{type:"action",...fallbackResult}]}}catch(_){throw new Error(`Failed to execute compound selection fallback action: ${_.message}`)}}catch(_){this.errorMessage=_.message,this.log(this.errorMessage);return}}getAnalyticsPayload(){return{fallbackType:"alternative-selector",...this.logPayload??{checksumId:this.data.checksumId,error:this.errorMessage}}}toString(){return`Checksum alternative selector (${this.data.checksumId})`}};e(_AlternateSelectorFallback,"AlternateSelectorFallback");var AEt=_AlternateSelectorFallback;var p$t=class p$t{constructor(l){this.options=l}async handleError(l,_,g){let C=`Error in ${_} action during ${l} execution: ${g.message}`;throw new Error(C)}async guardedExecute(){try{return await(this.options.timeout!=null?qL(this.execute(),this.options.timeout,"Execution timeout"):this.execute())}catch(l){return this.handleError(this.options.method,this.constructor.name,l)}}};e(p$t,"Action");var eFt=p$t,f$t=class f$t extends eFt{async execute(){return this.options.method in this.options.locator?this.options.locator[this.options.method](...this.options.args):this.options.locator}};e(f$t,"PlaywrightAction");var c$t=f$t,_$t=class _$t extends eFt{constructor(_,g){super(_);this.pageInteractor=g}};e(_$t,"APIAction");var u$t=_$t,d$t=class d$t extends u$t{constructor(l,_){super(l,_.pageInteractor)}async execute(){try{let{locator:l,args:_}=this.options,[g,C]=_,P=await l.screenshot({timeout:3e4}),M=(await this.pageInteractor.getTextDetection(P)).getRectangleByTextAndSizeRanking(g,C);if(!M)throw new Error("No matching text found");await l.click({position:M.center})}catch(l){throw new Error(`Error in canvas click action: ${l.message}`)}}};e(d$t,"CanvasClickAction");var l$t=d$t,rFt=class rFt{static createAction(l,_){return l.method in this.customActionMap?new this.customActionMap[l.method]({...l,timeout:15e3},_):new c$t(l)}};e(rFt,"ActionFactory"),rFt.customActionMap={canvasClick:l$t};var tFt=rFt;var m$t=class m$t{constructor(l){this.options=l;this.health=e(async()=>await fetch(`${this.options.apiURL}/client-api/runtime/api/health`,{headers:{ChecksumAppCode:this.options.apiKey}}).catch(l=>(console.log(l),null)),"health");this.getCanvasDetection=e(async l=>{try{let _=l.toString("base64");return await(await fetch(`${this.options.apiURL}/client-api/runtime/vision/text-detection`,{body:JSON.stringify({imageBuffer:_}),method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.options.apiKey}})).json()}catch(_){return console.log(_),null}},"getCanvasDetection")}};e(m$t,"ChecksumClient");var Rtt=m$t;var h$t=class h$t{constructor(){this.config={}}};e(h$t,"PageInteractorAPI");var nFt=h$t;var g$t=class g$t extends nFt{constructor(_){super();this.config=_;this.getTextDetection=e(async _=>{let g=await this.api.getCanvasDetection(_);if(!g)throw new Error("No data returned from canvas detection");return g},"getTextDetection");this.config=_,this.api=new Rtt({apiKey:_.apiKey,apiURL:_.apiURL})}};e(g$t,"RuntimePageInteractorAPI");var Btt=g$t;var Vhr=require("path");var y$t=class y$t{constructor(l){this.options=l;this.navigatingFrames={};this.trackedFramesGuid=[];this.frameNavigationPromises={};this.onFrameNavigated=e(async l=>{let _=wQ(l);if(this.trackedFramesGuid.includes(_))return this.frameNavigationPromises[_]=new Promise(async g=>{await this.loadScript(l),g()}),this.frameNavigationPromises[_]},"onFrameNavigated");this.loadScript=e(async(l,{retriesLeft:_=3,retryWaitMS:g=2e3,useWrapper:C=!0}={})=>{var V,W;if(C&&this.scriptLoadWrapper)return this.scriptLoadWrapper(()=>this.loadScript(l,{retriesLeft:_,retryWaitMS:g,useWrapper:!1}),l);if(!this.addScriptTagOptions){console.warn("[InjectedScriptManager] addScriptTagOptions not set, skipping loadScript");return}if(this.isFrameClosed(l))return;let P=!1;try{P=this.scriptLoadCheck?await((V=this.scriptLoadCheck)==null?void 0:V.call(this,l)):!1}catch{}if(P||this.isFrameClosed(l))return;try{await l.addScriptTag(this.addScriptTagOptions)}catch(Q){if(_>0)return console.warn(`[InjectedScriptManager] Failed to add script to frame ${wQ(l)}, trying again in ${g/1e3} seconds, ${_-1} retries left.`,Q.message),await WC(g),this.loadScript(l,{retriesLeft:_-1,retryWaitMS:g,useWrapper:C});throw Q}let F=wQ(l),M=Date.now().toString(36)+Math.random().toString(36).substr(2);if(this.navigatingFrames[F]=M,this.options.scriptInitWait&&(console.log(`Waiting ${this.options.scriptInitWait}[ms] before onScriptLoad...`),await WC(this.options.scriptInitWait),console.log("Done waiting before onScriptLoad")),!this.isFrameClosed(l)){if(this.navigatingFrames[F]&&this.navigatingFrames[F]!==M)return console.log("Page navigated again, waiting on new promise..."),this.frameNavigationPromises[F];try{await((W=this.scriptLoadCallback)==null?void 0:W.call(this,l))}catch(Q){console.error("[WebDriver] onScriptLoad error",Q)}}},"loadScript");this.addScriptTagOptions=this.makeFrameInjectedScriptOptions()}setScriptLoadCallback(l){return this.scriptLoadCallback=l,this}setScriptLoadCheck(l){return this.scriptLoadCheck=l,this}setScriptLoadWrapper(l){return this.scriptLoadWrapper=l,this}async addTrackedFrame(l,_=!0){let g="mainFrame"in l?l.mainFrame():l,C=wQ(g);if(this.trackedFramesGuid.includes(C)||this.trackedFramesGuid.push(C),_)return this.onFrameNavigated(g)}getNavigationPromise(l){if(!l){console.warn("[InjectedScriptManager] getNavigationPromise called with undefined argument");return}let _=typeof l=="string"?l:"mainFrame"in l?wQ(l.mainFrame()):wQ(l);return this.frameNavigationPromises[_]}makeFrameInjectedScriptOptions(){switch(this.options.scriptSource){case"file":return this.options.scriptFile?{path:this.options.isScriptFileAbsolute?this.options.scriptFile:(0,Vhr.join)(process.cwd(),this.options.scriptFile)}:void 0;case"url":return this.options.scriptURL?{url:this.options.scriptURL}:void 0;default:return}}isFrameClosed(l){return l.isDetached()||l.page().isClosed()}};e(y$t,"InjectedScriptManager");var jtt=y$t;var mZe=x7(require("path")),S$t=require("fs");var eon=__dirname,Khr=mZe.join(__dirname,".."),ton=(0,S$t.existsSync)(Khr)?Khr:eon;Ghr().config({path:mZe.resolve(ton,".env")});var aFt=process.env.DEV_MODE==="true";function Xhr(){let p=__dirname;for(;!(0,S$t.existsSync)(mZe.join(p,"package.json"));)p=mZe.join(p,"..");return p}e(Xhr,"findRoot");var Yhr=mZe.join(Xhr(),"vtg-build","index.html"),XS={isDevMode:aFt,logLevel:process.env.LOG_LEVEL??"warnings",checksumScript:{source:aFt?"url":"file",url:process.env.SCRIPT_URL,path:Xhr()+"/checksumlib.js"},vtg:{writeLogFile:process.env.WRITE_LOG_FILE==="true",localBuildPath:Yhr,appURL:aFt?process.env.VTG_APP_URL:`file://${Yhr}`,useFakeStory:process.env.USE_FAKE_STORY==="true",recordEvents:process.env.RECORD_EVENTS==="true",fakeStory:{goal:process.env.FAKE_STORY_GOAL??"Send email via outreach list",instructions:process.env.FAKE_STORY_INSTRUCTIONS??"Make sure to select a user from the list first"},fakeTestGeneration:{internalTestId:process.env.FAKE_STORY_INTERNAL_TEST_ID??`tempID${Date.now().toString().slice(-5)}`,generationBatchId:process.env.FAKE_GENERATION_BATCH_ID??`tempID${Date.now().toString().slice(-5)}`},remoteDebugging:process.env.REMOTE_DEBUGGING==="true",taskTimeMachine:{showTaskTimeMachine:process.env.SHOW_TASK_TIME_MACHINE==="true",taskTimeout:parseInt(process.env.TASK_TIME_MACHINE_TIMEOUT??"240000")},aiAssertions:{disabled:process.env.AI_ASSERTIONS_DISABLED==="true",allowRefactoring:process.env.ALLOW_AI_ASSERTIONS_REFACTORING==="true"},aiLocators:{disabled:process.env.AI_LOCATORS_DISABLED==="true",useFakeAILocators:process.env.USE_FAKE_AI_LOCATORS==="true"}},testRun:{timeMachine:{active:!0,headless:!0},monitoring:{segment:{writeKey:process.env.MONITORING_SEGMENT_WRITE_KEY??"MfFJgdVFaFaD3NrBrgX3A9Blwfxs0pSD"}}},buildTime:process.env.BUILD_TIME??"unknown"};aFt&&console.log("Build",XS.buildTime);var T$t=class T$t{constructor(){this.frames={};this.pages=[];this.channels={};this.events=[]}register(l,_,g){if(this.frames[l])return;this.frames[l]=_;let C=_.page();this.pages.includes(C)||(this.pages.push(C),C.exposeFunction("checksumSendMessage",async(P,F)=>{let M=this.frames[P];if(!M)throw new Error(`Frame ${P} not found`);try{await M.evaluate(({message:V})=>{window.postMessage(V,"*")},{message:F})}catch{}}),C.exposeFunction("checksumSendBroadcastMessage",async(P,F)=>{let M=this.channels[P]??[];if(g){let V=require("fs"),W=require("path");this.events.push(...F),this.events.length%10===0&&V.writeFileSync(W.join(process.cwd(),"rrweb-player","events.json"),JSON.stringify(this.events))}M.forEach(async V=>{if(!(V.originFrameGuid&&V.originFrameGuid!==wQ(_)))try{V.handler?await V.handler(F):await _.evaluate(({message:W})=>{window.postMessage(W,"*")},{message:F})}catch{}})}),C.exposeFunction("checksumBringPageToFront",async P=>{let F=this.frames[P];F&&await F.page().bringToFront()}))}subscribeToChannel(l,_,{originFrame:g,handler:C}={}){var P;(P=this.channels)[l]??(P[l]=[]),this.channels[l].push({frame:_,originFrameGuid:g?wQ(g):void 0,handler:C})}unsubscribeFromChannel(l,_){var g;(g=this.channels)[l]??(g[l]=[]),this.channels[l]=this.channels[l].filter(C=>C.frame!==_)}};e(T$t,"FramesMsgBroker");var Jtt=T$t;var Zhr=require("@playwright/test");var PEt=require("jsdom");var D$t=class D$t{constructor(l){this.activeDOMType="checksumIds";this.rawReducedHTMLDom=new PEt.JSDOM(l),this.process()}process(){this.expandedChecksumIdsReducedDom=new PEt.JSDOM(this.rawReducedHTMLDom.serialize()),this.reducedHTMLDom=new PEt.JSDOM(this.rawReducedHTMLDom.serialize()),this.rrwebIdsReducedDom=new PEt.JSDOM(this.rawReducedHTMLDom.serialize());let l=e(F=>{F.window.document.body.querySelectorAll("[checksumid]:not([checksuminteractable])").forEach(V=>{V.removeAttribute("checksumid")})},"removeChecksumIdAttributeFromNonInteractable"),_=e((F,M)=>M.window.document.body.querySelectorAll(`[${F}]`).forEach(V=>V.removeAttribute(F)),"removeAttributeFromAllElements"),g=e(F=>_("checksuminteractable",F),"removeChecksumInteractableAttribute"),C=e(F=>_("checksumid",F),"removeChecksumIdAttribute"),P=e(F=>_("rrwebid",F),"removeRrwebIdAttribute");l(this.reducedHTMLDom),g(this.expandedChecksumIdsReducedDom),g(this.reducedHTMLDom),g(this.rrwebIdsReducedDom),P(this.expandedChecksumIdsReducedDom),P(this.reducedHTMLDom),C(this.rrwebIdsReducedDom)}getDOMForType(l){switch(l){default:case"checksumIds":return this.reducedHTMLDom;case"expandedChecksumIds":return this.expandedChecksumIdsReducedDom;case"rrwebIds":return this.rrwebIdsReducedDom}}async enrich(l){return await l(this.rawReducedHTMLDom),this.process(),this}setActiveDomType(l){this.activeDOMType=l}getActiveDom(){return this.getDOMForType(this.activeDOMType)}getActiveDOMString(){return this.getActiveDom().serialize()}getRrwebIdsReducedDomString(){return this.rrwebIdsReducedDom.serialize()}getDOMStringForType(l){return this.getDOMForType(l).serialize()}get raw(){return this.rawReducedHTMLDom}};e(D$t,"ReducedHTMLDOM");var NEt=D$t;var Qhr=x7(require("path"));var E$t=class E$t{constructor(l="all"){this.listeners=[];this.logLevel=l}log(...l){try{let g=new Error().stack.split(`
1858
1858
  `)[4].trim().match(/\(([^)]+)\)/);if(!(g&&g[1]))throw new Error;let C=g[1].split(":"),P=C.slice(0,-2).join(":"),F=C[C.length-2],V=`${Qhr.default.basename(P)}:${F}`;console.log("\x1B[34m",V,"\x1B[0m",...l),setTimeout(()=>this.listeners.forEach(W=>W.onLog(...l)),0)}catch{console.log(...l)}}addListener(l){this.listeners.push(l)}info(...l){this.logLevel==="all"&&this.log(...l)}warning(...l){(this.logLevel==="all"||this.logLevel==="warnings")&&this.log(...l)}error(...l){this.log(...l)}setLogLevel(l){this.logLevel=l}};e(E$t,"Logger");var C$t=E$t,qtt=new C$t,ron=Object.assign((...p)=>qtt.info(...p),{info:e((...p)=>qtt.info(...p),"info"),warning:e((...p)=>qtt.warning(...p),"warning"),error:e((...p)=>qtt.error(...p),"error"),setLogLevel:e(p=>qtt.setLogLevel(p),"setLogLevel"),addLogListener:e(p=>qtt.addListener(p),"addLogListener")}),Nh=ron;var k$t=class k$t{constructor(l,_,g={headless:!0,logPerformance:!1,timestampBatchingEnabled:!1,sortByTimestamp:!1,taskTimeout:24e4}){this.frameMsgBroker=l;this.injectedScriptManager=_;this.options=g;this.taskQueue=[];this.isRunning=!1;this.currentTimestamp=0;this.currentBeforeTimestamp=!1;this.timeMachineTaskIndex=0;this.currentChecksumId="0";this.timeGoingBack=0;this.timeRunningTasks=0;this.tasksExecuted=0;this.reducedHTMLCache={};this.getReducedHTMLWithRetries=e(async(l,{retriesLeft:_=3,retryWaitMS:g=1e3}={})=>{try{let{reducedHTML:C,currentChecksumId:P}=await l.evaluate(async F=>{var M,V;return(V=(M=window==null?void 0:window.checksum)==null?void 0:M.testGenerator)==null?void 0:V.reduceHTML({},F)},{stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:this.currentChecksumId,fromTimeMachine:!0,invalidateCache:!0});return this.currentChecksumId=P,{reducedHTML:C}}catch(C){if(_>0)return await WC(g),this.getReducedHTMLWithRetries(l,{retriesLeft:_-1,retryWaitMS:g});throw C}},"getReducedHTMLWithRetries");this.rrwebEventHandler=e(async l=>{let _=JSON.stringify(l);await this.timeMachineFrame.evaluate(function(g){let C=JSON.parse(g);return window.checksum.timeMachine.handleEvents(C)},_),l=null},"rrwebEventHandler")}getPage(){return this.timeMachineFrame.page()}getFrame(){return this.timeMachineFrame}async prepare(l,_,g){this.recordingFrame=l,this.frameMsgBroker.register("live",l),_?this.timeMachineFrame=_:this.timeMachineFrame=await this.prepareBrowserContextAndFrame(),g&&g(this.timeMachineFrame),await this.injectedScriptManager.addTrackedFrame(this.timeMachineFrame),this.subscribeToRrwebEvents(),this.taskQueue=[],this.isRunning=!1,await this.start()}async start(){await this.timeMachineFrame.evaluate(async()=>{window.checksum.timeMachine.start({firstEventTimestamp:Date.now()})})}setBrowserContext(l){this.timeMachineBrowserContext=l}async executeTask(l,_=void 0,{name:g,beforeTimestamp:C=!1}={}){return new Promise((P,F)=>{let M=this.timeMachineTaskIndex++,V=e(async({shouldGoBack:W,shouldBatch:Q}={shouldGoBack:!0,shouldBatch:this.options.timestampBatchingEnabled})=>{if(this.timeMachineFrame.isDetached()&&F(),W){let _e=Date.now();await this.goBack(_,C),this.timeGoingBack+=Date.now()-_e}let G=[e(async()=>{try{let _e=Date.now(),ne=await qL(l(this.timeMachineFrame),this.options.taskTimeout,()=>`Task execution timeout - ${g}, took ${Date.now()-_e}ms with timeout of ${this.options.taskTimeout}ms`);P(ne)}catch(_e){Nh.error("Task execution error:",_e.message),F(_e)}},"safeRunTask")()];this.taskQueue.length>0&&Q&&(G.push(...this.taskQueue.filter(_e=>_e.timestamp===_).map(({task:_e})=>_e({shouldGoBack:!1,shouldBatch:!1}))),this.taskQueue=this.taskQueue.filter(_e=>_e.timestamp!==_),G.length&&console.log(`Batching to task "${g}, index: ${M} ${G.length-1} more tasks`)),await Promise.all(G)},"taskWrapper");this.taskQueue.push({name:g,task:V,timestamp:C?_-1:_,queuedAt:Date.now(),index:M}),this.runTasks()})}executeReducedHTMLTask(l){if(this.reducedHTMLCache[l]){let _=new NEt(this.reducedHTMLCache[l]);return Promise.resolve(_.getRrwebIdsReducedDomString())}return this.executeTask(async _=>{let g="",C=await this.getReducedHTMLWithRetries(_);return g=C==null?void 0:C.reducedHTML,g&&(this.reducedHTMLCache[l]=g),new NEt(g).getRrwebIdsReducedDomString()},l,{name:"getReducedHTMLForTimestamp"})}goBack(l,_=!1){return this.currentBeforeTimestamp===_&&this.currentTimestamp===l?Promise.resolve():(this.currentTimestamp=l,this.currentBeforeTimestamp=_,this.timeMachineFrame.evaluate(({timestamp:g,beforeTimestamp:C})=>g===void 0?window.checksum.timeMachine.goLive():window.checksum.timeMachine.goBack(g,{beforeTimestamp:C}),{timestamp:l,beforeTimestamp:_}))}goLive(){return this.timeMachineFrame.evaluate(()=>window.checksum.timeMachine.goLive())}popTask(){return this.options.sortByTimestamp&&(this.taskQueue=this.taskQueue.sort((l,_)=>l.timestamp-_.timestamp)),this.taskQueue.shift()}async runTasks(){if(this.isRunning)return;this.isRunning=!0;let l=this.popTask(),_=Date.now();try{let g=Date.now()-l.queuedAt;Nh.info(`Running task, timestamp: ${l.timestamp} \x1B[36m${l.name}\x1B[0m, index: ${l.index}, was pending for`,g),await l.task();let C=Date.now()-_;this.timeRunningTasks+=C,Nh.info("Finished running task, took",C,"ms.","Queue length:",this.taskQueue.length),this.tasksExecuted++}catch(g){Nh.error("Task execution error:",g)}finally{this.isRunning=!1,this.taskQueue.length>0?this.runTasks():Nh.info("Accumulated time running tasks:",this.timeRunningTasks,"ms, from which time spent going back:",this.timeGoingBack)}}async makeBrowserContext(){let l=await Zhr.chromium.launch({devtools:!1,headless:this.options.headless});return this.timeMachineBrowserContext=await l.newContext({bypassCSP:!0}),this.timeMachineBrowserContext}async makeFrame(){return(await this.timeMachineBrowserContext.newPage()).mainFrame()}async prepareBrowserContextAndFrame(){return this.timeMachineBrowserContext||await this.makeBrowserContext(),this.makeFrame()}subscribeToRrwebEvents(){let l="rrweb";this.frameMsgBroker.subscribeToChannel(l,this.timeMachineFrame,{originFrame:this.recordingFrame,handler:this.rrwebEventHandler}),this.timeMachineFrame.page().on("close",()=>this.frameMsgBroker.unsubscribeFromChannel(l,this.timeMachineFrame))}async toggleTimeMachineHandleEvents(l){try{await this.timeMachineFrame.evaluate(_=>window.checksum.timeMachine.setShouldHandleEvents(_),l)}catch{}}};e(k$t,"ChecksumTimeMachine");var tPe=k$t;var w$t=require("@playwright/test");var A$t=class A$t extends tPe{setTimeMachineBrowserContext(l){this.timeMachineBrowserContext=l}getTimeMachineBrowserContext(){return this.timeMachineBrowserContext}async makeBrowserContext(){w$t.chromium._checksumInternal=!0;let l=await w$t.chromium.launch({devtools:!1,headless:this.options.headless});return l._checksumInternal=!0,this.timeMachineBrowserContext=await l.newContext({bypassCSP:!0}),this.timeMachineBrowserContext._checksumInternal=!0,this.timeMachineBrowserContext.tracing.startChunk=async()=>{},this.timeMachineBrowserContext.tracing.stop(),this.timeMachineBrowserContext.tracing.stop=async()=>{},this.timeMachineBrowserContext.tracing.stopChunk=async()=>{},this.timeMachineBrowserContext}async makeFrame(){let l=await this.timeMachineBrowserContext.newPage();l._checksumInternal=!0;let _=l.mainFrame();return _._checksumInternal=!0,_}};e(A$t,"RuntimeTimeMachine");var sFt=A$t;var P$t=1e3*30;var hZe=class hZe{constructor(l,_="normal",g,C,P,F,M,V,W,Q,ae,G,_e){this.page=l;this.runMode=_;this.analytics=g;this.codeMirror=C;this.monitorBridge=P;this.testInfo=F;this.checksumTestId=M;this.test=V;this.options=W;this.isReplMode=Q;this.config=ae;this.pageInteractorAPI=G;this.locatorStack=[];this.hasRuntimeStartedTrace=!1;this.unzippedHarData=[];this.fallbacks=[];this.hasHealed=!1;this.thoughtsCounter=0;this.highLevelThoughts=[];this.pages={};this.framesMsgBroker=new Jtt;this.scriptLoadWrapper=e(async(l,_)=>{var g;return _!==((g=this.timeMachine)==null?void 0:g.getFrame())&&this.navigationPromise&&await this.navigationPromise,this.wrapInternalSteps(l,_.page())},"scriptLoadWrapper");this.scriptLoadCheck=e(async l=>l.evaluate(()=>!!window.checksum),"scriptLoadCheck");this.scriptLoadCallback=e(async l=>{var _,g;await l.evaluate(async({appSpecificRules:C,esraTimeout:P,sessionRecorder:F,showFrontendLogs:M,showTMSeeker:V})=>{var W;(W=window.checksum)==null||W.testGenerator.init(C,{esraTimeout:P,showFrontendLogs:M,skipElementHighlighting:!0},{assertionGenerator:!1,sessionRecorder:F});try{V&&window.checksum.timeMachine.openSeekbar()}catch{}},{appSpecificRules:this.appSpecificRules,esraTimeout:P$t,sessionRecorder:l!==((_=this.timeMachine)==null?void 0:_.getFrame()),showFrontendLogs:XS.isDevMode,showTMSeeker:l===((g=this.timeMachine)==null?void 0:g.getFrame())&&process.env.CHECKSUM_SHOW_TIME_MACHINE==="true"}),gT(`[init] init script loaded for ${l.page().url()}`)},"scriptLoadCallback");var qe,Xe;WPt(W.printLogs),process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG&&(this.options={...this.options,useChecksumAI:{actions:!1,assertions:!1},useMockData:!1,useChecksumSelectors:!1,autoHealPRs:!1}),this.analytics.setTestId(this.checksumTestId);let ne=U9e({config:this.config,throwIfAuthFailed:!0});this.injectedScriptManager=new jtt({scriptFile:XS.checksumScript.path,scriptSource:XS.checksumScript.source,scriptURL:XS.checksumScript.url,isScriptFileAbsolute:!0}),this.injectedScriptManager.setScriptLoadWrapper(this.scriptLoadWrapper).setScriptLoadCallback(this.scriptLoadCallback).setScriptLoadCheck(this.scriptLoadCheck);let ue=this.getPlaywrightProjectConfig();this.pageInteractor=new Mtt(this.evaluateWithChecksum.bind(this),()=>this.page.mainFrame(),()=>this.timeMachine,{log:gT,logError:gT},{navigationTimeout:(qe=ue.use)==null?void 0:qe.navigationTimeout,actionTimeout:(Xe=ue.use)==null?void 0:Xe.actionTimeout,testAssetsDir:EVt(q9e()),waitActionDelay:1e3},this.pageInteractorAPI,ne),this.setPageProxy(),this.registerPageEvents(),this.checkForActiveTracing(),this.resetFallbacks(),this.checksumClient=new Rtt({apiURL:this.config.apiURL,apiKey:this.config.apiKey}),_e&&(this.highLevelThoughts=_e.highLevelThoughts??[],this.pages=_e.pages??{},this.timeMachineBrowserContext=_e.timeMachineBrowserContext,this.variableStore=_e.variableStore),XS.testRun.timeMachine.active&&(this.timeMachine=new sFt(this.framesMsgBroker,this.injectedScriptManager,{headless:process.env.CHECKSUM_SHOW_TIME_MACHINE==="true"?!1:XS.testRun.timeMachine.headless}),this.timeMachineBrowserContext&&this.timeMachine.setTimeMachineBrowserContext(this.timeMachineBrowserContext)),this.pages[this.getPageGuid(l)]=this.proxy}static async init(l,_,g,C,P,F,M,V,W,Q=!1){M||(M=j9e(5),console.warn(`Checksum test id was not defined for test "${F.title}" and was auto-generated. Please replace - "${F.title}" with -
1859
- test(defineChecksumTest("${F.title}", "${M}"), async ({ page }) => {...`)),C.addTestInfo(M,F.testId),W.options.useChecksumAI!==void 0&&typeof W.options.useChecksumAI=="boolean"&&(W.options.useChecksumAI={actions:W.options.useChecksumAI,assertions:!1});let ae=new Btt(W),G=new hZe(l,W.runMode,_,g,C,F,M,V,{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:W.runMode!=="normal",useMockData:!1,printLogs:!1,...W.options},Q,W,ae,{variableStore:P});return V._checksum.expect.setPage(G),V._checksum.checksumAI.page=G,P.clearAll(),await G.asyncInit(),G.proxy}async asyncInit(l=!1){await this.loadAppSpecificRules(),await this.wrapInternalSteps(async()=>{await this.page.addInitScript(()=>{window.sessionStorage.setItem("checksumai:disable","true")})}),this.timeMachine&&(await this.timeMachine.prepare(this.page.mainFrame()),this.timeMachineBrowserContext=this.timeMachine.getTimeMachineBrowserContext()),this.pageInteractor.init(),l||await this.prepareForTestArtifacts()}async getPage(l){let _=this.page.context().pages()[l];if(!_)throw new Error(`Page with index ${l} not found`);return this.makePage(_)}async makePage(l){let _=this.getPageGuid(l);if(this.pages[_])return this.pages[_];let g=new hZe(l,this.runMode,this.analytics,this.codeMirror,this.monitorBridge,this.testInfo,this.checksumTestId,this.test,this.options,this.isReplMode,this.config,this.pageInteractorAPI,{highLevelThoughts:this.highLevelThoughts,pages:this.pages,timeMachineBrowserContext:this.timeMachineBrowserContext,variableStore:this.variableStore});return await g.asyncInit(!0),g.proxy}getTimeMachinePage(){return this.timeMachine.getPage()}getFramesMessageBroker(){return this.framesMsgBroker}async reauthenticate(l){try{await this.pageInteractor.reauthenticate(l,this.proxy)}catch(_){throw new Error(`Failed to reauthenticate: ${_}`)}}async waitForDialog(l){try{return this.pageInteractor.waitForDialog(!0,l)}catch(_){throw new Error(`Failed to handle native dialog: ${_}`)}}getPageGuid(l){return l._guid}getPlaywrightProjectConfig(){return this.testInfo.project}checkForActiveTracing(){var g;let _=(g=this.getPlaywrightProjectConfig().use)==null?void 0:g.trace;this.traceMode=typeof _=="string"?_:_==null?void 0:_.mode}registerPageEvents(){this.injectedScriptManager.addTrackedFrame(this.page),this.page.on("framenavigated",async l=>{this.injectedScriptManager.onFrameNavigated(l)})}setPageProxy(){this.proxy=new Proxy(this,{get:e(function(_,g){return _.getPageMethod(g)},"get")})}getPageMethod(l){return typeof this[l]=="function"?l==="constructor"?this[l]:this[l].bind(this):!Object.values(Xet).includes(l)||!this.testInfo?this.page[l]:(this.locatorStack.length===0&&(this.pageInitialCallInTestFile=this.getFirstStackTraceFromTestFile()),this.pushToLocatorStack([{type:l,base:this.page,line:this.pageInitialCallInTestFile.line}]),e(function(g,C){try{return this.executeLocator(g,C)}catch(P){throw this.popLocatorChain(),P}},"Page").bind(this))}checksumSelector(l){return this.checksumStepId=l,this.options.useChecksumSelectors&&this.setSelectorFallback(l),this.proxy}checksumAI(l,_,g){let C=this.addNewThought(l,"action",!!_);return this.locatorStack=[],_?this.test.step(l,async()=>{var P;try{return g!=null&&g.withDialog&&this.pageInteractor.listenToDialog(),await _()}catch(F){if(C.children=[],!this.options.useChecksumAI.actions||g!=null&&g.withDialog)throw F;this.setAIFallback(l);try{return await this.initiateFallbackSequence({type:"action",error:F,method:void 0,args:[],testInfo:this.testInfo},{fallbackTypes:[xNe]})}catch{this.analytics.actionExecutionFailure({thought:l})}return await this.initiateFallbackSequence({type:"action",error:F,method:void 0,args:[]},{fallbackTypes:[xNe]})}finally{this.pageInteractor.removeListener("dialog"),this.currentThought=(P=this.currentThought)==null?void 0:P.parent}}):(this.options.useChecksumAI.actions&&this.setAIFallback(l),this.proxy)}resolveAssetsFolder(l){return l.map(_=>rPe.join(EVt(q9e()),_))}compoundSelection(...l){var _;try{let g=this.locatorStack.length?(_=this.getCurrentLocatorInChain())==null?void 0:_.base:void 0,C=new KNt(this.page,this,this.executeLocatorAction.bind(this),g??this.page);return this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),C.init(...l)}catch{throw new Error("Failed generating compound selector")}}getRuntimeOptions(){return this.options}async onTestComplete(l){await this.sendTestArtifacts(),this.cleanupMockData()}async wrapInternalSteps(l,_=this.page){try{return _.mainFrame()._checksumInternal=!0,_._checksumInternal=!0,await l()}finally{_.mainFrame()._checksumInternal=!1,_._checksumInternal=!1}}async conditionallyWrapInternalSteps(l,_){return l?this.wrapInternalSteps(_):_()}async wrapNoLocationSteps(l){try{return this.testInfo._checksumNoLocation=!0,await l()}finally{this.testInfo._checksumNoLocation=!1}}async step(l,_,g=!0,{obtainStep:C=void 0,box:P=!1}={}){try{return this.testInfo._checksumInternal=g===!0,await this.test.step(l,_||(()=>{}),{obtainStep:C,box:P})}finally{this.testInfo._checksumInternal=!1}}addErrorMessage(l,_){this.testInfo.addError(l,_)}async evaluateWithChecksum(l,_,g=!0){return this.navigationPromise&&await this.navigationPromise,this.conditionallyWrapInternalSteps(g,()=>this.page.evaluate(l,_))}addNewThought(l,_,g=!1){let C={id:void 0,thought:l,type:_,children:g?[]:void 0,parent:void 0};if(!this.currentThought)this.highLevelThoughts.push(C);else if(this.currentThought.children)this.currentThought.children.push(C),C.parent=this.currentThought;else{let P=this.currentThought.parent;P?(P.children.push(C),C.parent=P):this.highLevelThoughts.push(C)}return C.parent?C.id=`${C.parent.id}.${C.parent.children.length}`:C.id=`${++this.thoughtsCounter}`,this.currentThought=C,C}buildThoughtsChainForFallback(l=this.highLevelThoughts){let _=[];return l.forEach(g=>{_.push(g.thought),g.children&&_.push(...this.buildThoughtsChainForFallback(g.children))}),_}get navigationPromise(){return this.injectedScriptManager.getNavigationPromise(this.page)}pushToLocatorStack(l){this.locatorStack.push(l)}getCurrentLocatorChain(){return this.locatorStack.length||this.locatorStack.push([]),this.locatorStack[this.locatorStack.length-1]}popLocatorChain(){return this.locatorStack.pop()}getCurrentLocatorInChain(){let l=this.getCurrentLocatorChain();return l==null?void 0:l[l.length-1]}getLocator(l,_){let g=this.getCurrentLocatorInChain();return g.base[g.type](l,_)}getFirstStackTraceFromTestFile(){let l=this.getTestFileStackTrace()[0];if(!l)throw new Error(`Could not find test file location from stack trace ${hZe.getStackTrace()}`);let g=[/\((.*):(\d+):(\d+)\)$/,/.*at (.*):(\d+):(\d+)$/].map(M=>M.exec(l)).find(M=>M!==null);if(!g)throw new Error(`Could not find test file location from stack trace ${l}`);let[,C,P,F]=g;return{file:C,line:parseInt(P),column:parseInt(F)}}getTestFileStackTrace(){return hZe.getStackTrace().filter(_=>_.includes(this.testInfo.file))}static getStackTrace(){return new Error().stack.split(`
1859
+ test(defineChecksumTest("${F.title}", "${M}"), async ({ page }) => {...`)),C.addTestInfo(M,F.testId),W.options.useChecksumAI!==void 0&&typeof W.options.useChecksumAI=="boolean"&&(W.options.useChecksumAI={actions:W.options.useChecksumAI,assertions:!1});let ae=new Btt(W),G=new hZe(l,W.runMode,_,g,C,F,M,V,{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:W.runMode!=="normal",useMockData:!1,printLogs:!1,...W.options},Q,W,ae,{variableStore:P});return V._checksum.expect.setPage(G),V._checksum.checksumAI.page=G,P.clearAll(),await G.asyncInit(),G.proxy}async asyncInit(l=!1){await this.loadAppSpecificRules(),await this.wrapInternalSteps(async()=>{await this.page.addInitScript(()=>{window.sessionStorage.setItem("checksumai:disable","true")})}),this.timeMachine&&(await this.timeMachine.prepare(this.page.mainFrame()),this.timeMachineBrowserContext=this.timeMachine.getTimeMachineBrowserContext()),this.pageInteractor.init(),l||await this.prepareForTestArtifacts()}async getPage(l){let _=this.page.context().pages()[l];if(!_)throw new Error(`Page with index ${l} not found`);return this.makePage(_)}async makePage(l){let _=this.getPageGuid(l);if(this.pages[_])return this.pages[_];let g=new hZe(l,this.runMode,this.analytics,this.codeMirror,this.monitorBridge,this.testInfo,this.checksumTestId,this.test,this.options,this.isReplMode,this.config,this.pageInteractorAPI,{highLevelThoughts:this.highLevelThoughts,pages:this.pages,timeMachineBrowserContext:this.timeMachineBrowserContext,variableStore:this.variableStore});return await g.asyncInit(!0),g.proxy}getTimeMachinePage(){return this.timeMachine.getPage()}getFramesMessageBroker(){return this.framesMsgBroker}async reauthenticate(l){try{await this.pageInteractor.reauthenticate(l,this.proxy)}catch(_){throw new Error(`Failed to reauthenticate: ${_}`)}}async waitForDialog(l){try{return this.pageInteractor.waitForDialog(!0,l)}catch(_){throw new Error(`Failed to handle native dialog: ${_}`)}}getPageGuid(l){return l._guid}getPlaywrightProjectConfig(){return this.testInfo.project}checkForActiveTracing(){var g;let _=(g=this.getPlaywrightProjectConfig().use)==null?void 0:g.trace;this.traceMode=typeof _=="string"?_:_==null?void 0:_.mode}registerPageEvents(){this.injectedScriptManager.addTrackedFrame(this.page),this.page.on("framenavigated",async l=>{this.injectedScriptManager.onFrameNavigated(l)})}setPageProxy(){this.proxy=new Proxy(this,{get:e(function(_,g){return _.getPageMethod(g)},"get")})}getPageMethod(l){return typeof this[l]=="function"?l==="constructor"?this[l]:this[l].bind(this):!Object.values(Xet).includes(l)||!this.testInfo?this.page[l]:(this.locatorStack.length===0&&(this.pageInitialCallInTestFile=this.getFirstStackTraceFromTestFile()),this.pushToLocatorStack([{type:l,base:this.page,line:this.pageInitialCallInTestFile.line}]),e(function(g,C){try{return this.executeLocator(g,C)}catch(P){throw this.popLocatorChain(),P}},"Page").bind(this))}checksumSelector(l){return this.checksumStepId=l,this.options.useChecksumSelectors&&this.setSelectorFallback(l),this.proxy}checksumAI(l,_,g){let C=this.addNewThought(l,"action",!!_);return this.locatorStack=[],_?this.test.step(l,async()=>{var P;try{return g!=null&&g.withDialog&&this.pageInteractor.listenToDialog(),await _()}catch(F){if(C.children=[],!this.options.useChecksumAI.actions||g!=null&&g.withDialog)throw F;this.setAIFallback(l);try{return await this.initiateFallbackSequence({type:"action",error:F,method:void 0,args:[],testInfo:this.testInfo},{fallbackTypes:[xNe]})}catch{this.analytics.actionExecutionFailure({thought:l})}return await this.initiateFallbackSequence({type:"action",error:F,method:void 0,args:[]},{fallbackTypes:[xNe]})}finally{this.pageInteractor.removeListener("dialog"),this.currentThought=(P=this.currentThought)==null?void 0:P.parent}}):(this.options.useChecksumAI.actions&&this.setAIFallback(l),this.proxy)}resolveAssetsFolder(l){return l.map(_=>rPe.join(EVt(q9e()),_))}compoundSelection(...l){var _;try{let g=this.locatorStack.length?(_=this.getCurrentLocatorInChain())==null?void 0:_.base:void 0,C=new KNt(this.page,this,this.executeLocatorAction.bind(this),g??this.page);return this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),C.init(...l)}catch{throw new Error("Failed generating compound selector")}}getRuntimeOptions(){return this.options}async onTestComplete(l){this.addErrorMessage(new Error("Test failed"),"Test failed because of an error"),await this.sendTestArtifacts(),this.cleanupMockData()}async wrapInternalSteps(l,_=this.page){try{return _.mainFrame()._checksumInternal=!0,_._checksumInternal=!0,await l()}finally{_.mainFrame()._checksumInternal=!1,_._checksumInternal=!1}}async conditionallyWrapInternalSteps(l,_){return l?this.wrapInternalSteps(_):_()}async wrapNoLocationSteps(l){try{return this.testInfo._checksumNoLocation=!0,await l()}finally{this.testInfo._checksumNoLocation=!1}}async step(l,_,g=!0,{obtainStep:C=void 0,box:P=!1}={}){try{return this.testInfo._checksumInternal=g===!0,await this.test.step(l,_||(()=>{}),{obtainStep:C,box:P})}finally{this.testInfo._checksumInternal=!1}}addErrorMessage(l,_){this.testInfo.addError(l,_)}async evaluateWithChecksum(l,_,g=!0){return this.navigationPromise&&await this.navigationPromise,this.conditionallyWrapInternalSteps(g,()=>this.page.evaluate(l,_))}addNewThought(l,_,g=!1){let C={id:void 0,thought:l,type:_,children:g?[]:void 0,parent:void 0};if(!this.currentThought)this.highLevelThoughts.push(C);else if(this.currentThought.children)this.currentThought.children.push(C),C.parent=this.currentThought;else{let P=this.currentThought.parent;P?(P.children.push(C),C.parent=P):this.highLevelThoughts.push(C)}return C.parent?C.id=`${C.parent.id}.${C.parent.children.length}`:C.id=`${++this.thoughtsCounter}`,this.currentThought=C,C}buildThoughtsChainForFallback(l=this.highLevelThoughts){let _=[];return l.forEach(g=>{_.push(g.thought),g.children&&_.push(...this.buildThoughtsChainForFallback(g.children))}),_}get navigationPromise(){return this.injectedScriptManager.getNavigationPromise(this.page)}pushToLocatorStack(l){this.locatorStack.push(l)}getCurrentLocatorChain(){return this.locatorStack.length||this.locatorStack.push([]),this.locatorStack[this.locatorStack.length-1]}popLocatorChain(){return this.locatorStack.pop()}getCurrentLocatorInChain(){let l=this.getCurrentLocatorChain();return l==null?void 0:l[l.length-1]}getLocator(l,_){let g=this.getCurrentLocatorInChain();return g.base[g.type](l,_)}getFirstStackTraceFromTestFile(){let l=this.getTestFileStackTrace()[0];if(!l)throw new Error(`Could not find test file location from stack trace ${hZe.getStackTrace()}`);let g=[/\((.*):(\d+):(\d+)\)$/,/.*at (.*):(\d+):(\d+)$/].map(M=>M.exec(l)).find(M=>M!==null);if(!g)throw new Error(`Could not find test file location from stack trace ${l}`);let[,C,P,F]=g;return{file:C,line:parseInt(P),column:parseInt(F)}}getTestFileStackTrace(){return hZe.getStackTrace().filter(_=>_.includes(this.testInfo.file))}static getStackTrace(){return new Error().stack.split(`
1860
1860
  `)}executeLocator(l,_){try{gT(`
1861
1861
  Executing locator ${this.getCurrentLocatorInChain().type} with ${typeof l=="string"?`selector ${l}`:"locator"}`);try{l&&typeof l=="object"&&"has"in l&&this.popLocatorChain()}catch{}let g=this.getLocator(l,_);return new Proxy(g,{get:e((C,P)=>this.getLocatorMethod(g,C,P),"get")})}catch(g){gT("Failed to locate",g)}}getLocatorMethod(l,_,g){return g==="then"?this.handleThen(l,_,g):g==="catch"?this.handleCatch(l,_):g==="finally"?this.handleFinally(l,_):g==="constructor"?e(function(...P){return this.popLocatorChain(),_.constructor(...P)},"Locator"):g in _&&typeof _[g]!="function"||g===Symbol.toPrimitive||g in Object?(this.popLocatorChain(),_[g]):g==="compoundSelection"?function(...C){let P=this.compoundSelection(...C);return P.setBase(l),P}.bind(this):[...Object.values(Xet),...Object.values(Qet)].includes(g)?["or","and"].includes(g)?(gT("'Or' and 'And' locator are not supported, will execute normally"),this.popLocatorChain(),_[g]):(this.getCurrentLocatorChain().push({type:g,base:l}),e(function(...P){return this.executeLocator(P[0],P[1])},"Locator").bind(this)):g==="page"?()=>(this.popLocatorChain(),this.proxy):e(async function(...P){let F=await this.executeLocatorAction(l,g,P);return this.popLocatorChain(),F},"Locator").bind(this)}async executeLocatorAction(l,_,g){if(g&&Array.from(g).some(V=>(V==null?void 0:V.bypassChecksum)===!0))return l[_](...g);let C=l._selector,P=this.consumeChecksumStepId();gT("Executing",_,C);let F=_==="_expect"?"assertion":"action";F==="action"&&this.lastLocatorActionType==="action"&&(gT("Adding minimal wait between consecutive actions..."),await new Promise(V=>setTimeout(V,100))),this.lastLocatorActionType=F,gT("Running initial locator...");let M;try{this.navigationPromise&&await this.navigationPromise,await this.wrapInternalSteps(async()=>{try{gT("[executeLocatorAction] waitForFunction"),await this.page.waitForFunction(()=>!!window.checksum,{timeout:5e3})}catch{gT("[executeLocatorAction] checksum libs not loaded")}});let W=await tFt.createAction({locator:l,method:_,args:g,timeout:this.getLocatorActionTimeout(F,_,g)},{api:this.checksumClient,pageInteractor:this.pageInteractor}).guardedExecute();if(F==="action"){if(W!==!1)return this.resetFallbacks(),W}else if(F==="assertion")return W;M=new Error("Locator action error")}catch(V){gT("Failed initial execution. Exception:",V.message),M=V}switch(F){case"action":try{return await this.initiateFallbackSequence({type:"action",locator:l,method:_,args:g,error:M})}catch(V){this.currentThought||this.analytics.actionExecutionFailure({locator:l,selector:l._selector,method:_,checksumId:P,error:V.toString()})}case"assertion":throw M}}consumeChecksumStepId(){let l=this.checksumStepId;return this.checksumStepId=void 0,l}setExpectConfiguration(l=void 0){this.expectConfiguration=l}getLocatorActionTimeout(l,_,g=[]){var C,P,F;if(this.isReplMode)return null;try{if(l==="assertion"){let Q=this.getAssertionTimeout(g);return gT(`Assertion timeout set to ${Q}`),Q}let M=["fill","dragTo"].includes(_)?1:0,V=(C=g[M])==null?void 0:C.timeout;if(!isNaN(V))return V;let W=(F=(P=this.testInfo.project)==null?void 0:P.use)==null?void 0:F.actionTimeout;return isNaN(W)?3e4:W}catch{return 3e4}}getAssertionTimeout(l=[]){var C,P,F,M,V;let _=(C=l[1])==null?void 0:C.timeout;if(_!==void 0)return _;if(((P=this.expectConfiguration)==null?void 0:P.timeout)!==void 0)return(F=this.expectConfiguration)==null?void 0:F.timeout;let g=(V=(M=this.testInfo._projectInternal)==null?void 0:M.expect)==null?void 0:V.timeout;return g!==void 0?g:3e4}handleThen(l,_,g){return(C,P)=>Promise.resolve(l).then(F=>{let M=C?C(F):F;return M instanceof Promise?M:this.getLocatorMethod(M,_,g)},F=>{if(P)return P(F);throw F})}handleCatch(l,_){return g=>Promise.resolve(l).catch(C=>{if(g)return g(C);throw C})}handleFinally(l,_){return g=>Promise.resolve(l).finally(g)}setSelectorFallback(l){let _={checksumId:l,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:P$t};this.pushFallback(this.constructFallback(BCt).init(_)),this.pushFallback(this.constructFallback(AEt).init(_))}setCompoundSelectorFallback(l){this.pushFallback(this.constructFallback(EEt).init({checksumId:l,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:P$t}))}setAIFallback(l){return this.pushFallback(this.constructFallback(xNe).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback()})),this.proxy}pushFallback(l){this.fallbacks.push(l),this.sortFallbacks()}async runFallback(l,_){this.analytics.fallbackStart(l);let g=l.resolve(_),C=await qL(g,l.timeout);if(!C)throw new Error("Fallback failed");if(this.hasHealed=!0,C.steps.length===1){let P=C.steps[0];P.thought&&(this.currentThought.thought=P.thought)}else this.currentThought.children=C.steps.map((P,F)=>({id:`${this.currentThought.id}.${F+1}`,thought:P.thought,type:P.type,children:void 0,parent:this.currentThought}))}async runConditionallyWithinStep(l,_,g){return l?await this.step(_,g):await g()}async initiateFallbackSequence(l,{fallbackTypes:_=void 0}={}){gT(`[initiateFallbackSequence] with type: ${l.type}...`);let g=this.fallbacks.find(P=>P instanceof xNe);if(g){let P=g.getFailedThought(),F=this.variableStore.getActiveVariables();this.fallbacks.forEach(M=>{M.setThought(P),M.setVariables(F)})}let C=this.fallbacks;_&&(C=C.filter(P=>_.reduce((F,M)=>F||P instanceof M,!1))),C=C.filter(P=>P.canResolve(l));try{for(let P of C){let F=P==null?void 0:P.toString();F&&console.log(`Using ${F}`);let M;try{await this.runConditionallyWithinStep(l.type!=="assertion"||!l.withChecksumAI,P.getRecoveryAttemptTitle(l),async()=>{await this.runFallback(P,l)}),M=!0}catch(V){if(M=!1,l.withChecksumAI&&V.message==="fetch failed")throw new Error(hNe);F&&console.log(`Failed to use ${F}`),P.cancel();continue}finally{this.analytics[`${l.type}FallbackExecution`](M,P)}return!0}throw l.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(jCt).init()]}async shutdown(){if(this.analytics)return gT("Flushing events..."),this.analytics.close()}sortFallbacks(){let l=[jCt,EEt,BCt,AEt,xNe];this.fallbacks.sort((_,g)=>l.indexOf(_.constructor)-l.indexOf(g.constructor))}constructFallback(l){return new l(this.page,this.evaluateWithChecksum.bind(this),this,this.pageInteractor,this.analytics,{generateSelectionData:this.runMode!=="normal"})}async prepareForTestArtifacts(){if((this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock(),this.traceMode&&this.traceMode!=="off"){let _=await this.getTraceFilePath();_&&this.monitorBridge.addAsset({type:"trace",path:_,testId:this.checksumTestId,project:this.testInfo.project.name})}if(!1){let _=F_r(Zet(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:_,testId:this.checksumTestId})}}async sendTestArtifacts(){this.runMode!=="normal"&&(await this.codeMirror.write()).forEach(l=>this.monitorBridge.addAsset(l))}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?I_r(Zet(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let l=kVt(Zet(this.testInfo.file)),_=rPe.join(l,`${this.checksumTestId}.har.zip`);if(!(0,Wae.existsSync)(_))throw new Error("Could not find har file or zip file");let g=rPe.join(l,"tmp");(0,Wae.existsSync)(g)||(0,Wae.mkdirSync)(g);let C=(0,Wae.readFileSync)(_),P=await(0,egr.loadAsync)(C);for(let M of Object.keys(P.files)){let V=await P.file(M).async("string"),W=rPe.join(g,M);(0,Wae.writeFileSync)(W,V),this.unzippedHarData.push(W)}let F=rPe.join(g,"test.har");if(!(0,Wae.existsSync)(F))throw this.cleanupMockData(),new Error(`Could not find har file ${F} after unzipping ${_}`);return F}cleanupMockData(){this.unzippedHarData.forEach(l=>{(0,Wae.rmSync)(l)}),this.unzippedHarData.length>0&&(0,Wae.rmSync)(rPe.dirname(this.unzippedHarData[0]),{recursive:!0,force:!0})}async prepareAPIMock(){let l={GET:0,POST:0,PUT:0,DELETE:0};try{let _=await this.prepareMockData();await this.page.routeFromHAR(_,{url:"*/**",notFound:"fallback",update:!1});let g=this.page._routes[0].handler;await this.page.route("**/*",C=>{let P=C.request().headers(),F=C.request().method();P["Checksum-Id"]=(++l[F]).toString(),C.request()._applyFallbackOverrides({headers:P}),g(C)})}catch(_){gT("Error setting up mock data",_.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let l=rPe.join(ett(q9e()),"settings.asr");if(!(0,Wae.existsSync)(l)){gT("Could not find ASR file");return}let{ungzip:_}=JPt();try{let g=await _((0,Wae.readFileSync)(l));this.appSpecificRules=JSON.parse(g)||{}}catch(g){gT("Could not read ASR file",g.message)}}};e(hZe,"ChecksumPage");var oFt=hZe;var gZe=x7(azt()),tgr=x7(require("path")),nPe=require("fs");var FEt=class FEt{constructor(l,_){this.runMode=l;this.assertionCodeGenerator=_;this.lines=[];this.linesOffsetFromOriginalFile=0;let g={getPageRegexMatchingUrl:e(()=>null,"getPageRegexMatchingUrl"),resolvePageIdFromUrl:e(()=>null,"resolvePageIdFromUrl")}}static init(l,_){return new FEt(l,_)}static initWithContent(l,_){let g=new FEt("normal",_);return g.lines=[l],g}async load(l,_){if(this.filename)return;this.filename=l,this.testId=_;let g=this.getProcessedFilename(this.filename);(0,nPe.existsSync)(g)&&(0,nPe.unlinkSync)(g),this.lines=["",...(0,nPe.readFileSync)(this.filename,"utf-8").split(`
1862
1862
  `)];try{this.esraMetadataMap=await qPt(Zet(g),_)}catch{console.log("[CodeMirror] Failed loading ESRA metadata for test file, creating new ESRA map"),this.esraMetadataMap={}}}addTestToCode(l,_){let g=gZe.createSourceFile("",this.lines.join(""),gZe.ScriptTarget.ES2015),C=this.findTitleInParentNode(this.getSourceFileChildren(g),g,l.description);if(C){let M=g.text.substring(0,C.pos)+_.generateSingleTestCode(l)+g.text.substring(C.end);return _.styleCode(M)}let P=this.getLastDescribeNode(this.getSourceFileChildren(g),g);if(P){let M=g.text.substring(0,g.text.substring(0,P.end).lastIndexOf("}")-1)+_.generateSingleTestCode(l)+"});";return _.styleCode(M)}let F=g.text+`
@@ -1946,7 +1946,7 @@ if (typeof globalThis.requireTs === "undefined") {
1946
1946
  `),P=new zkt(g.sourceFile);P.transformSourceFile([new $Lt(g.sourceFile),new WLt(g.sourceFile,g.testMirrors.filter(V=>V.internalTestId===l).map(V=>V.testBody),K3r(C))]);let F=this.testAssetsManager.getSavedTestFilePath();return P.write(F),(0,t8r.relative)(process.cwd(),F)}get isLoadedFromTestFile(){return!!this.vtgTestFileRunConfig}async reloadTestFromFile(){if(!this.vtgTestFileRunConfig)return;let l=this.getReloadTestEnvironmentCode();await this.evaluationService.execute(l);let g=new Vkt(this.testAssetsManager.getSavedTestFilePath()).loadActionsFromSingleTest();return await this.actionsManager.reloadTestSteps(g),g}getReloadTestEnvironmentCode(){let l=zLt(G3r(e8r)),_=this.testAssetsManager.getSavedTestFilePath(),g=VLt(_),C=new zkt(g);C.transformSourceFile([new GLt,new XLt,new KLt(_),new HLt,new QLt("requireTs"),new YLt(g)]);let P=C.getFormattedTestFileCode();return[l,P].join(`
1947
1947
  `)}getLocalSavedData(l){let _=`${this.testAssetsManager.getLocalSavePath()}/${l}/test.json`,g=this.readJsonFile(_);return g?{...g,executedActions:g.executedActions.map(C=>({...C,timestamp:void 0}))}:null}readJsonFile(l){try{let _=(0,HZe.readFileSync)(l,"utf-8");return JSON.parse(_)}catch(_){return Nh.error(`Error reading or parsing JSON file: ${_}`),null}}makeDraftData(){let l=this.userStoryService.getStory(),_=this.userStoryService.getTestGenerationData(),g=this.userStoryService.getEnvInfo();return{actions:this.actionsManager.actions,internalTestId:_.internalTestId,environmentUserId:g.user.username,description:l.goal}}async generateTestFileString(l){try{let _=this.makeDraftData(),g=l?`${l}.draft.spec.ts`:`test-${_.internalTestId}.draft.spec.ts`,C=await this.apiService.post("test-generation/generate-test-file-string",_);if(!C.ok)throw new Error(`test generation request failed: ${C.statusText}`);let P=await C.text();oxr(P,g,this.testAssetsManager.getLocalSavePath())}catch(_){throw Nh.error("Failed to generate test file string",_),new Error("Failed to generate test file string")}}localSave(){let l=JSON.stringify(this.replayJSON,null,2),_=this.testAssetsManager.getAssetsFolderPath();(0,HZe.writeFileSync)(`${_}/test.json`,l),(0,HZe.writeFileSync)(`${this.testAssetsManager.getLocalAutoSavePath()}/test.json`,l)}get replayJSON(){var l;return{executedActions:this.actionsManager.actions,testGenerationData:this.userStoryService.getTestGenerationData(),settings:{baseURL:(l=this.config.environments.find(_=>_.default))==null?void 0:l.baseURL,assetsFolderPath:this.testAssetsManager.getAssetsFolderPath(),didLogin:this.actionsService.hasLoggedIn(),traceFilePath:this.testAssetsManager.getTraceFilePath(),harFilePath:this.testAssetsManager.getHarFilePath()},story:this.userStoryService.getStory()}}async localBackup(l){if(l){this.testAssetsManager.setCurrentSaveAsLocation(l);let _=this.testAssetsManager.getLocalSaveAsPath();cxr(this.testAssetsManager.getLocalAutoSavePath(),_)}return this.saveTestFile()}getIsFolderAlreadyExistsInDrafts(l){try{let _=`${this.testAssetsManager.getLocalSavePath()}/${l}`;return(0,HZe.statSync)(_).isDirectory()}catch(_){if(_.code==="ENOENT")return!1;throw _}}async saveToCloud(){try{if(!this.userStoryService.hasTestGenerationData()){Nh("No test generation data, can't upload");return}let l=await this.userStoryService.createTestGeneration(),_=new gLt(this.apiService.getBaseURL(),this.config.apiKey,null,()=>`test-generation/${l}/get-upload-url`),g=e(M=>({complete:!1,error:!1,response:void 0,info:M}),"buildUploadAsset"),C=g({type:"trace",path:this.testAssetsManager.getTraceFilePath()}),P=g({type:"har",path:await N4r(this.testAssetsManager.getHarFolderPath())});await Promise.all([_.uploadAsset(C),_.uploadAsset(P)]);let F=this.actionsManager.actions.map(M=>({...M,parentFramesSelectors:M.parentFramesSelectors?M.parentFramesSelectors.filter(V=>V!=="iframe"):void 0}));await this.apiService.post(`test-generation/${l}/completed`,{actions:F})}catch(l){Nh.error("Failed to upload test",l)}}};e(xer,"VtgStorageService");var ZLt=xer;var Ser=class Ser{constructor(l,_){this.apiService=l;this.config=_}getStory(){return this.story}getTestGenerationData(){return this.userStoryTestGeneration}hasTestGenerationData(){var l;return!!((l=this.userStoryTestGeneration)!=null&&l.internalTestId)}setStoryInfo(l,_){this.story=l,this.userStoryTestGeneration=_}async fetchStory(l){if(XS.vtg.useFakeStory){console.log("Using fake flow data"),this.story={...XS.vtg.fakeStory,environment:{name:void 0,userRole:void 0}},this.userStoryTestGeneration={internalTestId:XS.vtg.fakeTestGeneration.internalTestId,generationBatchId:XS.vtg.fakeTestGeneration.generationBatchId};return}if(!l)throw new Error("no story id provided");let g=await(await this.apiService.post(`test-generation/info/${l}`)).json();if(!(g!=null&&g.id))throw new Error(`Story ${l} not found`);console.log("Received flow data:",g);let{id:C,title:P,steps:F,startUrl:M,userRole:V,environment:W,internalTestId:Q,generationBatchId:ae}=g;this.userStoryTestGeneration={internalTestId:Q,generationBatchId:ae},this.story={id:C,goal:P,instructions:F,url:M,environment:{userRole:V,name:W}}}getEnvInfo(){return RCt(this.config,{role:this.story.environment.userRole,environment:this.story.environment.name})}async createTestGeneration(){if(!this.story.id)return;let l=await this.apiService.post(`test-generation/create/${this.story.id}`,{internalTestId:this.userStoryTestGeneration.internalTestId,testGenerationBatchId:this.userStoryTestGeneration.generationBatchId}),{testGenerationId:_}=await l.json();return this.userStoryTestGeneration.testGenerationId=_,_}};e(Ser,"VtgUserStoryService");var eMt=Ser;var Ter=class Ter{constructor(){this._executedActions=[];this.onActionExecuted=this.pushExecutedActionOrAddAfterParent.bind(this)}get actions(){return this._executedActions}set executedActions(l){var _;this._executedActions=l,(_=this.storageService)==null||_.localSave()}addAction(l){var _;this._executedActions.push(l),(_=this.storageService)==null||_.localSave()}setActions(l){this._executedActions=l}updateAssertionById(l,_){this.executedActions=this._executedActions.map(g=>{var C;if(g.id===l){let P=!!((C=g.assertions)!=null&&C.find(({id:M})=>M===_.id)),F={...g};return P?F.assertions=g.assertions.map(M=>M.id===_.id?Object.assign(M,_):M):F.assertions=[...g.assertions??[],_],{...F,assertions:F.assertions.sort((M,V)=>M.timestamp!==V.timestamp?M.timestamp-V.timestamp:M.createdAt-V.createdAt)}}return g})}setStorageService(l){this.storageService=l}createAction(l){var V,W,Q;let{id:_,data:g,options:C,type:P}=l,F={id:_,...g},M=[...this._executedActions];switch(C==null?void 0:C.type){case"insertAfter":{let ae=this.findActionOrAssertionById(C.afterStepId),G=M.findIndex(_e=>_e.id===ae.action.id);if(ae.assertion||(W=(V=ae.action)==null?void 0:V.assertions)!=null&&W.length){let _e=ae.assertion??ae.action.assertions[0],{before:ne,after:ue}=E4n(((Q=M[G])==null?void 0:Q.assertions)??[],_e.id,!!ae.assertion);M[G].assertions=ne,F.assertions=ue.map(qe=>({...qe,actionId:F.id}))}G!==-1?M.splice(G+1,0,F):M.push(F);break}case"insertLast":M.push(F);break;case"replace":{let ae=M.findIndex(G=>G.id===C.stepId);ae!==-1&&M.splice(ae,1,F);break}case"replaceLast":M.length>0&&(M[M.length-1]=F);break}this.executedActions=M}pushExecutedActionOrAddAfterParent(l,_={}){if(_.previousActionId){let g=this._executedActions.findIndex(({id:C})=>C===_.previousActionId);if(g!==-1){let C={...l,timestamp:this._executedActions[g].timestamp+1};this._executedActions=[...this._executedActions.slice(0,g+1),C,...this._executedActions.slice(g+1)]}}else this.executedActions=Array.isArray(l)?[...this._executedActions,...l]:[...this._executedActions,l]}addManualActionsToExecuted(l){this.executedActions=[...this._executedActions,l]}updateExecutedAction(l){let _=this._executedActions.findIndex(({id:g})=>g===l.id);_!==-1&&(this.executedActions=[...this._executedActions.slice(0,_),{...this._executedActions[_],...l},...this._executedActions.slice(_+1)])}deleteStep(l,_,g={assertionsOnly:!1}){_==="Action"?g.assertionsOnly?this.executedActions=this._executedActions.map(C=>C.id===l?{...C,assertions:[]}:C):this.executedActions=this._executedActions.filter(C=>C.id!==l):_==="Assertion"&&(this.executedActions=this._executedActions.map(C=>(C.assertions=(C.assertions??[]).filter(P=>P.id!==l),C)))}clearTestSteps(l=!0){if(l){let{navigation:_,login:g}=this.findLoginAndNavigationActions();this.executedActions=this._executedActions.reduce((C,P)=>([_==null?void 0:_.id,g==null?void 0:g.id].includes(P.id)&&C.push({...P,assertions:[]}),C),[])}else this.executedActions=[];return this._executedActions}reloadTestSteps(l){this.clearTestSteps(!1),this.executedActions=l}findLoginAndNavigationActions(){let l=this._executedActions.find(({eventCode:g})=>g==="navigation"),_=this._executedActions.find(({eventCode:g})=>g==="login");return{navigation:l,login:_}}addAssertionToAction(l,_){this.executedActions=this._executedActions.map(g=>{if(g.id!==l.actionId)return g;if(g.assertions||(g.assertions=[]),_){let C=g.assertions.findIndex(({id:P})=>_===P);g.assertions.splice(C+1,0,l)}else g.assertions=[l,...g.assertions??[]];return g})}findActionByAssertionId(l){return this._executedActions.find(({assertions:_=[]})=>_.find(g=>g.id===l))}findActionOrAssertionById(l){let _={action:null,assertion:null};return this._executedActions.forEach(g=>{g.id===l&&(_.action=g);let C=(g.assertions??[]).find(P=>P.id===l);C&&(_={action:g,assertion:C})}),_}};e(Ter,"VtgActionsManager");var tMt=Ter,E4n=e((p,l,_=!0)=>{let g=Number(_),C=p.findIndex(M=>M.id===l);if(C===-1)return{before:p,after:[]};let P=p.slice(0,C+g),F=p.slice(C+g);return{before:P,after:F}},"splitArrayAtId");var _nr=x7(lAr()),hAr=x7(require("net")),gAr=x7(lrr()),yAr=x7(mAr());var pnr=class pnr{constructor(l,_,g){this.app=l;this.assertionsService=_;this.actionsManager=g}setupEndpoints(){this.app.post("/api/createStep",async(l,_)=>{let g=l.body;try{if(g.type==="Assertion"){let C=this.assertionsService.createAssertion(g);return _.status(200).json(C)}if(g.type==="Action")return this.actionsManager.createAction(g),_.send("success")}catch(C){return Nh.error("/api/createStep error:",C),_.status(500).send(C)}}),this.app.patch("/api/updateStep",async(l,_)=>{let g=l.body;try{if(g.type==="Assertion"){let C=await this.assertionsService.updateAssertion({id:g.id,data:g.data});_.status(200).json(C)}if(g.type==="Action")return this.actionsManager.updateExecutedAction({...g.data,id:g.id}),_.send("success")}catch(C){return _.status(500).send(C)}}),this.app.delete("/api/deleteStep",async(l,_)=>{let{id:g,options:C,type:P}=l.body;try{this.actionsManager.deleteStep(g,P,C)}catch(F){return _.status(500).send(F)}return _.status(200).send({message:"Success!"})}),this.app.post("/api/clear-test",async(l,_)=>{try{let g=this.actionsManager.clearTestSteps();return _.status(200).send(g)}catch(g){return _.status(500).send(g)}})}};e(pnr,"VtgStepsController");var xRt=pnr;var fnr=class fnr{constructor(l,_){this.app=l;this.locatorsService=_}setupEndpoints(){this.app.post("/api/locators/play",async(l,_)=>{let g=l.body;try{let C=await this.locatorsService.verifyLocatorOrSelector(g);return _.status(200).send(C)}catch(C){return _.status(400).send({error:C.message})}}),this.app.post("/api/locators/test-identical",async(l,_)=>{let{locator:g,compareLocator:C,timestamp:P}=l.body;try{let F=await this.locatorsService.verifyAndCompareLocatorOnTimemachine(g,C,P);return _.status(200).send(F)}catch(F){return _.status(400).send({error:F.message})}}),this.app.post("/api/ai/locators/generate",async(l,_)=>{let{step:g,target:C,processId:P}=l.body;g.isDefaultThought&&(g.thought=null);try{this.locatorsService.generateAILocators(g,C,P);let F={processId:P,stepId:C.id,success:!0};_.status(200).send(F)}catch(F){_.status(400).send({processId:P,success:!1,error:F.message})}}),this.app.post("/api/ai/locators/extract-css",async(l,_)=>{let{step:g,target:C,processId:P,llmLocators:F}=l.body;g.isDefaultThought&&(g.thought=null);try{this.locatorsService.extractCSS(g,C,P,F);let M={processId:P,stepId:C.id,success:!0};_.status(200).send(M)}catch(M){_.status(400).send({processId:P,error:M.message})}}),this.app.post("/api/ai/locators/filter",async(l,_)=>{let{step:g,target:C,processId:P,candidates:F}=l.body;g.isDefaultThought&&(g.thought=null);try{this.locatorsService.filterLocators(g,C,P,F);let M={processId:P,stepId:C.id,success:!0};_.status(200).send(M)}catch(M){_.status(400).send({processId:P,error:M.message})}}),this.app.delete("/api/ai/locators/process/:id",async(l,_)=>{let g=l.params.id;try{this.locatorsService.cancelProcess(g),Nh("Cancelled process",g),_.status(200).send({success:!0})}catch(C){_.status(400).send({error:C.message})}})}};e(fnr,"VtgLocatorsController");var SRt=fnr;var dnr=class dnr{constructor(l,_,g,C,P,F,M,V,W){this.actionsService=l;this.assertionsService=_;this.locatorsService=g;this.aiTestGenerationService=C;this.aiAssertionsService=P;this.aiThoughtsService=F;this.actionsManager=M;this.storageService=V;this.settingsService=W}async start(){return this.app=(0,_nr.default)(),this.app.use((0,yAr.default)()),this.app.use(gAr.default.json({limit:"50mb"})),this.app.use(_nr.default.raw({type:"multipart/form-data",limit:"50mb"})),this.port=await this.acquirePortNumber(),new xRt(this.app,this.assertionsService,this.actionsManager).setupEndpoints(),this.setupEndpoints(),new SRt(this.app,this.locatorsService).setupEndpoints(),new Promise(l=>{this.app.listen(this.port,()=>{console.log(`Express server running on port ${this.port}`),l()})})}setupEndpoints(){this.app.get("/api",async(l,_)=>{_.send("success")}),this.app.post("/api/test/generate-test-file-string",async(l,_)=>{try{return await this.storageService.generateTestFileString(l.body.fileName),_.send("success")}catch(g){return _.status(400).send({error:g.message})}}),this.app.post("/api/test/upload",async(l,_)=>(await this.storageService.saveToCloud(),_.send("success"))),this.app.post("/api/test/local-save",async(l,_)=>{await this.storageService.localSave(),_.send("success")}),this.app.post("/api/reload-test-from-file",async(l,_)=>{try{if(!this.storageService.isLoadedFromTestFile)return _.status(404).send("No test file found");let g=await this.storageService.reloadTestFromFile();return _.status(200).send(g)}catch(g){return console.log("failed to reload test from file",g),_.status(500).send(g.message)}}),this.app.post("/api/test/verify-save-location",async(l,_)=>{try{let g=this.storageService.getIsFolderAlreadyExistsInDrafts(l.body.location);_.send({exists:g})}catch(g){_.status(400).send({error:g})}}),this.app.post("/api/test/backup",async(l,_)=>{let{backupFolderName:g}=l.body;if(!uxr(g))return _.status(400).send({error:"Invalid folder name"});let C=await this.storageService.localBackup(g);_.send(C)}),this.app.post("/api/ai/init",async(l,_)=>{await this.aiTestGenerationService.init(),_.send("success")}),this.app.post("/api/ai/iterate",async(l,_)=>{let g=l.body,C=await this.aiTestGenerationService.iterate(g);return C?_.status(200).json(C):_.status(400).send("no action generated")}),this.app.post("/api/thoughts/actions/generate",async(l,_)=>{let g=l.body,{processId:C,action:{id:P}}=g;try{this.aiThoughtsService.generateActionThoughts(g);let F={processId:C,stepId:P,success:!0};_.status(200).send(F)}catch(F){return _.status(400).send({processId:C,error:F.message})}}),this.app.post("/api/thoughts/assertions/generate",async(l,_)=>{let g=l.body,{processId:C,assertion:{id:P}}=g;try{this.aiThoughtsService.generateAssertionThought(g);let F={processId:C,stepId:P,success:!0};_.status(200).send(F)}catch(F){return _.status(400).send({processId:C,error:F.message})}}),this.app.post("/api/thoughts/stop-generate",async(l,_)=>{let g=l.body;this.aiThoughtsService.stopGeneratingThought(g.stepId);let C={stepId:g.stepId};return _.status(200).send(C)}),this.app.post("/api/assertions/generate",(l,_)=>{let g=l.body,{processId:C}=g;try{this.aiAssertionsService.generateAiAssertions(g);let P={processId:C,stepId:g.id,success:!0};return _.status(200).json(P)}catch(P){return _.status(500).send({processId:C,error:P.message})}}),this.app.post("/api/assertions/stop-generate",(l,_)=>{let{id:g}=l.body,C={stepId:g};return this.aiAssertionsService.stopGenerateAiAssertions(g),_.status(200).send(C)}),this.app.post("/ai/stop",async(l,_)=>{this.aiTestGenerationService.stop()}),this.app.post("/api/assertion/verify/time-machine",async(l,_)=>{let g=l.body,C=await this.assertionsService.verifyOnTimeMachine(g);return _.status(200).send(C)}),this.app.post("/api/assertion/verify/live",async(l,_)=>{let g=l.body;try{let C=await this.assertionsService.verifyOnLive(g),P=C.success?200:404;return _.status(P).send(C)}catch(C){return _.status(404).send({success:!1,message:String(C)})}}),this.app.post("/api/assertion/save",async(l,_)=>{let g=l.body;try{let C=await this.assertionsService.updateAssertion(g);_.status(200).json(C)}catch(C){_.status(400).send({error:C.message})}}),this.app.post("/api/steps/execute",async(l,_)=>{let g=l.body;try{let C=null;return s9n(g)?C=await this.aiTestGenerationService.executeAction(g):o9n(g)&&(C=await this.actionsService.executeAction(g)),_.status(200).json(C)}catch(C){return _.status(400).send({error:C.message})}}),this.app.post("/api/upload-files",async(l,_)=>{try{await this.actionsService.uploadFiles(l.body.files)}catch(g){return _.status(500).send(g)}return _.status(200).send({message:"File uploaded successfully!"})}),this.app.post("/api/steps/add-manual-action",async(l,_)=>{let g=l.body;return this.actionsManager.addManualActionsToExecuted(g.action),_.send("success")}),this.app.put("/api/steps",async(l,_)=>{let g=l.body;try{this.actionsManager.pushExecutedActionOrAddAfterParent(g.action,g.options)}catch(C){return _.status(500).send(C)}return _.send("success")}),this.app.get("/api/settings",async(l,_)=>{let g=this.settingsService.getSettings();return _.status(200).send(g)}),this.app.post("/api/settings",async(l,_)=>(this.settingsService.updateSettings(l.body),_.status(200).send({message:"Success!"})))}async acquirePortNumber(){return await new Promise((l,_)=>{let g=hAr.default.createServer();g.unref(),g.on("error",_),g.listen(0,()=>{let C=g.address().port;g.close(()=>{l(C)})})})}async evaluateServerPort(l){if(!l)throw new Error("Page not initialized");await l.evaluate(_=>{window.vtg.setServerPort(_)},this.port)}};e(dnr,"VtgExpressServer");var TRt=dnr;function s9n(p){var l;return((l=p.options)==null?void 0:l.isAISuggestion)===!0}e(s9n,"isAIExecuteActionArgs");function o9n(p){var l;return((l=p.options)==null?void 0:l.isAISuggestion)===!1}e(o9n,"isManualExecuteActionArgs");var DRt=require("fs");var mnr=class mnr{constructor(l,_,g){this.projectRootDirectory=l;this.checksumRoot=_;this.vtgTestFileRunConfig=g;this.localSaveFolderPath=`${this.checksumRoot}/drafts`}createTestGenerationAssetsFolders(){this.assetsFolderPath=this.projectRootDirectory+`/tg-assets/${Date.now()}`,(0,DRt.mkdirSync)(this.assetsFolderPath,{recursive:!0}),(0,DRt.mkdirSync)(this.getHarFolderPath(),{recursive:!0})}createTestGenerationLocalAutoSaveFolder(l){this.autoSaveFolderPath=`/auto-save/${l}`,(0,DRt.mkdirSync)(this.getLocalAutoSavePath(),{recursive:!0})}getAssetsFolderPath(){return this.assetsFolderPath}getLocalAutoSavePath(){return this.localSaveFolderPath+this.autoSaveFolderPath}getLocalSaveAsPath(){return this.currentSaveAsLocation??(this.currentSaveAsLocation=`${Date.now()}_save`),`${this.localSaveFolderPath}/${this.currentSaveAsLocation}`}getSavedTestFilePath(){if(!this.vtgTestFileRunConfig)throw new Error("vtgTestFileRunConfig is required to get the test file save as path");if(this.currentSaveAsLocation){let l=this.vtgTestFileRunConfig.sourceFilePath.split("/").pop();return`${this.localSaveFolderPath}/${this.currentSaveAsLocation}/${l}`}else return this.vtgTestFileRunConfig.sourceFilePath}getLocalSavePath(){return this.localSaveFolderPath}getLogsPath(){return`${this.localSaveFolderPath}/logs`}getHarFolderPath(){return this.assetsFolderPath+"/har"}getHarFilePath(){return`${this.getHarFolderPath()}/har.har`}getTraceFilePath(){return`${this.assetsFolderPath}/trace.zip`}setCurrentSaveAsLocation(l){l&&!(l!=null&&l.startsWith("auto-save"))&&(this.currentSaveAsLocation=l)}};e(mnr,"VtgTestAssetsManager");var CRt=mnr;var c9n={useCDPSession:!0,trackLoadedResources:!0},hnr=class hnr extends jOt{constructor(_={},g={devtools:!1},C={},P,F){super({...c9n,..._},g,P,F);this.settings={frontendAppSpecificRules:void 0,initTestGenerator:!0,frontendTestGenerationConfig:void 0};this.isScriptLoaded=e(async(_,g=1e3)=>{try{return await _.waitForFunction(()=>!!window.checksum,void 0,{timeout:g}),!0}catch{return!1}},"isScriptLoaded");this.initInjectedScript=e(async _=>{try{return await _.waitForFunction(()=>{var g;return!!((g=window.checksum)!=null&&g.testGenerator)}),_.evaluate(async({appSpecificRules:g,config:C,initModules:P})=>{window.checksum.testGenerator.init(g,C,P),g.hasGoals&&await window.checksum.goalTracker.init()},{appSpecificRules:this.settings.frontendAppSpecificRules,config:this.getFrontendTestGenerationConfig(),initModules:this.getInjectedScriptInitModules(_)})}catch(g){console.log("initInjectedScript exception",g)}},"initInjectedScript");this.settings={...this.settings,...C},this.injectedScriptManager.setScriptLoadCheck(this.isScriptLoaded),this.settings.initTestGenerator&&this.injectedScriptManager.setScriptLoadCallback(this.initInjectedScript)}async prepare(_={}){let g=await super.prepare(_);return this.evaluateWithChecksumTargetFrame=this.page.mainFrame(),this.settings.loadScriptOnPrepare&&await this.injectedScriptManager.addTrackedFrame(this.page),await this.page.addInitScript(()=>{window.sessionStorage.setItem("checksumai:disable","true")}),g}setEvaluateWithChecksumTargetFrame(_){this.evaluateWithChecksumTargetFrame=_}getInjectedScriptInitModules(_){return{assertionGenerator:!0,sessionRecorder:!0,filesObserver:!1,assertionsObserver:!1,nativeDialogObserver:!1}}getFrontendTestGenerationConfig(){return this.settings.frontendTestGenerationConfig}async evaluateWithChecksum(_,g,C=this.evaluateWithChecksumTargetFrame){let P=this.injectedScriptManager.getNavigationPromise(C);P&&await P;try{return C.evaluate(_,g)}catch(F){throw console.error("evaluateWithChecksum error",F,_.toString()),F}}async getBestMatchingElementSimilarityScore(_){return this.evaluateWithChecksum(async g=>await window.checksum.testGenerator.getBestMatchingElementSimilarityScore(g),_)}async getInteractableElements(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getInteractableElements())}async getAllInteractableElementsForLastSelectQuery(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getAllInteractableElementsForLastSelectQuery())}async overlayInteractableElementsWithChecksumId(_){return this.evaluateWithChecksum(g=>window.checksum.testGenerator.overlayInteractableElementsWithChecksumId(g),_)}async getGoals(){return await this.evaluateWithChecksum(async()=>window.checksum.goalTracker.getGoals())}async takeElementSnapshot(_,g,C={},P={}){try{let{snapshot:F,elementLocator:M}=await super.takeElementSnapshot(_,g,C);if(!F||!C.takeBodyScreenshot)return F?{snapshot:F}:{};await this.highlightElementByLocator(M,C.mousePosition);let V=await this.takePageSnapshot(P);return await this.clearHighlights(),{snapshot:F,bodySnapshot:V}}catch(F){return console.error("[ChecksumWebDriver] takeElementSnapshot error",F),{}}}async highlightElementByLocator(_,g,C="20px solid rgba(255,0,0,1)",P=!1){return this.evaluateWithChecksum(async([F,M,V,W])=>{window.checksum.testGenerator.highlightElement(F,{highlightStyle:{outline:M},mousePosition:V,scroll:W})},[await _.elementHandle(),C,g,P])}async clearHighlights(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.clearHighlights())}};e(hnr,"ChecksumWebDriver");var ERt=hnr;var EAr=require("fs"),kAr=x7(require("path"));var gnr=require("fs");var ynr=class ynr{constructor(l,_=XS.vtg.localBuildPath){this.page=l;this.filePath=_;this.filePath=_}async start(){try{await this.modifyVTGBuildHtmlFile(),await this.startReactApp(),await WC(2e3)}catch(l){Nh.error("An error occurred:",l)}}async startReactApp(){if(!this.page)throw new Error("Page not initialized");let l=XS.vtg.appURL;await this.page.goto(l,{waitUntil:"networkidle",timeout:6e4})}async modifyVTGBuildHtmlFile(){if(XS.isDevMode){WPt(!0);return}try{let l=await gnr.promises.readFile(this.filePath,"utf8"),_=/(src|href)=(["'])(\/)static/g,g=l.replace(_,"$1=$2.$3static");await gnr.promises.writeFile(this.filePath,g,"utf8"),Nh(`Successfully modified ${this.filePath}`)}catch(l){Nh.error(`Error processing file ${this.filePath}:`,l)}}};e(ynr,"VtgFrontendLauncher");var kRt=ynr;var yFe={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},_ai={defaultMerge:yFe.defaultMerge};function u9n(p,l){return l}e(u9n,"defaultMetaDataUpdater");function l9n(p,l){return p.filter(_=>_!==void 0)}e(l9n,"defaultFilterValues");var vAr;(function(p){p[p.NOT=0]="NOT",p[p.RECORD=1]="RECORD",p[p.ARRAY=2]="ARRAY",p[p.SET=3]="SET",p[p.MAP=4]="MAP",p[p.OTHER=5]="OTHER"})(vAr||(vAr={}));function bAr(p){return typeof p!="object"||p===null?0:Array.isArray(p)?2:_9n(p)?1:p instanceof Set?3:p instanceof Map?4:5}e(bAr,"getObjectType");function p9n(p){let l=new Set;for(let _ of p)for(let g of[...Object.keys(_),...Object.getOwnPropertySymbols(_)])l.add(g);return l}e(p9n,"getKeys");function f9n(p,l){return typeof p=="object"&&Object.prototype.propertyIsEnumerable.call(p,l)}e(f9n,"objectHasProperty");function SAr(p){var g;let l=0,_=(g=p[0])==null?void 0:g[Symbol.iterator]();return{[Symbol.iterator](){return{next(){var C;do{if(_===void 0)return{done:!0,value:void 0};let P=_.next();if(P.done===!0){l+=1,_=(C=p[l])==null?void 0:C[Symbol.iterator]();continue}return{done:!1,value:P.value}}while(!0)}}}}}e(SAr,"getIterableOfIterables");var xAr=["[object Object]","[object Module]"];function _9n(p){if(!xAr.includes(Object.prototype.toString.call(p)))return!1;let{constructor:l}=p;if(l===void 0)return!0;let _=l.prototype;return!(_===null||typeof _!="object"||!xAr.includes(Object.prototype.toString.call(_))||!_.hasOwnProperty("isPrototypeOf"))}e(_9n,"isRecord");function d9n(p,l,_){let g={};for(let C of p9n(p)){let P=[];for(let V of p)f9n(V,C)&&P.push(V[C]);if(P.length===0)continue;let F=l.metaDataUpdater(_,{key:C,parents:p}),M=DAr(P,l,F);M!==yFe.skip&&(C==="__proto__"?Object.defineProperty(g,C,{value:M,configurable:!0,enumerable:!0,writable:!0}):g[C]=M)}return g}e(d9n,"mergeRecords$1");function m9n(p){return p.flat()}e(m9n,"mergeArrays$1");function h9n(p){return new Set(SAr(p))}e(h9n,"mergeSets$1");function g9n(p){return new Map(SAr(p))}e(g9n,"mergeMaps$1");function y9n(p){return p.at(-1)}e(y9n,"mergeOthers$1");var wRt={mergeRecords:d9n,mergeArrays:m9n,mergeSets:h9n,mergeMaps:g9n,mergeOthers:y9n};function TAr(...p){return v9n({})(...p)}e(TAr,"deepmerge");function v9n(p,l){let _=b9n(p,g);function g(...C){return DAr(C,_,l)}return e(g,"customizedDeepmerge"),g}e(v9n,"deepmergeCustom");function b9n(p,l){return{defaultMergeFunctions:wRt,mergeFunctions:{...wRt,...Object.fromEntries(Object.entries(p).filter(([_,g])=>Object.hasOwn(wRt,_)).map(([_,g])=>g===!1?[_,wRt.mergeOthers]:[_,g]))},metaDataUpdater:p.metaDataUpdater??u9n,deepmerge:l,useImplicitDefaultMerging:p.enableImplicitDefaultMerging??!1,filterValues:p.filterValues===!1?void 0:p.filterValues??l9n,actions:yFe}}e(b9n,"getUtils");function DAr(p,l,_){var P;let g=((P=l.filterValues)==null?void 0:P.call(l,p,_))??p;if(g.length===0)return;if(g.length===1)return vnr(g,l,_);let C=bAr(g[0]);if(C!==0&&C!==5){for(let F=1;F<g.length;F++)if(bAr(g[F])!==C)return vnr(g,l,_)}switch(C){case 1:return x9n(g,l,_);case 2:return S9n(g,l,_);case 3:return T9n(g,l,_);case 4:return D9n(g,l,_);default:return vnr(g,l,_)}}e(DAr,"mergeUnknowns");function x9n(p,l,_){let g=l.mergeFunctions.mergeRecords(p,l,_);return g===yFe.defaultMerge||l.useImplicitDefaultMerging&&g===void 0&&l.mergeFunctions.mergeRecords!==l.defaultMergeFunctions.mergeRecords?l.defaultMergeFunctions.mergeRecords(p,l,_):g}e(x9n,"mergeRecords");function S9n(p,l,_){let g=l.mergeFunctions.mergeArrays(p,l,_);return g===yFe.defaultMerge||l.useImplicitDefaultMerging&&g===void 0&&l.mergeFunctions.mergeArrays!==l.defaultMergeFunctions.mergeArrays?l.defaultMergeFunctions.mergeArrays(p):g}e(S9n,"mergeArrays");function T9n(p,l,_){let g=l.mergeFunctions.mergeSets(p,l,_);return g===yFe.defaultMerge||l.useImplicitDefaultMerging&&g===void 0&&l.mergeFunctions.mergeSets!==l.defaultMergeFunctions.mergeSets?l.defaultMergeFunctions.mergeSets(p):g}e(T9n,"mergeSets");function D9n(p,l,_){let g=l.mergeFunctions.mergeMaps(p,l,_);return g===yFe.defaultMerge||l.useImplicitDefaultMerging&&g===void 0&&l.mergeFunctions.mergeMaps!==l.defaultMergeFunctions.mergeMaps?l.defaultMergeFunctions.mergeMaps(p):g}e(D9n,"mergeMaps");function vnr(p,l,_){let g=l.mergeFunctions.mergeOthers(p,l,_);return g===yFe.defaultMerge||l.useImplicitDefaultMerging&&g===void 0&&l.mergeFunctions.mergeOthers!==l.defaultMergeFunctions.mergeOthers?l.defaultMergeFunctions.mergeOthers(p):g}e(vnr,"mergeOthers");var C9n=!0,CAr=void 0,PRt=class PRt extends ERt{constructor(_={},g={devtools:!1},C={},P){var F;super(_,g,PRt.makeSettings(C),P==null?void 0:P.getFramesMessageBroker(),P==null?void 0:P.context());this.liveAppPage=P;this.registeredTimeMachineFrames=[];this.onAppFrameCreated=e(async _=>{this.appFrame=_,this.frameMsgBroker.register("live",this.appFrame,XS.vtg.recordEvents),this.setEvaluateWithChecksumTargetFrame(this.appFrame),await this.injectedScriptManager.addTrackedFrame(this.appFrame)},"onAppFrameCreated");this.timeMachine=new tPe(this.frameMsgBroker,this.injectedScriptManager,{headless:((F=C==null?void 0:C.timeMachine)==null?void 0:F.headless)??!0}),this.liveTimeMachine=new tPe(this.frameMsgBroker,this.injectedScriptManager),this.appViewport=C.viewport}static makeSettings(_={}){return TAr({frontendTestGenerationConfig:{showFrontendLogs:XS.isDevMode,recordOptions:{...CAr?{checkoutEveryNms:CAr}:{},recordCanvas:!0,recordCrossOriginIframes:!0,collectFonts:!0,inlineImages:!0,sampling:{mousemove:!1}}}},_)}get appMainFrame(){return this.appFrame}get tmFrame(){return this.timeMachineFrame}getApplicationViewport(){return this.appViewport}getTimeMachine(){return this.timeMachine}registerTimeMachineFrame(_){this.registeredTimeMachineFrames.push(_)}async prepare(_={}){let g=await super.prepare(_);if(this.frameMsgBroker.register("vtg",this.page.mainFrame()),this.page.on("dialog",()=>{}),this.liveAppPage&&await(await this.page.context().newCDPSession(this.page)).send("Emulation.setDeviceMetricsOverride",{width:0,height:0,deviceScaleFactor:0,mobile:!1}),await new kRt(this.page).start(),this.timeMachineFrame=this.page.frames().find(C=>C.name()==="time-machine-iframe"),this.liveFrame=this.page.frames().find(C=>C.name()==="live-iframe"),C9n){let C;this.liveAppPage?C=this.liveAppPage:(C=await this.context.newPage(),await C.setViewportSize(this.appViewport)),await this.onAppFrameCreated(C.mainFrame())}else await this.interceptPageRequests(),await this.onAppFrameCreated(this.page.frames()[1]);return await this.timeMachine.prepare(this.appFrame,this.timeMachineFrame),await this.liveTimeMachine.prepare(this.appFrame,this.liveFrame),await this.exposeFunctionsForVTG(),g}async exposeFunctionsForVTG(){await this.page.exposeFunction("checksumGetFilesFromLive",async _=>{let g=this.appFrame;if(!g){Nh.info("no live frame detected");return}try{return g.evaluate(C=>window.checksum.testGenerator.filesObserver.getFilesByRrwebId(C),_)}catch(C){Nh.error("Error getting frame window",C)}})}async navigate(_){return this.appFrame.goto(_)}async getCurrentURL(){return this.appFrame.url()}getInjectedScriptInitModules(_){return this.registeredTimeMachineFrames.concat([this.timeMachineFrame,this.liveFrame]).includes(_)?{assertionGenerator:!1,sessionRecorder:!1,filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1}:_===this.appFrame?{...super.getInjectedScriptInitModules(_),filesObserver:!0,nativeDialogObserver:!0,assertionsObserver:!0}:super.getInjectedScriptInitModules(_)}async interceptPageRequests(){async function _(C){try{return await EAr.promises.readFile(C,"utf8")}catch(P){return Nh.error(`Error reading file ${C}:`,P),null}}e(_,"readLocalFile");function g(C){switch(kAr.extname(C).toLowerCase()){case".html":return"text/html";case".js":return"application/javascript";case".css":return"text/css";case".json":return"application/json";case".png":return"image/png";case".jpg":case".jpeg":return"image/jpeg";default:return"application/octet-stream"}}e(g,"getContentType"),await this.page.route("**/*",async C=>{try{let P=C.request().url();if(console.log("intercepted!",P),P.startsWith("file://")){let F=P.replace("file://",""),M=await _(F);M!==null?await C.fulfill({status:200,contentType:g(F),body:M}):await C.abort()}else{let F=0,M=5;for(;F<M;){let V=await C.fetch(),W=V.status();if(W>299&&W<400){F++;let Q=V.headers().location;if(!Q){console.warn("Redirect without Location header"),await C.abort();return}console.log(`Redirect ${F} to: ${Q}`),C.request().url=()=>new URL(Q,P).toString()}else{let Q={};Q["Access-Control-Allow-Origin"]="*",Q["Access-Control-Allow-Methods"]="GET, POST, PUT, DELETE, OPTIONS",Q["Access-Control-Allow-Headers"]="Content-Type, Authorization",await C.fulfill({response:V,headers:{...V.headers(),...Q,"content-security-policy":"","X-Frame-Options":"","x-frame-options":""}});return}}console.warn(`Max redirects (${M}) exceeded`),await C.abort()}}catch(P){console.warn("intercept error",P)}})}};e(PRt,"ChecksumVTGWebDriver");var ARt=PRt;var _it=require("fs");var E9n=".settings.json",bnr=class bnr{constructor(l){this.checksumRoot=l;this.settings={autoLogin:!0,autoRunSteps:!0,autoGenerateThoughts:!0,disableGenerateThoughts:!1,autoGenerateAssertions:!0,disableAutoGenerateAssertions:!1,disableAILocators:!1,optimizeLocators:!0,useOptimizedLocatorDefault:!0};this.settingsFilePath=`${this.checksumRoot}/${E9n}`,this.readSettings()}getSettings(){return{...this.settings,autoGenerateAssertions:XS.vtg.aiAssertions.disabled?!1:this.settings.autoGenerateAssertions,disableAutoGenerateAssertions:XS.vtg.aiAssertions.disabled,disableAILocators:XS.vtg.aiLocators.disabled}}updateSettings(l){this.settings=Object.assign(this.settings,l),this.writeSettingsData()}readSettings(){if(!(0,_it.existsSync)(this.settingsFilePath)){this.writeSettingsData();return}let l=(0,_it.readFileSync)(this.settingsFilePath,"utf-8");this.settings=JSON.parse(l)}writeSettingsData(){(0,_it.writeFileSync)(this.settingsFilePath,JSON.stringify(this.settings,null,2))}};e(bnr,"VtgSettingsService");var NRt=bnr;var zwt=require("fs");var xnr=class xnr{constructor(l,_,g,C,P,F={logPerformance:!1}){this.timeMachine=l;this.actionsManager=_;this.apiService=g;this.userStoryService=C;this.remoteSessionId=P;this.options=F}async generatePromptData(l,_){let g=l.id;if(this.promptData)return{...this.promptData,action:l};let C=this.getActionTimestamps(g,_);if(!C)return;let P=await this.timeMachine.executeReducedHTMLTask(C.before),F=await this.timeMachine.executeReducedHTMLTask(C.after),M=this.userStoryService.getStory();return this.promptData={reducedHTML:F,previousReducedHTML:P,actionId:g,previousActions:this.actionsManager.actions.slice(0,this.actionsManager.actions.length-1),action:l,title:M.goal,steps:M.instructions},this.promptData}async generatePromptDataForThought(l,_){return this.generatePromptData(l,_)}getVariables(){return[]}getVariablesString(l){return""}getActionTimestamps(l,_){let g=this.actionsManager.actions,C=g.findIndex(M=>M.id===l);if(C===-1){Nh(`[init] No action with id ${l} was found in executed actions`);return}let P=g[C],F=g[C+1];return{before:P.timestamp,after:(F==null?void 0:F.timestamp)??_}}logPerformance(l,_){this.options.logPerformance&&console.log(`${l} in`,Date.now()-_,"ms")}};e(xnr,"ActionsAgent");var FRt=xnr;var Snr=class Snr extends XNe{constructor(_,g,C,P,F,M={logPerformance:!1}){super(_,g,C);this.actionsManager=_;this.apiService=g;this.userStoryService=C;this.timeMachine=P;this.webDriver=F;this.options=M;this.activeRemoteSessionIdByStepId=new Map;this.assertionsAgent=new Art(P,_,g,this.remoteSessionId,this.userStoryService),this.actionsAgent=new FRt(P,_,g,this.userStoryService,this.remoteSessionId)}async init({retriesLeft:_=3,keepActionsWithoutDescription:g=!1,lastActionId:C=void 0}={}){await super.init({retriesLeft:_,keepActionsWithoutDescription:g,lastActionId:C}),this.activeRemoteSessionIdByStepId.set(C,this.remoteSessionId)}async generateActionThoughts({action:_,processId:g}){try{if(this.isRunning(_.id))throw Nh.warning("Already generating a thought for this action"),new Error("Already generating a thought for this action");let C=await this.actionsAgent.generatePromptDataForThought(_),P=await this.callThoughtApi("actions",C,g);return this.evaluateThoughtResponse({processId:g,id:_.id,thought:P.thought})}catch(C){return Nh.error("Error in AI thought generation",C),this.evaluateThoughtResponse({processId:g,id:_.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(_.id)}}async generateAssertionThought({assertion:_,parentActionId:g,processId:C}){try{if(this.isRunning(_.id))throw Nh.warning("Already generating a thought for this assertion"),new Error("Already generating a thought for this assertion");let P=await this.assertionsAgent.generateThoughtPromptData(g,_),F=await this.callThoughtApi("assertions",P,C);return this.evaluateThoughtResponse({processId:C,id:_.id,thought:F.thought})}catch(P){return Nh.error("Error in AI thought generation",P),this.evaluateThoughtResponse({processId:C,id:_.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(_.id)}}stopGeneratingThought(_){this.activeRemoteSessionIdByStepId.delete(_)}async callThoughtApi(_,g,C){let P=Date.now();if(g)try{P=Date.now();let F=await this.apiService.post(`${_}/thoughts/generate`,{sessionId:this.remoteSessionId,data:g});if(!F.ok){Nh.error(`Request for ${_} thought generation failed with status ${F.status}`);return}let M=await F.json();if(!(M!=null&&M.thought))throw Nh("No thought generated for action, got response",F),new Error("No thought generated");let V=_==="actions"?g.action:g.assertion;return Nh(`Thought generated (${C})`,{type:_,stepId:V.id,locator:V.locator,thought:M.thought}),M}catch(F){throw Nh.error(`Error in AI thought generation (${C})`,F),F}}isRunning(_){return this.activeRemoteSessionIdByStepId.has(_)}async evaluateThoughtResponse({id:_,processId:g,thought:C,error:P=!1}){try{await this.webDriver.page.evaluate(({id:F,thought:M,error:V,processId:W})=>{window.vtg.onAsyncProcessResponse({id:F,processId:W,thought:M,error:V})},{id:_,thought:C,error:P,processId:g})}catch(F){Nh.error("Error in AI thought generation",F)}}};e(Snr,"VTGThoughtsService");var IRt=Snr;var Tnr=class Tnr{constructor(l=new Utt){this._variableStore=l}get variableStore(){return this._variableStore}};e(Tnr,"VTGVariableStoreService");var ORt=Tnr;var _VtgEvaluatorService=class _VtgEvaluatorService{constructor(p,l){this.variableStoreService=p;this.vtgTestFileMode=l;this.listenerBody=e(async({vtg})=>{await vtg.eval(async(code,callback)=>{try{callback(null,await eval(`(async () => {
1948
1948
  ${code}
1949
- })()`))}catch(p){callback(p,null)}})},"listenerBody")}setPage(p){this.page=p}async execute(p,l={}){return this.vtgTestFileMode?this.executeInPlaywrightTest(p,l):this.executeOnLive(p,l)}get vtgContext(){return{page:this.page,vs:this.variableStoreService.variableStore,expect:IZe.expect,checksumAI:e((p,l)=>l(),"checksumAI")}}async executeOnLive(p,l={}){let _={...this.vtgContext,...l},g=this.wrapCodeInContext(p,_);return await(0,eval)(g)(_)}wrapCodeInContext(p,l){return`(async ({${Object.keys(l).join(", ")}}) => { ${p} })`}async executeInPlaywrightTest(p,l={}){let _=l?this.wrapCodeInContext(p,l)+"(context)":p;return new Promise((g,C)=>{this.listener&&this.listener(_,l,(P,F)=>{P?C(P):g(F)})})}async listenForExecution(p){return new Promise(l=>{this.resolveEvaluator=l,this.listener=p})}stopListening(){this.resolveEvaluator()}getFunctionContentToInject(){return this.listenerBody.toString()}};e(_VtgEvaluatorService,"VtgEvaluatorService");var LRt=_VtgEvaluatorService;var Cnr=class Cnr extends DOt{constructor(_,g=!1){g||(g=!!_.find(C=>C==="--debug"));super(_,g);this.checksumScriptFilePath="node_modules/@checksum-ai/runtime/checksumlib.js";this.vtgMode="start";this.initTimeMachine=e(async()=>{await this.webDriver.tmFrame.evaluate(()=>window.checksum.visualTestGenerator.init(!1))},"initTimeMachine");this.initVtgMode(_),Nh.setLogLevel(g?"all":XS.isDevMode?XS.logLevel:"errors")}async run(_){await this.init(_),this.buildServices(),this.buildServer();let g=await this.getInitialServicesData();g&&this.setServicesData(g),await this.start()}async init(_){await this.patchPlaywright(),this.loadChecksumData(),this.loadPlaywrightConfigForVTG(),this.webDriver=this.buildWebDriver(_),this.webDriver.registerEventListener(this),this.taskTimeMachine=new tPe(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!XS.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0,taskTimeout:XS.vtg.taskTimeMachine.taskTimeout}),this.pageInteractor=new Mtt(this.webDriver.evaluateWithChecksum.bind(this.webDriver),()=>this.webDriver.appMainFrame,this.webDriver.getTimeMachine.bind(this.webDriver),{log:Nh.info,logError:Nh.error},{...this.getTimeoutParams(),waitActionDelay:1e3,testAssetsDir:__dirname,listenToDialog:!0,listenToFileChooser:!1},new Btt(this.config)),this.testAssetsManager=new CRt(this.projectRootDirectory,this.checksumRoot,this.vtgTestFileRunConfig),(XS.vtg.writeLogFile||this.debugMode)&&this.addLogFile()}buildServices(){this.actionsManager=new tMt,this.apiService=new POt(this.config),this.userStoryService=new eMt(this.apiService,this.config),this.variableStoreService=new ORt,this.evaluatorService=new LRt(this.variableStoreService,this.vtgTestFileMode),this.actionsService=new kOt(this.config,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver,this.evaluatorService),this.assertionsService=new qOt(this.webDriver,this.actionsManager,this.evaluatorService),this.locatorsService=new XOt(this.webDriver,this.taskTimeMachine,this.apiService,this.userStoryService,this.evaluatorService),this.aiTestGenerationService=new AOt(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new JOt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver,this.evaluatorService),this.aiThoughtsService=new IRt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new ZLt(this.config,this.userStoryService,this.apiService,this.actionsManager,this.testAssetsManager,this.actionsService,this.vtgTestFileRunConfig,this.evaluatorService),this.settingsService=new NRt(this.checksumRoot),this.actionsManager.setStorageService(this.storageService)}buildServer(){this.reactAppServer=new TRt(this.actionsService,this.assertionsService,this.locatorsService,this.aiTestGenerationService,this.aiAssertionsService,this.aiThoughtsService,this.actionsManager,this.storageService,this.settingsService)}loadPlaywrightConfigForVTG(){try{let _=`${this.checksumRoot}/playwright.config.ts`;if((0,zwt.existsSync)(_)){let g=require(_).default;g&&(this.playwrightConfigForVTG=g)}}catch{console.warn("Could not find playwright config file, will run with defaults")}}async getInitialServicesData(){if(this.vtgMode==="cloud")return this.getInitialServicesDataFromCloud();if(this.vtgMode==="edit")return this.vtgTestFileMode?await this.getInitialServicesDataByInternalTestId():this.getInitialServicesDataFromEditLocationPath()}getInitialServicesDataFromEditLocationPath(){let _=this.storageService.getLocalSavedData(this.editLocationPath);return{actions:_.executedActions,story:_.story,testGenerationData:_.testGenerationData}}async getInitialServicesDataFromCloud(){let g=await(await this.apiService.post(`test-generation/${this.cloudTestGenerationId}/info`)).json(),{actionsDownloadSignedURL:C,story:P,testGenerationData:F}=g,M=await fetch(C,{mode:"cors",credentials:"same-origin",headers:{"Content-Type":"application/json"}});if(!M.ok)throw new Error(`HTTP error! Status: ${M.status}`);let V=await M.json();return{actions:this.addIdsToActionsAndAssertions(V),story:P,testGenerationData:F}}addIdsToActionsAndAssertions(_){return _.map((g,C)=>({...g,id:(0,Dnr.randomUUID)(),assertions:(g.assertions??[]).map(P=>({...P,id:(0,Dnr.randomUUID)()}))}))}async getInitialServicesDataByInternalTestId(){var P,F,M;if(((P=this.vtgTestFileRunConfig)==null?void 0:P.mode)!=="edit")return;let _=[];_=this.storageService.readJsonFile((F=this.vtgTestFileRunConfig)==null?void 0:F.actionsJsonFilePath),_=this.addIdsToActionsAndAssertions(_);let g=await this.apiService.post(`test-generation-by-internal-test-id/${(M=this.vtgTestFileRunConfig)==null?void 0:M.internalTestId}/info`);if(!g.ok)throw new Error(`Error fetching test generation data: ${g.statusText}`);let C=await g.json();return{actions:_,story:C.story,testGenerationData:C.testGenerationData}}setServicesData({actions:_,story:g,testGenerationData:C}){this.actionsManager.setActions(_),this.userStoryService.setStoryInfo(g,C),this.testAssetsManager.setCurrentSaveAsLocation(this.editLocationPath),this.storyId=g.id}async start({createAssetsFolder:_=!0}={}){var P,F;(this.vtgMode==="start"||this.vtgTestFileMode)&&await this.userStoryService.fetchStory(this.storyId),_&&this.testAssetsManager.createTestGenerationAssetsFolders(),this.testAssetsManager.createTestGenerationLocalAutoSaveFolder(this.storyId);let{environment:g}=this.userStoryService.getEnvInfo();await this.webDriver.prepare({baseURL:g.baseURL,shutdown:!this.vtgTestFileMode}),await this.webDriver.addHARMockAPIRecordings(this.testAssetsManager.getHarFilePath()),await this.initTimeMachine(),this.pageInteractor.init(),this.assertionsService.setPage(this.webDriver.appMainFrame.page()),this.actionsService.setPage(this.webDriver.appMainFrame.page()),this.evaluatorService.setPage(this.webDriver.appMainFrame.page()),await this.taskTimeMachine.prepare(this.webDriver.appMainFrame,void 0,M=>this.webDriver.registerTimeMachineFrame(M)),await this.reactAppServer.start(),await this.reactAppServer.evaluateServerPort(this.webDriver.page);let C=(()=>{let M=this.config.environments.find(V=>V.name===g.name);return!M||!M.baseURL?"/":M.baseURL})();this.webDriver.appMainFrame?await this.webDriver.appMainFrame.goto(C,{waitUntil:"domcontentloaded",timeout:0}):Nh.error("Iframe not found"),await this.webDriver.getTimeMachine().toggleTimeMachineHandleEvents(!1),this.vtgMode==="start"&&(await this.actionsService.addInitialLoginAction(),await this.actionsService.addStartURLNavigationAction(),this.vtgTestFileMode&&await this.storageService.saveTestFile()),console.log("VTG is ready",(P=this.userStoryService.getStory())==null?void 0:P.goal),await this.webDriver.page.evaluate(({localSaveFolderPath:M,actions:V,appViewport:W,userStoryGoal:Q,isLoadedFromFile:ae})=>{window.vtg.initClient(M,V,W,this.checksumRuntimeVersion,Q,ae)},{localSaveFolderPath:this.editLocationPath,actions:this.actionsManager.actions,appViewport:this.webDriver.getApplicationViewport(),userStoryGoal:(F=this.userStoryService.getStory())==null?void 0:F.goal,isLoadedFromFile:this.vtgTestFileMode}),this.vtgTestFileMode||await new Promise(()=>{})}getTimeoutParams(){var C,P,F,M;let _=((P=(C=this.playwrightConfigForVTG)==null?void 0:C.use)==null?void 0:P.navigationTimeout)||3e4,g=((M=(F=this.playwrightConfigForVTG)==null?void 0:F.use)==null?void 0:M.actionTimeout)||5e3;return{navigationTimeout:_,actionTimeout:g}}getPlaywrightProxySettings(){var F,M;let _=(M=(F=this.playwrightConfigForVTG)==null?void 0:F.use)==null?void 0:M.proxy,{server:g,username:C,password:P}=_||{};if(C&&P&&g)return{username:C,password:P,server:g}}getPlaywrightViewportSettings(){var C,P;let{width:_=1280,height:g=720}=((P=(C=this.playwrightConfigForVTG)==null?void 0:C.use)==null?void 0:P.viewport)||{};return{width:_,height:g}}buildWebDriver(_){var P;let g=this.getPlaywrightProxySettings(),C=this.getPlaywrightViewportSettings();return new ARt({scriptSource:XS.checksumScript.source,scriptURL:XS.checksumScript.url,scriptFile:XS.checksumScript.path,isScriptFileAbsolute:!0,fullScreenResolution:!1,hostWindowViewport:!0,baseURL:(P=this.config.environments.find(F=>F.default))==null?void 0:P.baseURL,useProxy:!!g,webProxy:g,disableWebSecurity:!0,allowFileAccess:!0,remoteDebugging:XS.vtg.remoteDebugging},{devtools:!1,headless:!1},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"},viewport:C},_)}async onWebDriverContextClose(){var _,g,C;this.evaluatorService.stopListening(),(_=this.vtgTestFileRunConfig)!=null&&_.evalFilePath&&(0,zwt.rmSync)((g=this.vtgTestFileRunConfig)==null?void 0:g.evalFilePath,{force:!0}),this.vtgTestFileRunConfig.mode==="edit"&&(0,zwt.rmSync)((C=this.vtgTestFileRunConfig)==null?void 0:C.actionsJsonFilePath,{force:!0})}initVtgMode(_){var P;let g=_.indexOf("--edit"),C=_.indexOf("--cloud");if(_.indexOf("--test-file")!==-1){this.vtgTestFileMode=!0,this.vtgTestFileRunConfig=JSON.parse(process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG),this.vtgMode=this.vtgTestFileRunConfig.mode,this.storyId=((P=this.vtgTestFileRunConfig)==null?void 0:P.mode)==="start"?this.vtgTestFileRunConfig.storyId:void 0;return}g!==-1&&(this.vtgMode="edit",this.editLocationPath=_.at(g+1)),C!==-1&&(this.vtgMode="cloud",this.cloudTestGenerationId=_.at(C+1)),this.vtgMode==="start"&&(this.storyId=_[0])}addLogFile(){let _=require("fs"),g=`${this.testAssetsManager.getLogsPath()}/vtg_${new Date().toISOString()}.log`;_.existsSync(this.testAssetsManager.getLogsPath())||_.mkdirSync(this.testAssetsManager.getLogsPath(),{recursive:!0}),Nh.addLogListener({onLog:e((...C)=>{let P=C.map(F=>{if(typeof F=="object")try{return JSON.stringify(F,null,2)}catch{}return String(F)}).join(" ")+`
1949
+ })()`))}catch(p){callback(p,null)}})},"listenerBody")}setPage(p){this.page=p}async execute(p,l={}){return this.vtgTestFileMode?this.executeInPlaywrightTest(p,l):this.executeOnLive(p,l)}get vtgContext(){return{page:this.page,vs:this.variableStoreService.variableStore,expect:IZe.expect,checksumAI:e((p,l)=>l(),"checksumAI")}}async executeOnLive(p,l={}){let _={...this.vtgContext,...l},g=this.wrapCodeInContext(p,_);return await(0,eval)(g)(_)}wrapCodeInContext(p,l){return`(async ({${Object.keys(l).join(", ")}}) => { ${p} })`}async executeInPlaywrightTest(p,l={}){let _=l?this.wrapCodeInContext(p,l)+"(context)":p;return new Promise((g,C)=>{this.listener&&this.listener(_,l,(P,F)=>{P?C(P):g(F)})})}async listenForExecution(p){return new Promise(l=>{this.resolveEvaluator=l,this.listener=p})}stopListening(){var p;(p=this.resolveEvaluator)==null||p.call(this)}getFunctionContentToInject(){return this.listenerBody.toString()}};e(_VtgEvaluatorService,"VtgEvaluatorService");var LRt=_VtgEvaluatorService;var Cnr=class Cnr extends DOt{constructor(_,g=!1){g||(g=!!_.find(C=>C==="--debug"));super(_,g);this.checksumScriptFilePath="node_modules/@checksum-ai/runtime/checksumlib.js";this.vtgMode="start";this.initTimeMachine=e(async()=>{await this.webDriver.tmFrame.evaluate(()=>window.checksum.visualTestGenerator.init(!1))},"initTimeMachine");this.initVtgMode(_),Nh.setLogLevel(g?"all":XS.isDevMode?XS.logLevel:"errors")}async run(_){await this.init(_),this.buildServices(),this.buildServer();let g=await this.getInitialServicesData();g&&this.setServicesData(g),await this.start()}async init(_){await this.patchPlaywright(),this.loadChecksumData(),this.loadPlaywrightConfigForVTG(),this.webDriver=this.buildWebDriver(_),this.webDriver.registerEventListener(this),this.taskTimeMachine=new tPe(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!XS.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0,taskTimeout:XS.vtg.taskTimeMachine.taskTimeout}),this.pageInteractor=new Mtt(this.webDriver.evaluateWithChecksum.bind(this.webDriver),()=>this.webDriver.appMainFrame,this.webDriver.getTimeMachine.bind(this.webDriver),{log:Nh.info,logError:Nh.error},{...this.getTimeoutParams(),waitActionDelay:1e3,testAssetsDir:__dirname,listenToDialog:!0,listenToFileChooser:!1},new Btt(this.config)),this.testAssetsManager=new CRt(this.projectRootDirectory,this.checksumRoot,this.vtgTestFileRunConfig),(XS.vtg.writeLogFile||this.debugMode)&&this.addLogFile()}buildServices(){this.actionsManager=new tMt,this.apiService=new POt(this.config),this.userStoryService=new eMt(this.apiService,this.config),this.variableStoreService=new ORt,this.evaluatorService=new LRt(this.variableStoreService,this.vtgTestFileMode),this.actionsService=new kOt(this.config,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver,this.evaluatorService),this.assertionsService=new qOt(this.webDriver,this.actionsManager,this.evaluatorService),this.locatorsService=new XOt(this.webDriver,this.taskTimeMachine,this.apiService,this.userStoryService,this.evaluatorService),this.aiTestGenerationService=new AOt(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new JOt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver,this.evaluatorService),this.aiThoughtsService=new IRt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new ZLt(this.config,this.userStoryService,this.apiService,this.actionsManager,this.testAssetsManager,this.actionsService,this.vtgTestFileRunConfig,this.evaluatorService),this.settingsService=new NRt(this.checksumRoot),this.actionsManager.setStorageService(this.storageService)}buildServer(){this.reactAppServer=new TRt(this.actionsService,this.assertionsService,this.locatorsService,this.aiTestGenerationService,this.aiAssertionsService,this.aiThoughtsService,this.actionsManager,this.storageService,this.settingsService)}loadPlaywrightConfigForVTG(){try{let _=`${this.checksumRoot}/playwright.config.ts`;if((0,zwt.existsSync)(_)){let g=require(_).default;g&&(this.playwrightConfigForVTG=g)}}catch{console.warn("Could not find playwright config file, will run with defaults")}}async getInitialServicesData(){if(this.vtgMode==="cloud")return this.getInitialServicesDataFromCloud();if(this.vtgMode==="edit")return this.vtgTestFileMode?await this.getInitialServicesDataByInternalTestId():this.getInitialServicesDataFromEditLocationPath()}getInitialServicesDataFromEditLocationPath(){let _=this.storageService.getLocalSavedData(this.editLocationPath);return{actions:_.executedActions,story:_.story,testGenerationData:_.testGenerationData}}async getInitialServicesDataFromCloud(){let g=await(await this.apiService.post(`test-generation/${this.cloudTestGenerationId}/info`)).json(),{actionsDownloadSignedURL:C,story:P,testGenerationData:F}=g,M=await fetch(C,{mode:"cors",credentials:"same-origin",headers:{"Content-Type":"application/json"}});if(!M.ok)throw new Error(`HTTP error! Status: ${M.status}`);let V=await M.json();return{actions:this.addIdsToActionsAndAssertions(V),story:P,testGenerationData:F}}addIdsToActionsAndAssertions(_){return _.map((g,C)=>({...g,id:(0,Dnr.randomUUID)(),assertions:(g.assertions??[]).map(P=>({...P,id:(0,Dnr.randomUUID)()}))}))}async getInitialServicesDataByInternalTestId(){var P,F,M;if(((P=this.vtgTestFileRunConfig)==null?void 0:P.mode)!=="edit")return;let _=[];_=this.storageService.readJsonFile((F=this.vtgTestFileRunConfig)==null?void 0:F.actionsJsonFilePath),_=this.addIdsToActionsAndAssertions(_);let g=await this.apiService.post(`test-generation-by-internal-test-id/${(M=this.vtgTestFileRunConfig)==null?void 0:M.internalTestId}/info`);if(!g.ok)throw new Error(`Error fetching test generation data: ${g.statusText}`);let C=await g.json();return{actions:_,story:C.story,testGenerationData:C.testGenerationData}}setServicesData({actions:_,story:g,testGenerationData:C}){this.actionsManager.setActions(_),this.userStoryService.setStoryInfo(g,C),this.testAssetsManager.setCurrentSaveAsLocation(this.editLocationPath),this.storyId=g.id}async start({createAssetsFolder:_=!0}={}){var P,F;(this.vtgMode==="start"||this.vtgTestFileMode)&&await this.userStoryService.fetchStory(this.storyId),_&&this.testAssetsManager.createTestGenerationAssetsFolders(),this.testAssetsManager.createTestGenerationLocalAutoSaveFolder(this.storyId);let{environment:g}=this.userStoryService.getEnvInfo();await this.webDriver.prepare({baseURL:g.baseURL,shutdown:!this.vtgTestFileMode}),await this.webDriver.addHARMockAPIRecordings(this.testAssetsManager.getHarFilePath()),await this.initTimeMachine(),this.pageInteractor.init(),this.assertionsService.setPage(this.webDriver.appMainFrame.page()),this.actionsService.setPage(this.webDriver.appMainFrame.page()),this.evaluatorService.setPage(this.webDriver.appMainFrame.page()),await this.taskTimeMachine.prepare(this.webDriver.appMainFrame,void 0,M=>this.webDriver.registerTimeMachineFrame(M)),await this.reactAppServer.start(),await this.reactAppServer.evaluateServerPort(this.webDriver.page);let C=(()=>{let M=this.config.environments.find(V=>V.name===g.name);return!M||!M.baseURL?"/":M.baseURL})();this.webDriver.appMainFrame?await this.webDriver.appMainFrame.goto(C,{waitUntil:"domcontentloaded",timeout:0}):Nh.error("Iframe not found"),await this.webDriver.getTimeMachine().toggleTimeMachineHandleEvents(!1),this.vtgMode==="start"&&(await this.actionsService.addInitialLoginAction(),await this.actionsService.addStartURLNavigationAction(),this.vtgTestFileMode&&await this.storageService.saveTestFile()),console.log("VTG is ready",(P=this.userStoryService.getStory())==null?void 0:P.goal),await this.webDriver.page.evaluate(({localSaveFolderPath:M,actions:V,appViewport:W,userStoryGoal:Q,isLoadedFromFile:ae})=>{window.vtg.initClient(M,V,W,this.checksumRuntimeVersion,Q,ae)},{localSaveFolderPath:this.editLocationPath,actions:this.actionsManager.actions,appViewport:this.webDriver.getApplicationViewport(),userStoryGoal:(F=this.userStoryService.getStory())==null?void 0:F.goal,isLoadedFromFile:this.vtgTestFileMode}),this.vtgTestFileMode||await new Promise(()=>{})}getTimeoutParams(){var C,P,F,M;let _=((P=(C=this.playwrightConfigForVTG)==null?void 0:C.use)==null?void 0:P.navigationTimeout)||3e4,g=((M=(F=this.playwrightConfigForVTG)==null?void 0:F.use)==null?void 0:M.actionTimeout)||5e3;return{navigationTimeout:_,actionTimeout:g}}getPlaywrightProxySettings(){var F,M;let _=(M=(F=this.playwrightConfigForVTG)==null?void 0:F.use)==null?void 0:M.proxy,{server:g,username:C,password:P}=_||{};if(C&&P&&g)return{username:C,password:P,server:g}}getPlaywrightViewportSettings(){var C,P;let{width:_=1280,height:g=720}=((P=(C=this.playwrightConfigForVTG)==null?void 0:C.use)==null?void 0:P.viewport)||{};return{width:_,height:g}}buildWebDriver(_){var P;let g=this.getPlaywrightProxySettings(),C=this.getPlaywrightViewportSettings();return new ARt({scriptSource:XS.checksumScript.source,scriptURL:XS.checksumScript.url,scriptFile:XS.checksumScript.path,isScriptFileAbsolute:!0,fullScreenResolution:!1,hostWindowViewport:!0,baseURL:(P=this.config.environments.find(F=>F.default))==null?void 0:P.baseURL,useProxy:!!g,webProxy:g,disableWebSecurity:!0,allowFileAccess:!0,remoteDebugging:XS.vtg.remoteDebugging},{devtools:!1,headless:!1},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"},viewport:C},_)}async onWebDriverContextClose(){var _,g,C;this.evaluatorService.stopListening(),(_=this.vtgTestFileRunConfig)!=null&&_.evalFilePath&&(0,zwt.rmSync)((g=this.vtgTestFileRunConfig)==null?void 0:g.evalFilePath,{force:!0}),this.vtgTestFileRunConfig.mode==="edit"&&(0,zwt.rmSync)((C=this.vtgTestFileRunConfig)==null?void 0:C.actionsJsonFilePath,{force:!0})}initVtgMode(_){var P;let g=_.indexOf("--edit"),C=_.indexOf("--cloud");if(_.indexOf("--test-file")!==-1){this.vtgTestFileMode=!0,this.vtgTestFileRunConfig=JSON.parse(process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG),this.vtgMode=this.vtgTestFileRunConfig.mode,this.storyId=((P=this.vtgTestFileRunConfig)==null?void 0:P.mode)==="start"?this.vtgTestFileRunConfig.storyId:void 0;return}g!==-1&&(this.vtgMode="edit",this.editLocationPath=_.at(g+1)),C!==-1&&(this.vtgMode="cloud",this.cloudTestGenerationId=_.at(C+1)),this.vtgMode==="start"&&(this.storyId=_[0])}addLogFile(){let _=require("fs"),g=`${this.testAssetsManager.getLogsPath()}/vtg_${new Date().toISOString()}.log`;_.existsSync(this.testAssetsManager.getLogsPath())||_.mkdirSync(this.testAssetsManager.getLogsPath(),{recursive:!0}),Nh.addLogListener({onLog:e((...C)=>{let P=C.map(F=>{if(typeof F=="object")try{return JSON.stringify(F,null,2)}catch{}return String(F)}).join(" ")+`
1950
1950
  `;try{_.appendFile(g,P,F=>{F&&console.error(F)})}catch{}},"onLog")})}async eval(_){return this.evaluatorService.listenForExecution(_)}};e(Cnr,"VisualTestGenerator");var MRt=Cnr;var Enr={},wAr=e((p,l,_={},g=!1)=>{let{runMode:C,environments:P}=l,F=process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG?{trace:"off",video:"off",screenshot:"off"}:{},M=p.extend({...F,codeMirror:[async({},W)=>{let Q=await cFt.init(C,{generateAssertionCode:e(()=>"","generateAssertionCode")});await W(Q)},{scope:"worker"}],monitorBridge:[async({},W,Q)=>{let ae=new uFt(Q);await W(ae)},{scope:"worker"}],variableStore:e(async({},W)=>{let Q=new Utt;await W(Q)},"variableStore"),vs:e(async({variableStore:W},Q)=>{await Q(W)},"vs"),variablesStore:e(async({variableStore:W},Q)=>{await Q(W)},"variablesStore"),analytics:e(async({},W)=>{let Q=Srt.getInstance({},XS.testRun.monitoring.segment,{logToConsole:l.options.printLogs}),ae=process.env.CHECKSUM_TEST_SUITE_ID;ae?await Q.identify(ae,{},!0):Q.setIsolatedMode(),await W(Q)},"analytics"),launchOptions:e(async({launchOptions:W},Q)=>{await Q({...W,args:[...W.args??[],..._.useMockData?["--disable-web-security"]:[]]})},"launchOptions"),page:e(async({page:W,codeMirror:Q,monitorBridge:ae,variableStore:G,analytics:_e},ne,ue)=>{let qe=await oFt.init(W,_e,Q,ae,G,ue,w9n(ue),M,l,g);Object.defineProperty(qe.constructor,"name",{value:"Page"}),await ne(qe),await qe.shutdown(),await qe.onTestComplete(ue.status==="passed")},"page"),vtg:e(async({page:W},Q)=>{if(!process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG)Q(null);else{let ae=new MRt(["--test-file"]);await ae.run(W),await Q(ae)}},"vtg")}),V=P.find(W=>W.default);return M.use({baseURL:V.baseURL,bypassCSP:!0}),{test:M,defineChecksumTest:k9n}},"createChecksumTestExtension"),k9n=e((p,l)=>{let g=new Error().stack.split(`
1951
1951
  `).filter(C=>C.includes(".checksum.spec.ts"))[0];if(!g)throw new Error("Could not locate test location. Make sure test is run from valid checksum test file");return Enr[g]=l,p},"defineChecksumTest");function w9n(p){let{file:l,line:_}=p,g=Object.keys(Enr).filter(P=>P.trim().includes(l.trim()));if(!g.length)return;let C=4;for(let P=0;P<C;P++)for(let F of g){let M;try{M=parseInt(F.split(":").reverse()[1])}catch{continue}if(M-P===parseInt(_))return Enr[F]}}e(w9n,"getCurrentTestIdFromMapping");var knr=class knr{constructor(l,_,g=!1,C={}){this.page=l;this.soft=g;this.configuration=C;this.fallbackEnabled=!1;this.withChecksumAI=!1;this.withChecksumAIMatcher=e(async()=>{throw this.withChecksumAI=!0,new Error},"withChecksumAIMatcher");this.setThought(_)}setThought(l){var _,g;l&&(this.checksumAIThought=this.page.addNewThought(l,"assertion"),(g=(_=this.page.getRuntimeOptions())==null?void 0:_.useChecksumAI)!=null&&g.assertions&&(this.page.setAIFallback(l),this.fallbackEnabled=!0))}get(l,_,g){if(typeof _!="string")return l[_];if(_==="checksumAI")return C=>(this.setThought(C),g);if(_==="withChecksumAI"||typeof l[_]=="function"){let C=_==="withChecksumAI"?this.withChecksumAIMatcher:l[_];return(...P)=>this.checksumAIThought?this.executeMatcherWithinStep(C,l,...P):this.executeMatcher(C,l,...P)}else{let C=l[_];return new Proxy(C,this)}}findNestedErrors(l,_){l.error&&l.infectParentStepsWithError&&_.push(l.error);for(let g of l.steps)this.findNestedErrors(g,_)}async callMatcher(l,_,...g){this.beforeMatcherCall();let C=l.call(_,...g),P=C instanceof Promise?await C:C;if(this.step){let F=[];if(this.step.error?F.push(this.step.error):this.findNestedErrors(this.step,F),F.length)throw F[0]}return P}executeMatcherWithinStep(l,_,...g){return this.page.step(this.checksumAIThought.thought,()=>this.callMatcher(l,_,...g).catch(this.onMatcherFailure.bind(this)),!1,{obtainStep:e(C=>this.step=C,"obtainStep")}).catch(C=>{if(!this.soft&&!(this.withChecksumAI&&C.message===hNe))throw C}).finally(this.afterMatcherExecute.bind(this))}async executeMatcher(l,_,...g){try{return await this.callMatcher(l,_,...g)}catch(C){await this.onMatcherFailure(C)}finally{this.afterMatcherExecute()}}beforeMatcherCall(){this.page.setExpectConfiguration(this.configuration)}afterMatcherExecute(){this.checksumAIThought=void 0,this.fallbackEnabled=!1,this.withChecksumAI=!1,this.page.resetFallbacks(),this.page.setExpectConfiguration(void 0)}async onMatcherFailure(l){var _,g;if(!this.fallbackEnabled)throw gT("[onMatcherFailure] fallback disabled, continuing with error."),this.page.analytics.assertionFailure((_=this.checksumAIThought)==null?void 0:_.thought,l.message,(g=l.matcherResult)==null?void 0:g.name),l;gT("[onMatcherFailure] initiating fallback sequence with thought:",this.checksumAIThought.thought);try{await this.page.initiateFallbackSequence({type:"assertion",error:l,withChecksumAI:this.withChecksumAI})}catch(C){if(this.soft)return;throw C}throw this.soft=!0,this.page.testInfo.status="failed",l}};e(knr,"ExpectCallProxyHandler");var RRt=knr;var jRt=class jRt{constructor(l=void 0,_={}){this.page=l;this.configuration=_}get(l,_){return _==="setPage"?g=>{this.page=g}:_==="extend"?(...g)=>{let C=l.extend(...g);return new Proxy(C,this)}:_==="configure"?g=>{let C=l.configure(g);return new Proxy(C,new jRt(this.page,{...this.configuration,...g}))}:_==="soft"?(...g)=>{let C=this.manipulateArgsAndExtractThought(g),P=l.soft(...g);return new Proxy(P,this.makeExpectCallProxyHandler(C,!0))}:_==="poll"?(...g)=>{let C=this.manipulateArgsAndExtractThought(g),P=l.poll(...g);return new Proxy(P,this.makeExpectCallProxyHandler(C))}:l[_]instanceof Function?l[_].bind(l):l[_]}apply(l,_,g){let C=this.manipulateArgsAndExtractThought(g),P=l.apply(_,g);return new Proxy(P,this.makeExpectCallProxyHandler(C))}makeExpectCallProxyHandler(l,_){var g;return new RRt(this.page,l,_===!0?!0:(g=this.configuration)==null?void 0:g.soft,this.configuration)}manipulateArgsAndExtractThought(l){let _,g=l[1];if(typeof g=="string")_=g,l[1]=void 0;else if(typeof g=="object"){if(g.checksumAI===!1){l[1].checksumAI=void 0;return}g.checksumAI&&typeof g.checksumAI=="string"?(_=g.checksumAI,l[1].checksumAI=void 0):g.message&&(_=g.message,l[1].message=void 0)}return _}};e(jRt,"ExpectProxyHandler");var BRt=jRt;var qRt=class qRt{constructor(l){this.expect=l;this.proxy=new Proxy(this.expect,new BRt)}static init(l){return new qRt(l).proxy}};e(qRt,"ChecksumExpect");var JRt=qRt;var AAr=require("@playwright/test");function A9n(p){let l=B_r(),{options:_,apiKey:g,environments:C}=l,P=C.find(_e=>_e.default);if(!P)throw new Error("No default environment found. Please set the default field to true on one of the environments in the checksum.config.ts file.");if(!P.baseURL)throw new Error("A baseURL is required. Please set the baseURL field in the default environment in the checksum.config.ts file.");if(!P.users.find(_e=>_e.default))throw new Error("A default user within the default environment is required. Please set one of the default environment users as default in the checksum.config.ts file.");if(!g)throw new Error("An API key is required. Please set the apiKey field in the checksum.config.ts file.");let M=process.env.CHECKSUM_REPL==="true",{test:V,defineChecksumTest:W}=wAr(p??AAr.test,l,_,M),Q=JRt.init(V.expect),ae=P9n();V._checksum={expect:Q,checksumAI:ae},M&&(console.log("Detected REPL mode"),V.beforeEach(async()=>{V.setTimeout(0)}),V.afterEach(async()=>{for(;;)await WC(1e3)}));let G=e(({name:_e,userRole:ne})=>{let{environment:ue,user:qe}=RCt(l,{environment:_e,role:ne},!0),Xe=R_r({config:l,throwIfEnvInfoInvalid:!0},{environmentName:ue.name,userRole:qe.role});return{environment:ue,user:qe,login:Xe}},"getEnvironment");return{test:V,expect:Q,login:U9e({config:l}),defineChecksumTest:W,getEnvironment:G,checksumAI:ae}}e(A9n,"init");var PAr=e(p=>new Proxy(p,{apply:e(function(_,g,C){return _.page.checksumAI(C[0],C[1],_.options)},"apply"),get:e(function(_,g){return g==="withDialog"?(_.options.withDialog=!0,PAr(p)):_[g]},"get"),set:e(function(_,g,C){if(g==="page")return _[g]=C},"set")}),"makeChecksumAIProxy"),P9n=e(()=>{let p=e(function(){},"func");return p.page=void 0,p.options={withDialog:!1,withTomer:!1},PAr(p)},"makeChecksumAI");0&&(module.exports={RunMode,getChecksumConfig,getLogin,init});
1952
1952
  /*! Bundled license information: