@checksum-ai/runtime 1.1.39 → 1.1.40

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.
Files changed (3) hide show
  1. package/cli.js +1 -1
  2. package/index.js +54 -54
  3. package/package.json +1 -1
package/cli.js CHANGED
@@ -108,7 +108,7 @@ Please see the 3.x to 4.x migration guide for details on how to update your app.
108
108
  <pre>`+t+`</pre>
109
109
  </body>
110
110
  </html>
111
- `}n(SZ,"createHtmlDocument");function kZ(){return n(function(){this.error(404)},"notFound")}n(kZ,"createNotFoundDirectoryListener");function _Z(){return n(function(t){if(this.hasTrailingSlash()){this.error(404);return}var r=Vx.original(this.req);r.path=null,r.pathname=wZ(r.pathname+"/");var i=gZ(yZ.format(r)),a=SZ("Redirecting","Redirecting to "+vZ(i));t.statusCode=301,t.setHeader("Content-Type","text/html; charset=UTF-8"),t.setHeader("Content-Length",Buffer.byteLength(a)),t.setHeader("Content-Security-Policy","default-src 'none'"),t.setHeader("X-Content-Type-Options","nosniff"),t.setHeader("Location",i),t.end(a)},"redirect")}n(_Z,"createRedirectDirectoryListener")});var t4=A((Wt,e4)=>{"use strict";var pf=tx(),AZ=require("events").EventEmitter,JP=GT(),XP=iP(),CZ=dx(),EZ=mx(),YP=PP(),QP=$P();Wt=e4.exports=TZ;function TZ(){var e=n(function(t,r,i){e.handle(t,r,i)},"app");return JP(e,AZ.prototype,!1),JP(e,XP,!1),e.request=Object.create(YP,{app:{configurable:!0,enumerable:!0,writable:!0,value:e}}),e.response=Object.create(QP,{app:{configurable:!0,enumerable:!0,writable:!0,value:e}}),e.init(),e}n(TZ,"createApplication");Wt.application=XP;Wt.request=YP;Wt.response=QP;Wt.Route=CZ;Wt.Router=EZ;Wt.json=pf.json;Wt.query=gx();Wt.raw=pf.raw;Wt.static=KP();Wt.text=pf.text;Wt.urlencoded=pf.urlencoded;var PZ=["bodyParser","compress","cookieSession","session","logger","cookieParser","favicon","responseTime","errorHandler","timeout","methodOverride","vhost","csrf","directory","limit","multipart","staticCache"];PZ.forEach(function(e){Object.defineProperty(Wt,e,{get:n(function(){throw new Error("Most middleware (like "+e+") is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.")},"get"),configurable:!0})})});var i4=A((gce,r4)=>{"use strict";r4.exports=t4()});var o4=A((vce,a4)=>{"use strict";var n4=Object.getOwnPropertySymbols,IZ=Object.prototype.hasOwnProperty,FZ=Object.prototype.propertyIsEnumerable;function RZ(e){if(e==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}n(RZ,"toObject");function MZ(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de",Object.getOwnPropertyNames(e)[0]==="5")return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;var i=Object.getOwnPropertyNames(t).map(function(s){return t[s]});if(i.join("")!=="0123456789")return!1;var a={};return"abcdefghijklmnopqrst".split("").forEach(function(s){a[s]=s}),Object.keys(Object.assign({},a)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}n(MZ,"shouldUseNative");a4.exports=MZ()?Object.assign:function(e,t){for(var r,i=RZ(e),a,s=1;s<arguments.length;s++){r=Object(arguments[s]);for(var l in r)IZ.call(r,l)&&(i[l]=r[l]);if(n4){a=n4(r);for(var u=0;u<a.length;u++)FZ.call(r,a[u])&&(i[a[u]]=r[a[u]])}}return i}});var c4=A((yce,s4)=>{(function(){"use strict";var e=o4(),t=$x(),r={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function i(S){return typeof S=="string"||S instanceof String}n(i,"isString");function a(S,k){if(Array.isArray(k)){for(var C=0;C<k.length;++C)if(a(S,k[C]))return!0;return!1}else return i(k)?S===k:k instanceof RegExp?k.test(S):!!k}n(a,"isOriginAllowed");function s(S,k){var C=k.headers.origin,I=[],F;return!S.origin||S.origin==="*"?I.push([{key:"Access-Control-Allow-Origin",value:"*"}]):i(S.origin)?(I.push([{key:"Access-Control-Allow-Origin",value:S.origin}]),I.push([{key:"Vary",value:"Origin"}])):(F=a(C,S.origin),I.push([{key:"Access-Control-Allow-Origin",value:F?C:!1}]),I.push([{key:"Vary",value:"Origin"}])),I}n(s,"configureOrigin");function l(S){var k=S.methods;return k.join&&(k=S.methods.join(",")),{key:"Access-Control-Allow-Methods",value:k}}n(l,"configureMethods");function u(S){return S.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}n(u,"configureCredentials");function d(S,k){var C=S.allowedHeaders||S.headers,I=[];return C?C.join&&(C=C.join(",")):(C=k.headers["access-control-request-headers"],I.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),C&&C.length&&I.push([{key:"Access-Control-Allow-Headers",value:C}]),I}n(d,"configureAllowedHeaders");function f(S){var k=S.exposedHeaders;if(k)k.join&&(k=k.join(","));else return null;return k&&k.length?{key:"Access-Control-Expose-Headers",value:k}:null}n(f,"configureExposedHeaders");function h(S){var k=(typeof S.maxAge=="number"||S.maxAge)&&S.maxAge.toString();return k&&k.length?{key:"Access-Control-Max-Age",value:k}:null}n(h,"configureMaxAge");function g(S,k){for(var C=0,I=S.length;C<I;C++){var F=S[C];F&&(Array.isArray(F)?g(F,k):F.key==="Vary"&&F.value?t(k,F.value):F.value&&k.setHeader(F.key,F.value))}}n(g,"applyHeaders");function x(S,k,C,I){var F=[],M=k.method&&k.method.toUpperCase&&k.method.toUpperCase();M==="OPTIONS"?(F.push(s(S,k)),F.push(u(S,k)),F.push(l(S,k)),F.push(d(S,k)),F.push(h(S,k)),F.push(f(S,k)),g(F,C),S.preflightContinue?I():(C.statusCode=S.optionsSuccessStatus,C.setHeader("Content-Length","0"),C.end())):(F.push(s(S,k)),F.push(u(S,k)),F.push(f(S,k)),g(F,C),I())}n(x,"cors");function w(S){var k=null;return typeof S=="function"?k=S:k=n(function(C,I){I(null,S)},"optionsCallback"),n(function(I,F,M){k(I,function(O,N){if(O)M(O);else{var j=e({},r,N),U=null;j.origin&&typeof j.origin=="function"?U=j.origin:j.origin&&(U=n(function(H,V){V(null,j.origin)},"originCallback")),U?U(I.headers.origin,function(H,V){H||!V?M(H):(j.origin=V,x(j,I,F,M))}):M()}})},"corsMiddleware")}n(w,"middlewareWrapper"),s4.exports=w})()});var Rl="checksum";var Hd=(u=>(u.CompleteWithErrors="complete-with-errors",u.Complete="complete",u.ReportComplete="report-complete",u.UploadProgress="upload-progress",u.Log="log",u.PlaywrightConfig="playwrightConfig",u.Port="port",u))(Hd||{});var Ko=At(require("path"));var Ce=n(e=>new Promise(t=>setTimeout(t,e)),"awaitSleep"),gt=n(async(e,t=1e3,r="guardReturnTimedOut")=>{if(t===null)return e;let i="guard-timed-out",a=n(async()=>(await Ce(t+1e3),i),"guard"),s=await Promise.race([e,a()]);if(typeof s=="string"&&s===i)throw new Error(r);return s},"guardReturn");function $d(e){return!!e&&!["navigation","keystroke","wait","get_more_items","custom_code","native_accept","native_dismiss","login"].includes(e)}n($d,"isActionOnElement");function Bb(e){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}[e]}n(Bb,"getActionEventCode");var Nb=n((e,t="page")=>t+"."+e.replace(".and(locator(",`.and(${t}.locator(`).replace(".or(locator(",`.or(${t}.locator(`),"injectBaseToLocatorString");var qb=n((e,t,r)=>{if(!t)return e;if(!r||!r.length)return e.locator(t);let i=e.frameLocator(r[0]);for(let a of r.slice(1))i=i.frameLocator(a);return i.locator(t)},"makeLocator");function Gd(){return process.env.CHECKSUM_ROOT_FOLDER?process.env.CHECKSUM_ROOT_FOLDER:Ko.join(__dirname,"..","..","..","checksum")}n(Gd,"checksumFolder");function jb({isInit:e,excludeLogin:t}){return[...e?["example.checksum.spec.ts","github-actions.example.yml"]:[],...t?[]:["login.ts"],"checksum.config.ts","playwright.config.ts","README.md",".gitignore.example"]}n(jb,"getRuntimeFiles");var hK={generateSelectionData:!1,navigationTimeout:30*1e3,actionTimeout:5*1e3};var m3=require("jsdom");var gN=At(Dm());var r_=At(t_());var Nm=class Nm{constructor(t){this.toJSON=n(()=>this.data,"toJSON");this.data=t}getSimilar(t){let r=null,i=-1/0;for(let a of Object.keys(this.data)){let s=(0,r_.levenshtein)([...t],[...a]);s>i&&(i=s,r=a)}return r?this.data[r]:null}};n(Nm,"SimilarityRecord");var Bm=Nm,Zi=class Zi extends Bm{constructor(t){super(Zi.preprocessRectangles(t))}getRectangleByTextAndSizeRanking(t,r){r=!r||!Number(r)?0:Number(r);let i=this.getSimilar(t);if(!i||i.length===0)return null;let a=Math.min(Math.max(r,0),i.length-1);return i[a]}};n(Zi,"RectangleIndex"),Zi.preprocessRectangles=n(t=>{let r=[...new Map([...t].map(a=>[JSON.stringify(a.vertices),a])).values()],i={};return r.forEach(a=>{i[a.text]||(i[a.text]=[]),i[a.text].push(a),i[a.text].sort((s,l)=>{let u=Zi.calculateArea(s.vertices),d=Zi.calculateArea(l.vertices);return u-d})}),i},"preprocessRectangles"),Zi.calculateArea=n(t=>{let r=Math.abs(t[1].x-t[0].x),i=Math.abs(t[3].y-t[0].y);return r*i},"calculateArea");var Cu=Zi;var o_=require("fs"),s_=require("path");function ft(e){return e._guid}n(ft,"getPageOrFrameGuid");async function Eu(e,t,r){let i=e,a=i._mainFrame;try{i._mainFrame=t,await r(i)}finally{i._mainFrame=a}}n(Eu,"executeOnPageWithFrame");var n_={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html"},qm={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"},a_=Object.fromEntries(Object.entries(qm).map(([e,t])=>[t,e]));var YB=!0,_TestGenerationPageInteractor=class _TestGenerationPageInteractor{constructor(e,t,r,i,a,s,l){this.evaluateWithChecksum=e;this.getFrame=t;this.getTimeMachine=r;this.logger=i;this.options=a;this.pageInteractorAPI=s;this.loginFunction=l;this.activeDialog=null;this.newPagesIds=[];this.listeners={dialog:null,filechooser:null,page:null};this.listenToContextPage=n(()=>{this.getPage().context().on("page",e=>{this.newPagesIds.push(e._guid)})},"listenToContextPage");this.listenToFileChooser=n(()=>{this.listeners.filechooser=async e=>{this.logger.log("File chooser event detected"),this.fileChooser=e},this.getPage().on("filechooser",this.listeners.filechooser)},"listenToFileChooser");this.waitForDialog=n((e=!0,t=1e4)=>new Promise(r=>{let a=0,s=n(()=>{if(this.activeDialog){let l=this.activeDialog;e&&(this.activeDialog=null),r(l)}else a>=t?r(null):(a+=1e3,setTimeout(s,1e3))},"checkDialog");s()}),"waitForDialog");this.performFileUploadAction=n(async(e,t)=>{if(!await e.evaluate(i=>i.tagName==="INPUT"&&i.getAttribute("type")==="file"))throw new Error("File upload action performed on non-file input element");let r=t.files.map(i=>(0,s_.join)(this.options.testAssetsDir,i)).filter(i=>(0,o_.existsSync)(i)?!0:(this.logger.log(`Upload file not found: ${i}. Filtering out.`),!1));if(!r.length)throw new Error("No files to upload");await this.actionGuardReturn(e.setInputFiles(r),"Set input files timeout")},"performFileUploadAction");this.getSelectionDataForAction=n(async(e,t)=>e.checksumid?this.getSelectionDataForChecksumId(e.checksumid,t):e.position?await this.evaluateWithChecksum(async([r,i])=>window.checksum.testGenerator.getSelectorByPosition(r,i),[e.position.x,e.position.y]):e.selector?{selector:e.selector,locator:`locator("${e.selector}")`}:{selector:"",locator:""},"getSelectionDataForAction")}getPage(){return this.getFrame().page()}init(){this.listenToContextPage(),this.listenToFileChooser(),this.options.listenToDialog&&this.listenToDialog()}listenToDialog(){this.listeners.dialog=async e=>{this.activeDialog=e},this.getPage().on("dialog",this.listeners.dialog)}removeListener(e){try{switch(e){case"dialog":this.listeners.dialog&&(this.getPage().removeListener(e,this.listeners.dialog),this.listeners.dialog=null);break;case"filechooser":this.getPage().off(e,this.listeners.filechooser),this.listeners.filechooser=null;break;case"page":this.getPage().context().off(e,this.listeners.page),this.listeners.page=null;break}}catch(t){this.logger.logError(`Error removing listener: ${e}`,t)}}getOpenedFileChooser(){if(this.fileChooser){let e=this.fileChooser;return this.fileChooser=void 0,e}return null}async handleFileChooserEvent(e=[]){let t=this.getOpenedFileChooser();if(!t)return{};let r="fc_"+Math.random().toString(36).slice(2,4);return await this.evaluateWithChecksum(async([i,a])=>{window.checksum.testGenerator.addForceIncludeElement(a,i)},[r,t.element()]),{interruptionEvent:"fileUploadOpenedEvent",payload:{checksumid:r,customFiles:e}}}async addMoreItemsToDom(e,t){let r=e.querySelector(`[checksum-get-more-items='${t}']`);if(!r)throw new Error("Get more items root not found");let{items:i,hasMoreItems:a}=await this.getMoreItemsForTemplate(t);r.innerHTML=r.innerHTML+i,a||r.removeAttribute("checksum-get-more-items")}async getPageInfo(e){let t=ft(e);return{id:t,url:e.url(),title:await e.title(),new:this.newPagesIds.includes(t),active:t===ft(this.getPage())}}async getTabsInfo(){var i;let e=this.getPage(),t=await Promise.all(e.context().pages().map(a=>this.getPageInfo(a))),r=(i=this.getTimeMachine())==null?void 0:i.getPage();return r&&r!==e&&(t=t.filter(a=>a.id!==ft(r))),this.newPagesIds=[],t}async getSelectionDataFromSelectorGenerator(e,t,r={}){if(r={useCompoundSelector:!0,useCSSExtraction:!0,useVariables:!0,useArbitrarySelector:!0,...r},!e||!$d(Bb(t.action.type))||!t.action.checksumid)return{};let i=await e.generateSelectionForAction(t,r);return i?{locator:`locator("${i.selector}")`,...i}:{}}async translateActionResponseToAgentPotentialAction(e,t=void 0,{pageId:r,makeStaticMetadataForESRA:i}={}){let a=structuredClone(e.actionHiddenOverride??e.action),{selector:s,selectorWithVars:l,locator:u,locatorWithVars:d,clickOffset:f,selectOptionValue:h,compoundSelector:g,alternateSelectors:x,parentFramesSelectors:w}={...await this.getSelectionDataForAction(a,e.actionHiddenOverride),...await this.getSelectionDataFromSelectorGenerator(t,e)},S=await this.getESRAForSelector(s,w,i);if(!S&&s&&this.logger.logError("Error getting ESRA metadata"),(S==null?void 0:S.tag)==="select")switch(this.getActionEventCode(a.type)){case"input":a.type="selectoption";break;case"click":h&&(a.type="selectoption",a.value=h);break}let k={eventCode:this.getActionEventCode(a.type),selector:s,selectorWithVars:l,parentFramesSelectors:w,locator:u,locatorWithVars:d,clickOffset:f,pageId:r,compoundSelector:g,alternateSelectors:x,fillValue:a.value,fillValueName:a.valueName?`variablesStore.${a.valueName}`:"",variables:e.variables,getMoreItemsId:a.getMoreItemsId,esraMetadata:S,thought:e.thought,userRole:a.userRole,canvas:a.canvas,id:a.id};switch(k.eventCode){case"drag_and_drop":{let{selector:C,selectorWithVars:I,locator:F,locatorWithVars:M,parentFramesSelectors:O}={...await this.getSelectionDataForAction({type:e.action.type,checksumid:e.action.dropTargetChecksumid}),...await this.getSelectionDataFromSelectorGenerator(t,{...e,action:{type:e.action.type,checksumid:e.action.dropTargetChecksumid}},{useCompoundSelector:!1})};k.dropTarget={selector:C,locator:F,parentFramesSelectors:O,esraMetadata:await this.getESRAForSelector(C,O,i)}}break;case"upload_files":k.files=this.mapFileMIMETypeToFilename(a.files);break;case"switch_tab":{let C=this.getPage();k.switchToTab={id:a.tabId,index:C.context().pages().findIndex(I=>ft(I)===a.tabId)};break}case"keystroke":k.fillValue=a.value}return k}async reauthenticate(e){let t=this.getPage();this.loginFunction&&(await Promise.all([t.context().clearCookies(),t.evaluate(()=>localStorage.clear())]),await this.loginFunction(t,{role:e}))}mapFileMIMETypeToFilename(e){return e.map(t=>{if(t.fileName)return t.fileName;switch(t.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(e,{useLocator:t=!1,handleActionFailed:r,monitorFlashingHTML:i=!0,timeout:a}={}){try{if(e.executed){this.logger.log("[performAction] Action marked as executed, skipping...");return}let s=t?!!e.locator:!!e.selector;if($d(e.eventCode)&&!s)throw new Error("No selector provided for action. Try changing app rules preMapReducedHTMLSelectors to true");i&&(this.logger.log("starting flashing elements detection"),await this.evaluateWithChecksum(async()=>window.checksum.testGenerator.startFlashingElementsDetection())),this.logger.log(`Performing action: ${e.eventCode}. Selector: ${e.selector}, Position: ${e.clickOffset}, Parent frame: ${e.parentFramesSelectors}`);let l=n(()=>t?this.makeLocatorFromLocator(e.locator):this.makeLocator(e.selector,e.parentFramesSelectors),"getLocator"),u=n(async(d,f,h={})=>this.actionGuardReturn(d,f,{timeout:a,...h}),"performWithActionGuard");switch(e.eventCode){case"click":try{await u(l().click({position:e.clickOffset}),"Click timeout")}catch(d){this.logger.log("Error performing click, will attempt a force click",d),e.force=!0,await u(l().click({position:e.clickOffset,force:!0}),"Force Click timeout")}break;case"double_click":try{await u(l().dblclick({position:e.clickOffset}),"DoubleClick timeout")}catch(d){this.logger.log("Error performing double click, will attempt a force double click",d),e.force=!0,await u(l().dblclick({position:e.clickOffset,force:!0}),"Force DoubleClick timeout")}break;case"check":await u(l().check(),"Check timeout");break;case"uncheck":await u(l().uncheck(),"UnCheck timeout");break;case"drag_and_drop":await u(l().dragTo(t?this.makeLocatorFromLocator(e.dropTarget.locator):this.makeLocator(e.dropTarget.selector,e.dropTarget.parentFramesSelectors)),"DragAndDrop timeout");break;case"input":await u(l().fill(this.getActionFillValue(e)),"Fill timeout");break;case"click_and_type":await gt(l().click({position:e.clickOffset}),1e4,"Click before type timeout"),await gt(l().pressSequentially(this.getActionFillValue(e)),1e4,"pressSequentially timeout");break;case"clear_and_type":await gt(l().clear(),1e4,"Clear before type timeout"),await gt(l().pressSequentially(this.getActionFillValue(e)),1e4,"pressSequentially timeout");break;case"selectoption":await u(l().selectOption(this.getActionFillValue(e)),"SelectOption timeout");break;case"hover":await u(l().hover(),"Hover timeout");break;case"navigation":await u(this.getFrame().goto(e.fillValue),"Navigation timeout",{isNavigation:!0});break;case"keystroke":{let d=this.getPage();await u(d.keyboard.press(e.fillValue),"Keystroke timeout");break}case"upload_files":await this.performFileUploadAction(l(),e);break;case"wait":await Ce(this.options.waitActionDelay??1e3);break;case"custom_code":await Eu(this.getPage(),this.getFrame(),async d=>{let f=`async (page) => {${e.fillValue}}`;await(0,eval)(f)(d)});break;case"logout_and_login":await this.reauthenticate(e.userRole);break;case"canvas_click":await this.canvasClick(l(),e.canvas);break}}catch(s){throw this.logger.log(`Error performing action: ${e.eventCode}, will attempt a correction template`,s),await(r==null?void 0:r()),new Error("Failed perfom action: "+s.message)}this.logger.log(`Successfully performed action ${e.eventCode} with description "${e.thought}"`)}async getTextDetection(e){return new Cu(await this.pageInteractorAPI.getTextDetection(e))}async canvasClick(e,t){try{if(!await e.evaluate(s=>s.tagName.toLowerCase()==="canvas"))throw new Error("Click attempted on a non-canvas element");let a=(await this.getTextDetection(await e.screenshot())).getRectangleByTextAndSizeRanking(t.canvasText,t.rectSizeIndex);if(!a)throw new Error(`Canvas click target not found for ${t.canvasText}`);this.logger.log(`Canvas click target: ${a}`),await this.actionGuardReturn(e.click({position:a.center}),"Canvas click could not be performed")}catch(r){throw this.logger.logError("Canvas click:",r.message),new Error("Canvas click action failed")}}getActionFillValue(e,t=!0){let r=e.fillValue;if(!r){let i=e.selector.match(/(?<=value.*)('|").*/);i&&(r=i[0].slice(1,-1))}return typeof r!="string"&&(r="X"),t&&(e.fillValue=r),r}actionGuardReturn(e,t,{isNavigation:r=!1,timeout:i}={}){return gt(e,i??(r?this.options.navigationTimeout:this.options.actionTimeout),t)}makeLocator(e,t=[]){return qb(this.getFrame(),e,t)}makeLocatorFromLocator(locator){return eval("this.getFrame()."+locator)}getCurrentURL(){return this.getFrame().url()}async getSelectionDataForChecksumId(e,t){if(t!=null&&t.selector)return{...t,selector:t.selector,clickOffset:t.position};if(!e)return this.logger.log(`[getSelectionDataForChecksumId] checksumid not provided (${e})`),{...t,selector:e};let r=await this.evaluateWithChecksum(async i=>{let{selector:a,locator:s,clickOffset:l,parentFramesSelectors:u,invalid:d,rrwebId:f}=await window.checksum.testGenerator.getSelectorForChecksumId(i),h=await window.checksum.testGenerator.getElementForChecksumId(i),g=h instanceof HTMLOptionElement&&h.value?h.value:void 0;return{selector:a,locator:s,clickOffset:l,selectOptionValue:g,parentFramesSelectors:u,invalid:d,rrwebId:f}},e);if(YB&&r.invalid&&r.rrwebId){this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${e}. Trying to use time machine...`);try{let i=await this.getSelectionDataForRRwebIdAtReduceHTMLTime(r.rrwebId);r={...r,...i}}catch{this.logger.log(`[getSelectionDataForChecksumId] error using time machine to get selector for checksumid: ${e}`)}this.logger.log(`[getSelectionDataForChecksumId] got selector: ${r.selector} for checksumid: ${e} from time machine`)}return r!=null&&r.selector||this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${e}. If checksumid is correct, try to change app rules preMapReducedHTMLSelectors to true`),r}async getSelectionDataForRRwebIdAtReduceHTMLTime(e){if(!this.rrwebEventAtLastReducedHTML)return;let t=this.getTimeMachine();if(t)return t.executeTask(r=>r.evaluate(async({rrwebId:i})=>await window.checksum.testGenerator.getInspectedElementSelectionResultByRRwebId(i,{ignoredIframesSelectors:[".replayer-wrapper > iframe"],fromTimeMachine:!0}),{rrwebId:e}),this.rrwebEventAtLastReducedHTML.timestamp,{name:"getSelectionDataForRRwebIdAtReduceHTMLTime"})}async getESRAForSelector(e,t,r){let i=await this.evaluateWithChecksum(async({selector:a,parentFramesSelectors:s})=>window.checksum.testGenerator.getSelectionDataForSelector(a,s),{selector:e,parentFramesSelectors:t});return i!=null&&i.esraMetadata&&r&&(i.esraMetadata.staticMetadata=await r(i.esraMetadata,e)),i==null?void 0:i.esraMetadata}async getMoreItemsForTemplate(e){return await this.evaluateWithChecksum(async t=>window.checksum.testGenerator.getMoreItemsForTemplate(t,{}),e)??{items:"",hasMoreItems:!1}}async getCurrentReducedHTML({retriesLeft:e=3,retryWaitMS:t=2e3,initialChecksumId:r="0",extractESRAForInterpretationRequiredElements:i=!1,stopFlashingElementsDetection:a=!1,assignChecksumIdsToAllElements:s}={}){let l=new Date;this.logger.log("[getCurrentReducedHTML] Fetching reduced HTML...");try{let{reducedHTML:u,currentChecksumId:d,flashingHTML:f,elementsForNodeInterpretation:h,lastRRwebEvent:g}=await this.evaluateWithChecksum(async w=>window.checksum.testGenerator.reduceHTML({},w),{initialChecksumId:r,extractESRAForInterpretationRequiredElements:i,stopFlashingElementsDetection:a,assignChecksumIdsToAllElements:s}),x=new Date;return this.logger.log(`[getCurrentReducedHTML] Fetched reduced HTML in ${x.getTime()-l.getTime()}ms`),this.rrwebEventAtLastReducedHTML=g,{reducedHTML:u,flashingHTML:f,elementsForNodeInterpretation:h,currentChecksumId:d}}catch(u){if(e>0)return this.logger.logError(`[getCurrentReducedHTML] Error: ${u.message}`),this.logger.logError(`Failed do obtain reduced HTML, trying again in ${t/1e3} seconds, ${e-1} to go.`),await Ce(t),this.getCurrentReducedHTML({retriesLeft:e-1,retryWaitMS:t});throw u}}getActionEventCode(e){return qm[e]}};n(_TestGenerationPageInteractor,"TestGenerationPageInteractor");var Ls=_TestGenerationPageInteractor;var jm=class jm{constructor(t){this.options=t;this.health=n(async()=>await fetch(`${this.options.apiURL}/client-api/runtime/api/health`,{headers:{ChecksumAppCode:this.options.apiKey}}).catch(t=>(console.log(t),null)),"health");this.getCanvasDetection=n(async t=>{try{let r=t.toString("base64");return await(await fetch(`${this.options.apiURL}/client-api/runtime/vision/text-detection`,{body:JSON.stringify({imageBuffer:r}),method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.options.apiKey}})).json()}catch(r){return console.log(r),null}},"getCanvasDetection")}};n(jm,"ChecksumClient");var Os=jm;var Um=class Um{constructor(){this.config={}}};n(Um,"PageInteractorAPI");var Tu=Um;var zm=class zm extends Tu{constructor(r){super();this.config=r;this.getTextDetection=n(async r=>{let i=await this.api.getCanvasDetection(r);if(!i)throw new Error("No data returned from canvas detection");return i},"getTextDetection");this.config=r,this.api=new Os({apiKey:r.apiKey,apiURL:r.apiURL})}};n(zm,"RuntimePageInteractorAPI");var Ds=zm;var c_=require("path");var Wm=class Wm{constructor(t){this.options=t;this.navigatingFrames={};this.trackedFramesGuid=[];this.frameNavigationPromises={};this.onFrameNavigated=n(async t=>{let r=ft(t);if(this.trackedFramesGuid.includes(r))return this.frameNavigationPromises[r]=new Promise(async i=>{await this.loadScript(t),i()}),this.frameNavigationPromises[r]},"onFrameNavigated");this.loadScript=n(async(t,{retriesLeft:r=3,retryWaitMS:i=2e3,useWrapper:a=!0}={})=>{var d,f;if(a&&this.scriptLoadWrapper)return this.scriptLoadWrapper(()=>this.loadScript(t,{retriesLeft:r,retryWaitMS:i,useWrapper:!1}),t);if(!this.addScriptTagOptions){console.warn("[InjectedScriptManager] addScriptTagOptions not set, skipping loadScript");return}if(this.isFrameClosed(t))return;let s=!1;try{s=this.scriptLoadCheck?await((d=this.scriptLoadCheck)==null?void 0:d.call(this,t)):!1}catch{}if(s||this.isFrameClosed(t))return;try{await t.addScriptTag(this.addScriptTagOptions)}catch(h){if(r>0)return console.warn(`[InjectedScriptManager] Failed to add script to frame ${ft(t)}, trying again in ${i/1e3} seconds, ${r-1} retries left.`,h.message),await Ce(i),this.loadScript(t,{retriesLeft:r-1,retryWaitMS:i,useWrapper:a});throw h}let l=ft(t),u=Date.now().toString(36)+Math.random().toString(36).substr(2);if(this.navigatingFrames[l]=u,this.options.scriptInitWait&&(console.log(`Waiting ${this.options.scriptInitWait}[ms] before onScriptLoad...`),await Ce(this.options.scriptInitWait),console.log("Done waiting before onScriptLoad")),!this.isFrameClosed(t)){if(this.navigatingFrames[l]&&this.navigatingFrames[l]!==u)return console.log("Page navigated again, waiting on new promise..."),this.frameNavigationPromises[l];try{await((f=this.scriptLoadCallback)==null?void 0:f.call(this,t))}catch(h){console.error("[WebDriver] onScriptLoad error",h)}}},"loadScript");this.addScriptTagOptions=this.makeFrameInjectedScriptOptions()}setScriptLoadCallback(t){return this.scriptLoadCallback=t,this}setScriptLoadCheck(t){return this.scriptLoadCheck=t,this}setScriptLoadWrapper(t){return this.scriptLoadWrapper=t,this}async addTrackedFrame(t,r=!0){let i="mainFrame"in t?t.mainFrame():t,a=ft(i);if(this.trackedFramesGuid.includes(a)||this.trackedFramesGuid.push(a),r)return this.onFrameNavigated(i)}getNavigationPromise(t){if(!t){console.warn("[InjectedScriptManager] getNavigationPromise called with undefined argument");return}let r=typeof t=="string"?t:"mainFrame"in t?ft(t.mainFrame()):ft(t);return this.frameNavigationPromises[r]}makeFrameInjectedScriptOptions(){switch(this.options.scriptSource){case"file":return this.options.scriptFile?{path:this.options.isScriptFileAbsolute?this.options.scriptFile:(0,c_.join)(process.cwd(),this.options.scriptFile)}:void 0;case"url":return this.options.scriptURL?{url:this.options.scriptURL}:void 0;default:return}}isFrameClosed(t){return t.isDetached()||t.page().isClosed()}};n(Wm,"InjectedScriptManager");var Bs=Wm;var Ln=At(require("path")),m_=require("fs");d_().config({path:Ln.resolve(Ln.join(__dirname,".."),".env")});var Vm=process.env.DEV_MODE==="true";function g_(){let e=__dirname;for(;!(0,m_.existsSync)(Ln.join(e,"package.json"));)e=Ln.join(e,"..");return e}n(g_,"findRoot");var h_=Ln.join(g_(),"vtg-build","index.html"),Je={isDevMode:Vm,checksumScript:{source:Vm?"url":"file",url:process.env.SCRIPT_URL,path:g_()+"/checksumlib.js"},vtg:{localBuildPath:h_,appURL:Vm?process.env.VTG_APP_URL:`file://${h_}`,useFakeStory:process.env.USE_FAKE_STORY==="true",taskTimeMachine:{showTaskTimeMachine:process.env.SHOW_TASK_TIME_MACHINE==="true"},aiAssertions:{disabled:process.env.AI_ASSERTIONS_DISABLED==="true",allowRefactoring:process.env.ALLOW_AI_ASSERTIONS_REFACTORING==="true"}},testRun:{timeMachine:{active:!0,headless:!0}}};var Zm=class Zm{constructor(){this.frames={};this.pages=[];this.channels={}}register(t,r){if(this.frames[t])return;this.frames[t]=r;let i=r.page();this.pages.includes(i)||(this.pages.push(i),i.exposeFunction("checksumSendMessage",async(a,s)=>{let l=this.frames[a];if(!l)throw new Error(`Frame ${a} not found`);try{await l.evaluate(({message:u})=>{window.postMessage(u,"*")},{message:s})}catch{}}),i.exposeFunction("checksumSendBroadcastMessage",async(a,s)=>{(this.channels[a]??[]).forEach(async u=>{if(!(u.originFrameGuid&&u.originFrameGuid!==ft(r)))try{u.handler?await u.handler(s):await r.evaluate(({message:d})=>{window.postMessage(d,"*")},{message:s})}catch{}})}),i.exposeFunction("checksumBringPageToFront",async a=>{let s=this.frames[a];s&&await s.page().bringToFront()}))}subscribeToChannel(t,r,{originFrame:i,handler:a}={}){var s;(s=this.channels)[t]??(s[t]=[]),this.channels[t].push({frame:r,originFrameGuid:i?ft(i):void 0,handler:a})}unsubscribeFromChannel(t,r){var i;(i=this.channels)[t]??(i[t]=[]),this.channels[t]=this.channels[t].filter(a=>a.frame!==r)}};n(Zm,"FramesMsgBroker");var Ns=Zm;var v_=require("@playwright/test");var Km=class Km{constructor(t,r,i={headless:!0,logPerformance:!1,timestampBatchingEnabled:!1,sortByTimestamp:!1}){this.frameMsgBroker=t;this.injectedScriptManager=r;this.options=i;this.taskQueue=[];this.isRunning=!1;this.currentTimestamp=0;this.currentBeforeTimestamp=!1;this.timeMachineTaskIndex=0;this.rrwebEventHandler=n(async t=>{let r=JSON.stringify(t);await this.timeMachineFrame.evaluate(function(i){let a=JSON.parse(i);return window.checksum.timeMachine.handleEvents(a)},r),t=null},"rrwebEventHandler")}getPage(){return this.timeMachineFrame.page()}getFrame(){return this.timeMachineFrame}async prepare(t,r){this.recordingFrame=t,this.frameMsgBroker.register("live",t),r?this.timeMachineFrame=r:this.timeMachineFrame=await this.prepareBrowserContextAndFrame(),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(t){this.timeMachineBrowserContext=t}async executeTask(t,r=void 0,{name:i,beforeTimestamp:a=!1}={}){return new Promise((s,l)=>{let u=this.timeMachineTaskIndex++,d=n(async({shouldGoBack:f,shouldBatch:h}={shouldGoBack:!0,shouldBatch:this.options.timestampBatchingEnabled})=>{this.timeMachineFrame.isDetached()&&l(),f&&await this.goBack(r,a);let x=[n(async()=>{try{let w=await t(this.timeMachineFrame);s(w)}catch(w){l(w)}},"safeRunTask")()];this.taskQueue.length>0&&h&&(x.push(...this.taskQueue.filter(w=>w.timestamp===r).map(({task:w})=>w({shouldGoBack:!1,shouldBatch:!1}))),this.taskQueue=this.taskQueue.filter(w=>w.timestamp!==r),x.length&&console.log(`Batching to task "${i}, index: ${u} ${x.length-1} more tasks`)),await Promise.all(x)},"taskWrapper");this.taskQueue.push({name:i,task:d,timestamp:a?r-1:r,queuedAt:Date.now(),index:u}),this.runTasks()})}goBack(t,r=!1){return this.currentBeforeTimestamp===r&&this.currentTimestamp===t?Promise.resolve():(this.currentTimestamp=t,this.currentBeforeTimestamp=r,this.timeMachineFrame.evaluate(({timestamp:i,beforeTimestamp:a})=>i===void 0?window.checksum.timeMachine.goLive():window.checksum.timeMachine.goBack(i,{beforeTimestamp:a}),{timestamp:t,beforeTimestamp:r}))}goLive(){return this.timeMachineFrame.evaluate(()=>window.checksum.timeMachine.goLive())}popTask(){return this.options.sortByTimestamp&&(this.taskQueue=this.taskQueue.sort((t,r)=>t.timestamp-r.timestamp)),this.taskQueue.shift()}async runTasks(){if(this.isRunning)return;this.isRunning=!0;let t=this.popTask(),r=Date.now();try{let i=Date.now()-t.queuedAt;await t.task();let a=Date.now()-r;this.options.logPerformance&&console.log(`running task "${t.name}, index: ${t.index} was pending for`,i,"ms and took",a)}catch(i){console.error("Task execution error:",i)}finally{this.isRunning=!1,this.taskQueue.length>0&&this.runTasks()}}async makeBrowserContext(){let t=await v_.chromium.launch({devtools:!1,headless:this.options.headless});return this.timeMachineBrowserContext=await t.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 t="rrweb";this.frameMsgBroker.subscribeToChannel(t,this.timeMachineFrame,{originFrame:this.recordingFrame,handler:this.rrwebEventHandler}),this.timeMachineFrame.page().on("close",()=>this.frameMsgBroker.unsubscribeFromChannel(t,this.timeMachineFrame))}async toggleTimeMachineHandleEvents(t){try{await this.timeMachineFrame.evaluate(r=>window.checksum.timeMachine.setShouldHandleEvents(r),t)}catch{}}};n(Km,"ChecksumTimeMachine");var On=Km;var hN=require("@playwright/test");var ote=1e3*30;var x_=require("fs");var y_=!1;function Jm(e){y_=e}n(Jm,"setLogToConsole");function Ve(...e){y_&&console.log(...e)}n(Ve,"log");function Ym(e,{role:t,environment:r}={},i=!1){var u,d;let a;r&&(a=(u=e.environments)==null?void 0:u.find(({name:f})=>r===f)),a||(a=(d=e.environments)==null?void 0:d.find(({default:f})=>f)),a||(a={baseURL:e.baseURL,default:!0,name:void 0});let s=(a==null?void 0:a.users)??e.users,l;if(s&&(t&&(l=s.find(f=>f.role===t)),l||(l=s.find(f=>f.default))),l||(l={role:void 0,username:e.username,password:e.password,default:!0}),r&&a.name!==r){if(i)throw new Error(`Could not find environment with name "${r}" in config file`);console.warn(`Could not find environment with name "${r}" in config file, trying to use default environment`)}if(t&&l.role!==t){if(i)throw new Error(`Could not find user with role "${t}" for environment "${r}" in config file`);console.warn(`Could not find user with role "${t}" for environment "${r}" in config file, trying to login with environment's default user`)}return{environment:a,user:l}}n(Ym,"resolveEnvironment");async function vN(e){let t=`${e??Gd()}/login.ts`;if(!(0,x_.existsSync)(t))throw console.warn(`Could not locate the login.ts file. Please make sure your login file exists at ${t}`),new Error("Could not find login.ts file");try{return console.log("Loading login.ts file",t),require(t).default}catch(r){throw console.warn("Error loading login.ts file",r),r}}n(vN,"requireLogin");async function xN(e,{environment:t,user:r,credentials:i,config:a,dir:s}){let l=await vN(s);try{let u=n(()=>l(e,{...a,...i},{environment:t,user:r}),"performLogin");"checksumAI"in e?await e.checksumAI(`Log in${r!=null&&r.role?` using ${r.role} role`:""}${t!=null&&t.name?` in ${t.name} environment`:""}`,u):await u()}catch(u){throw console.warn("The login method threw an exception, please check the login.ts file",u),u}}n(xN,"proceedWithLogin");function Xm(e){let{config:t,folder:r,throwIfAuthFailed:i}=e;return async(a,{role:s,environment:l}={})=>{let u={username:t.username,password:t.password},{environment:d,user:f}=Ym(t,{role:s,environment:l},e.throwIfEnvInfoInvalid);if(i&&!f)throw new Error("Could not find user credentials matching the provided role and/or environment");f&&(u.username=f.username,u.password=f.password),await xN(a,{environment:d,user:f,credentials:u,config:t,dir:r})}}n(Xm,"makeUnboundLogin");var b_=require("fs"),w_=At(require("child_process")),qs=require("path");var dt=require("fs"),Iu=At(require("child_process")),er=require("path");var Qm=class Qm{constructor(t,r=!1){this.args=t;this.debugMode=r;this.checksumAppUrl="https://app.checksum.ai";this.childProcesses=[];this.printError=n(t=>{console.log("\x1B[31m%s\x1B[0m",t)},"printError");this.processConfigArg(),["SIGINT","SIGTERM"].forEach(i=>{process.on(i,()=>{this.cleanup(),process.exit()})}),this.checksumRuntimeVersion=this.getChecksumRuntimeVersion()}getChecksumRuntimeVersion(){if(this.checksumRuntimeVersion)return this.checksumRuntimeVersion;try{return require("./package.json").version}catch{return"unknown"}}async execCmd(t,r={}){let i={...process.env,...r},a=await Iu.spawn(t,{env:i,shell:!0,stdio:"inherit"});return this.childProcesses.push(a),new Promise((l,u)=>{a.on("exit",d=>{d===0?l(!0):u(new Error(`Checksum failed execution with code: ${d} `)),this.childProcesses=this.childProcesses.filter(f=>f!==a)})})}async getCmdOutput(t){return new Promise(function(r,i){Iu.exec(t,(a,s,l)=>{if(a){i(`Error executing command: ${a.message}`);return}r(s.trim())})})}validateAuthExists(){this.checksumRoot||this.findChecksumRoot();let t=(0,er.join)(this.checksumRoot,".auth");(0,dt.existsSync)(t)||(0,dt.writeFileSync)(t,"{}")}loadChecksumData(){this.locateChecksumLibs(),this.setChecksumConfig()}async patchPlaywright(t=!1){Ve("Patching playwright",t);let r=(0,er.join)(__dirname,"./scripts/patch.js");(0,dt.existsSync)(r)||(r=(0,er.join)(__dirname,"../../../scripts/src/patch_playwright.js"));let i=`node "${r}"${t?" off":""}`;try{await this.execCmd(i,{PROJECT_ROOT:this.projectRootDirectory,RUNTIME:"true"})}catch(a){console.log("Error patching playwright",a.message)}}getPlaywrightConfigFilePath(){return(0,er.join)(this.checksumRoot,"playwright.config.ts")}buildVolatileConfig(){if(!this.volatileChecksumConfig)return;let t=this.getVolatileConfigPath(),r=`
111
+ `}n(SZ,"createHtmlDocument");function kZ(){return n(function(){this.error(404)},"notFound")}n(kZ,"createNotFoundDirectoryListener");function _Z(){return n(function(t){if(this.hasTrailingSlash()){this.error(404);return}var r=Vx.original(this.req);r.path=null,r.pathname=wZ(r.pathname+"/");var i=gZ(yZ.format(r)),a=SZ("Redirecting","Redirecting to "+vZ(i));t.statusCode=301,t.setHeader("Content-Type","text/html; charset=UTF-8"),t.setHeader("Content-Length",Buffer.byteLength(a)),t.setHeader("Content-Security-Policy","default-src 'none'"),t.setHeader("X-Content-Type-Options","nosniff"),t.setHeader("Location",i),t.end(a)},"redirect")}n(_Z,"createRedirectDirectoryListener")});var t4=A((Wt,e4)=>{"use strict";var pf=tx(),AZ=require("events").EventEmitter,JP=GT(),XP=iP(),CZ=dx(),EZ=mx(),YP=PP(),QP=$P();Wt=e4.exports=TZ;function TZ(){var e=n(function(t,r,i){e.handle(t,r,i)},"app");return JP(e,AZ.prototype,!1),JP(e,XP,!1),e.request=Object.create(YP,{app:{configurable:!0,enumerable:!0,writable:!0,value:e}}),e.response=Object.create(QP,{app:{configurable:!0,enumerable:!0,writable:!0,value:e}}),e.init(),e}n(TZ,"createApplication");Wt.application=XP;Wt.request=YP;Wt.response=QP;Wt.Route=CZ;Wt.Router=EZ;Wt.json=pf.json;Wt.query=gx();Wt.raw=pf.raw;Wt.static=KP();Wt.text=pf.text;Wt.urlencoded=pf.urlencoded;var PZ=["bodyParser","compress","cookieSession","session","logger","cookieParser","favicon","responseTime","errorHandler","timeout","methodOverride","vhost","csrf","directory","limit","multipart","staticCache"];PZ.forEach(function(e){Object.defineProperty(Wt,e,{get:n(function(){throw new Error("Most middleware (like "+e+") is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.")},"get"),configurable:!0})})});var i4=A((gce,r4)=>{"use strict";r4.exports=t4()});var o4=A((vce,a4)=>{"use strict";var n4=Object.getOwnPropertySymbols,IZ=Object.prototype.hasOwnProperty,FZ=Object.prototype.propertyIsEnumerable;function RZ(e){if(e==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}n(RZ,"toObject");function MZ(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de",Object.getOwnPropertyNames(e)[0]==="5")return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;var i=Object.getOwnPropertyNames(t).map(function(s){return t[s]});if(i.join("")!=="0123456789")return!1;var a={};return"abcdefghijklmnopqrst".split("").forEach(function(s){a[s]=s}),Object.keys(Object.assign({},a)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}n(MZ,"shouldUseNative");a4.exports=MZ()?Object.assign:function(e,t){for(var r,i=RZ(e),a,s=1;s<arguments.length;s++){r=Object(arguments[s]);for(var l in r)IZ.call(r,l)&&(i[l]=r[l]);if(n4){a=n4(r);for(var u=0;u<a.length;u++)FZ.call(r,a[u])&&(i[a[u]]=r[a[u]])}}return i}});var c4=A((yce,s4)=>{(function(){"use strict";var e=o4(),t=$x(),r={origin:"*",methods:"GET,HEAD,PUT,PATCH,POST,DELETE",preflightContinue:!1,optionsSuccessStatus:204};function i(S){return typeof S=="string"||S instanceof String}n(i,"isString");function a(S,k){if(Array.isArray(k)){for(var C=0;C<k.length;++C)if(a(S,k[C]))return!0;return!1}else return i(k)?S===k:k instanceof RegExp?k.test(S):!!k}n(a,"isOriginAllowed");function s(S,k){var C=k.headers.origin,I=[],F;return!S.origin||S.origin==="*"?I.push([{key:"Access-Control-Allow-Origin",value:"*"}]):i(S.origin)?(I.push([{key:"Access-Control-Allow-Origin",value:S.origin}]),I.push([{key:"Vary",value:"Origin"}])):(F=a(C,S.origin),I.push([{key:"Access-Control-Allow-Origin",value:F?C:!1}]),I.push([{key:"Vary",value:"Origin"}])),I}n(s,"configureOrigin");function l(S){var k=S.methods;return k.join&&(k=S.methods.join(",")),{key:"Access-Control-Allow-Methods",value:k}}n(l,"configureMethods");function u(S){return S.credentials===!0?{key:"Access-Control-Allow-Credentials",value:"true"}:null}n(u,"configureCredentials");function d(S,k){var C=S.allowedHeaders||S.headers,I=[];return C?C.join&&(C=C.join(",")):(C=k.headers["access-control-request-headers"],I.push([{key:"Vary",value:"Access-Control-Request-Headers"}])),C&&C.length&&I.push([{key:"Access-Control-Allow-Headers",value:C}]),I}n(d,"configureAllowedHeaders");function f(S){var k=S.exposedHeaders;if(k)k.join&&(k=k.join(","));else return null;return k&&k.length?{key:"Access-Control-Expose-Headers",value:k}:null}n(f,"configureExposedHeaders");function h(S){var k=(typeof S.maxAge=="number"||S.maxAge)&&S.maxAge.toString();return k&&k.length?{key:"Access-Control-Max-Age",value:k}:null}n(h,"configureMaxAge");function g(S,k){for(var C=0,I=S.length;C<I;C++){var F=S[C];F&&(Array.isArray(F)?g(F,k):F.key==="Vary"&&F.value?t(k,F.value):F.value&&k.setHeader(F.key,F.value))}}n(g,"applyHeaders");function x(S,k,C,I){var F=[],M=k.method&&k.method.toUpperCase&&k.method.toUpperCase();M==="OPTIONS"?(F.push(s(S,k)),F.push(u(S,k)),F.push(l(S,k)),F.push(d(S,k)),F.push(h(S,k)),F.push(f(S,k)),g(F,C),S.preflightContinue?I():(C.statusCode=S.optionsSuccessStatus,C.setHeader("Content-Length","0"),C.end())):(F.push(s(S,k)),F.push(u(S,k)),F.push(f(S,k)),g(F,C),I())}n(x,"cors");function w(S){var k=null;return typeof S=="function"?k=S:k=n(function(C,I){I(null,S)},"optionsCallback"),n(function(I,F,M){k(I,function(O,N){if(O)M(O);else{var j=e({},r,N),U=null;j.origin&&typeof j.origin=="function"?U=j.origin:j.origin&&(U=n(function(H,V){V(null,j.origin)},"originCallback")),U?U(I.headers.origin,function(H,V){H||!V?M(H):(j.origin=V,x(j,I,F,M))}):M()}})},"corsMiddleware")}n(w,"middlewareWrapper"),s4.exports=w})()});var Rl="checksum";var Hd=(u=>(u.CompleteWithErrors="complete-with-errors",u.Complete="complete",u.ReportComplete="report-complete",u.UploadProgress="upload-progress",u.Log="log",u.PlaywrightConfig="playwrightConfig",u.Port="port",u))(Hd||{});var Ko=At(require("path"));var Ce=n(e=>new Promise(t=>setTimeout(t,e)),"awaitSleep"),gt=n(async(e,t=1e3,r="guardReturnTimedOut")=>{if(t===null)return e;let i="guard-timed-out",a=n(async()=>(await Ce(t+1e3),i),"guard"),s=await Promise.race([e,a()]);if(typeof s=="string"&&s===i)throw new Error(r);return s},"guardReturn");function $d(e){return!!e&&!["navigation","keystroke","wait","get_more_items","custom_code","native_accept","native_dismiss","login"].includes(e)}n($d,"isActionOnElement");function Bb(e){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}[e]}n(Bb,"getActionEventCode");var Nb=n((e,t="page")=>t+"."+e.replace(".and(locator(",`.and(${t}.locator(`).replace(".or(locator(",`.or(${t}.locator(`),"injectBaseToLocatorString");var qb=n((e,t,r)=>{if(!t)return e;if(!r||!r.length)return e.locator(t);let i=e.frameLocator(r[0]);for(let a of r.slice(1))i=i.frameLocator(a);return i.locator(t)},"makeLocator");function Gd(){return process.env.CHECKSUM_ROOT_FOLDER?process.env.CHECKSUM_ROOT_FOLDER:Ko.join(__dirname,"..","..","..","checksum")}n(Gd,"checksumFolder");function jb({isInit:e,excludeLogin:t}){return[...e?["example.checksum.spec.ts","github-actions.example.yml"]:[],...t?[]:["login.ts"],"checksum.config.ts","playwright.config.ts","README.md",".gitignore.example"]}n(jb,"getRuntimeFiles");var hK={generateSelectionData:!1,navigationTimeout:30*1e3,actionTimeout:5*1e3};var m3=require("jsdom");var gN=At(Dm());var r_=At(t_());var Nm=class Nm{constructor(t){this.toJSON=n(()=>this.data,"toJSON");this.data=t}getSimilar(t){let r=null,i=-1/0;for(let a of Object.keys(this.data)){let s=(0,r_.levenshtein)([...t],[...a]);s>i&&(i=s,r=a)}return r?this.data[r]:null}};n(Nm,"SimilarityRecord");var Bm=Nm,Zi=class Zi extends Bm{constructor(t){super(Zi.preprocessRectangles(t))}getRectangleByTextAndSizeRanking(t,r){r=!r||!Number(r)?0:Number(r);let i=this.getSimilar(t);if(!i||i.length===0)return null;let a=Math.min(Math.max(r,0),i.length-1);return i[a]}};n(Zi,"RectangleIndex"),Zi.preprocessRectangles=n(t=>{let r=[...new Map([...t].map(a=>[JSON.stringify(a.vertices),a])).values()],i={};return r.forEach(a=>{i[a.text]||(i[a.text]=[]),i[a.text].push(a),i[a.text].sort((s,l)=>{let u=Zi.calculateArea(s.vertices),d=Zi.calculateArea(l.vertices);return u-d})}),i},"preprocessRectangles"),Zi.calculateArea=n(t=>{let r=Math.abs(t[1].x-t[0].x),i=Math.abs(t[3].y-t[0].y);return r*i},"calculateArea");var Cu=Zi;var o_=require("fs"),s_=require("path");function ft(e){return e._guid}n(ft,"getPageOrFrameGuid");async function Eu(e,t,r){let i=e,a=i._mainFrame;try{i._mainFrame=t,await r(i)}finally{i._mainFrame=a}}n(Eu,"executeOnPageWithFrame");var n_={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html"},qm={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"},a_=Object.fromEntries(Object.entries(qm).map(([e,t])=>[t,e]));var YB=!0,_TestGenerationPageInteractor=class _TestGenerationPageInteractor{constructor(e,t,r,i,a,s,l){this.evaluateWithChecksum=e;this.getFrame=t;this.getTimeMachine=r;this.logger=i;this.options=a;this.pageInteractorAPI=s;this.loginFunction=l;this.activeDialog=null;this.newPagesIds=[];this.listeners={dialog:null,filechooser:null,page:null};this.listenToContextPage=n(()=>{this.getPage().context().on("page",e=>{this.newPagesIds.push(e._guid)})},"listenToContextPage");this.listenToFileChooser=n(()=>{this.listeners.filechooser=async e=>{this.logger.log("File chooser event detected"),this.fileChooser=e},this.getPage().on("filechooser",this.listeners.filechooser)},"listenToFileChooser");this.waitForDialog=n((e=!0,t=1e4)=>new Promise(r=>{let a=0,s=n(()=>{if(this.activeDialog){let l=this.activeDialog;e&&(this.activeDialog=null),r(l)}else a>=t?r(null):(a+=1e3,setTimeout(s,1e3))},"checkDialog");s()}),"waitForDialog");this.performFileUploadAction=n(async(e,t)=>{if(!await e.evaluate(i=>i.tagName==="INPUT"&&i.getAttribute("type")==="file"))throw new Error("File upload action performed on non-file input element");let r=t.files.map(i=>(0,s_.join)(this.options.testAssetsDir,i)).filter(i=>(0,o_.existsSync)(i)?!0:(this.logger.log(`Upload file not found: ${i}. Filtering out.`),!1));if(!r.length)throw new Error("No files to upload");await this.actionGuardReturn(e.setInputFiles(r),"Set input files timeout")},"performFileUploadAction");this.getSelectionDataForAction=n(async(e,t)=>e.checksumid?this.getSelectionDataForChecksumId(e.checksumid,t):e.position?await this.evaluateWithChecksum(async([r,i])=>window.checksum.testGenerator.getSelectorByPosition(r,i),[e.position.x,e.position.y]):e.selector?{selector:e.selector,locator:`locator("${e.selector}")`}:{selector:"",locator:""},"getSelectionDataForAction")}getPage(){return this.getFrame().page()}init(){this.listenToContextPage(),this.listenToFileChooser(),this.options.listenToDialog&&this.listenToDialog()}listenToDialog(){this.listeners.dialog=async e=>{this.activeDialog=e},this.getPage().on("dialog",this.listeners.dialog)}removeListener(e){try{switch(e){case"dialog":this.listeners.dialog&&(this.getPage().removeListener(e,this.listeners.dialog),this.listeners.dialog=null);break;case"filechooser":this.getPage().off(e,this.listeners.filechooser),this.listeners.filechooser=null;break;case"page":this.getPage().context().off(e,this.listeners.page),this.listeners.page=null;break}}catch(t){this.logger.logError(`Error removing listener: ${e}`,t)}}getOpenedFileChooser(){if(this.fileChooser){let e=this.fileChooser;return this.fileChooser=void 0,e}return null}async handleFileChooserEvent(e=[]){let t=this.getOpenedFileChooser();if(!t)return{};let r="fc_"+Math.random().toString(36).slice(2,4);return await this.evaluateWithChecksum(async([i,a])=>{window.checksum.testGenerator.addForceIncludeElement(a,i)},[r,t.element()]),{interruptionEvent:"fileUploadOpenedEvent",payload:{checksumid:r,customFiles:e}}}async addMoreItemsToDom(e,t){let r=e.querySelector(`[checksum-get-more-items='${t}']`);if(!r)throw new Error("Get more items root not found");let{items:i,hasMoreItems:a}=await this.getMoreItemsForTemplate(t);r.innerHTML=r.innerHTML+i,a||r.removeAttribute("checksum-get-more-items")}async getPageInfo(e){let t=ft(e);return{id:t,url:e.url(),title:await e.title(),new:this.newPagesIds.includes(t),active:t===ft(this.getPage())}}async getTabsInfo(){var i;let e=this.getPage(),t=await Promise.all(e.context().pages().map(a=>this.getPageInfo(a))),r=(i=this.getTimeMachine())==null?void 0:i.getPage();return r&&r!==e&&(t=t.filter(a=>a.id!==ft(r))),this.newPagesIds=[],t}async getSelectionDataFromSelectorGenerator(e,t,r={}){if(r={useCompoundSelector:!0,useCSSExtraction:!0,useVariables:!0,useArbitrarySelector:!0,...r},!e||!$d(Bb(t.action.type))||!t.action.checksumid)return{};let i=await e.generateSelectionForAction(t,r);return i?{locator:`locator("${i.selector}")`,...i}:{}}async translateActionResponseToAgentPotentialAction(e,t=void 0,{pageId:r,makeStaticMetadataForESRA:i}={}){let a=structuredClone(e.actionHiddenOverride??e.action),{selector:s,selectorWithVars:l,locator:u,locatorWithVars:d,clickOffset:f,selectOptionValue:h,compoundSelector:g,alternateSelectors:x,parentFramesSelectors:w}={...await this.getSelectionDataForAction(a,e.actionHiddenOverride),...await this.getSelectionDataFromSelectorGenerator(t,e)},S=await this.getESRAForSelector(s,w,i);if(!S&&s&&this.logger.logError("Error getting ESRA metadata"),(S==null?void 0:S.tag)==="select")switch(this.getActionEventCode(a.type)){case"input":a.type="selectoption";break;case"click":h&&(a.type="selectoption",a.value=h);break}let k={eventCode:this.getActionEventCode(a.type),selector:s,selectorWithVars:l,parentFramesSelectors:w,locator:u,locatorWithVars:d,clickOffset:f,pageId:r,compoundSelector:g,alternateSelectors:x,fillValue:a.value,fillValueName:a.valueName?`variablesStore.${a.valueName}`:"",variables:e.variables,getMoreItemsId:a.getMoreItemsId,esraMetadata:S,thought:e.thought,userRole:a.userRole,canvas:a.canvas,id:a.id};switch(k.eventCode){case"drag_and_drop":{let{selector:C,selectorWithVars:I,locator:F,locatorWithVars:M,parentFramesSelectors:O}={...await this.getSelectionDataForAction({type:e.action.type,checksumid:e.action.dropTargetChecksumid}),...await this.getSelectionDataFromSelectorGenerator(t,{...e,action:{type:e.action.type,checksumid:e.action.dropTargetChecksumid}},{useCompoundSelector:!1})};k.dropTarget={selector:C,locator:F,parentFramesSelectors:O,esraMetadata:await this.getESRAForSelector(C,O,i)}}break;case"upload_files":k.files=this.mapFileMIMETypeToFilename(a.files);break;case"switch_tab":{let C=this.getPage();k.switchToTab={id:a.tabId,index:C.context().pages().findIndex(I=>ft(I)===a.tabId)};break}case"keystroke":k.fillValue=a.value}return k}async reauthenticate(e){let t=this.getPage();this.loginFunction&&(await Promise.all([t.context().clearCookies(),t.evaluate(()=>localStorage.clear())]),await this.loginFunction(t,{role:e}))}mapFileMIMETypeToFilename(e){return e.map(t=>{if(t.fileName)return t.fileName;switch(t.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(e,{useLocator:t=!1,handleActionFailed:r,monitorFlashingHTML:i=!0,timeout:a}={}){try{if(e.executed){this.logger.log("[performAction] Action marked as executed, skipping...");return}let s=t?!!e.locator:!!e.selector;if($d(e.eventCode)&&!s)throw new Error("No selector provided for action. Try changing app rules preMapReducedHTMLSelectors to true");i&&(this.logger.log("starting flashing elements detection"),await this.evaluateWithChecksum(async()=>window.checksum.testGenerator.startFlashingElementsDetection())),this.logger.log(`Performing action: ${e.eventCode}. Selector: ${e.selector}, Position: ${e.clickOffset}, Parent frame: ${e.parentFramesSelectors}`);let l=n(()=>t?this.makeLocatorFromLocator(e.locator):this.makeLocator(e.selector,e.parentFramesSelectors),"getLocator"),u=n(async(d,f,h={})=>this.actionGuardReturn(d,f,{timeout:a,...h}),"performWithActionGuard");switch(e.eventCode){case"click":try{await u(l().click({position:e.clickOffset}),"Click timeout")}catch(d){this.logger.log("Error performing click, will attempt a force click",d),e.force=!0,await u(l().click({position:e.clickOffset,force:!0}),"Force Click timeout")}break;case"double_click":try{await u(l().dblclick({position:e.clickOffset}),"DoubleClick timeout")}catch(d){this.logger.log("Error performing double click, will attempt a force double click",d),e.force=!0,await u(l().dblclick({position:e.clickOffset,force:!0}),"Force DoubleClick timeout")}break;case"check":await u(l().check(),"Check timeout");break;case"uncheck":await u(l().uncheck(),"UnCheck timeout");break;case"drag_and_drop":await u(l().dragTo(t?this.makeLocatorFromLocator(e.dropTarget.locator):this.makeLocator(e.dropTarget.selector,e.dropTarget.parentFramesSelectors)),"DragAndDrop timeout");break;case"input":await u(l().fill(this.getActionFillValue(e)),"Fill timeout");break;case"click_and_type":await gt(l().click({position:e.clickOffset}),1e4,"Click before type timeout"),await gt(l().pressSequentially(this.getActionFillValue(e)),1e4,"pressSequentially timeout");break;case"clear_and_type":await gt(l().clear(),1e4,"Clear before type timeout"),await gt(l().pressSequentially(this.getActionFillValue(e)),1e4,"pressSequentially timeout");break;case"selectoption":await u(l().selectOption(this.getActionFillValue(e)),"SelectOption timeout");break;case"hover":await u(l().hover(),"Hover timeout");break;case"navigation":await u(this.getFrame().goto(e.fillValue),"Navigation timeout",{isNavigation:!0});break;case"keystroke":{let d=this.getPage();await u(d.keyboard.press(e.fillValue),"Keystroke timeout");break}case"upload_files":await this.performFileUploadAction(l(),e);break;case"wait":await Ce(this.options.waitActionDelay??1e3);break;case"custom_code":await Eu(this.getPage(),this.getFrame(),async d=>{let f=`async (page) => {${e.fillValue}}`;await(0,eval)(f)(d)});break;case"logout_and_login":await this.reauthenticate(e.userRole);break;case"canvas_click":await this.canvasClick(l(),e.canvas);break}}catch(s){throw this.logger.log(`Error performing action: ${e.eventCode}, will attempt a correction template`,s),await(r==null?void 0:r()),new Error("Failed perfom action: "+s.message)}this.logger.log(`Successfully performed action ${e.eventCode} with description "${e.thought}"`)}async getTextDetection(e){return new Cu(await this.pageInteractorAPI.getTextDetection(e))}async canvasClick(e,t){try{if(!await e.evaluate(s=>s.tagName.toLowerCase()==="canvas"))throw new Error("Click attempted on a non-canvas element");let a=(await this.getTextDetection(await e.screenshot())).getRectangleByTextAndSizeRanking(t.canvasText,t.rectSizeIndex);if(!a)throw new Error(`Canvas click target not found for ${t.canvasText}`);this.logger.log(`Canvas click target: ${a}`),await this.actionGuardReturn(e.click({position:a.center}),"Canvas click could not be performed")}catch(r){throw this.logger.logError("Canvas click:",r.message),new Error("Canvas click action failed")}}getActionFillValue(e,t=!0){let r=e.fillValue;if(!r){let i=e.selector.match(/(?<=value.*)('|").*/);i&&(r=i[0].slice(1,-1))}return typeof r!="string"&&(r="X"),t&&(e.fillValue=r),r}actionGuardReturn(e,t,{isNavigation:r=!1,timeout:i}={}){return gt(e,i??(r?this.options.navigationTimeout:this.options.actionTimeout),t)}makeLocator(e,t=[]){return qb(this.getFrame(),e,t)}makeLocatorFromLocator(locator){return eval("this.getFrame()."+locator)}getCurrentURL(){return this.getFrame().url()}async getSelectionDataForChecksumId(e,t){if(t!=null&&t.selector)return{...t,selector:t.selector,clickOffset:t.position};if(!e)return this.logger.log(`[getSelectionDataForChecksumId] checksumid not provided (${e})`),{...t,selector:e};let r=await this.evaluateWithChecksum(async i=>{let{selector:a,locator:s,clickOffset:l,parentFramesSelectors:u,invalid:d,rrwebId:f}=await window.checksum.testGenerator.getSelectorForChecksumId(i),h=await window.checksum.testGenerator.getElementForChecksumId(i),g=h instanceof HTMLOptionElement&&h.value?h.value:void 0;return{selector:a,locator:s,clickOffset:l,selectOptionValue:g,parentFramesSelectors:u,invalid:d,rrwebId:f}},e);if(YB&&r.invalid&&r.rrwebId){this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${e}. Trying to use time machine...`);try{let i=await this.getSelectionDataForRRwebIdAtReduceHTMLTime(r.rrwebId);r={...r,...i}}catch{this.logger.log(`[getSelectionDataForChecksumId] error using time machine to get selector for checksumid: ${e}`)}this.logger.log(`[getSelectionDataForChecksumId] got selector: ${r.selector} for checksumid: ${e} from time machine`)}return r!=null&&r.selector||this.logger.log(`[getSelectionDataForChecksumId] Could not get selector for checksumid: ${e}. If checksumid is correct, try to change app rules preMapReducedHTMLSelectors to true`),r}async getSelectionDataForRRwebIdAtReduceHTMLTime(e){if(!this.rrwebEventAtLastReducedHTML)return;let t=this.getTimeMachine();if(t)return t.executeTask(r=>r.evaluate(async({rrwebId:i})=>await window.checksum.testGenerator.getInspectedElementSelectionResultByRRwebId(i,{ignoredIframesSelectors:[".replayer-wrapper > iframe"],fromTimeMachine:!0}),{rrwebId:e}),this.rrwebEventAtLastReducedHTML.timestamp,{name:"getSelectionDataForRRwebIdAtReduceHTMLTime"})}async getESRAForSelector(e,t,r){let i=await this.evaluateWithChecksum(async({selector:a,parentFramesSelectors:s})=>window.checksum.testGenerator.getSelectionDataForSelector(a,s),{selector:e,parentFramesSelectors:t});return i!=null&&i.esraMetadata&&r&&(i.esraMetadata.staticMetadata=await r(i.esraMetadata,e)),i==null?void 0:i.esraMetadata}async getMoreItemsForTemplate(e){return await this.evaluateWithChecksum(async t=>window.checksum.testGenerator.getMoreItemsForTemplate(t,{}),e)??{items:"",hasMoreItems:!1}}async getCurrentReducedHTML({retriesLeft:e=3,retryWaitMS:t=2e3,initialChecksumId:r="0",extractESRAForInterpretationRequiredElements:i=!1,stopFlashingElementsDetection:a=!1,assignChecksumIdsToAllElements:s}={}){let l=new Date;this.logger.log("[getCurrentReducedHTML] Fetching reduced HTML...");try{let{reducedHTML:u,currentChecksumId:d,flashingHTML:f,elementsForNodeInterpretation:h,lastRRwebEvent:g}=await this.evaluateWithChecksum(async w=>window.checksum.testGenerator.reduceHTML({},w),{initialChecksumId:r,extractESRAForInterpretationRequiredElements:i,stopFlashingElementsDetection:a,assignChecksumIdsToAllElements:s}),x=new Date;return this.logger.log(`[getCurrentReducedHTML] Fetched reduced HTML in ${x.getTime()-l.getTime()}ms`),this.rrwebEventAtLastReducedHTML=g,{reducedHTML:u,flashingHTML:f,elementsForNodeInterpretation:h,currentChecksumId:d}}catch(u){if(e>0)return this.logger.logError(`[getCurrentReducedHTML] Error: ${u.message}`),this.logger.logError(`Failed do obtain reduced HTML, trying again in ${t/1e3} seconds, ${e-1} to go.`),await Ce(t),this.getCurrentReducedHTML({retriesLeft:e-1,retryWaitMS:t});throw u}}getActionEventCode(e){return qm[e]}};n(_TestGenerationPageInteractor,"TestGenerationPageInteractor");var Ls=_TestGenerationPageInteractor;var jm=class jm{constructor(t){this.options=t;this.health=n(async()=>await fetch(`${this.options.apiURL}/client-api/runtime/api/health`,{headers:{ChecksumAppCode:this.options.apiKey}}).catch(t=>(console.log(t),null)),"health");this.getCanvasDetection=n(async t=>{try{let r=t.toString("base64");return await(await fetch(`${this.options.apiURL}/client-api/runtime/vision/text-detection`,{body:JSON.stringify({imageBuffer:r}),method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.options.apiKey}})).json()}catch(r){return console.log(r),null}},"getCanvasDetection")}};n(jm,"ChecksumClient");var Os=jm;var Um=class Um{constructor(){this.config={}}};n(Um,"PageInteractorAPI");var Tu=Um;var zm=class zm extends Tu{constructor(r){super();this.config=r;this.getTextDetection=n(async r=>{let i=await this.api.getCanvasDetection(r);if(!i)throw new Error("No data returned from canvas detection");return i},"getTextDetection");this.config=r,this.api=new Os({apiKey:r.apiKey,apiURL:r.apiURL})}};n(zm,"RuntimePageInteractorAPI");var Ds=zm;var c_=require("path");var Wm=class Wm{constructor(t){this.options=t;this.navigatingFrames={};this.trackedFramesGuid=[];this.frameNavigationPromises={};this.onFrameNavigated=n(async t=>{let r=ft(t);if(this.trackedFramesGuid.includes(r))return this.frameNavigationPromises[r]=new Promise(async i=>{await this.loadScript(t),i()}),this.frameNavigationPromises[r]},"onFrameNavigated");this.loadScript=n(async(t,{retriesLeft:r=3,retryWaitMS:i=2e3,useWrapper:a=!0}={})=>{var d,f;if(a&&this.scriptLoadWrapper)return this.scriptLoadWrapper(()=>this.loadScript(t,{retriesLeft:r,retryWaitMS:i,useWrapper:!1}),t);if(!this.addScriptTagOptions){console.warn("[InjectedScriptManager] addScriptTagOptions not set, skipping loadScript");return}if(this.isFrameClosed(t))return;let s=!1;try{s=this.scriptLoadCheck?await((d=this.scriptLoadCheck)==null?void 0:d.call(this,t)):!1}catch{}if(s||this.isFrameClosed(t))return;try{await t.addScriptTag(this.addScriptTagOptions)}catch(h){if(r>0)return console.warn(`[InjectedScriptManager] Failed to add script to frame ${ft(t)}, trying again in ${i/1e3} seconds, ${r-1} retries left.`,h.message),await Ce(i),this.loadScript(t,{retriesLeft:r-1,retryWaitMS:i,useWrapper:a});throw h}let l=ft(t),u=Date.now().toString(36)+Math.random().toString(36).substr(2);if(this.navigatingFrames[l]=u,this.options.scriptInitWait&&(console.log(`Waiting ${this.options.scriptInitWait}[ms] before onScriptLoad...`),await Ce(this.options.scriptInitWait),console.log("Done waiting before onScriptLoad")),!this.isFrameClosed(t)){if(this.navigatingFrames[l]&&this.navigatingFrames[l]!==u)return console.log("Page navigated again, waiting on new promise..."),this.frameNavigationPromises[l];try{await((f=this.scriptLoadCallback)==null?void 0:f.call(this,t))}catch(h){console.error("[WebDriver] onScriptLoad error",h)}}},"loadScript");this.addScriptTagOptions=this.makeFrameInjectedScriptOptions()}setScriptLoadCallback(t){return this.scriptLoadCallback=t,this}setScriptLoadCheck(t){return this.scriptLoadCheck=t,this}setScriptLoadWrapper(t){return this.scriptLoadWrapper=t,this}async addTrackedFrame(t,r=!0){let i="mainFrame"in t?t.mainFrame():t,a=ft(i);if(this.trackedFramesGuid.includes(a)||this.trackedFramesGuid.push(a),r)return this.onFrameNavigated(i)}getNavigationPromise(t){if(!t){console.warn("[InjectedScriptManager] getNavigationPromise called with undefined argument");return}let r=typeof t=="string"?t:"mainFrame"in t?ft(t.mainFrame()):ft(t);return this.frameNavigationPromises[r]}makeFrameInjectedScriptOptions(){switch(this.options.scriptSource){case"file":return this.options.scriptFile?{path:this.options.isScriptFileAbsolute?this.options.scriptFile:(0,c_.join)(process.cwd(),this.options.scriptFile)}:void 0;case"url":return this.options.scriptURL?{url:this.options.scriptURL}:void 0;default:return}}isFrameClosed(t){return t.isDetached()||t.page().isClosed()}};n(Wm,"InjectedScriptManager");var Bs=Wm;var Ln=At(require("path")),m_=require("fs");d_().config({path:Ln.resolve(Ln.join(__dirname,".."),".env")});var Vm=process.env.DEV_MODE==="true";function g_(){let e=__dirname;for(;!(0,m_.existsSync)(Ln.join(e,"package.json"));)e=Ln.join(e,"..");return e}n(g_,"findRoot");var h_=Ln.join(g_(),"vtg-build","index.html"),Je={isDevMode:Vm,checksumScript:{source:Vm?"url":"file",url:process.env.SCRIPT_URL,path:g_()+"/checksumlib.js"},vtg:{localBuildPath:h_,appURL:Vm?process.env.VTG_APP_URL:`file://${h_}`,useFakeStory:process.env.USE_FAKE_STORY==="true",taskTimeMachine:{showTaskTimeMachine:process.env.SHOW_TASK_TIME_MACHINE==="true"},aiAssertions:{disabled:process.env.AI_ASSERTIONS_DISABLED==="true",allowRefactoring:process.env.ALLOW_AI_ASSERTIONS_REFACTORING==="true"}},testRun:{timeMachine:{active:!0,headless:!0}}};var Zm=class Zm{constructor(){this.frames={};this.pages=[];this.channels={}}register(t,r){if(this.frames[t])return;this.frames[t]=r;let i=r.page();this.pages.includes(i)||(this.pages.push(i),i.exposeFunction("checksumSendMessage",async(a,s)=>{let l=this.frames[a];if(!l)throw new Error(`Frame ${a} not found`);try{await l.evaluate(({message:u})=>{window.postMessage(u,"*")},{message:s})}catch{}}),i.exposeFunction("checksumSendBroadcastMessage",async(a,s)=>{(this.channels[a]??[]).forEach(async u=>{if(!(u.originFrameGuid&&u.originFrameGuid!==ft(r)))try{u.handler?await u.handler(s):await r.evaluate(({message:d})=>{window.postMessage(d,"*")},{message:s})}catch{}})}),i.exposeFunction("checksumBringPageToFront",async a=>{let s=this.frames[a];s&&await s.page().bringToFront()}))}subscribeToChannel(t,r,{originFrame:i,handler:a}={}){var s;(s=this.channels)[t]??(s[t]=[]),this.channels[t].push({frame:r,originFrameGuid:i?ft(i):void 0,handler:a})}unsubscribeFromChannel(t,r){var i;(i=this.channels)[t]??(i[t]=[]),this.channels[t]=this.channels[t].filter(a=>a.frame!==r)}};n(Zm,"FramesMsgBroker");var Ns=Zm;var v_=require("@playwright/test");var Km=class Km{constructor(t,r,i={headless:!0,logPerformance:!1,timestampBatchingEnabled:!1,sortByTimestamp:!1}){this.frameMsgBroker=t;this.injectedScriptManager=r;this.options=i;this.taskQueue=[];this.isRunning=!1;this.currentTimestamp=0;this.currentBeforeTimestamp=!1;this.timeMachineTaskIndex=0;this.rrwebEventHandler=n(async t=>{let r=JSON.stringify(t);await this.timeMachineFrame.evaluate(function(i){let a=JSON.parse(i);return window.checksum.timeMachine.handleEvents(a)},r),t=null},"rrwebEventHandler")}getPage(){return this.timeMachineFrame.page()}getFrame(){return this.timeMachineFrame}async prepare(t,r){this.recordingFrame=t,this.frameMsgBroker.register("live",t),r?this.timeMachineFrame=r:this.timeMachineFrame=await this.prepareBrowserContextAndFrame(),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(t){this.timeMachineBrowserContext=t}async executeTask(t,r=void 0,{name:i,beforeTimestamp:a=!1}={}){return new Promise((s,l)=>{let u=this.timeMachineTaskIndex++,d=n(async({shouldGoBack:f,shouldBatch:h}={shouldGoBack:!0,shouldBatch:this.options.timestampBatchingEnabled})=>{this.timeMachineFrame.isDetached()&&l(),f&&await this.goBack(r,a);let x=[n(async()=>{try{let w=await t(this.timeMachineFrame);s(w)}catch(w){l(w)}},"safeRunTask")()];this.taskQueue.length>0&&h&&(x.push(...this.taskQueue.filter(w=>w.timestamp===r).map(({task:w})=>w({shouldGoBack:!1,shouldBatch:!1}))),this.taskQueue=this.taskQueue.filter(w=>w.timestamp!==r),x.length&&console.log(`Batching to task "${i}, index: ${u} ${x.length-1} more tasks`)),await Promise.all(x)},"taskWrapper");this.taskQueue.push({name:i,task:d,timestamp:a?r-1:r,queuedAt:Date.now(),index:u}),this.runTasks()})}goBack(t,r=!1){return this.currentBeforeTimestamp===r&&this.currentTimestamp===t?Promise.resolve():(this.currentTimestamp=t,this.currentBeforeTimestamp=r,this.timeMachineFrame.evaluate(({timestamp:i,beforeTimestamp:a})=>i===void 0?window.checksum.timeMachine.goLive():window.checksum.timeMachine.goBack(i,{beforeTimestamp:a}),{timestamp:t,beforeTimestamp:r}))}goLive(){return this.timeMachineFrame.evaluate(()=>window.checksum.timeMachine.goLive())}popTask(){return this.options.sortByTimestamp&&(this.taskQueue=this.taskQueue.sort((t,r)=>t.timestamp-r.timestamp)),this.taskQueue.shift()}async runTasks(){if(this.isRunning)return;this.isRunning=!0;let t=this.popTask(),r=Date.now();try{let i=Date.now()-t.queuedAt;await t.task();let a=Date.now()-r;this.options.logPerformance&&console.log(`running task "${t.name}, index: ${t.index} was pending for`,i,"ms and took",a)}catch(i){console.error("Task execution error:",i)}finally{this.isRunning=!1,this.taskQueue.length>0&&this.runTasks()}}async makeBrowserContext(){let t=await v_.chromium.launch({devtools:!1,headless:this.options.headless});return this.timeMachineBrowserContext=await t.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 t="rrweb";this.frameMsgBroker.subscribeToChannel(t,this.timeMachineFrame,{originFrame:this.recordingFrame,handler:this.rrwebEventHandler}),this.timeMachineFrame.page().on("close",()=>this.frameMsgBroker.unsubscribeFromChannel(t,this.timeMachineFrame))}async toggleTimeMachineHandleEvents(t){try{await this.timeMachineFrame.evaluate(r=>window.checksum.timeMachine.setShouldHandleEvents(r),t)}catch{}}};n(Km,"ChecksumTimeMachine");var On=Km;var hN=require("@playwright/test");var ote=1e3*30;var x_=require("fs");var y_=!1;function Jm(e){y_=e}n(Jm,"setLogToConsole");function Ve(...e){y_&&console.log(...e)}n(Ve,"log");function Ym(e,{role:t,environment:r}={},i=!1){var u,d;let a;r&&(a=(u=e.environments)==null?void 0:u.find(({name:f})=>r===f)),a||(a=(d=e.environments)==null?void 0:d.find(({default:f})=>f)),a||(a={baseURL:e.baseURL,default:!0,name:void 0});let s=(a==null?void 0:a.users)??e.users,l;if(s&&(t&&(l=s.find(f=>f.role===t)),l||(l=s.find(f=>f.default))),l||(l={role:void 0,username:e.username,password:e.password,default:!0}),r&&a.name!==r){if(i)throw new Error(`Could not find environment with name "${r}" in config file`);console.warn(`Could not find environment with name "${r}" in config file, trying to use default environment`)}if(t&&l.role!==t){if(i)throw new Error(`Could not find user with role "${t}" for environment "${r}" in config file`);console.warn(`Could not find user with role "${t}" for environment "${r}" in config file, trying to login with environment's default user`)}return{environment:a,user:l}}n(Ym,"resolveEnvironment");function vN(e){let t=`${e??Gd()}/login.ts`;if(!(0,x_.existsSync)(t))throw console.warn(`Could not locate the login.ts file. Please make sure your login file exists at ${t}`),new Error("Could not find login.ts file");try{return console.log("Loading login.ts file",t),require(t).default}catch(r){throw console.warn("Error loading login.ts file",r),r}}n(vN,"requireLogin");async function xN(e,t,{environment:r,user:i,credentials:a,config:s,dir:l}){try{let u=n(()=>t(e,{...s,...a},{environment:r,user:i}),"performLogin");"checksumAI"in e?await e.checksumAI(`Log in${i!=null&&i.role?` using ${i.role} role`:""}${r!=null&&r.name?` in ${r.name} environment`:""}`,u):await u()}catch(u){throw console.warn("The login method threw an exception, please check the login.ts file",u),u}}n(xN,"proceedWithLogin");function Xm(e){let{config:t,folder:r,throwIfAuthFailed:i}=e,a=vN(r);return async(s,{role:l,environment:u}={})=>{let d={username:t.username,password:t.password},{environment:f,user:h}=Ym(t,{role:l,environment:u},e.throwIfEnvInfoInvalid);if(i&&!h)throw new Error("Could not find user credentials matching the provided role and/or environment");h&&(d.username=h.username,d.password=h.password),await xN(s,a,{environment:f,user:h,credentials:d,config:t,dir:r})}}n(Xm,"makeUnboundLogin");var b_=require("fs"),w_=At(require("child_process")),qs=require("path");var dt=require("fs"),Iu=At(require("child_process")),er=require("path");var Qm=class Qm{constructor(t,r=!1){this.args=t;this.debugMode=r;this.checksumAppUrl="https://app.checksum.ai";this.childProcesses=[];this.printError=n(t=>{console.log("\x1B[31m%s\x1B[0m",t)},"printError");this.processConfigArg(),["SIGINT","SIGTERM"].forEach(i=>{process.on(i,()=>{this.cleanup(),process.exit()})}),this.checksumRuntimeVersion=this.getChecksumRuntimeVersion()}getChecksumRuntimeVersion(){if(this.checksumRuntimeVersion)return this.checksumRuntimeVersion;try{return require("./package.json").version}catch{return"unknown"}}async execCmd(t,r={}){let i={...process.env,...r},a=await Iu.spawn(t,{env:i,shell:!0,stdio:"inherit"});return this.childProcesses.push(a),new Promise((l,u)=>{a.on("exit",d=>{d===0?l(!0):u(new Error(`Checksum failed execution with code: ${d} `)),this.childProcesses=this.childProcesses.filter(f=>f!==a)})})}async getCmdOutput(t){return new Promise(function(r,i){Iu.exec(t,(a,s,l)=>{if(a){i(`Error executing command: ${a.message}`);return}r(s.trim())})})}validateAuthExists(){this.checksumRoot||this.findChecksumRoot();let t=(0,er.join)(this.checksumRoot,".auth");(0,dt.existsSync)(t)||(0,dt.writeFileSync)(t,"{}")}loadChecksumData(){this.locateChecksumLibs(),this.setChecksumConfig()}async patchPlaywright(t=!1){Ve("Patching playwright",t);let r=(0,er.join)(__dirname,"./scripts/patch.js");(0,dt.existsSync)(r)||(r=(0,er.join)(__dirname,"../../../scripts/src/patch_playwright.js"));let i=`node "${r}"${t?" off":""}`;try{await this.execCmd(i,{PROJECT_ROOT:this.projectRootDirectory,RUNTIME:"true"})}catch(a){console.log("Error patching playwright",a.message)}}getPlaywrightConfigFilePath(){return(0,er.join)(this.checksumRoot,"playwright.config.ts")}buildVolatileConfig(){if(!this.volatileChecksumConfig)return;let t=this.getVolatileConfigPath(),r=`
112
112
  import { RunMode, getChecksumConfig } from "@checksum-ai/runtime";
113
113
 
114
114
  export default getChecksumConfig(${JSON.stringify(this.config,null,2)});