@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/.env CHANGED
@@ -1 +1 @@
1
- BUILD_TIME=2025-03-07T17:35:52.440Z
1
+ BUILD_TIME=2025-03-09T09:07:08.811Z
package/cli.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(cAn,"createHtmlDocument");function uAn(){return e(function(){this.error(404)},"notFound")}e(uAn,"createNotFoundDirectoryListener");function lAn(){return e(function(p){if(this.hasTrailingSlash()){this.error(404);return}var d=brr.original(this.req);d.path=null,d.pathname=oAn(d.pathname+"/");var y=rAn(aAn.format(d)),E=cAn("Redirecting","Redirecting to "+nAn(y));p.statusCode=301,p.setHeader("Content-Type","text/html; charset=UTF-8"),p.setHeader("Content-Length",Buffer.byteLength(E)),p.setHeader("Content-Security-Policy","default-src 'none'"),p.setHeader("X-Content-Type-Options","nosniff"),p.setHeader("Location",y),p.end(E)},"redirect")}e(lAn,"createRedirectDirectoryListener")});var D5r=es((hce,T5r)=>{"use strict";var zMt=xtr(),pAn=require("events").EventEmitter,v5r=aEr(),b5r=wwr(),fAn=Itr(),_An=Ltr(),x5r=e5r(),S5r=h5r();hce=T5r.exports=dAn;function dAn(){var l=e(function(p,d,y){l.handle(p,d,y)},"app");return v5r(l,pAn.prototype,!1),v5r(l,b5r,!1),l.request=Object.create(x5r,{app:{configurable:!0,enumerable:!0,writable:!0,value:l}}),l.response=Object.create(S5r,{app:{configurable:!0,enumerable:!0,writable:!0,value:l}}),l.init(),l}e(dAn,"createApplication");hce.application=b5r;hce.request=x5r;hce.response=S5r;hce.Route=fAn;hce.Router=_An;hce.json=zMt.json;hce.query=Vtr();hce.raw=zMt.raw;hce.static=y5r();hce.text=zMt.text;hce.urlencoded=zMt.urlencoded;var mAn=["bodyParser","compress","cookieSession","session","logger","cookieParser","favicon","responseTime","errorHandler","timeout","methodOverride","vhost","csrf","directory","limit","multipart","staticCache"];mAn.forEach(function(l){Object.defineProperty(hce,l,{get:e(function(){throw new Error("Most middleware (like "+l+") is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.")},"get"),configurable:!0})})});var E5r=es((Fni,C5r)=>{"use strict";C5r.exports=D5r()});var A5r=es((Ini,w5r)=>{"use strict";var k5r=Object.getOwnPropertySymbols,hAn=Object.prototype.hasOwnProperty,gAn=Object.prototype.propertyIsEnumerable;function yAn(l){if(l==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(l)}e(yAn,"toObject");function vAn(){try{if(!Object.assign)return!1;var l=new String("abc");if(l[5]="de",Object.getOwnPropertyNames(l)[0]==="5")return!1;for(var p={},d=0;d<10;d++)p["_"+String.fromCharCode(d)]=d;var y=Object.getOwnPropertyNames(p).map(function(N){return p[N]});if(y.join("")!=="0123456789")return!1;var E={};return"abcdefghijklmnopqrst".split("").forEach(function(N){E[N]=N}),Object.keys(Object.assign({},E)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}e(vAn,"shouldUseNative");w5r.exports=vAn()?Object.assign:function(l,p){for(var d,y=yAn(l),E,N=1;N<arguments.length;N++){d=Object(arguments[N]);for(var F in d)hAn.call(d,F)&&(y[F]=d[F]);if(k5r){E=k5r(d);for(var R=0;R<E.length;R++)gAn.call(d,E[R])&&(y[E[R]]=d[E[R]])}}return y}});var N5r=es((Lni,P5r)=>{(function(){"use strict";var l=A5r(),p=yrr(),d={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function y(ne){return typeof ne=="string"||ne instanceof String}e(y,"isString");function E(ne,le){if(Array.isArray(le)){for(var Ue=0;Ue<le.length;++Ue)if(E(ne,le[Ue]))return!0;return!1}else return y(le)?ne===le:le instanceof RegExp?le.test(ne):!!le}e(E,"isOriginAllowed");function N(ne,le){var Ue=le.headers.origin,Xe=[],rt;return!ne.origin||ne.origin==="*"?Xe.push([{key:"Access-Control-Allow-Origin",value:"*"}]):y(ne.origin)?(Xe.push([{key:"Access-Control-Allow-Origin",value:ne.origin}]),Xe.push([{key:"Vary",value:"Origin"}])):(rt=E(Ue,ne.origin),Xe.push([{key:"Access-Control-Allow-Origin",value:rt?Ue:!1}]),Xe.push([{key:"Vary",value:"Origin"}])),Xe}e(N,"configureOrigin");function F(ne){var le=ne.methods;return le.join&&(le=ne.methods.join(",")),{key:"Access-Control-Allow-Methods",value:le}}e(F,"configureMethods");function R(ne){return ne.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}e(R,"configureCredentials");function V(ne,le){var Ue=ne.allowedHeaders||ne.headers,Xe=[];return Ue?Ue.join&&(Ue=Ue.join(",")):(Ue=le.headers["access-control-request-headers"],Xe.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),Ue&&Ue.length&&Xe.push([{key:"Access-Control-Allow-Headers",value:Ue}]),Xe}e(V,"configureAllowedHeaders");function H(ne){var le=ne.exposedHeaders;if(le)le.join&&(le=le.join(","));else return null;return le&&le.length?{key:"Access-Control-Expose-Headers",value:le}:null}e(H,"configureExposedHeaders");function Q(ne){var le=(typeof ne.maxAge=="number"||ne.maxAge)&&ne.maxAge.toString();return le&&le.length?{key:"Access-Control-Max-Age",value:le}:null}e(Q,"configureMaxAge");function se(ne,le){for(var Ue=0,Xe=ne.length;Ue<Xe;Ue++){var rt=ne[Ue];rt&&(Array.isArray(rt)?se(rt,le):rt.key==="Vary"&&rt.value?p(le,rt.value):rt.value&&le.setHeader(rt.key,rt.value))}}e(se,"applyHeaders");function G(ne,le,Ue,Xe){var rt=[],Tt=le.method&&le.method.toUpperCase&&le.method.toUpperCase();Tt==="OPTIONS"?(rt.push(N(ne,le)),rt.push(R(ne,le)),rt.push(F(ne,le)),rt.push(V(ne,le)),rt.push(Q(ne,le)),rt.push(H(ne,le)),se(rt,Ue),ne.preflightContinue?Xe():(Ue.statusCode=ne.optionsSuccessStatus,Ue.setHeader("Content-Length","0"),Ue.end())):(rt.push(N(ne,le)),rt.push(R(ne,le)),rt.push(H(ne,le)),se(rt,Ue),Xe())}e(G,"cors");function _e(ne){var le=null;return typeof ne=="function"?le=ne:le=e(function(Ue,Xe){Xe(null,ne)},"optionsCallback"),e(function(Xe,rt,Tt){le(Xe,function(Nt,er){if(Nt)Tt(Nt);else{var jt=l({},d,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"),P5r.exports=_e})()});var kPt="checksum";var HUt=(V=>(V.UploadsCompleteWithErrors="uploads-complete-with-errors",V.UploadsComplete="uploads-complete",V.ReportComplete="report-complete",V.UploadProgress="upload-progress",V.Log="log",V.Trace="trace",V.PlaywrightConfig="playwrightConfig",V.Port="port",V))(HUt||{});var $V=x7(require("path")),J9e=require("fs");var GUt=(y=>(y.Alert="alert",y.Confirm="confirm",y.Prompt="prompt",y))(GUt||{});var aA=e(l=>new Promise(p=>setTimeout(p,l)),"awaitSleep"),Dj=e(async(l,p=1e3,d)=>{if(p===null)return l;let y="guard-timed-out",E=e(async()=>(await aA(p+1e3),y),"guard"),N=await Promise.race([l,E()]);if(typeof N=="string"&&N===y)throw typeof d=="function"?new Error(d()):new Error(d??"guardReturnTimedOut");return N},"guardReturn");function xCt(l=5,p="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"){let d="";for(let y=l;y>0;--y)d+=p[Math.floor(Math.random()*p.length)];return d}e(xCt,"randomString");function KUt(l){return!!l&&!["navigation","keystroke","wait","get_more_items","custom_code","native_accept","native_dismiss","login"].includes(l)}e(KUt,"isActionOnElement");function Wfr(l){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}[l]}e(Wfr,"getActionEventCode");var J0e=e((l,p="page")=>p+"."+wPt(l,p),"injectBaseToLocatorString"),wPt=e((l,p="page")=>l.replace(".and(locator(",`.and(${p}.locator(`).replace(".or(locator(",`.or(${p}.locator(`),"injectBaseToLogicalLocatorString");async function Kfr(l,p){let y=e(()=>{let V=xen(l,p);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 ${p}`)},"getFilePath")(),{ungzip:E}=Gfr(),N=await E((0,J9e.readFileSync)(y)),F=JSON.parse(N),R=Object.keys(F);return R.length>0&&!F[R[0]].esraMetadata?R.reduce((V,H)=>({...V,[H]:{esraMetadata:F[H]}}),{}):F}e(Kfr,"getMetadataForTestId");function xen(l,p){return $V.join(Sen(l),`${p}.checksum.data`)}e(xen,"getMetadataFilePath");function Sen(l){return $V.join(Yfr(l),"esra")}e(Sen,"getMetadataFolderPath");function Yfr(l){return $V.join(l,"test-data")}e(Yfr,"getTestDataPath");var Xfr=e((l,p,d)=>{if(!p)return l;if(!d||!d.length)return l.locator(p);let y=l.frameLocator(d[0]);for(let E of d.slice(1))y=y.frameLocator(E);return y.locator(p)},"makeLocator");function YUt(){return process.env.CHECKSUM_ROOT_FOLDER?process.env.CHECKSUM_ROOT_FOLDER:$V.join(__dirname,"..","..","..","checksum")}e(YUt,"checksumFolder");function Qfr({isInit:l,excludeLogin:p}){return[...l?["example.checksum.spec.ts","github-actions.example.yml"]:[],...p?[]:["login.ts"],"checksum.config.ts","playwright.config.ts","README.md",".gitignore.example"]}e(Qfr,"getRuntimeFiles");function Zfr(l,p){try{let d=l.filter(y=>y.endsWith("checksum.config.ts")&&$V.dirname(y).endsWith("checksum"));return d.find(y=>y==="checksum/checksum.config.ts")?"checksum":d.length===1?$V.dirname(d[0]):p?$V.dirname(Ten(d,p)):$V.dirname(d.sort((y,E)=>E.length-y.length)[0])}catch{return"checksum"}}e(Zfr,"findChecksumRootFolder");function Ten(l,p){let d=e(R=>R.split($V.sep).filter(V=>V.length>0),"splitPath"),y=e((R,V)=>{let H=d(R),Q=d(V),se=Math.min(H.length,Q.length),G=Math.abs(H.length-Q.length);for(let _e=0;_e<se;_e++)if(H[_e]!==Q[_e]){G+=2*(se-_e);break}return G},"directoryDistance"),E=null,N=1/0,F=$V.dirname(p);return l.forEach(R=>{let V=y(F,R);V<N&&(N=V,E=R)}),E}e(Ten,"getClosestPath");function e_r(l,p=2){let d=[],y=[],E=e(F=>{if(d.includes(F))return;d.push(F);let R=(0,J9e.readdirSync)(F);for(let V of R){let H=$V.join(F,V),Q=(0,J9e.statSync)(H);if(!(Q.isSymbolicLink()||H.includes("node_modules"))){if(Q.isDirectory())E(H);else if(V==="checksum.config.ts"){y.push(H);return}}}},"searchDirectory"),N=$V.dirname(l);try{for(let F=0;F<p&&(E(N),N=$V.join(N,".."),F===p-1&&F<9&&!y.length&&(p+=2),!($V.resolve(N)==="/"||!N||$V.resolve(N)===$V.resolve(process.cwd())));F++);return y}catch{return y}}e(e_r,"findChecksumRootQualifyingPathsForTestFile");var Den={generateSelectionData:!1,navigationTimeout:30*1e3,actionTimeout:5*1e3},QUt=class QUt{constructor(p,d,y,E,N,F){this.page=p;this.evaluateWithChecksum=d;this.checksumPage=y;this.pageInteractor=E;this.trace=N;this.options=F;this.API_BASE_DOMAIN="https://api.checksum.ai";this.didCancel=!1;this.timeout=15*60*1e3;this.canResolveAssertion=!1;this.page=p,this.options={...Den,...F}}canResolve(p){return!(p.type==="assertion"&&!this.canResolveAssertion)}addMetadata(p){}cancel(){this.didCancel=!0}async execute(p,d,y,E=6e4){return t_r(p,d,y,E)}log(...p){XG(...p)}setThought(p){this.thought=p}setVariables(p){this.variables=p}get shouldSendToAnalytics(){return!0}getAnalyticsPayload(){return{}}toString(){return this.constructor.name}};e(QUt,"AbstractFallback");var Vet=QUt;var ZUt=class ZUt extends Vet{constructor(){super(...arguments);this.API_BASE_ROUTE="/client-api/runtime/esra-fallback"}init(d){let{apiKey:y,testId:E,apiURL:N,checksumId:F,fileName:R,timeout:V}=d;return this.data={...this.data,testId:E,checksumId:F,fileName:R},this.apiKey=y,N&&(this.API_BASE_DOMAIN=N.replace(/\/$/,"")),V&&(this.timeout=V),this.checksumRootFolder=process.env.CHECKSUM_ROOT_FOLDER??Zfr(e_r(this.data.fileName),this.data.fileName),this}getRecoveryAttemptTitle(d){return`Checksum auto-heal: trying to locate the element using checksumSelector("${this.data.checksumId}")...`}async sendLog(d){let y=this.getLogPayload(d);try{fetch(`${this.getAPIBaseURL()}/log`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.apiKey},body:JSON.stringify(y)}).catch(E=>this.log("[ESRAFallback] Error sending log"))}catch(E){this.log("[ESRAFallback] Error sending log",E)}}getLogPayload(d){let y=process.env.CHECKSUM_TEST_SUITE_ID??"",{selector:E}=d,{checksumId:N,testId:F}=this.data;return this.logPayload={testSuiteId:y,testId:F,selector:E,checksumId:N,thought:this.thought},this.logPayload}async getMetadataForTestId(){return Kfr(this.checksumRootFolder,this.data.testId)}getAPIBaseURL(){return this.API_BASE_DOMAIN+this.API_BASE_ROUTE}};e(ZUt,"MetadataBaseFallback");var zet=ZUt;var utn=x7(M_r());var ltn=require("jsdom");var msn=x7(fWt());var K1r=x7(G1r());var mWt=class mWt{constructor(p){this.toJSON=e(()=>this.data,"toJSON");this.data=p}getSimilar(p){let d=null,y=-1/0;for(let E of Object.keys(this.data)){let N=(0,K1r.levenshtein)([...p],[...E]);N>y&&(y=N,d=E)}return d?this.data[d]:null}};e(mWt,"SimilarityRecord");var dWt=mWt,ENe=class ENe extends dWt{constructor(p){super(ENe.preprocessRectangles(p))}getRectangleByTextAndSizeRanking(p,d){d=!d||!Number(d)?0:Number(d);let y=this.getSimilar(p);if(!y||y.length===0)return null;let E=Math.min(Math.max(d,0),y.length-1);return y[E]}};e(ENe,"RectangleIndex"),ENe.preprocessRectangles=e(p=>{let d=[...new Map([...p].map(E=>[JSON.stringify(E.vertices),E])).values()],y={};return d.forEach(E=>{y[E.text]||(y[E.text]=[]),y[E.text].push(E),y[E.text].sort((N,F)=>{let R=ENe.calculateArea(N.vertices),V=ENe.calculateArea(F.vertices);return R-V})}),y},"preprocessRectangles"),ENe.calculateArea=e(p=>{let d=Math.abs(p[1].x-p[0].x),y=Math.abs(p[3].y-p[0].y);return d*y},"calculateArea");var wNt=ENe;var nhr=require("fs"),ihr=require("path");function wQ(l){return l._guid}e(wQ,"getPageOrFrameGuid");async function ANt(l,p,d){let y=l,E=y._mainFrame;try{y._mainFrame=p,await d(y)}finally{y._mainFrame=E}}e(ANt,"executeOnPageWithFrame");var X1r={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html"},hWt={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"},Q1r=Object.fromEntries(Object.entries(hWt).map(l=>l.reverse())),gWt={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"},Z1r=Object.fromEntries(Object.entries(gWt).map(l=>l.reverse()));var ehr={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]},Ttt={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 Han=e(l=>l.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\${/g,"\\${"),"escapeStringForTemplateLiteral"),thr="variableStore",kNe=thr+".",rhr=e((l,{alwaysIncludeInitializationLine:p=!1,onlyValueExpression:d=!1}={})=>[p?`const ${thr} = {};`:"",...l.map(({name:E,value:N,valueExpression:F})=>{let R=typeof N=="string"&&!d?`\`${Han(N)}\``:F;return`${kNe}${E} = ${R};`})].join(`
1837
- `),"variablesToString");var Gan=!0,_TestGenerationPageInteractor=class _TestGenerationPageInteractor{constructor(l,p,d,y,E,N,F){this.evaluateWithChecksum=l;this.getFrame=p;this.getTimeMachine=d;this.logger=y;this.options=E;this.pageInteractorAPI=N;this.loginFunction=F;this.activeDialog=null;this.newPagesIds=[];this.listeners={dialog:null,filechooser:null,page:null};this.listenToContextPage=e(()=>{this.getPage().context().on("page",l=>{this.newPagesIds.push(l._guid)})},"listenToContextPage");this.listenToFileChooser=e(()=>{this.listeners.filechooser=async l=>{this.logger.log("File chooser event detected"),this.fileChooser=l},this.getPage().on("filechooser",this.listeners.filechooser)},"listenToFileChooser");this.waitForDialog=e((l=!0,p=1e4)=>new Promise(d=>{let E=0,N=e(()=>{if(this.activeDialog){let F=this.activeDialog;l&&(this.activeDialog=null),d(F)}else E>=p?d(null):(E+=1e3,setTimeout(N,1e3))},"checkDialog");N()}),"waitForDialog");this.performFileUploadAction=e(async(l,p)=>{if(!await l.evaluate(y=>y.tagName==="INPUT"&&y.getAttribute("type")==="file"))throw new Error("File upload action performed on non-file input element");let d=p.files.map(y=>(0,ihr.join)(this.options.testAssetsDir,y)).filter(y=>(0,nhr.existsSync)(y)?!0:(this.logger.log(`Upload file not found: ${y}. Filtering out.`),!1));if(!d.length)throw new Error("No files to upload");await this.actionGuardReturn(l.setInputFiles(d),"Set input files timeout")},"performFileUploadAction");this.getSelectionDataForAction=e(async(l,p)=>l.checksumid?this.getSelectionDataForChecksumId(l.checksumid,p):l.position?await this.evaluateWithChecksum(async([d,y])=>window.checksum.testGenerator.getSelectorByPosition(d,y),[l.position.x,l.position.y]):l.selector?{selector:l.selector,locator:`locator("${l.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 l=>{this.activeDialog=l},this.getPage().on("dialog",this.listeners.dialog)}removeListener(l){try{switch(l){case"dialog":this.listeners.dialog&&(this.getPage().removeListener(l,this.listeners.dialog),this.listeners.dialog=null);break;case"filechooser":this.getPage().off(l,this.listeners.filechooser),this.listeners.filechooser=null;break;case"page":this.getPage().context().off(l,this.listeners.page),this.listeners.page=null;break}}catch(p){this.logger.logError(`Error removing listener: ${l}`,p)}}getOpenedFileChooser(){if(this.fileChooser){let l=this.fileChooser;return this.fileChooser=void 0,l}return null}async handleFileChooserEvent(l=[]){let p=this.getOpenedFileChooser();if(!p)return{};let d="fc_"+Math.random().toString(36).slice(2,4);return await this.evaluateWithChecksum(async([y,E])=>{window.checksum.testGenerator.addForceIncludeElement(E,y)},[d,p.element()]),{interruptionEvent:"fileUploadOpenedEvent",payload:{checksumid:d,customFiles:l}}}async addMoreItemsToDom(l,p){let d=l.querySelector(`[checksum-get-more-items='${p}']`);if(!d)throw new Error("Get more items root not found");let{items:y,hasMoreItems:E}=await this.getMoreItemsForTemplate(p);d.innerHTML=d.innerHTML+y,E||d.removeAttribute("checksum-get-more-items")}async getPageInfo(l){let p=wQ(l);return{id:p,url:l.url(),title:await l.title(),new:this.newPagesIds.includes(p),active:p===wQ(this.getPage())}}async getTabsInfo(){var y;let l=this.getPage(),p=await Promise.all(l.context().pages().map(E=>this.getPageInfo(E))),d=(y=this.getTimeMachine())==null?void 0:y.getPage();return d&&d!==l&&(p=p.filter(E=>E.id!==wQ(d))),this.newPagesIds=[],p}async getSelectionDataFromSelectorGenerator(l,p,d={}){if(d={useCompoundSelector:!0,useCSSExtraction:!0,useVariables:!0,useArbitrarySelector:!0,...d},!l||!KUt(Wfr(p.action.type))||!p.action.checksumid)return{};let y=await l.generateSelectionForAction(p,d);return y?{locator:`locator("${y.selector}")`,...y}:{}}async translateActionResponseToAgentPotentialAction(l,p=void 0,{pageId:d,makeStaticMetadataForESRA:y}={}){let E=structuredClone(l.actionHiddenOverride??l.action),{selector:N,selectorWithVars:F,locator:R,locatorWithVars:V,clickOffset:H,selectOptionValue:Q,compoundSelector:se,alternateLocators:G,parentFramesSelectors:_e}={...await this.getSelectionDataForAction(E,l.actionHiddenOverride),...await this.getSelectionDataFromSelectorGenerator(p,l)},ne=await this.getESRAForSelector(N,_e,y);if(!ne&&N&&this.logger.logError("Error getting ESRA metadata"),(ne==null?void 0:ne.tag)==="select")switch(this.getActionEventCode(E.type)){case"input":E.type="selectoption";break;case"click":Q&&(E.type="selectoption",E.value=Q);break}let le={eventCode:this.getActionEventCode(E.type),selector:N,selectorWithVars:F,parentFramesSelectors:_e,locator:R,locatorWithVars:V,clickOffset:H,pageId:d,compoundSelector:se,alternateLocators:G,fillValue:E.value,fillValueName:E.valueName?`${kNe}${E.valueName}`:"",variables:l.variables,getMoreItemsId:E.getMoreItemsId,esraMetadata:ne,thought:l.thought,userRole:E.userRole,canvas:E.canvas,id:E.id};switch(le.eventCode){case"drag_and_drop":{let{selector:Ue,selectorWithVars:Xe,locator:rt,locatorWithVars:Tt,parentFramesSelectors:Nt}={...await this.getSelectionDataForAction({type:l.action.type,checksumid:l.action.dropTargetChecksumid}),...await this.getSelectionDataFromSelectorGenerator(p,{...l,action:{type:l.action.type,checksumid:l.action.dropTargetChecksumid}},{useCompoundSelector:!1})};le.dropTarget={selector:Ue,locator:rt,parentFramesSelectors:Nt,esraMetadata:await this.getESRAForSelector(Ue,Nt,y)}}break;case"upload_files":le.files=this.mapFileMIMETypeToFilename(E.files);break;case"switch_tab":{let Ue=this.getPage();le.switchToTab={id:E.tabId,index:Ue.context().pages().findIndex(Xe=>wQ(Xe)===E.tabId)};break}case"keystroke":le.fillValue=E.value}return le}async reauthenticate(l,p){let d=this.getPage();this.loginFunction&&(await Promise.all([d.context().clearCookies(),d.evaluate(()=>localStorage.clear())]),await this.loginFunction(p??d,{role:l}))}mapFileMIMETypeToFilename(l){return l.map(p=>{if(p.fileName)return p.fileName;switch(p.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(l,{useLocator:p=!1,handleActionFailed:d,monitorFlashingHTML:y=!0,timeout:E,allowForceClick:N=!0}={}){try{if(l.executed){this.logger.log("[performAction] Action marked as executed, skipping...");return}let F=p?!!l.locator:!!l.selector;if(KUt(l.eventCode)&&!F)throw new Error("No selector provided for action. Try changing app rules preMapReducedHTMLSelectors to true");y&&(this.logger.log("starting flashing elements detection"),await this.evaluateWithChecksum(async()=>window.checksum.testGenerator.startFlashingElementsDetection())),this.logger.log(`Performing action: ${l.eventCode}. Selector: ${l.selector}, Position: ${l.clickOffset}, Parent frame: ${l.parentFramesSelectors}`);let R=e(()=>p?this.makeLocatorFromLocator(l.locator):this.makeLocator(l.selector,l.parentFramesSelectors),"getLocator"),V=e(async(H,Q,se={})=>this.actionGuardReturn(H,Q,{timeout:E,...se}),"performWithActionGuard");switch(l.eventCode){case"click":try{await V(R().click({position:l.clickOffset,timeout:E??this.options.actionTimeout}),"Click timeout")}catch(H){if(!N)throw H;this.logger.log("Error performing click, will attempt a force click",H.message),l.force=!0,await V(R().click({position:l.clickOffset,force:!0,timeout:E??this.options.actionTimeout}),"Force Click timeout")}break;case"double_click":try{await V(R().dblclick({position:l.clickOffset,timeout:E??this.options.actionTimeout}),"DoubleClick timeout")}catch(H){if(!N)throw H;this.logger.log("Error performing double click, will attempt a force double click",H),l.force=!0,await V(R().dblclick({position:l.clickOffset,timeout:E??this.options.actionTimeout,force:!0}),"Force DoubleClick timeout")}break;case"check":await V(R().check({timeout:E??this.options.actionTimeout}),"Check timeout");break;case"uncheck":await V(R().uncheck({timeout:E??this.options.actionTimeout}),"UnCheck timeout");break;case"drag_and_drop":await V(R().dragTo(p?this.makeLocatorFromLocator(l.dropTarget.locator):this.makeLocator(l.dropTarget.selector,l.dropTarget.parentFramesSelectors),{timeout:E??this.options.actionTimeout}),"DragAndDrop timeout");break;case"input":await V(R().fill(this.getActionFillValue(l),{timeout:E??this.options.actionTimeout}),"Fill timeout");break;case"click_and_type":await Dj(R().click({position:l.clickOffset,timeout:E??this.options.actionTimeout}),1e4,"Click before type timeout"),await Dj(R().pressSequentially(this.getActionFillValue(l),{timeout:E??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"clear_and_type":await Dj(R().clear({timeout:E??this.options.actionTimeout}),1e4,"Clear before type timeout"),await Dj(R().pressSequentially(this.getActionFillValue(l),{timeout:E??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"selectoption":await V(R().selectOption(this.getActionFillValue(l),{timeout:E??this.options.actionTimeout}),"SelectOption timeout");break;case"hover":await V(R().hover({timeout:E??this.options.actionTimeout}),"Hover timeout");break;case"navigation":await V(this.getFrame().goto(l.fillValue,{timeout:E??this.options.navigationTimeout}),"Navigation timeout",{isNavigation:!0});break;case"keystroke":{let H=this.getPage();await V(H.keyboard.press(l.fillValue),"Keystroke timeout");break}case"upload_files":await this.performFileUploadAction(R(),l);break;case"wait":await aA(this.options.waitActionDelay??1e3);break;case"custom_code":await ANt(this.getPage(),this.getFrame(),async H=>{let Q=`async (page) => {${l.fillValue}}`;await(0,eval)(Q)(H)});break;case"logout_and_login":await this.reauthenticate(l.userRole);break;case"canvas_click":await this.canvasClick(R(),l.canvas);break}}catch(F){throw this.logger.log(`Error performing action: ${l.eventCode}, will attempt a correction template`,F),await(d==null?void 0:d()),F}this.logger.log(`Successfully performed action ${l.eventCode} with description "${l.thought}"`)}async getTextDetection(l){return new wNt(await this.pageInteractorAPI.getTextDetection(l))}async canvasClick(l,p){try{if(!await l.evaluate(N=>N.tagName.toLowerCase()==="canvas"))throw new Error("Click attempted on a non-canvas element");let E=(await this.getTextDetection(await l.screenshot())).getRectangleByTextAndSizeRanking(p.canvasText,p.rectSizeIndex);if(!E)throw new Error(`Canvas click target not found for ${p.canvasText}`);this.logger.log(`Canvas click target: ${E}`),await this.actionGuardReturn(l.click({position:E.center}),"Canvas click could not be performed")}catch(d){throw this.logger.logError("Canvas click:",d.message),new Error("Canvas click action failed")}}getActionFillValue(l,p=!0){let d=l.fillValue;if(!d){let y=l.selector.match(/(?<=value.*)('|").*/);y&&(d=y[0].slice(1,-1))}return typeof d!="string"&&(d="X"),p&&(l.fillValue=d),d}actionGuardReturn(l,p,{isNavigation:d=!1,timeout:y}={}){return Dj(l,y??(d?this.options.navigationTimeout:this.options.actionTimeout),p)}makeLocator(l,p=[]){return Xfr(this.getFrame(),l,p)}makeLocatorFromLocator(locator){return eval("this.getFrame()."+locator)}getCurrentURL(){return this.getFrame().url()}async getSelectionDataForChecksumId(l,p){if(p!=null&&p.selector)return{...p,selector:p.selector,locator:p.locator,clickOffset:p.position};if(!l)return this.logger.log(`[getSelectionDataForChecksumId] checksumid not provided (${l})`),{...p,selector:l,locator:`locator("${l}")`};let d=await this.evaluateWithChecksum(async y=>{let{selector:E,locator:N,clickOffset:F,parentFramesSelectors:R,invalid:V,rrwebId:H}=await window.checksum.testGenerator.getSelectorForChecksumId(y),Q=await window.checksum.testGenerator.getElementForChecksumId(y),se=Q instanceof HTMLOptionElement&&Q.value?Q.value:void 0;return{selector:E,locator:N,clickOffset:F,selectOptionValue:se,parentFramesSelectors:R,invalid:V,rrwebId:H}},l);if(Gan&&d.invalid&&d.rrwebId){this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${l}. Trying to use time machine...`);try{let y=await this.getSelectionDataForRRwebIdAtReduceHTMLTime(d.rrwebId);d={...d,...y}}catch{this.logger.log(`[getSelectionDataForChecksumId] error using time machine to get selector for checksumid: ${l}`)}this.logger.log(`[getSelectionDataForChecksumId] got selector: ${d.selector} for checksumid: ${l} from time machine`)}return d!=null&&d.selector||this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${l}. If checksumid is correct, try to change app rules preMapReducedHTMLSelectors to true`),d}async getSelectionDataForRRwebIdAtReduceHTMLTime(l){if(!this.rrwebEventAtLastReducedHTML)return;let p=this.getTimeMachine();if(p)return p.executeTask(d=>d.evaluate(async({rrwebId:y})=>await window.checksum.testGenerator.getInspectedElementSelectionResultByRRwebId(y,{ignoredIframesSelectors:[".replayer-wrapper > iframe"],fromTimeMachine:!0}),{rrwebId:l}),this.rrwebEventAtLastReducedHTML.timestamp,{name:"getSelectionDataForRRwebIdAtReduceHTMLTime"})}async getESRAForSelector(l,p,d){let y=await this.evaluateWithChecksum(async({selector:E,parentFramesSelectors:N})=>window.checksum.testGenerator.getSelectionDataForSelector(E,N),{selector:l,parentFramesSelectors:p});return y!=null&&y.esraMetadata&&d&&(y.esraMetadata.staticMetadata=await d(y.esraMetadata,l)),y==null?void 0:y.esraMetadata}async getMoreItemsForTemplate(l){return await this.evaluateWithChecksum(async p=>window.checksum.testGenerator.getMoreItemsForTemplate(p,{}),l)??{items:"",hasMoreItems:!1}}async getCurrentReducedHTML({retriesLeft:l=3,retryWaitMS:p=2e3,initialChecksumId:d="0",extractESRAForInterpretationRequiredElements:y=!1,stopFlashingElementsDetection:E=!1,assignChecksumIdsToAllElements:N}={}){let F=new Date;this.logger.log("[getCurrentReducedHTML] Fetching reduced HTML...");try{let{reducedHTML:R,currentChecksumId:V,flashingHTML:H,elementsForNodeInterpretation:Q,lastRRwebEvent:se}=await this.evaluateWithChecksum(async _e=>window.checksum.testGenerator.reduceHTML({},_e),{initialChecksumId:d,extractESRAForInterpretationRequiredElements:y,stopFlashingElementsDetection:E,assignChecksumIdsToAllElements:N}),G=new Date;return this.logger.log(`[getCurrentReducedHTML] Fetched reduced HTML in ${G.getTime()-F.getTime()}ms`),this.rrwebEventAtLastReducedHTML=se,{reducedHTML:R,flashingHTML:H,elementsForNodeInterpretation:Q,currentChecksumId:V}}catch(R){if(l>0)return this.logger.logError(`[getCurrentReducedHTML] Error: ${R.message}`),this.logger.logError(`Failed do obtain reduced HTML, trying again in ${p/1e3} seconds, ${l-1} to go.`),await aA(p),this.getCurrentReducedHTML({retriesLeft:l-1,retryWaitMS:p});throw R}}getActionEventCode(l){return hWt[l]}};e(_TestGenerationPageInteractor,"TestGenerationPageInteractor");var pEt=_TestGenerationPageInteractor;var _AlternateSelectorFallback=class _AlternateSelectorFallback extends zet{constructor(){super(...arguments);this.timeout=5*1e3}init(p){return super.init(p),this}async resolve(params){var p;try{let{method,args}=params,{checksumId}=this.data,alternateLocators=[];try{let d=await this.getMetadataForTestId();if(!(checksumId in d)||!d[checksumId].alternateLocators)throw new Error(`No alternate selection metadata found for id ${checksumId}`);alternateLocators=d[checksumId].alternateLocators.locators}catch(d){throw super.log(`Could not read alternate selector metadata file, ${d.message}`),d}try{this.log("Resolving alternate selectors locators");let elementsMap=new Map;await Promise.all(alternateLocators.map(async locatorExpression=>{let locator=eval(J0e(locatorExpression,"this.page"));try{await Dj(locator.first().waitFor({bypassChecksum:!0}),5e3),(await Dj(locator.elementHandles({bypassChecksum:!0}),1e3)).forEach(y=>{elementsMap.has(y)?elementsMap.set(y,elementsMap.get(y)+1):elementsMap.set(y,1)})}catch(d){return}}));let majorityElementHandle=(p=Array.from(elementsMap.entries()))==null?void 0:p.reduce((d,y)=>d[1]>y[1]?d:y)[0];if(!majorityElementHandle)throw this.errorMessage="No alternate element found",new Error(this.errorMessage);let totalElements=Array.from(elementsMap.values()).reduce((d,y)=>d+y,0),elementSelector=await this.evaluateWithChecksum(async({element:d})=>window.playwright.selector(d),{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(d){throw new Error(`Failed to execute compound selection fallback action: ${d.message}`)}}catch(d){this.errorMessage=d.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 yWt=_AlternateSelectorFallback;var TWt=class TWt{constructor(p){this.options=p}async handleError(p,d,y){let E=`Error in ${d} action during ${p} execution: ${y.message}`;throw new Error(E)}async guardedExecute(){try{return await(this.options.timeout!=null?Dj(this.execute(),this.options.timeout,"Execution timeout"):this.execute())}catch(p){return this.handleError(this.options.method,this.constructor.name,p)}}};e(TWt,"Action");var PNt=TWt,DWt=class DWt extends PNt{async execute(){return this.options.method in this.options.locator?this.options.locator[this.options.method](...this.options.args):this.options.locator}};e(DWt,"PlaywrightAction");var vWt=DWt,CWt=class CWt extends PNt{constructor(d,y){super(d);this.pageInteractor=y}};e(CWt,"APIAction");var bWt=CWt,EWt=class EWt extends bWt{constructor(p,d){super(p,d.pageInteractor)}async execute(){try{let{locator:p,args:d}=this.options,[y,E]=d,N=await p.screenshot({timeout:3e4}),R=(await this.pageInteractor.getTextDetection(N)).getRectangleByTextAndSizeRanking(y,E);if(!R)throw new Error("No matching text found");await p.click({position:R.center})}catch(p){throw new Error(`Error in canvas click action: ${p.message}`)}}};e(EWt,"CanvasClickAction");var xWt=EWt,NNt=class NNt{static createAction(p,d){return p.method in this.customActionMap?new this.customActionMap[p.method]({...p,timeout:15e3},d):new vWt(p)}};e(NNt,"ActionFactory"),NNt.customActionMap={canvasClick:xWt};var SWt=NNt;var kWt=class kWt{constructor(p){this.options=p;this.health=e(async()=>await fetch(`${this.options.apiURL}/client-api/runtime/api/health`,{headers:{ChecksumAppCode:this.options.apiKey}}).catch(p=>(console.log(p),null)),"health");this.getCanvasDetection=e(async p=>{try{let d=p.toString("base64");return await(await fetch(`${this.options.apiURL}/client-api/runtime/vision/text-detection`,{body:JSON.stringify({imageBuffer:d}),method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.options.apiKey}})).json()}catch(d){return console.log(d),null}},"getCanvasDetection")}};e(kWt,"ChecksumClient");var fEt=kWt;var wWt=class wWt{constructor(){this.config={}}};e(wWt,"PageInteractorAPI");var FNt=wWt;var AWt=class AWt extends FNt{constructor(d){super();this.config=d;this.getTextDetection=e(async d=>{let y=await this.api.getCanvasDetection(d);if(!y)throw new Error("No data returned from canvas detection");return y},"getTextDetection");this.config=d,this.api=new fEt({apiKey:d.apiKey,apiURL:d.apiURL})}};e(AWt,"RuntimePageInteractorAPI");var _Et=AWt;var ahr=require("path");var PWt=class PWt{constructor(p){this.options=p;this.navigatingFrames={};this.trackedFramesGuid=[];this.frameNavigationPromises={};this.onFrameNavigated=e(async p=>{let d=wQ(p);if(this.trackedFramesGuid.includes(d))return this.frameNavigationPromises[d]=new Promise(async y=>{await this.loadScript(p),y()}),this.frameNavigationPromises[d]},"onFrameNavigated");this.loadScript=e(async(p,{retriesLeft:d=3,retryWaitMS:y=2e3,useWrapper:E=!0}={})=>{var V,H;if(E&&this.scriptLoadWrapper)return this.scriptLoadWrapper(()=>this.loadScript(p,{retriesLeft:d,retryWaitMS:y,useWrapper:!1}),p);if(!this.addScriptTagOptions){console.warn("[InjectedScriptManager] addScriptTagOptions not set, skipping loadScript");return}if(this.isFrameClosed(p))return;let N=!1;try{N=this.scriptLoadCheck?await((V=this.scriptLoadCheck)==null?void 0:V.call(this,p)):!1}catch{}if(N||this.isFrameClosed(p))return;try{await p.addScriptTag(this.addScriptTagOptions)}catch(Q){if(d>0)return console.warn(`[InjectedScriptManager] Failed to add script to frame ${wQ(p)}, trying again in ${y/1e3} seconds, ${d-1} retries left.`,Q.message),await aA(y),this.loadScript(p,{retriesLeft:d-1,retryWaitMS:y,useWrapper:E});throw Q}let F=wQ(p),R=Date.now().toString(36)+Math.random().toString(36).substr(2);if(this.navigatingFrames[F]=R,this.options.scriptInitWait&&(console.log(`Waiting ${this.options.scriptInitWait}[ms] before onScriptLoad...`),await aA(this.options.scriptInitWait),console.log("Done waiting before onScriptLoad")),!this.isFrameClosed(p)){if(this.navigatingFrames[F]&&this.navigatingFrames[F]!==R)return console.log("Page navigated again, waiting on new promise..."),this.frameNavigationPromises[F];try{await((H=this.scriptLoadCallback)==null?void 0:H.call(this,p))}catch(Q){console.error("[WebDriver] onScriptLoad error",Q)}}},"loadScript");this.addScriptTagOptions=this.makeFrameInjectedScriptOptions()}setScriptLoadCallback(p){return this.scriptLoadCallback=p,this}setScriptLoadCheck(p){return this.scriptLoadCheck=p,this}setScriptLoadWrapper(p){return this.scriptLoadWrapper=p,this}async addTrackedFrame(p,d=!0){let y="mainFrame"in p?p.mainFrame():p,E=wQ(y);if(this.trackedFramesGuid.includes(E)||this.trackedFramesGuid.push(E),d)return this.onFrameNavigated(y)}getNavigationPromise(p){if(!p){console.warn("[InjectedScriptManager] getNavigationPromise called with undefined argument");return}let d=typeof p=="string"?p:"mainFrame"in p?wQ(p.mainFrame()):wQ(p);return this.frameNavigationPromises[d]}makeFrameInjectedScriptOptions(){switch(this.options.scriptSource){case"file":return this.options.scriptFile?{path:this.options.isScriptFileAbsolute?this.options.scriptFile:(0,ahr.join)(process.cwd(),this.options.scriptFile)}:void 0;case"url":return this.options.scriptURL?{url:this.options.scriptURL}:void 0;default:return}}isFrameClosed(p){return p.isDetached()||p.page().isClosed()}};e(PWt,"InjectedScriptManager");var dEt=PWt;var uZe=x7(require("path")),OWt=require("fs");var lsn=__dirname,phr=uZe.join(__dirname,".."),psn=(0,OWt.existsSync)(phr)?phr:lsn;lhr().config({path:uZe.resolve(psn,".env")});var ONt=process.env.DEV_MODE==="true";function _hr(){let l=__dirname;for(;!(0,OWt.existsSync)(uZe.join(l,"package.json"));)l=uZe.join(l,"..");return l}e(_hr,"findRoot");var fhr=uZe.join(_hr(),"vtg-build","index.html"),vC={isDevMode:ONt,logLevel:process.env.LOG_LEVEL??"warnings",checksumScript:{source:ONt?"url":"file",url:process.env.SCRIPT_URL,path:_hr()+"/checksumlib.js"},vtg:{writeLogFile:process.env.WRITE_LOG_FILE==="true",localBuildPath:fhr,appURL:ONt?process.env.VTG_APP_URL:`file://${fhr}`,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"};ONt&&console.log("Build",vC.buildTime);var LWt=class LWt{constructor(){this.frames={};this.pages=[];this.channels={};this.events=[]}register(p,d,y){if(this.frames[p])return;this.frames[p]=d;let E=d.page();this.pages.includes(E)||(this.pages.push(E),E.exposeFunction("checksumSendMessage",async(N,F)=>{let R=this.frames[N];if(!R)throw new Error(`Frame ${N} not found`);try{await R.evaluate(({message:V})=>{window.postMessage(V,"*")},{message:F})}catch{}}),E.exposeFunction("checksumSendBroadcastMessage",async(N,F)=>{let R=this.channels[N]??[];if(y){let V=require("fs"),H=require("path");this.events.push(...F),this.events.length%10===0&&V.writeFileSync(H.join(process.cwd(),"rrweb-player","events.json"),JSON.stringify(this.events))}R.forEach(async V=>{if(!(V.originFrameGuid&&V.originFrameGuid!==wQ(d)))try{V.handler?await V.handler(F):await d.evaluate(({message:H})=>{window.postMessage(H,"*")},{message:F})}catch{}})}),E.exposeFunction("checksumBringPageToFront",async N=>{let F=this.frames[N];F&&await F.page().bringToFront()}))}subscribeToChannel(p,d,{originFrame:y,handler:E}={}){var N;(N=this.channels)[p]??(N[p]=[]),this.channels[p].push({frame:d,originFrameGuid:y?wQ(y):void 0,handler:E})}unsubscribeFromChannel(p,d){var y;(y=this.channels)[p]??(y[p]=[]),this.channels[p]=this.channels[p].filter(E=>E.frame!==d)}};e(LWt,"FramesMsgBroker");var mEt=LWt;var mhr=require("@playwright/test");var hEt=require("jsdom");var MWt=class MWt{constructor(p){this.activeDOMType="checksumIds";this.rawReducedHTMLDom=new hEt.JSDOM(p),this.process()}process(){this.expandedChecksumIdsReducedDom=new hEt.JSDOM(this.rawReducedHTMLDom.serialize()),this.reducedHTMLDom=new hEt.JSDOM(this.rawReducedHTMLDom.serialize()),this.rrwebIdsReducedDom=new hEt.JSDOM(this.rawReducedHTMLDom.serialize());let p=e(F=>{F.window.document.body.querySelectorAll("[checksumid]:not([checksuminteractable])").forEach(V=>{V.removeAttribute("checksumid")})},"removeChecksumIdAttributeFromNonInteractable"),d=e((F,R)=>R.window.document.body.querySelectorAll(`[${F}]`).forEach(V=>V.removeAttribute(F)),"removeAttributeFromAllElements"),y=e(F=>d("checksuminteractable",F),"removeChecksumInteractableAttribute"),E=e(F=>d("checksumid",F),"removeChecksumIdAttribute"),N=e(F=>d("rrwebid",F),"removeRrwebIdAttribute");p(this.reducedHTMLDom),y(this.expandedChecksumIdsReducedDom),y(this.reducedHTMLDom),y(this.rrwebIdsReducedDom),N(this.expandedChecksumIdsReducedDom),N(this.reducedHTMLDom),E(this.rrwebIdsReducedDom)}getDOMForType(p){switch(p){default:case"checksumIds":return this.reducedHTMLDom;case"expandedChecksumIds":return this.expandedChecksumIdsReducedDom;case"rrwebIds":return this.rrwebIdsReducedDom}}async enrich(p){return await p(this.rawReducedHTMLDom),this.process(),this}setActiveDomType(p){this.activeDOMType=p}getActiveDom(){return this.getDOMForType(this.activeDOMType)}getActiveDOMString(){return this.getActiveDom().serialize()}getRrwebIdsReducedDomString(){return this.rrwebIdsReducedDom.serialize()}getDOMStringForType(p){return this.getDOMForType(p).serialize()}get raw(){return this.rawReducedHTMLDom}};e(MWt,"ReducedHTMLDOM");var gEt=MWt;var dhr=x7(require("path"));var BWt=class BWt{constructor(p="all"){this.listeners=[];this.logLevel=p}log(...p){try{let y=new Error().stack.split(`
1837
+ `),"variablesToString");var Gan=!0,_TestGenerationPageInteractor=class _TestGenerationPageInteractor{constructor(l,p,d,y,E,N,F){this.evaluateWithChecksum=l;this.getFrame=p;this.getTimeMachine=d;this.logger=y;this.options=E;this.pageInteractorAPI=N;this.loginFunction=F;this.activeDialog=null;this.newPagesIds=[];this.listeners={dialog:null,filechooser:null,page:null};this.listenToContextPage=e(()=>{this.getPage().context().on("page",l=>{this.newPagesIds.push(l._guid)})},"listenToContextPage");this.listenToFileChooser=e(()=>{this.listeners.filechooser=async l=>{this.logger.log("File chooser event detected"),this.fileChooser=l},this.getPage().on("filechooser",this.listeners.filechooser)},"listenToFileChooser");this.waitForDialog=e((l=!0,p=1e4)=>new Promise(d=>{let E=0,N=e(()=>{if(this.activeDialog){let F=this.activeDialog;l&&(this.activeDialog=null),d(F)}else E>=p?d(null):(E+=1e3,setTimeout(N,1e3))},"checkDialog");N()}),"waitForDialog");this.performFileUploadAction=e(async(l,p)=>{if(!await l.evaluate(y=>y.tagName==="INPUT"&&y.getAttribute("type")==="file"))throw new Error("File upload action performed on non-file input element");let d=p.files.map(y=>(0,ihr.join)(this.options.testAssetsDir,y)).filter(y=>(0,nhr.existsSync)(y)?!0:(this.logger.log(`Upload file not found: ${y}. Filtering out.`),!1));if(!d.length)throw new Error("No files to upload");await this.actionGuardReturn(l.setInputFiles(d),"Set input files timeout")},"performFileUploadAction");this.getSelectionDataForAction=e(async(l,p)=>l.checksumid?this.getSelectionDataForChecksumId(l.checksumid,p):l.position?await this.evaluateWithChecksum(async([d,y])=>window.checksum.testGenerator.getSelectorByPosition(d,y),[l.position.x,l.position.y]):l.selector?{selector:l.selector,locator:`locator("${l.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 l=>{this.activeDialog=l},this.getPage().on("dialog",this.listeners.dialog)}removeListener(l){try{switch(l){case"dialog":this.listeners.dialog&&(this.getPage().removeListener(l,this.listeners.dialog),this.listeners.dialog=null);break;case"filechooser":this.getPage().off(l,this.listeners.filechooser),this.listeners.filechooser=null;break;case"page":this.getPage().context().off(l,this.listeners.page),this.listeners.page=null;break}}catch(p){this.logger.logError(`Error removing listener: ${l}`,p)}}getOpenedFileChooser(){if(this.fileChooser){let l=this.fileChooser;return this.fileChooser=void 0,l}return null}async handleFileChooserEvent(l=[]){let p=this.getOpenedFileChooser();if(!p)return{};let d="fc_"+Math.random().toString(36).slice(2,4);return await this.evaluateWithChecksum(async([y,E])=>{window.checksum.testGenerator.addForceIncludeElement(E,y)},[d,p.element()]),{interruptionEvent:"fileUploadOpenedEvent",payload:{checksumid:d,customFiles:l}}}async addMoreItemsToDom(l,p){let d=l.querySelector(`[checksum-get-more-items='${p}']`);if(!d)throw new Error("Get more items root not found");let{items:y,hasMoreItems:E}=await this.getMoreItemsForTemplate(p);d.innerHTML=d.innerHTML+y,E||d.removeAttribute("checksum-get-more-items")}async getPageInfo(l){let p=wQ(l);return{id:p,url:l.url(),title:await l.title(),new:this.newPagesIds.includes(p),active:p===wQ(this.getPage())}}async getTabsInfo(){var y;let l=this.getPage(),p=await Promise.all(l.context().pages().map(E=>this.getPageInfo(E))),d=(y=this.getTimeMachine())==null?void 0:y.getPage();return d&&d!==l&&(p=p.filter(E=>E.id!==wQ(d))),this.newPagesIds=[],p}async getSelectionDataFromSelectorGenerator(l,p,d={}){if(d={useCompoundSelector:!0,useCSSExtraction:!0,useVariables:!0,useArbitrarySelector:!0,...d},!l||!KUt(Wfr(p.action.type))||!p.action.checksumid)return{};let y=await l.generateSelectionForAction(p,d);return y?{locator:`locator("${y.selector}")`,...y}:{}}async translateActionResponseToAgentPotentialAction(l,p=void 0,{pageId:d,makeStaticMetadataForESRA:y}={}){let E=structuredClone(l.actionHiddenOverride??l.action),{selector:N,selectorWithVars:F,locator:R,locatorWithVars:V,clickOffset:H,selectOptionValue:Q,compoundSelector:se,alternateLocators:G,parentFramesSelectors:_e}={...await this.getSelectionDataForAction(E,l.actionHiddenOverride),...await this.getSelectionDataFromSelectorGenerator(p,l)},ne=await this.getESRAForSelector(N,_e,y);if(!ne&&N&&this.logger.logError("Error getting ESRA metadata"),(ne==null?void 0:ne.tag)==="select")switch(this.getActionEventCode(E.type)){case"input":E.type="selectoption";break;case"click":Q&&(E.type="selectoption",E.value=Q);break}let le={eventCode:this.getActionEventCode(E.type),selector:N,selectorWithVars:F,parentFramesSelectors:_e,locator:R,locatorWithVars:V,clickOffset:H,pageId:d,compoundSelector:se,alternateLocators:G,fillValue:E.value,fillValueName:E.valueName?`${kNe}${E.valueName}`:"",variables:l.variables,getMoreItemsId:E.getMoreItemsId,esraMetadata:ne,thought:l.thought,userRole:E.userRole,canvas:E.canvas,id:E.id};switch(le.eventCode){case"drag_and_drop":{let{selector:Ue,selectorWithVars:Xe,locator:rt,locatorWithVars:Tt,parentFramesSelectors:Nt}={...await this.getSelectionDataForAction({type:l.action.type,checksumid:l.action.dropTargetChecksumid}),...await this.getSelectionDataFromSelectorGenerator(p,{...l,action:{type:l.action.type,checksumid:l.action.dropTargetChecksumid}},{useCompoundSelector:!1})};le.dropTarget={selector:Ue,locator:rt,parentFramesSelectors:Nt,esraMetadata:await this.getESRAForSelector(Ue,Nt,y)}}break;case"upload_files":le.files=this.mapFileMIMETypeToFilename(E.files);break;case"switch_tab":{let Ue=this.getPage();le.switchToTab={id:E.tabId,index:Ue.context().pages().findIndex(Xe=>wQ(Xe)===E.tabId)};break}case"keystroke":le.fillValue=E.value}return le}async reauthenticate(l,p){let d=this.getPage();this.loginFunction&&(await Promise.all([d.context().clearCookies(),d.evaluate(()=>localStorage.clear())]),await this.loginFunction(p??d,{role:l}))}mapFileMIMETypeToFilename(l){return l.map(p=>{if(p.fileName)return p.fileName;switch(p.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(l,{useLocator:p=!1,handleActionFailed:d,monitorFlashingHTML:y=!0,timeout:E,allowForceClick:N=!0}={}){try{if(l.executed){this.logger.log("[performAction] Action marked as executed, skipping...");return}let F=p?!!l.locator:!!l.selector;if(KUt(l.eventCode)&&!F)throw new Error("No selector provided for action. Try changing app rules preMapReducedHTMLSelectors to true");y&&(this.logger.log("starting flashing elements detection"),await this.evaluateWithChecksum(async()=>window.checksum.testGenerator.startFlashingElementsDetection())),this.logger.log(`Performing action: ${l.eventCode}. Selector: ${l.selector}, Position: ${l.clickOffset}, Parent frame: ${l.parentFramesSelectors}`);let R=e(()=>p?this.makeLocatorFromLocator(l.locator):this.makeLocator(l.selector,l.parentFramesSelectors),"getLocator"),V=e(async(H,Q,se={})=>this.actionGuardReturn(H,Q,{timeout:E,...se}),"performWithActionGuard");switch(l.eventCode){case"click":try{await V(R().click({position:l.clickOffset,timeout:E??this.options.actionTimeout}),"Click timeout")}catch(H){if(!N)throw H;this.logger.log("Error performing click, will attempt a force click",H.message),l.force=!0,await V(R().click({position:l.clickOffset,force:!0,timeout:E??this.options.actionTimeout}),"Force Click timeout")}break;case"double_click":try{await V(R().dblclick({position:l.clickOffset,timeout:E??this.options.actionTimeout}),"DoubleClick timeout")}catch(H){if(!N)throw H;this.logger.log("Error performing double click, will attempt a force double click",H),l.force=!0,await V(R().dblclick({position:l.clickOffset,timeout:E??this.options.actionTimeout,force:!0}),"Force DoubleClick timeout")}break;case"check":await V(R().check({timeout:E??this.options.actionTimeout}),"Check timeout");break;case"uncheck":await V(R().uncheck({timeout:E??this.options.actionTimeout}),"UnCheck timeout");break;case"drag_and_drop":await V(R().dragTo(p?this.makeLocatorFromLocator(l.dropTarget.locator):this.makeLocator(l.dropTarget.selector,l.dropTarget.parentFramesSelectors),{timeout:E??this.options.actionTimeout}),"DragAndDrop timeout");break;case"input":await V(R().fill(this.getActionFillValue(l),{timeout:E??this.options.actionTimeout}),"Fill timeout");break;case"click_and_type":await Dj(R().click({position:l.clickOffset,timeout:E??this.options.actionTimeout}),1e4,"Click before type timeout"),await Dj(R().pressSequentially(this.getActionFillValue(l),{timeout:E??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"clear_and_type":await Dj(R().clear({timeout:E??this.options.actionTimeout}),1e4,"Clear before type timeout"),await Dj(R().pressSequentially(this.getActionFillValue(l),{timeout:E??this.options.actionTimeout}),1e4,"pressSequentially timeout");break;case"selectoption":await V(R().selectOption(this.getActionFillValue(l),{timeout:E??this.options.actionTimeout}),"SelectOption timeout");break;case"hover":await V(R().hover({timeout:E??this.options.actionTimeout}),"Hover timeout");break;case"navigation":await V(this.getFrame().goto(l.fillValue,{timeout:E??this.options.navigationTimeout}),"Navigation timeout",{isNavigation:!0});break;case"keystroke":{let H=this.getPage();await V(H.keyboard.press(l.fillValue),"Keystroke timeout");break}case"upload_files":await this.performFileUploadAction(R(),l);break;case"wait":await aA(this.options.waitActionDelay??1e3);break;case"custom_code":await ANt(this.getPage(),this.getFrame(),async H=>{let Q=`async (page) => {${l.fillValue}}`;await(0,eval)(Q)(H)});break;case"logout_and_login":await this.reauthenticate(l.userRole);break;case"canvas_click":await this.canvasClick(R(),l.canvas);break}}catch(F){throw this.logger.log(`Error performing action: ${l.eventCode}, will attempt a correction template`,F),await(d==null?void 0:d()),F}this.logger.log(`Successfully performed action ${l.eventCode} with description "${l.thought}"`)}async getTextDetection(l){return new wNt(await this.pageInteractorAPI.getTextDetection(l))}async canvasClick(l,p){try{if(!await l.evaluate(N=>N.tagName.toLowerCase()==="canvas"))throw new Error("Click attempted on a non-canvas element");let E=(await this.getTextDetection(await l.screenshot())).getRectangleByTextAndSizeRanking(p.canvasText,p.rectSizeIndex);if(!E)throw new Error(`Canvas click target not found for ${p.canvasText}`);this.logger.log(`Canvas click target: ${E}`),await this.actionGuardReturn(l.click({position:E.center}),"Canvas click could not be performed")}catch(d){throw this.logger.logError("Canvas click:",d.message),new Error("Canvas click action failed")}}getActionFillValue(l,p=!0){let d=l.fillValue;if(!d){let y=l.selector.match(/(?<=value.*)('|").*/);y&&(d=y[0].slice(1,-1))}return typeof d!="string"&&(d="X"),p&&(l.fillValue=d),d}actionGuardReturn(l,p,{isNavigation:d=!1,timeout:y}={}){return Dj(l,y??(d?this.options.navigationTimeout:this.options.actionTimeout),p)}makeLocator(l,p=[]){return Xfr(this.getFrame(),l,p)}makeLocatorFromLocator(locator){return eval("this.getFrame()."+locator)}getCurrentURL(){return this.getFrame().url()}async getSelectionDataForChecksumId(l,p){if(p!=null&&p.selector)return{...p,selector:p.selector,locator:p.locator,clickOffset:p.position};if(!l)return this.logger.log(`[getSelectionDataForChecksumId] checksumid not provided (${l})`),{...p,selector:l,locator:`locator("${l}")`};let d=await this.evaluateWithChecksum(async y=>{let{selector:E,locator:N,clickOffset:F,parentFramesSelectors:R,invalid:V,rrwebId:H}=await window.checksum.testGenerator.getSelectorForChecksumId(y),Q=await window.checksum.testGenerator.getElementForChecksumId(y),se=Q instanceof HTMLOptionElement&&Q.value?Q.value:void 0;return{selector:E,locator:N,clickOffset:F,selectOptionValue:se,parentFramesSelectors:R,invalid:V,rrwebId:H}},l);if(Gan&&d.invalid&&d.rrwebId){this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${l}. Trying to use time machine...`);try{let y=await this.getSelectionDataForRRwebIdAtReduceHTMLTime(d.rrwebId);d={...d,...y}}catch{this.logger.log(`[getSelectionDataForChecksumId] error using time machine to get selector for checksumid: ${l}`)}this.logger.log(`[getSelectionDataForChecksumId] got selector: ${d.selector} for checksumid: ${l} from time machine`)}return d!=null&&d.selector||this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${l}. If checksumid is correct, try to change app rules preMapReducedHTMLSelectors to true`),d}async getSelectionDataForRRwebIdAtReduceHTMLTime(l){if(!this.rrwebEventAtLastReducedHTML)return;let p=this.getTimeMachine();if(p)return p.executeTask(d=>d.evaluate(async({rrwebId:y})=>await window.checksum.testGenerator.getInspectedElementSelectionResultByRRwebId(y,{ignoredIframesSelectors:[".replayer-wrapper > iframe"],fromTimeMachine:!0}),{rrwebId:l}),this.rrwebEventAtLastReducedHTML.timestamp,{name:"getSelectionDataForRRwebIdAtReduceHTMLTime"})}async getESRAForSelector(l,p,d){let y=await this.evaluateWithChecksum(async({selector:E,parentFramesSelectors:N})=>window.checksum.testGenerator.getSelectionDataForSelector(E,N),{selector:l,parentFramesSelectors:p});return y!=null&&y.esraMetadata&&d&&(y.esraMetadata.staticMetadata=await d(y.esraMetadata,l)),y==null?void 0:y.esraMetadata}async getMoreItemsForTemplate(l){return await this.evaluateWithChecksum(async p=>window.checksum.testGenerator.getMoreItemsForTemplate(p,{}),l)??{items:"",hasMoreItems:!1}}async getCurrentReducedHTML({retriesLeft:l=3,retryWaitMS:p=2e3,initialChecksumId:d="0",extractESRAForInterpretationRequiredElements:y=!1,stopFlashingElementsDetection:E=!1,assignChecksumIdsToAllElements:N}={}){let F=new Date;this.logger.log("[getCurrentReducedHTML] Fetching reduced HTML...");try{let{reducedHTML:R,currentChecksumId:V,flashingHTML:H,elementsForNodeInterpretation:Q,lastRRwebEvent:se}=await this.evaluateWithChecksum(async _e=>window.checksum.testGenerator.reduceHTML({},_e),{initialChecksumId:d,extractESRAForInterpretationRequiredElements:y,stopFlashingElementsDetection:E,assignChecksumIdsToAllElements:N}),G=new Date;return this.logger.log(`[getCurrentReducedHTML] Fetched reduced HTML in ${G.getTime()-F.getTime()}ms`),this.rrwebEventAtLastReducedHTML=se,{reducedHTML:R,flashingHTML:H,elementsForNodeInterpretation:Q,currentChecksumId:V}}catch(R){if(l>0)return this.logger.logError(`[getCurrentReducedHTML] Error: ${R.message}`),this.logger.logError(`Failed do obtain reduced HTML, trying again in ${p/1e3} seconds, ${l-1} to go.`),await aA(p),this.getCurrentReducedHTML({retriesLeft:l-1,retryWaitMS:p});throw R}}getActionEventCode(l){return hWt[l]}};e(_TestGenerationPageInteractor,"TestGenerationPageInteractor");var pEt=_TestGenerationPageInteractor;var _AlternateSelectorFallback=class _AlternateSelectorFallback extends zet{constructor(){super(...arguments);this.timeout=5*1e3}init(p){return super.init(p),this}async resolve(params){var p;try{let{method,args}=params,{checksumId}=this.data,alternateLocators=[];try{let d=await this.getMetadataForTestId();if(!(checksumId in d)||!d[checksumId].alternateLocators)throw new Error(`No alternate selection metadata found for id ${checksumId}`);alternateLocators=d[checksumId].alternateLocators.locators}catch(d){throw super.log(`Could not read alternate selector metadata file, ${d.message}`),d}try{this.log("Resolving alternate selectors locators");let elementsMap=new Map;await Promise.all(alternateLocators.map(async locatorExpression=>{let locator=eval(J0e(locatorExpression,"this.page"));try{await Dj(locator.first().waitFor({bypassChecksum:!0}),5e3),(await Dj(locator.elementHandles({bypassChecksum:!0}),1e3)).forEach(y=>{elementsMap.has(y)?elementsMap.set(y,elementsMap.get(y)+1):elementsMap.set(y,1)})}catch(d){return}}));let majorityElementHandle=(p=Array.from(elementsMap.entries()))==null?void 0:p.reduce((d,y)=>d[1]>y[1]?d:y)[0];if(!majorityElementHandle)throw this.errorMessage="No alternate element found",new Error(this.errorMessage);let totalElements=Array.from(elementsMap.values()).reduce((d,y)=>d+y,0),elementSelector=await this.evaluateWithChecksum(async({element:d})=>window.playwright.selector(d),{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(d){throw new Error(`Failed to execute compound selection fallback action: ${d.message}`)}}catch(d){this.errorMessage=d.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 yWt=_AlternateSelectorFallback;var TWt=class TWt{constructor(p){this.options=p}async handleError(p,d,y){let E=`Error in ${d} action during ${p} execution: ${y.message}`;throw new Error(E)}async guardedExecute(){try{return await(this.options.timeout!=null?Dj(this.execute(),this.options.timeout,"Execution timeout"):this.execute())}catch(p){return this.handleError(this.options.method,this.constructor.name,p)}}};e(TWt,"Action");var PNt=TWt,DWt=class DWt extends PNt{async execute(){return this.options.method in this.options.locator?this.options.locator[this.options.method](...this.options.args):this.options.locator}};e(DWt,"PlaywrightAction");var vWt=DWt,CWt=class CWt extends PNt{constructor(d,y){super(d);this.pageInteractor=y}};e(CWt,"APIAction");var bWt=CWt,EWt=class EWt extends bWt{constructor(p,d){super(p,d.pageInteractor)}async execute(){try{let{locator:p,args:d}=this.options,[y,E]=d,N=await p.screenshot({timeout:3e4}),R=(await this.pageInteractor.getTextDetection(N)).getRectangleByTextAndSizeRanking(y,E);if(!R)throw new Error("No matching text found");await p.click({position:R.center})}catch(p){throw new Error(`Error in canvas click action: ${p.message}`)}}};e(EWt,"CanvasClickAction");var xWt=EWt,NNt=class NNt{static createAction(p,d){return p.method in this.customActionMap?new this.customActionMap[p.method]({...p,timeout:15e3},d):new vWt(p)}};e(NNt,"ActionFactory"),NNt.customActionMap={canvasClick:xWt};var SWt=NNt;var kWt=class kWt{constructor(p){this.options=p;this.health=e(async()=>await fetch(`${this.options.apiURL}/client-api/runtime/api/health`,{headers:{ChecksumAppCode:this.options.apiKey}}).catch(p=>(console.log(p),null)),"health");this.getCanvasDetection=e(async p=>{try{let d=p.toString("base64");return await(await fetch(`${this.options.apiURL}/client-api/runtime/vision/text-detection`,{body:JSON.stringify({imageBuffer:d}),method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.options.apiKey}})).json()}catch(d){return console.log(d),null}},"getCanvasDetection")}};e(kWt,"ChecksumClient");var fEt=kWt;var wWt=class wWt{constructor(){this.config={}}};e(wWt,"PageInteractorAPI");var FNt=wWt;var AWt=class AWt extends FNt{constructor(d){super();this.config=d;this.getTextDetection=e(async d=>{let y=await this.api.getCanvasDetection(d);if(!y)throw new Error("No data returned from canvas detection");return y},"getTextDetection");this.config=d,this.api=new fEt({apiKey:d.apiKey,apiURL:d.apiURL})}};e(AWt,"RuntimePageInteractorAPI");var _Et=AWt;var ahr=require("path");var PWt=class PWt{constructor(p){this.options=p;this.navigatingFrames={};this.trackedFramesGuid=[];this.frameNavigationPromises={};this.onFrameNavigated=e(async p=>{let d=wQ(p);if(this.trackedFramesGuid.includes(d))return this.frameNavigationPromises[d]=new Promise(async y=>{await this.loadScript(p),y()}),this.frameNavigationPromises[d]},"onFrameNavigated");this.loadScript=e(async(p,{retriesLeft:d=3,retryWaitMS:y=2e3,useWrapper:E=!0}={})=>{var V,H;if(E&&this.scriptLoadWrapper)return this.scriptLoadWrapper(()=>this.loadScript(p,{retriesLeft:d,retryWaitMS:y,useWrapper:!1}),p);if(!this.addScriptTagOptions){console.warn("[InjectedScriptManager] addScriptTagOptions not set, skipping loadScript");return}if(this.isFrameClosed(p))return;let N=!1;try{N=this.scriptLoadCheck?await((V=this.scriptLoadCheck)==null?void 0:V.call(this,p)):!1}catch{}if(N||this.isFrameClosed(p))return;try{await p.addScriptTag(this.addScriptTagOptions)}catch(Q){if(d>0)return console.warn(`[InjectedScriptManager] Failed to add script to frame ${wQ(p)}, trying again in ${y/1e3} seconds, ${d-1} retries left.`,Q.message),await aA(y),this.loadScript(p,{retriesLeft:d-1,retryWaitMS:y,useWrapper:E});throw Q}let F=wQ(p),R=Date.now().toString(36)+Math.random().toString(36).substr(2);if(this.navigatingFrames[F]=R,this.options.scriptInitWait&&(console.log(`Waiting ${this.options.scriptInitWait}[ms] before onScriptLoad...`),await aA(this.options.scriptInitWait),console.log("Done waiting before onScriptLoad")),!this.isFrameClosed(p)){if(this.navigatingFrames[F]&&this.navigatingFrames[F]!==R)return console.log("Page navigated again, waiting on new promise..."),this.frameNavigationPromises[F];try{await((H=this.scriptLoadCallback)==null?void 0:H.call(this,p))}catch(Q){console.error("[WebDriver] onScriptLoad error",Q)}}},"loadScript");this.addScriptTagOptions=this.makeFrameInjectedScriptOptions()}setScriptLoadCallback(p){return this.scriptLoadCallback=p,this}setScriptLoadCheck(p){return this.scriptLoadCheck=p,this}setScriptLoadWrapper(p){return this.scriptLoadWrapper=p,this}async addTrackedFrame(p,d=!0){let y="mainFrame"in p?p.mainFrame():p,E=wQ(y);if(this.trackedFramesGuid.includes(E)||this.trackedFramesGuid.push(E),d)return this.onFrameNavigated(y)}getNavigationPromise(p){if(!p){console.warn("[InjectedScriptManager] getNavigationPromise called with undefined argument");return}let d=typeof p=="string"?p:"mainFrame"in p?wQ(p.mainFrame()):wQ(p);return this.frameNavigationPromises[d]}makeFrameInjectedScriptOptions(){switch(this.options.scriptSource){case"file":return this.options.scriptFile?{path:this.options.isScriptFileAbsolute?this.options.scriptFile:(0,ahr.join)(process.cwd(),this.options.scriptFile)}:void 0;case"url":return this.options.scriptURL?{url:this.options.scriptURL}:void 0;default:return}}isFrameClosed(p){return p.isDetached()||p.page().isClosed()}};e(PWt,"InjectedScriptManager");var dEt=PWt;var uZe=x7(require("path")),OWt=require("fs");var lsn=__dirname,phr=uZe.join(__dirname,".."),psn=(0,OWt.existsSync)(phr)?phr:lsn;lhr().config({path:uZe.resolve(psn,".env")});var ONt=process.env.DEV_MODE==="true";function _hr(){let l=__dirname;for(;!(0,OWt.existsSync)(uZe.join(l,"package.json"));)l=uZe.join(l,"..");return l}e(_hr,"findRoot");var fhr=uZe.join(_hr(),"vtg-build","index.html"),vC={isDevMode:ONt,logLevel:process.env.LOG_LEVEL??"warnings",checksumScript:{source:ONt?"url":"file",url:process.env.SCRIPT_URL,path:_hr()+"/checksumlib.js"},vtg:{writeLogFile:process.env.WRITE_LOG_FILE==="true",localBuildPath:fhr,appURL:ONt?process.env.VTG_APP_URL:`file://${fhr}`,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"};ONt&&console.log("Build",vC.buildTime);var LWt=class LWt{constructor(){this.frames={};this.pages=[];this.channels={};this.events=[]}register(p,d,y){if(this.frames[p])return;this.frames[p]=d;let E=d.page();this.pages.includes(E)||(this.pages.push(E),E.exposeFunction("checksumSendMessage",async(N,F)=>{let R=this.frames[N];if(!R)throw new Error(`Frame ${N} not found`);try{await R.evaluate(({message:V})=>{window.postMessage(V,"*")},{message:F})}catch{}}),E.exposeFunction("checksumSendBroadcastMessage",async(N,F)=>{let R=this.channels[N]??[];if(y){let V=require("fs"),H=require("path");this.events.push(...F),this.events.length%10===0&&V.writeFileSync(H.join(process.cwd(),"rrweb-player","events.json"),JSON.stringify(this.events))}R.forEach(async V=>{if(!(V.originFrameGuid&&V.originFrameGuid!==wQ(d)))try{V.handler?await V.handler(F):await d.evaluate(({message:H})=>{window.postMessage(H,"*")},{message:F})}catch{}})}),E.exposeFunction("checksumBringPageToFront",async N=>{let F=this.frames[N];F&&await F.page().bringToFront()}))}subscribeToChannel(p,d,{originFrame:y,handler:E}={}){var N;(N=this.channels)[p]??(N[p]=[]),this.channels[p].push({frame:d,originFrameGuid:y?wQ(y):void 0,handler:E})}unsubscribeFromChannel(p,d){var y;(y=this.channels)[p]??(y[p]=[]),this.channels[p]=this.channels[p].filter(E=>E.frame!==d)}};e(LWt,"FramesMsgBroker");var mEt=LWt;var mhr=require("@playwright/test");var hEt=require("jsdom");var MWt=class MWt{constructor(p){this.activeDOMType="checksumIds";this.rawReducedHTMLDom=new hEt.JSDOM(p),this.process()}process(){this.expandedChecksumIdsReducedDom=new hEt.JSDOM(this.rawReducedHTMLDom.serialize()),this.reducedHTMLDom=new hEt.JSDOM(this.rawReducedHTMLDom.serialize()),this.rrwebIdsReducedDom=new hEt.JSDOM(this.rawReducedHTMLDom.serialize());let p=e(F=>{F.window.document.body.querySelectorAll("[checksumid]:not([checksuminteractable])").forEach(V=>{V.removeAttribute("checksumid")})},"removeChecksumIdAttributeFromNonInteractable"),d=e((F,R)=>R.window.document.body.querySelectorAll(`[${F}]`).forEach(V=>V.removeAttribute(F)),"removeAttributeFromAllElements"),y=e(F=>d("checksuminteractable",F),"removeChecksumInteractableAttribute"),E=e(F=>d("checksumid",F),"removeChecksumIdAttribute"),N=e(F=>d("rrwebid",F),"removeRrwebIdAttribute");p(this.reducedHTMLDom),y(this.expandedChecksumIdsReducedDom),y(this.reducedHTMLDom),y(this.rrwebIdsReducedDom),N(this.expandedChecksumIdsReducedDom),N(this.reducedHTMLDom),E(this.rrwebIdsReducedDom)}getDOMForType(p){switch(p){default:case"checksumIds":return this.reducedHTMLDom;case"expandedChecksumIds":return this.expandedChecksumIdsReducedDom;case"rrwebIds":return this.rrwebIdsReducedDom}}async enrich(p){return await p(this.rawReducedHTMLDom),this.process(),this}setActiveDomType(p){this.activeDOMType=p}getActiveDom(){return this.getDOMForType(this.activeDOMType)}getActiveDOMString(){return this.getActiveDom().serialize()}getRrwebIdsReducedDomString(){return this.rrwebIdsReducedDom.serialize()}getDOMStringForType(p){return this.getDOMForType(p).serialize()}get raw(){return this.rawReducedHTMLDom}};e(MWt,"ReducedHTMLDOM");var gEt=MWt;var dhr=x7(require("path"));var BWt=class BWt{constructor(p="all"){this.listeners=[];this.logLevel=p}log(...p){try{let y=new Error().stack.split(`
1838
1838
  `)[4].trim().match(/\(([^)]+)\)/);if(!(y&&y[1]))throw new Error;let E=y[1].split(":"),N=E.slice(0,-2).join(":"),F=E[E.length-2],V=`${dhr.default.basename(N)}:${F}`;console.log("\x1B[34m",V,"\x1B[0m",...p),setTimeout(()=>this.listeners.forEach(H=>H.onLog(...p)),0)}catch{console.log(...p)}}addListener(p){this.listeners.push(p)}info(...p){this.logLevel==="all"&&this.log(...p)}warning(...p){(this.logLevel==="all"||this.logLevel==="warnings")&&this.log(...p)}error(...p){this.log(...p)}setLogLevel(p){this.logLevel=p}};e(BWt,"Logger");var RWt=BWt,Dtt=new RWt,fsn=Object.assign((...l)=>Dtt.info(...l),{info:e((...l)=>Dtt.info(...l),"info"),warning:e((...l)=>Dtt.warning(...l),"warning"),error:e((...l)=>Dtt.error(...l),"error"),setLogLevel:e(l=>Dtt.setLogLevel(l),"setLogLevel"),addLogListener:e(l=>Dtt.addListener(l),"addLogListener")}),Nh=fsn;var jWt=class jWt{constructor(p,d,y={headless:!0,logPerformance:!1,timestampBatchingEnabled:!1,sortByTimestamp:!1,taskTimeout:24e4}){this.frameMsgBroker=p;this.injectedScriptManager=d;this.options=y;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(p,{retriesLeft:d=3,retryWaitMS:y=1e3}={})=>{try{let{reducedHTML:E,currentChecksumId:N}=await p.evaluate(async F=>{var R,V;return(V=(R=window==null?void 0:window.checksum)==null?void 0:R.testGenerator)==null?void 0:V.reduceHTML({},F)},{stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:this.currentChecksumId,fromTimeMachine:!0,invalidateCache:!0});return this.currentChecksumId=N,{reducedHTML:E}}catch(E){if(d>0)return await aA(y),this.getReducedHTMLWithRetries(p,{retriesLeft:d-1,retryWaitMS:y});throw E}},"getReducedHTMLWithRetries");this.rrwebEventHandler=e(async p=>{let d=JSON.stringify(p);await this.timeMachineFrame.evaluate(function(y){let E=JSON.parse(y);return window.checksum.timeMachine.handleEvents(E)},d),p=null},"rrwebEventHandler")}getPage(){return this.timeMachineFrame.page()}getFrame(){return this.timeMachineFrame}async prepare(p,d,y){this.recordingFrame=p,this.frameMsgBroker.register("live",p),d?this.timeMachineFrame=d:this.timeMachineFrame=await this.prepareBrowserContextAndFrame(),y&&y(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(p){this.timeMachineBrowserContext=p}async executeTask(p,d=void 0,{name:y,beforeTimestamp:E=!1}={}){return new Promise((N,F)=>{let R=this.timeMachineTaskIndex++,V=e(async({shouldGoBack:H,shouldBatch:Q}={shouldGoBack:!0,shouldBatch:this.options.timestampBatchingEnabled})=>{if(this.timeMachineFrame.isDetached()&&F(),H){let _e=Date.now();await this.goBack(d,E),this.timeGoingBack+=Date.now()-_e}let G=[e(async()=>{try{let _e=Date.now(),ne=await Dj(p(this.timeMachineFrame),this.options.taskTimeout,()=>`Task execution timeout - ${y}, took ${Date.now()-_e}ms with timeout of ${this.options.taskTimeout}ms`);N(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===d).map(({task:_e})=>_e({shouldGoBack:!1,shouldBatch:!1}))),this.taskQueue=this.taskQueue.filter(_e=>_e.timestamp!==d),G.length&&console.log(`Batching to task "${y}, index: ${R} ${G.length-1} more tasks`)),await Promise.all(G)},"taskWrapper");this.taskQueue.push({name:y,task:V,timestamp:E?d-1:d,queuedAt:Date.now(),index:R}),this.runTasks()})}executeReducedHTMLTask(p){if(this.reducedHTMLCache[p]){let d=new gEt(this.reducedHTMLCache[p]);return Promise.resolve(d.getRrwebIdsReducedDomString())}return this.executeTask(async d=>{let y="",E=await this.getReducedHTMLWithRetries(d);return y=E==null?void 0:E.reducedHTML,y&&(this.reducedHTMLCache[p]=y),new gEt(y).getRrwebIdsReducedDomString()},p,{name:"getReducedHTMLForTimestamp"})}goBack(p,d=!1){return this.currentBeforeTimestamp===d&&this.currentTimestamp===p?Promise.resolve():(this.currentTimestamp=p,this.currentBeforeTimestamp=d,this.timeMachineFrame.evaluate(({timestamp:y,beforeTimestamp:E})=>y===void 0?window.checksum.timeMachine.goLive():window.checksum.timeMachine.goBack(y,{beforeTimestamp:E}),{timestamp:p,beforeTimestamp:d}))}goLive(){return this.timeMachineFrame.evaluate(()=>window.checksum.timeMachine.goLive())}popTask(){return this.options.sortByTimestamp&&(this.taskQueue=this.taskQueue.sort((p,d)=>p.timestamp-d.timestamp)),this.taskQueue.shift()}async runTasks(){if(this.isRunning)return;this.isRunning=!0;let p=this.popTask(),d=Date.now();try{let y=Date.now()-p.queuedAt;Nh.info(`Running task, timestamp: ${p.timestamp} \x1B[36m${p.name}\x1B[0m, index: ${p.index}, was pending for`,y),await p.task();let E=Date.now()-d;this.timeRunningTasks+=E,Nh.info("Finished running task, took",E,"ms.","Queue length:",this.taskQueue.length),this.tasksExecuted++}catch(y){Nh.error("Task execution error:",y)}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 p=await mhr.chromium.launch({devtools:!1,headless:this.options.headless});return this.timeMachineBrowserContext=await p.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 p="rrweb";this.frameMsgBroker.subscribeToChannel(p,this.timeMachineFrame,{originFrame:this.recordingFrame,handler:this.rrwebEventHandler}),this.timeMachineFrame.page().on("close",()=>this.frameMsgBroker.unsubscribeFromChannel(p,this.timeMachineFrame))}async toggleTimeMachineHandleEvents(p){try{await this.timeMachineFrame.evaluate(d=>window.checksum.timeMachine.setShouldHandleEvents(d),p)}catch{}}};e(jWt,"ChecksumTimeMachine");var wNe=jWt;var _sn=require("@playwright/test");var xLn=1e3*30;var hhr=require("fs");var ghr=!1;function yEt(l){ghr=l}e(yEt,"setLogToConsole");function XG(...l){ghr&&console.log(...l)}e(XG,"log");async function t_r(l,p,d,y=6e4){if(!(p in l))return l;let E=e(()=>l[p](...d),"executor");return y===null?E():Dj(E(),y,"Execution timeout")}e(t_r,"executePlaywrightMethodWithTimeout");function qWt(l,{role:p,environment:d}={},y=!1){var R,V;let E;if(d&&(E=(R=l.environments)==null?void 0:R.find(({name:H})=>d===H)),E||(E=(V=l.environments)==null?void 0:V.find(({default:H})=>H)),!E)throw new Error("Environment not found. Please make sure your environments are properly defined in the checksum.config.ts file.");let N=E.users,F;if(N&&(p!==void 0&&(F=N.find(H=>H.role===p)),F||(F=N.find(H=>H.default))),!F)throw new Error(`User not found. Please make sure the users array for the "${E.name}" environment is properly defined in the checksum.config.ts file.`);if(d&&E.name!==d){if(y)throw new Error(`Could not find environment with name "${d}" in config file`);console.warn(`Could not find environment with name "${d}" in config file, trying to use default environment`)}if(p&&F.role!==p){if(y)throw new Error(`Could not find user with role "${p}" for environment "${d}" in config file`);console.warn(`Could not find user with role "${p}" for environment "${d}" in config file, trying to login with environment's default user`)}return{environment:E,user:F}}e(qWt,"resolveEnvironment");function hsn(l){let p=`${l??YUt()}/login.ts`;if(!(0,hhr.existsSync)(p))throw console.warn(`Could not locate the login.ts file. Please make sure your login file exists at ${p}`),new Error("Could not find login.ts file");try{return require(p).default}catch(d){throw console.warn("Error loading login.ts file",d),d}}e(hsn,"requireLogin");async function gsn(l,p,{environment:d,user:y,config:E}){try{let N=e(()=>p(l,{environment:d,user:y,config:E}),"performLogin");"checksumAI"in l?await l.checksumAI(`Log in${y!=null&&y.role?` using ${y.role} role`:""}${d!=null&&d.name?` in ${d.name} environment`:""}`,N):await N()}catch(N){throw console.warn(`The login method threw an exception, please check the login.ts file for the following error:
1839
1839
  `,N),N}}e(gsn,"proceedWithLogin");function JWt(l){let{config:p,folder:d,throwIfAuthFailed:y}=l,E=hsn(d);return async(N,{role:F,environment:R}={})=>{let{environment:V,user:H}=qWt(p,{role:F,environment:R},l.throwIfEnvInfoInvalid);if(y&&!H)throw new Error("Could not find user credentials matching the provided role and/or environment");await gsn(N,E,{environment:V,user:H,config:p})}}e(JWt,"makeUnboundLogin");var Pwt=require("fs"),z5r=x7(require("child_process")),a4e=require("path");var LQ=require("fs"),YIt=x7(require("child_process")),ace=require("path");var Sbr=x7(xbr());var $It=(d=>(d.Launched="Launched",d.Log="Log",d))($It||{});var dYt=class dYt{constructor(p,d){this.config=p;this.options=d;this.didIdentify=!1;this.isolatedMode=!1;this.internalId=process.env.CHECKSUM_TRACE_INTERNAL_ID??xCt(6)}async identify(p,d,y=!1){let E=this.identifier;this.identifier=p,this.didIdentify=!0,!(!this.analyticsBase||y)&&(E&&(this.analyticsBase.alias({userId:p,previousId:E}),await aA(10)),this.analyticsBase.identify({userId:p,anonymousId:E,traits:{...d,...this.getTraits()}}))}log(...p){this.trackEvent("Log",{lines:p})}setIsolatedMode(){this.isolatedMode=!0}trackEvent(p,d={}){if(!(!this.analyticsBase||this.isolatedMode))try{!this.didIdentify&&!this.identifier&&(this.identifier=Date.now().toString()),d.internalId=this.internalId,this.track(p,d),this.logToConsole(p,d)}catch(y){console.error(`Failed to track event: ${p} with payload:`,d,y)}}logToConsole(p,d){this.options.logToConsole&&console.log(`Event Tracked: ${p}`,d)}getTraits(){return{}}};e(dYt,"BaseAnalytics");var HIt=dYt;var mYt=class mYt extends HIt{constructor(p,d){super(p,d),p!=null&&p.writeKey&&(this.analyticsBase=new Sbr.default({...p,flushAt:1,flushInterval:1e3}))}async flush(){this.analyticsBase&&await this.analytics.flush()}async close(){this.analyticsBase&&await this.analytics.closeAndFlush({timeout:1e4})}track(p,d){if(this.analyticsBase)try{let y=this.didIdentify?{userId:this.identifier}:{anonymousId:this.identifier};this.analytics.track({...y,event:p,properties:d})}catch(y){console.error(`Failed to track event: ${p} with payload:`,d,y)}}get analytics(){return this.analyticsBase}};e(mYt,"NodeAnalytics");var GIt=mYt;var irt=(_r=>(_r.RuntimeError="Runtime Error",_r.TestRunMonitorError="Test Run Monitor Error",_r.ChecksumConfigError="Checksum Config Error",_r.InitializationError="Initialization Error",_r.UploadStart="Upload Start",_r.UploadComplete="Upload Complete",_r.UploadFailed="Upload Failed",_r.TestRunStarted="Test Run Started",_r.TestRunEnd="Test Run End",_r.TestRunFailed="Test Run Failed",_r.AllUploadsComplete="All Uploads Complete",_r.UploadsCompleteWithErrors="Upload Complete With Errors",_r.ReportComplete="Report Complete",_r.ReportUploadError="Report Upload Error",_r.RuntimeTimeout="Runtime Timeout",_r.CompletionStatus="Completion Status",_r.RuntimeComplete="Runtime Complete",_r.ChecksumConfig="Checksum Config",_r.PlaywrightConfig="Playwright Config",_r.FallbackStart="Fallback Start",_r.ActionExecutionFailure="Action Execution Failure",_r.AIFallbackStep="AI Fallback Step",_r.ActionFallbackExecution="Action Fallback Execution",_r.AssertionFallbackExecution="Assertion Fallback Execution",_r.AssertionFailure="Assertion Failure",_r.CompoundSelectionFailure="Compound Selection Failure",_r))(irt||{});var TZe=class TZe extends GIt{constructor(d,y,E){super(y,E);this.traits=d}static getInstance(d={},y={},E={logToConsole:!0}){return TZe.instance||(TZe.instance=new TZe(d,y,E)),TZe.instance}setTestId(d){this.testId=d}event(d){this.trackEvent(d)}eventWithMessage(d,y){this.trackEvent(d,{message:y})}runtimeError(d){this.trackEvent("Runtime Error",d)}completionStatus(d){this.trackEvent("Completion Status",{stats:d})}reportComplete(d,y){this.trackEvent("Report Complete",{stats:d,reportUrl:y})}allUploadsComplete(){this.trackEvent("All Uploads Complete")}uploadsCompleteWithErrors(d){this.trackEvent("Upload Complete With Errors",{errors:d})}testsStart(){this.trackEvent("Test Run Started")}testsEnd(){this.trackEvent("Test Run End")}testsFailed(){this.trackEvent("Test Run Failed")}checksumConfig(d){this.trackEvent("Checksum Config",d)}playwrightConfig(d){this.trackEvent("Playwright Config",d)}uploadStart(d){this.trackEvent("Upload Start",{filename:d})}uploadComplete(d){this.trackEvent("Upload Complete",{filename:d})}uploadFailed(d,y){this.trackEvent("Upload Failed",{filename:d,error:y})}fallbackStart(d){d.shouldSendToAnalytics&&this.trackEvent("Fallback Start",{description:d.toString(),testId:this.testId})}actionFallbackExecution(d,y){y.shouldSendToAnalytics&&this.trackEvent("Action Fallback Execution",{success:d,...y.getAnalyticsPayload(),testId:this.testId})}actionExecutionFailure(d){this.trackEvent("Action Execution Failure",{...d,testId:this.testId})}aiFallbackStep(d,y){this.trackEvent("AI Fallback Step",{sessionId:d,...y,testId:this.testId})}compoundSelectionFailure(d,y){this.trackEvent("Compound Selection Failure",{error:d,compoundSelector:y,testId:this.testId})}assertionFailure(d,y,E){this.trackEvent("Assertion Failure",{thought:d,error:y,matcher:E,testId:this.testId})}assertionFallbackExecution(d,y){y.shouldSendToAnalytics&&this.trackEvent("Assertion Fallback Execution",{success:d,...y.getAnalyticsPayload(),testId:this.testId})}track(d,y){if(!this.getAllowedEvents().includes(d))throw new Error(`Invalid runtime event type: ${d}`);super.track(d,y)}getTraits(){return this.traits}getAllowedEvents(){return[...Object.values(irt),...Object.values($It)]}};e(TZe,"RuntimeAnalytics");var KIt=TZe;var hYt=class hYt{constructor(p,d=!1){this.args=p;this.debugMode=d;this.checksumAppUrl="https://app.checksum.ai";this.childProcesses=[];this.printError=e(p=>{console.log("\x1B[31m%s\x1B[0m",p,"\x1B[0m")},"printError");this.processConfigArg(),["SIGINT","SIGTERM"].forEach(y=>{process.on(y,()=>{this.cleanup(),process.exit()})}),this.checksumRuntimeVersion=this.getChecksumRuntimeVersion()}getChecksumRuntimeVersion(){if(this.checksumRuntimeVersion)return this.checksumRuntimeVersion;try{return require("./package.json").version}catch{return"unknown"}}loadTracer(){let p=vC.testRun.monitoring.segment;this.trace=KIt.getInstance({version:this.checksumRuntimeVersion},p,{logToConsole:this.debugMode})}async execCmd(p,d={}){let y={...process.env,...d},E=await YIt.spawn(p,{env:y,shell:!0,stdio:"inherit"});return this.childProcesses.push(E),new Promise((F,R)=>{E.on("exit",V=>{V===0?F(!0):R(new Error(`Checksum failed execution with code: ${V} `)),this.childProcesses=this.childProcesses.filter(H=>H!==E)})})}async getCmdOutput(p){return new Promise(function(d,y){YIt.exec(p,(E,N,F)=>{if(E){y(`Error executing command: ${E.message}`);return}d(N.trim())})})}validateAuthExists(){this.checksumRoot||this.findChecksumRoot();let p=(0,ace.join)(this.checksumRoot,".auth");(0,LQ.existsSync)(p)||(0,LQ.writeFileSync)(p,"{}")}loadChecksumData(){this.locateChecksumLibs(),this.setChecksumConfig()}async patchPlaywright(p=!1){XG("Patching playwright",p);let d=(0,ace.join)(__dirname,"./scripts/patch.js");(0,LQ.existsSync)(d)||(d=(0,ace.join)(__dirname,"../../../scripts/src/patch_playwright.js"));let y=`node "${d}"${p?" off":""}`;try{await this.execCmd(y,{PROJECT_ROOT:this.projectRootDirectory,RUNTIME:"true"})}catch(E){console.log("Error patching playwright",E.message)}}getPlaywrightConfigFilePath(){return(0,ace.join)(this.checksumRoot,"playwright.config.ts")}buildVolatileConfig(){if(!this.volatileChecksumConfig)return;let p=this.getVolatileConfigPath(),d=`
1840
1840
  import { RunMode, getChecksumConfig } from "@checksum-ai/runtime";
@@ -1913,7 +1913,7 @@ if (typeof globalThis.requireTs === "undefined") {
1913
1913
  `)}getLocalSavedData(p){let d=`${this.testAssetsManager.getLocalSavePath()}/${p}/test.json`,y=this.readJsonFile(d);return y?{...y,executedActions:y.executedActions.map(E=>({...E,timestamp:void 0}))}:null}readJsonFile(p){try{let d=(0,JZe.readFileSync)(p,"utf-8");return JSON.parse(d)}catch(d){return Nh.error(`Error reading or parsing JSON file: ${d}`),null}}makeDraftData(){let p=this.userStoryService.getStory(),d=this.userStoryService.getTestGenerationData(),y=this.userStoryService.getEnvInfo();return{actions:this.actionsManager.actions,internalTestId:d.internalTestId,environmentUserId:y.user.username,description:p.goal}}async generateTestFileString(p){try{let d=this.makeDraftData(),y=p?`${p}.draft.spec.ts`:`test-${d.internalTestId}.draft.spec.ts`,E=await this.apiService.post("test-generation/generate-test-file-string",d);if(!E.ok)throw new Error(`test generation request failed: ${E.statusText}`);let N=await E.text();$6r(N,y,this.testAssetsManager.getLocalSavePath())}catch(d){throw Nh.error("Failed to generate test file string",d),new Error("Failed to generate test file string")}}localSave(){let p=JSON.stringify(this.replayJSON,null,2),d=this.testAssetsManager.getAssetsFolderPath();(0,JZe.writeFileSync)(`${d}/test.json`,p),(0,JZe.writeFileSync)(`${this.testAssetsManager.getLocalAutoSavePath()}/test.json`,p)}get replayJSON(){var p;return{executedActions:this.actionsManager.actions,testGenerationData:this.userStoryService.getTestGenerationData(),settings:{baseURL:(p=this.config.environments.find(d=>d.default))==null?void 0:p.baseURL,assetsFolderPath:this.testAssetsManager.getAssetsFolderPath(),didLogin:this.actionsService.hasLoggedIn(),traceFilePath:this.testAssetsManager.getTraceFilePath(),harFilePath:this.testAssetsManager.getHarFilePath()},story:this.userStoryService.getStory()}}async localBackup(p){if(p){this.testAssetsManager.setCurrentSaveAsLocation(p);let d=this.testAssetsManager.getLocalSaveAsPath();H6r(this.testAssetsManager.getLocalAutoSavePath(),d)}return this.saveTestFile()}getIsFolderAlreadyExistsInDrafts(p){try{let d=`${this.testAssetsManager.getLocalSavePath()}/${p}`;return(0,JZe.statSync)(d).isDirectory()}catch(d){if(d.code==="ENOENT")return!1;throw d}}async saveToCloud(){try{if(!this.userStoryService.hasTestGenerationData()){Nh("No test generation data, can't upload");return}let p=await this.userStoryService.createTestGeneration(),d=new mLt(this.apiService.getBaseURL(),this.config.apiKey,null,()=>`test-generation/${p}/get-upload-url`),y=e(R=>({complete:!1,error:!1,response:void 0,info:R}),"buildUploadAsset"),E=y({type:"trace",path:this.testAssetsManager.getTraceFilePath()}),N=y({type:"har",path:await h3r(this.testAssetsManager.getHarFolderPath())});await Promise.all([d.uploadAsset(E),d.uploadAsset(N)]);let F=this.actionsManager.actions.map(R=>({...R,parentFramesSelectors:R.parentFramesSelectors?R.parentFramesSelectors.filter(V=>V!=="iframe"):void 0}));await this.apiService.post(`test-generation/${p}/completed`,{actions:F})}catch(p){Nh.error("Failed to upload test",p)}}};e(FZt,"VtgStorageService");var TLt=FZt;var IZt=class IZt{constructor(p,d){this.apiService=p;this.config=d}getStory(){return this.story}getTestGenerationData(){return this.userStoryTestGeneration}hasTestGenerationData(){var p;return!!((p=this.userStoryTestGeneration)!=null&&p.internalTestId)}setStoryInfo(p,d){this.story=p,this.userStoryTestGeneration=d}async fetchStory(p){if(vC.vtg.useFakeStory){console.log("Using fake flow data"),this.story={...vC.vtg.fakeStory,environment:{name:void 0,userRole:void 0}},this.userStoryTestGeneration={internalTestId:vC.vtg.fakeTestGeneration.internalTestId,generationBatchId:vC.vtg.fakeTestGeneration.generationBatchId};return}if(!p)throw new Error("no story id provided");let y=await(await this.apiService.post(`test-generation/info/${p}`)).json();if(!(y!=null&&y.id))throw new Error(`Story ${p} not found`);console.log("Received flow data:",y);let{id:E,title:N,steps:F,startUrl:R,userRole:V,environment:H,internalTestId:Q,generationBatchId:se}=y;this.userStoryTestGeneration={internalTestId:Q,generationBatchId:se},this.story={id:E,goal:N,instructions:F,url:R,environment:{userRole:V,name:H}}}getEnvInfo(){return qWt(this.config,{role:this.story.environment.userRole,environment:this.story.environment.name})}async createTestGeneration(){if(!this.story.id)return;let p=await this.apiService.post(`test-generation/create/${this.story.id}`,{internalTestId:this.userStoryTestGeneration.internalTestId,testGenerationBatchId:this.userStoryTestGeneration.generationBatchId}),{testGenerationId:d}=await p.json();return this.userStoryTestGeneration.testGenerationId=d,d}};e(IZt,"VtgUserStoryService");var DLt=IZt;var OZt=class OZt{constructor(){this._executedActions=[];this.onActionExecuted=this.pushExecutedActionOrAddAfterParent.bind(this)}get actions(){return this._executedActions}set executedActions(p){var d;this._executedActions=p,(d=this.storageService)==null||d.localSave()}addAction(p){var d;this._executedActions.push(p),(d=this.storageService)==null||d.localSave()}setActions(p){this._executedActions=p}updateAssertionById(p,d){this.executedActions=this._executedActions.map(y=>{var E;if(y.id===p){let N=!!((E=y.assertions)!=null&&E.find(({id:R})=>R===d.id)),F={...y};return N?F.assertions=y.assertions.map(R=>R.id===d.id?Object.assign(R,d):R):F.assertions=[...y.assertions??[],d],{...F,assertions:F.assertions.sort((R,V)=>R.timestamp!==V.timestamp?R.timestamp-V.timestamp:R.createdAt-V.createdAt)}}return y})}setStorageService(p){this.storageService=p}createAction(p){var V,H,Q;let{id:d,data:y,options:E,type:N}=p,F={id:d,...y},R=[...this._executedActions];switch(E==null?void 0:E.type){case"insertAfter":{let se=this.findActionOrAssertionById(E.afterStepId),G=R.findIndex(_e=>_e.id===se.action.id);if(se.assertion||(H=(V=se.action)==null?void 0:V.assertions)!=null&&H.length){let _e=se.assertion??se.action.assertions[0],{before:ne,after:le}=J7n(((Q=R[G])==null?void 0:Q.assertions)??[],_e.id,!!se.assertion);R[G].assertions=ne,F.assertions=le.map(Ue=>({...Ue,actionId:F.id}))}G!==-1?R.splice(G+1,0,F):R.push(F);break}case"insertLast":R.push(F);break;case"replace":{let se=R.findIndex(G=>G.id===E.stepId);se!==-1&&R.splice(se,1,F);break}case"replaceLast":R.length>0&&(R[R.length-1]=F);break}this.executedActions=R}pushExecutedActionOrAddAfterParent(p,d={}){if(d.previousActionId){let y=this._executedActions.findIndex(({id:E})=>E===d.previousActionId);if(y!==-1){let E={...p,timestamp:this._executedActions[y].timestamp+1};this._executedActions=[...this._executedActions.slice(0,y+1),E,...this._executedActions.slice(y+1)]}}else this.executedActions=Array.isArray(p)?[...this._executedActions,...p]:[...this._executedActions,p]}addManualActionsToExecuted(p){this.executedActions=[...this._executedActions,p]}updateExecutedAction(p){let d=this._executedActions.findIndex(({id:y})=>y===p.id);d!==-1&&(this.executedActions=[...this._executedActions.slice(0,d),{...this._executedActions[d],...p},...this._executedActions.slice(d+1)])}deleteStep(p,d,y={assertionsOnly:!1}){d==="Action"?y.assertionsOnly?this.executedActions=this._executedActions.map(E=>E.id===p?{...E,assertions:[]}:E):this.executedActions=this._executedActions.filter(E=>E.id!==p):d==="Assertion"&&(this.executedActions=this._executedActions.map(E=>(E.assertions=(E.assertions??[]).filter(N=>N.id!==p),E)))}clearTestSteps(p=!0){if(p){let{navigation:d,login:y}=this.findLoginAndNavigationActions();this.executedActions=this._executedActions.reduce((E,N)=>([d==null?void 0:d.id,y==null?void 0:y.id].includes(N.id)&&E.push({...N,assertions:[]}),E),[])}else this.executedActions=[];return this._executedActions}reloadTestSteps(p){this.clearTestSteps(!1),this.executedActions=p}findLoginAndNavigationActions(){let p=this._executedActions.find(({eventCode:y})=>y==="navigation"),d=this._executedActions.find(({eventCode:y})=>y==="login");return{navigation:p,login:d}}addAssertionToAction(p,d){this.executedActions=this._executedActions.map(y=>{if(y.id!==p.actionId)return y;if(y.assertions||(y.assertions=[]),d){let E=y.assertions.findIndex(({id:N})=>d===N);y.assertions.splice(E+1,0,p)}else y.assertions=[p,...y.assertions??[]];return y})}findActionByAssertionId(p){return this._executedActions.find(({assertions:d=[]})=>d.find(y=>y.id===p))}findActionOrAssertionById(p){let d={action:null,assertion:null};return this._executedActions.forEach(y=>{y.id===p&&(d.action=y);let E=(y.assertions??[]).find(N=>N.id===p);E&&(d={action:y,assertion:E})}),d}};e(OZt,"VtgActionsManager");var CLt=OZt,J7n=e((l,p,d=!0)=>{let y=Number(d),E=l.findIndex(R=>R.id===p);if(E===-1)return{before:l,after:[]};let N=l.slice(0,E+y),F=l.slice(E+y);return{before:N,after:F}},"splitArrayAtId");var Drr=x7(E5r()),F5r=x7(require("net")),I5r=x7(xtr()),O5r=x7(N5r());var Srr=class Srr{constructor(p,d,y){this.app=p;this.assertionsService=d;this.actionsManager=y}setupEndpoints(){this.app.post("/api/createStep",async(p,d)=>{let y=p.body;try{if(y.type==="Assertion"){let E=this.assertionsService.createAssertion(y);return d.status(200).json(E)}if(y.type==="Action")return this.actionsManager.createAction(y),d.send("success")}catch(E){return Nh.error("/api/createStep error:",E),d.status(500).send(E)}}),this.app.patch("/api/updateStep",async(p,d)=>{let y=p.body;try{if(y.type==="Assertion"){let E=await this.assertionsService.updateAssertion({id:y.id,data:y.data});d.status(200).json(E)}if(y.type==="Action")return this.actionsManager.updateExecutedAction({...y.data,id:y.id}),d.send("success")}catch(E){return d.status(500).send(E)}}),this.app.delete("/api/deleteStep",async(p,d)=>{let{id:y,options:E,type:N}=p.body;try{this.actionsManager.deleteStep(y,N,E)}catch(F){return d.status(500).send(F)}return d.status(200).send({message:"Success!"})}),this.app.post("/api/clear-test",async(p,d)=>{try{let y=this.actionsManager.clearTestSteps();return d.status(200).send(y)}catch(y){return d.status(500).send(y)}})}};e(Srr,"VtgStepsController");var WMt=Srr;var Trr=class Trr{constructor(p,d){this.app=p;this.locatorsService=d}setupEndpoints(){this.app.post("/api/locators/play",async(p,d)=>{let y=p.body;try{let E=await this.locatorsService.verifyLocatorOrSelector(y);return d.status(200).send(E)}catch(E){return d.status(400).send({error:E.message})}}),this.app.post("/api/locators/test-identical",async(p,d)=>{let{locator:y,compareLocator:E,timestamp:N}=p.body;try{let F=await this.locatorsService.verifyAndCompareLocatorOnTimemachine(y,E,N);return d.status(200).send(F)}catch(F){return d.status(400).send({error:F.message})}}),this.app.post("/api/ai/locators/generate",async(p,d)=>{let{step:y,target:E,processId:N}=p.body;y.isDefaultThought&&(y.thought=null);try{this.locatorsService.generateAILocators(y,E,N);let F={processId:N,stepId:E.id,success:!0};d.status(200).send(F)}catch(F){d.status(400).send({processId:N,success:!1,error:F.message})}}),this.app.post("/api/ai/locators/extract-css",async(p,d)=>{let{step:y,target:E,processId:N,llmLocators:F}=p.body;y.isDefaultThought&&(y.thought=null);try{this.locatorsService.extractCSS(y,E,N,F);let R={processId:N,stepId:E.id,success:!0};d.status(200).send(R)}catch(R){d.status(400).send({processId:N,error:R.message})}}),this.app.post("/api/ai/locators/filter",async(p,d)=>{let{step:y,target:E,processId:N,candidates:F}=p.body;y.isDefaultThought&&(y.thought=null);try{this.locatorsService.filterLocators(y,E,N,F);let R={processId:N,stepId:E.id,success:!0};d.status(200).send(R)}catch(R){d.status(400).send({processId:N,error:R.message})}}),this.app.delete("/api/ai/locators/process/:id",async(p,d)=>{let y=p.params.id;try{this.locatorsService.cancelProcess(y),Nh("Cancelled process",y),d.status(200).send({success:!0})}catch(E){d.status(400).send({error:E.message})}})}};e(Trr,"VtgLocatorsController");var $Mt=Trr;var Crr=class Crr{constructor(p,d,y,E,N,F,R,V,H){this.actionsService=p;this.assertionsService=d;this.locatorsService=y;this.aiTestGenerationService=E;this.aiAssertionsService=N;this.aiThoughtsService=F;this.actionsManager=R;this.storageService=V;this.settingsService=H}async start(){return this.app=(0,Drr.default)(),this.app.use((0,O5r.default)()),this.app.use(I5r.default.json({limit:"50mb"})),this.app.use(Drr.default.raw({type:"multipart/form-data",limit:"50mb"})),this.port=await this.acquirePortNumber(),new WMt(this.app,this.assertionsService,this.actionsManager).setupEndpoints(),this.setupEndpoints(),new $Mt(this.app,this.locatorsService).setupEndpoints(),new Promise(p=>{this.app.listen(this.port,()=>{console.log(`Express server running on port ${this.port}`),p()})})}setupEndpoints(){this.app.get("/api",async(p,d)=>{d.send("success")}),this.app.post("/api/test/generate-test-file-string",async(p,d)=>{try{return await this.storageService.generateTestFileString(p.body.fileName),d.send("success")}catch(y){return d.status(400).send({error:y.message})}}),this.app.post("/api/test/upload",async(p,d)=>(await this.storageService.saveToCloud(),d.send("success"))),this.app.post("/api/test/local-save",async(p,d)=>{await this.storageService.localSave(),d.send("success")}),this.app.post("/api/reload-test-from-file",async(p,d)=>{try{if(!this.storageService.isLoadedFromTestFile)return d.status(404).send("No test file found");let y=await this.storageService.reloadTestFromFile();return d.status(200).send(y)}catch(y){return console.log("failed to reload test from file",y),d.status(500).send(y.message)}}),this.app.post("/api/test/verify-save-location",async(p,d)=>{try{let y=this.storageService.getIsFolderAlreadyExistsInDrafts(p.body.location);d.send({exists:y})}catch(y){d.status(400).send({error:y})}}),this.app.post("/api/test/backup",async(p,d)=>{let{backupFolderName:y}=p.body;if(!G6r(y))return d.status(400).send({error:"Invalid folder name"});let E=await this.storageService.localBackup(y);d.send(E)}),this.app.post("/api/ai/init",async(p,d)=>{await this.aiTestGenerationService.init(),d.send("success")}),this.app.post("/api/ai/iterate",async(p,d)=>{let y=p.body,E=await this.aiTestGenerationService.iterate(y);return E?d.status(200).json(E):d.status(400).send("no action generated")}),this.app.post("/api/thoughts/actions/generate",async(p,d)=>{let y=p.body,{processId:E,action:{id:N}}=y;try{this.aiThoughtsService.generateActionThoughts(y);let F={processId:E,stepId:N,success:!0};d.status(200).send(F)}catch(F){return d.status(400).send({processId:E,error:F.message})}}),this.app.post("/api/thoughts/assertions/generate",async(p,d)=>{let y=p.body,{processId:E,assertion:{id:N}}=y;try{this.aiThoughtsService.generateAssertionThought(y);let F={processId:E,stepId:N,success:!0};d.status(200).send(F)}catch(F){return d.status(400).send({processId:E,error:F.message})}}),this.app.post("/api/thoughts/stop-generate",async(p,d)=>{let y=p.body;this.aiThoughtsService.stopGeneratingThought(y.stepId);let E={stepId:y.stepId};return d.status(200).send(E)}),this.app.post("/api/assertions/generate",(p,d)=>{let y=p.body,{processId:E}=y;try{this.aiAssertionsService.generateAiAssertions(y);let N={processId:E,stepId:y.id,success:!0};return d.status(200).json(N)}catch(N){return d.status(500).send({processId:E,error:N.message})}}),this.app.post("/api/assertions/stop-generate",(p,d)=>{let{id:y}=p.body,E={stepId:y};return this.aiAssertionsService.stopGenerateAiAssertions(y),d.status(200).send(E)}),this.app.post("/ai/stop",async(p,d)=>{this.aiTestGenerationService.stop()}),this.app.post("/api/assertion/verify/time-machine",async(p,d)=>{let y=p.body,E=await this.assertionsService.verifyOnTimeMachine(y);return d.status(200).send(E)}),this.app.post("/api/assertion/verify/live",async(p,d)=>{let y=p.body;try{let E=await this.assertionsService.verifyOnLive(y),N=E.success?200:404;return d.status(N).send(E)}catch(E){return d.status(404).send({success:!1,message:String(E)})}}),this.app.post("/api/assertion/save",async(p,d)=>{let y=p.body;try{let E=await this.assertionsService.updateAssertion(y);d.status(200).json(E)}catch(E){d.status(400).send({error:E.message})}}),this.app.post("/api/steps/execute",async(p,d)=>{let y=p.body;try{let E=null;return bAn(y)?E=await this.aiTestGenerationService.executeAction(y):xAn(y)&&(E=await this.actionsService.executeAction(y)),d.status(200).json(E)}catch(E){return d.status(400).send({error:E.message})}}),this.app.post("/api/upload-files",async(p,d)=>{try{await this.actionsService.uploadFiles(p.body.files)}catch(y){return d.status(500).send(y)}return d.status(200).send({message:"File uploaded successfully!"})}),this.app.post("/api/steps/add-manual-action",async(p,d)=>{let y=p.body;return this.actionsManager.addManualActionsToExecuted(y.action),d.send("success")}),this.app.put("/api/steps",async(p,d)=>{let y=p.body;try{this.actionsManager.pushExecutedActionOrAddAfterParent(y.action,y.options)}catch(E){return d.status(500).send(E)}return d.send("success")}),this.app.get("/api/settings",async(p,d)=>{let y=this.settingsService.getSettings();return d.status(200).send(y)}),this.app.post("/api/settings",async(p,d)=>(this.settingsService.updateSettings(p.body),d.status(200).send({message:"Success!"})))}async acquirePortNumber(){return await new Promise((p,d)=>{let y=F5r.default.createServer();y.unref(),y.on("error",d),y.listen(0,()=>{let E=y.address().port;y.close(()=>{p(E)})})})}async evaluateServerPort(p){if(!p)throw new Error("Page not initialized");await p.evaluate(d=>{window.vtg.setServerPort(d)},this.port)}};e(Crr,"VtgExpressServer");var HMt=Crr;function bAn(l){var p;return((p=l.options)==null?void 0:p.isAISuggestion)===!0}e(bAn,"isAIExecuteActionArgs");function xAn(l){var p;return((p=l.options)==null?void 0:p.isAISuggestion)===!1}e(xAn,"isManualExecuteActionArgs");var GMt=require("fs");var Err=class Err{constructor(p,d,y){this.projectRootDirectory=p;this.checksumRoot=d;this.vtgTestFileRunConfig=y;this.localSaveFolderPath=`${this.checksumRoot}/drafts`}createTestGenerationAssetsFolders(){this.assetsFolderPath=this.projectRootDirectory+`/tg-assets/${Date.now()}`,(0,GMt.mkdirSync)(this.assetsFolderPath,{recursive:!0}),(0,GMt.mkdirSync)(this.getHarFolderPath(),{recursive:!0})}createTestGenerationLocalAutoSaveFolder(p){this.autoSaveFolderPath=`/auto-save/${p}`,(0,GMt.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 p=this.vtgTestFileRunConfig.sourceFilePath.split("/").pop();return`${this.localSaveFolderPath}/${this.currentSaveAsLocation}/${p}`}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(p){p&&!(p!=null&&p.startsWith("auto-save"))&&(this.currentSaveAsLocation=p)}};e(Err,"VtgTestAssetsManager");var KMt=Err;var SAn={useCDPSession:!0,trackLoadedResources:!0},krr=class krr extends ROt{constructor(d={},y={devtools:!1},E={},N,F){super({...SAn,...d},y,N,F);this.settings={frontendAppSpecificRules:void 0,initTestGenerator:!0,frontendTestGenerationConfig:void 0};this.isScriptLoaded=e(async(d,y=1e3)=>{try{return await d.waitForFunction(()=>!!window.checksum,void 0,{timeout:y}),!0}catch{return!1}},"isScriptLoaded");this.initInjectedScript=e(async d=>{try{return await d.waitForFunction(()=>{var y;return!!((y=window.checksum)!=null&&y.testGenerator)}),d.evaluate(async({appSpecificRules:y,config:E,initModules:N})=>{window.checksum.testGenerator.init(y,E,N),y.hasGoals&&await window.checksum.goalTracker.init()},{appSpecificRules:this.settings.frontendAppSpecificRules,config:this.getFrontendTestGenerationConfig(),initModules:this.getInjectedScriptInitModules(d)})}catch(y){console.log("initInjectedScript exception",y)}},"initInjectedScript");this.settings={...this.settings,...E},this.injectedScriptManager.setScriptLoadCheck(this.isScriptLoaded),this.settings.initTestGenerator&&this.injectedScriptManager.setScriptLoadCallback(this.initInjectedScript)}async prepare(d={}){let y=await super.prepare(d);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")}),y}setEvaluateWithChecksumTargetFrame(d){this.evaluateWithChecksumTargetFrame=d}getInjectedScriptInitModules(d){return{assertionGenerator:!0,sessionRecorder:!0,filesObserver:!1,assertionsObserver:!1,nativeDialogObserver:!1}}getFrontendTestGenerationConfig(){return this.settings.frontendTestGenerationConfig}async evaluateWithChecksum(d,y,E=this.evaluateWithChecksumTargetFrame){let N=this.injectedScriptManager.getNavigationPromise(E);N&&await N;try{return E.evaluate(d,y)}catch(F){throw console.error("evaluateWithChecksum error",F,d.toString()),F}}async getBestMatchingElementSimilarityScore(d){return this.evaluateWithChecksum(async y=>await window.checksum.testGenerator.getBestMatchingElementSimilarityScore(y),d)}async getInteractableElements(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getInteractableElements())}async getAllInteractableElementsForLastSelectQuery(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getAllInteractableElementsForLastSelectQuery())}async overlayInteractableElementsWithChecksumId(d){return this.evaluateWithChecksum(y=>window.checksum.testGenerator.overlayInteractableElementsWithChecksumId(y),d)}async getGoals(){return await this.evaluateWithChecksum(async()=>window.checksum.goalTracker.getGoals())}async takeElementSnapshot(d,y,E={},N={}){try{let{snapshot:F,elementLocator:R}=await super.takeElementSnapshot(d,y,E);if(!F||!E.takeBodyScreenshot)return F?{snapshot:F}:{};await this.highlightElementByLocator(R,E.mousePosition);let V=await this.takePageSnapshot(N);return await this.clearHighlights(),{snapshot:F,bodySnapshot:V}}catch(F){return console.error("[ChecksumWebDriver] takeElementSnapshot error",F),{}}}async highlightElementByLocator(d,y,E="20px solid rgba(255,0,0,1)",N=!1){return this.evaluateWithChecksum(async([F,R,V,H])=>{window.checksum.testGenerator.highlightElement(F,{highlightStyle:{outline:R},mousePosition:V,scroll:H})},[await d.elementHandle(),E,y,N])}async clearHighlights(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.clearHighlights())}};e(krr,"ChecksumWebDriver");var YMt=krr;var U5r=require("fs"),V5r=x7(require("path"));var wrr=require("fs");var Arr=class Arr{constructor(p,d=vC.vtg.localBuildPath){this.page=p;this.filePath=d;this.filePath=d}async start(){try{await this.modifyVTGBuildHtmlFile(),await this.startReactApp(),await aA(2e3)}catch(p){Nh.error("An error occurred:",p)}}async startReactApp(){if(!this.page)throw new Error("Page not initialized");let p=vC.vtg.appURL;await this.page.goto(p,{waitUntil:"networkidle",timeout:6e4})}async modifyVTGBuildHtmlFile(){if(vC.isDevMode){yEt(!0);return}try{let p=await wrr.promises.readFile(this.filePath,"utf8"),d=/(src|href)=(["'])(\/)static/g,y=p.replace(d,"$1=$2.$3static");await wrr.promises.writeFile(this.filePath,y,"utf8"),Nh(`Successfully modified ${this.filePath}`)}catch(p){Nh.error(`Error processing file ${this.filePath}:`,p)}}};e(Arr,"VtgFrontendLauncher");var XMt=Arr;var fFe={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},fii={defaultMerge:fFe.defaultMerge};function TAn(l,p){return p}e(TAn,"defaultMetaDataUpdater");function DAn(l,p){return l.filter(d=>d!==void 0)}e(DAn,"defaultFilterValues");var L5r;(function(l){l[l.NOT=0]="NOT",l[l.RECORD=1]="RECORD",l[l.ARRAY=2]="ARRAY",l[l.SET=3]="SET",l[l.MAP=4]="MAP",l[l.OTHER=5]="OTHER"})(L5r||(L5r={}));function M5r(l){return typeof l!="object"||l===null?0:Array.isArray(l)?2:kAn(l)?1:l instanceof Set?3:l instanceof Map?4:5}e(M5r,"getObjectType");function CAn(l){let p=new Set;for(let d of l)for(let y of[...Object.keys(d),...Object.getOwnPropertySymbols(d)])p.add(y);return p}e(CAn,"getKeys");function EAn(l,p){return typeof l=="object"&&Object.prototype.propertyIsEnumerable.call(l,p)}e(EAn,"objectHasProperty");function B5r(l){var y;let p=0,d=(y=l[0])==null?void 0:y[Symbol.iterator]();return{[Symbol.iterator](){return{next(){var E;do{if(d===void 0)return{done:!0,value:void 0};let N=d.next();if(N.done===!0){p+=1,d=(E=l[p])==null?void 0:E[Symbol.iterator]();continue}return{done:!1,value:N.value}}while(!0)}}}}}e(B5r,"getIterableOfIterables");var R5r=["[object Object]","[object Module]"];function kAn(l){if(!R5r.includes(Object.prototype.toString.call(l)))return!1;let{constructor:p}=l;if(p===void 0)return!0;let d=p.prototype;return!(d===null||typeof d!="object"||!R5r.includes(Object.prototype.toString.call(d))||!d.hasOwnProperty("isPrototypeOf"))}e(kAn,"isRecord");function wAn(l,p,d){let y={};for(let E of CAn(l)){let N=[];for(let V of l)EAn(V,E)&&N.push(V[E]);if(N.length===0)continue;let F=p.metaDataUpdater(d,{key:E,parents:l}),R=J5r(N,p,F);R!==fFe.skip&&(E==="__proto__"?Object.defineProperty(y,E,{value:R,configurable:!0,enumerable:!0,writable:!0}):y[E]=R)}return y}e(wAn,"mergeRecords$1");function AAn(l){return l.flat()}e(AAn,"mergeArrays$1");function PAn(l){return new Set(B5r(l))}e(PAn,"mergeSets$1");function NAn(l){return new Map(B5r(l))}e(NAn,"mergeMaps$1");function FAn(l){return l.at(-1)}e(FAn,"mergeOthers$1");var QMt={mergeRecords:wAn,mergeArrays:AAn,mergeSets:PAn,mergeMaps:NAn,mergeOthers:FAn};function j5r(...l){return IAn({})(...l)}e(j5r,"deepmerge");function IAn(l,p){let d=OAn(l,y);function y(...E){return J5r(E,d,p)}return e(y,"customizedDeepmerge"),y}e(IAn,"deepmergeCustom");function OAn(l,p){return{defaultMergeFunctions:QMt,mergeFunctions:{...QMt,...Object.fromEntries(Object.entries(l).filter(([d,y])=>Object.hasOwn(QMt,d)).map(([d,y])=>y===!1?[d,QMt.mergeOthers]:[d,y]))},metaDataUpdater:l.metaDataUpdater??TAn,deepmerge:p,useImplicitDefaultMerging:l.enableImplicitDefaultMerging??!1,filterValues:l.filterValues===!1?void 0:l.filterValues??DAn,actions:fFe}}e(OAn,"getUtils");function J5r(l,p,d){var N;let y=((N=p.filterValues)==null?void 0:N.call(p,l,d))??l;if(y.length===0)return;if(y.length===1)return Prr(y,p,d);let E=M5r(y[0]);if(E!==0&&E!==5){for(let F=1;F<y.length;F++)if(M5r(y[F])!==E)return Prr(y,p,d)}switch(E){case 1:return LAn(y,p,d);case 2:return MAn(y,p,d);case 3:return RAn(y,p,d);case 4:return BAn(y,p,d);default:return Prr(y,p,d)}}e(J5r,"mergeUnknowns");function LAn(l,p,d){let y=p.mergeFunctions.mergeRecords(l,p,d);return y===fFe.defaultMerge||p.useImplicitDefaultMerging&&y===void 0&&p.mergeFunctions.mergeRecords!==p.defaultMergeFunctions.mergeRecords?p.defaultMergeFunctions.mergeRecords(l,p,d):y}e(LAn,"mergeRecords");function MAn(l,p,d){let y=p.mergeFunctions.mergeArrays(l,p,d);return y===fFe.defaultMerge||p.useImplicitDefaultMerging&&y===void 0&&p.mergeFunctions.mergeArrays!==p.defaultMergeFunctions.mergeArrays?p.defaultMergeFunctions.mergeArrays(l):y}e(MAn,"mergeArrays");function RAn(l,p,d){let y=p.mergeFunctions.mergeSets(l,p,d);return y===fFe.defaultMerge||p.useImplicitDefaultMerging&&y===void 0&&p.mergeFunctions.mergeSets!==p.defaultMergeFunctions.mergeSets?p.defaultMergeFunctions.mergeSets(l):y}e(RAn,"mergeSets");function BAn(l,p,d){let y=p.mergeFunctions.mergeMaps(l,p,d);return y===fFe.defaultMerge||p.useImplicitDefaultMerging&&y===void 0&&p.mergeFunctions.mergeMaps!==p.defaultMergeFunctions.mergeMaps?p.defaultMergeFunctions.mergeMaps(l):y}e(BAn,"mergeMaps");function Prr(l,p,d){let y=p.mergeFunctions.mergeOthers(l,p,d);return y===fFe.defaultMerge||p.useImplicitDefaultMerging&&y===void 0&&p.mergeFunctions.mergeOthers!==p.defaultMergeFunctions.mergeOthers?p.defaultMergeFunctions.mergeOthers(l):y}e(Prr,"mergeOthers");var jAn=!0,q5r=void 0,eRt=class eRt extends YMt{constructor(d={},y={devtools:!1},E={},N){var F;super(d,y,eRt.makeSettings(E),N==null?void 0:N.getFramesMessageBroker(),N==null?void 0:N.context());this.liveAppPage=N;this.registeredTimeMachineFrames=[];this.onAppFrameCreated=e(async d=>{this.appFrame=d,this.frameMsgBroker.register("live",this.appFrame,vC.vtg.recordEvents),this.setEvaluateWithChecksumTargetFrame(this.appFrame),await this.injectedScriptManager.addTrackedFrame(this.appFrame)},"onAppFrameCreated");this.timeMachine=new wNe(this.frameMsgBroker,this.injectedScriptManager,{headless:((F=E==null?void 0:E.timeMachine)==null?void 0:F.headless)??!0}),this.liveTimeMachine=new wNe(this.frameMsgBroker,this.injectedScriptManager),this.appViewport=E.viewport}static makeSettings(d={}){return j5r({frontendTestGenerationConfig:{showFrontendLogs:vC.isDevMode,recordOptions:{...q5r?{checkoutEveryNms:q5r}:{},recordCanvas:!0,recordCrossOriginIframes:!0,collectFonts:!0,inlineImages:!0,sampling:{mousemove:!1}}}},d)}get appMainFrame(){return this.appFrame}get tmFrame(){return this.timeMachineFrame}getApplicationViewport(){return this.appViewport}getTimeMachine(){return this.timeMachine}registerTimeMachineFrame(d){this.registeredTimeMachineFrames.push(d)}async prepare(d={}){let y=await super.prepare(d);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 XMt(this.page).start(),this.timeMachineFrame=this.page.frames().find(E=>E.name()==="time-machine-iframe"),this.liveFrame=this.page.frames().find(E=>E.name()==="live-iframe"),jAn){let E;this.liveAppPage?E=this.liveAppPage:(E=await this.context.newPage(),await E.setViewportSize(this.appViewport)),await this.onAppFrameCreated(E.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(),y}async exposeFunctionsForVTG(){await this.page.exposeFunction("checksumGetFilesFromLive",async d=>{let y=this.appFrame;if(!y){Nh.info("no live frame detected");return}try{return y.evaluate(E=>window.checksum.testGenerator.filesObserver.getFilesByRrwebId(E),d)}catch(E){Nh.error("Error getting frame window",E)}})}async navigate(d){return this.appFrame.goto(d)}async getCurrentURL(){return this.appFrame.url()}getInjectedScriptInitModules(d){return this.registeredTimeMachineFrames.concat([this.timeMachineFrame,this.liveFrame]).includes(d)?{assertionGenerator:!1,sessionRecorder:!1,filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1}:d===this.appFrame?{...super.getInjectedScriptInitModules(d),filesObserver:!0,nativeDialogObserver:!0,assertionsObserver:!0}:super.getInjectedScriptInitModules(d)}async interceptPageRequests(){async function d(E){try{return await U5r.promises.readFile(E,"utf8")}catch(N){return Nh.error(`Error reading file ${E}:`,N),null}}e(d,"readLocalFile");function y(E){switch(V5r.extname(E).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(y,"getContentType"),await this.page.route("**/*",async E=>{try{let N=E.request().url();if(console.log("intercepted!",N),N.startsWith("file://")){let F=N.replace("file://",""),R=await d(F);R!==null?await E.fulfill({status:200,contentType:y(F),body:R}):await E.abort()}else{let F=0,R=5;for(;F<R;){let V=await E.fetch(),H=V.status();if(H>299&&H<400){F++;let Q=V.headers().location;if(!Q){console.warn("Redirect without Location header"),await E.abort();return}console.log(`Redirect ${F} to: ${Q}`),E.request().url=()=>new URL(Q,N).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 E.fulfill({response:V,headers:{...V.headers(),...Q,"content-security-policy":"","X-Frame-Options":"","x-frame-options":""}});return}}console.warn(`Max redirects (${R}) exceeded`),await E.abort()}}catch(N){console.warn("intercept error",N)}})}};e(eRt,"ChecksumVTGWebDriver");var ZMt=eRt;var Xnt=require("fs");var JAn=".settings.json",Nrr=class Nrr{constructor(p){this.checksumRoot=p;this.settings={autoLogin:!0,autoRunSteps:!0,autoGenerateThoughts:!0,disableGenerateThoughts:!1,autoGenerateAssertions:!0,disableAutoGenerateAssertions:!1,disableAILocators:!1,optimizeLocators:!0,useOptimizedLocatorDefault:!0};this.settingsFilePath=`${this.checksumRoot}/${JAn}`,this.readSettings()}getSettings(){return{...this.settings,autoGenerateAssertions:vC.vtg.aiAssertions.disabled?!1:this.settings.autoGenerateAssertions,disableAutoGenerateAssertions:vC.vtg.aiAssertions.disabled,disableAILocators:vC.vtg.aiLocators.disabled}}updateSettings(p){this.settings=Object.assign(this.settings,p),this.writeSettingsData()}readSettings(){if(!(0,Xnt.existsSync)(this.settingsFilePath)){this.writeSettingsData();return}let p=(0,Xnt.readFileSync)(this.settingsFilePath,"utf-8");this.settings=JSON.parse(p)}writeSettingsData(){(0,Xnt.writeFileSync)(this.settingsFilePath,JSON.stringify(this.settings,null,2))}};e(Nrr,"VtgSettingsService");var tRt=Nrr;var wwt=require("fs");var Frr=class Frr{constructor(p,d,y,E,N,F={logPerformance:!1}){this.timeMachine=p;this.actionsManager=d;this.apiService=y;this.userStoryService=E;this.remoteSessionId=N;this.options=F}async generatePromptData(p,d){let y=p.id;if(this.promptData)return{...this.promptData,action:p};let E=this.getActionTimestamps(y,d);if(!E)return;let N=await this.timeMachine.executeReducedHTMLTask(E.before),F=await this.timeMachine.executeReducedHTMLTask(E.after),R=this.userStoryService.getStory();return this.promptData={reducedHTML:F,previousReducedHTML:N,actionId:y,previousActions:this.actionsManager.actions.slice(0,this.actionsManager.actions.length-1),action:p,title:R.goal,steps:R.instructions},this.promptData}async generatePromptDataForThought(p,d){return this.generatePromptData(p,d)}getVariables(){return[]}getVariablesString(p){return""}getActionTimestamps(p,d){let y=this.actionsManager.actions,E=y.findIndex(R=>R.id===p);if(E===-1){Nh(`[init] No action with id ${p} was found in executed actions`);return}let N=y[E],F=y[E+1];return{before:N.timestamp,after:(F==null?void 0:F.timestamp)??d}}logPerformance(p,d){this.options.logPerformance&&console.log(`${p} in`,Date.now()-d,"ms")}};e(Frr,"ActionsAgent");var rRt=Frr;var Irr=class Irr extends XNe{constructor(d,y,E,N,F,R={logPerformance:!1}){super(d,y,E);this.actionsManager=d;this.apiService=y;this.userStoryService=E;this.timeMachine=N;this.webDriver=F;this.options=R;this.activeRemoteSessionIdByStepId=new Map;this.assertionsAgent=new Crt(N,d,y,this.remoteSessionId,this.userStoryService),this.actionsAgent=new rRt(N,d,y,this.userStoryService,this.remoteSessionId)}async init({retriesLeft:d=3,keepActionsWithoutDescription:y=!1,lastActionId:E=void 0}={}){await super.init({retriesLeft:d,keepActionsWithoutDescription:y,lastActionId:E}),this.activeRemoteSessionIdByStepId.set(E,this.remoteSessionId)}async generateActionThoughts({action:d,processId:y}){try{if(this.isRunning(d.id))throw Nh.warning("Already generating a thought for this action"),new Error("Already generating a thought for this action");let E=await this.actionsAgent.generatePromptDataForThought(d),N=await this.callThoughtApi("actions",E,y);return this.evaluateThoughtResponse({processId:y,id:d.id,thought:N.thought})}catch(E){return Nh.error("Error in AI thought generation",E),this.evaluateThoughtResponse({processId:y,id:d.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(d.id)}}async generateAssertionThought({assertion:d,parentActionId:y,processId:E}){try{if(this.isRunning(d.id))throw Nh.warning("Already generating a thought for this assertion"),new Error("Already generating a thought for this assertion");let N=await this.assertionsAgent.generateThoughtPromptData(y,d),F=await this.callThoughtApi("assertions",N,E);return this.evaluateThoughtResponse({processId:E,id:d.id,thought:F.thought})}catch(N){return Nh.error("Error in AI thought generation",N),this.evaluateThoughtResponse({processId:E,id:d.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(d.id)}}stopGeneratingThought(d){this.activeRemoteSessionIdByStepId.delete(d)}async callThoughtApi(d,y,E){let N=Date.now();if(y)try{N=Date.now();let F=await this.apiService.post(`${d}/thoughts/generate`,{sessionId:this.remoteSessionId,data:y});if(!F.ok){Nh.error(`Request for ${d} thought generation failed with status ${F.status}`);return}let R=await F.json();if(!(R!=null&&R.thought))throw Nh("No thought generated for action, got response",F),new Error("No thought generated");let V=d==="actions"?y.action:y.assertion;return Nh(`Thought generated (${E})`,{type:d,stepId:V.id,locator:V.locator,thought:R.thought}),R}catch(F){throw Nh.error(`Error in AI thought generation (${E})`,F),F}}isRunning(d){return this.activeRemoteSessionIdByStepId.has(d)}async evaluateThoughtResponse({id:d,processId:y,thought:E,error:N=!1}){try{await this.webDriver.page.evaluate(({id:F,thought:R,error:V,processId:H})=>{window.vtg.onAsyncProcessResponse({id:F,processId:H,thought:R,error:V})},{id:d,thought:E,error:N,processId:y})}catch(F){Nh.error("Error in AI thought generation",F)}}};e(Irr,"VTGThoughtsService");var nRt=Irr;var qAn=e(()=>{let p=new Error().stack.split(`
1914
1914
  `).find(d=>d.includes(".checksum.spec.ts"));if(p)return{lineNumber:parseInt(p.split(":")[1]),columnNumber:parseInt(p.split(":")[2])}},"findCodeLocationFromStackTrace"),Orr=class Orr{constructor(){this.store={};this.activeVariablesSet=new Set;return new Proxy(this,this)}clearAll(){for(let p in this.store)Object.prototype.hasOwnProperty.call(this.store,p)&&delete this.store[p];this.activeVariablesSet.clear()}getActiveVariables(){return Array.from(this.activeVariablesSet).map(p=>this.store[p])}setVariable(p,d){this.store[p]={name:p,value:d,type:d instanceof Function?"RandomValueGenerator":"FillValue"}}set(p,d,y){if(typeof d!="string")return!1;let E=qAn();return p.store[d]={name:d,value:y,type:y instanceof Function?"RandomValueGenerator":"FillValue",...E,line:""},!0}get(p,d){var y;if(d in p)return p[d];if(!(d in p.store))throw new Error(`Variable ${d} is not defined`);return p.activeVariablesSet.add(d),(y=p.store[d])==null?void 0:y.value}};e(Orr,"VariableStore");var iRt=Orr;var Lrr=class Lrr{constructor(p=new iRt){this._variableStore=p}get variableStore(){return this._variableStore}};e(Lrr,"VTGVariableStoreService");var aRt=Lrr;var _VtgEvaluatorService=class _VtgEvaluatorService{constructor(l,p){this.variableStoreService=l;this.vtgTestFileMode=p;this.listenerBody=e(async({vtg})=>{await vtg.eval(async(code,callback)=>{try{callback(null,await eval(`(async () => {
1915
1915
  ${code}
1916
- })()`))}catch(l){callback(l,null)}})},"listenerBody")}setPage(l){this.page=l}async execute(l,p={}){return this.vtgTestFileMode?this.executeInPlaywrightTest(l,p):this.executeOnLive(l,p)}get vtgContext(){return{page:this.page,vs:this.variableStoreService.variableStore,expect:PZe.expect,checksumAI:e((l,p)=>p(),"checksumAI")}}async executeOnLive(l,p={}){let d={...this.vtgContext,...p},y=this.wrapCodeInContext(l,d);return await(0,eval)(y)(d)}wrapCodeInContext(l,p){return`(async ({${Object.keys(p).join(", ")}}) => { ${l} })`}async executeInPlaywrightTest(l,p={}){let d=p?this.wrapCodeInContext(l,p)+"(context)":l;return new Promise((y,E)=>{this.listener&&this.listener(d,p,(N,F)=>{N?E(N):y(F)})})}async listenForExecution(l){return new Promise(p=>{this.resolveEvaluator=p,this.listener=l})}stopListening(){this.resolveEvaluator()}getFunctionContentToInject(){return this.listenerBody.toString()}};e(_VtgEvaluatorService,"VtgEvaluatorService");var sRt=_VtgEvaluatorService;var Rrr=class Rrr extends sce{constructor(d,y=!1){y||(y=!!d.find(E=>E==="--debug"));super(d,y);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(d),Nh.setLogLevel(y?"all":vC.isDevMode?vC.logLevel:"errors")}async run(d){await this.init(d),this.buildServices(),this.buildServer();let y=await this.getInitialServicesData();y&&this.setServicesData(y),await this.start()}async init(d){await this.patchPlaywright(),this.loadChecksumData(),this.loadPlaywrightConfigForVTG(),this.webDriver=this.buildWebDriver(d),this.webDriver.registerEventListener(this),this.taskTimeMachine=new wNe(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!vC.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0,taskTimeout:vC.vtg.taskTimeMachine.taskTimeout}),this.pageInteractor=new pEt(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 _Et(this.config)),this.testAssetsManager=new KMt(this.projectRootDirectory,this.checksumRoot,this.vtgTestFileRunConfig),(vC.vtg.writeLogFile||this.debugMode)&&this.addLogFile()}buildServices(){this.actionsManager=new CLt,this.apiService=new wOt(this.config),this.userStoryService=new DLt(this.apiService,this.config),this.variableStoreService=new aRt,this.evaluatorService=new sRt(this.variableStoreService,this.vtgTestFileMode),this.actionsService=new COt(this.config,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver,this.evaluatorService),this.assertionsService=new jOt(this.webDriver,this.actionsManager,this.evaluatorService),this.locatorsService=new KOt(this.webDriver,this.taskTimeMachine,this.apiService,this.userStoryService,this.evaluatorService),this.aiTestGenerationService=new kOt(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new BOt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver,this.evaluatorService),this.aiThoughtsService=new nRt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new TLt(this.config,this.userStoryService,this.apiService,this.actionsManager,this.testAssetsManager,this.actionsService,this.vtgTestFileRunConfig,this.evaluatorService),this.settingsService=new tRt(this.checksumRoot),this.actionsManager.setStorageService(this.storageService)}buildServer(){this.reactAppServer=new HMt(this.actionsService,this.assertionsService,this.locatorsService,this.aiTestGenerationService,this.aiAssertionsService,this.aiThoughtsService,this.actionsManager,this.storageService,this.settingsService)}loadPlaywrightConfigForVTG(){try{let d=`${this.checksumRoot}/playwright.config.ts`;if((0,wwt.existsSync)(d)){let y=require(d).default;y&&(this.playwrightConfigForVTG=y)}}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 d=this.storageService.getLocalSavedData(this.editLocationPath);return{actions:d.executedActions,story:d.story,testGenerationData:d.testGenerationData}}async getInitialServicesDataFromCloud(){let y=await(await this.apiService.post(`test-generation/${this.cloudTestGenerationId}/info`)).json(),{actionsDownloadSignedURL:E,story:N,testGenerationData:F}=y,R=await fetch(E,{mode:"cors",credentials:"same-origin",headers:{"Content-Type":"application/json"}});if(!R.ok)throw new Error(`HTTP error! Status: ${R.status}`);let V=await R.json();return{actions:this.addIdsToActionsAndAssertions(V),story:N,testGenerationData:F}}addIdsToActionsAndAssertions(d){return d.map((y,E)=>({...y,id:(0,Mrr.randomUUID)(),assertions:(y.assertions??[]).map(N=>({...N,id:(0,Mrr.randomUUID)()}))}))}async getInitialServicesDataByInternalTestId(){var N,F,R;if(((N=this.vtgTestFileRunConfig)==null?void 0:N.mode)!=="edit")return;let d=[];d=this.storageService.readJsonFile((F=this.vtgTestFileRunConfig)==null?void 0:F.actionsJsonFilePath),d=this.addIdsToActionsAndAssertions(d);let y=await this.apiService.post(`test-generation-by-internal-test-id/${(R=this.vtgTestFileRunConfig)==null?void 0:R.internalTestId}/info`);if(!y.ok)throw new Error(`Error fetching test generation data: ${y.statusText}`);let E=await y.json();return{actions:d,story:E.story,testGenerationData:E.testGenerationData}}setServicesData({actions:d,story:y,testGenerationData:E}){this.actionsManager.setActions(d),this.userStoryService.setStoryInfo(y,E),this.testAssetsManager.setCurrentSaveAsLocation(this.editLocationPath),this.storyId=y.id}async start({createAssetsFolder:d=!0}={}){var N,F;(this.vtgMode==="start"||this.vtgTestFileMode)&&await this.userStoryService.fetchStory(this.storyId),d&&this.testAssetsManager.createTestGenerationAssetsFolders(),this.testAssetsManager.createTestGenerationLocalAutoSaveFolder(this.storyId);let{environment:y}=this.userStoryService.getEnvInfo();await this.webDriver.prepare({baseURL:y.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,R=>this.webDriver.registerTimeMachineFrame(R)),await this.reactAppServer.start(),await this.reactAppServer.evaluateServerPort(this.webDriver.page);let E=(()=>{let R=this.config.environments.find(V=>V.name===y.name);return!R||!R.baseURL?"/":R.baseURL})();this.webDriver.appMainFrame?await this.webDriver.appMainFrame.goto(E,{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",(N=this.userStoryService.getStory())==null?void 0:N.goal),await this.webDriver.page.evaluate(({localSaveFolderPath:R,actions:V,appViewport:H,userStoryGoal:Q,isLoadedFromFile:se})=>{window.vtg.initClient(R,V,H,this.checksumRuntimeVersion,Q,se)},{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 E,N,F,R;let d=((N=(E=this.playwrightConfigForVTG)==null?void 0:E.use)==null?void 0:N.navigationTimeout)||3e4,y=((R=(F=this.playwrightConfigForVTG)==null?void 0:F.use)==null?void 0:R.actionTimeout)||5e3;return{navigationTimeout:d,actionTimeout:y}}getPlaywrightProxySettings(){var F,R;let d=(R=(F=this.playwrightConfigForVTG)==null?void 0:F.use)==null?void 0:R.proxy,{server:y,username:E,password:N}=d||{};if(E&&N&&y)return{username:E,password:N,server:y}}getPlaywrightViewportSettings(){var E,N;let{width:d=1280,height:y=720}=((N=(E=this.playwrightConfigForVTG)==null?void 0:E.use)==null?void 0:N.viewport)||{};return{width:d,height:y}}buildWebDriver(d){var N;let y=this.getPlaywrightProxySettings(),E=this.getPlaywrightViewportSettings();return new ZMt({scriptSource:vC.checksumScript.source,scriptURL:vC.checksumScript.url,scriptFile:vC.checksumScript.path,isScriptFileAbsolute:!0,fullScreenResolution:!1,hostWindowViewport:!0,baseURL:(N=this.config.environments.find(F=>F.default))==null?void 0:N.baseURL,useProxy:!!y,webProxy:y,disableWebSecurity:!0,allowFileAccess:!0,remoteDebugging:vC.vtg.remoteDebugging},{devtools:!1,headless:!1},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"},viewport:E},d)}async onWebDriverContextClose(){var d,y,E;this.evaluatorService.stopListening(),(d=this.vtgTestFileRunConfig)!=null&&d.evalFilePath&&(0,wwt.rmSync)((y=this.vtgTestFileRunConfig)==null?void 0:y.evalFilePath,{force:!0}),this.vtgTestFileRunConfig.mode==="edit"&&(0,wwt.rmSync)((E=this.vtgTestFileRunConfig)==null?void 0:E.actionsJsonFilePath,{force:!0})}initVtgMode(d){var N;let y=d.indexOf("--edit"),E=d.indexOf("--cloud");if(d.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=((N=this.vtgTestFileRunConfig)==null?void 0:N.mode)==="start"?this.vtgTestFileRunConfig.storyId:void 0;return}y!==-1&&(this.vtgMode="edit",this.editLocationPath=d.at(y+1)),E!==-1&&(this.vtgMode="cloud",this.cloudTestGenerationId=d.at(E+1)),this.vtgMode==="start"&&(this.storyId=d[0])}addLogFile(){let d=require("fs"),y=`${this.testAssetsManager.getLogsPath()}/vtg_${new Date().toISOString()}.log`;d.existsSync(this.testAssetsManager.getLogsPath())||d.mkdirSync(this.testAssetsManager.getLogsPath(),{recursive:!0}),Nh.addLogListener({onLog:e((...E)=>{let N=E.map(F=>{if(typeof F=="object")try{return JSON.stringify(F,null,2)}catch{}return String(F)}).join(" ")+`
1916
+ })()`))}catch(l){callback(l,null)}})},"listenerBody")}setPage(l){this.page=l}async execute(l,p={}){return this.vtgTestFileMode?this.executeInPlaywrightTest(l,p):this.executeOnLive(l,p)}get vtgContext(){return{page:this.page,vs:this.variableStoreService.variableStore,expect:PZe.expect,checksumAI:e((l,p)=>p(),"checksumAI")}}async executeOnLive(l,p={}){let d={...this.vtgContext,...p},y=this.wrapCodeInContext(l,d);return await(0,eval)(y)(d)}wrapCodeInContext(l,p){return`(async ({${Object.keys(p).join(", ")}}) => { ${l} })`}async executeInPlaywrightTest(l,p={}){let d=p?this.wrapCodeInContext(l,p)+"(context)":l;return new Promise((y,E)=>{this.listener&&this.listener(d,p,(N,F)=>{N?E(N):y(F)})})}async listenForExecution(l){return new Promise(p=>{this.resolveEvaluator=p,this.listener=l})}stopListening(){var l;(l=this.resolveEvaluator)==null||l.call(this)}getFunctionContentToInject(){return this.listenerBody.toString()}};e(_VtgEvaluatorService,"VtgEvaluatorService");var sRt=_VtgEvaluatorService;var Rrr=class Rrr extends sce{constructor(d,y=!1){y||(y=!!d.find(E=>E==="--debug"));super(d,y);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(d),Nh.setLogLevel(y?"all":vC.isDevMode?vC.logLevel:"errors")}async run(d){await this.init(d),this.buildServices(),this.buildServer();let y=await this.getInitialServicesData();y&&this.setServicesData(y),await this.start()}async init(d){await this.patchPlaywright(),this.loadChecksumData(),this.loadPlaywrightConfigForVTG(),this.webDriver=this.buildWebDriver(d),this.webDriver.registerEventListener(this),this.taskTimeMachine=new wNe(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!vC.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0,taskTimeout:vC.vtg.taskTimeMachine.taskTimeout}),this.pageInteractor=new pEt(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 _Et(this.config)),this.testAssetsManager=new KMt(this.projectRootDirectory,this.checksumRoot,this.vtgTestFileRunConfig),(vC.vtg.writeLogFile||this.debugMode)&&this.addLogFile()}buildServices(){this.actionsManager=new CLt,this.apiService=new wOt(this.config),this.userStoryService=new DLt(this.apiService,this.config),this.variableStoreService=new aRt,this.evaluatorService=new sRt(this.variableStoreService,this.vtgTestFileMode),this.actionsService=new COt(this.config,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver,this.evaluatorService),this.assertionsService=new jOt(this.webDriver,this.actionsManager,this.evaluatorService),this.locatorsService=new KOt(this.webDriver,this.taskTimeMachine,this.apiService,this.userStoryService,this.evaluatorService),this.aiTestGenerationService=new kOt(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new BOt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver,this.evaluatorService),this.aiThoughtsService=new nRt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new TLt(this.config,this.userStoryService,this.apiService,this.actionsManager,this.testAssetsManager,this.actionsService,this.vtgTestFileRunConfig,this.evaluatorService),this.settingsService=new tRt(this.checksumRoot),this.actionsManager.setStorageService(this.storageService)}buildServer(){this.reactAppServer=new HMt(this.actionsService,this.assertionsService,this.locatorsService,this.aiTestGenerationService,this.aiAssertionsService,this.aiThoughtsService,this.actionsManager,this.storageService,this.settingsService)}loadPlaywrightConfigForVTG(){try{let d=`${this.checksumRoot}/playwright.config.ts`;if((0,wwt.existsSync)(d)){let y=require(d).default;y&&(this.playwrightConfigForVTG=y)}}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 d=this.storageService.getLocalSavedData(this.editLocationPath);return{actions:d.executedActions,story:d.story,testGenerationData:d.testGenerationData}}async getInitialServicesDataFromCloud(){let y=await(await this.apiService.post(`test-generation/${this.cloudTestGenerationId}/info`)).json(),{actionsDownloadSignedURL:E,story:N,testGenerationData:F}=y,R=await fetch(E,{mode:"cors",credentials:"same-origin",headers:{"Content-Type":"application/json"}});if(!R.ok)throw new Error(`HTTP error! Status: ${R.status}`);let V=await R.json();return{actions:this.addIdsToActionsAndAssertions(V),story:N,testGenerationData:F}}addIdsToActionsAndAssertions(d){return d.map((y,E)=>({...y,id:(0,Mrr.randomUUID)(),assertions:(y.assertions??[]).map(N=>({...N,id:(0,Mrr.randomUUID)()}))}))}async getInitialServicesDataByInternalTestId(){var N,F,R;if(((N=this.vtgTestFileRunConfig)==null?void 0:N.mode)!=="edit")return;let d=[];d=this.storageService.readJsonFile((F=this.vtgTestFileRunConfig)==null?void 0:F.actionsJsonFilePath),d=this.addIdsToActionsAndAssertions(d);let y=await this.apiService.post(`test-generation-by-internal-test-id/${(R=this.vtgTestFileRunConfig)==null?void 0:R.internalTestId}/info`);if(!y.ok)throw new Error(`Error fetching test generation data: ${y.statusText}`);let E=await y.json();return{actions:d,story:E.story,testGenerationData:E.testGenerationData}}setServicesData({actions:d,story:y,testGenerationData:E}){this.actionsManager.setActions(d),this.userStoryService.setStoryInfo(y,E),this.testAssetsManager.setCurrentSaveAsLocation(this.editLocationPath),this.storyId=y.id}async start({createAssetsFolder:d=!0}={}){var N,F;(this.vtgMode==="start"||this.vtgTestFileMode)&&await this.userStoryService.fetchStory(this.storyId),d&&this.testAssetsManager.createTestGenerationAssetsFolders(),this.testAssetsManager.createTestGenerationLocalAutoSaveFolder(this.storyId);let{environment:y}=this.userStoryService.getEnvInfo();await this.webDriver.prepare({baseURL:y.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,R=>this.webDriver.registerTimeMachineFrame(R)),await this.reactAppServer.start(),await this.reactAppServer.evaluateServerPort(this.webDriver.page);let E=(()=>{let R=this.config.environments.find(V=>V.name===y.name);return!R||!R.baseURL?"/":R.baseURL})();this.webDriver.appMainFrame?await this.webDriver.appMainFrame.goto(E,{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",(N=this.userStoryService.getStory())==null?void 0:N.goal),await this.webDriver.page.evaluate(({localSaveFolderPath:R,actions:V,appViewport:H,userStoryGoal:Q,isLoadedFromFile:se})=>{window.vtg.initClient(R,V,H,this.checksumRuntimeVersion,Q,se)},{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 E,N,F,R;let d=((N=(E=this.playwrightConfigForVTG)==null?void 0:E.use)==null?void 0:N.navigationTimeout)||3e4,y=((R=(F=this.playwrightConfigForVTG)==null?void 0:F.use)==null?void 0:R.actionTimeout)||5e3;return{navigationTimeout:d,actionTimeout:y}}getPlaywrightProxySettings(){var F,R;let d=(R=(F=this.playwrightConfigForVTG)==null?void 0:F.use)==null?void 0:R.proxy,{server:y,username:E,password:N}=d||{};if(E&&N&&y)return{username:E,password:N,server:y}}getPlaywrightViewportSettings(){var E,N;let{width:d=1280,height:y=720}=((N=(E=this.playwrightConfigForVTG)==null?void 0:E.use)==null?void 0:N.viewport)||{};return{width:d,height:y}}buildWebDriver(d){var N;let y=this.getPlaywrightProxySettings(),E=this.getPlaywrightViewportSettings();return new ZMt({scriptSource:vC.checksumScript.source,scriptURL:vC.checksumScript.url,scriptFile:vC.checksumScript.path,isScriptFileAbsolute:!0,fullScreenResolution:!1,hostWindowViewport:!0,baseURL:(N=this.config.environments.find(F=>F.default))==null?void 0:N.baseURL,useProxy:!!y,webProxy:y,disableWebSecurity:!0,allowFileAccess:!0,remoteDebugging:vC.vtg.remoteDebugging},{devtools:!1,headless:!1},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"},viewport:E},d)}async onWebDriverContextClose(){var d,y,E;this.evaluatorService.stopListening(),(d=this.vtgTestFileRunConfig)!=null&&d.evalFilePath&&(0,wwt.rmSync)((y=this.vtgTestFileRunConfig)==null?void 0:y.evalFilePath,{force:!0}),this.vtgTestFileRunConfig.mode==="edit"&&(0,wwt.rmSync)((E=this.vtgTestFileRunConfig)==null?void 0:E.actionsJsonFilePath,{force:!0})}initVtgMode(d){var N;let y=d.indexOf("--edit"),E=d.indexOf("--cloud");if(d.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=((N=this.vtgTestFileRunConfig)==null?void 0:N.mode)==="start"?this.vtgTestFileRunConfig.storyId:void 0;return}y!==-1&&(this.vtgMode="edit",this.editLocationPath=d.at(y+1)),E!==-1&&(this.vtgMode="cloud",this.cloudTestGenerationId=d.at(E+1)),this.vtgMode==="start"&&(this.storyId=d[0])}addLogFile(){let d=require("fs"),y=`${this.testAssetsManager.getLogsPath()}/vtg_${new Date().toISOString()}.log`;d.existsSync(this.testAssetsManager.getLogsPath())||d.mkdirSync(this.testAssetsManager.getLogsPath(),{recursive:!0}),Nh.addLogListener({onLog:e((...E)=>{let N=E.map(F=>{if(typeof F=="object")try{return JSON.stringify(F,null,2)}catch{}return String(F)}).join(" ")+`
1917
1917
  `;try{d.appendFile(y,N,F=>{F&&console.error(F)})}catch{}},"onLog")})}async eval(d){return this.evaluatorService.listenForExecution(d)}};e(Rrr,"VisualTestGenerator");var Awt=Rrr;var gce=x7(Kae());var Brr=class Brr{constructor(p,d=!1){this.desiredType=p;this.recursive=d}changeAssignmentType(p){let d=p.declarationList.declarations.map(E=>gce.factory.createVariableDeclaration(E.name,E.exclamationToken,E.type,E.initializer)),y=gce.factory.createVariableDeclarationList(d,this.desiredType);return gce.factory.updateVariableStatement(p,p.modifiers,y)}transform(p){let d=e(y=>(gce.isVariableStatement(y)&&(y=this.changeAssignmentType(y)),gce.isSourceFile(y)||gce.isStatement(y)||this.recursive?gce.visitEachChild(y,d,p):y),"visit");return y=>gce.visitNode(y,d)}};e(Brr,"ChangeAllAssignmentsTypesTransformer");var oRt=Brr;var W5r=x7(Kae());var jrr=class jrr extends sce{constructor(d,y=!1,E=!1){super(d,y);this.vtgMode=E;this.MAX_COMPLETION_WAIT=2*3600*1e3;this.TEST_RUN_MONITOR_PATH=(0,a4e.join)(__dirname,"test-run-monitor.js");this.didFail=!1;this.isolationMode=!1;this.trmMessagesBuffer="";this.completeIndicators={upload:!1,tests:!1,report:!1};this.uploadProgress=0;this.fileNameTimestamp=new Date().toString().split(" ").slice(0,5).join(" ")}get replMode(){return this.getChecksumArg("repl")??!1}get vtgLegacyMode(){return this.getChecksumArg("legacy")||!1}get vtgEditMode(){return this.getChecksumArg("edit")||!1}async run(){var F;if(this.loadTracer(),this.loadChecksumData(),this.validateAuthExists(),this.vtgMode&&!this.vtgLegacyMode&&(this.config.options.hostReports=!1),!await this.getSession())return;this.trace.log(`Project root found at ${this.projectRootDirectory}`,`Checksum root found at ${this.checksumRoot}`);let d;try{d=await Dj(this.startTestRunMonitor(this.testSession),1e4,"test run monitor timeout")}catch{this.logAndTrace("Error starting test run monitor. Test results will not be available on checksum.","Test Run Monitor Error")}this.buildVolatileConfig();let y={CHECKSUM_ROOT_FOLDER:this.checksumRoot};d&&(y.CHECKSUM_UPLOAD_AGENT_PORT=d),this.config.options.hostReports&&(y.PW_TEST_HTML_REPORT_OPEN="never"),this.testSession&&this.testSession!=="isolated-session"&&(y.CHECKSUM_TEST_SUITE_ID=this.testSession),this.replMode&&(y.CHECKSUM_REPL="true"),(F=this.trace)!=null&&F.internalId&&(y.CHECKSUM_TRACE_INTERNAL_ID=this.trace.internalId),this.getChecksumArg("tm")&&(y.CHECKSUM_SHOW_TIME_MACHINE="true");let E=this.getNonChecksumArgs();if(this.vtgMode&&!this.vtgLegacyMode&&(E.unshift("--reporter=line"),y.CHECKSUM_VTG_TEST_FILE_MODE="true",this.vtgEditMode?y.CHECKSUM_VTG_TEST_FILE_EDIT_MODE="true":y.CHECKSUM_VTG_STORY_ID=E[E.length-1],y.PW_TEST_HTML_REPORT_OPEN="never"),this.vtgMode&&!this.vtgLegacyMode){let R,V;if(this.vtgEditMode){R=E[E.length-1];let H=this.loadVtgTestFileMirror(R);this.createActionJsonFileForExistingChecksumSpec(H,R),this.createEvalFileForExistingChecksumSpec(H,R),V={mode:"edit",actionsJsonFilePath:this.getActionJsonFilePath(R),internalTestId:H.testMirrors[0].internalTestId,evalFilePath:this.getEvalFilePath(R),sourceFilePath:R}}else this.createEvalFileForNewChecksumSpec(),cRt.writeFileSync(this.getSavePathForNewChecksumSpec(),SXt({body:"",testFunctionParams:["page","vs"]})),V={mode:"start",sourceFilePath:this.getSavePathForNewChecksumSpec(),evalFilePath:this.getEvalFilePath(),storyId:E[E.length-1]};y.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG=JSON.stringify(V),E[E.length-1]=this.getEvalFilePath(this.vtgEditMode?R:void 0)}this.replMode&&E.push("--debug");let N=`npx playwright test --config "${this.getPlaywrightConfigFilePath()}" ${E.map(R=>`"${R}"`).join(" ")}`;await this.patchPlaywright();try{console.log(`Tests running with @checksum-ai/runtime version ${this.checksumRuntimeVersion}`),this.replMode?(console.log("Running in REPL mode"),this.execCmd(N,y),await this.execCmd(`node ${__dirname}/repl.js`,y)):(this.trace.testsStart(),await this.execCmd(N,y),this.trace.testsEnd()),console.log("Tests execution finished")}catch{this.didFail=!0,console.log("Error during test execution: Failed passing test"),this.trace.testsFailed()}finally{this.isolationMode||console.log("Waiting for test files to upload to Checksum..."),this.sendReportUploadRequest(),await this.patchPlaywright(!0),this.completeIndicators.tests=!0,await this.handleCompleteMessage()}}createEvalFileForExistingChecksumSpec(d,y){let E=new wZe(d.sourceFile);E.transformSourceFile([new grt(y),new yrt(d.sourceFile,d.testMirrors.map(N=>N.testBody),SOt(EXt),["page","vs","vtg"]),new oRt(W5r.NodeFlags.Let,!0)]),E.write(this.getEvalFilePath(y))}loadVtgTestFileMirror(d){if(!d||!d.startsWith("/"))throw new Error("Currently vtg mode can only run with absolute path to file");let y=new sPe(d);return y.loadTestFromFile(),y}createActionJsonFileForExistingChecksumSpec(d,y){let E=d.testMirrors[0].translateStatementsToActions(),N=this.getActionJsonFilePath(y);cRt.writeFileSync(N,JSON.stringify(E,null,2))}createFolderIfNotExists(d){return(0,Pwt.existsSync)(d)||(0,Pwt.mkdirSync)(d,{recursive:!0}),d}getSavePathForNewChecksumSpec(){let d=this.createFolderIfNotExists((0,a4e.join)(this.checksumRoot,"tests"));return(0,a4e.join)(d,`test-${this.fileNameTimestamp}.checksum.spec.ts`)}createEvalFileForNewChecksumSpec(){let d=this.getEvalFilePath();cRt.writeFileSync(d,SXt({body:EXt,testFunctionParams:["page","vs","vtg"],importMode:"require",useLocalChecksumImport:!!process.env.DEV_MODE}))}getTempFolder(){return this.createFolderIfNotExists((0,a4e.join)(this.checksumRoot,"drafts","temp"))}getActionJsonFilePath(d){let y=this.getFileName(d).replace(".spec.ts",".json");return(0,a4e.join)(this.getTempFolder(),y)}getFileName(d){return d.split("/").pop()}getEvalFilePath(d){let y=d?this.getFileName(d).replace(/(\.eval)?(\.checksum\.spec\.ts)$/,(E,N,F)=>N?F:".eval"+F):`test-${this.fileNameTimestamp}.eval.checksum.spec.ts`;return(0,a4e.join)(this.getTempFolder(),y)}getPlaywrightReportPath(){var E;let d=e(N=>(XG("Using report folder",N),(0,a4e.join)(N,"index.html")),"makeFilePath");if(process.env.PLAYWRIGHT_HTML_OUTPUT_DIR)return d(process.env.PLAYWRIGHT_HTML_OUTPUT_DIR);let y=(E=this.playwrightConfig)==null?void 0:E.reporter;if(y instanceof Array){let F=y.filter(R=>R instanceof Array&&R[0]==="html").find(R=>{var V;return(V=R[1])==null?void 0:V.outputFolder});if(F)return d((0,a4e.join)(this.checksumRoot,F[1].outputFolder))}return d((0,a4e.join)(this.projectRootDirectory,"playwright-report"))}sendReportUploadRequest(){let d=this.getPlaywrightReportPath();if(!(0,Pwt.existsSync)(d)){this.logAndTrace(`Could not find report file at ${d}`,"Runtime Error"),this.completeIndicators.report=!0,this.testRunMonitorProcess.stdin.write("cli:report=false");return}XG("Sending report upload request",d),this.testRunMonitorProcess.stdin.write(`cli:report=${d}`)}startTestRunMonitor(d){return new Promise(y=>{console.log("Starting test run monitor"),this.testRunMonitorProcess=z5r.spawn("node",[this.TEST_RUN_MONITOR_PATH,JSON.stringify({sessionId:d,apiURL:this.config.apiURL,apiKey:this.config.apiKey}),...this.isolationMode?["isolated"]:[]]),this.testRunMonitorProcess.stdout.on("data",E=>{let N=this.parseTRMMessages(E.toString().trim());if(N.length){this.logTRMMessage(N);for(let F of N){if(F.startsWith("trace")&&this.handleTestRunMonitorTrace(F.substring("trace".length+1)),!F.startsWith("monitor"))continue;let R=F.substring("monitor".length+1),V=R.indexOf("=");if(V===-1){this.handleTestRunMonitorMessage(R,"");continue}let[H,Q]=[R.substring(0,V),R.substring(V+1)];if(!Object.values(HUt).includes(H)){console.warn(`Unknown test run monitor message: ${H}`);continue}H==="port"?y(Q):this.handleTestRunMonitorMessage(H,Q)}}}),this.testRunMonitorProcess.on("exit",(E,N)=>{this.logAndTrace(`test run monitor process exited with code ${E} and signal ${N}`,"Test Run Monitor Error")}),this.testRunMonitorProcess.stderr.on("data",E=>{this.logAndTrace(`TRM Error: ${E.toString().substring(0,300)}`,"Test Run Monitor Error")}),this.testRunMonitorProcess.on("error",E=>{this.logAndTrace(`Error starting test run monitor: ${E.message}`,"Test Run Monitor Error")})})}parseTRMMessages(d){let y=this.trmMessagesBuffer+d,E,N,F=e(()=>{E=y.indexOf("{trm}"),N=y.indexOf("{/trm}")},"findIndexes");F();let R=[];for(;E!==-1&&N!==-1&&N>E;){if(R.push(y.substring(E+"{trm}".length,N)),y=y.slice(N+"{/trm}".length).trim(),y.length&&!y.startsWith("{trm}"))return console.warn("Buffered data does not start with start delimiter",y),this.trmMessagesBuffer="",R;this.trmMessagesBuffer=y,F()}return R}async handleTestRunMonitorTrace(d){let y=d.indexOf("="),[E,N]=y>-1?[d.substring(0,y),d.substring(y+1)]:[d,""];if(!Object.values(irt).includes(E)){XG("Unknown trace event",E);return}try{let F=N?JSON.parse(N):{};switch(E){case"Upload Start":this.trace.uploadStart(F.filename);break;case"Upload Complete":this.trace.uploadComplete(F.filename);break;case"Upload Failed":this.trace.uploadFailed(F.filename,F.error);break}}catch(F){XG(`Error parsing trace payload, ${F.message}`)}}async handleTestRunMonitorMessage(d,y){switch(d){case"uploads-complete-with-errors":console.log("Error uploading test files to Checksum");try{let N=JSON.parse(y);this.trace.uploadsCompleteWithErrors(N)}catch{}this.sendProcessingError().then(()=>{this.completeIndicators.upload=!0});break;case"uploads-complete":this.isolationMode||console.log("Test files uploaded successfully"),this.trace.allUploadsComplete(),this.sendUploadsComplete().then(()=>{this.completeIndicators.upload=!0});break;case"report-complete":{if(this.isolationMode){this.completeIndicators.report=!0;break}let N=y.slice(0,y.indexOf(":"))==="true",F=y.slice(y.indexOf(":")+1),R={};try{F&&F.length>0?R=JSON.parse(F):XG("No stats received from test run monitor")}catch(V){this.logAndTrace(`Error parsing stats - ${V.message}`,"Runtime Error")}if(await this.sendTestRunEnd(R),this.completeIndicators.report=!0,N){let V=`${this.checksumAppUrl}/#/test-runs/${this.testSession}`,H=`Checksum report URL: ${V}`,Q="*".repeat(H.length);console.log(`${Q}
1918
1918
  ${H}
1919
1919
  ${Q}`),this.trace.reportComplete(R,V)}else this.trace.event("Report Upload Error"),console.log("An error occurred while uploading the test report to Checksum");break}case"upload-progress":{if(this.isolationMode)break;let N=parseInt(y);(N<this.uploadProgress||N>=this.uploadProgress+10||N===100&&this.uploadProgress!==100)&&(this.uploadProgress=N,console.log(`[ Uploads progress: ${this.uploadProgress}% ]`))}break;case"log":console.log(y);break;case"trace":let E=y;if(!Object.values(irt).includes(E))return;this.trace.event(E);break;case"playwrightConfig":try{this.playwrightConfig||(this.playwrightConfig=JSON.parse(y),this.trace.playwrightConfig(this.playwrightConfig))}catch(N){this.logAndTrace(`Error parsing playwright config - ${N.message}`,"Runtime Error")}break;default:this.logAndTrace(`Unhandled test run monitor message: ${d}=${y}`,"Runtime Error")}}async handleCompleteMessage(){let d=Date.now(),y=12;for(;;){if(Date.now()-d>this.MAX_COMPLETION_WAIT){console.log("Warning: Checksum wasn't able to upload all test assets or expected a file the couldn't be found. This might cause issues when viewing the report/trace."),this.trace.event("Runtime Timeout"),this.shutdown(1);return}if(Object.keys(this.completeIndicators).find(E=>!this.completeIndicators[E]))XG(this.completeIndicators),--y===0&&(this.trace.completionStatus(this.completeIndicators),y=12),await aA(5e3);else{this.trace.event("Runtime Complete"),console.log("Checksum test run complete"),await this.shutdown(this.didFail?1:0);return}}}async shutdown(d=0){await this.cleanup(),process.exit(d)}async cleanup(){var d,y;await super.cleanup(),(d=this.testRunMonitorProcess)==null||d.stdin.write("cli:shutdown"),(y=this.testRunMonitorProcess)==null||y.kill()}async getSession(){let d,y;try{if(!this.config.options.hostReports)return this.setIsolatedMode(),!0;if(y=this.config.apiKey,!y||y==="<API key>")return this.logAndTrace("No API key found in checksum config - please set it in the config file - checksum.config.ts","Checksum Config Error",!0),this.shutdown(1),!1;let E=await this.getEnvInfo(),N=JSON.stringify({...E,isHidden:!!this.config.options.hideReports}),F=await fetch(`${this.config.apiURL}/client-api/test-runs`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:y},body:N}),{uuid:R,appName:V}=await F.json();return this.testSession=R,E.commit=E.name,E.name=V,await this.trace.identify(this.testSession,{...E,company:V,apiKey:y}),!0}catch(E){return this.logAndTrace(`Error connecting to Checksum, the report will not be hosted - ${E.message}`,"Initialization Error"),this.setIsolatedMode(),!0}}setIsolatedMode(){this.isolationMode=!0,this.testSession="isolated-session",this.trace.setIsolatedMode()}async sendTestRunEnd(d){if(!this.isolationMode)try{let y="{}";try{y=JSON.stringify({...d,endedAt:Date.now()})}catch(E){this.logAndTrace(`Error stringifying stats ${E.message}`,"Runtime Error")}await this.updateTestRun(`${this.config.apiURL}/client-api/test-runs/${this.testSession}`,"PATCH",y)}catch(y){return this.logAndTrace(`Error sending test run end ${y.message}`,"Runtime Error"),null}}async sendUploadsComplete(){if(!this.isolationMode)try{await this.updateTestRun(`${this.config.apiURL}/client-api/test-runs/${this.testSession}/uploads-completed`,"PATCH")}catch(d){this.logAndTrace(`Error sending test run uploads complete - ${d.message}`,"Runtime Error")}}async sendProcessingError(){if(!this.isolationMode)try{await this.updateTestRun(`${this.config.apiURL}/client-api/test-runs/${this.testSession}/process-error`,"PATCH")}catch(d){this.logAndTrace(`Error sending test run processing error - ${d.message}`,"Runtime Error")}}async updateTestRun(d,y,E=void 0){let N=await fetch(d,{method:y,headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:E});return XG("Received update test run response from url:",d),await this.logApiResponse(N),N}async logApiResponse(d){try{if(!d.ok){let{status:E,statusText:N}=d,F=await d.text();this.trace.runtimeError({status:E,statusText:N,errorText:F});return}d.headers.get("Content-Type").includes("application/json")?d.json().then(E=>{XG("API Response:",E)}):d.text().then(E=>{XG("API Response:",E)})}catch(y){this.trace.eventWithMessage("Runtime Error",`Error logging API response - ${y.message}`)}}logTRMMessage(d){(Array.isArray(d)?d:[d]).forEach(y=>{XG("\x1B[33m","[trm]","\x1B[0m",y)})}};e(jrr,"TestsRunner");var Nwt=jrr;var Jrr=class Jrr extends sce{constructor(p,d=!1){super(p,d)}async run(p){switch(p){default:console.log(`