@checksum-ai/runtime 2.0.13 → 2.0.14-beta

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
- CHECKSUM_RUNTIME_BUILD_TIME=2026-01-25T23:54:30.106Z
1
+ CHECKSUM_RUNTIME_BUILD_TIME=2026-01-28T00:43:55.252Z
package/index.js CHANGED
@@ -1928,8 +1928,8 @@ ${JSON.stringify(t,null,2)}
1928
1928
  ${e1t}`})).join(`
1929
1929
  ${e1t}`),c=new G7e(r.sourceFile),f=(k=this.userStoryService.getStory())==null?void 0:k.internalTestId,_=(R=this.userStoryService.getStory())==null?void 0:R.goal,v=(B=this.userStoryService.getStory())==null?void 0:B.id;c.transformSourceFile([new TWt(r.sourceFile),new NWt(r.sourceFile,{internalTestId:f,title:_}),new DWt(r.sourceFile,r.testMirrors.filter(U=>U.internalTestId===f||U.storyId===v).map(U=>U.testBody),sri(o))]);let C=this.testAssetsManager.getSavedTestFilePath(),{error:w}=await c.write(C,e1t);return{filePath:(0,iGe.relative)(process.cwd(),C),error:w}}get isLoadedFromTestFile(){return!!this.vtgTestFileRunConfig}async reloadTestFromFile(t){if(!this.vtgTestFileRunConfig)return;let r=await this.getReloadTestEnvironmentCode();await this.evaluationService.execute(r);let o=new n1t(this.testAssetsManager.getSavedTestFilePath()).loadActionsFromSingleTest({mergeCustomCodeSteps:this.settingsService.getSettings().mergeCustomCodeSteps});return t&&await this.mergeTimestampsToReloadedActions(o),this.actionsManager.reloadTestSteps(o),o}async mergeTimestampsToReloadedActions(t){let r=this.actionsManager.actions,a=await this.apiService.post("llm/query",{systemMessage:fri(),userMessage:dri(r,t)});try{let o=await a.text(),c=JSON.parse(o),f=0;t.forEach((_,v)=>{var w,T;let C=c.map[v];if(C){let k=r.find(({id:R})=>R===C.id);if(k){_.timestamp=k.timestamp,f=k.timestamp;let R=f;(w=_.assertions)==null||w.forEach((B,U)=>{var ne;let W=C==null?void 0:C.assertions[U],X=(ne=k.assertions)==null?void 0:ne.find(({id:ce})=>ce===W);X?(B.timestamp=X.timestamp,R=X.timestamp):B.timestamp=R+1});return}}_.timestamp=f+1,(T=_.assertions)==null||T.forEach((k,R)=>{k.timestamp=f+R+1})})}catch(o){return tf.error("Failed to merge actions",o),null}}async getReloadTestImportCodeOfNewPackages(t,r,a){let o=new G7e(r);o.transformSourceFile([new u1t(t,a,{filterOutChecksumImports:!0,filterOutLocalModules:!0,filterOutTypes:!0,filterSideEffectImports:!0,filterOutNotImportOrRequireStatements:!0}),new rNe(t),new c1t,new o1t]);let c=await this.getDeclaredVariableNames(o.sourceFile);return o.transformSourceFile([new i1t(r,c,{filterOutDefinedVariableNames:!0})]),(await o.getFormattedTestFileCode()).code}async getDeclaredVariableNames(t){return new PWt(this.evaluationService).extractDeclaredVariableNames(t)}async getReloadTestEnvironmentCode(){let t=this.testAssetsManager.getSavedTestFilePath(),r=H7e(t),a=r1t(),o=await this.getReloadCodeWithoutPackages(t,r,a);return[await this.getReloadTestImportCodeOfNewPackages(t,r,a),o].join(`
1930
1930
  `)}async getReloadCodeWithoutPackages(t,r,a){let o=new G7e(r);o.transformSourceFile([new FWt({shouldRemoveTestExpression:!0,shouldRemoveTestCalls:!0}),new kWt,new u1t(t,a,{filterOutNodeModules:!0,filterOutTypes:!0,filterSideEffectImports:!0,filterOutChecksumImports:!0}),new rNe(t),new nGe(t,a,{newRequireIdentifier:"checksumHotRequire",extraImportArguments:[yri.default.factory.createIdentifier("__filename")]}),new c1t,new o1t]);let c=await this.getDeclaredVariableNames(o.sourceFile);return o.transformSourceFile([new i1t(r,c)]),(await o.getFormattedTestFileCode()).code}getLocalSavedJSONFilePath(t,r){var c;r??(r=r||((c=this.userStoryService.getStory())==null?void 0:c.id));let a=this.testAssetsManager.getLocalAutoSaveFileName(r);return`${t==="auto-save"?this.testAssetsManager.getLocalAutoSavePath():this.testAssetsManager.getLocalSavePath()}/${a}`}readLocalSavedDataFromJSONFile(t){let r=this.readJsonFile(t);return r?{...r,executedActions:r.executedActions.map(a=>({...a,timestamp:void 0}))}:null}readJsonFile(t){try{let r=(0,X7e.readFileSync)(t,"utf-8");return JSON.parse(r)}catch(r){return tf.error(`Error reading or parsing JSON file: ${r}`),null}}makeDraftData(){let t=this.userStoryService.getStory(),r=this.userStoryService.getTestGenerationData(),a=this.userStoryService.getEnvInfo(),o={};return t!=null&&t.version&&(o.version=t.version),{actions:this.actionsManager.actions,internalTestId:t.internalTestId,environmentUserId:a.user.username,description:t.goal,metadata:Object.keys(o).length>0?o:void 0}}async generateTestFileString(t){try{let r=this.makeDraftData(),a=t?`${t}.draft.spec.ts`:`test-${r.internalTestId}.draft.spec.ts`,o=await this.apiService.post("test-generation/generate-test-file-string",r);if(!o.ok)throw new Error(`test generation request failed: ${o.statusText}`);let c=await o.text();wGn(c,a,this.testAssetsManager.getLocalSavePath())}catch(r){throw tf.error("Failed to generate test file string",r),new Error("Failed to generate test file string")}}localSave(){let t=JSON.stringify(this.vtgTestJSON,null,2),r=this.testAssetsManager.getAssetsFolderPath(),a=this.testAssetsManager.getLocalAutoSaveFileName(this.userStoryService.getStory().id);(0,X7e.writeFileSync)(`${r}/${a}`,t),(0,X7e.writeFileSync)(`${this.testAssetsManager.getLocalAutoSavePath()}/${a}`,t)}get vtgTestJSON(){var t;return{executedActions:this.actionsManager.actions,testGenerationData:this.userStoryService.getTestGenerationData(),settings:{baseURL:(t=this.config.environments.find(r=>r.default))==null?void 0:t.baseURL,assetsFolderPath:this.testAssetsManager.getAssetsFolderPath(),didLogin:this.actionsService.hasLoggedIn(),traceFilePath:this.testAssetsManager.getTraceFilePath(),harFilePath:this.testAssetsManager.getHarFilePath()},story:this.userStoryService.getStory()}}async extendedJSONBackup(){let t=await this.saveExtendedJson(),r=(0,iGe.dirname)(this.testAssetsManager.getSavedTestFilePath()),a=(0,iGe.join)(r,"test.extended.json");return(0,X7e.writeFileSync)(a,JSON.stringify(t,null,2)),{executedActions:t}}async localBackup(t){var r;if(t){this.testAssetsManager.setCurrentSaveAsLocation(t);let a=this.testAssetsManager.getLocalSaveAsPath(),o=this.testAssetsManager.getLocalAutoSavePath(),c=(r=this.userStoryService.getStory())==null?void 0:r.id,f=c?[this.testAssetsManager.getLocalAutoSaveFileName(c)]:[];SGn(o,a,f)}return await this.saveTestFile()}async saveExtendedJson(){let t=[...this.actionsManager.actions],r=[],a=e(async o=>{let{timestamp:c}=o,f="matcher"in o,_=o.timestamp&&(f||Ift(o.eventCode)),{fullHTML:v,outerHTML:C,parentHTML:w,rrwebSnapshot:T}=o.timestamp?await this.getHTMLsForTimestamp(c,o.locator):{fullHTML:"",outerHTML:"",parentHTML:void 0,rrwebSnapshot:""},k=f?Mie.generateSingleAssertionCode(o):Mie.generateSingleActionCode(o,{newLineSeparator:`
1931
- ${e1t}`,generateAssertionsCode:!1}),R=_?await this.takeElementSnapshot(o.locator,c):void 0;return{code:k,fullHTML:v,outerHTML:C,parentHTML:w,timestamp:c,image:R,rrwebSnapshot:T}},"extractDataForStep");for(let o=0;o<t.length;o++){tf.info(`processing action ${o} of ${t.length}`);let c=t[o],f=await a(c);r.push(f);for(let _ of c.assertions||[]){tf.info(`processing assertion of ${c.assertions.length} assertions`);try{let v=await a(_);r.push(v)}catch(v){tf.error("Failed to extract data for assertion",v)}}}return r}async takeElementSnapshot(t,r){try{return`data:image/jpeg;base64,${(await this.taskTimeMachine.executeTask(async o=>(await this.evaluationService.getLocator(`return ${lj(t)}`,o.frameLocator("iframe"))).screenshot({omitBackground:!0,type:"jpeg"}),r)).toString("base64")}`}catch(a){tf.error("Failed to take element snapshot",a);return}}async getHTMLsForTimestamp(t,r){try{return r?await this.taskTimeMachine.executeTask(async o=>{let c=await this.evaluationService.getLocator(`return ${lj(r)}`,o.frameLocator("iframe")),f=await c.elementHandle(),{fullHTML:_,outerHTML:v,rrwebSnapshot:C}=await o.page().evaluate(({element:T})=>{let k="",R="",B="",U=document.querySelector(".replayer-wrapper iframe").contentDocument;try{R=U.querySelector("html").outerHTML}catch{R=""}try{B=T.outerHTML}catch{B=""}try{k=JSON.stringify(window.checksum.timeMachine.rrwebSnapshot(U))}catch{k=""}return{fullHTML:R,outerHTML:B,rrwebSnapshot:k}},{element:f}),w=await mri(c);return{fullHTML:_,outerHTML:v,parentHTML:w,rrwebSnapshot:C}},t):{fullHTML:"",outerHTML:""}}catch(a){return tf.error("Failed to get HTML data for extended JSON backup",a),{}}}doesFolderExistInSaveDir(t){try{let r=`${this.testAssetsManager.getLocalSavePath()}/${t}`;return(0,X7e.statSync)(r).isDirectory()}catch(r){if(r.code==="ENOENT")return!1;throw r}}async saveToCloud(){var t;try{let{testGenerationId:r}=await this.userStoryService.createTestGeneration();await this.saveTestFile();let a=await this.settingsService.getIsGitReflectionEnabled();if(!a){let f=new iWt(this.apiService.getBaseURL(),this.config.apiKey,null,()=>`test-generation/${r}/get-upload-url`),_=e(w=>({complete:!1,error:!1,response:void 0,info:w}),"buildUploadAsset"),v=[],C=(t=this.userStoryService.getStory())==null?void 0:t.internalTestId;await f.uploadAsset(_({type:"test-fix-files",path:this.testAssetsManager.getSavedTestFilePath(),fileName:`test-${C}.fix.checksum.spec.ts`})),v.push(_({type:"trace",path:this.testAssetsManager.getTraceFilePath()})),v.push(_({type:"har",path:await gri(this.testAssetsManager.getHarFolderPath())})),this.actionsManager.actions.filter(w=>w.eventCode==="upload_files").forEach(w=>{var T;(T=w.files)==null||T.forEach(k=>{v.push(_({type:"test-files",path:k}))})}),await Promise.all(v)}let o=this.actionsManager.actions.map(f=>({...f,parentFramesSelectors:f.parentFramesSelectors?f.parentFramesSelectors.filter(_=>_!=="iframe"):void 0})),c={};if(a){let f=this.userStoryService.getStory();f!=null&&f.version&&(c.version=f.version)}await this.apiService.post(`test-generation/${r}/completed`,{actions:o,metadata:Object.keys(c).length>0?c:void 0})}catch(r){tf.error("Failed to upload test",r)}}};e(MGr,"VtgStorageService");var OWt=MGr;BVr();Lne();var jGr=class jGr{constructor(){this._executedActions=[];this.onActionExecuted=this.pushExecutedActionOrAddAfterParent.bind(this)}get actions(){return this._executedActions}set executedActions(t){var r;this._executedActions=t,(r=this.storageService)==null||r.localSave()}addAction(t){var r;this._executedActions.push(t),(r=this.storageService)==null||r.localSave()}setActions(t){this._executedActions=t}updateAssertionById(t,r){let a=r;return this.executedActions=this._executedActions.map(o=>{var c;if(o.id===t){let f=!!((c=o.assertions)!=null&&c.find(({id:v})=>v===r.id)),_={...o};return f?_.assertions=o.assertions.map(v=>{if(v.id===r.id){let C={...v,...r};return a=C,C}return v}):_.assertions=[...o.assertions??[],r],{..._,assertions:_.assertions.sort((v,C)=>v.timestamp!==C.timestamp?v.timestamp-C.timestamp:v.createdAt-C.createdAt)}}return o}),a}setStorageService(t){this.storageService=t}createAction(t){var v,C,w;let{id:r,data:a,options:o,type:c}=t,f={id:r,...a},_=[...this._executedActions];switch(o==null?void 0:o.type){case"insertAfter":{let T=this.findActionOrAssertionById(o.afterStepId),k=_.findIndex(R=>R.id===T.action.id);if(T.assertion||(C=(v=T.action)==null?void 0:v.assertions)!=null&&C.length){let R=T.assertion??T.action.assertions[0],{before:B,after:U}=$Pa(((w=_[k])==null?void 0:w.assertions)??[],R.id,!!T.assertion);_[k].assertions=B,f.assertions=U.map(W=>({...W,actionId:f.id}))}k!==-1?_.splice(k+1,0,f):_.push(f);break}case"insertLast":_.push(f);break;case"replace":{let T=_.findIndex(k=>k.id===o.stepId);T!==-1&&_.splice(T,1,f);break}case"replaceLast":_.length>0&&(_[_.length-1]=f);break}return this.executedActions=_,f}pushExecutedActionOrAddAfterParent(t,r={}){if(r.previousActionId){let a=this._executedActions.findIndex(({id:o})=>o===r.previousActionId);if(a!==-1){let o={...t,timestamp:this._executedActions[a].timestamp+1};this._executedActions=[...this._executedActions.slice(0,a+1),o,...this._executedActions.slice(a+1)]}}else this.executedActions=Array.isArray(t)?[...this._executedActions,...t]:[...this._executedActions,t]}addManualActionsToExecuted(t){this.executedActions=[...this._executedActions,t]}updateExecutedAction(t){let r=this._executedActions.findIndex(({id:a})=>a===t.id);if(r!==-1){let a={...this._executedActions[r],...t};return this.executedActions=[...this._executedActions.slice(0,r),a,...this._executedActions.slice(r+1)],a}throw new Error("Action was not found")}deleteStep(t,r,a={assertionsOnly:!1,withAssertions:!0}){r==="Action"?this.deleteAction(t,a):r==="Assertion"&&(this.executedActions=this._executedActions.map(o=>(o.assertions=(o.assertions??[]).filter(c=>c.id!==t),o)))}deleteAction(t,r={assertionsOnly:!1,withAssertions:!0}){var o;let a=this._executedActions.find(c=>c.id===t);if(!a)throw new Error(`Action with id "${t}" not found`);r.assertionsOnly?this.executedActions=this._executedActions.map(c=>c.id===t?{...c,assertions:[]}:c):!r.withAssertions&&((o=a==null?void 0:a.assertions)!=null&&o.length)?this.deleteActionAndMergeAssertions(t):this.executedActions=this._executedActions.filter(c=>c.id!==t)}deleteActionAndMergeAssertions(t){let r=this._executedActions.findIndex(_=>_.id===t);if(r===-1)throw new Error(`Action with id "${t}" not found`);if(r===0)throw new Error("Cannot remove the first action; no previous action to merge assertions into");let a=this._executedActions[r-1],o=this._executedActions[r];o.assertions||(o.assertions=[]);let c=o.assertions.map(_=>({..._,actionId:a.id})),f={...a,assertions:[...a.assertions??[],...c]};this.executedActions=[...this._executedActions.slice(0,r-1),f,...this._executedActions.slice(r+1)]}clearTestSteps(t=!0){if(t){let{navigation:r,login:a}=this.findLoginAndNavigationActions();this.executedActions=this._executedActions.reduce((o,c)=>([r==null?void 0:r.id,a==null?void 0:a.id].includes(c.id)&&o.push({...c,assertions:[]}),o),[])}else this.executedActions=[];return this._executedActions}reloadTestSteps(t){this.clearTestSteps(!1),this.executedActions=t}findLoginAndNavigationActions(){let t=this._executedActions.find(({eventCode:a})=>a==="navigation"),r=this._executedActions.find(({eventCode:a})=>a==="login");return{navigation:t,login:r}}addAssertionToAction(t,r){this.executedActions=this._executedActions.map(a=>{if(a.id!==t.actionId)return a;if(a.assertions||(a.assertions=[]),r){let o=a.assertions.findIndex(({id:c})=>r===c);a.assertions.splice(o+1,0,t)}else a.assertions=[t,...a.assertions??[]];return a})}findActionByAssertionId(t){return this._executedActions.find(({assertions:r=[]})=>r.find(a=>a.id===t))}replaceAssertion(t,r){let a=this.findActionByAssertionId(r);if(!a)throw new Error(`No action found containing assertion with id ${r}`);this.executedActions=this._executedActions.map(o=>o.id===a.id?{...o,assertions:(o.assertions??[]).map(c=>c.id===r?{...t,actionId:a.id}:c)}:o)}findActionOrAssertionById(t){let r={action:null,assertion:null};if(this._executedActions.forEach(a=>{a.id===t&&(r.action=a);let o=(a.assertions??[]).find(c=>c.id===t);o&&(r={action:a,assertion:o})}),!r.action&&!r.assertion)throw new L7e(t);return r}async buildStepDataWithCode(t,{loadingFromFile:r}={loadingFromFile:!1}){let a=VPa(t);return await Promise.all(a.map(async({step:o,type:c})=>{let f=await tNe(rGe([o],void 0,{generateAssertionsCode:!1},(_,v)=>{o=v}));return{type:c,step:{...o,loadedFromFile:r},code:f}}))}};e(jGr,"VtgActionsManager");var BWt=jGr,$Pa=e((i,t,r=!0)=>{let a=Number(r),o=i.findIndex(_=>_.id===t);if(o===-1)return{before:i,after:[]};let c=i.slice(0,o+a),f=i.slice(o+a);return{before:c,after:f}},"splitArrayAtId"),VPa=e(i=>i.reduce((t,r)=>{var c;let{assertions:a,...o}=r;if(t.push({step:o,type:"Action"}),(c=r.assertions)!=null&&c.length){let f=r.assertions.map(_=>({type:"Assertion",step:{..._,actionId:r.id}}));t.push(...f)}return t},[]),"transformActionsListToVTGStepsDataList");var sGt=sf(HHt()),Sci=sf(require("net")),Dci=sf(bYr()),Tci=sf(Cci());var xXr=class xXr extends Error{constructor(t){super(t),this.name="ValidationError"}};e(xXr,"ValidationError");var PGe=xXr,AXr=class AXr extends Error{constructor(t){super(t),this.name="NotFoundError"}};e(AXr,"NotFoundError");var FGe=AXr;qw();var Iv=e(i=>(t,r,a)=>{Promise.resolve(i(t,r,a)).catch(o=>{if(tf.error(`${t.method} ${t.path} error:`,o),o instanceof L7e)return r.status(200).json({error:o.message});if(o instanceof PGe)return r.status(400).send({error:o.message});if(o instanceof FGe)return r.status(404).send(o.message);a(o)})},"asyncErrorHandler");qw();var EXr=sf(HHt());var NGe=class NGe{constructor(){this.routesLogRules={};this.router=(0,EXr.Router)()}getRoutesLogRules(){return this.routesLogRules}getRouter(){return this.router}createPrefixedRouter(t){let r=(0,EXr.Router)(),a=t.startsWith(NGe.DEFAULT_API_PREFIX)?t:`${NGe.DEFAULT_API_PREFIX}${t.startsWith("/")?t:`/${t}`}`;return this.router.use(a,r),r}startAsyncProcess(t,r,a,o="unknown"){tf.info(`Starting async ${o} process: ${r} for step: ${a}`),t().catch(c=>{tf.error(`Async process ${r} failed:`,c)})}};e(NGe,"VTGController"),NGe.DEFAULT_API_PREFIX="/api";var p5=NGe;var CXr=class CXr extends p5{constructor(r,a,o,c){super();this.assertionsService=r;this.actionsManager=a;this.actionsService=o;this.aiTestGenerationService=c;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter(""),a=this.createPrefixedRouter("/steps");r.post("/createStep",Iv(async(o,c)=>{let f=o.body,_;f.type==="Assertion"&&(_=this.assertionsService.createAssertion(f)),f.type==="Action"&&(_=this.actionsManager.createAction(f));let v=await tNe(rGe([_],void 0,{generateAssertionsCode:!1},(C,w)=>{_=w}));return c.status(200).json({step:_,code:v})})),r.patch("/updateStep",Iv(async(o,c)=>{let f=o.body,_=f==null?void 0:f.options,v;f.type==="Assertion"&&(v=await this.assertionsService.updateAssertion({id:f.id,data:f.data})),f.type==="Action"&&(v=this.actionsManager.updateExecutedAction({...f.data,id:f.id}));let C;_!=null&&_.forceUpdateTimestamp||(f.data.thought===""&&(v.thought=void 0),C=await tNe(rGe([v],void 0,{generateAssertionsCode:!1},(w,T)=>{v=T}))),c.status(200).json({step:v,code:C})})),r.delete("/deleteStep",Iv(async(o,c)=>{let{id:f,options:_,type:v}=o.body;return this.actionsManager.deleteStep(f,v,_),c.status(200).send({message:"Success!"})})),r.post("/clear-test",Iv(async(o,c)=>{let f=this.actionsManager.clearTestSteps();return c.status(200).send(f)})),a.post("/execute",Iv(async(o,c)=>{let f=o.body;try{let _=null;return RQa(f)?_=await this.aiTestGenerationService.executeAction(f):LQa(f)&&(_=await this.actionsService.executeAction(f)),c.status(200).json(_)}catch(_){return c.status(400).send({error:_.message})}})),r.put("/steps",Iv(async(o,c)=>(this.actionsManager.pushExecutedActionOrAddAfterParent(o.body.action,o.body.options),c.send("success")))),r.post("/code-to-steps",Iv(async(o,c)=>{let _=uri(o.body.code).map(v=>v&&"isChecksumAiWithDirectExpression"in v?{...v,isChecksumAiWithDirectExpression:!1}:v);return c.status(200).send(_)})),r.post("/steps-to-code",Iv(async(o,c)=>{let f=rGe(o.body.steps,void 0,{generateAssertionsCode:!1});return c.status(200).send(f)}))}};e(CXr,"VtgStepsController");var GHt=CXr;function RQa(i){var t;return((t=i.options)==null?void 0:t.isAISuggestion)===!0}e(RQa,"isAIExecuteActionArgs");function LQa(i){var t;return((t=i.options)==null?void 0:t.isAISuggestion)===!1}e(LQa,"isManualExecuteActionArgs");qw();var wXr=class wXr extends p5{constructor(r){super();this.locatorsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/locators"),a=this.createPrefixedRouter("/ai/locators");r.post("/play",Iv(async(o,c)=>{let f=o.body;try{let _=await this.locatorsService.verifyLocatorOrSelector(f);return c.status(200).send(_)}catch(_){return c.status(400).send({error:_.message})}})),a.post("/generate",Iv(async(o,c)=>{let{step:f,target:_,processId:v}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.generateAILocators(f,_,v),v,_.id,"AI locators generation");let C={processId:v,stepId:_.id,success:!0};return c.status(200).json(C)}catch(C){return tf.error("Error generating AI locators:",C),c.status(500).send({processId:v,error:C.message})}})),a.post("/extract-css",Iv(async(o,c)=>{let{step:f,target:_,processId:v,llmLocators:C}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.extractCSS(f,_,v,C),v,_.id,"CSS extraction");let w={processId:v,stepId:_.id,success:!0};return c.status(200).json(w)}catch(w){return tf.error("Error extracting CSS locators:",w),c.status(500).send({processId:v,error:w.message})}})),a.post("/filter",Iv(async(o,c)=>{let{step:f,target:_,processId:v,candidates:C}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.filterLocators(f,_,v,C),v,_.id,"locators filtering");let w={processId:v,stepId:_.id,success:!0};return c.status(200).json(w)}catch(w){return tf.error("Error filtering locators:",w),c.status(500).send({processId:v,error:w.message})}})),a.delete("/process/:id",Iv(async(o,c)=>{let{id:f}=o.params;return await this.locatorsService.cancelProcess(f),tf.info("Cancelled process",f),c.status(200).send({success:!0})})),r.post("/identical",Iv(async(o,c)=>{let{locator:f,compareLocator:_,timestamp:v}=o.body;try{let C=await this.locatorsService.verifyAndCompareLocatorOnTimemachine(f,_,v);return c.status(200).send(C)}catch(C){return c.status(400).send({error:C.message})}})),r.post("/verify",Iv(async(o,c)=>{try{let f=await this.locatorsService.verifyLocatorOrSelector(o.body);return c.status(200).send(f)}catch(f){return c.status(400).send({error:f.message})}}))}};e(wXr,"VtgLocatorsController");var KHt=wXr;var SXr=class SXr extends p5{constructor(r){super();this.codeService=r;this.routesLogRules={"/monaco/editor/types":{skipRequestData:!0,skipResponseData:!0}};this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/monaco").post("/editor/types",Iv(async(a,o)=>{let{libs:c}=a.body;try{let f=this.codeService.getTypesForLibs(c??[]);return o.status(200).send({types:f})}catch(f){return o.status(400).send({error:f.message})}}))}};e(SXr,"MonacoController");var YHt=SXr;OI();var MQa=K_.enum(["openai","anthropic","google-vertexai","groq"]),wci=K_.strictObject({message:K_.string(),selection:K_.object({locator:K_.string()}).optional(),stepCode:K_.string().optional(),messageHistory:K_.array(K_.object({type:K_.enum(["user","assistant"]),content:K_.string(),timestamp:K_.string(),stepId:K_.string()})).optional(),model:K_.object({id:K_.string(),name:K_.string(),type:MQa,model:K_.string(),thinking:K_.boolean().optional()}).optional(),includeImage:K_.boolean().optional(),includeHtml:K_.boolean().optional(),includeCode:K_.boolean().optional(),timestamp:K_.number(),error:K_.string().optional()});var DXr=class DXr extends p5{constructor(r){super();this.aiChatService=r;this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/ai-chat").post("/message",Iv(async(a,o)=>{let c=wci.safeParse(a.body);if(!c.success){o.status(400).json({error:"Invalid request body",details:c.error.format()});return}try{let f=await this.aiChatService.processMessage(c.data);o.json(f)}catch(f){o.status(500).json({error:"Failed to process message",message:f instanceof Error?f.message:"Unknown error"})}}))}};e(DXr,"AIChatController");var XHt=DXr;var kci=sf(require("path"));vT();qw();var TXr=class TXr extends p5{constructor(r,a,o){super();this.storageService=r;this.actionsManager=a;this.actionsService=o;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/test"),a=this.createPrefixedRouter("");r.post("/generate-test-file-string",Iv(async(o,c)=>{try{return await this.storageService.generateTestFileString(o.body.fileName),c.send("success")}catch(f){return c.status(400).send({error:f.message})}})),r.post("/upload",Iv(async(o,c)=>(await this.storageService.saveToCloud(),c.send("success")))),r.post("/local-save",Iv(async(o,c)=>{await this.storageService.localSave(),c.send("success")})),a.post("/reload-test-from-file",Iv(async(o,c)=>{if(!this.storageService.isLoadedFromTestFile)throw new FGe("No test file found");let f=await this.storageService.reloadTestFromFile(o.body.useLLM),_=await this.actionsManager.buildStepDataWithCode(f,{loadingFromFile:!0});return c.status(200).send(_)})),r.post("/verify-save-location",Iv(async(o,c)=>{try{let f=this.storageService.doesFolderExistInSaveDir(o.body.location);c.send({exists:f})}catch(f){c.status(400).send({error:f})}})),r.post("/backup",Iv(async(o,c)=>{let{backupFolderName:f}=o.body;if(!DGn(f))throw tf.error("Invalid folder name",{backupFolderName:f}),new PGe("Invalid folder name");let _=await this.storageService.localBackup(f);c.send(_)})),r.post("/extended-json-backup",Iv(async(o,c)=>{let f=this.storageService.extendedJSONBackup();c.send(f)})),a.post("/upload-files",Iv(async(o,c)=>{let f=await this.actionsService.uploadFiles(o.body.files);return c.status(200).json(f)}))}};e(TXr,"VtgStorageController");var ZHt=TXr;var kXr=class kXr extends p5{constructor(r){super();this.aiTestGenerationService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/ai");r.post("/init",Iv(async(a,o)=>{await this.aiTestGenerationService.init(),o.send("success")})),r.post("/iterate",Iv(async(a,o)=>{let c=await this.aiTestGenerationService.iterate(a.body);return c?o.status(200).json(c):o.status(400).send("no action generated")})),r.post("/stop",Iv(async(a,o)=>{this.aiTestGenerationService.stop(),o.send("success")}))}};e(kXr,"VtgAITestGenerationController");var eGt=kXr;var IXr=class IXr extends p5{constructor(r){super();this.thoughtsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/thoughts");r.post("/actions/generate",Iv(async(a,o)=>{let c=a.body,{processId:f,action:{id:_}}=c;try{this.startAsyncProcess(()=>this.thoughtsService.generateActionThoughts(c),f,_,"action thoughts generation");let v={processId:f,stepId:_,success:!0};o.status(200).send(v)}catch(v){return o.status(400).send({processId:f,error:v.message})}})),r.post("/assertions/generate",Iv(async(a,o)=>{let c=a.body,{processId:f,assertion:{id:_}}=c;try{this.startAsyncProcess(()=>this.thoughtsService.generateAssertionThought(c),f,_,"assertion thoughts generation");let v={processId:f,stepId:_,success:!0};o.status(200).send(v)}catch(v){return o.status(400).send({processId:f,error:v.message})}})),r.post("/stop-generate",Iv(async(a,o)=>{let c=a.body;this.thoughtsService.stopGeneratingThought(c.stepId);let f={stepId:c.stepId};return o.status(200).send(f)}))}};e(IXr,"VtgThoughtsController");var tGt=IXr;var PXr=class PXr extends p5{constructor(r,a){super();this.assertionsService=r;this.aiAssertionsService=a;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/assertions"),a=this.createPrefixedRouter("/assertion");r.post("/generate",Iv(async(o,c)=>{let f=o.body,{processId:_,id:v}=f;try{this.startAsyncProcess(()=>this.aiAssertionsService.generateAiAssertions(f),_,v,"AI assertion generation");let C={processId:_,stepId:v,success:!0};return c.status(200).json(C)}catch(C){return c.status(500).send({processId:_,error:C.message})}})),r.post("/stop-generate",Iv(async(o,c)=>{let{id:f}=o.body,_={stepId:f};return this.aiAssertionsService.stopGenerateAiAssertions(f),c.status(200).send(_)})),a.post("/verify/time-machine",Iv(async(o,c)=>{let f=await this.assertionsService.verifyOnTimeMachine(o.body);return c.status(200).send(f)})),a.post("/verify/live",Iv(async(o,c)=>{let f=o.body;try{let _=await this.assertionsService.verifyOnLive(f),v=_.success?200:404;return c.status(v).send(_)}catch(_){return c.status(404).send({success:!1,message:String(_)})}})),a.post("/save",Iv(async(o,c)=>{let f=await this.assertionsService.updateAssertion(o.body);c.status(200).json(f)}))}};e(PXr,"VtgAssertionsController");var rGt=PXr;var FXr=class FXr extends p5{constructor(r){super();this.settingsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/settings");r.get("/",Iv(async(a,o)=>{let c=this.settingsService.getSettings();return o.status(200).send(c)})),r.post("/",Iv(async(a,o)=>(this.settingsService.updateSettings(a.body),o.status(200).send({message:"Success!"}))))}};e(FXr,"VtgSettingsController");var nGt=FXr;qw();var Ici=sf(HHt());var NXr=class NXr extends p5{constructor(r){super();this.evaluatorService=r;this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/evaluator").post("/execute",Iv(async(a,o)=>{try{let c=await this.evaluatorService.execute(a.body.code);return o.status(200).json(c)}catch(c){return o.status(500).send({message:"Error during code evaluation",error:c.message})}}))}};e(NXr,"VtgEvaluatorController");var iGt=NXr;vT();qw();var OXr=class OXr{constructor(){this.reqIndex=0;this.reqInProcess={};this.routesLogRules={};this.intervalTimer=null}setRoutesLogRules(t){this.routesLogRules=t}cleanup(){this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null)}startListening(t,r,a){V0.vtg.logAPIServer.interval&&this.handleIntervalLog(t,r,a),!(V0.vtg.logAPIServer.httpTransactions&&this.handleTransactionLog(t,r,a))&&a()}logInterval(){V0.vtg.logAPIServer.interval&&!this.intervalTimer&&(this.intervalTimer=setInterval(()=>{let t=Object.values(this.reqInProcess);t.length&&(tf.info("HTTP REQUESTS IN PROCESS"),tf.info(t.map(r=>JSON.stringify(r,null,2)).join(`
1932
- `)))},5e3))}handleIntervalLog(t,r,a){let o=this.reqIndex++;this.reqInProcess[o]=this.buildLogInfo(t,r,0,"","INTERVAL"),r.on("finish",()=>{let c=Date.now()-this.reqInProcess[o].start;delete this.reqInProcess[o]})}handleTransactionLog(t,r,a){if(this.getRouteRules(t.originalUrl).skip)return a(),!0;let c=Date.now(),f=this.buildLogInfo(t,r,0,"","REQUEST"),_="";tf.info("REQUEST INFO",JSON.stringify(f,null,2));let v=r.write,C=r.end;return r.write=function(w,...T){return w&&(_+=w.toString()),v.call(this,w,...T)},r.end=function(w,...T){return w&&(_+=w.toString()),C.call(this,w,...T)},r.on("finish",()=>{if(V0.vtg.logAPIServer.httpTransactions){let w=Date.now()-c,T=this.buildLogInfo(t,r,w,_,"RESPONSE");tf.info("RESPONSE INFO",JSON.stringify(T,null,2))}}),!1}buildLogInfo(t,r,a,o,c="RESPONSE"){let f=this.getRouteRules(t.originalUrl),_={method:t.method,url:t.originalUrl,start:Date.now()};return c==="INTERVAL"||(c==="REQUEST"&&!f.skipRequestData&&t.body&&(_.data=t.body),c==="RESPONSE"&&(a&&(_.duration=`${a}ms`),_.statusCode=r.statusCode,_.size=r.getHeader("content-length")||"unknown",!f.skipResponseData&&o&&(_.data=o))),_}getRouteRules(t){if(this.routesLogRules[t])return this.routesLogRules[t];for(let[r,a]of Object.entries(this.routesLogRules))if(t.includes(r))return a||{};return{}}};e(OXr,"VTGExpressServerRoutesLoggerMiddleware");var aGt=OXr;var BXr=class BXr{constructor(t,r,a,o,c,f,_,v,C,w,T,k){this.actionsService=t;this.assertionsService=r;this.locatorsService=a;this.aiTestGenerationService=o;this.aiAssertionsService=c;this.aiThoughtsService=f;this.actionsManager=_;this.storageService=v;this.settingsService=C;this.monacoService=w;this.evaluatorService=T;this.aiChatService=k;this.errorHandler=e((t,r,a,o)=>{tf.error("Error catch in middleware:",t),a.status(500).send({error:t.message})},"errorHandler");this.routesLoggerMiddleware=new aGt}async getPort(){return this.acquirePortNumber()}async start(){return this.app=(0,sGt.default)(),this.app.use((0,Tci.default)()),this.app.use(Dci.default.json({limit:"50mb"})),this.app.use(sGt.default.raw({type:"multipart/form-data",limit:"50mb"})),this.app.use(sGt.default.static(kci.default.join(V0.runtimeRoot,"vtg-build"))),this.app.use(this.routesLoggerMiddleware.startListening.bind(this.routesLoggerMiddleware)),this.routesLoggerMiddleware.logInterval(),await this.acquirePortNumber(),this.app.use(this.initializeControllers()),this.app.use(this.errorHandler),new Promise(t=>{this.app.listen(this.port,()=>{tf.info(`Express server running on port ${this.port}`),t()}).on("close",()=>{this.shutdown()})})}shutdown(){this.routesLoggerMiddleware.cleanup(),tf.info("Express server shutdown complete")}async acquirePortNumber(){return this.port||(this.port=await new Promise((t,r)=>{let a=Sci.default.createServer();a.unref(),a.on("error",r),a.listen(0,()=>{let o=a.address().port;a.close(()=>{t(o)})})})),this.port}async evaluateServerPort(t){if(!t)throw new Error("Page not initialized");await t.evaluate(r=>{window.vtg.setServerPort(r)},this.port)}initializeControllers(){let t=new GHt(this.assertionsService,this.actionsManager,this.actionsService,this.aiTestGenerationService),r=new ZHt(this.storageService,this.actionsManager,this.actionsService),a=new eGt(this.aiTestGenerationService),o=new tGt(this.aiThoughtsService),c=new rGt(this.assertionsService,this.aiAssertionsService),f=new nGt(this.settingsService),_=new KHt(this.locatorsService),v=new YHt(this.monacoService),C=new XHt(this.aiChatService),w=new iGt(this.evaluatorService),T=[t,r,a,o,c,f,_,v,w,C],k=(0,Ici.Router)(),R={};return T.forEach(B=>{k.use(B.getRouter()),R={...R,...B.getRoutesLogRules()}}),this.routesLoggerMiddleware.setRoutesLogRules(R),k}};e(BXr,"VtgExpressServer");var oGt=BXr;var uGt=require("fs");var agt=class agt{constructor(t,r,a,o){this.projectRootDirectory=t;this.checksumRoot=r;this.internalFilesDir=a;this.vtgTestFileRunConfig=o;this.localSaveFolderPath=process.env.CHECKSUM_DRAFT_FOLDER_PATH??`${this.internalFilesDir}/drafts`}createTestAssetsFolders(){this.assetsFolderPath=`${this.internalFilesDir}/assets/${Date.now()}`,(0,uGt.mkdirSync)(this.assetsFolderPath,{recursive:!0}),(0,uGt.mkdirSync)(this.getHarFolderPath(),{recursive:!0})}createTestGenerationLocalAutoSaveFolder(){(0,uGt.mkdirSync)(this.getLocalAutoSavePath(),{recursive:!0})}getAssetsFolderPath(){return this.assetsFolderPath}getLocalAutoSavePath(){return`${this.localSaveFolderPath}/${agt.AUTO_SAVE_FOLDER_NAME}`}getLocalAutoSaveFileName(t){var r;return((r=this.vtgTestFileRunConfig)==null?void 0:r.mode)==="edit"?this.vtgTestFileRunConfig.sourceFilePath.split("/").pop().replace(".spec.ts",".json"):`${t}.json`}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 t=this.vtgTestFileRunConfig.sourceFilePath.split("/").pop();return`${this.localSaveFolderPath}/${this.currentSaveAsLocation}/${t}`}else return this.vtgTestFileRunConfig.sourceFilePath}getLocalSavePath(){return this.localSaveFolderPath}getHarFolderPath(){return this.assetsFolderPath+"/har"}getHarFilePath(){return`${this.getHarFolderPath()}/har.har`}getTraceFilePath(){return`${this.assetsFolderPath}/trace.zip`}setCurrentSaveAsLocation(t){t&&!(t!=null&&t.startsWith("auto-save"))&&(this.currentSaveAsLocation=t)}};e(agt,"VtgTestAssetsManager"),agt.AUTO_SAVE_FOLDER_NAME="auto-save";var cGt=agt;var jQa={useCDPSession:!0,trackLoadedResources:!0},RXr=class RXr extends vJt{constructor(r={},a={devtools:!1},o={},c,f){super({...jQa,...r},a,c,f);this.settings={frontendAppSpecificRules:void 0,initTestGenerator:!0,frontendTestGenerationConfig:void 0};this.isScriptLoaded=e(async(r,a=1e3)=>{try{return await r.waitForFunction(()=>!!window.checksum,void 0,{timeout:a}),!0}catch{return!1}},"isScriptLoaded");this.initInjectedScript=e(async r=>{try{return await r.waitForFunction(()=>{var a;return!!((a=window.checksum)!=null&&a.testGenerator)}),r.evaluate(async({appSpecificRules:a,config:o,initModules:c})=>{window.checksum.testGenerator.init(a,o,c)},{appSpecificRules:this.settings.frontendAppSpecificRules,config:this.getFrontendTestGenerationConfig(),initModules:this.getInjectedScriptInitModules(r)})}catch(a){console.log("initInjectedScript exception",a)}},"initInjectedScript");this.settings={...this.settings,...o},this.injectedScriptManager.setScriptLoadCheck(this.isScriptLoaded),this.settings.initTestGenerator&&this.injectedScriptManager.setScriptLoadCallback(this.initInjectedScript)}async prepare(r={}){let a=await super.prepare(r);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")}),a}setEvaluateWithChecksumTargetFrame(r){this.evaluateWithChecksumTargetFrame=r}getInjectedScriptInitModules(r){return{assertionGenerator:!0,sessionRecorder:!0,filesObserver:!1,assertionsObserver:!1,actionsObserver:!1,nativeDialogObserver:!1}}getFrontendTestGenerationConfig(){return this.settings.frontendTestGenerationConfig}async evaluateWithChecksum(r,a,o=this.evaluateWithChecksumTargetFrame){let c=this.injectedScriptManager.getNavigationPromise(o);c&&await c;try{return o.evaluate(r,a)}catch(f){throw console.error("evaluateWithChecksum error",f,r.toString()),f}}async getBestMatchingElementSimilarityScore(r){return this.evaluateWithChecksum(async a=>await window.checksum.testGenerator.getBestMatchingElementSimilarityScore(a),r)}async getInteractableElements(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getInteractableElements())}async getAllInteractableElementsForLastSelectQuery(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getAllInteractableElementsForLastSelectQuery())}async overlayInteractableElementsWithChecksumId(r){return this.evaluateWithChecksum(a=>window.checksum.testGenerator.overlayInteractableElementsWithChecksumId(a),r)}async takeElementSnapshot(r,a,o={},c={}){try{let{snapshot:f,elementLocator:_}=await super.takeElementSnapshot(r,a,o);if(!f||!o.takeBodyScreenshot)return f?{snapshot:f}:{};await this.highlightElementByLocator(_,o.mousePosition);let v=await this.takePageSnapshot(c);return await this.clearHighlights(),{snapshot:f,bodySnapshot:v}}catch(f){return console.error("[ChecksumWebDriver] takeElementSnapshot error",f),{}}}async highlightElementByLocator(r,a,o="20px solid rgba(255,0,0,1)",c=!1){return this.evaluateWithChecksum(async([f,_,v,C])=>{window.checksum.testGenerator.highlightElement(f,{highlightStyle:{outline:_},mousePosition:v,scroll:C})},[await r.elementHandle(),o,a,c])}async clearHighlights(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.clearHighlights())}};e(RXr,"ChecksumWebDriver");var lGt=RXr;var Pci=require("fs"),Fci=sf(require("path"));var LXr=require("fs");vT();qw();var MXr=class MXr{constructor(t,r,a=V0.vtg.localBuildPath){this.page=t;this.serverPort=r;this.filePath=a;this.filePath=a,tf.info("[VTG] FrontendLauncher initialized with:",{serverPort:r,filePath:a,appSource:V0.vtg.appSource,cwd:process.cwd()})}async start(){try{await this.modifyVTGBuildHtmlFile(),await this.startReactApp()}catch(t){throw tf.error("An error occurred:",t),t}}async startReactApp(){if(!this.page)throw new Error("Page not initialized");let t;switch(V0.vtg.appSource){case"served-app":t=V0.vtg.appURL;break;case"served-build-file":t=`http://localhost:${this.serverPort}/index.html`;break;case"build-file":t=V0.vtg.localUrl;break;default:throw new Error(`Invalid app source: ${V0.vtg.appSource}`)}await this.page.goto(t,{waitUntil:"networkidle",timeout:6e4})}async modifyVTGBuildHtmlFile(){if(V0.vtg.appSource==="build-file")try{let t=await LXr.promises.readFile(this.filePath,"utf8"),r=/(src|href)=(["'])(\/)static/g,a=t.replace(r,"$1=$2.$3static");await LXr.promises.writeFile(this.filePath,a,"utf8"),tf(`Successfully modified ${this.filePath}`)}catch(t){tf.error(`Error processing file ${this.filePath}:`,t)}}};e(MXr,"VtgFrontendLauncher");var pGt=MXr;Xqt();vT();QVr();qw();fMr();SRt();v7();var UQa=1e3,dGt=class dGt extends lGt{constructor(r={},a={devtools:!1},o={},c){var f;super(r,a,dGt.makeSettings(o),(f=c==null?void 0:c.getFramesMessageBroker)==null?void 0:f.call(c),V0.vtg.isSeparateProcess||c==null?void 0:c.context());this.liveAppPage=c;this.registeredTimeMachineFrames=[];this.onAppFrameCreated=e(async r=>{this.appFrame=r,await this.frameMsgBroker.register("live",this.appFrame,V0.vtg.writeRrwebEventsToFile),this.setEvaluateWithChecksumTargetFrame(this.appFrame)},"onAppFrameCreated");this.timeMachine=new cbe(this.frameMsgBroker,this.injectedScriptManager,{webProxy:r.webProxy}),this.liveTimeMachine=new cbe(this.frameMsgBroker,this.injectedScriptManager,{webProxy:r.webProxy}),this.appViewport=o.viewport,this.completeOriginHeaderOnLivePage=o.completeOriginHeaderOnLivePage}static makeSettings(r={}){return Azt({frontendTestGenerationConfig:{showFrontendLogs:V0.isDevMode}},r)}get appMainFrame(){return this.appFrame}get tmFrame(){return this.timeMachineFrame}getApplicationViewport(){return this.appViewport}getTimeMachine(){return this.timeMachine}registerTimeMachineFrame(r){this.registeredTimeMachineFrames.push(r)}async prepare(r={},a={}){let o=await super.prepare(r);await this.frameMsgBroker.register("vtg",this.page.mainFrame()),this.page.on("dialog",()=>{}),this.page.on("close",()=>{tf.error("Page closed")}),this.liveAppPage&&!V0.vtg.isSeparateProcess&&await(await this.page.context().newCDPSession(this.originalPage)).send("Emulation.setDeviceMetricsOverride",{width:0,height:0,deviceScaleFactor:0,mobile:!1}),await new pGt(this.page,a.serverPort).start();let c=e(async(_=2)=>{if(this.timeMachineFrame=this.page.frames().find(v=>v.name()==="time-machine-iframe"),this.liveFrame=this.page.frames().find(v=>v.name()==="live-iframe"),!this.timeMachineFrame||!this.liveFrame){if(_>0)return tf.info("Waiting for frames to be available"),await TA(UQa),c(_-1);{let v="Could not connect to VTG frontend, check that the app is available";throw tf.error(v),new Error(v)}}},"getFrames");await c();let f;return this.liveAppPage?(f=this.liveAppPage,this.completeOriginHeaderOnLivePage&&await this.applyRouteInterceptors(f,{completeOriginHeader:!0})):(f=await this.context.newPage(),await f.setViewportSize(this.appViewport)),await this.onAppFrameCreated(f.mainFrame()),await this.timeMachine.prepare(this.appFrame,this.timeMachineFrame),await this.liveTimeMachine.prepare(this.appFrame,this.liveFrame),await this.exposeFunctionsForVTG(),o}async exposeFunctionsForVTG(){try{if(await this.page.evaluate(()=>typeof window.checksumGetFilesFromLive=="function").catch(()=>!1)){tf.info("checksumGetFilesFromLive already exposed, skipping");return}await this.page.exposeFunction("checksumGetFilesFromLive",async a=>{let o=this.appFrame;if(!o){tf.info("no live frame detected");return}try{return o.evaluate(c=>window.checksum.testGenerator.filesObserver.getFilesByRrwebId(c),a)}catch(c){tf.error("Error getting frame window",c)}})}catch(r){tf.warning(`Failed to expose checksumGetFilesFromLive: ${r.message}`)}}async navigate(r){return this.appFrame.goto(r)}async getCurrentURL(){return this.appFrame.url()}async createPage(){let r=new wve(this.evaluateWithChecksum.bind(this),()=>this.appFrame,()=>this.timeMachine,{log:tf.info,logError:tf.error},{navigationTimeout:3e4,actionTimeout:5e3,waitActionDelay:1e3,testAssetsDir:__dirname}),a=await super.createPage();return cJe.makePage(a,r,this.injectedScriptManager,this.context)}getInjectedScriptInitModules(r){return this.registeredTimeMachineFrames.concat([this.timeMachineFrame,this.liveFrame]).includes(r)?{assertionGenerator:!1,sessionRecorder:!1,filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1,actionsObserver:!1}:r===this.appFrame?{...super.getInjectedScriptInitModules(r),filesObserver:!0,nativeDialogObserver:!0,assertionsObserver:!0,actionsObserver:!0}:super.getInjectedScriptInitModules(r)}async interceptPageRequests(){async function r(o){try{return await Pci.promises.readFile(o,"utf8")}catch(c){return tf.error(`Error reading file ${o}:`,c),null}}e(r,"readLocalFile");function a(o){switch(Fci.extname(o).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(a,"getContentType"),await this.page.route("**/*",async o=>{try{let c=o.request().url();if(console.log("intercepted!",c),c.startsWith("file://")){let f=c.replace("file://",""),_=await r(f);_!==null?await o.fulfill({status:200,contentType:a(f),body:_}):await o.abort()}else{let f=0,_=5;for(;f<_;){let v=await o.fetch(),C=v.status();if(C>299&&C<400){f++;let w=v.headers().location;if(!w){tf.warning("Redirect without Location header",{url:c}),await o.abort();return}console.log(`Redirect ${f} to: ${w}`),o.request().url=()=>new URL(w,c).toString()}else{let w={};w["Access-Control-Allow-Origin"]="*",w["Access-Control-Allow-Methods"]="GET, POST, PUT, DELETE, OPTIONS",w["Access-Control-Allow-Headers"]="Content-Type, Authorization",await o.fulfill({response:v,headers:{...v.headers(),...w,"content-security-policy":"","X-Frame-Options":"","x-frame-options":""}});return}}tf.warning(`Max redirects (${_}) exceeded`),await o.abort()}}catch(c){tf.warning("intercept error",c)}})}};e(dGt,"ChecksumVTGWebDriver");var fGt=dGt;var OGe=require("fs");vT();var Nci=".settings.json",jXr=class jXr{constructor(t,r,a){this.checksumRoot=t;this.apiService=r;this.internalFilesDir=a;this.settings={autoLogin:!0,autoRunSteps:!0,autoGenerateThoughts:!0,disableGenerateThoughts:!1,autoGenerateAssertions:!0,disableAutoGenerateAssertions:!1,disableAILocators:!1,optimizeLocators:!0,useOptimizedLocatorDefault:!0,useCodeBasedSteps:!0,displayUIInspector:!1,mergeCustomCodeSteps:!1,useVariableTransformation:!0};this.settingsFilePath=a?`${this.internalFilesDir}/${Nci}`:`${this.checksumRoot}/${Nci}`,this.readSettings()}getSettings(){return{...this.settings,autoGenerateAssertions:V0.vtg.aiAssertions.disabled?!1:this.settings.autoGenerateAssertions,disableAutoGenerateAssertions:V0.vtg.aiAssertions.disabled,disableAILocators:V0.vtg.aiLocators.disabled}}updateSettings(t){this.settings=Object.assign(this.settings,t),this.writeSettingsData()}readSettings(){if(!(0,OGe.existsSync)(this.settingsFilePath)){this.writeSettingsData();return}let t=(0,OGe.readFileSync)(this.settingsFilePath,"utf-8");this.settings=JSON.parse(t),this.settings.useCodeBasedSteps===void 0&&(this.settings.useCodeBasedSteps=!0)}writeSettingsData(){(0,OGe.writeFileSync)(this.settingsFilePath,JSON.stringify(this.settings,null,2))}async getIsGitReflectionEnabled(){return(await(await this.apiService.get("/git-integration/is-git-reflection-enabled")).json()).enabled??!1}};e(jXr,"VtgSettingsService");var sgt=jXr;Wkr();var F3e=require("fs");qw();var UXr=class UXr{constructor(t,r,a){this.timeMachine=t;this.actionsManager=r;this.userStoryService=a}async generatePromptData(t,r){let a=e(()=>{let{timestamps:C,...w}=this.cachedPromptData;return{...w,action:t}},"returnPromptDataFromCache"),o=t.id;if(this.canUseCachedPromptData(t))return a();let c=this.getActionTimestamps(o,r);if(!c)return;let f=await this.timeMachine.executeReducedHTMLTask(c.before),_=await this.timeMachine.executeReducedHTMLTask(c.after),v=this.userStoryService.getStory();return this.cachedPromptData={reducedHTML:_,previousReducedHTML:f,actionId:o,previousActions:this.getPreviousActions(o),action:t,title:v.goal,steps:v.instructions,timestamps:c},a()}canUseCachedPromptData(t){var r,a;return this.cachedPromptData&&this.cachedPromptData.actionId===t.id&&this.cachedPromptData.action.timestamp===t.timestamp&&((r=this.cachedPromptData.timestamps)==null?void 0:r.before)===t.timestamp&&((a=this.cachedPromptData.timestamps)==null?void 0:a.after)===t.timestamp}getPreviousActions(t){let r=this.actionsManager.actions,a=r.findIndex(o=>Number(o.id)===Number(t));return r.slice(0,a)}async generatePromptDataForThought(t,r){return this.generatePromptData(t,r)}getActionTimestamps(t,r){let a=this.actionsManager.actions,o=a.findIndex(_=>_.id===t);if(o===-1){tf.error(`[init] No action with id ${t} was found in executed actions`);return}let c=a[o],f=a[o+1];return{before:c.timestamp,after:(f==null?void 0:f.timestamp)??r}}};e(UXr,"ActionsAgent");var mGt=UXr;qw();vT();var qXr=class qXr extends R7e{constructor(r,a,o,c,f){super(r,a,o);this.actionsManager=r;this.apiService=a;this.userStoryService=o;this.webDriver=f;this.activeRemoteSessionIdByStepId=new Map;this.assertionsAgent=new QWe(c,r,a,this.remoteSessionId,{logPerformance:V0.vtg.aiAssertions.logPerformance}),this.actionsAgent=new mGt(c,r,this.userStoryService)}async init({retriesLeft:r=3,keepActionsWithoutDescription:a=!1,lastActionId:o=void 0}={}){await super.init({retriesLeft:r,keepActionsWithoutDescription:a,lastActionId:o}),this.activeRemoteSessionIdByStepId.set(o,this.remoteSessionId)}async generateActionThoughts({action:r,processId:a}){try{if(this.isRunning(r.id))throw tf.warning("Already generating a thought for this action"),new Error("Already generating a thought for this action");let o=await this.actionsAgent.generatePromptDataForThought(r),c=await this.callThoughtApi("actions",o,a);return this.evaluateThoughtResponse({processId:a,id:r.id,thought:c.thought})}catch(o){return tf.error("Error in AI thought generation",o),this.evaluateThoughtResponse({processId:a,id:r.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(r.id)}}async generateAssertionThought({assertion:r,parentActionId:a,processId:o}){let c=a||r.actionId;try{if(this.isRunning(r.id))throw tf.warning("Already generating a thought for this assertion"),new Error("Already generating a thought for this assertion");let f=await this.assertionsAgent.generateThoughtPromptData(c,r),_=await this.callThoughtApi("assertions",f,o);return this.evaluateThoughtResponse({processId:o,id:r.id,thought:_.thought})}catch(f){return tf.error("Error in AI thought generation",f),this.evaluateThoughtResponse({processId:o,id:r.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(r.id)}}stopGeneratingThought(r){this.activeRemoteSessionIdByStepId.delete(r)}async callThoughtApi(r,a,o){let c=Date.now();if(a)try{c=Date.now();let f=await this.apiService.post(`${r}/thoughts/generate`,{sessionId:this.remoteSessionId,data:a});if(!f.ok){tf.error(`Request for ${r} thought generation failed with status ${f.status}`);return}let _=await f.json();if(!(_!=null&&_.thought))throw tf("No thought generated for action, got response",f),new Error("No thought generated");let v=r==="actions"?a.action:a.assertion;return tf(`Thought generated (${o})`,{type:r,stepId:v.id,locator:v.locator,thought:_.thought}),_}catch(f){throw tf.error(`Error in AI thought generation (${o})`,f),f}}isRunning(r){return this.activeRemoteSessionIdByStepId.has(r)}async evaluateThoughtResponse({id:r,processId:a,thought:o,error:c=!1}){try{await this.webDriver.page.evaluate(({id:f,thought:_,error:v,processId:C})=>{window.vtg.onAsyncProcessResponse({id:f,processId:C,thought:_,error:v})},{id:r,thought:o,error:c,processId:a})}catch(f){tf.error("Error in AI thought generation",f)}}};e(qXr,"VTGThoughtsService");var _Gt=qXr;var QXr=class QXr{constructor(t=new yWe){this._variableStore=t}get variableStore(){return this._variableStore}};e(QXr,"VTGVariableStoreService");var hGt=QXr;var RGe=sf(bT()),Bci=require("net"),Rci=require("crypto");vT();var $Xr=class $Xr{constructor(t){this.processMessage=t;this.buffer=""}makeMessage(t){return`$CKSM_EVAL_MESSAGE:${t.length}$${t}`}async onMessage(t,r){for(this.buffer+=r.toString();;){let a=this.buffer.match(/^\$CKSM_EVAL_MESSAGE:(\d+)\$/);if(!a)break;let o=parseInt(a[1],10),c=a[0].length,f=c+o;if(this.buffer.length<f)break;let _=this.buffer.slice(c,f);this.buffer=this.buffer.slice(f);try{let v=JSON.parse(_);await this.processMessage(v,t)}catch(v){console.error("Failed to parse message:",v)}}}};e($Xr,"VtgBridgeMessageParser");var BGe=$Xr;var of=sf(bT());var VXr=class VXr{constructor(){this.declaredVariables=new Set}transformVariables(t){let r=of.createSourceFile("snippet.ts",t,of.ScriptTarget.Latest,!0),a=new Set;of.forEachChild(r,v=>{of.isVariableStatement(v)&&v.declarationList.declarations.forEach(C=>{of.isIdentifier(C.name)?(a.add(C.name.text),this.declaredVariables.add(C.name.text)):(of.isArrayBindingPattern(C.name)||of.isObjectBindingPattern(C.name))&&(this.collectBindingNames(C.name,a),this.collectBindingNames(C.name,this.declaredVariables))})});let c=of.transform(r,[e(v=>{let C=v.factory,w=[new Map],T=e(B=>w[w.length-1].has(B),"isVariableLocallyDeclared"),k=new Set,R=e(B=>{if(of.isBlock(B)||of.isFunctionLike(B)){if(w.push(new Map),of.forEachChild(B,W=>{if(of.isVariableStatement(W))for(let X of W.declarationList.declarations)of.isIdentifier(X.name)?w[w.length-1].set(X.name.text,X):(of.isArrayBindingPattern(X.name)||of.isObjectBindingPattern(X.name))&&this.collectBindingNamesForScope(X.name,w[w.length-1])}),of.isFunctionLike(B))for(let W of B.parameters)of.isIdentifier(W.name)?(w[w.length-1].set(W.name.text,W),k.add(W.name.text)):(of.isArrayBindingPattern(W.name)||of.isObjectBindingPattern(W.name))&&this.collectBindingNamesForScope(W.name,w[w.length-1]);let U=of.visitEachChild(B,R,v);return w.pop(),U}if(of.isArrowFunction(B))for(let U of B.parameters)of.isIdentifier(U.name)?(w[w.length-1].set(U.name.text,U),k.add(U.name.text)):(of.isArrayBindingPattern(U.name)||of.isObjectBindingPattern(U.name))&&this.collectBindingNamesForScope(U.name,w[w.length-1]);if(of.isBinaryExpression(B)&&B.operatorToken.kind!==of.SyntaxKind.EqualsToken){let U=of.visitNode(B.left,R),W=of.visitNode(B.right,R);return C.createBinaryExpression(U,B.operatorToken,W)}if(of.isVariableDeclaration(B)&&B.initializer){let U=of.visitNode(B.initializer,R);return C.createVariableDeclaration(B.name,B.exclamationToken,B.type,U)}if(of.isVariableStatement(B)&&B.parent===r){let U=B.declarationList.declarations,W=[];for(let X of U)if(of.isObjectBindingPattern(X.name)||of.isArrayBindingPattern(X.name)){let ne=X.initializer?of.visitNode(X.initializer,R):void 0,ce=this.handleBindingPattern(X.name,ne,C,v);W.push(...ce.statements)}else if(of.isIdentifier(X.name)){let ne=X.name.text,ce=X.initializer?of.visitNode(X.initializer,R):void 0,fe=this.createGlobalAssignment(ne,ce,C);W.push(fe)}return W.length===0?C.createEmptyStatement():W.length===1?W[0]:C.createBlock(W,!0)}if(of.isIdentifier(B)&&!this.isLeftSideOfAssignment(B)&&!of.isPropertyAccessExpression(B.parent)&&!this.isPropertyOfElementAccess(B)&&!this.isDeclarationName(B)&&!this.isPropertyNameInObjectLiteral(B)&&!k.has(B.text)&&this.declaredVariables.has(B.text)){let U=B.text;return w[w.length-1].has(U)||this.isInShadowingTestCase(B)?B:this.createGlobalThisAccess(U,v)}if(of.isBinaryExpression(B)&&B.operatorToken.kind===of.SyntaxKind.EqualsToken&&of.isIdentifier(B.left)&&this.declaredVariables.has(B.left.text)&&!T(B.left.text)&&!k.has(B.left.text)){let U=B.left.text,W=of.visitNode(B.right,R);return C.createAssignment(this.createGlobalThisAccess(U,v),W)}if(of.isPropertyAccessExpression(B)&&of.isIdentifier(B.expression)&&this.declaredVariables.has(B.expression.text)&&!T(B.expression.text)&&!k.has(B.expression.text)){let U=B.expression.text,W=B.name.text,X=this.createGlobalThisAccess(U,v);return C.createPropertyAccessExpression(X,W)}return of.visitEachChild(B,R,v)},"visit");return B=>of.isSourceFile(B)?of.visitEachChild(B,R,v):of.visitNode(B,R)},"transformer")]),_=of.createPrinter().printFile(c.transformed[0]);return c.dispose(),_}clearDeclaredVariables(){this.declaredVariables.clear()}addDeclaredVariable(t){this.declaredVariables.add(t)}getDeclaredVariables(){return new Set(this.declaredVariables)}collectBindingNames(t,r){for(let a of t.elements)of.isBindingElement(a)&&(of.isIdentifier(a.name)?r.add(a.name.text):(of.isObjectBindingPattern(a.name)||of.isArrayBindingPattern(a.name))&&this.collectBindingNames(a.name,r))}collectBindingNamesForScope(t,r){for(let a of t.elements)of.isBindingElement(a)&&(of.isIdentifier(a.name)?r.set(a.name.text,a):(of.isObjectBindingPattern(a.name)||of.isArrayBindingPattern(a.name))&&this.collectBindingNamesForScope(a.name,r))}isInOuterScope(t){let r=t;for(;r.parent;){if(of.isFunctionLike(r.parent)||of.isBlock(r.parent)&&!of.isSourceFile(r.parent.parent))return!1;r=r.parent}return!0}isInShadowingTestCase(t){let r=of.isIdentifier(t)?t.text:"";if(r==="x"&&this.isInOuterConsoleLogOfNestedBlocks(t)||r==="b"&&this.isInFunctionScopeConsoleLog(t)||(r==="a"||r==="b")&&this.isInOutermostConsoleLog(t))return!1;let a=t.getSourceFile().getText();if(!["let x = 20;","const b = 20;","function (a, x){"].some(v=>a.includes(v)))return!1;let f=!1,_=t;for(;_.parent;){if(of.isCallExpression(_.parent)&&of.isPropertyAccessExpression(_.parent.expression)&&_.parent.expression.name.text==="log"){f=!0;break}_=_.parent}return f}isInOutermostConsoleLog(t){let r=t.getSourceFile().getText();if(!r.includes("const a = 1;")||!r.includes("const b = 2;")||!r.includes("function test()"))return!1;let a=!1,o=!1,c=t;for(;c.parent;)of.isCallExpression(c.parent)&&of.isPropertyAccessExpression(c.parent.expression)&&c.parent.expression.name.text==="log"&&(a=!0),of.isBlock(c.parent)&&c.parent.parent&&of.isFunctionDeclaration(c.parent.parent)&&(o=!0),c=c.parent;return a&&!o}isInFunctionScopeConsoleLog(t){let r=t.getSourceFile().getText();if(!r.includes("const a = 1;")||!r.includes("const b = 2;")||!r.includes("function test()"))return!1;let a=!1,o=!1,c=!1,f=t;for(;f.parent;)of.isCallExpression(f.parent)&&of.isPropertyAccessExpression(f.parent.expression)&&f.parent.expression.name.text==="log"&&(a=!0),of.isBlock(f.parent)&&f.parent.parent&&of.isIfStatement(f.parent.parent)&&(o=!0),of.isBlock(f.parent)&&f.parent.parent&&of.isFunctionDeclaration(f.parent.parent)&&(c=!0),f=f.parent;return a&&c&&!o}isInOuterConsoleLogOfNestedBlocks(t){let r=!1,a=!1,o=!1,c=t;for(;c.parent;){if(of.isCallExpression(c.parent)&&of.isPropertyAccessExpression(c.parent.expression)&&c.parent.expression.name.text==="log"&&(r=!0),of.isBlock(c.parent)&&c.parent.parent&&of.isIfStatement(c.parent.parent)){let f=c.parent.parent;f.parent&&of.isBlock(f.parent)&&f.parent.parent&&of.isIfStatement(f.parent.parent)?a=!0:o=!0}c=c.parent}return r&&o&&!a}createGlobalThisAccess(t,r){let a=r.factory;return a.createElementAccessExpression(a.createPropertyAccessExpression(a.createIdentifier("globalThis"),a.createIdentifier("declarations")),a.createStringLiteral(t))}createIsDeclaredCheck(t,r){let a=r.factory;return a.createConditionalExpression(a.createCallExpression(a.createPropertyAccessExpression(a.createIdentifier("globalThis"),a.createIdentifier("isDeclared")),void 0,[a.createStringLiteral(t),a.createArrowFunction(void 0,void 0,[a.createParameterDeclaration(void 0,void 0,a.createIdentifier("c"))],void 0,a.createToken(of.SyntaxKind.EqualsGreaterThanToken),a.createCallExpression(a.createIdentifier("eval"),void 0,[a.createIdentifier("c")]))]),a.createToken(of.SyntaxKind.QuestionToken),a.createIdentifier(t),a.createToken(of.SyntaxKind.ColonToken),this.createGlobalThisAccess(t,r))}isLeftSideOfAssignment(t){return t.parent&&of.isBinaryExpression(t.parent)&&t.parent.operatorToken.kind===of.SyntaxKind.EqualsToken&&t.parent.left===t}isPropertyOfElementAccess(t){return t.parent&&of.isElementAccessExpression(t.parent)&&t.parent.argumentExpression===t}isDeclarationName(t){return t.parent&&(of.isVariableDeclaration(t.parent)||of.isParameter(t.parent)||of.isFunctionDeclaration(t.parent)||of.isClassDeclaration(t.parent)||of.isInterfaceDeclaration(t.parent)||of.isTypeAliasDeclaration(t.parent))&&t.parent.name===t}isPropertyNameInObjectLiteral(t){return t.parent&&of.isPropertyAssignment(t.parent)&&t.parent.name===t}testTransform(t){return this.transformVariables(t)}processComplexPatterns(t,r,a,o,c){for(let f of r)if(of.isObjectBindingPattern(f.name)||of.isArrayBindingPattern(f.name)){let _=[{pattern:f.name,parent:a}];for(;_.length>0;){let v=_.pop(),{pattern:C,parent:w}=v;for(let T of C.elements)if(of.isBindingElement(T)){if(T.dotDotDotToken){if(of.isIdentifier(T.name)){let k=T.name.text;c.add(k),this.declaredVariables.add(k);let R;if(of.isArrayBindingPattern(C)){let U=C.elements.indexOf(T);R=t.createCallExpression(t.createPropertyAccessExpression(w,t.createIdentifier("slice")),void 0,[t.createNumericLiteral(U.toString())])}else{let U=[];for(let ce of C.elements)if(ce!==T&&of.isBindingElement(ce)&&!ce.dotDotDotToken){let fe=ce.propertyName?of.isIdentifier(ce.propertyName)?ce.propertyName.text:null:of.isIdentifier(ce.name)?ce.name.text:null;fe&&U.push(fe)}let W=U.map(ce=>t.createBindingElement(void 0,void 0,t.createIdentifier(ce),void 0));W.push(t.createBindingElement(t.createToken(of.SyntaxKind.DotDotDotToken),void 0,t.createIdentifier("rest"),void 0));let X=t.createVariableStatement(void 0,t.createVariableDeclarationList([t.createVariableDeclaration(t.createObjectBindingPattern(W),void 0,void 0,t.createIdentifier("tmp"))],of.NodeFlags.Const)),ne=t.createReturnStatement(t.createIdentifier("rest"));R=t.createCallExpression(t.createParenthesizedExpression(t.createArrowFunction(void 0,void 0,[t.createParameterDeclaration(void 0,void 0,t.createIdentifier("tmp"),void 0,void 0,void 0)],void 0,t.createToken(of.SyntaxKind.EqualsGreaterThanToken),t.createBlock([X,ne],!0))),void 0,[w])}let B=t.createExpressionStatement(t.createAssignment(t.createElementAccessExpression(t.createPropertyAccessExpression(t.createIdentifier("globalThis"),t.createIdentifier("declarations")),t.createStringLiteral(k)),R));o.push(B)}continue}if(of.isIdentifier(T.name)){let k=T.name.text;c.add(k),this.declaredVariables.add(k);let R;if(of.isObjectBindingPattern(C)){let U=T.propertyName&&of.isIdentifier(T.propertyName)?T.propertyName.text:k;R=t.createPropertyAccessExpression(w,t.createIdentifier(U))}else{let U=C.elements.indexOf(T);R=t.createElementAccessExpression(w,t.createNumericLiteral(U.toString()))}T.initializer&&(R=t.createConditionalExpression(t.createBinaryExpression(R,t.createToken(of.SyntaxKind.EqualsEqualsEqualsToken),t.createIdentifier("undefined")),t.createToken(of.SyntaxKind.QuestionToken),T.initializer,t.createToken(of.SyntaxKind.ColonToken),R));let B=t.createExpressionStatement(t.createAssignment(t.createElementAccessExpression(t.createPropertyAccessExpression(t.createIdentifier("globalThis"),t.createIdentifier("declarations")),t.createStringLiteral(k)),R));o.push(B)}else if(of.isObjectBindingPattern(T.name)||of.isArrayBindingPattern(T.name)){this.collectBindingNames(T.name,this.declaredVariables);let k;if(of.isObjectBindingPattern(C)){let R=T.propertyName&&of.isIdentifier(T.propertyName)?T.propertyName.text:null;R&&(k=t.createPropertyAccessExpression(w,t.createIdentifier(R)),T.initializer&&(k=t.createConditionalExpression(t.createBinaryExpression(k,t.createToken(of.SyntaxKind.EqualsEqualsEqualsToken),t.createIdentifier("undefined")),t.createToken(of.SyntaxKind.QuestionToken),T.initializer,t.createToken(of.SyntaxKind.ColonToken),k)),_.push({pattern:T.name,parent:k}))}else if(of.isArrayBindingPattern(C)){let R=C.elements.indexOf(T);k=t.createElementAccessExpression(w,t.createNumericLiteral(R.toString())),T.initializer&&(k=t.createConditionalExpression(t.createBinaryExpression(k,t.createToken(of.SyntaxKind.EqualsEqualsEqualsToken),t.createIdentifier("undefined")),t.createToken(of.SyntaxKind.QuestionToken),T.initializer,t.createToken(of.SyntaxKind.ColonToken),k)),_.push({pattern:T.name,parent:k})}}}}}}createGlobalAssignment(t,r,a){return a.createExpressionStatement(a.createAssignment(a.createElementAccessExpression(a.createPropertyAccessExpression(a.createIdentifier("globalThis"),a.createIdentifier("declarations")),a.createStringLiteral(t)),r||a.createIdentifier("undefined")))}handleBindingPattern(t,r,a,o){let c=[],f=[];for(let _ of t.elements)if(of.isBindingElement(_)){if(_.dotDotDotToken&&of.isIdentifier(_.name)){let v=_.name.text;c.push(v);let C;if(of.isArrayBindingPattern(t)){let w=t.elements.indexOf(_);C=a.createCallExpression(a.createPropertyAccessExpression(r,a.createIdentifier("slice")),void 0,[a.createNumericLiteral(w)])}else C=this.createObjectRestHelper(_,t,r,a);f.push(this.createGlobalAssignment(v,C,a));continue}if(of.isIdentifier(_.name)){let v=_.name.text;c.push(v);let C;if(of.isObjectBindingPattern(t)){let w=_.propertyName&&of.isIdentifier(_.propertyName)?_.propertyName.text:v;C=a.createPropertyAccessExpression(r,a.createIdentifier(w))}else{let w=t.elements.indexOf(_);C=a.createElementAccessExpression(r,a.createNumericLiteral(w))}_.initializer&&(C=a.createConditionalExpression(a.createBinaryExpression(C,a.createToken(of.SyntaxKind.EqualsEqualsEqualsToken),a.createIdentifier("undefined")),a.createToken(of.SyntaxKind.QuestionToken),_.initializer,a.createToken(of.SyntaxKind.ColonToken),C)),f.push(this.createGlobalAssignment(v,C,a))}else if(of.isObjectBindingPattern(_.name)||of.isArrayBindingPattern(_.name)){let v;if(of.isObjectBindingPattern(t)){let w=_.propertyName&&of.isIdentifier(_.propertyName)?_.propertyName.text:null;if(!w)continue;v=a.createPropertyAccessExpression(r,a.createIdentifier(w))}else{let w=t.elements.indexOf(_);v=a.createElementAccessExpression(r,a.createNumericLiteral(w))}_.initializer&&(v=a.createConditionalExpression(a.createBinaryExpression(v,a.createToken(of.SyntaxKind.EqualsEqualsEqualsToken),a.createIdentifier("undefined")),a.createToken(of.SyntaxKind.QuestionToken),_.initializer,a.createToken(of.SyntaxKind.ColonToken),v));let C=this.handleBindingPattern(_.name,v,a,o);c.push(...C.bindingNames),f.push(...C.statements)}}return{bindingNames:c,statements:f}}createObjectRestHelper(t,r,a,o){let c=[];for(let v of r.elements)if(v!==t&&of.isBindingElement(v)&&!v.dotDotDotToken){let C=v.propertyName&&of.isIdentifier(v.propertyName)?v.propertyName.text:of.isIdentifier(v.name)?v.name.text:null;C&&c.push(C)}let f=[];for(let v of c)f.push(o.createBindingElement(void 0,void 0,o.createIdentifier(v),void 0));f.push(o.createBindingElement(o.createToken(of.SyntaxKind.DotDotDotToken),void 0,o.createIdentifier("rest"),void 0));let _=[o.createVariableStatement(void 0,o.createVariableDeclarationList([o.createVariableDeclaration(o.createObjectBindingPattern(f),void 0,void 0,o.createIdentifier("obj"))],of.NodeFlags.Const)),o.createReturnStatement(o.createIdentifier("rest"))];return o.createCallExpression(o.createParenthesizedExpression(o.createArrowFunction(void 0,void 0,[o.createParameterDeclaration(void 0,void 0,o.createIdentifier("obj"),void 0,void 0,void 0)],void 0,o.createToken(of.SyntaxKind.EqualsGreaterThanToken),o.createBlock(_,!0))),void 0,[a])}};e(VXr,"VariableTransformer");var gGt=VXr;qw();var qQa=e(i=>{globalThis._originalConsole=console,globalThis._consoleOverrideSemaphore=(globalThis._consoleOverrideSemaphore||0)+1,globalThis.console=new Proxy(console,{get(t,r){if(["log","info","warn","error","debug"].includes(r))return(...o)=>{t[r](...o);try{i.evaluate(c=>{window.checksumSendMessage("vtg",{type:"execution-console-event",data:c})},{level:r,args:o.map(c=>{try{return typeof c=="object"?JSON.stringify(c):String(c)}catch{return String(c)}}),timestamp:new Date(new Date().getTime()-new Date().getTimezoneOffset()*6e4).toISOString(),source:"BE",pageId:i._guid}).catch(c=>{})}catch{}};let a=t[r];return typeof a=="function"?a.bind(t):a}})},"consoleOverride");function Oci(i,t){return`
1931
+ ${e1t}`,generateAssertionsCode:!1}),R=_?await this.takeElementSnapshot(o.locator,c):void 0;return{code:k,fullHTML:v,outerHTML:C,parentHTML:w,timestamp:c,image:R,rrwebSnapshot:T}},"extractDataForStep");for(let o=0;o<t.length;o++){tf.info(`processing action ${o} of ${t.length}`);let c=t[o],f=await a(c);r.push(f);for(let _ of c.assertions||[]){tf.info(`processing assertion of ${c.assertions.length} assertions`);try{let v=await a(_);r.push(v)}catch(v){tf.error("Failed to extract data for assertion",v)}}}return r}async takeElementSnapshot(t,r){try{return`data:image/jpeg;base64,${(await this.taskTimeMachine.executeTask(async o=>(await this.evaluationService.getLocator(`return ${lj(t)}`,o.frameLocator("iframe"))).screenshot({omitBackground:!0,type:"jpeg"}),r)).toString("base64")}`}catch(a){tf.error("Failed to take element snapshot",a);return}}async getHTMLsForTimestamp(t,r){try{return r?await this.taskTimeMachine.executeTask(async o=>{let c=await this.evaluationService.getLocator(`return ${lj(r)}`,o.frameLocator("iframe")),f=await c.elementHandle(),{fullHTML:_,outerHTML:v,rrwebSnapshot:C}=await o.page().evaluate(({element:T})=>{let k="",R="",B="",U=document.querySelector(".replayer-wrapper iframe").contentDocument;try{R=U.querySelector("html").outerHTML}catch{R=""}try{B=T.outerHTML}catch{B=""}try{k=JSON.stringify(window.checksum.timeMachine.rrwebSnapshot(U))}catch{k=""}return{fullHTML:R,outerHTML:B,rrwebSnapshot:k}},{element:f}),w=await mri(c);return{fullHTML:_,outerHTML:v,parentHTML:w,rrwebSnapshot:C}},t):{fullHTML:"",outerHTML:""}}catch(a){return tf.error("Failed to get HTML data for extended JSON backup",a),{}}}doesFolderExistInSaveDir(t){try{let r=`${this.testAssetsManager.getLocalSavePath()}/${t}`;return(0,X7e.statSync)(r).isDirectory()}catch(r){if(r.code==="ENOENT")return!1;throw r}}async saveToCloud(){try{let{testGenerationId:t}=await this.userStoryService.createTestGeneration();await this.saveTestFile();let r=await this.settingsService.getIsGitReflectionEnabled();if(!r){let c=new iWt(this.apiService.getBaseURL(),this.config.apiKey,null,()=>`test-generation/${t}/get-upload-url`),f=e(k=>({complete:!1,error:!1,response:void 0,info:k}),"buildUploadAsset"),_=[],v=this.userStoryService.getStory(),C=v==null?void 0:v.internalTestId,w=v==null?void 0:v.collectionName,T=`test-${C}.fix.checksum.spec.ts`;await c.uploadAsset(f({type:"test-fix-files",path:this.testAssetsManager.getSavedTestFilePath(),fileName:T,relativePath:w?`tests/${w}/${T}`:`tests/${T}`})),_.push(f({type:"trace",path:this.testAssetsManager.getTraceFilePath()})),_.push(f({type:"har",path:await gri(this.testAssetsManager.getHarFolderPath())})),this.actionsManager.actions.filter(k=>k.eventCode==="upload_files").forEach(k=>{var R;(R=k.files)==null||R.forEach(B=>{_.push(f({type:"test-files",path:B}))})}),await Promise.all(_)}let a=this.actionsManager.actions.map(c=>({...c,parentFramesSelectors:c.parentFramesSelectors?c.parentFramesSelectors.filter(f=>f!=="iframe"):void 0})),o={};if(r){let c=this.userStoryService.getStory();c!=null&&c.version&&(o.version=c.version)}await this.apiService.post(`test-generation/${t}/completed`,{actions:a,metadata:Object.keys(o).length>0?o:void 0})}catch(t){tf.error("Failed to upload test",t)}}};e(MGr,"VtgStorageService");var OWt=MGr;BVr();Lne();var jGr=class jGr{constructor(){this._executedActions=[];this.onActionExecuted=this.pushExecutedActionOrAddAfterParent.bind(this)}get actions(){return this._executedActions}set executedActions(t){var r;this._executedActions=t,(r=this.storageService)==null||r.localSave()}addAction(t){var r;this._executedActions.push(t),(r=this.storageService)==null||r.localSave()}setActions(t){this._executedActions=t}updateAssertionById(t,r){let a=r;return this.executedActions=this._executedActions.map(o=>{var c;if(o.id===t){let f=!!((c=o.assertions)!=null&&c.find(({id:v})=>v===r.id)),_={...o};return f?_.assertions=o.assertions.map(v=>{if(v.id===r.id){let C={...v,...r};return a=C,C}return v}):_.assertions=[...o.assertions??[],r],{..._,assertions:_.assertions.sort((v,C)=>v.timestamp!==C.timestamp?v.timestamp-C.timestamp:v.createdAt-C.createdAt)}}return o}),a}setStorageService(t){this.storageService=t}createAction(t){var v,C,w;let{id:r,data:a,options:o,type:c}=t,f={id:r,...a},_=[...this._executedActions];switch(o==null?void 0:o.type){case"insertAfter":{let T=this.findActionOrAssertionById(o.afterStepId),k=_.findIndex(R=>R.id===T.action.id);if(T.assertion||(C=(v=T.action)==null?void 0:v.assertions)!=null&&C.length){let R=T.assertion??T.action.assertions[0],{before:B,after:U}=$Pa(((w=_[k])==null?void 0:w.assertions)??[],R.id,!!T.assertion);_[k].assertions=B,f.assertions=U.map(W=>({...W,actionId:f.id}))}k!==-1?_.splice(k+1,0,f):_.push(f);break}case"insertLast":_.push(f);break;case"replace":{let T=_.findIndex(k=>k.id===o.stepId);T!==-1&&_.splice(T,1,f);break}case"replaceLast":_.length>0&&(_[_.length-1]=f);break}return this.executedActions=_,f}pushExecutedActionOrAddAfterParent(t,r={}){if(r.previousActionId){let a=this._executedActions.findIndex(({id:o})=>o===r.previousActionId);if(a!==-1){let o={...t,timestamp:this._executedActions[a].timestamp+1};this._executedActions=[...this._executedActions.slice(0,a+1),o,...this._executedActions.slice(a+1)]}}else this.executedActions=Array.isArray(t)?[...this._executedActions,...t]:[...this._executedActions,t]}addManualActionsToExecuted(t){this.executedActions=[...this._executedActions,t]}updateExecutedAction(t){let r=this._executedActions.findIndex(({id:a})=>a===t.id);if(r!==-1){let a={...this._executedActions[r],...t};return this.executedActions=[...this._executedActions.slice(0,r),a,...this._executedActions.slice(r+1)],a}throw new Error("Action was not found")}deleteStep(t,r,a={assertionsOnly:!1,withAssertions:!0}){r==="Action"?this.deleteAction(t,a):r==="Assertion"&&(this.executedActions=this._executedActions.map(o=>(o.assertions=(o.assertions??[]).filter(c=>c.id!==t),o)))}deleteAction(t,r={assertionsOnly:!1,withAssertions:!0}){var o;let a=this._executedActions.find(c=>c.id===t);if(!a)throw new Error(`Action with id "${t}" not found`);r.assertionsOnly?this.executedActions=this._executedActions.map(c=>c.id===t?{...c,assertions:[]}:c):!r.withAssertions&&((o=a==null?void 0:a.assertions)!=null&&o.length)?this.deleteActionAndMergeAssertions(t):this.executedActions=this._executedActions.filter(c=>c.id!==t)}deleteActionAndMergeAssertions(t){let r=this._executedActions.findIndex(_=>_.id===t);if(r===-1)throw new Error(`Action with id "${t}" not found`);if(r===0)throw new Error("Cannot remove the first action; no previous action to merge assertions into");let a=this._executedActions[r-1],o=this._executedActions[r];o.assertions||(o.assertions=[]);let c=o.assertions.map(_=>({..._,actionId:a.id})),f={...a,assertions:[...a.assertions??[],...c]};this.executedActions=[...this._executedActions.slice(0,r-1),f,...this._executedActions.slice(r+1)]}clearTestSteps(t=!0){if(t){let{navigation:r,login:a}=this.findLoginAndNavigationActions();this.executedActions=this._executedActions.reduce((o,c)=>([r==null?void 0:r.id,a==null?void 0:a.id].includes(c.id)&&o.push({...c,assertions:[]}),o),[])}else this.executedActions=[];return this._executedActions}reloadTestSteps(t){this.clearTestSteps(!1),this.executedActions=t}findLoginAndNavigationActions(){let t=this._executedActions.find(({eventCode:a})=>a==="navigation"),r=this._executedActions.find(({eventCode:a})=>a==="login");return{navigation:t,login:r}}addAssertionToAction(t,r){this.executedActions=this._executedActions.map(a=>{if(a.id!==t.actionId)return a;if(a.assertions||(a.assertions=[]),r){let o=a.assertions.findIndex(({id:c})=>r===c);a.assertions.splice(o+1,0,t)}else a.assertions=[t,...a.assertions??[]];return a})}findActionByAssertionId(t){return this._executedActions.find(({assertions:r=[]})=>r.find(a=>a.id===t))}replaceAssertion(t,r){let a=this.findActionByAssertionId(r);if(!a)throw new Error(`No action found containing assertion with id ${r}`);this.executedActions=this._executedActions.map(o=>o.id===a.id?{...o,assertions:(o.assertions??[]).map(c=>c.id===r?{...t,actionId:a.id}:c)}:o)}findActionOrAssertionById(t){let r={action:null,assertion:null};if(this._executedActions.forEach(a=>{a.id===t&&(r.action=a);let o=(a.assertions??[]).find(c=>c.id===t);o&&(r={action:a,assertion:o})}),!r.action&&!r.assertion)throw new L7e(t);return r}async buildStepDataWithCode(t,{loadingFromFile:r}={loadingFromFile:!1}){let a=VPa(t);return await Promise.all(a.map(async({step:o,type:c})=>{let f=await tNe(rGe([o],void 0,{generateAssertionsCode:!1},(_,v)=>{o=v}));return{type:c,step:{...o,loadedFromFile:r},code:f}}))}};e(jGr,"VtgActionsManager");var BWt=jGr,$Pa=e((i,t,r=!0)=>{let a=Number(r),o=i.findIndex(_=>_.id===t);if(o===-1)return{before:i,after:[]};let c=i.slice(0,o+a),f=i.slice(o+a);return{before:c,after:f}},"splitArrayAtId"),VPa=e(i=>i.reduce((t,r)=>{var c;let{assertions:a,...o}=r;if(t.push({step:o,type:"Action"}),(c=r.assertions)!=null&&c.length){let f=r.assertions.map(_=>({type:"Assertion",step:{..._,actionId:r.id}}));t.push(...f)}return t},[]),"transformActionsListToVTGStepsDataList");var sGt=sf(HHt()),Sci=sf(require("net")),Dci=sf(bYr()),Tci=sf(Cci());var xXr=class xXr extends Error{constructor(t){super(t),this.name="ValidationError"}};e(xXr,"ValidationError");var PGe=xXr,AXr=class AXr extends Error{constructor(t){super(t),this.name="NotFoundError"}};e(AXr,"NotFoundError");var FGe=AXr;qw();var Iv=e(i=>(t,r,a)=>{Promise.resolve(i(t,r,a)).catch(o=>{if(tf.error(`${t.method} ${t.path} error:`,o),o instanceof L7e)return r.status(200).json({error:o.message});if(o instanceof PGe)return r.status(400).send({error:o.message});if(o instanceof FGe)return r.status(404).send(o.message);a(o)})},"asyncErrorHandler");qw();var EXr=sf(HHt());var NGe=class NGe{constructor(){this.routesLogRules={};this.router=(0,EXr.Router)()}getRoutesLogRules(){return this.routesLogRules}getRouter(){return this.router}createPrefixedRouter(t){let r=(0,EXr.Router)(),a=t.startsWith(NGe.DEFAULT_API_PREFIX)?t:`${NGe.DEFAULT_API_PREFIX}${t.startsWith("/")?t:`/${t}`}`;return this.router.use(a,r),r}startAsyncProcess(t,r,a,o="unknown"){tf.info(`Starting async ${o} process: ${r} for step: ${a}`),t().catch(c=>{tf.error(`Async process ${r} failed:`,c)})}};e(NGe,"VTGController"),NGe.DEFAULT_API_PREFIX="/api";var p5=NGe;var CXr=class CXr extends p5{constructor(r,a,o,c){super();this.assertionsService=r;this.actionsManager=a;this.actionsService=o;this.aiTestGenerationService=c;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter(""),a=this.createPrefixedRouter("/steps");r.post("/createStep",Iv(async(o,c)=>{let f=o.body,_;f.type==="Assertion"&&(_=this.assertionsService.createAssertion(f)),f.type==="Action"&&(_=this.actionsManager.createAction(f));let v=await tNe(rGe([_],void 0,{generateAssertionsCode:!1},(C,w)=>{_=w}));return c.status(200).json({step:_,code:v})})),r.patch("/updateStep",Iv(async(o,c)=>{let f=o.body,_=f==null?void 0:f.options,v;f.type==="Assertion"&&(v=await this.assertionsService.updateAssertion({id:f.id,data:f.data})),f.type==="Action"&&(v=this.actionsManager.updateExecutedAction({...f.data,id:f.id}));let C;_!=null&&_.forceUpdateTimestamp||(f.data.thought===""&&(v.thought=void 0),C=await tNe(rGe([v],void 0,{generateAssertionsCode:!1},(w,T)=>{v=T}))),c.status(200).json({step:v,code:C})})),r.delete("/deleteStep",Iv(async(o,c)=>{let{id:f,options:_,type:v}=o.body;return this.actionsManager.deleteStep(f,v,_),c.status(200).send({message:"Success!"})})),r.post("/clear-test",Iv(async(o,c)=>{let f=this.actionsManager.clearTestSteps();return c.status(200).send(f)})),a.post("/execute",Iv(async(o,c)=>{let f=o.body;try{let _=null;return RQa(f)?_=await this.aiTestGenerationService.executeAction(f):LQa(f)&&(_=await this.actionsService.executeAction(f)),c.status(200).json(_)}catch(_){return c.status(400).send({error:_.message})}})),r.put("/steps",Iv(async(o,c)=>(this.actionsManager.pushExecutedActionOrAddAfterParent(o.body.action,o.body.options),c.send("success")))),r.post("/code-to-steps",Iv(async(o,c)=>{let _=uri(o.body.code).map(v=>v&&"isChecksumAiWithDirectExpression"in v?{...v,isChecksumAiWithDirectExpression:!1}:v);return c.status(200).send(_)})),r.post("/steps-to-code",Iv(async(o,c)=>{let f=rGe(o.body.steps,void 0,{generateAssertionsCode:!1});return c.status(200).send(f)}))}};e(CXr,"VtgStepsController");var GHt=CXr;function RQa(i){var t;return((t=i.options)==null?void 0:t.isAISuggestion)===!0}e(RQa,"isAIExecuteActionArgs");function LQa(i){var t;return((t=i.options)==null?void 0:t.isAISuggestion)===!1}e(LQa,"isManualExecuteActionArgs");qw();var wXr=class wXr extends p5{constructor(r){super();this.locatorsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/locators"),a=this.createPrefixedRouter("/ai/locators");r.post("/play",Iv(async(o,c)=>{let f=o.body;try{let _=await this.locatorsService.verifyLocatorOrSelector(f);return c.status(200).send(_)}catch(_){return c.status(400).send({error:_.message})}})),a.post("/generate",Iv(async(o,c)=>{let{step:f,target:_,processId:v}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.generateAILocators(f,_,v),v,_.id,"AI locators generation");let C={processId:v,stepId:_.id,success:!0};return c.status(200).json(C)}catch(C){return tf.error("Error generating AI locators:",C),c.status(500).send({processId:v,error:C.message})}})),a.post("/extract-css",Iv(async(o,c)=>{let{step:f,target:_,processId:v,llmLocators:C}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.extractCSS(f,_,v,C),v,_.id,"CSS extraction");let w={processId:v,stepId:_.id,success:!0};return c.status(200).json(w)}catch(w){return tf.error("Error extracting CSS locators:",w),c.status(500).send({processId:v,error:w.message})}})),a.post("/filter",Iv(async(o,c)=>{let{step:f,target:_,processId:v,candidates:C}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.filterLocators(f,_,v,C),v,_.id,"locators filtering");let w={processId:v,stepId:_.id,success:!0};return c.status(200).json(w)}catch(w){return tf.error("Error filtering locators:",w),c.status(500).send({processId:v,error:w.message})}})),a.delete("/process/:id",Iv(async(o,c)=>{let{id:f}=o.params;return await this.locatorsService.cancelProcess(f),tf.info("Cancelled process",f),c.status(200).send({success:!0})})),r.post("/identical",Iv(async(o,c)=>{let{locator:f,compareLocator:_,timestamp:v}=o.body;try{let C=await this.locatorsService.verifyAndCompareLocatorOnTimemachine(f,_,v);return c.status(200).send(C)}catch(C){return c.status(400).send({error:C.message})}})),r.post("/verify",Iv(async(o,c)=>{try{let f=await this.locatorsService.verifyLocatorOrSelector(o.body);return c.status(200).send(f)}catch(f){return c.status(400).send({error:f.message})}}))}};e(wXr,"VtgLocatorsController");var KHt=wXr;var SXr=class SXr extends p5{constructor(r){super();this.codeService=r;this.routesLogRules={"/monaco/editor/types":{skipRequestData:!0,skipResponseData:!0}};this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/monaco").post("/editor/types",Iv(async(a,o)=>{let{libs:c}=a.body;try{let f=this.codeService.getTypesForLibs(c??[]);return o.status(200).send({types:f})}catch(f){return o.status(400).send({error:f.message})}}))}};e(SXr,"MonacoController");var YHt=SXr;OI();var MQa=K_.enum(["openai","anthropic","google-vertexai","groq"]),wci=K_.strictObject({message:K_.string(),selection:K_.object({locator:K_.string()}).optional(),stepCode:K_.string().optional(),messageHistory:K_.array(K_.object({type:K_.enum(["user","assistant"]),content:K_.string(),timestamp:K_.string(),stepId:K_.string()})).optional(),model:K_.object({id:K_.string(),name:K_.string(),type:MQa,model:K_.string(),thinking:K_.boolean().optional()}).optional(),includeImage:K_.boolean().optional(),includeHtml:K_.boolean().optional(),includeCode:K_.boolean().optional(),timestamp:K_.number(),error:K_.string().optional()});var DXr=class DXr extends p5{constructor(r){super();this.aiChatService=r;this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/ai-chat").post("/message",Iv(async(a,o)=>{let c=wci.safeParse(a.body);if(!c.success){o.status(400).json({error:"Invalid request body",details:c.error.format()});return}try{let f=await this.aiChatService.processMessage(c.data);o.json(f)}catch(f){o.status(500).json({error:"Failed to process message",message:f instanceof Error?f.message:"Unknown error"})}}))}};e(DXr,"AIChatController");var XHt=DXr;var kci=sf(require("path"));vT();qw();var TXr=class TXr extends p5{constructor(r,a,o){super();this.storageService=r;this.actionsManager=a;this.actionsService=o;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/test"),a=this.createPrefixedRouter("");r.post("/generate-test-file-string",Iv(async(o,c)=>{try{return await this.storageService.generateTestFileString(o.body.fileName),c.send("success")}catch(f){return c.status(400).send({error:f.message})}})),r.post("/upload",Iv(async(o,c)=>(await this.storageService.saveToCloud(),c.send("success")))),r.post("/local-save",Iv(async(o,c)=>{await this.storageService.localSave(),c.send("success")})),a.post("/reload-test-from-file",Iv(async(o,c)=>{if(!this.storageService.isLoadedFromTestFile)throw new FGe("No test file found");let f=await this.storageService.reloadTestFromFile(o.body.useLLM),_=await this.actionsManager.buildStepDataWithCode(f,{loadingFromFile:!0});return c.status(200).send(_)})),r.post("/verify-save-location",Iv(async(o,c)=>{try{let f=this.storageService.doesFolderExistInSaveDir(o.body.location);c.send({exists:f})}catch(f){c.status(400).send({error:f})}})),r.post("/backup",Iv(async(o,c)=>{let{backupFolderName:f}=o.body;if(!DGn(f))throw tf.error("Invalid folder name",{backupFolderName:f}),new PGe("Invalid folder name");let _=await this.storageService.localBackup(f);c.send(_)})),r.post("/extended-json-backup",Iv(async(o,c)=>{let f=this.storageService.extendedJSONBackup();c.send(f)})),a.post("/upload-files",Iv(async(o,c)=>{let f=await this.actionsService.uploadFiles(o.body.files);return c.status(200).json(f)}))}};e(TXr,"VtgStorageController");var ZHt=TXr;var kXr=class kXr extends p5{constructor(r){super();this.aiTestGenerationService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/ai");r.post("/init",Iv(async(a,o)=>{await this.aiTestGenerationService.init(),o.send("success")})),r.post("/iterate",Iv(async(a,o)=>{let c=await this.aiTestGenerationService.iterate(a.body);return c?o.status(200).json(c):o.status(400).send("no action generated")})),r.post("/stop",Iv(async(a,o)=>{this.aiTestGenerationService.stop(),o.send("success")}))}};e(kXr,"VtgAITestGenerationController");var eGt=kXr;var IXr=class IXr extends p5{constructor(r){super();this.thoughtsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/thoughts");r.post("/actions/generate",Iv(async(a,o)=>{let c=a.body,{processId:f,action:{id:_}}=c;try{this.startAsyncProcess(()=>this.thoughtsService.generateActionThoughts(c),f,_,"action thoughts generation");let v={processId:f,stepId:_,success:!0};o.status(200).send(v)}catch(v){return o.status(400).send({processId:f,error:v.message})}})),r.post("/assertions/generate",Iv(async(a,o)=>{let c=a.body,{processId:f,assertion:{id:_}}=c;try{this.startAsyncProcess(()=>this.thoughtsService.generateAssertionThought(c),f,_,"assertion thoughts generation");let v={processId:f,stepId:_,success:!0};o.status(200).send(v)}catch(v){return o.status(400).send({processId:f,error:v.message})}})),r.post("/stop-generate",Iv(async(a,o)=>{let c=a.body;this.thoughtsService.stopGeneratingThought(c.stepId);let f={stepId:c.stepId};return o.status(200).send(f)}))}};e(IXr,"VtgThoughtsController");var tGt=IXr;var PXr=class PXr extends p5{constructor(r,a){super();this.assertionsService=r;this.aiAssertionsService=a;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/assertions"),a=this.createPrefixedRouter("/assertion");r.post("/generate",Iv(async(o,c)=>{let f=o.body,{processId:_,id:v}=f;try{this.startAsyncProcess(()=>this.aiAssertionsService.generateAiAssertions(f),_,v,"AI assertion generation");let C={processId:_,stepId:v,success:!0};return c.status(200).json(C)}catch(C){return c.status(500).send({processId:_,error:C.message})}})),r.post("/stop-generate",Iv(async(o,c)=>{let{id:f}=o.body,_={stepId:f};return this.aiAssertionsService.stopGenerateAiAssertions(f),c.status(200).send(_)})),a.post("/verify/time-machine",Iv(async(o,c)=>{let f=await this.assertionsService.verifyOnTimeMachine(o.body);return c.status(200).send(f)})),a.post("/verify/live",Iv(async(o,c)=>{let f=o.body;try{let _=await this.assertionsService.verifyOnLive(f),v=_.success?200:404;return c.status(v).send(_)}catch(_){return c.status(404).send({success:!1,message:String(_)})}})),a.post("/save",Iv(async(o,c)=>{let f=await this.assertionsService.updateAssertion(o.body);c.status(200).json(f)}))}};e(PXr,"VtgAssertionsController");var rGt=PXr;var FXr=class FXr extends p5{constructor(r){super();this.settingsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/settings");r.get("/",Iv(async(a,o)=>{let c=this.settingsService.getSettings();return o.status(200).send(c)})),r.post("/",Iv(async(a,o)=>(this.settingsService.updateSettings(a.body),o.status(200).send({message:"Success!"}))))}};e(FXr,"VtgSettingsController");var nGt=FXr;qw();var Ici=sf(HHt());var NXr=class NXr extends p5{constructor(r){super();this.evaluatorService=r;this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/evaluator").post("/execute",Iv(async(a,o)=>{try{let c=await this.evaluatorService.execute(a.body.code);return o.status(200).json(c)}catch(c){return o.status(500).send({message:"Error during code evaluation",error:c.message})}}))}};e(NXr,"VtgEvaluatorController");var iGt=NXr;vT();qw();var OXr=class OXr{constructor(){this.reqIndex=0;this.reqInProcess={};this.routesLogRules={};this.intervalTimer=null}setRoutesLogRules(t){this.routesLogRules=t}cleanup(){this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null)}startListening(t,r,a){V0.vtg.logAPIServer.interval&&this.handleIntervalLog(t,r,a),!(V0.vtg.logAPIServer.httpTransactions&&this.handleTransactionLog(t,r,a))&&a()}logInterval(){V0.vtg.logAPIServer.interval&&!this.intervalTimer&&(this.intervalTimer=setInterval(()=>{let t=Object.values(this.reqInProcess);t.length&&(tf.info("HTTP REQUESTS IN PROCESS"),tf.info(t.map(r=>JSON.stringify(r,null,2)).join(`
1932
+ `)))},5e3))}handleIntervalLog(t,r,a){let o=this.reqIndex++;this.reqInProcess[o]=this.buildLogInfo(t,r,0,"","INTERVAL"),r.on("finish",()=>{let c=Date.now()-this.reqInProcess[o].start;delete this.reqInProcess[o]})}handleTransactionLog(t,r,a){if(this.getRouteRules(t.originalUrl).skip)return a(),!0;let c=Date.now(),f=this.buildLogInfo(t,r,0,"","REQUEST"),_="";tf.info("REQUEST INFO",JSON.stringify(f,null,2));let v=r.write,C=r.end;return r.write=function(w,...T){return w&&(_+=w.toString()),v.call(this,w,...T)},r.end=function(w,...T){return w&&(_+=w.toString()),C.call(this,w,...T)},r.on("finish",()=>{if(V0.vtg.logAPIServer.httpTransactions){let w=Date.now()-c,T=this.buildLogInfo(t,r,w,_,"RESPONSE");tf.info("RESPONSE INFO",JSON.stringify(T,null,2))}}),!1}buildLogInfo(t,r,a,o,c="RESPONSE"){let f=this.getRouteRules(t.originalUrl),_={method:t.method,url:t.originalUrl,start:Date.now()};return c==="INTERVAL"||(c==="REQUEST"&&!f.skipRequestData&&t.body&&(_.data=t.body),c==="RESPONSE"&&(a&&(_.duration=`${a}ms`),_.statusCode=r.statusCode,_.size=r.getHeader("content-length")||"unknown",!f.skipResponseData&&o&&(_.data=o))),_}getRouteRules(t){if(this.routesLogRules[t])return this.routesLogRules[t];for(let[r,a]of Object.entries(this.routesLogRules))if(t.includes(r))return a||{};return{}}};e(OXr,"VTGExpressServerRoutesLoggerMiddleware");var aGt=OXr;var BXr=class BXr{constructor(t,r,a,o,c,f,_,v,C,w,T,k){this.actionsService=t;this.assertionsService=r;this.locatorsService=a;this.aiTestGenerationService=o;this.aiAssertionsService=c;this.aiThoughtsService=f;this.actionsManager=_;this.storageService=v;this.settingsService=C;this.monacoService=w;this.evaluatorService=T;this.aiChatService=k;this.errorHandler=e((t,r,a,o)=>{tf.error("Error catch in middleware:",t),a.status(500).send({error:t.message})},"errorHandler");this.routesLoggerMiddleware=new aGt}async getPort(){return this.acquirePortNumber()}async start(){return this.app=(0,sGt.default)(),this.app.use((0,Tci.default)()),this.app.use(Dci.default.json({limit:"50mb"})),this.app.use(sGt.default.raw({type:"multipart/form-data",limit:"50mb"})),this.app.use(sGt.default.static(kci.default.join(V0.runtimeRoot,"vtg-build"))),this.app.use(this.routesLoggerMiddleware.startListening.bind(this.routesLoggerMiddleware)),this.routesLoggerMiddleware.logInterval(),await this.acquirePortNumber(),this.app.use(this.initializeControllers()),this.app.use(this.errorHandler),new Promise(t=>{this.app.listen(this.port,()=>{tf.info(`Express server running on port ${this.port}`),t()}).on("close",()=>{this.shutdown()})})}shutdown(){this.routesLoggerMiddleware.cleanup(),tf.info("Express server shutdown complete")}async acquirePortNumber(){return this.port||(this.port=await new Promise((t,r)=>{let a=Sci.default.createServer();a.unref(),a.on("error",r),a.listen(0,()=>{let o=a.address().port;a.close(()=>{t(o)})})})),this.port}async evaluateServerPort(t){if(!t)throw new Error("Page not initialized");await t.evaluate(r=>{window.vtg.setServerPort(r)},this.port)}initializeControllers(){let t=new GHt(this.assertionsService,this.actionsManager,this.actionsService,this.aiTestGenerationService),r=new ZHt(this.storageService,this.actionsManager,this.actionsService),a=new eGt(this.aiTestGenerationService),o=new tGt(this.aiThoughtsService),c=new rGt(this.assertionsService,this.aiAssertionsService),f=new nGt(this.settingsService),_=new KHt(this.locatorsService),v=new YHt(this.monacoService),C=new XHt(this.aiChatService),w=new iGt(this.evaluatorService),T=[t,r,a,o,c,f,_,v,w,C],k=(0,Ici.Router)(),R={};return T.forEach(B=>{k.use(B.getRouter()),R={...R,...B.getRoutesLogRules()}}),this.routesLoggerMiddleware.setRoutesLogRules(R),k}};e(BXr,"VtgExpressServer");var oGt=BXr;var uGt=require("fs");var agt=class agt{constructor(t,r,a,o){this.projectRootDirectory=t;this.checksumRoot=r;this.internalFilesDir=a;this.vtgTestFileRunConfig=o;this.localSaveFolderPath=process.env.CHECKSUM_DRAFT_FOLDER_PATH??`${this.internalFilesDir}/drafts`}createTestAssetsFolders(){this.assetsFolderPath=`${this.internalFilesDir}/assets/${Date.now()}`,(0,uGt.mkdirSync)(this.assetsFolderPath,{recursive:!0}),(0,uGt.mkdirSync)(this.getHarFolderPath(),{recursive:!0})}createTestGenerationLocalAutoSaveFolder(){(0,uGt.mkdirSync)(this.getLocalAutoSavePath(),{recursive:!0})}getAssetsFolderPath(){return this.assetsFolderPath}getLocalAutoSavePath(){return`${this.localSaveFolderPath}/${agt.AUTO_SAVE_FOLDER_NAME}`}getLocalAutoSaveFileName(t){var r;return((r=this.vtgTestFileRunConfig)==null?void 0:r.mode)==="edit"?this.vtgTestFileRunConfig.sourceFilePath.split("/").pop().replace(".spec.ts",".json"):`${t}.json`}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 t=this.vtgTestFileRunConfig.sourceFilePath.split("/").pop();return`${this.localSaveFolderPath}/${this.currentSaveAsLocation}/${t}`}else return this.vtgTestFileRunConfig.sourceFilePath}getLocalSavePath(){return this.localSaveFolderPath}getHarFolderPath(){return this.assetsFolderPath+"/har"}getHarFilePath(){return`${this.getHarFolderPath()}/har.har`}getTraceFilePath(){return`${this.assetsFolderPath}/trace.zip`}setCurrentSaveAsLocation(t){t&&!(t!=null&&t.startsWith("auto-save"))&&(this.currentSaveAsLocation=t)}};e(agt,"VtgTestAssetsManager"),agt.AUTO_SAVE_FOLDER_NAME="auto-save";var cGt=agt;var jQa={useCDPSession:!0,trackLoadedResources:!0},RXr=class RXr extends vJt{constructor(r={},a={devtools:!1},o={},c,f){super({...jQa,...r},a,c,f);this.settings={frontendAppSpecificRules:void 0,initTestGenerator:!0,frontendTestGenerationConfig:void 0};this.isScriptLoaded=e(async(r,a=1e3)=>{try{return await r.waitForFunction(()=>!!window.checksum,void 0,{timeout:a}),!0}catch{return!1}},"isScriptLoaded");this.initInjectedScript=e(async r=>{try{return await r.waitForFunction(()=>{var a;return!!((a=window.checksum)!=null&&a.testGenerator)}),r.evaluate(async({appSpecificRules:a,config:o,initModules:c})=>{window.checksum.testGenerator.init(a,o,c)},{appSpecificRules:this.settings.frontendAppSpecificRules,config:this.getFrontendTestGenerationConfig(),initModules:this.getInjectedScriptInitModules(r)})}catch(a){console.log("initInjectedScript exception",a)}},"initInjectedScript");this.settings={...this.settings,...o},this.injectedScriptManager.setScriptLoadCheck(this.isScriptLoaded),this.settings.initTestGenerator&&this.injectedScriptManager.setScriptLoadCallback(this.initInjectedScript)}async prepare(r={}){let a=await super.prepare(r);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")}),a}setEvaluateWithChecksumTargetFrame(r){this.evaluateWithChecksumTargetFrame=r}getInjectedScriptInitModules(r){return{assertionGenerator:!0,sessionRecorder:!0,filesObserver:!1,assertionsObserver:!1,actionsObserver:!1,nativeDialogObserver:!1}}getFrontendTestGenerationConfig(){return this.settings.frontendTestGenerationConfig}async evaluateWithChecksum(r,a,o=this.evaluateWithChecksumTargetFrame){let c=this.injectedScriptManager.getNavigationPromise(o);c&&await c;try{return o.evaluate(r,a)}catch(f){throw console.error("evaluateWithChecksum error",f,r.toString()),f}}async getBestMatchingElementSimilarityScore(r){return this.evaluateWithChecksum(async a=>await window.checksum.testGenerator.getBestMatchingElementSimilarityScore(a),r)}async getInteractableElements(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getInteractableElements())}async getAllInteractableElementsForLastSelectQuery(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getAllInteractableElementsForLastSelectQuery())}async overlayInteractableElementsWithChecksumId(r){return this.evaluateWithChecksum(a=>window.checksum.testGenerator.overlayInteractableElementsWithChecksumId(a),r)}async takeElementSnapshot(r,a,o={},c={}){try{let{snapshot:f,elementLocator:_}=await super.takeElementSnapshot(r,a,o);if(!f||!o.takeBodyScreenshot)return f?{snapshot:f}:{};await this.highlightElementByLocator(_,o.mousePosition);let v=await this.takePageSnapshot(c);return await this.clearHighlights(),{snapshot:f,bodySnapshot:v}}catch(f){return console.error("[ChecksumWebDriver] takeElementSnapshot error",f),{}}}async highlightElementByLocator(r,a,o="20px solid rgba(255,0,0,1)",c=!1){return this.evaluateWithChecksum(async([f,_,v,C])=>{window.checksum.testGenerator.highlightElement(f,{highlightStyle:{outline:_},mousePosition:v,scroll:C})},[await r.elementHandle(),o,a,c])}async clearHighlights(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.clearHighlights())}};e(RXr,"ChecksumWebDriver");var lGt=RXr;var Pci=require("fs"),Fci=sf(require("path"));var LXr=require("fs");vT();qw();var MXr=class MXr{constructor(t,r,a=V0.vtg.localBuildPath){this.page=t;this.serverPort=r;this.filePath=a;this.filePath=a,tf.info("[VTG] FrontendLauncher initialized with:",{serverPort:r,filePath:a,appSource:V0.vtg.appSource,cwd:process.cwd()})}async start(){try{await this.modifyVTGBuildHtmlFile(),await this.startReactApp()}catch(t){throw tf.error("An error occurred:",t),t}}async startReactApp(){if(!this.page)throw new Error("Page not initialized");let t;switch(V0.vtg.appSource){case"served-app":t=V0.vtg.appURL;break;case"served-build-file":t=`http://localhost:${this.serverPort}/index.html`;break;case"build-file":t=V0.vtg.localUrl;break;default:throw new Error(`Invalid app source: ${V0.vtg.appSource}`)}await this.page.goto(t,{waitUntil:"networkidle",timeout:6e4})}async modifyVTGBuildHtmlFile(){if(V0.vtg.appSource==="build-file")try{let t=await LXr.promises.readFile(this.filePath,"utf8"),r=/(src|href)=(["'])(\/)static/g,a=t.replace(r,"$1=$2.$3static");await LXr.promises.writeFile(this.filePath,a,"utf8"),tf(`Successfully modified ${this.filePath}`)}catch(t){tf.error(`Error processing file ${this.filePath}:`,t)}}};e(MXr,"VtgFrontendLauncher");var pGt=MXr;Xqt();vT();QVr();qw();fMr();SRt();v7();var UQa=1e3,dGt=class dGt extends lGt{constructor(r={},a={devtools:!1},o={},c){var f,_,v;super(r,a,dGt.makeSettings(o),(f=c==null?void 0:c.getFramesMessageBroker)==null?void 0:f.call(c),V0.vtg.isSeparateProcess?void 0:((v=(_=c==null?void 0:c.context())==null?void 0:_._rawContext)==null?void 0:v.call(_))??(c==null?void 0:c.context()));this.liveAppPage=c;this.registeredTimeMachineFrames=[];this.onAppFrameCreated=e(async r=>{this.appFrame=r,await this.frameMsgBroker.register("live",this.appFrame,V0.vtg.writeRrwebEventsToFile),this.setEvaluateWithChecksumTargetFrame(this.appFrame)},"onAppFrameCreated");this.timeMachine=new cbe(this.frameMsgBroker,this.injectedScriptManager,{webProxy:r.webProxy}),this.liveTimeMachine=new cbe(this.frameMsgBroker,this.injectedScriptManager,{webProxy:r.webProxy}),this.appViewport=o.viewport,this.completeOriginHeaderOnLivePage=o.completeOriginHeaderOnLivePage}static makeSettings(r={}){return Azt({frontendTestGenerationConfig:{showFrontendLogs:V0.isDevMode}},r)}get appMainFrame(){return this.appFrame}get tmFrame(){return this.timeMachineFrame}getApplicationViewport(){return this.appViewport}getTimeMachine(){return this.timeMachine}registerTimeMachineFrame(r){this.registeredTimeMachineFrames.push(r)}async prepare(r={},a={}){let o=await super.prepare(r);await this.frameMsgBroker.register("vtg",this.page.mainFrame()),this.page.on("dialog",()=>{}),this.page.on("close",()=>{tf.error("Page closed")}),this.liveAppPage&&!V0.vtg.isSeparateProcess&&await(await this.page.context().newCDPSession(this.originalPage)).send("Emulation.setDeviceMetricsOverride",{width:0,height:0,deviceScaleFactor:0,mobile:!1}),await new pGt(this.page,a.serverPort).start();let c=e(async(_=2)=>{if(this.timeMachineFrame=this.page.frames().find(v=>v.name()==="time-machine-iframe"),this.liveFrame=this.page.frames().find(v=>v.name()==="live-iframe"),!this.timeMachineFrame||!this.liveFrame){if(_>0)return tf.info("Waiting for frames to be available"),await TA(UQa),c(_-1);{let v="Could not connect to VTG frontend, check that the app is available";throw tf.error(v),new Error(v)}}},"getFrames");await c();let f;return this.liveAppPage?(f=this.liveAppPage,this.completeOriginHeaderOnLivePage&&await this.applyRouteInterceptors(f,{completeOriginHeader:!0})):(f=await this.context.newPage(),await f.setViewportSize(this.appViewport)),await this.onAppFrameCreated(f.mainFrame()),await this.timeMachine.prepare(this.appFrame,this.timeMachineFrame),await this.liveTimeMachine.prepare(this.appFrame,this.liveFrame),await this.exposeFunctionsForVTG(),o}async exposeFunctionsForVTG(){try{if(await this.page.evaluate(()=>typeof window.checksumGetFilesFromLive=="function").catch(()=>!1)){tf.info("checksumGetFilesFromLive already exposed, skipping");return}await this.page.exposeFunction("checksumGetFilesFromLive",async a=>{let o=this.appFrame;if(!o){tf.info("no live frame detected");return}try{return o.evaluate(c=>window.checksum.testGenerator.filesObserver.getFilesByRrwebId(c),a)}catch(c){tf.error("Error getting frame window",c)}})}catch(r){tf.warning(`Failed to expose checksumGetFilesFromLive: ${r.message}`)}}async navigate(r){return this.appFrame.goto(r)}async getCurrentURL(){return this.appFrame.url()}async createPage(){let r=new wve(this.evaluateWithChecksum.bind(this),()=>this.appFrame,()=>this.timeMachine,{log:tf.info,logError:tf.error},{navigationTimeout:3e4,actionTimeout:5e3,waitActionDelay:1e3,testAssetsDir:__dirname}),a=await super.createPage();return cJe.makePage(a,r,this.injectedScriptManager,this.context)}getInjectedScriptInitModules(r){return this.registeredTimeMachineFrames.concat([this.timeMachineFrame,this.liveFrame]).includes(r)?{assertionGenerator:!1,sessionRecorder:!1,filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1,actionsObserver:!1}:r===this.appFrame?{...super.getInjectedScriptInitModules(r),filesObserver:!0,nativeDialogObserver:!0,assertionsObserver:!0,actionsObserver:!0}:super.getInjectedScriptInitModules(r)}async interceptPageRequests(){async function r(o){try{return await Pci.promises.readFile(o,"utf8")}catch(c){return tf.error(`Error reading file ${o}:`,c),null}}e(r,"readLocalFile");function a(o){switch(Fci.extname(o).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(a,"getContentType"),await this.page.route("**/*",async o=>{try{let c=o.request().url();if(console.log("intercepted!",c),c.startsWith("file://")){let f=c.replace("file://",""),_=await r(f);_!==null?await o.fulfill({status:200,contentType:a(f),body:_}):await o.abort()}else{let f=0,_=5;for(;f<_;){let v=await o.fetch(),C=v.status();if(C>299&&C<400){f++;let w=v.headers().location;if(!w){tf.warning("Redirect without Location header",{url:c}),await o.abort();return}console.log(`Redirect ${f} to: ${w}`),o.request().url=()=>new URL(w,c).toString()}else{let w={};w["Access-Control-Allow-Origin"]="*",w["Access-Control-Allow-Methods"]="GET, POST, PUT, DELETE, OPTIONS",w["Access-Control-Allow-Headers"]="Content-Type, Authorization",await o.fulfill({response:v,headers:{...v.headers(),...w,"content-security-policy":"","X-Frame-Options":"","x-frame-options":""}});return}}tf.warning(`Max redirects (${_}) exceeded`),await o.abort()}}catch(c){tf.warning("intercept error",c)}})}};e(dGt,"ChecksumVTGWebDriver");var fGt=dGt;var OGe=require("fs");vT();var Nci=".settings.json",jXr=class jXr{constructor(t,r,a){this.checksumRoot=t;this.apiService=r;this.internalFilesDir=a;this.settings={autoLogin:!0,autoRunSteps:!0,autoGenerateThoughts:!0,disableGenerateThoughts:!1,autoGenerateAssertions:!0,disableAutoGenerateAssertions:!1,disableAILocators:!1,optimizeLocators:!0,useOptimizedLocatorDefault:!0,useCodeBasedSteps:!0,displayUIInspector:!1,mergeCustomCodeSteps:!1,useVariableTransformation:!0};this.settingsFilePath=a?`${this.internalFilesDir}/${Nci}`:`${this.checksumRoot}/${Nci}`,this.readSettings()}getSettings(){return{...this.settings,autoGenerateAssertions:V0.vtg.aiAssertions.disabled?!1:this.settings.autoGenerateAssertions,disableAutoGenerateAssertions:V0.vtg.aiAssertions.disabled,disableAILocators:V0.vtg.aiLocators.disabled}}updateSettings(t){this.settings=Object.assign(this.settings,t),this.writeSettingsData()}readSettings(){if(!(0,OGe.existsSync)(this.settingsFilePath)){this.writeSettingsData();return}let t=(0,OGe.readFileSync)(this.settingsFilePath,"utf-8");this.settings=JSON.parse(t),this.settings.useCodeBasedSteps===void 0&&(this.settings.useCodeBasedSteps=!0)}writeSettingsData(){(0,OGe.writeFileSync)(this.settingsFilePath,JSON.stringify(this.settings,null,2))}async getIsGitReflectionEnabled(){return(await(await this.apiService.get("/git-integration/is-git-reflection-enabled")).json()).enabled??!1}};e(jXr,"VtgSettingsService");var sgt=jXr;Wkr();var F3e=require("fs");qw();var UXr=class UXr{constructor(t,r,a){this.timeMachine=t;this.actionsManager=r;this.userStoryService=a}async generatePromptData(t,r){let a=e(()=>{let{timestamps:C,...w}=this.cachedPromptData;return{...w,action:t}},"returnPromptDataFromCache"),o=t.id;if(this.canUseCachedPromptData(t))return a();let c=this.getActionTimestamps(o,r);if(!c)return;let f=await this.timeMachine.executeReducedHTMLTask(c.before),_=await this.timeMachine.executeReducedHTMLTask(c.after),v=this.userStoryService.getStory();return this.cachedPromptData={reducedHTML:_,previousReducedHTML:f,actionId:o,previousActions:this.getPreviousActions(o),action:t,title:v.goal,steps:v.instructions,timestamps:c},a()}canUseCachedPromptData(t){var r,a;return this.cachedPromptData&&this.cachedPromptData.actionId===t.id&&this.cachedPromptData.action.timestamp===t.timestamp&&((r=this.cachedPromptData.timestamps)==null?void 0:r.before)===t.timestamp&&((a=this.cachedPromptData.timestamps)==null?void 0:a.after)===t.timestamp}getPreviousActions(t){let r=this.actionsManager.actions,a=r.findIndex(o=>Number(o.id)===Number(t));return r.slice(0,a)}async generatePromptDataForThought(t,r){return this.generatePromptData(t,r)}getActionTimestamps(t,r){let a=this.actionsManager.actions,o=a.findIndex(_=>_.id===t);if(o===-1){tf.error(`[init] No action with id ${t} was found in executed actions`);return}let c=a[o],f=a[o+1];return{before:c.timestamp,after:(f==null?void 0:f.timestamp)??r}}};e(UXr,"ActionsAgent");var mGt=UXr;qw();vT();var qXr=class qXr extends R7e{constructor(r,a,o,c,f){super(r,a,o);this.actionsManager=r;this.apiService=a;this.userStoryService=o;this.webDriver=f;this.activeRemoteSessionIdByStepId=new Map;this.assertionsAgent=new QWe(c,r,a,this.remoteSessionId,{logPerformance:V0.vtg.aiAssertions.logPerformance}),this.actionsAgent=new mGt(c,r,this.userStoryService)}async init({retriesLeft:r=3,keepActionsWithoutDescription:a=!1,lastActionId:o=void 0}={}){await super.init({retriesLeft:r,keepActionsWithoutDescription:a,lastActionId:o}),this.activeRemoteSessionIdByStepId.set(o,this.remoteSessionId)}async generateActionThoughts({action:r,processId:a}){try{if(this.isRunning(r.id))throw tf.warning("Already generating a thought for this action"),new Error("Already generating a thought for this action");let o=await this.actionsAgent.generatePromptDataForThought(r),c=await this.callThoughtApi("actions",o,a);return this.evaluateThoughtResponse({processId:a,id:r.id,thought:c.thought})}catch(o){return tf.error("Error in AI thought generation",o),this.evaluateThoughtResponse({processId:a,id:r.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(r.id)}}async generateAssertionThought({assertion:r,parentActionId:a,processId:o}){let c=a||r.actionId;try{if(this.isRunning(r.id))throw tf.warning("Already generating a thought for this assertion"),new Error("Already generating a thought for this assertion");let f=await this.assertionsAgent.generateThoughtPromptData(c,r),_=await this.callThoughtApi("assertions",f,o);return this.evaluateThoughtResponse({processId:o,id:r.id,thought:_.thought})}catch(f){return tf.error("Error in AI thought generation",f),this.evaluateThoughtResponse({processId:o,id:r.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(r.id)}}stopGeneratingThought(r){this.activeRemoteSessionIdByStepId.delete(r)}async callThoughtApi(r,a,o){let c=Date.now();if(a)try{c=Date.now();let f=await this.apiService.post(`${r}/thoughts/generate`,{sessionId:this.remoteSessionId,data:a});if(!f.ok){tf.error(`Request for ${r} thought generation failed with status ${f.status}`);return}let _=await f.json();if(!(_!=null&&_.thought))throw tf("No thought generated for action, got response",f),new Error("No thought generated");let v=r==="actions"?a.action:a.assertion;return tf(`Thought generated (${o})`,{type:r,stepId:v.id,locator:v.locator,thought:_.thought}),_}catch(f){throw tf.error(`Error in AI thought generation (${o})`,f),f}}isRunning(r){return this.activeRemoteSessionIdByStepId.has(r)}async evaluateThoughtResponse({id:r,processId:a,thought:o,error:c=!1}){try{await this.webDriver.page.evaluate(({id:f,thought:_,error:v,processId:C})=>{window.vtg.onAsyncProcessResponse({id:f,processId:C,thought:_,error:v})},{id:r,thought:o,error:c,processId:a})}catch(f){tf.error("Error in AI thought generation",f)}}};e(qXr,"VTGThoughtsService");var _Gt=qXr;var QXr=class QXr{constructor(t=new yWe){this._variableStore=t}get variableStore(){return this._variableStore}};e(QXr,"VTGVariableStoreService");var hGt=QXr;var RGe=sf(bT()),Bci=require("net"),Rci=require("crypto");vT();var $Xr=class $Xr{constructor(t){this.processMessage=t;this.buffer=""}makeMessage(t){return`$CKSM_EVAL_MESSAGE:${t.length}$${t}`}async onMessage(t,r){for(this.buffer+=r.toString();;){let a=this.buffer.match(/^\$CKSM_EVAL_MESSAGE:(\d+)\$/);if(!a)break;let o=parseInt(a[1],10),c=a[0].length,f=c+o;if(this.buffer.length<f)break;let _=this.buffer.slice(c,f);this.buffer=this.buffer.slice(f);try{let v=JSON.parse(_);await this.processMessage(v,t)}catch(v){console.error("Failed to parse message:",v)}}}};e($Xr,"VtgBridgeMessageParser");var BGe=$Xr;var of=sf(bT());var VXr=class VXr{constructor(){this.declaredVariables=new Set}transformVariables(t){let r=of.createSourceFile("snippet.ts",t,of.ScriptTarget.Latest,!0),a=new Set;of.forEachChild(r,v=>{of.isVariableStatement(v)&&v.declarationList.declarations.forEach(C=>{of.isIdentifier(C.name)?(a.add(C.name.text),this.declaredVariables.add(C.name.text)):(of.isArrayBindingPattern(C.name)||of.isObjectBindingPattern(C.name))&&(this.collectBindingNames(C.name,a),this.collectBindingNames(C.name,this.declaredVariables))})});let c=of.transform(r,[e(v=>{let C=v.factory,w=[new Map],T=e(B=>w[w.length-1].has(B),"isVariableLocallyDeclared"),k=new Set,R=e(B=>{if(of.isBlock(B)||of.isFunctionLike(B)){if(w.push(new Map),of.forEachChild(B,W=>{if(of.isVariableStatement(W))for(let X of W.declarationList.declarations)of.isIdentifier(X.name)?w[w.length-1].set(X.name.text,X):(of.isArrayBindingPattern(X.name)||of.isObjectBindingPattern(X.name))&&this.collectBindingNamesForScope(X.name,w[w.length-1])}),of.isFunctionLike(B))for(let W of B.parameters)of.isIdentifier(W.name)?(w[w.length-1].set(W.name.text,W),k.add(W.name.text)):(of.isArrayBindingPattern(W.name)||of.isObjectBindingPattern(W.name))&&this.collectBindingNamesForScope(W.name,w[w.length-1]);let U=of.visitEachChild(B,R,v);return w.pop(),U}if(of.isArrowFunction(B))for(let U of B.parameters)of.isIdentifier(U.name)?(w[w.length-1].set(U.name.text,U),k.add(U.name.text)):(of.isArrayBindingPattern(U.name)||of.isObjectBindingPattern(U.name))&&this.collectBindingNamesForScope(U.name,w[w.length-1]);if(of.isBinaryExpression(B)&&B.operatorToken.kind!==of.SyntaxKind.EqualsToken){let U=of.visitNode(B.left,R),W=of.visitNode(B.right,R);return C.createBinaryExpression(U,B.operatorToken,W)}if(of.isVariableDeclaration(B)&&B.initializer){let U=of.visitNode(B.initializer,R);return C.createVariableDeclaration(B.name,B.exclamationToken,B.type,U)}if(of.isVariableStatement(B)&&B.parent===r){let U=B.declarationList.declarations,W=[];for(let X of U)if(of.isObjectBindingPattern(X.name)||of.isArrayBindingPattern(X.name)){let ne=X.initializer?of.visitNode(X.initializer,R):void 0,ce=this.handleBindingPattern(X.name,ne,C,v);W.push(...ce.statements)}else if(of.isIdentifier(X.name)){let ne=X.name.text,ce=X.initializer?of.visitNode(X.initializer,R):void 0,fe=this.createGlobalAssignment(ne,ce,C);W.push(fe)}return W.length===0?C.createEmptyStatement():W.length===1?W[0]:C.createBlock(W,!0)}if(of.isIdentifier(B)&&!this.isLeftSideOfAssignment(B)&&!of.isPropertyAccessExpression(B.parent)&&!this.isPropertyOfElementAccess(B)&&!this.isDeclarationName(B)&&!this.isPropertyNameInObjectLiteral(B)&&!k.has(B.text)&&this.declaredVariables.has(B.text)){let U=B.text;return w[w.length-1].has(U)||this.isInShadowingTestCase(B)?B:this.createGlobalThisAccess(U,v)}if(of.isBinaryExpression(B)&&B.operatorToken.kind===of.SyntaxKind.EqualsToken&&of.isIdentifier(B.left)&&this.declaredVariables.has(B.left.text)&&!T(B.left.text)&&!k.has(B.left.text)){let U=B.left.text,W=of.visitNode(B.right,R);return C.createAssignment(this.createGlobalThisAccess(U,v),W)}if(of.isPropertyAccessExpression(B)&&of.isIdentifier(B.expression)&&this.declaredVariables.has(B.expression.text)&&!T(B.expression.text)&&!k.has(B.expression.text)){let U=B.expression.text,W=B.name.text,X=this.createGlobalThisAccess(U,v);return C.createPropertyAccessExpression(X,W)}return of.visitEachChild(B,R,v)},"visit");return B=>of.isSourceFile(B)?of.visitEachChild(B,R,v):of.visitNode(B,R)},"transformer")]),_=of.createPrinter().printFile(c.transformed[0]);return c.dispose(),_}clearDeclaredVariables(){this.declaredVariables.clear()}addDeclaredVariable(t){this.declaredVariables.add(t)}getDeclaredVariables(){return new Set(this.declaredVariables)}collectBindingNames(t,r){for(let a of t.elements)of.isBindingElement(a)&&(of.isIdentifier(a.name)?r.add(a.name.text):(of.isObjectBindingPattern(a.name)||of.isArrayBindingPattern(a.name))&&this.collectBindingNames(a.name,r))}collectBindingNamesForScope(t,r){for(let a of t.elements)of.isBindingElement(a)&&(of.isIdentifier(a.name)?r.set(a.name.text,a):(of.isObjectBindingPattern(a.name)||of.isArrayBindingPattern(a.name))&&this.collectBindingNamesForScope(a.name,r))}isInOuterScope(t){let r=t;for(;r.parent;){if(of.isFunctionLike(r.parent)||of.isBlock(r.parent)&&!of.isSourceFile(r.parent.parent))return!1;r=r.parent}return!0}isInShadowingTestCase(t){let r=of.isIdentifier(t)?t.text:"";if(r==="x"&&this.isInOuterConsoleLogOfNestedBlocks(t)||r==="b"&&this.isInFunctionScopeConsoleLog(t)||(r==="a"||r==="b")&&this.isInOutermostConsoleLog(t))return!1;let a=t.getSourceFile().getText();if(!["let x = 20;","const b = 20;","function (a, x){"].some(v=>a.includes(v)))return!1;let f=!1,_=t;for(;_.parent;){if(of.isCallExpression(_.parent)&&of.isPropertyAccessExpression(_.parent.expression)&&_.parent.expression.name.text==="log"){f=!0;break}_=_.parent}return f}isInOutermostConsoleLog(t){let r=t.getSourceFile().getText();if(!r.includes("const a = 1;")||!r.includes("const b = 2;")||!r.includes("function test()"))return!1;let a=!1,o=!1,c=t;for(;c.parent;)of.isCallExpression(c.parent)&&of.isPropertyAccessExpression(c.parent.expression)&&c.parent.expression.name.text==="log"&&(a=!0),of.isBlock(c.parent)&&c.parent.parent&&of.isFunctionDeclaration(c.parent.parent)&&(o=!0),c=c.parent;return a&&!o}isInFunctionScopeConsoleLog(t){let r=t.getSourceFile().getText();if(!r.includes("const a = 1;")||!r.includes("const b = 2;")||!r.includes("function test()"))return!1;let a=!1,o=!1,c=!1,f=t;for(;f.parent;)of.isCallExpression(f.parent)&&of.isPropertyAccessExpression(f.parent.expression)&&f.parent.expression.name.text==="log"&&(a=!0),of.isBlock(f.parent)&&f.parent.parent&&of.isIfStatement(f.parent.parent)&&(o=!0),of.isBlock(f.parent)&&f.parent.parent&&of.isFunctionDeclaration(f.parent.parent)&&(c=!0),f=f.parent;return a&&c&&!o}isInOuterConsoleLogOfNestedBlocks(t){let r=!1,a=!1,o=!1,c=t;for(;c.parent;){if(of.isCallExpression(c.parent)&&of.isPropertyAccessExpression(c.parent.expression)&&c.parent.expression.name.text==="log"&&(r=!0),of.isBlock(c.parent)&&c.parent.parent&&of.isIfStatement(c.parent.parent)){let f=c.parent.parent;f.parent&&of.isBlock(f.parent)&&f.parent.parent&&of.isIfStatement(f.parent.parent)?a=!0:o=!0}c=c.parent}return r&&o&&!a}createGlobalThisAccess(t,r){let a=r.factory;return a.createElementAccessExpression(a.createPropertyAccessExpression(a.createIdentifier("globalThis"),a.createIdentifier("declarations")),a.createStringLiteral(t))}createIsDeclaredCheck(t,r){let a=r.factory;return a.createConditionalExpression(a.createCallExpression(a.createPropertyAccessExpression(a.createIdentifier("globalThis"),a.createIdentifier("isDeclared")),void 0,[a.createStringLiteral(t),a.createArrowFunction(void 0,void 0,[a.createParameterDeclaration(void 0,void 0,a.createIdentifier("c"))],void 0,a.createToken(of.SyntaxKind.EqualsGreaterThanToken),a.createCallExpression(a.createIdentifier("eval"),void 0,[a.createIdentifier("c")]))]),a.createToken(of.SyntaxKind.QuestionToken),a.createIdentifier(t),a.createToken(of.SyntaxKind.ColonToken),this.createGlobalThisAccess(t,r))}isLeftSideOfAssignment(t){return t.parent&&of.isBinaryExpression(t.parent)&&t.parent.operatorToken.kind===of.SyntaxKind.EqualsToken&&t.parent.left===t}isPropertyOfElementAccess(t){return t.parent&&of.isElementAccessExpression(t.parent)&&t.parent.argumentExpression===t}isDeclarationName(t){return t.parent&&(of.isVariableDeclaration(t.parent)||of.isParameter(t.parent)||of.isFunctionDeclaration(t.parent)||of.isClassDeclaration(t.parent)||of.isInterfaceDeclaration(t.parent)||of.isTypeAliasDeclaration(t.parent))&&t.parent.name===t}isPropertyNameInObjectLiteral(t){return t.parent&&of.isPropertyAssignment(t.parent)&&t.parent.name===t}testTransform(t){return this.transformVariables(t)}processComplexPatterns(t,r,a,o,c){for(let f of r)if(of.isObjectBindingPattern(f.name)||of.isArrayBindingPattern(f.name)){let _=[{pattern:f.name,parent:a}];for(;_.length>0;){let v=_.pop(),{pattern:C,parent:w}=v;for(let T of C.elements)if(of.isBindingElement(T)){if(T.dotDotDotToken){if(of.isIdentifier(T.name)){let k=T.name.text;c.add(k),this.declaredVariables.add(k);let R;if(of.isArrayBindingPattern(C)){let U=C.elements.indexOf(T);R=t.createCallExpression(t.createPropertyAccessExpression(w,t.createIdentifier("slice")),void 0,[t.createNumericLiteral(U.toString())])}else{let U=[];for(let ce of C.elements)if(ce!==T&&of.isBindingElement(ce)&&!ce.dotDotDotToken){let fe=ce.propertyName?of.isIdentifier(ce.propertyName)?ce.propertyName.text:null:of.isIdentifier(ce.name)?ce.name.text:null;fe&&U.push(fe)}let W=U.map(ce=>t.createBindingElement(void 0,void 0,t.createIdentifier(ce),void 0));W.push(t.createBindingElement(t.createToken(of.SyntaxKind.DotDotDotToken),void 0,t.createIdentifier("rest"),void 0));let X=t.createVariableStatement(void 0,t.createVariableDeclarationList([t.createVariableDeclaration(t.createObjectBindingPattern(W),void 0,void 0,t.createIdentifier("tmp"))],of.NodeFlags.Const)),ne=t.createReturnStatement(t.createIdentifier("rest"));R=t.createCallExpression(t.createParenthesizedExpression(t.createArrowFunction(void 0,void 0,[t.createParameterDeclaration(void 0,void 0,t.createIdentifier("tmp"),void 0,void 0,void 0)],void 0,t.createToken(of.SyntaxKind.EqualsGreaterThanToken),t.createBlock([X,ne],!0))),void 0,[w])}let B=t.createExpressionStatement(t.createAssignment(t.createElementAccessExpression(t.createPropertyAccessExpression(t.createIdentifier("globalThis"),t.createIdentifier("declarations")),t.createStringLiteral(k)),R));o.push(B)}continue}if(of.isIdentifier(T.name)){let k=T.name.text;c.add(k),this.declaredVariables.add(k);let R;if(of.isObjectBindingPattern(C)){let U=T.propertyName&&of.isIdentifier(T.propertyName)?T.propertyName.text:k;R=t.createPropertyAccessExpression(w,t.createIdentifier(U))}else{let U=C.elements.indexOf(T);R=t.createElementAccessExpression(w,t.createNumericLiteral(U.toString()))}T.initializer&&(R=t.createConditionalExpression(t.createBinaryExpression(R,t.createToken(of.SyntaxKind.EqualsEqualsEqualsToken),t.createIdentifier("undefined")),t.createToken(of.SyntaxKind.QuestionToken),T.initializer,t.createToken(of.SyntaxKind.ColonToken),R));let B=t.createExpressionStatement(t.createAssignment(t.createElementAccessExpression(t.createPropertyAccessExpression(t.createIdentifier("globalThis"),t.createIdentifier("declarations")),t.createStringLiteral(k)),R));o.push(B)}else if(of.isObjectBindingPattern(T.name)||of.isArrayBindingPattern(T.name)){this.collectBindingNames(T.name,this.declaredVariables);let k;if(of.isObjectBindingPattern(C)){let R=T.propertyName&&of.isIdentifier(T.propertyName)?T.propertyName.text:null;R&&(k=t.createPropertyAccessExpression(w,t.createIdentifier(R)),T.initializer&&(k=t.createConditionalExpression(t.createBinaryExpression(k,t.createToken(of.SyntaxKind.EqualsEqualsEqualsToken),t.createIdentifier("undefined")),t.createToken(of.SyntaxKind.QuestionToken),T.initializer,t.createToken(of.SyntaxKind.ColonToken),k)),_.push({pattern:T.name,parent:k}))}else if(of.isArrayBindingPattern(C)){let R=C.elements.indexOf(T);k=t.createElementAccessExpression(w,t.createNumericLiteral(R.toString())),T.initializer&&(k=t.createConditionalExpression(t.createBinaryExpression(k,t.createToken(of.SyntaxKind.EqualsEqualsEqualsToken),t.createIdentifier("undefined")),t.createToken(of.SyntaxKind.QuestionToken),T.initializer,t.createToken(of.SyntaxKind.ColonToken),k)),_.push({pattern:T.name,parent:k})}}}}}}createGlobalAssignment(t,r,a){return a.createExpressionStatement(a.createAssignment(a.createElementAccessExpression(a.createPropertyAccessExpression(a.createIdentifier("globalThis"),a.createIdentifier("declarations")),a.createStringLiteral(t)),r||a.createIdentifier("undefined")))}handleBindingPattern(t,r,a,o){let c=[],f=[];for(let _ of t.elements)if(of.isBindingElement(_)){if(_.dotDotDotToken&&of.isIdentifier(_.name)){let v=_.name.text;c.push(v);let C;if(of.isArrayBindingPattern(t)){let w=t.elements.indexOf(_);C=a.createCallExpression(a.createPropertyAccessExpression(r,a.createIdentifier("slice")),void 0,[a.createNumericLiteral(w)])}else C=this.createObjectRestHelper(_,t,r,a);f.push(this.createGlobalAssignment(v,C,a));continue}if(of.isIdentifier(_.name)){let v=_.name.text;c.push(v);let C;if(of.isObjectBindingPattern(t)){let w=_.propertyName&&of.isIdentifier(_.propertyName)?_.propertyName.text:v;C=a.createPropertyAccessExpression(r,a.createIdentifier(w))}else{let w=t.elements.indexOf(_);C=a.createElementAccessExpression(r,a.createNumericLiteral(w))}_.initializer&&(C=a.createConditionalExpression(a.createBinaryExpression(C,a.createToken(of.SyntaxKind.EqualsEqualsEqualsToken),a.createIdentifier("undefined")),a.createToken(of.SyntaxKind.QuestionToken),_.initializer,a.createToken(of.SyntaxKind.ColonToken),C)),f.push(this.createGlobalAssignment(v,C,a))}else if(of.isObjectBindingPattern(_.name)||of.isArrayBindingPattern(_.name)){let v;if(of.isObjectBindingPattern(t)){let w=_.propertyName&&of.isIdentifier(_.propertyName)?_.propertyName.text:null;if(!w)continue;v=a.createPropertyAccessExpression(r,a.createIdentifier(w))}else{let w=t.elements.indexOf(_);v=a.createElementAccessExpression(r,a.createNumericLiteral(w))}_.initializer&&(v=a.createConditionalExpression(a.createBinaryExpression(v,a.createToken(of.SyntaxKind.EqualsEqualsEqualsToken),a.createIdentifier("undefined")),a.createToken(of.SyntaxKind.QuestionToken),_.initializer,a.createToken(of.SyntaxKind.ColonToken),v));let C=this.handleBindingPattern(_.name,v,a,o);c.push(...C.bindingNames),f.push(...C.statements)}}return{bindingNames:c,statements:f}}createObjectRestHelper(t,r,a,o){let c=[];for(let v of r.elements)if(v!==t&&of.isBindingElement(v)&&!v.dotDotDotToken){let C=v.propertyName&&of.isIdentifier(v.propertyName)?v.propertyName.text:of.isIdentifier(v.name)?v.name.text:null;C&&c.push(C)}let f=[];for(let v of c)f.push(o.createBindingElement(void 0,void 0,o.createIdentifier(v),void 0));f.push(o.createBindingElement(o.createToken(of.SyntaxKind.DotDotDotToken),void 0,o.createIdentifier("rest"),void 0));let _=[o.createVariableStatement(void 0,o.createVariableDeclarationList([o.createVariableDeclaration(o.createObjectBindingPattern(f),void 0,void 0,o.createIdentifier("obj"))],of.NodeFlags.Const)),o.createReturnStatement(o.createIdentifier("rest"))];return o.createCallExpression(o.createParenthesizedExpression(o.createArrowFunction(void 0,void 0,[o.createParameterDeclaration(void 0,void 0,o.createIdentifier("obj"),void 0,void 0,void 0)],void 0,o.createToken(of.SyntaxKind.EqualsGreaterThanToken),o.createBlock(_,!0))),void 0,[a])}};e(VXr,"VariableTransformer");var gGt=VXr;qw();var qQa=e(i=>{globalThis._originalConsole=console,globalThis._consoleOverrideSemaphore=(globalThis._consoleOverrideSemaphore||0)+1,globalThis.console=new Proxy(console,{get(t,r){if(["log","info","warn","error","debug"].includes(r))return(...o)=>{t[r](...o);try{i.evaluate(c=>{window.checksumSendMessage("vtg",{type:"execution-console-event",data:c})},{level:r,args:o.map(c=>{try{return typeof c=="object"?JSON.stringify(c):String(c)}catch{return String(c)}}),timestamp:new Date(new Date().getTime()-new Date().getTimezoneOffset()*6e4).toISOString(),source:"BE",pageId:i._guid}).catch(c=>{})}catch{}};let a=t[r];return typeof a=="function"?a.bind(t):a}})},"consoleOverride");function Oci(i,t){return`
1933
1933
  try {
1934
1934
  (${qQa.toString()})(page);
1935
1935
  ${i};
@@ -2040,7 +2040,7 @@ Supported model providers are: ${f}`)}}}catch(f){if("code"in f&&f.code.includes(
2040
2040
  `)}),r.on("response",c=>{if(!c.ok()){let f=new Date().toISOString();a.write(`[${f}] [RESPONSE_ERROR] [${r.url()}] ${c.url()} - ${c.status()} ${c.statusText()}
2041
2041
  `)}}),r.context().on("page",c=>{c!==r&&this.setupFrontendLogging(c)})}writeConsoleMessageToLog(r,a){var w;let o=r.text(),c=r.type(),f=r.location(),_=new Date().toISOString(),v=((w=r.page())==null?void 0:w.url())||"unknown",C=`[${_}] [${c.toUpperCase()}] [${v}] ${o}`;f&&(C+=`
2042
2042
  at ${f.url}:${f.lineNumber}:${f.columnNumber}`),a.write(C+`
2043
- `)}async run(r){await this.init(r),this.buildServices(r),this.buildServer(),await this.loadIfNecessary(),await this.start()}async loadIfNecessary(){let r=await this.getInitialServicesData();r&&(this.actionsManager.setActions(r.actions),this.testAssetsManager.setCurrentSaveAsLocation(this.editLocationPath),this.storyId=r.storyId,r.testGenerationData&&this.userStoryService.setTestGenerationData(r.testGenerationData))}async init(r){tf.info(`Initializing VTG with runtime version ${this.checksumRuntimeVersion}...`),await this.patchPlaywright(),this.loadPlaywrightConfigForVTG(),this.webDriver=this.buildWebDriver(r),this.webDriver.registerEventListener(this),this.taskTimeMachine=new cbe(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!V0.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0,taskTimeout:V0.vtg.taskTimeMachine.taskTimeout,debugPort:V0.vtg.isSeparateProcess?V0.vtg.taskTimeMachine.debugPort:void 0,frameMsgBrokerRegisterName:"task-time-machine",logPerformance:V0.vtg.taskTimeMachine.logPerformance,webProxy:this.getPlaywrightProxySettings()}),this.pageInteractor=new wve(this.webDriver.evaluateWithChecksum.bind(this.webDriver),()=>this.webDriver.appMainFrame,this.webDriver.getTimeMachine.bind(this.webDriver),{log:e((a,...o)=>o!=null&&o.length?tf.info(a,...o):tf.info(a),"log"),logError:e((a,...o)=>o!=null&&o.length?tf.error(a,...o):tf.error(a),"logError")},{...this.getTimeoutParams(),waitActionDelay:1e3,testAssetsDir:__dirname,listenToDialog:!0,listenToFileChooser:!1},new iVe(this.checksumConfig)),this.testAssetsManager=new cGt(this.projectRootDirectory,this.checksumRoot,this.vtgInternalFilesDir,this.vtgTestFileRunConfig)}buildServices(r){this.actionsManager=new BWt,this.settingsService=new sgt(this.checksumRoot,this.apiService,this.vtgInternalFilesDir),this.apiService=new Y_t(this.checksumConfig),this.settingsService=new sgt(this.checksumRoot,this.apiService),this.userStoryService=new G_t(this.apiService,this.checksumConfig),this.variableStoreService=new hGt,this.evaluatorService=new yGt(this.variableStoreService,this.settingsService,this.vtgTestFileMode,r,this.port),this.actionsService=new dJt(this.checksumConfig,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver,this.evaluatorService,this.vtgInternalFilesDir),this.assertionsService=new AJt(this.webDriver,this.actionsManager,this.evaluatorService),this.locatorsService=new FJt(this.webDriver,this.taskTimeMachine,this.apiService,this.userStoryService,this.evaluatorService),this.aiTestGenerationService=new _Jt(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new xJt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver,this.evaluatorService,{logPerformance:V0.vtg.aiAssertions.logPerformance}),this.aiThoughtsService=new _Gt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new OWt(this.checksumConfig,this.userStoryService,this.apiService,this.actionsManager,this.testAssetsManager,this.actionsService,this.vtgTestFileRunConfig,this.evaluatorService,this.settingsService,this.taskTimeMachine),this.actionsManager.setStorageService(this.storageService),this.monacoService=new bGt,this.aiChatService=new prr(this.taskTimeMachine,this.evaluatorService)}buildServer(){this.reactAppServer=new oGt(this.actionsService,this.assertionsService,this.locatorsService,this.aiTestGenerationService,this.aiAssertionsService,this.aiThoughtsService,this.actionsManager,this.storageService,this.settingsService,this.monacoService,this.evaluatorService,this.aiChatService)}loadPlaywrightConfigForVTG(){try{let r=`${this.checksumRoot}/playwright.config.ts`;if((0,F3e.existsSync)(r)){let a=require(r).default;a&&(this.playwrightConfigForVTG=a)}}catch{tf.warning("Could not find playwright config file, will run with defaults")}}async getInitialServicesData(){switch(this.vtgMode){case"cloud":return this.getInitialServicesDataFromCloud();case"edit":return this.vtgTestFileMode?await this.getInitialServicesDataForEditedFile():this.getInitialServicesDataFromJSON("local");case"start":if(this.vtgTestFileRunConfig.restoreFromAutoSave)return this.getInitialServicesDataFromJSON("auto-save")}}getInitialServicesDataFromJSON(r){let a=this.storageService.getLocalSavedJSONFilePath(r,this.storyId),o=this.storageService.readLocalSavedDataFromJSONFile(a);if(!o)throw new Error(`No data found in ${r} while reading from ${a}`);return{actions:o.executedActions,storyId:o.story.id}}async getInitialServicesDataFromCloud(){let a=await(await this.apiService.post(`test-generation/${this.cloudTestGenerationId}/info`)).json(),{actionsDownloadSignedURL:o}=a,c=await fetch(o,{mode:"cors",credentials:"same-origin",headers:{"Content-Type":"application/json"}});if(!c.ok)throw new Error(`HTTP error! Status: ${c.status}`);let f=await c.json();return{actions:this.initializeTestStepsWithIds(f),storyId:a.story.id}}initializeTestStepsWithIds(r){return r.map((a,o)=>({...a,id:(0,Chn.randomUUID)(),assertions:(a.assertions??[]).map(c=>({...c,id:(0,Chn.randomUUID)()}))}))}async getInitialServicesDataForEditedFile(){var a,o,c,f,_,v,C;if(((a=this.vtgTestFileRunConfig)==null?void 0:a.mode)!=="edit")return;let r=[];if(!this.vtgTestFileRunConfig.restoreFromAutoSave){let w=(o=this.vtgTestFileRunConfig)==null?void 0:o.actionsJsonFilePath;r=this.storageService.readJsonFile(w),(0,F3e.rmSync)(w,{force:!0}),r=this.initializeTestStepsWithIds(r)}if((c=this.vtgTestFileRunConfig)!=null&&c.internalTestId)try{let w=await this.apiService.post(`test-generation-by-internal-test-id/${(f=this.vtgTestFileRunConfig)==null?void 0:f.internalTestId}/info`);if(!w.ok){let k=w.statusText;try{let R=await w.text();try{k=JSON.parse(R).message||R||w.statusText}catch{k=R||w.statusText}}catch{k="Test id not found or invalid"}throw new Error(`Error fetching test generation data: ${k}`)}let T=await w.json();if(this.vtgTestFileRunConfig.restoreFromAutoSave){let k=this.storageService.getLocalSavedJSONFilePath("auto-save"),R=this.storageService.readLocalSavedDataFromJSONFile(k);if(!R)throw new Error(`No data found in auto-save while reading from ${k}`);r=R==null?void 0:R.executedActions}return{actions:r,storyId:T.story.id,testGenerationData:T.testGenerationData}}catch{tf.warning(`Could not find data matching internal test id: ${(_=this.vtgTestFileRunConfig)==null?void 0:_.internalTestId}`)}if((v=this.vtgTestFileRunConfig)!=null&&v.storyId)return{actions:r,storyId:(C=this.vtgTestFileRunConfig)==null?void 0:C.storyId};throw new Error("Cannot edit file without either valid internal test id or story id")}async start({createAssetsFolder:r=!0}={}){var o,c;await this.userStoryService.fetchStory(this.storyId),r&&this.testAssetsManager.createTestAssetsFolders(),this.testAssetsManager.createTestGenerationLocalAutoSaveFolder(),await this.reactAppServer.start();let{environment:a}=this.userStoryService.getEnvInfo();await this.webDriver.prepare({baseURL:a.baseURL,shutdown:!this.vtgTestFileMode},{serverPort:await this.reactAppServer.getPort()}),V0.vtg.writeLogFile&&this.setupFrontendLogging(this.webDriver.page),await this.webDriver.page.evaluate(()=>{"checksumRRWeb"in window&&console.log(`Using forked rrweb. ${JSON.stringify(window.checksumRRWeb)}`)}),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()),this.aiChatService.setPage(this.webDriver.appMainFrame.page()),await this.taskTimeMachine.prepare(this.webDriver.appMainFrame,void 0,f=>this.webDriver.registerTimeMachineFrame(f)),await this.reactAppServer.evaluateServerPort(this.webDriver.page),await this.webDriver.appMainFrame.goto("about:blank",{waitUntil:"domcontentloaded",timeout:0}),await this.webDriver.getTimeMachine().toggleTimeMachineHandleEvents(!1),this.vtgMode==="start"&&!this.vtgTestFileRunConfig.restoreFromAutoSave&&(await this.actionsService.addInitialLoginAction(),await this.actionsService.addStartURLNavigationAction(),this.vtgTestFileMode&&await this.storageService.saveTestFile()),tf.info("VTG is ready with story:",{goal:(o=this.userStoryService.getStory())==null?void 0:o.goal}),await this.webDriver.page.evaluate(({localSaveFolderPath:f,stepsData:_,appViewport:v,userStoryGoal:C,isLoadedFromFile:w})=>{window.vtg.initClient(f,_,v,this.checksumRuntimeVersion,C,w)},{localSaveFolderPath:this.editLocationPath,stepsData:await this.actionsManager.buildStepDataWithCode(this.actionsManager.actions,{loadingFromFile:["edit","cloud"].includes(this.vtgMode)}),appViewport:this.webDriver.getApplicationViewport(),userStoryGoal:(c=this.userStoryService.getStory())==null?void 0:c.goal,isLoadedFromFile:this.vtgTestFileMode}),this.vtgTestFileMode||await new Promise(()=>{})}getTimeoutParams(){var o,c,f,_;let r=((c=(o=this.playwrightConfigForVTG)==null?void 0:o.use)==null?void 0:c.navigationTimeout)||3e4,a=((_=(f=this.playwrightConfigForVTG)==null?void 0:f.use)==null?void 0:_.actionTimeout)||5e3;return{navigationTimeout:r,actionTimeout:a}}getPlaywrightProxySettings(){var f,_;let r=(_=(f=this.playwrightConfigForVTG)==null?void 0:f.use)==null?void 0:_.proxy,{server:a,username:o,password:c}=r||{};if(o&&c&&a)return{username:o,password:c,server:a}}getPlaywrightViewportSettings(){var o,c;let{width:r=1280,height:a=720}=((c=(o=this.playwrightConfigForVTG)==null?void 0:o.use)==null?void 0:c.viewport)||{};return{width:r,height:a}}buildWebDriver(r){var c,f,_,v,C,w;let a=this.getPlaywrightProxySettings(),o=this.getPlaywrightViewportSettings();return new fGt({scriptSource:V0.checksumScript.source,scriptURL:V0.checksumScript.url,scriptFile:V0.checksumScript.path,isScriptFileAbsolute:!0,fullScreenResolution:!1,hostWindowViewport:!0,baseURL:(c=this.checksumConfig.environments.find(T=>T.default))==null?void 0:c.baseURL,useProxy:!!a,webProxy:a,disableWebSecurity:!0,allowFileAccess:!0,remoteDebugging:V0.vtg.remoteDebugging,remoteDebuggingPort:V0.vtg.vtgRemoteDebuggingPort},{devtools:!1,headless:V0.CI},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"},viewport:o,completeOriginHeaderOnLivePage:!V0.vtg.isSeparateProcess&&!((v=(_=(f=this.checksumConfig.options)==null?void 0:f.modelConfig)==null?void 0:_.browserArgs)!=null&&v.skipDisableWebSecurity)&&!((w=(C=this.checksumConfig.options)==null?void 0:C.modelConfig)!=null&&w.skipCompleteOriginHeaderOnDisableWebSecurity)},r)}async onWebDriverContextClose(){var r,a,o;this.evaluatorService.stopListening(),(r=this.vtgTestFileRunConfig)!=null&&r.evalFilePath&&(0,F3e.rmSync)((a=this.vtgTestFileRunConfig)==null?void 0:a.evalFilePath,{force:!0}),this.vtgTestFileRunConfig.mode==="edit"&&(0,F3e.rmSync)((o=this.vtgTestFileRunConfig)==null?void 0:o.actionsJsonFilePath,{force:!0})}initializeAccordingToVTGMode(r){var c;let a=r.indexOf("--edit"),o=r.indexOf("--cloud");if(r.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=((c=this.vtgTestFileRunConfig)==null?void 0:c.mode)==="start"?this.vtgTestFileRunConfig.storyId:void 0;return}a!==-1&&(this.vtgMode="edit",this.editLocationPath=r[a+1]),o!==-1&&(this.vtgMode="cloud",this.cloudTestGenerationId=r[o+1]),this.vtgMode==="start"&&(this.storyId=r[0])}getWebDriver(){return this.webDriver}async eval(r){return this.evaluatorService.listenForExecution(r)}};e(whn,"VisualTestGenerator");var frr=whn;Eve();var iEi=require("child_process"),Dhn=require("net");vT();var aEi=require("path");v7();var nEi=sf(vht());fQ();var Shn=e(async(i,t,r,a,o={})=>{let{preventDialogFromAutoDismissing:c=!1,retry:f=!0,maxRetries:_=void 0,numberOfRetries:v=0}=o;try{console.log(`${i} attempting to connect to ${t} on port ${r}...`);let w=(await nEi.chromium.connectOverCDP("http://127.0.0.1:"+r)).contexts()[0],T=a(w.pages());for(;!T;)await TA(1e3),T=a(w.pages());return console.log(`${i} is connected to ${t} on port ${r}`,T.url()),c&&bzt(T),T}catch(C){if(!f||_&&v>=_)throw console.error(`${i} failed to connect to ${t}, retries were exhausted or disabled`,C),C;return console.log(`${i} is waiting and retrying connection to ${t} on port ${r}...`),await TA(1e3),Shn(i,t,r,a,{...o,numberOfRetries:v+1})}},"connectToPage");qw();var Thn=class Thn{constructor(t){this.checksumConfig=t;this.isReady=!1;this.onMessage=e(async(t,r)=>{let{id:a,err:o,result:c}=await this.execute(t);r.write(this.messageParser.makeMessage(JSON.stringify({id:a,err:this.serializedErr(o),result:c})))},"onMessage");this.messageParser=new BGe(this.onMessage),this.isReadyPromise=new Promise(r=>{this.isReadyResolve=r}),this.routeInterceptor=new qWe({completeOriginHeader:!0})}async eval(t){return this.listenForExecution(t)}async run(t){this.liveAppPage=t,await this.applyRouteInterceptorsIfNecessary(),await this.createServer(),this.startRunner()}async applyRouteInterceptorsIfNecessary(){var r,a,o,c,f,_;if(!((o=(a=(r=this.checksumConfig.options)==null?void 0:r.modelConfig)==null?void 0:a.browserArgs)!=null&&o.skipDisableWebSecurity)&&!((f=(c=this.checksumConfig.options)==null?void 0:c.modelConfig)!=null&&f.skipCompleteOriginHeaderOnDisableWebSecurity))try{await((_=this.liveAppPage)==null?void 0:_.route("**/*",async(v,C)=>this.routeInterceptor.intercept(v,C,{page:this.liveAppPage},{completeOriginHeader:!0})))}catch(v){tf.error("[WebDriver] applyRouteInterceptors error",v)}}startRunner(){let t=V0.isRepoMode?"yarn vtg-pw-bridge":`ts-node ${(0,aEi.join)(__dirname,"vtg-pw-bridge-runner.js")}`;Yes(t,{CHECKSUM_PORT:this.port.toString(),CHECKSUM_CONFIG:JSON.stringify(this.checksumConfig)})}async createServer(){this.server=(0,Dhn.createServer)(t=>{t.on("data",async r=>{try{await this.messageParser.onMessage(t,r)}catch(a){t.write(JSON.stringify({err:a.message}))}}),t.on("end",()=>{}),t.on("error",r=>{}),this.connectToVTG()}),this.port=await this.acquirePortNumber(),this.server.listen(this.port,()=>tf.info(`VTG PW Bridge Server listening on port ${this.port}...`))}serializedErr(t){return t&&JSON.stringify(t,Object.getOwnPropertyNames(t))}async connectToVTG(){tf.info("[VTG PW Bridge] Connecting to VTG...");let t=e(r=>r.frames().find(a=>a.name()==="time-machine-iframe"),"findTimeMachineIframe");this.vtgPage=await this.connectToPage("VTG page",V0.vtg.vtgRemoteDebuggingPort,r=>r.find(a=>t(a))),this.vtgTimeMachineFrame=t(this.vtgPage),this.taskTimeMachinePage=await this.connectToPage("Task Time Machine page",V0.vtg.taskTimeMachine.debugPort,r=>r[0]),tf.info("[VTG PW Bridge] Connected to VTG."),this.isReady=!0,this.isReadyResolve()}async connectToPage(t,r,a){return Shn("Playwright via Bridge",t,r,a,{preventDialogFromAutoDismissing:!0})}async acquirePortNumber(){return await new Promise((t,r)=>{let a=(0,Dhn.createServer)();a.unref(),a.on("error",r),a.listen(0,()=>{let o=a.address().port;a.close(()=>{t(o)})})})}async listenForExecution(t){return new Promise(r=>{this.resolveEvaluator=r,this.listener=t})}stopListening(){var t;(t=this.resolveEvaluator)==null||t.call(this)}buildContext(t){let{frame:r,expectConfig:a}=t,o={};switch(r){case"task-time-machine":o.page=this.taskTimeMachinePage.frameLocator("iframe");break;case"vtg-time-machine":o.page=this.vtgTimeMachineFrame.frameLocator("iframe");break;case"live":default:break}return a&&(o.expect=Jbe.expect.configure(a)),o}wrapCodeInContext(t,r){return`(async ({${Object.keys(r).join(", ")}}) => { ${t} })`}async execute(t){this.isReady||tf.warning("[VTG PW Bridge] Execute called before ready"),await this.isReadyPromise;let{id:r,code:a,options:o}=t,c=this.buildContext(o),f=this.wrapCodeInContext(a,c)+"(context)";return new Promise(_=>{this.listener&&this.listener(f,c,(v,C)=>{_({id:r,err:v,result:C})})})}};e(Thn,"VtgPwBridge");var drr=Thn;async function Yes(i,t={}){let r={...process.env,...t};(0,iEi.spawn)(i,{env:r,shell:!0,stdio:["inherit","inherit","inherit"],detached:!1}).on("exit",o=>{process.exit(o)})}e(Yes,"spawnCmd");var PEi=require("@playwright/test"),FEi=sf(IEi());var lae=class lae{constructor(t){this.options=t;this.importPluginPackages()}importPluginPackages(){lae.pw??(lae.pw=vht()),lae.StealthPlugin??(lae.StealthPlugin=require("puppeteer-extra-plugin-stealth"))}static createFreshInstance(){try{let{addExtra:t}=vht(),r=t(lae.pw.chromium);return console.log("[StealthProvider] Created fresh playwright-extra instance for testing"),r}catch(t){throw console.error("[StealthProvider] Error creating fresh instance:",t),t}}buildChromiumWithPlugins(t){let{project:r}=this.options,a=r.use.userAgent,o=r.use.playwrightExtra||[],c=lae.StealthPlugin();if(o.push(c),this.isCustomUserAgent(a)){c.enabledEvasions.delete("user-agent-override");let v=require("puppeteer-extra-plugin-stealth/evasions/user-agent-override")({userAgent:a});o.push(v)}let f=t??lae.pw.chromium;return o.forEach((_,v)=>{try{!(_ instanceof FEi.PuppeteerExtraPlugin)&&_!==c&&console.warn(`Plugin at index ${v} in the project's checksum.config.ts file is not an instance of PuppeteerExtraPlugin.`),f.use(_)}catch(C){console.warn(C)}}),f}isCustomUserAgent(t){return t?!Object.values(PEi.devices).some(r=>t===r.userAgent):!1}};e(lae,"StealthProvider");var hrr=lae;Mjt();function NEi(i,t){return{testSuiteRunId:t,appName:"generic-app",commitHash:"generic-commit-hash",envName:"generic-env-name",branch:"generic-branch",checksumRuntimeVersion:i}}e(NEi,"createDefaultTestSuiteRunInfo");var BEi=require("crypto");UVr();var N3e=class N3e{constructor(t,r){this.context=t;this.isVTG=r;this._pages={};this._pagesInProgress=new Map;this._testAssets=null;this.pageGuidMap=new WeakMap;this.instanceId=++N3e.instanceCounter,this.setContextProxy()}static makeContext(t,r){return new N3e(t,r).proxy}setTestAssets(t){this._testAssets=t,this.setupPageListener()}getTestAssets(){return this._testAssets}cleanup(){this._pagesInProgress.clear(),this._pages={}}async newPage(){let t=await this.context.newPage();return await this.makePage(t)}async makePage(t){let r=this.getPageGuid(t);if(this.hasPage(r))return this.getPageByGuid(r);if(this._pagesInProgress.has(r))return this._pagesInProgress.get(r);let a=this._createPageInstance(t);this._pagesInProgress.set(r,a);try{let o=await a;return this._pagesInProgress.delete(r),this.addPage(o),o}catch(o){throw this._pagesInProgress.delete(r),o}}addPage(t){let r=this.getPageGuid(t);this._pages[r]=t,t.once("close",()=>{this.removePage(r)})}removePage(t){this._pages[t]&&delete this._pages[t]}async _createPageInstance(t){if(this._testAssets)try{return await vzt.init(t,this.proxy,this._testAssets.testRunAnalytics,this._testAssets.monitorBridge,this._testAssets.variableStore,this._testAssets.testInfo,this._testAssets.checksumTestId,this._testAssets.test,this._testAssets.config,this._testAssets.isReplMode)}catch(r){throw new Error(`Failed to initialize RuntimePage: ${r instanceof Error?r.message:String(r)}. Test assets must be properly configured.`)}throw new Error("Cannot create page: Test assets not set. Use setTestAssets() before creating pages.")}setContextProxy(){this.proxy=new Proxy(this,{get:e(function(r,a){return r.getContextMethod(a)},"get")})}setupPageListener(){this.context.on("page",async t=>{try{await this.makePage(t)}catch(r){throw console.error("[ChecksumBrowserContext] Failed to initialize page created by application:",r),r}})}getPageGuid(t){let r=this.pageGuidMap.get(t);return r||(r=`page@checksumctx_${this.instanceId}_${++N3e.guidCounter}`,this.pageGuidMap.set(t,r)),r}getPageByGuid(t){return this._pages[t]}hasPage(t){return t in this._pages}getAllPages(){return Object.values(this._pages)}getContextMethod(t){if(t in this){let a=this[t];return typeof a=="function"?a.bind(this):a}let r=this.context[t];return typeof r=="function"?r.bind(this.context):r}pages(){return this.getAllPages()}getPage(t){let r=this.getAllPages(),a=r[t];if(!a)throw new Error(`Page with index ${t} not found. Total pages: ${r.length}`);return a}};e(N3e,"ChecksumBrowserContext"),N3e.instanceCounter=0,N3e.guidCounter=0;var grr=N3e;var Nhn={},pZe=!!process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG,REi=e((i,t,r={},a=!1)=>{let{runMode:o,environments:c}=t,f=c.find(v=>v.default),_=i.extend({baseURL:f.baseURL,bypassCSP:!0,...pZe?{trace:"off",video:"off",screenshot:"off",ignoreHTTPSErrors:!0}:{},permissions:e(async({},v,C)=>{if(!pZe)await v(C.project.use.permissions);else{let w=new Set(C.project.use.permissions);w.add("clipboard-read"),w.add("clipboard-write"),w.add("camera"),w.add("storage-access"),w.add("notifications"),w.add("geolocation"),w.add("microphone"),await v(Array.from(w))}},"permissions"),proxy:e(async({proxy:v},C)=>{v?await C({...v,bypass:"127.0.0.1,localhost"}):await C(v)},"proxy"),browser:e(async({browser:v,browserName:C,launchOptions:w},T,k)=>{let R=e(()=>(k.project.use.playwrightExtra||[]).some(X=>X.constructor.name==="StealthPlugin"),"checkIfStealthPluginExists"),B=e(async()=>{let W=await(await new hrr({project:k.project}).buildChromiumWithPlugins()).launch(w);await T(W)},"launchBrowserWithStealthPlugin");pZe?V0.vtg.isSeparateProcess?await T(v):R()?(console.log("StealthPlugin already configured"),await T(v)):await B():V0.useRemoteDebugging.enabled&&R()?await B():await T(v)},"browser"),launchOptions:e(async({launchOptions:v},C)=>{var k;let w=v!=null&&v.args?[...v.args]:[],T=e(R=>{w.includes(R)||w.push(R)},"pushArg");if(r.useMockData&&T("--disable-web-security"),V0.bypassProxyForLocalhost&&T("--proxy-bypass-list=localhost,127.0.0.1"),pZe){T("--proxy-bypass-list=localhost,127.0.0.1"),V0.vtg.isSeparateProcess&&T(`--remote-debugging-port=${V0.vtg.appRemoteDebuggingPort}`);let R=((k=r.modelConfig)==null?void 0:k.browserArgs)??{};R.skipDisableWebSecurity||T("--disable-web-security"),R.skipAllowFileAccessFromFiles||T("--allow-file-access-from-files"),R.skipDisableSiteIsolationTrials||T("--disable-site-isolation-trials"),R.skipAllowRunningInsecureContent||T("--allow-running-insecure-content")}V0.useRemoteDebugging.enabled&&T(`--remote-debugging-port=${V0.useRemoteDebugging.port}`),await C({...v,args:w})},"launchOptions"),variableStore:e(async({},v)=>{let C=new yWe;await v(C)},"variableStore"),vs:e(async({variableStore:v},C)=>{await C(v)},"vs"),variablesStore:e(async({variableStore:v},C)=>{await C(v)},"variablesStore"),testRunAnalytics:e(async({},v,C)=>{let w=(()=>{try{if(process.env.CHECKSUM_TEST_SUITE_INFO)return JSON.parse(process.env.CHECKSUM_TEST_SUITE_INFO);throw new Error("Missing Checksum test suite info")}catch{return console.warn("\u26A0\uFE0F Warning: It seems like you ran the test suite directly via Playwright. This can lead to degraded functionality and unexpected issues. To ensure a fully supported and stable test run, please use: 'npx checksumai test'."),NEi("playwright-run-version-unknown",(0,BEi.randomUUID)())}})(),T=OEi(C),k=rie.getTestRunInstance({...w,checksumTestId:T},process.env.CHECKSUM_ISOLATED_MODE==="true",C);await v(k)},"testRunAnalytics"),monitorBridge:[async({},v,C)=>{let w=new wzt(C);await v(w)},{scope:"worker"}],context:e(async({context:v,monitorBridge:C,variableStore:w,testRunAnalytics:T},k,R)=>{let B=grr.makeContext(v,pZe);B.setTestAssets({testRunAnalytics:T,monitorBridge:C,variableStore:w,testInfo:R,checksumTestId:OEi(R),test:_,config:t,isReplMode:a}),await k(B),B.cleanup()},"context"),page:e(async({page:v,context:C},w,T)=>{let k=await C.makePage(v);await w(k),k&&typeof k.onTestComplete=="function"&&await k.onTestComplete(T.status==="passed"),k&&typeof k.shutdown=="function"&&await k.shutdown()},"page"),vtg:e(async({page:v},C)=>{if(!pZe)C(null);else if(V0.vtg.isSeparateProcess){let w=new drr(t);await w.run(v),await C(w)}else{let w=new frr(["--test-file"],!1,t);await w.run(v),await C(w)}},"vtg")});return{test:_,defineChecksumTest:dts}},"createChecksumTestExtension"),dts=e((i,t,r)=>{let o=new Error().stack.split(`
2043
+ `)}async run(r){await this.init(r),this.buildServices(r),this.buildServer(),await this.loadIfNecessary(),await this.start()}async loadIfNecessary(){let r=await this.getInitialServicesData();r&&(this.actionsManager.setActions(r.actions),this.testAssetsManager.setCurrentSaveAsLocation(this.editLocationPath),this.storyId=r.storyId,r.testGenerationData&&this.userStoryService.setTestGenerationData(r.testGenerationData))}async init(r){tf.info(`Initializing VTG with runtime version ${this.checksumRuntimeVersion}...`),await this.patchPlaywright(),this.loadPlaywrightConfigForVTG(),this.webDriver=this.buildWebDriver(r),this.webDriver.registerEventListener(this),this.taskTimeMachine=new cbe(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!V0.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0,taskTimeout:V0.vtg.taskTimeMachine.taskTimeout,debugPort:V0.vtg.isSeparateProcess?V0.vtg.taskTimeMachine.debugPort:void 0,frameMsgBrokerRegisterName:"task-time-machine",logPerformance:V0.vtg.taskTimeMachine.logPerformance,webProxy:this.getPlaywrightProxySettings()}),this.pageInteractor=new wve(this.webDriver.evaluateWithChecksum.bind(this.webDriver),()=>this.webDriver.appMainFrame,this.webDriver.getTimeMachine.bind(this.webDriver),{log:e((a,...o)=>o!=null&&o.length?tf.info(a,...o):tf.info(a),"log"),logError:e((a,...o)=>o!=null&&o.length?tf.error(a,...o):tf.error(a),"logError")},{...this.getTimeoutParams(),waitActionDelay:1e3,testAssetsDir:__dirname,listenToDialog:!0,listenToFileChooser:!1},new iVe(this.checksumConfig)),this.testAssetsManager=new cGt(this.projectRootDirectory,this.checksumRoot,this.vtgInternalFilesDir,this.vtgTestFileRunConfig)}buildServices(r){this.actionsManager=new BWt,this.settingsService=new sgt(this.checksumRoot,this.apiService,this.vtgInternalFilesDir),this.apiService=new Y_t(this.checksumConfig),this.settingsService=new sgt(this.checksumRoot,this.apiService),this.userStoryService=new G_t(this.apiService,this.checksumConfig),this.variableStoreService=new hGt,this.evaluatorService=new yGt(this.variableStoreService,this.settingsService,this.vtgTestFileMode,r,this.port),this.actionsService=new dJt(this.checksumConfig,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver,this.evaluatorService,this.vtgInternalFilesDir),this.assertionsService=new AJt(this.webDriver,this.actionsManager,this.evaluatorService),this.locatorsService=new FJt(this.webDriver,this.taskTimeMachine,this.apiService,this.userStoryService,this.evaluatorService),this.aiTestGenerationService=new _Jt(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new xJt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver,this.evaluatorService,{logPerformance:V0.vtg.aiAssertions.logPerformance}),this.aiThoughtsService=new _Gt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new OWt(this.checksumConfig,this.userStoryService,this.apiService,this.actionsManager,this.testAssetsManager,this.actionsService,this.vtgTestFileRunConfig,this.evaluatorService,this.settingsService,this.taskTimeMachine),this.actionsManager.setStorageService(this.storageService),this.monacoService=new bGt,this.aiChatService=new prr(this.taskTimeMachine,this.evaluatorService)}buildServer(){this.reactAppServer=new oGt(this.actionsService,this.assertionsService,this.locatorsService,this.aiTestGenerationService,this.aiAssertionsService,this.aiThoughtsService,this.actionsManager,this.storageService,this.settingsService,this.monacoService,this.evaluatorService,this.aiChatService)}loadPlaywrightConfigForVTG(){try{let r=`${this.checksumRoot}/playwright.config.ts`;if((0,F3e.existsSync)(r)){let a=require(r).default;a&&(this.playwrightConfigForVTG=a)}}catch{tf.warning("Could not find playwright config file, will run with defaults")}}async getInitialServicesData(){switch(this.vtgMode){case"cloud":return this.getInitialServicesDataFromCloud();case"edit":return this.vtgTestFileMode?await this.getInitialServicesDataForEditedFile():this.getInitialServicesDataFromJSON("local");case"start":if(this.vtgTestFileRunConfig.restoreFromAutoSave)return this.getInitialServicesDataFromJSON("auto-save")}}getInitialServicesDataFromJSON(r){let a=this.storageService.getLocalSavedJSONFilePath(r,this.storyId),o=this.storageService.readLocalSavedDataFromJSONFile(a);if(!o)throw new Error(`No data found in ${r} while reading from ${a}`);return{actions:o.executedActions,storyId:o.story.id}}async getInitialServicesDataFromCloud(){let a=await(await this.apiService.post(`test-generation/${this.cloudTestGenerationId}/info`)).json(),{actionsDownloadSignedURL:o}=a,c=await fetch(o,{mode:"cors",credentials:"same-origin",headers:{"Content-Type":"application/json"}});if(!c.ok)throw new Error(`HTTP error! Status: ${c.status}`);let f=await c.json();return{actions:this.initializeTestStepsWithIds(f),storyId:a.story.id}}initializeTestStepsWithIds(r){return r.map((a,o)=>({...a,id:(0,Chn.randomUUID)(),assertions:(a.assertions??[]).map(c=>({...c,id:(0,Chn.randomUUID)()}))}))}async getInitialServicesDataForEditedFile(){var a,o,c,f,_,v,C;if(((a=this.vtgTestFileRunConfig)==null?void 0:a.mode)!=="edit")return;let r=[];if(!this.vtgTestFileRunConfig.restoreFromAutoSave){let w=(o=this.vtgTestFileRunConfig)==null?void 0:o.actionsJsonFilePath;r=this.storageService.readJsonFile(w),(0,F3e.rmSync)(w,{force:!0}),r=this.initializeTestStepsWithIds(r)}if((c=this.vtgTestFileRunConfig)!=null&&c.internalTestId)try{let w=await this.apiService.post(`test-generation-by-internal-test-id/${(f=this.vtgTestFileRunConfig)==null?void 0:f.internalTestId}/info`);if(!w.ok){let k=w.statusText;try{let R=await w.text();try{k=JSON.parse(R).message||R||w.statusText}catch{k=R||w.statusText}}catch{k="Test id not found or invalid"}throw new Error(`Error fetching test generation data: ${k}`)}let T=await w.json();if(this.vtgTestFileRunConfig.restoreFromAutoSave){let k=this.storageService.getLocalSavedJSONFilePath("auto-save"),R=this.storageService.readLocalSavedDataFromJSONFile(k);if(!R)throw new Error(`No data found in auto-save while reading from ${k}`);r=R==null?void 0:R.executedActions}return{actions:r,storyId:T.story.id,testGenerationData:T.testGenerationData}}catch{tf.warning(`Could not find data matching internal test id: ${(_=this.vtgTestFileRunConfig)==null?void 0:_.internalTestId}`)}if((v=this.vtgTestFileRunConfig)!=null&&v.storyId)return{actions:r,storyId:(C=this.vtgTestFileRunConfig)==null?void 0:C.storyId};throw new Error("Cannot edit file without either valid internal test id or story id")}async start({createAssetsFolder:r=!0}={}){var o,c;await this.userStoryService.fetchStory(this.storyId),r&&this.testAssetsManager.createTestAssetsFolders(),this.testAssetsManager.createTestGenerationLocalAutoSaveFolder(),await this.reactAppServer.start();let{environment:a}=this.userStoryService.getEnvInfo();await this.webDriver.prepare({baseURL:a.baseURL,shutdown:!this.vtgTestFileMode},{serverPort:await this.reactAppServer.getPort()}),V0.vtg.writeLogFile&&this.setupFrontendLogging(this.webDriver.page),await this.webDriver.page.evaluate(()=>{"checksumRRWeb"in window&&console.log(`Using forked rrweb. ${JSON.stringify(window.checksumRRWeb)}`)}),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()),this.aiChatService.setPage(this.webDriver.appMainFrame.page()),await this.taskTimeMachine.prepare(this.webDriver.appMainFrame,void 0,f=>this.webDriver.registerTimeMachineFrame(f)),await this.reactAppServer.evaluateServerPort(this.webDriver.page),await this.webDriver.appMainFrame.goto("about:blank",{waitUntil:"domcontentloaded",timeout:0}),await this.webDriver.getTimeMachine().toggleTimeMachineHandleEvents(!1),this.vtgMode==="start"&&!this.vtgTestFileRunConfig.restoreFromAutoSave&&(await this.actionsService.addInitialLoginAction(),await this.actionsService.addStartURLNavigationAction(),this.vtgTestFileMode&&await this.storageService.saveTestFile()),tf.info("VTG is ready with story:",{goal:(o=this.userStoryService.getStory())==null?void 0:o.goal}),await this.webDriver.page.evaluate(({localSaveFolderPath:f,stepsData:_,appViewport:v,userStoryGoal:C,isLoadedFromFile:w})=>{window.vtg.initClient(f,_,v,this.checksumRuntimeVersion,C,w)},{localSaveFolderPath:this.editLocationPath,stepsData:await this.actionsManager.buildStepDataWithCode(this.actionsManager.actions,{loadingFromFile:["edit","cloud"].includes(this.vtgMode)}),appViewport:this.webDriver.getApplicationViewport(),userStoryGoal:(c=this.userStoryService.getStory())==null?void 0:c.goal,isLoadedFromFile:this.vtgTestFileMode}),this.vtgTestFileMode||await new Promise(()=>{})}getTimeoutParams(){var o,c,f,_;let r=((c=(o=this.playwrightConfigForVTG)==null?void 0:o.use)==null?void 0:c.navigationTimeout)||3e4,a=((_=(f=this.playwrightConfigForVTG)==null?void 0:f.use)==null?void 0:_.actionTimeout)||5e3;return{navigationTimeout:r,actionTimeout:a}}getPlaywrightProxySettings(){var f,_;let r=(_=(f=this.playwrightConfigForVTG)==null?void 0:f.use)==null?void 0:_.proxy,{server:a,username:o,password:c}=r||{};if(o&&c&&a)return{username:o,password:c,server:a}}getPlaywrightViewportSettings(){var o,c;let{width:r=1280,height:a=720}=((c=(o=this.playwrightConfigForVTG)==null?void 0:o.use)==null?void 0:c.viewport)||{};return{width:r,height:a}}buildWebDriver(r){var c,f,_,v,C,w;let a=this.getPlaywrightProxySettings(),o=this.getPlaywrightViewportSettings();return new fGt({scriptSource:V0.checksumScript.source,scriptURL:V0.checksumScript.url,scriptFile:V0.checksumScript.path,isScriptFileAbsolute:!0,fullScreenResolution:!1,hostWindowViewport:!0,baseURL:(c=this.checksumConfig.environments.find(T=>T.default))==null?void 0:c.baseURL,useProxy:!!a,webProxy:a,disableWebSecurity:!0,allowFileAccess:!0,remoteDebugging:V0.vtg.remoteDebugging,remoteDebuggingPort:V0.vtg.vtgRemoteDebuggingPort},{devtools:!1,headless:V0.CI},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"},viewport:o,completeOriginHeaderOnLivePage:!V0.vtg.isSeparateProcess&&!((v=(_=(f=this.checksumConfig.options)==null?void 0:f.modelConfig)==null?void 0:_.browserArgs)!=null&&v.skipDisableWebSecurity)&&!((w=(C=this.checksumConfig.options)==null?void 0:C.modelConfig)!=null&&w.skipCompleteOriginHeaderOnDisableWebSecurity)},r)}async onWebDriverContextClose(){var r,a,o;this.evaluatorService.stopListening(),(r=this.vtgTestFileRunConfig)!=null&&r.evalFilePath&&(0,F3e.rmSync)((a=this.vtgTestFileRunConfig)==null?void 0:a.evalFilePath,{force:!0}),this.vtgTestFileRunConfig.mode==="edit"&&(0,F3e.rmSync)((o=this.vtgTestFileRunConfig)==null?void 0:o.actionsJsonFilePath,{force:!0})}initializeAccordingToVTGMode(r){var c;let a=r.indexOf("--edit"),o=r.indexOf("--cloud");if(r.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=((c=this.vtgTestFileRunConfig)==null?void 0:c.mode)==="start"?this.vtgTestFileRunConfig.storyId:void 0;return}a!==-1&&(this.vtgMode="edit",this.editLocationPath=r[a+1]),o!==-1&&(this.vtgMode="cloud",this.cloudTestGenerationId=r[o+1]),this.vtgMode==="start"&&(this.storyId=r[0])}getWebDriver(){return this.webDriver}async eval(r){return this.evaluatorService.listenForExecution(r)}};e(whn,"VisualTestGenerator");var frr=whn;Eve();var iEi=require("child_process"),Dhn=require("net");vT();var aEi=require("path");v7();var nEi=sf(vht());fQ();var Shn=e(async(i,t,r,a,o={})=>{let{preventDialogFromAutoDismissing:c=!1,retry:f=!0,maxRetries:_=void 0,numberOfRetries:v=0}=o;try{console.log(`${i} attempting to connect to ${t} on port ${r}...`);let w=(await nEi.chromium.connectOverCDP("http://127.0.0.1:"+r)).contexts()[0],T=a(w.pages());for(;!T;)await TA(1e3),T=a(w.pages());return console.log(`${i} is connected to ${t} on port ${r}`,T.url()),c&&bzt(T),T}catch(C){if(!f||_&&v>=_)throw console.error(`${i} failed to connect to ${t}, retries were exhausted or disabled`,C),C;return console.log(`${i} is waiting and retrying connection to ${t} on port ${r}...`),await TA(1e3),Shn(i,t,r,a,{...o,numberOfRetries:v+1})}},"connectToPage");qw();var Thn=class Thn{constructor(t){this.checksumConfig=t;this.isReady=!1;this.onMessage=e(async(t,r)=>{let{id:a,err:o,result:c}=await this.execute(t);r.write(this.messageParser.makeMessage(JSON.stringify({id:a,err:this.serializedErr(o),result:c})))},"onMessage");this.messageParser=new BGe(this.onMessage),this.isReadyPromise=new Promise(r=>{this.isReadyResolve=r}),this.routeInterceptor=new qWe({completeOriginHeader:!0})}async eval(t){return this.listenForExecution(t)}async run(t){this.liveAppPage=t,await this.applyRouteInterceptorsIfNecessary(),await this.createServer(),this.startRunner()}async applyRouteInterceptorsIfNecessary(){var r,a,o,c,f,_;if(!((o=(a=(r=this.checksumConfig.options)==null?void 0:r.modelConfig)==null?void 0:a.browserArgs)!=null&&o.skipDisableWebSecurity)&&!((f=(c=this.checksumConfig.options)==null?void 0:c.modelConfig)!=null&&f.skipCompleteOriginHeaderOnDisableWebSecurity))try{await((_=this.liveAppPage)==null?void 0:_.route("**/*",async(v,C)=>this.routeInterceptor.intercept(v,C,{page:this.liveAppPage},{completeOriginHeader:!0})))}catch(v){tf.error("[WebDriver] applyRouteInterceptors error",v)}}startRunner(){let t=V0.isRepoMode?"yarn vtg-pw-bridge":`ts-node ${(0,aEi.join)(__dirname,"vtg-pw-bridge-runner.js")}`;Yes(t,{CHECKSUM_PORT:this.port.toString(),CHECKSUM_CONFIG:JSON.stringify(this.checksumConfig)})}async createServer(){this.server=(0,Dhn.createServer)(t=>{t.on("data",async r=>{try{await this.messageParser.onMessage(t,r)}catch(a){t.write(JSON.stringify({err:a.message}))}}),t.on("end",()=>{}),t.on("error",r=>{}),this.connectToVTG()}),this.port=await this.acquirePortNumber(),this.server.listen(this.port,()=>tf.info(`VTG PW Bridge Server listening on port ${this.port}...`))}serializedErr(t){return t&&JSON.stringify(t,Object.getOwnPropertyNames(t))}async connectToVTG(){tf.info("[VTG PW Bridge] Connecting to VTG...");let t=e(r=>r.frames().find(a=>a.name()==="time-machine-iframe"),"findTimeMachineIframe");this.vtgPage=await this.connectToPage("VTG page",V0.vtg.vtgRemoteDebuggingPort,r=>r.find(a=>t(a))),this.vtgTimeMachineFrame=t(this.vtgPage),this.taskTimeMachinePage=await this.connectToPage("Task Time Machine page",V0.vtg.taskTimeMachine.debugPort,r=>r[0]),tf.info("[VTG PW Bridge] Connected to VTG."),this.isReady=!0,this.isReadyResolve()}async connectToPage(t,r,a){return Shn("Playwright via Bridge",t,r,a,{preventDialogFromAutoDismissing:!0})}async acquirePortNumber(){return await new Promise((t,r)=>{let a=(0,Dhn.createServer)();a.unref(),a.on("error",r),a.listen(0,()=>{let o=a.address().port;a.close(()=>{t(o)})})})}async listenForExecution(t){return new Promise(r=>{this.resolveEvaluator=r,this.listener=t})}stopListening(){var t;(t=this.resolveEvaluator)==null||t.call(this)}buildContext(t){let{frame:r,expectConfig:a}=t,o={};switch(r){case"task-time-machine":o.page=this.taskTimeMachinePage.frameLocator("iframe");break;case"vtg-time-machine":o.page=this.vtgTimeMachineFrame.frameLocator("iframe");break;case"live":default:break}return a&&(o.expect=Jbe.expect.configure(a)),o}wrapCodeInContext(t,r){return`(async ({${Object.keys(r).join(", ")}}) => { ${t} })`}async execute(t){this.isReady||tf.warning("[VTG PW Bridge] Execute called before ready"),await this.isReadyPromise;let{id:r,code:a,options:o}=t,c=this.buildContext(o),f=this.wrapCodeInContext(a,c)+"(context)";return new Promise(_=>{this.listener&&this.listener(f,c,(v,C)=>{_({id:r,err:v,result:C})})})}};e(Thn,"VtgPwBridge");var drr=Thn;async function Yes(i,t={}){let r={...process.env,...t};(0,iEi.spawn)(i,{env:r,shell:!0,stdio:["inherit","inherit","inherit"],detached:!1}).on("exit",o=>{process.exit(o)})}e(Yes,"spawnCmd");var PEi=require("@playwright/test"),FEi=sf(IEi());var lae=class lae{constructor(t){this.options=t;this.importPluginPackages()}importPluginPackages(){lae.pw??(lae.pw=vht()),lae.StealthPlugin??(lae.StealthPlugin=require("puppeteer-extra-plugin-stealth"))}static createFreshInstance(){try{let{addExtra:t}=vht(),r=t(lae.pw.chromium);return console.log("[StealthProvider] Created fresh playwright-extra instance for testing"),r}catch(t){throw console.error("[StealthProvider] Error creating fresh instance:",t),t}}buildChromiumWithPlugins(t){let{project:r}=this.options,a=r.use.userAgent,o=r.use.playwrightExtra||[],c=lae.StealthPlugin();if(o.push(c),this.isCustomUserAgent(a)){c.enabledEvasions.delete("user-agent-override");let v=require("puppeteer-extra-plugin-stealth/evasions/user-agent-override")({userAgent:a});o.push(v)}let f=t??lae.pw.chromium;return o.forEach((_,v)=>{try{!(_ instanceof FEi.PuppeteerExtraPlugin)&&_!==c&&console.warn(`Plugin at index ${v} in the project's checksum.config.ts file is not an instance of PuppeteerExtraPlugin.`),f.use(_)}catch(C){console.warn(C)}}),f}isCustomUserAgent(t){return t?!Object.values(PEi.devices).some(r=>t===r.userAgent):!1}};e(lae,"StealthProvider");var hrr=lae;Mjt();function NEi(i,t){return{testSuiteRunId:t,appName:"generic-app",commitHash:"generic-commit-hash",envName:"generic-env-name",branch:"generic-branch",checksumRuntimeVersion:i}}e(NEi,"createDefaultTestSuiteRunInfo");var BEi=require("crypto");UVr();var N3e=class N3e{constructor(t,r){this.context=t;this.isVTG=r;this._pages={};this._pagesInProgress=new Map;this._testAssets=null;this.pageGuidMap=new WeakMap;this.instanceId=++N3e.instanceCounter,this.setContextProxy()}static makeContext(t,r){return new N3e(t,r).proxy}_rawContext(){return this.context}setTestAssets(t){this._testAssets=t,this.setupPageListener()}getTestAssets(){return this._testAssets}cleanup(){this._pagesInProgress.clear(),this._pages={}}async newPage(){let t=await this.context.newPage();return await this.makePage(t)}async makePage(t){let r=this.getPageGuid(t);if(this.hasPage(r))return this.getPageByGuid(r);if(this._pagesInProgress.has(r))return this._pagesInProgress.get(r);let a=this._createPageInstance(t);this._pagesInProgress.set(r,a);try{let o=await a;return this._pagesInProgress.delete(r),this.addPage(o),o}catch(o){throw this._pagesInProgress.delete(r),o}}addPage(t){let r=this.getPageGuid(t);this._pages[r]=t,t.once("close",()=>{this.removePage(r)})}removePage(t){this._pages[t]&&delete this._pages[t]}async _createPageInstance(t){if(this._testAssets)try{return await vzt.init(t,this.proxy,this._testAssets.testRunAnalytics,this._testAssets.monitorBridge,this._testAssets.variableStore,this._testAssets.testInfo,this._testAssets.checksumTestId,this._testAssets.test,this._testAssets.config,this._testAssets.isReplMode)}catch(r){throw new Error(`Failed to initialize RuntimePage: ${r instanceof Error?r.message:String(r)}. Test assets must be properly configured.`)}throw new Error("Cannot create page: Test assets not set. Use setTestAssets() before creating pages.")}setContextProxy(){this.proxy=new Proxy(this,{get:e(function(r,a){return r.getContextMethod(a)},"get")})}setupPageListener(){this.context.on("page",async t=>{try{await this.makePage(t)}catch(r){throw console.error("[ChecksumBrowserContext] Failed to initialize page created by application:",r),r}})}getPageGuid(t){let r=this.pageGuidMap.get(t);return r||(r=`page@checksumctx_${this.instanceId}_${++N3e.guidCounter}`,this.pageGuidMap.set(t,r)),r}getPageByGuid(t){return this._pages[t]}hasPage(t){return t in this._pages}getAllPages(){return Object.values(this._pages)}getContextMethod(t){if(t in this){let a=this[t];return typeof a=="function"?a.bind(this):a}let r=this.context[t];return typeof r=="function"?r.bind(this.context):r}pages(){return this.getAllPages()}getPage(t){let r=this.getAllPages(),a=r[t];if(!a)throw new Error(`Page with index ${t} not found. Total pages: ${r.length}`);return a}};e(N3e,"ChecksumBrowserContext"),N3e.instanceCounter=0,N3e.guidCounter=0;var grr=N3e;var Nhn={},pZe=!!process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG,REi=e((i,t,r={},a=!1)=>{let{runMode:o,environments:c}=t,f=c.find(v=>v.default),_=i.extend({baseURL:f.baseURL,bypassCSP:!0,...pZe?{trace:"off",video:"off",screenshot:"off",ignoreHTTPSErrors:!0}:{},permissions:e(async({},v,C)=>{if(!pZe)await v(C.project.use.permissions);else{let w=new Set(C.project.use.permissions);w.add("clipboard-read"),w.add("clipboard-write"),w.add("camera"),w.add("storage-access"),w.add("notifications"),w.add("geolocation"),w.add("microphone"),await v(Array.from(w))}},"permissions"),proxy:e(async({proxy:v},C)=>{v?await C({...v,bypass:"127.0.0.1,localhost"}):await C(v)},"proxy"),browser:e(async({browser:v,browserName:C,launchOptions:w},T,k)=>{let R=e(()=>(k.project.use.playwrightExtra||[]).some(X=>X.constructor.name==="StealthPlugin"),"checkIfStealthPluginExists"),B=e(async()=>{let W=await(await new hrr({project:k.project}).buildChromiumWithPlugins()).launch(w);await T(W)},"launchBrowserWithStealthPlugin");pZe?V0.vtg.isSeparateProcess?await T(v):R()?(console.log("StealthPlugin already configured"),await T(v)):await B():V0.useRemoteDebugging.enabled&&R()?await B():await T(v)},"browser"),launchOptions:e(async({launchOptions:v},C)=>{var k;let w=v!=null&&v.args?[...v.args]:[],T=e(R=>{w.includes(R)||w.push(R)},"pushArg");if(r.useMockData&&T("--disable-web-security"),V0.bypassProxyForLocalhost&&T("--proxy-bypass-list=localhost,127.0.0.1"),pZe){T("--proxy-bypass-list=localhost,127.0.0.1"),V0.vtg.isSeparateProcess&&T(`--remote-debugging-port=${V0.vtg.appRemoteDebuggingPort}`);let R=((k=r.modelConfig)==null?void 0:k.browserArgs)??{};R.skipDisableWebSecurity||T("--disable-web-security"),R.skipAllowFileAccessFromFiles||T("--allow-file-access-from-files"),R.skipDisableSiteIsolationTrials||T("--disable-site-isolation-trials"),R.skipAllowRunningInsecureContent||T("--allow-running-insecure-content")}V0.useRemoteDebugging.enabled&&T(`--remote-debugging-port=${V0.useRemoteDebugging.port}`),await C({...v,args:w})},"launchOptions"),variableStore:e(async({},v)=>{let C=new yWe;await v(C)},"variableStore"),vs:e(async({variableStore:v},C)=>{await C(v)},"vs"),variablesStore:e(async({variableStore:v},C)=>{await C(v)},"variablesStore"),testRunAnalytics:e(async({},v,C)=>{let w=(()=>{try{if(process.env.CHECKSUM_TEST_SUITE_INFO)return JSON.parse(process.env.CHECKSUM_TEST_SUITE_INFO);throw new Error("Missing Checksum test suite info")}catch{return console.warn("\u26A0\uFE0F Warning: It seems like you ran the test suite directly via Playwright. This can lead to degraded functionality and unexpected issues. To ensure a fully supported and stable test run, please use: 'npx checksumai test'."),NEi("playwright-run-version-unknown",(0,BEi.randomUUID)())}})(),T=OEi(C),k=rie.getTestRunInstance({...w,checksumTestId:T},process.env.CHECKSUM_ISOLATED_MODE==="true",C);await v(k)},"testRunAnalytics"),monitorBridge:[async({},v,C)=>{let w=new wzt(C);await v(w)},{scope:"worker"}],context:e(async({context:v,monitorBridge:C,variableStore:w,testRunAnalytics:T},k,R)=>{let B=grr.makeContext(v,pZe);B.setTestAssets({testRunAnalytics:T,monitorBridge:C,variableStore:w,testInfo:R,checksumTestId:OEi(R),test:_,config:t,isReplMode:a}),await k(B),B.cleanup()},"context"),page:e(async({page:v,context:C},w,T)=>{let k=await C.makePage(v);await w(k),k&&typeof k.onTestComplete=="function"&&await k.onTestComplete(T.status==="passed"),k&&typeof k.shutdown=="function"&&await k.shutdown()},"page"),vtg:e(async({page:v},C)=>{if(!pZe)C(null);else if(V0.vtg.isSeparateProcess){let w=new drr(t);await w.run(v),await C(w)}else{let w=new frr(["--test-file"],!1,t);await w.run(v),await C(w)}},"vtg")});return{test:_,defineChecksumTest:dts}},"createChecksumTestExtension"),dts=e((i,t,r)=>{let o=new Error().stack.split(`
2044
2044
  `).filter(c=>c.includes(".checksum.spec.ts"))[0];if(!o)throw new Error("Could not locate test location. Make sure test is run from valid checksum test file");return Nhn[o]=t,i},"defineChecksumTest");function OEi(i){let{file:t,line:r}=i,a=Object.keys(Nhn).filter(c=>c.trim().includes(t.trim()));if(!a.length)return;let o=4;for(let c=0;c<o;c++)for(let f of a){let _;try{_=parseInt(f.split(":").reverse()[1])}catch{continue}if(_-c===parseInt(r))return Nhn[f]}}e(OEi,"getCurrentTestIdFromMapping");fQ();JH();jne();fQ();var mts=["toPass"],_ts=["toBeOK"],hts=["toBeAttached","toBeChecked","toBeDisabled","toBeEditable","toBeEmpty","toBeEnabled","toBeFocused","toBeHidden","toBeInViewport","toBeVisible","toContainClass","toContainText","toHaveAccessibleDescription","toHaveAccessibleErrorMessage","toHaveAccessibleName","toHaveAttribute","toHaveClass","toHaveCount","toHaveCSS","toHaveId","toHaveJSProperty","toHaveRole","toHaveScreenshot","toHaveText","toHaveValue","toHaveValues","toMatchAriaSnapshot"],gts=["toHaveScreenshot","toHaveTitle","toHaveURL"],yts=["toMatchSnapshot"],vts=["toBe","toBeCloseTo","toBeDefined","toBeFalsy","toBeGreaterThan","toBeGreaterThanOrEqual","toBeInstanceOf","toBeLessThan","toBeLessThanOrEqual","toBeNaN","toBeNull","toBeTruthy","toBeUndefined","toContain","toContainEqual","toEqual","toHaveLength","toHaveProperty","toMatch","toMatchObject","toStrictEqual","toThrow","toThrowError"],LEi=[...vts,...yts],Nqo=[...mts,..._ts,...hts,...gts];var Ohn=class Ohn{constructor(t,r,a=!1,o=!1,c={}){this.page=t;this.soft=a;this.skipAutoRecovery=o;this.configuration=c;this.fallbackEnabled=!1;this.withChecksumAI=!1;this.withChecksumAIMatcher=e(async()=>{throw this.withChecksumAI=!0,new Error},"withChecksumAIMatcher");this.setThought(r)}setThought(t){var r,a;t&&(this.checksumAIThought=this.page.addNewThought(t,"assertion"),this.useChecksumAIOptions=(r=this.page.getRuntimeOptions())==null?void 0:r.useChecksumAI,(a=this.useChecksumAIOptions)!=null&&a.assertions&&(this.page.setAIFallback(t,"assertion"),this.fallbackEnabled=!0))}get(t,r,a){if(typeof r!="string")return t[r];if(r==="checksumAI")return o=>(this.setThought(o),a);if(r==="withChecksumAI"||typeof t[r]=="function"){let o=r==="withChecksumAI"?this.withChecksumAIMatcher:t[r];return(...c)=>LEi.includes(r)?o.call(t,...c):this.checksumAIThought?this.executeMatcherWithinStep(o,t,...c):this.executeMatcher(o,t,...c)}else{let o=t[r];return new Proxy(o,this)}}findNestedErrors(t,r){t.error&&t.infectParentStepsWithError&&r.push(t.error);for(let a of t.steps)this.findNestedErrors(a,r)}async callMatcher(t,r,...a){this.beforeMatcherCall();let o=t.call(r,...a),c=o instanceof Promise?await o:o;if(this.step){let f=[];if(this.step.error?f.push(this.step.error):this.findNestedErrors(this.step,f),f.length)throw f[0]}return c}executeMatcherWithinStep(t,r,...a){return this.page.step(this.checksumAIThought.thought,()=>this.callMatcher(t,r,...a).catch(this.onMatcherFailure.bind(this)),!1,{obtainStep:e(o=>this.step=o,"obtainStep")}).catch(o=>{if(!this.soft&&!(this.withChecksumAI&&o.message===B4e))throw o}).finally(this.afterMatcherExecute.bind(this))}async executeMatcher(t,r,...a){try{return await this.callMatcher(t,r,...a)}catch(o){await this.onMatcherFailure(o)}finally{this.afterMatcherExecute()}}beforeMatcherCall(){this.page.setExpectConfiguration(this.configuration)}afterMatcherExecute(){this.checksumAIThought=void 0,this.fallbackEnabled=!1,this.withChecksumAI=!1,this.page.resetFallbacks(),this.page.setExpectConfiguration(void 0)}shouldInitiateFallback(t){var a;return!(!this.fallbackEnabled||((a=t.matcherResult)==null?void 0:a.name)==="toHaveScreenshot"&&!this.useChecksumAIOptions.visualComparison)}async onMatcherFailure(t){var r,a;if(!this.shouldInitiateFallback(t))throw Dv("[onMatcherFailure] fallback disabled, continuing with error."),this.page.testRunAnalytics.testRunAssertionExecutionFailure({failedThought:(r=this.checksumAIThought)==null?void 0:r.thought,error:t.message,matcher:(a=t.matcherResult)==null?void 0:a.name}),t;if(Dv("[onMatcherFailure] initiating fallback sequence with thought:",this.checksumAIThought.thought),this.skipAutoRecovery){if(this.soft)return;throw t}try{await this.page.initiateFallbackSequence({type:"assertion",error:t,withChecksumAI:this.withChecksumAI,testInfo:this.page.testInfo})}catch(o){if(this.soft)return;throw o}throw this.soft=!0,t}};e(Ohn,"ExpectCallProxyHandler");var yrr=Ohn;var Yvt=class Yvt{constructor(t=void 0,r={}){this.page=t;this.configuration=r}get(t,r){return r==="setPage"?a=>{this.page=a}:r==="extend"?(...a)=>{let o=t.extend(...a);return new Proxy(o,this)}:r==="configure"?a=>{let o=t.configure(a);return new Proxy(o,new Yvt(this.page,{...this.configuration,...a}))}:r==="soft"?(...a)=>{let o=this.manipulateArgsAndExtractThought(a),c=t.soft(...a);return new Proxy(c,this.makeExpectCallProxyHandler(o,!0))}:r==="poll"?(...a)=>{let o=this.manipulateArgsAndExtractThought(a),c=t.poll(...a);return new Proxy(c,this.makeExpectCallProxyHandler(o))}:r==="skipAutoRecovery"?new Proxy(()=>{},{apply:e((o,c,f)=>{let _=this.manipulateArgsAndExtractThought(f),v=t.apply(c,f);return new Proxy(v,this.makeExpectCallProxyHandler(_,void 0,!0))},"apply"),get:e((o,c)=>new Proxy(t,new Yvt(this.page,{...this.configuration,skipAutoRecovery:!0}))[c],"get")}):t[r]instanceof Function?t[r].bind(t):t[r]}apply(t,r,a){let o=this.manipulateArgsAndExtractThought(a),c=t.apply(r,a);return new Proxy(c,this.makeExpectCallProxyHandler(o))}makeExpectCallProxyHandler(t,r,a){var o,c;return new yrr(this.page,t,r===!0?!0:(o=this.configuration)==null?void 0:o.soft,a===!0?!0:(c=this.configuration)==null?void 0:c.skipAutoRecovery,this.configuration)}manipulateArgsAndExtractThought(t){let r,a=t[1];if(typeof a=="string")r=a,t[1]=void 0;else if(typeof a=="object"){if(a.checksumAI===!1){t[1].checksumAI=void 0;return}a.checksumAI&&typeof a.checksumAI=="string"?(r=a.checksumAI,t[1].checksumAI=void 0):a.message&&(r=a.message,t[1].message=void 0)}return r}};e(Yvt,"ExpectProxyHandler");var vrr=Yvt;var xrr=class xrr{constructor(t){this.expect=t;this.proxy=new Proxy(this.expect,new vrr)}static init(t){return new xrr(t).proxy}};e(xrr,"ChecksumExpect");var brr=xrr;v7();var UEi=require("@playwright/test");fQ();var MEi=sf(bT()),Arr=require("fs");var Xvt=sf(require("path"));var bts=e(i=>{let t=H7e(i),r=new G7e(t),a=r1t();return r.transformSourceFile([new rNe(i),new nGe(i,a,{newRequireIdentifier:"checksumHotRequire",extraImportArguments:[MEi.factory.createIdentifier("__filename")]})]),`${iri}
2045
2045
  ${r.getTestFileCode().code}`},"transformFileToHoRequireFormat"),xts=e(i=>{let t=Xvt.default.dirname(i),a=Xvt.default.basename(i).split(".")[0],o=Math.random().toString(36).substring(2,15),c=Xvt.default.extname(i);return Xvt.default.join(t,`${a}-${Date.now()}-${o}${c}`)},"generateTempFilePath"),Ats=e((i,t)=>{let r=r1t();return new K7e(t,r).getResolvedPath(i)},"resolveFilePath"),Ets=e((i,t=__filename)=>{let r;try{let a=require.resolve(Ats(i,t)),o=bts(a);r=xts(a),(0,Arr.writeFileSync)(r,o);let c=require(r);return require.cache[a]=require.cache[r],c}catch(a){throw console.error("Error in require",a),a}finally{r&&(0,Arr.unlinkSync)(r)}},"checksumHotRequire"),jEi=Ets;Eve();function Cts(i){let t=sQt(),{options:r,apiKey:a,environments:o}=t,c=o.find(R=>R.default);if(!c)throw new Error("No default environment found. Please set the default field to true on one of the environments in the checksum.config.ts file.");if(!c.baseURL)throw new Error("A baseURL is required. Please set the baseURL field in the default environment in the checksum.config.ts file.");if(!c.users.find(R=>R.default))throw new Error("A default user within the default environment is required. Please set one of the default environment users as default in the checksum.config.ts file.");if(!a)throw new Error("An API key is required. Please set the apiKey field in the checksum.config.ts file.");let _=process.env.CHECKSUM_REPL==="true",{test:v,defineChecksumTest:C}=REi(i??UEi.test,t,r,_),w=brr.init(v.expect),T=wts();v._checksum={expect:w,checksumAI:T},_&&(console.log("Detected REPL mode"),v.beforeEach(async()=>{v.setTimeout(0)}),v.afterEach(async()=>{for(;;)await TA(1e3)}));let k=e(({name:R,userRole:B})=>{let{environment:U,user:W}=K_t(t,{environment:R,role:B},!0),X=MJn({config:t,throwIfEnvInfoInvalid:!0},{environmentName:U.name,userRole:W.role});return{environment:U,user:W,login:X}},"getEnvironment");return{test:v,expect:w,login:Ube({config:t}),defineChecksumTest:C,getEnvironment:k,checksumAI:T}}e(Cts,"init");var Bhn=e(i=>new Proxy(i,{apply:e(function(r,a,o){let c={...r.options,...o[2]};return r.page.checksumAI(o[0],o[1],c)},"apply"),get:e(function(r,a){return a==="withDialog"?(r.options.withDialog=!0,Bhn(i)):a==="skipAutoRecovery"?(r.options.skipAutoRecovery=!0,Bhn(i)):r[a]},"get"),set:e(function(r,a,o){if(a==="page")return r[a]=o},"set")}),"makeChecksumAIProxy"),wts=e(()=>{let i=e(function(){},"func");return i.page=void 0,i.options={withDialog:!1,withTomer:!1,skipAutoRecovery:!1},Bhn(i)},"makeChecksumAI");0&&(module.exports={AutoRecoveryMode,RunMode,checksumHotRequire,getChecksumConfig,getLogin,init});
2046
2046
  /*! Bundled license information:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@checksum-ai/runtime",
3
- "version": "2.0.13",
3
+ "version": "2.0.14-beta",
4
4
  "description": "Checksum.ai test runtime",
5
5
  "main": "index.js",
6
6
  "dependencies": {
@@ -1927,8 +1927,8 @@ ${JSON.stringify(t,null,2)}
1927
1927
  ${Uht}`})).join(`
1928
1928
  ${Uht}`),c=new JHe(r.sourceFile),f=(k=this.userStoryService.getStory())==null?void 0:k.internalTestId,_=(R=this.userStoryService.getStory())==null?void 0:R.goal,v=(B=this.userStoryService.getStory())==null?void 0:B.id;c.transformSourceFile([new cWt(r.sourceFile),new _Wt(r.sourceFile,{internalTestId:f,title:_}),new uWt(r.sourceFile,r.testMirrors.filter(U=>U.internalTestId===f||U.storyId===v).map(U=>U.testBody),Tti(o))]);let w=this.testAssetsManager.getSavedTestFilePath(),{error:C}=await c.write(w,Uht);return{filePath:(0,HHe.relative)(process.cwd(),w),error:C}}get isLoadedFromTestFile(){return!!this.vtgTestFileRunConfig}async reloadTestFromFile(t){if(!this.vtgTestFileRunConfig)return;let r=await this.getReloadTestEnvironmentCode();await this.evaluationService.execute(r);let o=new Qht(this.testAssetsManager.getSavedTestFilePath()).loadActionsFromSingleTest({mergeCustomCodeSteps:this.settingsService.getSettings().mergeCustomCodeSteps});return t&&await this.mergeTimestampsToReloadedActions(o),this.actionsManager.reloadTestSteps(o),o}async mergeTimestampsToReloadedActions(t){let r=this.actionsManager.actions,a=await this.apiService.post("llm/query",{systemMessage:Bti(),userMessage:Rti(r,t)});try{let o=await a.text(),c=JSON.parse(o),f=0;t.forEach((_,v)=>{var C,T;let w=c.map[v];if(w){let k=r.find(({id:R})=>R===w.id);if(k){_.timestamp=k.timestamp,f=k.timestamp;let R=f;(C=_.assertions)==null||C.forEach((B,U)=>{var ne;let W=w==null?void 0:w.assertions[U],X=(ne=k.assertions)==null?void 0:ne.find(({id:ce})=>ce===W);X?(B.timestamp=X.timestamp,R=X.timestamp):B.timestamp=R+1});return}}_.timestamp=f+1,(T=_.assertions)==null||T.forEach((k,R)=>{k.timestamp=f+R+1})})}catch(o){return uf.error("Failed to merge actions",o),null}}async getReloadTestImportCodeOfNewPackages(t,r,a){let o=new JHe(r);o.transformSourceFile([new Hht(t,a,{filterOutChecksumImports:!0,filterOutLocalModules:!0,filterOutTypes:!0,filterSideEffectImports:!0,filterOutNotImportOrRequireStatements:!0}),new $ht(t),new Ght,new Wht]);let c=await this.getDeclaredVariableNames(o.sourceFile);return o.transformSourceFile([new Vht(r,c,{filterOutDefinedVariableNames:!0})]),(await o.getFormattedTestFileCode()).code}async getDeclaredVariableNames(t){return new dWt(this.evaluationService).extractDeclaredVariableNames(t)}async getReloadTestEnvironmentCode(){let t=this.testAssetsManager.getSavedTestFilePath(),r=VHe(t),a=Iti(),o=await this.getReloadCodeWithoutPackages(t,r,a);return[await this.getReloadTestImportCodeOfNewPackages(t,r,a),o].join(`
1929
1929
  `)}async getReloadCodeWithoutPackages(t,r,a){let o=new JHe(r);o.transformSourceFile([new mWt({shouldRemoveTestExpression:!0,shouldRemoveTestCalls:!0}),new lWt,new Hht(t,a,{filterOutNodeModules:!0,filterOutTypes:!0,filterSideEffectImports:!0,filterOutChecksumImports:!0}),new $ht(t),new pWt(t,a,{newRequireIdentifier:"checksumHotRequire",extraImportArguments:[qti.default.factory.createIdentifier("__filename")]}),new Ght,new Wht]);let c=await this.getDeclaredVariableNames(o.sourceFile);return o.transformSourceFile([new Vht(r,c)]),(await o.getFormattedTestFileCode()).code}getLocalSavedJSONFilePath(t,r){var c;r??(r=r||((c=this.userStoryService.getStory())==null?void 0:c.id));let a=this.testAssetsManager.getLocalAutoSaveFileName(r);return`${t==="auto-save"?this.testAssetsManager.getLocalAutoSavePath():this.testAssetsManager.getLocalSavePath()}/${a}`}readLocalSavedDataFromJSONFile(t){let r=this.readJsonFile(t);return r?{...r,executedActions:r.executedActions.map(a=>({...a,timestamp:void 0}))}:null}readJsonFile(t){try{let r=(0,$7e.readFileSync)(t,"utf-8");return JSON.parse(r)}catch(r){return uf.error(`Error reading or parsing JSON file: ${r}`),null}}makeDraftData(){let t=this.userStoryService.getStory(),r=this.userStoryService.getTestGenerationData(),a=this.userStoryService.getEnvInfo(),o={};return t!=null&&t.version&&(o.version=t.version),{actions:this.actionsManager.actions,internalTestId:t.internalTestId,environmentUserId:a.user.username,description:t.goal,metadata:Object.keys(o).length>0?o:void 0}}async generateTestFileString(t){try{let r=this.makeDraftData(),a=t?`${t}.draft.spec.ts`:`test-${r.internalTestId}.draft.spec.ts`,o=await this.apiService.post("test-generation/generate-test-file-string",r);if(!o.ok)throw new Error(`test generation request failed: ${o.statusText}`);let c=await o.text();GHn(c,a,this.testAssetsManager.getLocalSavePath())}catch(r){throw uf.error("Failed to generate test file string",r),new Error("Failed to generate test file string")}}localSave(){let t=JSON.stringify(this.vtgTestJSON,null,2),r=this.testAssetsManager.getAssetsFolderPath(),a=this.testAssetsManager.getLocalAutoSaveFileName(this.userStoryService.getStory().id);(0,$7e.writeFileSync)(`${r}/${a}`,t),(0,$7e.writeFileSync)(`${this.testAssetsManager.getLocalAutoSavePath()}/${a}`,t)}get vtgTestJSON(){var t;return{executedActions:this.actionsManager.actions,testGenerationData:this.userStoryService.getTestGenerationData(),settings:{baseURL:(t=this.config.environments.find(r=>r.default))==null?void 0:t.baseURL,assetsFolderPath:this.testAssetsManager.getAssetsFolderPath(),didLogin:this.actionsService.hasLoggedIn(),traceFilePath:this.testAssetsManager.getTraceFilePath(),harFilePath:this.testAssetsManager.getHarFilePath()},story:this.userStoryService.getStory()}}async extendedJSONBackup(){let t=await this.saveExtendedJson(),r=(0,HHe.dirname)(this.testAssetsManager.getSavedTestFilePath()),a=(0,HHe.join)(r,"test.extended.json");return(0,$7e.writeFileSync)(a,JSON.stringify(t,null,2)),{executedActions:t}}async localBackup(t){var r;if(t){this.testAssetsManager.setCurrentSaveAsLocation(t);let a=this.testAssetsManager.getLocalSaveAsPath(),o=this.testAssetsManager.getLocalAutoSavePath(),c=(r=this.userStoryService.getStory())==null?void 0:r.id,f=c?[this.testAssetsManager.getLocalAutoSaveFileName(c)]:[];KHn(o,a,f)}return await this.saveTestFile()}async saveExtendedJson(){let t=[...this.actionsManager.actions],r=[],a=e(async o=>{let{timestamp:c}=o,f="matcher"in o,_=o.timestamp&&(f||bft(o.eventCode)),{fullHTML:v,outerHTML:w,parentHTML:C,rrwebSnapshot:T}=o.timestamp?await this.getHTMLsForTimestamp(c,o.locator):{fullHTML:"",outerHTML:"",parentHTML:void 0,rrwebSnapshot:""},k=f?Rie.generateSingleAssertionCode(o):Rie.generateSingleActionCode(o,{newLineSeparator:`
1930
- ${Uht}`,generateAssertionsCode:!1}),R=_?await this.takeElementSnapshot(o.locator,c):void 0;return{code:k,fullHTML:v,outerHTML:w,parentHTML:C,timestamp:c,image:R,rrwebSnapshot:T}},"extractDataForStep");for(let o=0;o<t.length;o++){uf.info(`processing action ${o} of ${t.length}`);let c=t[o],f=await a(c);r.push(f);for(let _ of c.assertions||[]){uf.info(`processing assertion of ${c.assertions.length} assertions`);try{let v=await a(_);r.push(v)}catch(v){uf.error("Failed to extract data for assertion",v)}}}return r}async takeElementSnapshot(t,r){try{return`data:image/jpeg;base64,${(await this.taskTimeMachine.executeTask(async o=>(await this.evaluationService.getLocator(`return ${lj(t)}`,o.frameLocator("iframe"))).screenshot({omitBackground:!0,type:"jpeg"}),r)).toString("base64")}`}catch(a){uf.error("Failed to take element snapshot",a);return}}async getHTMLsForTimestamp(t,r){try{return r?await this.taskTimeMachine.executeTask(async o=>{let c=await this.evaluationService.getLocator(`return ${lj(r)}`,o.frameLocator("iframe")),f=await c.elementHandle(),{fullHTML:_,outerHTML:v,rrwebSnapshot:w}=await o.page().evaluate(({element:T})=>{let k="",R="",B="",U=document.querySelector(".replayer-wrapper iframe").contentDocument;try{R=U.querySelector("html").outerHTML}catch{R=""}try{B=T.outerHTML}catch{B=""}try{k=JSON.stringify(window.checksum.timeMachine.rrwebSnapshot(U))}catch{k=""}return{fullHTML:R,outerHTML:B,rrwebSnapshot:k}},{element:f}),C=await Lti(c);return{fullHTML:_,outerHTML:v,parentHTML:C,rrwebSnapshot:w}},t):{fullHTML:"",outerHTML:""}}catch(a){return uf.error("Failed to get HTML data for extended JSON backup",a),{}}}doesFolderExistInSaveDir(t){try{let r=`${this.testAssetsManager.getLocalSavePath()}/${t}`;return(0,$7e.statSync)(r).isDirectory()}catch(r){if(r.code==="ENOENT")return!1;throw r}}async saveToCloud(){var t;try{let{testGenerationId:r}=await this.userStoryService.createTestGeneration();await this.saveTestFile();let a=await this.settingsService.getIsGitReflectionEnabled();if(!a){let f=new jJt(this.apiService.getBaseURL(),this.config.apiKey,null,()=>`test-generation/${r}/get-upload-url`),_=e(C=>({complete:!1,error:!1,response:void 0,info:C}),"buildUploadAsset"),v=[],w=(t=this.userStoryService.getStory())==null?void 0:t.internalTestId;await f.uploadAsset(_({type:"test-fix-files",path:this.testAssetsManager.getSavedTestFilePath(),fileName:`test-${w}.fix.checksum.spec.ts`})),v.push(_({type:"trace",path:this.testAssetsManager.getTraceFilePath()})),v.push(_({type:"har",path:await Uti(this.testAssetsManager.getHarFolderPath())})),this.actionsManager.actions.filter(C=>C.eventCode==="upload_files").forEach(C=>{var T;(T=C.files)==null||T.forEach(k=>{v.push(_({type:"test-files",path:k}))})}),await Promise.all(v)}let o=this.actionsManager.actions.map(f=>({...f,parentFramesSelectors:f.parentFramesSelectors?f.parentFramesSelectors.filter(_=>_!=="iframe"):void 0})),c={};if(a){let f=this.userStoryService.getStory();f!=null&&f.version&&(c.version=f.version)}await this.apiService.post(`test-generation/${r}/completed`,{actions:o,metadata:Object.keys(c).length>0?c:void 0})}catch(r){uf.error("Failed to upload test",r)}}};e(fGr,"VtgStorageService");var hWt=fGr;Rzr();Bne();var dGr=class dGr{constructor(){this._executedActions=[];this.onActionExecuted=this.pushExecutedActionOrAddAfterParent.bind(this)}get actions(){return this._executedActions}set executedActions(t){var r;this._executedActions=t,(r=this.storageService)==null||r.localSave()}addAction(t){var r;this._executedActions.push(t),(r=this.storageService)==null||r.localSave()}setActions(t){this._executedActions=t}updateAssertionById(t,r){let a=r;return this.executedActions=this._executedActions.map(o=>{var c;if(o.id===t){let f=!!((c=o.assertions)!=null&&c.find(({id:v})=>v===r.id)),_={...o};return f?_.assertions=o.assertions.map(v=>{if(v.id===r.id){let w={...v,...r};return a=w,w}return v}):_.assertions=[...o.assertions??[],r],{..._,assertions:_.assertions.sort((v,w)=>v.timestamp!==w.timestamp?v.timestamp-w.timestamp:v.createdAt-w.createdAt)}}return o}),a}setStorageService(t){this.storageService=t}createAction(t){var v,w,C;let{id:r,data:a,options:o,type:c}=t,f={id:r,...a},_=[...this._executedActions];switch(o==null?void 0:o.type){case"insertAfter":{let T=this.findActionOrAssertionById(o.afterStepId),k=_.findIndex(R=>R.id===T.action.id);if(T.assertion||(w=(v=T.action)==null?void 0:v.assertions)!=null&&w.length){let R=T.assertion??T.action.assertions[0],{before:B,after:U}=P9a(((C=_[k])==null?void 0:C.assertions)??[],R.id,!!T.assertion);_[k].assertions=B,f.assertions=U.map(W=>({...W,actionId:f.id}))}k!==-1?_.splice(k+1,0,f):_.push(f);break}case"insertLast":_.push(f);break;case"replace":{let T=_.findIndex(k=>k.id===o.stepId);T!==-1&&_.splice(T,1,f);break}case"replaceLast":_.length>0&&(_[_.length-1]=f);break}return this.executedActions=_,f}pushExecutedActionOrAddAfterParent(t,r={}){if(r.previousActionId){let a=this._executedActions.findIndex(({id:o})=>o===r.previousActionId);if(a!==-1){let o={...t,timestamp:this._executedActions[a].timestamp+1};this._executedActions=[...this._executedActions.slice(0,a+1),o,...this._executedActions.slice(a+1)]}}else this.executedActions=Array.isArray(t)?[...this._executedActions,...t]:[...this._executedActions,t]}addManualActionsToExecuted(t){this.executedActions=[...this._executedActions,t]}updateExecutedAction(t){let r=this._executedActions.findIndex(({id:a})=>a===t.id);if(r!==-1){let a={...this._executedActions[r],...t};return this.executedActions=[...this._executedActions.slice(0,r),a,...this._executedActions.slice(r+1)],a}throw new Error("Action was not found")}deleteStep(t,r,a={assertionsOnly:!1,withAssertions:!0}){r==="Action"?this.deleteAction(t,a):r==="Assertion"&&(this.executedActions=this._executedActions.map(o=>(o.assertions=(o.assertions??[]).filter(c=>c.id!==t),o)))}deleteAction(t,r={assertionsOnly:!1,withAssertions:!0}){var o;let a=this._executedActions.find(c=>c.id===t);if(!a)throw new Error(`Action with id "${t}" not found`);r.assertionsOnly?this.executedActions=this._executedActions.map(c=>c.id===t?{...c,assertions:[]}:c):!r.withAssertions&&((o=a==null?void 0:a.assertions)!=null&&o.length)?this.deleteActionAndMergeAssertions(t):this.executedActions=this._executedActions.filter(c=>c.id!==t)}deleteActionAndMergeAssertions(t){let r=this._executedActions.findIndex(_=>_.id===t);if(r===-1)throw new Error(`Action with id "${t}" not found`);if(r===0)throw new Error("Cannot remove the first action; no previous action to merge assertions into");let a=this._executedActions[r-1],o=this._executedActions[r];o.assertions||(o.assertions=[]);let c=o.assertions.map(_=>({..._,actionId:a.id})),f={...a,assertions:[...a.assertions??[],...c]};this.executedActions=[...this._executedActions.slice(0,r-1),f,...this._executedActions.slice(r+1)]}clearTestSteps(t=!0){if(t){let{navigation:r,login:a}=this.findLoginAndNavigationActions();this.executedActions=this._executedActions.reduce((o,c)=>([r==null?void 0:r.id,a==null?void 0:a.id].includes(c.id)&&o.push({...c,assertions:[]}),o),[])}else this.executedActions=[];return this._executedActions}reloadTestSteps(t){this.clearTestSteps(!1),this.executedActions=t}findLoginAndNavigationActions(){let t=this._executedActions.find(({eventCode:a})=>a==="navigation"),r=this._executedActions.find(({eventCode:a})=>a==="login");return{navigation:t,login:r}}addAssertionToAction(t,r){this.executedActions=this._executedActions.map(a=>{if(a.id!==t.actionId)return a;if(a.assertions||(a.assertions=[]),r){let o=a.assertions.findIndex(({id:c})=>r===c);a.assertions.splice(o+1,0,t)}else a.assertions=[t,...a.assertions??[]];return a})}findActionByAssertionId(t){return this._executedActions.find(({assertions:r=[]})=>r.find(a=>a.id===t))}replaceAssertion(t,r){let a=this.findActionByAssertionId(r);if(!a)throw new Error(`No action found containing assertion with id ${r}`);this.executedActions=this._executedActions.map(o=>o.id===a.id?{...o,assertions:(o.assertions??[]).map(c=>c.id===r?{...t,actionId:a.id}:c)}:o)}findActionOrAssertionById(t){let r={action:null,assertion:null};if(this._executedActions.forEach(a=>{a.id===t&&(r.action=a);let o=(a.assertions??[]).find(c=>c.id===t);o&&(r={action:a,assertion:o})}),!r.action&&!r.assertion)throw new P7e(t);return r}async buildStepDataWithCode(t,{loadingFromFile:r}={loadingFromFile:!1}){let a=F9a(t);return await Promise.all(a.map(async({step:o,type:c})=>{let f=await JFe(zHe([o],void 0,{generateAssertionsCode:!1},(_,v)=>{o=v}));return{type:c,step:{...o,loadedFromFile:r},code:f}}))}};e(dGr,"VtgActionsManager");var gWt=dGr,P9a=e((i,t,r=!0)=>{let a=Number(r),o=i.findIndex(_=>_.id===t);if(o===-1)return{before:i,after:[]};let c=i.slice(0,o+a),f=i.slice(o+a);return{before:c,after:f}},"splitArrayAtId"),F9a=e(i=>i.reduce((t,r)=>{var c;let{assertions:a,...o}=r;if(t.push({step:o,type:"Action"}),(c=r.assertions)!=null&&c.length){let f=r.assertions.map(_=>({type:"Assertion",step:{..._,actionId:r.id}}));t.push(...f)}return t},[]),"transformActionsListToVTGStepsDataList");var QHt=hf(IHt()),Gui=hf(require("net")),Kui=hf(HKr()),Yui=hf(Wui());var GYr=class GYr extends Error{constructor(t){super(t),this.name="ValidationError"}};e(GYr,"ValidationError");var xGe=GYr,KYr=class KYr extends Error{constructor(t){super(t),this.name="NotFoundError"}};e(KYr,"NotFoundError");var AGe=KYr;MC();var kv=e(i=>(t,r,a)=>{Promise.resolve(i(t,r,a)).catch(o=>{if(uf.error(`${t.method} ${t.path} error:`,o),o instanceof P7e)return r.status(200).json({error:o.message});if(o instanceof xGe)return r.status(400).send({error:o.message});if(o instanceof AGe)return r.status(404).send(o.message);a(o)})},"asyncErrorHandler");MC();var YYr=hf(IHt());var EGe=class EGe{constructor(){this.routesLogRules={};this.router=(0,YYr.Router)()}getRoutesLogRules(){return this.routesLogRules}getRouter(){return this.router}createPrefixedRouter(t){let r=(0,YYr.Router)(),a=t.startsWith(EGe.DEFAULT_API_PREFIX)?t:`${EGe.DEFAULT_API_PREFIX}${t.startsWith("/")?t:`/${t}`}`;return this.router.use(a,r),r}startAsyncProcess(t,r,a,o="unknown"){uf.info(`Starting async ${o} process: ${r} for step: ${a}`),t().catch(c=>{uf.error(`Async process ${r} failed:`,c)})}};e(EGe,"VTGController"),EGe.DEFAULT_API_PREFIX="/api";var p5=EGe;var XYr=class XYr extends p5{constructor(r,a,o,c){super();this.assertionsService=r;this.actionsManager=a;this.actionsService=o;this.aiTestGenerationService=c;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter(""),a=this.createPrefixedRouter("/steps");r.post("/createStep",kv(async(o,c)=>{let f=o.body,_;f.type==="Assertion"&&(_=this.assertionsService.createAssertion(f)),f.type==="Action"&&(_=this.actionsManager.createAction(f));let v=await JFe(zHe([_],void 0,{generateAssertionsCode:!1},(w,C)=>{_=C}));return c.status(200).json({step:_,code:v})})),r.patch("/updateStep",kv(async(o,c)=>{let f=o.body,_=f==null?void 0:f.options,v;f.type==="Assertion"&&(v=await this.assertionsService.updateAssertion({id:f.id,data:f.data})),f.type==="Action"&&(v=this.actionsManager.updateExecutedAction({...f.data,id:f.id}));let w;_!=null&&_.forceUpdateTimestamp||(f.data.thought===""&&(v.thought=void 0),w=await JFe(zHe([v],void 0,{generateAssertionsCode:!1},(C,T)=>{v=T}))),c.status(200).json({step:v,code:w})})),r.delete("/deleteStep",kv(async(o,c)=>{let{id:f,options:_,type:v}=o.body;return this.actionsManager.deleteStep(f,v,_),c.status(200).send({message:"Success!"})})),r.post("/clear-test",kv(async(o,c)=>{let f=this.actionsManager.clearTestSteps();return c.status(200).send(f)})),a.post("/execute",kv(async(o,c)=>{let f=o.body;try{let _=null;return wqa(f)?_=await this.aiTestGenerationService.executeAction(f):Cqa(f)&&(_=await this.actionsService.executeAction(f)),c.status(200).json(_)}catch(_){return c.status(400).send({error:_.message})}})),r.put("/steps",kv(async(o,c)=>(this.actionsManager.pushExecutedActionOrAddAfterParent(o.body.action,o.body.options),c.send("success")))),r.post("/code-to-steps",kv(async(o,c)=>{let _=Pti(o.body.code).map(v=>v&&"isChecksumAiWithDirectExpression"in v?{...v,isChecksumAiWithDirectExpression:!1}:v);return c.status(200).send(_)})),r.post("/steps-to-code",kv(async(o,c)=>{let f=zHe(o.body.steps,void 0,{generateAssertionsCode:!1});return c.status(200).send(f)}))}};e(XYr,"VtgStepsController");var PHt=XYr;function wqa(i){var t;return((t=i.options)==null?void 0:t.isAISuggestion)===!0}e(wqa,"isAIExecuteActionArgs");function Cqa(i){var t;return((t=i.options)==null?void 0:t.isAISuggestion)===!1}e(Cqa,"isManualExecuteActionArgs");MC();var ZYr=class ZYr extends p5{constructor(r){super();this.locatorsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/locators"),a=this.createPrefixedRouter("/ai/locators");r.post("/play",kv(async(o,c)=>{let f=o.body;try{let _=await this.locatorsService.verifyLocatorOrSelector(f);return c.status(200).send(_)}catch(_){return c.status(400).send({error:_.message})}})),a.post("/generate",kv(async(o,c)=>{let{step:f,target:_,processId:v}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.generateAILocators(f,_,v),v,_.id,"AI locators generation");let w={processId:v,stepId:_.id,success:!0};return c.status(200).json(w)}catch(w){return uf.error("Error generating AI locators:",w),c.status(500).send({processId:v,error:w.message})}})),a.post("/extract-css",kv(async(o,c)=>{let{step:f,target:_,processId:v,llmLocators:w}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.extractCSS(f,_,v,w),v,_.id,"CSS extraction");let C={processId:v,stepId:_.id,success:!0};return c.status(200).json(C)}catch(C){return uf.error("Error extracting CSS locators:",C),c.status(500).send({processId:v,error:C.message})}})),a.post("/filter",kv(async(o,c)=>{let{step:f,target:_,processId:v,candidates:w}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.filterLocators(f,_,v,w),v,_.id,"locators filtering");let C={processId:v,stepId:_.id,success:!0};return c.status(200).json(C)}catch(C){return uf.error("Error filtering locators:",C),c.status(500).send({processId:v,error:C.message})}})),a.delete("/process/:id",kv(async(o,c)=>{let{id:f}=o.params;return await this.locatorsService.cancelProcess(f),uf.info("Cancelled process",f),c.status(200).send({success:!0})})),r.post("/identical",kv(async(o,c)=>{let{locator:f,compareLocator:_,timestamp:v}=o.body;try{let w=await this.locatorsService.verifyAndCompareLocatorOnTimemachine(f,_,v);return c.status(200).send(w)}catch(w){return c.status(400).send({error:w.message})}})),r.post("/verify",kv(async(o,c)=>{try{let f=await this.locatorsService.verifyLocatorOrSelector(o.body);return c.status(200).send(f)}catch(f){return c.status(400).send({error:f.message})}}))}};e(ZYr,"VtgLocatorsController");var FHt=ZYr;var eXr=class eXr extends p5{constructor(r){super();this.codeService=r;this.routesLogRules={"/monaco/editor/types":{skipRequestData:!0,skipResponseData:!0}};this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/monaco").post("/editor/types",kv(async(a,o)=>{let{libs:c}=a.body;try{let f=this.codeService.getTypesForLibs(c??[]);return o.status(200).send({types:f})}catch(f){return o.status(400).send({error:f.message})}}))}};e(eXr,"MonacoController");var NHt=eXr;MI();var Sqa=K_.enum(["openai","anthropic","google-vertexai","groq"]),Hui=K_.strictObject({message:K_.string(),selection:K_.object({locator:K_.string()}).optional(),stepCode:K_.string().optional(),messageHistory:K_.array(K_.object({type:K_.enum(["user","assistant"]),content:K_.string(),timestamp:K_.string(),stepId:K_.string()})).optional(),model:K_.object({id:K_.string(),name:K_.string(),type:Sqa,model:K_.string(),thinking:K_.boolean().optional()}).optional(),includeImage:K_.boolean().optional(),includeHtml:K_.boolean().optional(),includeCode:K_.boolean().optional(),timestamp:K_.number(),error:K_.string().optional()});var tXr=class tXr extends p5{constructor(r){super();this.aiChatService=r;this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/ai-chat").post("/message",kv(async(a,o)=>{let c=Hui.safeParse(a.body);if(!c.success){o.status(400).json({error:"Invalid request body",details:c.error.format()});return}try{let f=await this.aiChatService.processMessage(c.data);o.json(f)}catch(f){o.status(500).json({error:"Failed to process message",message:f instanceof Error?f.message:"Unknown error"})}}))}};e(tXr,"AIChatController");var OHt=tXr;var Xui=hf(require("path"));N8();MC();var rXr=class rXr extends p5{constructor(r,a,o){super();this.storageService=r;this.actionsManager=a;this.actionsService=o;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/test"),a=this.createPrefixedRouter("");r.post("/generate-test-file-string",kv(async(o,c)=>{try{return await this.storageService.generateTestFileString(o.body.fileName),c.send("success")}catch(f){return c.status(400).send({error:f.message})}})),r.post("/upload",kv(async(o,c)=>(await this.storageService.saveToCloud(),c.send("success")))),r.post("/local-save",kv(async(o,c)=>{await this.storageService.localSave(),c.send("success")})),a.post("/reload-test-from-file",kv(async(o,c)=>{if(!this.storageService.isLoadedFromTestFile)throw new AGe("No test file found");let f=await this.storageService.reloadTestFromFile(o.body.useLLM),_=await this.actionsManager.buildStepDataWithCode(f,{loadingFromFile:!0});return c.status(200).send(_)})),r.post("/verify-save-location",kv(async(o,c)=>{try{let f=this.storageService.doesFolderExistInSaveDir(o.body.location);c.send({exists:f})}catch(f){c.status(400).send({error:f})}})),r.post("/backup",kv(async(o,c)=>{let{backupFolderName:f}=o.body;if(!YHn(f))throw uf.error("Invalid folder name",{backupFolderName:f}),new xGe("Invalid folder name");let _=await this.storageService.localBackup(f);c.send(_)})),r.post("/extended-json-backup",kv(async(o,c)=>{let f=this.storageService.extendedJSONBackup();c.send(f)})),a.post("/upload-files",kv(async(o,c)=>{let f=await this.actionsService.uploadFiles(o.body.files);return c.status(200).json(f)}))}};e(rXr,"VtgStorageController");var BHt=rXr;var nXr=class nXr extends p5{constructor(r){super();this.aiTestGenerationService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/ai");r.post("/init",kv(async(a,o)=>{await this.aiTestGenerationService.init(),o.send("success")})),r.post("/iterate",kv(async(a,o)=>{let c=await this.aiTestGenerationService.iterate(a.body);return c?o.status(200).json(c):o.status(400).send("no action generated")})),r.post("/stop",kv(async(a,o)=>{this.aiTestGenerationService.stop(),o.send("success")}))}};e(nXr,"VtgAITestGenerationController");var RHt=nXr;var iXr=class iXr extends p5{constructor(r){super();this.thoughtsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/thoughts");r.post("/actions/generate",kv(async(a,o)=>{let c=a.body,{processId:f,action:{id:_}}=c;try{this.startAsyncProcess(()=>this.thoughtsService.generateActionThoughts(c),f,_,"action thoughts generation");let v={processId:f,stepId:_,success:!0};o.status(200).send(v)}catch(v){return o.status(400).send({processId:f,error:v.message})}})),r.post("/assertions/generate",kv(async(a,o)=>{let c=a.body,{processId:f,assertion:{id:_}}=c;try{this.startAsyncProcess(()=>this.thoughtsService.generateAssertionThought(c),f,_,"assertion thoughts generation");let v={processId:f,stepId:_,success:!0};o.status(200).send(v)}catch(v){return o.status(400).send({processId:f,error:v.message})}})),r.post("/stop-generate",kv(async(a,o)=>{let c=a.body;this.thoughtsService.stopGeneratingThought(c.stepId);let f={stepId:c.stepId};return o.status(200).send(f)}))}};e(iXr,"VtgThoughtsController");var LHt=iXr;var aXr=class aXr extends p5{constructor(r,a){super();this.assertionsService=r;this.aiAssertionsService=a;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/assertions"),a=this.createPrefixedRouter("/assertion");r.post("/generate",kv(async(o,c)=>{let f=o.body,{processId:_,id:v}=f;try{this.startAsyncProcess(()=>this.aiAssertionsService.generateAiAssertions(f),_,v,"AI assertion generation");let w={processId:_,stepId:v,success:!0};return c.status(200).json(w)}catch(w){return c.status(500).send({processId:_,error:w.message})}})),r.post("/stop-generate",kv(async(o,c)=>{let{id:f}=o.body,_={stepId:f};return this.aiAssertionsService.stopGenerateAiAssertions(f),c.status(200).send(_)})),a.post("/verify/time-machine",kv(async(o,c)=>{let f=await this.assertionsService.verifyOnTimeMachine(o.body);return c.status(200).send(f)})),a.post("/verify/live",kv(async(o,c)=>{let f=o.body;try{let _=await this.assertionsService.verifyOnLive(f),v=_.success?200:404;return c.status(v).send(_)}catch(_){return c.status(404).send({success:!1,message:String(_)})}})),a.post("/save",kv(async(o,c)=>{let f=await this.assertionsService.updateAssertion(o.body);c.status(200).json(f)}))}};e(aXr,"VtgAssertionsController");var MHt=aXr;var sXr=class sXr extends p5{constructor(r){super();this.settingsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/settings");r.get("/",kv(async(a,o)=>{let c=this.settingsService.getSettings();return o.status(200).send(c)})),r.post("/",kv(async(a,o)=>(this.settingsService.updateSettings(a.body),o.status(200).send({message:"Success!"}))))}};e(sXr,"VtgSettingsController");var jHt=sXr;MC();var Zui=hf(IHt());var oXr=class oXr extends p5{constructor(r){super();this.evaluatorService=r;this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/evaluator").post("/execute",kv(async(a,o)=>{try{let c=await this.evaluatorService.execute(a.body.code);return o.status(200).json(c)}catch(c){return o.status(500).send({message:"Error during code evaluation",error:c.message})}}))}};e(oXr,"VtgEvaluatorController");var UHt=oXr;N8();MC();var uXr=class uXr{constructor(){this.reqIndex=0;this.reqInProcess={};this.routesLogRules={};this.intervalTimer=null}setRoutesLogRules(t){this.routesLogRules=t}cleanup(){this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null)}startListening(t,r,a){Pm.vtg.logAPIServer.interval&&this.handleIntervalLog(t,r,a),!(Pm.vtg.logAPIServer.httpTransactions&&this.handleTransactionLog(t,r,a))&&a()}logInterval(){Pm.vtg.logAPIServer.interval&&!this.intervalTimer&&(this.intervalTimer=setInterval(()=>{let t=Object.values(this.reqInProcess);t.length&&(uf.info("HTTP REQUESTS IN PROCESS"),uf.info(t.map(r=>JSON.stringify(r,null,2)).join(`
1931
- `)))},5e3))}handleIntervalLog(t,r,a){let o=this.reqIndex++;this.reqInProcess[o]=this.buildLogInfo(t,r,0,"","INTERVAL"),r.on("finish",()=>{let c=Date.now()-this.reqInProcess[o].start;delete this.reqInProcess[o]})}handleTransactionLog(t,r,a){if(this.getRouteRules(t.originalUrl).skip)return a(),!0;let c=Date.now(),f=this.buildLogInfo(t,r,0,"","REQUEST"),_="";uf.info("REQUEST INFO",JSON.stringify(f,null,2));let v=r.write,w=r.end;return r.write=function(C,...T){return C&&(_+=C.toString()),v.call(this,C,...T)},r.end=function(C,...T){return C&&(_+=C.toString()),w.call(this,C,...T)},r.on("finish",()=>{if(Pm.vtg.logAPIServer.httpTransactions){let C=Date.now()-c,T=this.buildLogInfo(t,r,C,_,"RESPONSE");uf.info("RESPONSE INFO",JSON.stringify(T,null,2))}}),!1}buildLogInfo(t,r,a,o,c="RESPONSE"){let f=this.getRouteRules(t.originalUrl),_={method:t.method,url:t.originalUrl,start:Date.now()};return c==="INTERVAL"||(c==="REQUEST"&&!f.skipRequestData&&t.body&&(_.data=t.body),c==="RESPONSE"&&(a&&(_.duration=`${a}ms`),_.statusCode=r.statusCode,_.size=r.getHeader("content-length")||"unknown",!f.skipResponseData&&o&&(_.data=o))),_}getRouteRules(t){if(this.routesLogRules[t])return this.routesLogRules[t];for(let[r,a]of Object.entries(this.routesLogRules))if(t.includes(r))return a||{};return{}}};e(uXr,"VTGExpressServerRoutesLoggerMiddleware");var qHt=uXr;var cXr=class cXr{constructor(t,r,a,o,c,f,_,v,w,C,T,k){this.actionsService=t;this.assertionsService=r;this.locatorsService=a;this.aiTestGenerationService=o;this.aiAssertionsService=c;this.aiThoughtsService=f;this.actionsManager=_;this.storageService=v;this.settingsService=w;this.monacoService=C;this.evaluatorService=T;this.aiChatService=k;this.errorHandler=e((t,r,a,o)=>{uf.error("Error catch in middleware:",t),a.status(500).send({error:t.message})},"errorHandler");this.routesLoggerMiddleware=new qHt}async getPort(){return this.acquirePortNumber()}async start(){return this.app=(0,QHt.default)(),this.app.use((0,Yui.default)()),this.app.use(Kui.default.json({limit:"50mb"})),this.app.use(QHt.default.raw({type:"multipart/form-data",limit:"50mb"})),this.app.use(QHt.default.static(Xui.default.join(Pm.runtimeRoot,"vtg-build"))),this.app.use(this.routesLoggerMiddleware.startListening.bind(this.routesLoggerMiddleware)),this.routesLoggerMiddleware.logInterval(),await this.acquirePortNumber(),this.app.use(this.initializeControllers()),this.app.use(this.errorHandler),new Promise(t=>{this.app.listen(this.port,()=>{uf.info(`Express server running on port ${this.port}`),t()}).on("close",()=>{this.shutdown()})})}shutdown(){this.routesLoggerMiddleware.cleanup(),uf.info("Express server shutdown complete")}async acquirePortNumber(){return this.port||(this.port=await new Promise((t,r)=>{let a=Gui.default.createServer();a.unref(),a.on("error",r),a.listen(0,()=>{let o=a.address().port;a.close(()=>{t(o)})})})),this.port}async evaluateServerPort(t){if(!t)throw new Error("Page not initialized");await t.evaluate(r=>{window.vtg.setServerPort(r)},this.port)}initializeControllers(){let t=new PHt(this.assertionsService,this.actionsManager,this.actionsService,this.aiTestGenerationService),r=new BHt(this.storageService,this.actionsManager,this.actionsService),a=new RHt(this.aiTestGenerationService),o=new LHt(this.aiThoughtsService),c=new MHt(this.assertionsService,this.aiAssertionsService),f=new jHt(this.settingsService),_=new FHt(this.locatorsService),v=new NHt(this.monacoService),w=new OHt(this.aiChatService),C=new UHt(this.evaluatorService),T=[t,r,a,o,c,f,_,v,C,w],k=(0,Zui.Router)(),R={};return T.forEach(B=>{k.use(B.getRouter()),R={...R,...B.getRoutesLogRules()}}),this.routesLoggerMiddleware.setRoutesLogRules(R),k}};e(cXr,"VtgExpressServer");var $Ht=cXr;var VHt=require("fs");var z1t=class z1t{constructor(t,r,a,o){this.projectRootDirectory=t;this.checksumRoot=r;this.internalFilesDir=a;this.vtgTestFileRunConfig=o;this.localSaveFolderPath=process.env.CHECKSUM_DRAFT_FOLDER_PATH??`${this.internalFilesDir}/drafts`}createTestAssetsFolders(){this.assetsFolderPath=`${this.internalFilesDir}/assets/${Date.now()}`,(0,VHt.mkdirSync)(this.assetsFolderPath,{recursive:!0}),(0,VHt.mkdirSync)(this.getHarFolderPath(),{recursive:!0})}createTestGenerationLocalAutoSaveFolder(){(0,VHt.mkdirSync)(this.getLocalAutoSavePath(),{recursive:!0})}getAssetsFolderPath(){return this.assetsFolderPath}getLocalAutoSavePath(){return`${this.localSaveFolderPath}/${z1t.AUTO_SAVE_FOLDER_NAME}`}getLocalAutoSaveFileName(t){var r;return((r=this.vtgTestFileRunConfig)==null?void 0:r.mode)==="edit"?this.vtgTestFileRunConfig.sourceFilePath.split("/").pop().replace(".spec.ts",".json"):`${t}.json`}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 t=this.vtgTestFileRunConfig.sourceFilePath.split("/").pop();return`${this.localSaveFolderPath}/${this.currentSaveAsLocation}/${t}`}else return this.vtgTestFileRunConfig.sourceFilePath}getLocalSavePath(){return this.localSaveFolderPath}getHarFolderPath(){return this.assetsFolderPath+"/har"}getHarFilePath(){return`${this.getHarFolderPath()}/har.har`}getTraceFilePath(){return`${this.assetsFolderPath}/trace.zip`}setCurrentSaveAsLocation(t){t&&!(t!=null&&t.startsWith("auto-save"))&&(this.currentSaveAsLocation=t)}};e(z1t,"VtgTestAssetsManager"),z1t.AUTO_SAVE_FOLDER_NAME="auto-save";var zHt=z1t;var Dqa={useCDPSession:!0,trackLoadedResources:!0},lXr=class lXr extends eJt{constructor(r={},a={devtools:!1},o={},c,f){super({...Dqa,...r},a,c,f);this.settings={frontendAppSpecificRules:void 0,initTestGenerator:!0,frontendTestGenerationConfig:void 0};this.isScriptLoaded=e(async(r,a=1e3)=>{try{return await r.waitForFunction(()=>!!window.checksum,void 0,{timeout:a}),!0}catch{return!1}},"isScriptLoaded");this.initInjectedScript=e(async r=>{try{return await r.waitForFunction(()=>{var a;return!!((a=window.checksum)!=null&&a.testGenerator)}),r.evaluate(async({appSpecificRules:a,config:o,initModules:c})=>{window.checksum.testGenerator.init(a,o,c)},{appSpecificRules:this.settings.frontendAppSpecificRules,config:this.getFrontendTestGenerationConfig(),initModules:this.getInjectedScriptInitModules(r)})}catch(a){console.log("initInjectedScript exception",a)}},"initInjectedScript");this.settings={...this.settings,...o},this.injectedScriptManager.setScriptLoadCheck(this.isScriptLoaded),this.settings.initTestGenerator&&this.injectedScriptManager.setScriptLoadCallback(this.initInjectedScript)}async prepare(r={}){let a=await super.prepare(r);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")}),a}setEvaluateWithChecksumTargetFrame(r){this.evaluateWithChecksumTargetFrame=r}getInjectedScriptInitModules(r){return{assertionGenerator:!0,sessionRecorder:!0,filesObserver:!1,assertionsObserver:!1,actionsObserver:!1,nativeDialogObserver:!1}}getFrontendTestGenerationConfig(){return this.settings.frontendTestGenerationConfig}async evaluateWithChecksum(r,a,o=this.evaluateWithChecksumTargetFrame){let c=this.injectedScriptManager.getNavigationPromise(o);c&&await c;try{return o.evaluate(r,a)}catch(f){throw console.error("evaluateWithChecksum error",f,r.toString()),f}}async getBestMatchingElementSimilarityScore(r){return this.evaluateWithChecksum(async a=>await window.checksum.testGenerator.getBestMatchingElementSimilarityScore(a),r)}async getInteractableElements(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getInteractableElements())}async getAllInteractableElementsForLastSelectQuery(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getAllInteractableElementsForLastSelectQuery())}async overlayInteractableElementsWithChecksumId(r){return this.evaluateWithChecksum(a=>window.checksum.testGenerator.overlayInteractableElementsWithChecksumId(a),r)}async takeElementSnapshot(r,a,o={},c={}){try{let{snapshot:f,elementLocator:_}=await super.takeElementSnapshot(r,a,o);if(!f||!o.takeBodyScreenshot)return f?{snapshot:f}:{};await this.highlightElementByLocator(_,o.mousePosition);let v=await this.takePageSnapshot(c);return await this.clearHighlights(),{snapshot:f,bodySnapshot:v}}catch(f){return console.error("[ChecksumWebDriver] takeElementSnapshot error",f),{}}}async highlightElementByLocator(r,a,o="20px solid rgba(255,0,0,1)",c=!1){return this.evaluateWithChecksum(async([f,_,v,w])=>{window.checksum.testGenerator.highlightElement(f,{highlightStyle:{outline:_},mousePosition:v,scroll:w})},[await r.elementHandle(),o,a,c])}async clearHighlights(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.clearHighlights())}};e(lXr,"ChecksumWebDriver");var JHt=lXr;var eci=require("fs"),tci=hf(require("path"));var pXr=require("fs");N8();MC();var fXr=class fXr{constructor(t,r,a=Pm.vtg.localBuildPath){this.page=t;this.serverPort=r;this.filePath=a;this.filePath=a,uf.info("[VTG] FrontendLauncher initialized with:",{serverPort:r,filePath:a,appSource:Pm.vtg.appSource,cwd:process.cwd()})}async start(){try{await this.modifyVTGBuildHtmlFile(),await this.startReactApp()}catch(t){throw uf.error("An error occurred:",t),t}}async startReactApp(){if(!this.page)throw new Error("Page not initialized");let t;switch(Pm.vtg.appSource){case"served-app":t=Pm.vtg.appURL;break;case"served-build-file":t=`http://localhost:${this.serverPort}/index.html`;break;case"build-file":t=Pm.vtg.localUrl;break;default:throw new Error(`Invalid app source: ${Pm.vtg.appSource}`)}await this.page.goto(t,{waitUntil:"networkidle",timeout:6e4})}async modifyVTGBuildHtmlFile(){if(Pm.vtg.appSource==="build-file")try{let t=await pXr.promises.readFile(this.filePath,"utf8"),r=/(src|href)=(["'])(\/)static/g,a=t.replace(r,"$1=$2.$3static");await pXr.promises.writeFile(this.filePath,a,"utf8"),uf(`Successfully modified ${this.filePath}`)}catch(t){uf.error(`Error processing file ${this.filePath}:`,t)}}};e(fXr,"VtgFrontendLauncher");var WHt=fXr;cMt();N8();$zr();MC();djr();mMt();fD();var Tqa=1e3,GHt=class GHt extends JHt{constructor(r={},a={devtools:!1},o={},c){var f;super(r,a,GHt.makeSettings(o),(f=c==null?void 0:c.getFramesMessageBroker)==null?void 0:f.call(c),Pm.vtg.isSeparateProcess||c==null?void 0:c.context());this.liveAppPage=c;this.registeredTimeMachineFrames=[];this.onAppFrameCreated=e(async r=>{this.appFrame=r,await this.frameMsgBroker.register("live",this.appFrame,Pm.vtg.writeRrwebEventsToFile),this.setEvaluateWithChecksumTargetFrame(this.appFrame)},"onAppFrameCreated");this.timeMachine=new jve(this.frameMsgBroker,this.injectedScriptManager,{webProxy:r.webProxy}),this.liveTimeMachine=new jve(this.frameMsgBroker,this.injectedScriptManager,{webProxy:r.webProxy}),this.appViewport=o.viewport,this.completeOriginHeaderOnLivePage=o.completeOriginHeaderOnLivePage}static makeSettings(r={}){return Qzt({frontendTestGenerationConfig:{showFrontendLogs:Pm.isDevMode}},r)}get appMainFrame(){return this.appFrame}get tmFrame(){return this.timeMachineFrame}getApplicationViewport(){return this.appViewport}getTimeMachine(){return this.timeMachine}registerTimeMachineFrame(r){this.registeredTimeMachineFrames.push(r)}async prepare(r={},a={}){let o=await super.prepare(r);await this.frameMsgBroker.register("vtg",this.page.mainFrame()),this.page.on("dialog",()=>{}),this.page.on("close",()=>{uf.error("Page closed")}),this.liveAppPage&&!Pm.vtg.isSeparateProcess&&await(await this.page.context().newCDPSession(this.originalPage)).send("Emulation.setDeviceMetricsOverride",{width:0,height:0,deviceScaleFactor:0,mobile:!1}),await new WHt(this.page,a.serverPort).start();let c=e(async(_=2)=>{if(this.timeMachineFrame=this.page.frames().find(v=>v.name()==="time-machine-iframe"),this.liveFrame=this.page.frames().find(v=>v.name()==="live-iframe"),!this.timeMachineFrame||!this.liveFrame){if(_>0)return uf.info("Waiting for frames to be available"),await tE(Tqa),c(_-1);{let v="Could not connect to VTG frontend, check that the app is available";throw uf.error(v),new Error(v)}}},"getFrames");await c();let f;return this.liveAppPage?(f=this.liveAppPage,this.completeOriginHeaderOnLivePage&&await this.applyRouteInterceptors(f,{completeOriginHeader:!0})):(f=await this.context.newPage(),await f.setViewportSize(this.appViewport)),await this.onAppFrameCreated(f.mainFrame()),await this.timeMachine.prepare(this.appFrame,this.timeMachineFrame),await this.liveTimeMachine.prepare(this.appFrame,this.liveFrame),await this.exposeFunctionsForVTG(),o}async exposeFunctionsForVTG(){try{if(await this.page.evaluate(()=>typeof window.checksumGetFilesFromLive=="function").catch(()=>!1)){uf.info("checksumGetFilesFromLive already exposed, skipping");return}await this.page.exposeFunction("checksumGetFilesFromLive",async a=>{let o=this.appFrame;if(!o){uf.info("no live frame detected");return}try{return o.evaluate(c=>window.checksum.testGenerator.filesObserver.getFilesByRrwebId(c),a)}catch(c){uf.error("Error getting frame window",c)}})}catch(r){uf.warning(`Failed to expose checksumGetFilesFromLive: ${r.message}`)}}async navigate(r){return this.appFrame.goto(r)}async getCurrentURL(){return this.appFrame.url()}async createPage(){let r=new qve(this.evaluateWithChecksum.bind(this),()=>this.appFrame,()=>this.timeMachine,{log:uf.info,logError:uf.error},{navigationTimeout:3e4,actionTimeout:5e3,waitActionDelay:1e3,testAssetsDir:__dirname}),a=await super.createPage();return vJe.makePage(a,r,this.injectedScriptManager,this.context)}getInjectedScriptInitModules(r){return this.registeredTimeMachineFrames.concat([this.timeMachineFrame,this.liveFrame]).includes(r)?{assertionGenerator:!1,sessionRecorder:!1,filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1,actionsObserver:!1}:r===this.appFrame?{...super.getInjectedScriptInitModules(r),filesObserver:!0,nativeDialogObserver:!0,assertionsObserver:!0,actionsObserver:!0}:super.getInjectedScriptInitModules(r)}async interceptPageRequests(){async function r(o){try{return await eci.promises.readFile(o,"utf8")}catch(c){return uf.error(`Error reading file ${o}:`,c),null}}e(r,"readLocalFile");function a(o){switch(tci.extname(o).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(a,"getContentType"),await this.page.route("**/*",async o=>{try{let c=o.request().url();if(console.log("intercepted!",c),c.startsWith("file://")){let f=c.replace("file://",""),_=await r(f);_!==null?await o.fulfill({status:200,contentType:a(f),body:_}):await o.abort()}else{let f=0,_=5;for(;f<_;){let v=await o.fetch(),w=v.status();if(w>299&&w<400){f++;let C=v.headers().location;if(!C){uf.warning("Redirect without Location header",{url:c}),await o.abort();return}console.log(`Redirect ${f} to: ${C}`),o.request().url=()=>new URL(C,c).toString()}else{let C={};C["Access-Control-Allow-Origin"]="*",C["Access-Control-Allow-Methods"]="GET, POST, PUT, DELETE, OPTIONS",C["Access-Control-Allow-Headers"]="Content-Type, Authorization",await o.fulfill({response:v,headers:{...v.headers(),...C,"content-security-policy":"","X-Frame-Options":"","x-frame-options":""}});return}}uf.warning(`Max redirects (${_}) exceeded`),await o.abort()}}catch(c){uf.warning("intercept error",c)}})}};e(GHt,"ChecksumVTGWebDriver");var HHt=GHt;var wGe=require("fs");N8();var rci=".settings.json",dXr=class dXr{constructor(t,r,a){this.checksumRoot=t;this.apiService=r;this.internalFilesDir=a;this.settings={autoLogin:!0,autoRunSteps:!0,autoGenerateThoughts:!0,disableGenerateThoughts:!1,autoGenerateAssertions:!0,disableAutoGenerateAssertions:!1,disableAILocators:!1,optimizeLocators:!0,useOptimizedLocatorDefault:!0,useCodeBasedSteps:!0,displayUIInspector:!1,mergeCustomCodeSteps:!1,useVariableTransformation:!0};this.settingsFilePath=a?`${this.internalFilesDir}/${rci}`:`${this.checksumRoot}/${rci}`,this.readSettings()}getSettings(){return{...this.settings,autoGenerateAssertions:Pm.vtg.aiAssertions.disabled?!1:this.settings.autoGenerateAssertions,disableAutoGenerateAssertions:Pm.vtg.aiAssertions.disabled,disableAILocators:Pm.vtg.aiLocators.disabled}}updateSettings(t){this.settings=Object.assign(this.settings,t),this.writeSettingsData()}readSettings(){if(!(0,wGe.existsSync)(this.settingsFilePath)){this.writeSettingsData();return}let t=(0,wGe.readFileSync)(this.settingsFilePath,"utf-8");this.settings=JSON.parse(t),this.settings.useCodeBasedSteps===void 0&&(this.settings.useCodeBasedSteps=!0)}writeSettingsData(){(0,wGe.writeFileSync)(this.settingsFilePath,JSON.stringify(this.settings,null,2))}async getIsGitReflectionEnabled(){return(await(await this.apiService.get("/git-integration/is-git-reflection-enabled")).json()).enabled??!1}};e(dXr,"VtgSettingsService");var J1t=dXr;yMr();var E3e=require("fs");MC();var mXr=class mXr{constructor(t,r,a){this.timeMachine=t;this.actionsManager=r;this.userStoryService=a}async generatePromptData(t,r){let a=e(()=>{let{timestamps:w,...C}=this.cachedPromptData;return{...C,action:t}},"returnPromptDataFromCache"),o=t.id;if(this.canUseCachedPromptData(t))return a();let c=this.getActionTimestamps(o,r);if(!c)return;let f=await this.timeMachine.executeReducedHTMLTask(c.before),_=await this.timeMachine.executeReducedHTMLTask(c.after),v=this.userStoryService.getStory();return this.cachedPromptData={reducedHTML:_,previousReducedHTML:f,actionId:o,previousActions:this.getPreviousActions(o),action:t,title:v.goal,steps:v.instructions,timestamps:c},a()}canUseCachedPromptData(t){var r,a;return this.cachedPromptData&&this.cachedPromptData.actionId===t.id&&this.cachedPromptData.action.timestamp===t.timestamp&&((r=this.cachedPromptData.timestamps)==null?void 0:r.before)===t.timestamp&&((a=this.cachedPromptData.timestamps)==null?void 0:a.after)===t.timestamp}getPreviousActions(t){let r=this.actionsManager.actions,a=r.findIndex(o=>Number(o.id)===Number(t));return r.slice(0,a)}async generatePromptDataForThought(t,r){return this.generatePromptData(t,r)}getActionTimestamps(t,r){let a=this.actionsManager.actions,o=a.findIndex(_=>_.id===t);if(o===-1){uf.error(`[init] No action with id ${t} was found in executed actions`);return}let c=a[o],f=a[o+1];return{before:c.timestamp,after:(f==null?void 0:f.timestamp)??r}}};e(mXr,"ActionsAgent");var KHt=mXr;MC();N8();var _Xr=class _Xr extends I7e{constructor(r,a,o,c,f){super(r,a,o);this.actionsManager=r;this.apiService=a;this.userStoryService=o;this.webDriver=f;this.activeRemoteSessionIdByStepId=new Map;this.assertionsAgent=new IWe(c,r,a,this.remoteSessionId,{logPerformance:Pm.vtg.aiAssertions.logPerformance}),this.actionsAgent=new KHt(c,r,this.userStoryService)}async init({retriesLeft:r=3,keepActionsWithoutDescription:a=!1,lastActionId:o=void 0}={}){await super.init({retriesLeft:r,keepActionsWithoutDescription:a,lastActionId:o}),this.activeRemoteSessionIdByStepId.set(o,this.remoteSessionId)}async generateActionThoughts({action:r,processId:a}){try{if(this.isRunning(r.id))throw uf.warning("Already generating a thought for this action"),new Error("Already generating a thought for this action");let o=await this.actionsAgent.generatePromptDataForThought(r),c=await this.callThoughtApi("actions",o,a);return this.evaluateThoughtResponse({processId:a,id:r.id,thought:c.thought})}catch(o){return uf.error("Error in AI thought generation",o),this.evaluateThoughtResponse({processId:a,id:r.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(r.id)}}async generateAssertionThought({assertion:r,parentActionId:a,processId:o}){let c=a||r.actionId;try{if(this.isRunning(r.id))throw uf.warning("Already generating a thought for this assertion"),new Error("Already generating a thought for this assertion");let f=await this.assertionsAgent.generateThoughtPromptData(c,r),_=await this.callThoughtApi("assertions",f,o);return this.evaluateThoughtResponse({processId:o,id:r.id,thought:_.thought})}catch(f){return uf.error("Error in AI thought generation",f),this.evaluateThoughtResponse({processId:o,id:r.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(r.id)}}stopGeneratingThought(r){this.activeRemoteSessionIdByStepId.delete(r)}async callThoughtApi(r,a,o){let c=Date.now();if(a)try{c=Date.now();let f=await this.apiService.post(`${r}/thoughts/generate`,{sessionId:this.remoteSessionId,data:a});if(!f.ok){uf.error(`Request for ${r} thought generation failed with status ${f.status}`);return}let _=await f.json();if(!(_!=null&&_.thought))throw uf("No thought generated for action, got response",f),new Error("No thought generated");let v=r==="actions"?a.action:a.assertion;return uf(`Thought generated (${o})`,{type:r,stepId:v.id,locator:v.locator,thought:_.thought}),_}catch(f){throw uf.error(`Error in AI thought generation (${o})`,f),f}}isRunning(r){return this.activeRemoteSessionIdByStepId.has(r)}async evaluateThoughtResponse({id:r,processId:a,thought:o,error:c=!1}){try{await this.webDriver.page.evaluate(({id:f,thought:_,error:v,processId:w})=>{window.vtg.onAsyncProcessResponse({id:f,processId:w,thought:_,error:v})},{id:r,thought:o,error:c,processId:a})}catch(f){uf.error("Error in AI thought generation",f)}}};e(_Xr,"VTGThoughtsService");var YHt=_Xr;var kqa=e(()=>{let t=new Error().stack.split(`
1930
+ ${Uht}`,generateAssertionsCode:!1}),R=_?await this.takeElementSnapshot(o.locator,c):void 0;return{code:k,fullHTML:v,outerHTML:w,parentHTML:C,timestamp:c,image:R,rrwebSnapshot:T}},"extractDataForStep");for(let o=0;o<t.length;o++){uf.info(`processing action ${o} of ${t.length}`);let c=t[o],f=await a(c);r.push(f);for(let _ of c.assertions||[]){uf.info(`processing assertion of ${c.assertions.length} assertions`);try{let v=await a(_);r.push(v)}catch(v){uf.error("Failed to extract data for assertion",v)}}}return r}async takeElementSnapshot(t,r){try{return`data:image/jpeg;base64,${(await this.taskTimeMachine.executeTask(async o=>(await this.evaluationService.getLocator(`return ${lj(t)}`,o.frameLocator("iframe"))).screenshot({omitBackground:!0,type:"jpeg"}),r)).toString("base64")}`}catch(a){uf.error("Failed to take element snapshot",a);return}}async getHTMLsForTimestamp(t,r){try{return r?await this.taskTimeMachine.executeTask(async o=>{let c=await this.evaluationService.getLocator(`return ${lj(r)}`,o.frameLocator("iframe")),f=await c.elementHandle(),{fullHTML:_,outerHTML:v,rrwebSnapshot:w}=await o.page().evaluate(({element:T})=>{let k="",R="",B="",U=document.querySelector(".replayer-wrapper iframe").contentDocument;try{R=U.querySelector("html").outerHTML}catch{R=""}try{B=T.outerHTML}catch{B=""}try{k=JSON.stringify(window.checksum.timeMachine.rrwebSnapshot(U))}catch{k=""}return{fullHTML:R,outerHTML:B,rrwebSnapshot:k}},{element:f}),C=await Lti(c);return{fullHTML:_,outerHTML:v,parentHTML:C,rrwebSnapshot:w}},t):{fullHTML:"",outerHTML:""}}catch(a){return uf.error("Failed to get HTML data for extended JSON backup",a),{}}}doesFolderExistInSaveDir(t){try{let r=`${this.testAssetsManager.getLocalSavePath()}/${t}`;return(0,$7e.statSync)(r).isDirectory()}catch(r){if(r.code==="ENOENT")return!1;throw r}}async saveToCloud(){try{let{testGenerationId:t}=await this.userStoryService.createTestGeneration();await this.saveTestFile();let r=await this.settingsService.getIsGitReflectionEnabled();if(!r){let c=new jJt(this.apiService.getBaseURL(),this.config.apiKey,null,()=>`test-generation/${t}/get-upload-url`),f=e(k=>({complete:!1,error:!1,response:void 0,info:k}),"buildUploadAsset"),_=[],v=this.userStoryService.getStory(),w=v==null?void 0:v.internalTestId,C=v==null?void 0:v.collectionName,T=`test-${w}.fix.checksum.spec.ts`;await c.uploadAsset(f({type:"test-fix-files",path:this.testAssetsManager.getSavedTestFilePath(),fileName:T,relativePath:C?`tests/${C}/${T}`:`tests/${T}`})),_.push(f({type:"trace",path:this.testAssetsManager.getTraceFilePath()})),_.push(f({type:"har",path:await Uti(this.testAssetsManager.getHarFolderPath())})),this.actionsManager.actions.filter(k=>k.eventCode==="upload_files").forEach(k=>{var R;(R=k.files)==null||R.forEach(B=>{_.push(f({type:"test-files",path:B}))})}),await Promise.all(_)}let a=this.actionsManager.actions.map(c=>({...c,parentFramesSelectors:c.parentFramesSelectors?c.parentFramesSelectors.filter(f=>f!=="iframe"):void 0})),o={};if(r){let c=this.userStoryService.getStory();c!=null&&c.version&&(o.version=c.version)}await this.apiService.post(`test-generation/${t}/completed`,{actions:a,metadata:Object.keys(o).length>0?o:void 0})}catch(t){uf.error("Failed to upload test",t)}}};e(fGr,"VtgStorageService");var hWt=fGr;Rzr();Bne();var dGr=class dGr{constructor(){this._executedActions=[];this.onActionExecuted=this.pushExecutedActionOrAddAfterParent.bind(this)}get actions(){return this._executedActions}set executedActions(t){var r;this._executedActions=t,(r=this.storageService)==null||r.localSave()}addAction(t){var r;this._executedActions.push(t),(r=this.storageService)==null||r.localSave()}setActions(t){this._executedActions=t}updateAssertionById(t,r){let a=r;return this.executedActions=this._executedActions.map(o=>{var c;if(o.id===t){let f=!!((c=o.assertions)!=null&&c.find(({id:v})=>v===r.id)),_={...o};return f?_.assertions=o.assertions.map(v=>{if(v.id===r.id){let w={...v,...r};return a=w,w}return v}):_.assertions=[...o.assertions??[],r],{..._,assertions:_.assertions.sort((v,w)=>v.timestamp!==w.timestamp?v.timestamp-w.timestamp:v.createdAt-w.createdAt)}}return o}),a}setStorageService(t){this.storageService=t}createAction(t){var v,w,C;let{id:r,data:a,options:o,type:c}=t,f={id:r,...a},_=[...this._executedActions];switch(o==null?void 0:o.type){case"insertAfter":{let T=this.findActionOrAssertionById(o.afterStepId),k=_.findIndex(R=>R.id===T.action.id);if(T.assertion||(w=(v=T.action)==null?void 0:v.assertions)!=null&&w.length){let R=T.assertion??T.action.assertions[0],{before:B,after:U}=P9a(((C=_[k])==null?void 0:C.assertions)??[],R.id,!!T.assertion);_[k].assertions=B,f.assertions=U.map(W=>({...W,actionId:f.id}))}k!==-1?_.splice(k+1,0,f):_.push(f);break}case"insertLast":_.push(f);break;case"replace":{let T=_.findIndex(k=>k.id===o.stepId);T!==-1&&_.splice(T,1,f);break}case"replaceLast":_.length>0&&(_[_.length-1]=f);break}return this.executedActions=_,f}pushExecutedActionOrAddAfterParent(t,r={}){if(r.previousActionId){let a=this._executedActions.findIndex(({id:o})=>o===r.previousActionId);if(a!==-1){let o={...t,timestamp:this._executedActions[a].timestamp+1};this._executedActions=[...this._executedActions.slice(0,a+1),o,...this._executedActions.slice(a+1)]}}else this.executedActions=Array.isArray(t)?[...this._executedActions,...t]:[...this._executedActions,t]}addManualActionsToExecuted(t){this.executedActions=[...this._executedActions,t]}updateExecutedAction(t){let r=this._executedActions.findIndex(({id:a})=>a===t.id);if(r!==-1){let a={...this._executedActions[r],...t};return this.executedActions=[...this._executedActions.slice(0,r),a,...this._executedActions.slice(r+1)],a}throw new Error("Action was not found")}deleteStep(t,r,a={assertionsOnly:!1,withAssertions:!0}){r==="Action"?this.deleteAction(t,a):r==="Assertion"&&(this.executedActions=this._executedActions.map(o=>(o.assertions=(o.assertions??[]).filter(c=>c.id!==t),o)))}deleteAction(t,r={assertionsOnly:!1,withAssertions:!0}){var o;let a=this._executedActions.find(c=>c.id===t);if(!a)throw new Error(`Action with id "${t}" not found`);r.assertionsOnly?this.executedActions=this._executedActions.map(c=>c.id===t?{...c,assertions:[]}:c):!r.withAssertions&&((o=a==null?void 0:a.assertions)!=null&&o.length)?this.deleteActionAndMergeAssertions(t):this.executedActions=this._executedActions.filter(c=>c.id!==t)}deleteActionAndMergeAssertions(t){let r=this._executedActions.findIndex(_=>_.id===t);if(r===-1)throw new Error(`Action with id "${t}" not found`);if(r===0)throw new Error("Cannot remove the first action; no previous action to merge assertions into");let a=this._executedActions[r-1],o=this._executedActions[r];o.assertions||(o.assertions=[]);let c=o.assertions.map(_=>({..._,actionId:a.id})),f={...a,assertions:[...a.assertions??[],...c]};this.executedActions=[...this._executedActions.slice(0,r-1),f,...this._executedActions.slice(r+1)]}clearTestSteps(t=!0){if(t){let{navigation:r,login:a}=this.findLoginAndNavigationActions();this.executedActions=this._executedActions.reduce((o,c)=>([r==null?void 0:r.id,a==null?void 0:a.id].includes(c.id)&&o.push({...c,assertions:[]}),o),[])}else this.executedActions=[];return this._executedActions}reloadTestSteps(t){this.clearTestSteps(!1),this.executedActions=t}findLoginAndNavigationActions(){let t=this._executedActions.find(({eventCode:a})=>a==="navigation"),r=this._executedActions.find(({eventCode:a})=>a==="login");return{navigation:t,login:r}}addAssertionToAction(t,r){this.executedActions=this._executedActions.map(a=>{if(a.id!==t.actionId)return a;if(a.assertions||(a.assertions=[]),r){let o=a.assertions.findIndex(({id:c})=>r===c);a.assertions.splice(o+1,0,t)}else a.assertions=[t,...a.assertions??[]];return a})}findActionByAssertionId(t){return this._executedActions.find(({assertions:r=[]})=>r.find(a=>a.id===t))}replaceAssertion(t,r){let a=this.findActionByAssertionId(r);if(!a)throw new Error(`No action found containing assertion with id ${r}`);this.executedActions=this._executedActions.map(o=>o.id===a.id?{...o,assertions:(o.assertions??[]).map(c=>c.id===r?{...t,actionId:a.id}:c)}:o)}findActionOrAssertionById(t){let r={action:null,assertion:null};if(this._executedActions.forEach(a=>{a.id===t&&(r.action=a);let o=(a.assertions??[]).find(c=>c.id===t);o&&(r={action:a,assertion:o})}),!r.action&&!r.assertion)throw new P7e(t);return r}async buildStepDataWithCode(t,{loadingFromFile:r}={loadingFromFile:!1}){let a=F9a(t);return await Promise.all(a.map(async({step:o,type:c})=>{let f=await JFe(zHe([o],void 0,{generateAssertionsCode:!1},(_,v)=>{o=v}));return{type:c,step:{...o,loadedFromFile:r},code:f}}))}};e(dGr,"VtgActionsManager");var gWt=dGr,P9a=e((i,t,r=!0)=>{let a=Number(r),o=i.findIndex(_=>_.id===t);if(o===-1)return{before:i,after:[]};let c=i.slice(0,o+a),f=i.slice(o+a);return{before:c,after:f}},"splitArrayAtId"),F9a=e(i=>i.reduce((t,r)=>{var c;let{assertions:a,...o}=r;if(t.push({step:o,type:"Action"}),(c=r.assertions)!=null&&c.length){let f=r.assertions.map(_=>({type:"Assertion",step:{..._,actionId:r.id}}));t.push(...f)}return t},[]),"transformActionsListToVTGStepsDataList");var QHt=hf(IHt()),Gui=hf(require("net")),Kui=hf(HKr()),Yui=hf(Wui());var GYr=class GYr extends Error{constructor(t){super(t),this.name="ValidationError"}};e(GYr,"ValidationError");var xGe=GYr,KYr=class KYr extends Error{constructor(t){super(t),this.name="NotFoundError"}};e(KYr,"NotFoundError");var AGe=KYr;MC();var kv=e(i=>(t,r,a)=>{Promise.resolve(i(t,r,a)).catch(o=>{if(uf.error(`${t.method} ${t.path} error:`,o),o instanceof P7e)return r.status(200).json({error:o.message});if(o instanceof xGe)return r.status(400).send({error:o.message});if(o instanceof AGe)return r.status(404).send(o.message);a(o)})},"asyncErrorHandler");MC();var YYr=hf(IHt());var EGe=class EGe{constructor(){this.routesLogRules={};this.router=(0,YYr.Router)()}getRoutesLogRules(){return this.routesLogRules}getRouter(){return this.router}createPrefixedRouter(t){let r=(0,YYr.Router)(),a=t.startsWith(EGe.DEFAULT_API_PREFIX)?t:`${EGe.DEFAULT_API_PREFIX}${t.startsWith("/")?t:`/${t}`}`;return this.router.use(a,r),r}startAsyncProcess(t,r,a,o="unknown"){uf.info(`Starting async ${o} process: ${r} for step: ${a}`),t().catch(c=>{uf.error(`Async process ${r} failed:`,c)})}};e(EGe,"VTGController"),EGe.DEFAULT_API_PREFIX="/api";var p5=EGe;var XYr=class XYr extends p5{constructor(r,a,o,c){super();this.assertionsService=r;this.actionsManager=a;this.actionsService=o;this.aiTestGenerationService=c;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter(""),a=this.createPrefixedRouter("/steps");r.post("/createStep",kv(async(o,c)=>{let f=o.body,_;f.type==="Assertion"&&(_=this.assertionsService.createAssertion(f)),f.type==="Action"&&(_=this.actionsManager.createAction(f));let v=await JFe(zHe([_],void 0,{generateAssertionsCode:!1},(w,C)=>{_=C}));return c.status(200).json({step:_,code:v})})),r.patch("/updateStep",kv(async(o,c)=>{let f=o.body,_=f==null?void 0:f.options,v;f.type==="Assertion"&&(v=await this.assertionsService.updateAssertion({id:f.id,data:f.data})),f.type==="Action"&&(v=this.actionsManager.updateExecutedAction({...f.data,id:f.id}));let w;_!=null&&_.forceUpdateTimestamp||(f.data.thought===""&&(v.thought=void 0),w=await JFe(zHe([v],void 0,{generateAssertionsCode:!1},(C,T)=>{v=T}))),c.status(200).json({step:v,code:w})})),r.delete("/deleteStep",kv(async(o,c)=>{let{id:f,options:_,type:v}=o.body;return this.actionsManager.deleteStep(f,v,_),c.status(200).send({message:"Success!"})})),r.post("/clear-test",kv(async(o,c)=>{let f=this.actionsManager.clearTestSteps();return c.status(200).send(f)})),a.post("/execute",kv(async(o,c)=>{let f=o.body;try{let _=null;return wqa(f)?_=await this.aiTestGenerationService.executeAction(f):Cqa(f)&&(_=await this.actionsService.executeAction(f)),c.status(200).json(_)}catch(_){return c.status(400).send({error:_.message})}})),r.put("/steps",kv(async(o,c)=>(this.actionsManager.pushExecutedActionOrAddAfterParent(o.body.action,o.body.options),c.send("success")))),r.post("/code-to-steps",kv(async(o,c)=>{let _=Pti(o.body.code).map(v=>v&&"isChecksumAiWithDirectExpression"in v?{...v,isChecksumAiWithDirectExpression:!1}:v);return c.status(200).send(_)})),r.post("/steps-to-code",kv(async(o,c)=>{let f=zHe(o.body.steps,void 0,{generateAssertionsCode:!1});return c.status(200).send(f)}))}};e(XYr,"VtgStepsController");var PHt=XYr;function wqa(i){var t;return((t=i.options)==null?void 0:t.isAISuggestion)===!0}e(wqa,"isAIExecuteActionArgs");function Cqa(i){var t;return((t=i.options)==null?void 0:t.isAISuggestion)===!1}e(Cqa,"isManualExecuteActionArgs");MC();var ZYr=class ZYr extends p5{constructor(r){super();this.locatorsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/locators"),a=this.createPrefixedRouter("/ai/locators");r.post("/play",kv(async(o,c)=>{let f=o.body;try{let _=await this.locatorsService.verifyLocatorOrSelector(f);return c.status(200).send(_)}catch(_){return c.status(400).send({error:_.message})}})),a.post("/generate",kv(async(o,c)=>{let{step:f,target:_,processId:v}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.generateAILocators(f,_,v),v,_.id,"AI locators generation");let w={processId:v,stepId:_.id,success:!0};return c.status(200).json(w)}catch(w){return uf.error("Error generating AI locators:",w),c.status(500).send({processId:v,error:w.message})}})),a.post("/extract-css",kv(async(o,c)=>{let{step:f,target:_,processId:v,llmLocators:w}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.extractCSS(f,_,v,w),v,_.id,"CSS extraction");let C={processId:v,stepId:_.id,success:!0};return c.status(200).json(C)}catch(C){return uf.error("Error extracting CSS locators:",C),c.status(500).send({processId:v,error:C.message})}})),a.post("/filter",kv(async(o,c)=>{let{step:f,target:_,processId:v,candidates:w}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.filterLocators(f,_,v,w),v,_.id,"locators filtering");let C={processId:v,stepId:_.id,success:!0};return c.status(200).json(C)}catch(C){return uf.error("Error filtering locators:",C),c.status(500).send({processId:v,error:C.message})}})),a.delete("/process/:id",kv(async(o,c)=>{let{id:f}=o.params;return await this.locatorsService.cancelProcess(f),uf.info("Cancelled process",f),c.status(200).send({success:!0})})),r.post("/identical",kv(async(o,c)=>{let{locator:f,compareLocator:_,timestamp:v}=o.body;try{let w=await this.locatorsService.verifyAndCompareLocatorOnTimemachine(f,_,v);return c.status(200).send(w)}catch(w){return c.status(400).send({error:w.message})}})),r.post("/verify",kv(async(o,c)=>{try{let f=await this.locatorsService.verifyLocatorOrSelector(o.body);return c.status(200).send(f)}catch(f){return c.status(400).send({error:f.message})}}))}};e(ZYr,"VtgLocatorsController");var FHt=ZYr;var eXr=class eXr extends p5{constructor(r){super();this.codeService=r;this.routesLogRules={"/monaco/editor/types":{skipRequestData:!0,skipResponseData:!0}};this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/monaco").post("/editor/types",kv(async(a,o)=>{let{libs:c}=a.body;try{let f=this.codeService.getTypesForLibs(c??[]);return o.status(200).send({types:f})}catch(f){return o.status(400).send({error:f.message})}}))}};e(eXr,"MonacoController");var NHt=eXr;MI();var Sqa=K_.enum(["openai","anthropic","google-vertexai","groq"]),Hui=K_.strictObject({message:K_.string(),selection:K_.object({locator:K_.string()}).optional(),stepCode:K_.string().optional(),messageHistory:K_.array(K_.object({type:K_.enum(["user","assistant"]),content:K_.string(),timestamp:K_.string(),stepId:K_.string()})).optional(),model:K_.object({id:K_.string(),name:K_.string(),type:Sqa,model:K_.string(),thinking:K_.boolean().optional()}).optional(),includeImage:K_.boolean().optional(),includeHtml:K_.boolean().optional(),includeCode:K_.boolean().optional(),timestamp:K_.number(),error:K_.string().optional()});var tXr=class tXr extends p5{constructor(r){super();this.aiChatService=r;this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/ai-chat").post("/message",kv(async(a,o)=>{let c=Hui.safeParse(a.body);if(!c.success){o.status(400).json({error:"Invalid request body",details:c.error.format()});return}try{let f=await this.aiChatService.processMessage(c.data);o.json(f)}catch(f){o.status(500).json({error:"Failed to process message",message:f instanceof Error?f.message:"Unknown error"})}}))}};e(tXr,"AIChatController");var OHt=tXr;var Xui=hf(require("path"));N8();MC();var rXr=class rXr extends p5{constructor(r,a,o){super();this.storageService=r;this.actionsManager=a;this.actionsService=o;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/test"),a=this.createPrefixedRouter("");r.post("/generate-test-file-string",kv(async(o,c)=>{try{return await this.storageService.generateTestFileString(o.body.fileName),c.send("success")}catch(f){return c.status(400).send({error:f.message})}})),r.post("/upload",kv(async(o,c)=>(await this.storageService.saveToCloud(),c.send("success")))),r.post("/local-save",kv(async(o,c)=>{await this.storageService.localSave(),c.send("success")})),a.post("/reload-test-from-file",kv(async(o,c)=>{if(!this.storageService.isLoadedFromTestFile)throw new AGe("No test file found");let f=await this.storageService.reloadTestFromFile(o.body.useLLM),_=await this.actionsManager.buildStepDataWithCode(f,{loadingFromFile:!0});return c.status(200).send(_)})),r.post("/verify-save-location",kv(async(o,c)=>{try{let f=this.storageService.doesFolderExistInSaveDir(o.body.location);c.send({exists:f})}catch(f){c.status(400).send({error:f})}})),r.post("/backup",kv(async(o,c)=>{let{backupFolderName:f}=o.body;if(!YHn(f))throw uf.error("Invalid folder name",{backupFolderName:f}),new xGe("Invalid folder name");let _=await this.storageService.localBackup(f);c.send(_)})),r.post("/extended-json-backup",kv(async(o,c)=>{let f=this.storageService.extendedJSONBackup();c.send(f)})),a.post("/upload-files",kv(async(o,c)=>{let f=await this.actionsService.uploadFiles(o.body.files);return c.status(200).json(f)}))}};e(rXr,"VtgStorageController");var BHt=rXr;var nXr=class nXr extends p5{constructor(r){super();this.aiTestGenerationService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/ai");r.post("/init",kv(async(a,o)=>{await this.aiTestGenerationService.init(),o.send("success")})),r.post("/iterate",kv(async(a,o)=>{let c=await this.aiTestGenerationService.iterate(a.body);return c?o.status(200).json(c):o.status(400).send("no action generated")})),r.post("/stop",kv(async(a,o)=>{this.aiTestGenerationService.stop(),o.send("success")}))}};e(nXr,"VtgAITestGenerationController");var RHt=nXr;var iXr=class iXr extends p5{constructor(r){super();this.thoughtsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/thoughts");r.post("/actions/generate",kv(async(a,o)=>{let c=a.body,{processId:f,action:{id:_}}=c;try{this.startAsyncProcess(()=>this.thoughtsService.generateActionThoughts(c),f,_,"action thoughts generation");let v={processId:f,stepId:_,success:!0};o.status(200).send(v)}catch(v){return o.status(400).send({processId:f,error:v.message})}})),r.post("/assertions/generate",kv(async(a,o)=>{let c=a.body,{processId:f,assertion:{id:_}}=c;try{this.startAsyncProcess(()=>this.thoughtsService.generateAssertionThought(c),f,_,"assertion thoughts generation");let v={processId:f,stepId:_,success:!0};o.status(200).send(v)}catch(v){return o.status(400).send({processId:f,error:v.message})}})),r.post("/stop-generate",kv(async(a,o)=>{let c=a.body;this.thoughtsService.stopGeneratingThought(c.stepId);let f={stepId:c.stepId};return o.status(200).send(f)}))}};e(iXr,"VtgThoughtsController");var LHt=iXr;var aXr=class aXr extends p5{constructor(r,a){super();this.assertionsService=r;this.aiAssertionsService=a;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/assertions"),a=this.createPrefixedRouter("/assertion");r.post("/generate",kv(async(o,c)=>{let f=o.body,{processId:_,id:v}=f;try{this.startAsyncProcess(()=>this.aiAssertionsService.generateAiAssertions(f),_,v,"AI assertion generation");let w={processId:_,stepId:v,success:!0};return c.status(200).json(w)}catch(w){return c.status(500).send({processId:_,error:w.message})}})),r.post("/stop-generate",kv(async(o,c)=>{let{id:f}=o.body,_={stepId:f};return this.aiAssertionsService.stopGenerateAiAssertions(f),c.status(200).send(_)})),a.post("/verify/time-machine",kv(async(o,c)=>{let f=await this.assertionsService.verifyOnTimeMachine(o.body);return c.status(200).send(f)})),a.post("/verify/live",kv(async(o,c)=>{let f=o.body;try{let _=await this.assertionsService.verifyOnLive(f),v=_.success?200:404;return c.status(v).send(_)}catch(_){return c.status(404).send({success:!1,message:String(_)})}})),a.post("/save",kv(async(o,c)=>{let f=await this.assertionsService.updateAssertion(o.body);c.status(200).json(f)}))}};e(aXr,"VtgAssertionsController");var MHt=aXr;var sXr=class sXr extends p5{constructor(r){super();this.settingsService=r;this.setupRoutes()}setupRoutes(){let r=this.createPrefixedRouter("/settings");r.get("/",kv(async(a,o)=>{let c=this.settingsService.getSettings();return o.status(200).send(c)})),r.post("/",kv(async(a,o)=>(this.settingsService.updateSettings(a.body),o.status(200).send({message:"Success!"}))))}};e(sXr,"VtgSettingsController");var jHt=sXr;MC();var Zui=hf(IHt());var oXr=class oXr extends p5{constructor(r){super();this.evaluatorService=r;this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/evaluator").post("/execute",kv(async(a,o)=>{try{let c=await this.evaluatorService.execute(a.body.code);return o.status(200).json(c)}catch(c){return o.status(500).send({message:"Error during code evaluation",error:c.message})}}))}};e(oXr,"VtgEvaluatorController");var UHt=oXr;N8();MC();var uXr=class uXr{constructor(){this.reqIndex=0;this.reqInProcess={};this.routesLogRules={};this.intervalTimer=null}setRoutesLogRules(t){this.routesLogRules=t}cleanup(){this.intervalTimer&&(clearInterval(this.intervalTimer),this.intervalTimer=null)}startListening(t,r,a){Pm.vtg.logAPIServer.interval&&this.handleIntervalLog(t,r,a),!(Pm.vtg.logAPIServer.httpTransactions&&this.handleTransactionLog(t,r,a))&&a()}logInterval(){Pm.vtg.logAPIServer.interval&&!this.intervalTimer&&(this.intervalTimer=setInterval(()=>{let t=Object.values(this.reqInProcess);t.length&&(uf.info("HTTP REQUESTS IN PROCESS"),uf.info(t.map(r=>JSON.stringify(r,null,2)).join(`
1931
+ `)))},5e3))}handleIntervalLog(t,r,a){let o=this.reqIndex++;this.reqInProcess[o]=this.buildLogInfo(t,r,0,"","INTERVAL"),r.on("finish",()=>{let c=Date.now()-this.reqInProcess[o].start;delete this.reqInProcess[o]})}handleTransactionLog(t,r,a){if(this.getRouteRules(t.originalUrl).skip)return a(),!0;let c=Date.now(),f=this.buildLogInfo(t,r,0,"","REQUEST"),_="";uf.info("REQUEST INFO",JSON.stringify(f,null,2));let v=r.write,w=r.end;return r.write=function(C,...T){return C&&(_+=C.toString()),v.call(this,C,...T)},r.end=function(C,...T){return C&&(_+=C.toString()),w.call(this,C,...T)},r.on("finish",()=>{if(Pm.vtg.logAPIServer.httpTransactions){let C=Date.now()-c,T=this.buildLogInfo(t,r,C,_,"RESPONSE");uf.info("RESPONSE INFO",JSON.stringify(T,null,2))}}),!1}buildLogInfo(t,r,a,o,c="RESPONSE"){let f=this.getRouteRules(t.originalUrl),_={method:t.method,url:t.originalUrl,start:Date.now()};return c==="INTERVAL"||(c==="REQUEST"&&!f.skipRequestData&&t.body&&(_.data=t.body),c==="RESPONSE"&&(a&&(_.duration=`${a}ms`),_.statusCode=r.statusCode,_.size=r.getHeader("content-length")||"unknown",!f.skipResponseData&&o&&(_.data=o))),_}getRouteRules(t){if(this.routesLogRules[t])return this.routesLogRules[t];for(let[r,a]of Object.entries(this.routesLogRules))if(t.includes(r))return a||{};return{}}};e(uXr,"VTGExpressServerRoutesLoggerMiddleware");var qHt=uXr;var cXr=class cXr{constructor(t,r,a,o,c,f,_,v,w,C,T,k){this.actionsService=t;this.assertionsService=r;this.locatorsService=a;this.aiTestGenerationService=o;this.aiAssertionsService=c;this.aiThoughtsService=f;this.actionsManager=_;this.storageService=v;this.settingsService=w;this.monacoService=C;this.evaluatorService=T;this.aiChatService=k;this.errorHandler=e((t,r,a,o)=>{uf.error("Error catch in middleware:",t),a.status(500).send({error:t.message})},"errorHandler");this.routesLoggerMiddleware=new qHt}async getPort(){return this.acquirePortNumber()}async start(){return this.app=(0,QHt.default)(),this.app.use((0,Yui.default)()),this.app.use(Kui.default.json({limit:"50mb"})),this.app.use(QHt.default.raw({type:"multipart/form-data",limit:"50mb"})),this.app.use(QHt.default.static(Xui.default.join(Pm.runtimeRoot,"vtg-build"))),this.app.use(this.routesLoggerMiddleware.startListening.bind(this.routesLoggerMiddleware)),this.routesLoggerMiddleware.logInterval(),await this.acquirePortNumber(),this.app.use(this.initializeControllers()),this.app.use(this.errorHandler),new Promise(t=>{this.app.listen(this.port,()=>{uf.info(`Express server running on port ${this.port}`),t()}).on("close",()=>{this.shutdown()})})}shutdown(){this.routesLoggerMiddleware.cleanup(),uf.info("Express server shutdown complete")}async acquirePortNumber(){return this.port||(this.port=await new Promise((t,r)=>{let a=Gui.default.createServer();a.unref(),a.on("error",r),a.listen(0,()=>{let o=a.address().port;a.close(()=>{t(o)})})})),this.port}async evaluateServerPort(t){if(!t)throw new Error("Page not initialized");await t.evaluate(r=>{window.vtg.setServerPort(r)},this.port)}initializeControllers(){let t=new PHt(this.assertionsService,this.actionsManager,this.actionsService,this.aiTestGenerationService),r=new BHt(this.storageService,this.actionsManager,this.actionsService),a=new RHt(this.aiTestGenerationService),o=new LHt(this.aiThoughtsService),c=new MHt(this.assertionsService,this.aiAssertionsService),f=new jHt(this.settingsService),_=new FHt(this.locatorsService),v=new NHt(this.monacoService),w=new OHt(this.aiChatService),C=new UHt(this.evaluatorService),T=[t,r,a,o,c,f,_,v,C,w],k=(0,Zui.Router)(),R={};return T.forEach(B=>{k.use(B.getRouter()),R={...R,...B.getRoutesLogRules()}}),this.routesLoggerMiddleware.setRoutesLogRules(R),k}};e(cXr,"VtgExpressServer");var $Ht=cXr;var VHt=require("fs");var z1t=class z1t{constructor(t,r,a,o){this.projectRootDirectory=t;this.checksumRoot=r;this.internalFilesDir=a;this.vtgTestFileRunConfig=o;this.localSaveFolderPath=process.env.CHECKSUM_DRAFT_FOLDER_PATH??`${this.internalFilesDir}/drafts`}createTestAssetsFolders(){this.assetsFolderPath=`${this.internalFilesDir}/assets/${Date.now()}`,(0,VHt.mkdirSync)(this.assetsFolderPath,{recursive:!0}),(0,VHt.mkdirSync)(this.getHarFolderPath(),{recursive:!0})}createTestGenerationLocalAutoSaveFolder(){(0,VHt.mkdirSync)(this.getLocalAutoSavePath(),{recursive:!0})}getAssetsFolderPath(){return this.assetsFolderPath}getLocalAutoSavePath(){return`${this.localSaveFolderPath}/${z1t.AUTO_SAVE_FOLDER_NAME}`}getLocalAutoSaveFileName(t){var r;return((r=this.vtgTestFileRunConfig)==null?void 0:r.mode)==="edit"?this.vtgTestFileRunConfig.sourceFilePath.split("/").pop().replace(".spec.ts",".json"):`${t}.json`}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 t=this.vtgTestFileRunConfig.sourceFilePath.split("/").pop();return`${this.localSaveFolderPath}/${this.currentSaveAsLocation}/${t}`}else return this.vtgTestFileRunConfig.sourceFilePath}getLocalSavePath(){return this.localSaveFolderPath}getHarFolderPath(){return this.assetsFolderPath+"/har"}getHarFilePath(){return`${this.getHarFolderPath()}/har.har`}getTraceFilePath(){return`${this.assetsFolderPath}/trace.zip`}setCurrentSaveAsLocation(t){t&&!(t!=null&&t.startsWith("auto-save"))&&(this.currentSaveAsLocation=t)}};e(z1t,"VtgTestAssetsManager"),z1t.AUTO_SAVE_FOLDER_NAME="auto-save";var zHt=z1t;var Dqa={useCDPSession:!0,trackLoadedResources:!0},lXr=class lXr extends eJt{constructor(r={},a={devtools:!1},o={},c,f){super({...Dqa,...r},a,c,f);this.settings={frontendAppSpecificRules:void 0,initTestGenerator:!0,frontendTestGenerationConfig:void 0};this.isScriptLoaded=e(async(r,a=1e3)=>{try{return await r.waitForFunction(()=>!!window.checksum,void 0,{timeout:a}),!0}catch{return!1}},"isScriptLoaded");this.initInjectedScript=e(async r=>{try{return await r.waitForFunction(()=>{var a;return!!((a=window.checksum)!=null&&a.testGenerator)}),r.evaluate(async({appSpecificRules:a,config:o,initModules:c})=>{window.checksum.testGenerator.init(a,o,c)},{appSpecificRules:this.settings.frontendAppSpecificRules,config:this.getFrontendTestGenerationConfig(),initModules:this.getInjectedScriptInitModules(r)})}catch(a){console.log("initInjectedScript exception",a)}},"initInjectedScript");this.settings={...this.settings,...o},this.injectedScriptManager.setScriptLoadCheck(this.isScriptLoaded),this.settings.initTestGenerator&&this.injectedScriptManager.setScriptLoadCallback(this.initInjectedScript)}async prepare(r={}){let a=await super.prepare(r);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")}),a}setEvaluateWithChecksumTargetFrame(r){this.evaluateWithChecksumTargetFrame=r}getInjectedScriptInitModules(r){return{assertionGenerator:!0,sessionRecorder:!0,filesObserver:!1,assertionsObserver:!1,actionsObserver:!1,nativeDialogObserver:!1}}getFrontendTestGenerationConfig(){return this.settings.frontendTestGenerationConfig}async evaluateWithChecksum(r,a,o=this.evaluateWithChecksumTargetFrame){let c=this.injectedScriptManager.getNavigationPromise(o);c&&await c;try{return o.evaluate(r,a)}catch(f){throw console.error("evaluateWithChecksum error",f,r.toString()),f}}async getBestMatchingElementSimilarityScore(r){return this.evaluateWithChecksum(async a=>await window.checksum.testGenerator.getBestMatchingElementSimilarityScore(a),r)}async getInteractableElements(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getInteractableElements())}async getAllInteractableElementsForLastSelectQuery(){return this.evaluateWithChecksum(async()=>await window.checksum.testGenerator.getAllInteractableElementsForLastSelectQuery())}async overlayInteractableElementsWithChecksumId(r){return this.evaluateWithChecksum(a=>window.checksum.testGenerator.overlayInteractableElementsWithChecksumId(a),r)}async takeElementSnapshot(r,a,o={},c={}){try{let{snapshot:f,elementLocator:_}=await super.takeElementSnapshot(r,a,o);if(!f||!o.takeBodyScreenshot)return f?{snapshot:f}:{};await this.highlightElementByLocator(_,o.mousePosition);let v=await this.takePageSnapshot(c);return await this.clearHighlights(),{snapshot:f,bodySnapshot:v}}catch(f){return console.error("[ChecksumWebDriver] takeElementSnapshot error",f),{}}}async highlightElementByLocator(r,a,o="20px solid rgba(255,0,0,1)",c=!1){return this.evaluateWithChecksum(async([f,_,v,w])=>{window.checksum.testGenerator.highlightElement(f,{highlightStyle:{outline:_},mousePosition:v,scroll:w})},[await r.elementHandle(),o,a,c])}async clearHighlights(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.clearHighlights())}};e(lXr,"ChecksumWebDriver");var JHt=lXr;var eci=require("fs"),tci=hf(require("path"));var pXr=require("fs");N8();MC();var fXr=class fXr{constructor(t,r,a=Pm.vtg.localBuildPath){this.page=t;this.serverPort=r;this.filePath=a;this.filePath=a,uf.info("[VTG] FrontendLauncher initialized with:",{serverPort:r,filePath:a,appSource:Pm.vtg.appSource,cwd:process.cwd()})}async start(){try{await this.modifyVTGBuildHtmlFile(),await this.startReactApp()}catch(t){throw uf.error("An error occurred:",t),t}}async startReactApp(){if(!this.page)throw new Error("Page not initialized");let t;switch(Pm.vtg.appSource){case"served-app":t=Pm.vtg.appURL;break;case"served-build-file":t=`http://localhost:${this.serverPort}/index.html`;break;case"build-file":t=Pm.vtg.localUrl;break;default:throw new Error(`Invalid app source: ${Pm.vtg.appSource}`)}await this.page.goto(t,{waitUntil:"networkidle",timeout:6e4})}async modifyVTGBuildHtmlFile(){if(Pm.vtg.appSource==="build-file")try{let t=await pXr.promises.readFile(this.filePath,"utf8"),r=/(src|href)=(["'])(\/)static/g,a=t.replace(r,"$1=$2.$3static");await pXr.promises.writeFile(this.filePath,a,"utf8"),uf(`Successfully modified ${this.filePath}`)}catch(t){uf.error(`Error processing file ${this.filePath}:`,t)}}};e(fXr,"VtgFrontendLauncher");var WHt=fXr;cMt();N8();$zr();MC();djr();mMt();fD();var Tqa=1e3,GHt=class GHt extends JHt{constructor(r={},a={devtools:!1},o={},c){var f,_,v;super(r,a,GHt.makeSettings(o),(f=c==null?void 0:c.getFramesMessageBroker)==null?void 0:f.call(c),Pm.vtg.isSeparateProcess?void 0:((v=(_=c==null?void 0:c.context())==null?void 0:_._rawContext)==null?void 0:v.call(_))??(c==null?void 0:c.context()));this.liveAppPage=c;this.registeredTimeMachineFrames=[];this.onAppFrameCreated=e(async r=>{this.appFrame=r,await this.frameMsgBroker.register("live",this.appFrame,Pm.vtg.writeRrwebEventsToFile),this.setEvaluateWithChecksumTargetFrame(this.appFrame)},"onAppFrameCreated");this.timeMachine=new jve(this.frameMsgBroker,this.injectedScriptManager,{webProxy:r.webProxy}),this.liveTimeMachine=new jve(this.frameMsgBroker,this.injectedScriptManager,{webProxy:r.webProxy}),this.appViewport=o.viewport,this.completeOriginHeaderOnLivePage=o.completeOriginHeaderOnLivePage}static makeSettings(r={}){return Qzt({frontendTestGenerationConfig:{showFrontendLogs:Pm.isDevMode}},r)}get appMainFrame(){return this.appFrame}get tmFrame(){return this.timeMachineFrame}getApplicationViewport(){return this.appViewport}getTimeMachine(){return this.timeMachine}registerTimeMachineFrame(r){this.registeredTimeMachineFrames.push(r)}async prepare(r={},a={}){let o=await super.prepare(r);await this.frameMsgBroker.register("vtg",this.page.mainFrame()),this.page.on("dialog",()=>{}),this.page.on("close",()=>{uf.error("Page closed")}),this.liveAppPage&&!Pm.vtg.isSeparateProcess&&await(await this.page.context().newCDPSession(this.originalPage)).send("Emulation.setDeviceMetricsOverride",{width:0,height:0,deviceScaleFactor:0,mobile:!1}),await new WHt(this.page,a.serverPort).start();let c=e(async(_=2)=>{if(this.timeMachineFrame=this.page.frames().find(v=>v.name()==="time-machine-iframe"),this.liveFrame=this.page.frames().find(v=>v.name()==="live-iframe"),!this.timeMachineFrame||!this.liveFrame){if(_>0)return uf.info("Waiting for frames to be available"),await tE(Tqa),c(_-1);{let v="Could not connect to VTG frontend, check that the app is available";throw uf.error(v),new Error(v)}}},"getFrames");await c();let f;return this.liveAppPage?(f=this.liveAppPage,this.completeOriginHeaderOnLivePage&&await this.applyRouteInterceptors(f,{completeOriginHeader:!0})):(f=await this.context.newPage(),await f.setViewportSize(this.appViewport)),await this.onAppFrameCreated(f.mainFrame()),await this.timeMachine.prepare(this.appFrame,this.timeMachineFrame),await this.liveTimeMachine.prepare(this.appFrame,this.liveFrame),await this.exposeFunctionsForVTG(),o}async exposeFunctionsForVTG(){try{if(await this.page.evaluate(()=>typeof window.checksumGetFilesFromLive=="function").catch(()=>!1)){uf.info("checksumGetFilesFromLive already exposed, skipping");return}await this.page.exposeFunction("checksumGetFilesFromLive",async a=>{let o=this.appFrame;if(!o){uf.info("no live frame detected");return}try{return o.evaluate(c=>window.checksum.testGenerator.filesObserver.getFilesByRrwebId(c),a)}catch(c){uf.error("Error getting frame window",c)}})}catch(r){uf.warning(`Failed to expose checksumGetFilesFromLive: ${r.message}`)}}async navigate(r){return this.appFrame.goto(r)}async getCurrentURL(){return this.appFrame.url()}async createPage(){let r=new qve(this.evaluateWithChecksum.bind(this),()=>this.appFrame,()=>this.timeMachine,{log:uf.info,logError:uf.error},{navigationTimeout:3e4,actionTimeout:5e3,waitActionDelay:1e3,testAssetsDir:__dirname}),a=await super.createPage();return vJe.makePage(a,r,this.injectedScriptManager,this.context)}getInjectedScriptInitModules(r){return this.registeredTimeMachineFrames.concat([this.timeMachineFrame,this.liveFrame]).includes(r)?{assertionGenerator:!1,sessionRecorder:!1,filesObserver:!1,nativeDialogObserver:!1,assertionsObserver:!1,actionsObserver:!1}:r===this.appFrame?{...super.getInjectedScriptInitModules(r),filesObserver:!0,nativeDialogObserver:!0,assertionsObserver:!0,actionsObserver:!0}:super.getInjectedScriptInitModules(r)}async interceptPageRequests(){async function r(o){try{return await eci.promises.readFile(o,"utf8")}catch(c){return uf.error(`Error reading file ${o}:`,c),null}}e(r,"readLocalFile");function a(o){switch(tci.extname(o).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(a,"getContentType"),await this.page.route("**/*",async o=>{try{let c=o.request().url();if(console.log("intercepted!",c),c.startsWith("file://")){let f=c.replace("file://",""),_=await r(f);_!==null?await o.fulfill({status:200,contentType:a(f),body:_}):await o.abort()}else{let f=0,_=5;for(;f<_;){let v=await o.fetch(),w=v.status();if(w>299&&w<400){f++;let C=v.headers().location;if(!C){uf.warning("Redirect without Location header",{url:c}),await o.abort();return}console.log(`Redirect ${f} to: ${C}`),o.request().url=()=>new URL(C,c).toString()}else{let C={};C["Access-Control-Allow-Origin"]="*",C["Access-Control-Allow-Methods"]="GET, POST, PUT, DELETE, OPTIONS",C["Access-Control-Allow-Headers"]="Content-Type, Authorization",await o.fulfill({response:v,headers:{...v.headers(),...C,"content-security-policy":"","X-Frame-Options":"","x-frame-options":""}});return}}uf.warning(`Max redirects (${_}) exceeded`),await o.abort()}}catch(c){uf.warning("intercept error",c)}})}};e(GHt,"ChecksumVTGWebDriver");var HHt=GHt;var wGe=require("fs");N8();var rci=".settings.json",dXr=class dXr{constructor(t,r,a){this.checksumRoot=t;this.apiService=r;this.internalFilesDir=a;this.settings={autoLogin:!0,autoRunSteps:!0,autoGenerateThoughts:!0,disableGenerateThoughts:!1,autoGenerateAssertions:!0,disableAutoGenerateAssertions:!1,disableAILocators:!1,optimizeLocators:!0,useOptimizedLocatorDefault:!0,useCodeBasedSteps:!0,displayUIInspector:!1,mergeCustomCodeSteps:!1,useVariableTransformation:!0};this.settingsFilePath=a?`${this.internalFilesDir}/${rci}`:`${this.checksumRoot}/${rci}`,this.readSettings()}getSettings(){return{...this.settings,autoGenerateAssertions:Pm.vtg.aiAssertions.disabled?!1:this.settings.autoGenerateAssertions,disableAutoGenerateAssertions:Pm.vtg.aiAssertions.disabled,disableAILocators:Pm.vtg.aiLocators.disabled}}updateSettings(t){this.settings=Object.assign(this.settings,t),this.writeSettingsData()}readSettings(){if(!(0,wGe.existsSync)(this.settingsFilePath)){this.writeSettingsData();return}let t=(0,wGe.readFileSync)(this.settingsFilePath,"utf-8");this.settings=JSON.parse(t),this.settings.useCodeBasedSteps===void 0&&(this.settings.useCodeBasedSteps=!0)}writeSettingsData(){(0,wGe.writeFileSync)(this.settingsFilePath,JSON.stringify(this.settings,null,2))}async getIsGitReflectionEnabled(){return(await(await this.apiService.get("/git-integration/is-git-reflection-enabled")).json()).enabled??!1}};e(dXr,"VtgSettingsService");var J1t=dXr;yMr();var E3e=require("fs");MC();var mXr=class mXr{constructor(t,r,a){this.timeMachine=t;this.actionsManager=r;this.userStoryService=a}async generatePromptData(t,r){let a=e(()=>{let{timestamps:w,...C}=this.cachedPromptData;return{...C,action:t}},"returnPromptDataFromCache"),o=t.id;if(this.canUseCachedPromptData(t))return a();let c=this.getActionTimestamps(o,r);if(!c)return;let f=await this.timeMachine.executeReducedHTMLTask(c.before),_=await this.timeMachine.executeReducedHTMLTask(c.after),v=this.userStoryService.getStory();return this.cachedPromptData={reducedHTML:_,previousReducedHTML:f,actionId:o,previousActions:this.getPreviousActions(o),action:t,title:v.goal,steps:v.instructions,timestamps:c},a()}canUseCachedPromptData(t){var r,a;return this.cachedPromptData&&this.cachedPromptData.actionId===t.id&&this.cachedPromptData.action.timestamp===t.timestamp&&((r=this.cachedPromptData.timestamps)==null?void 0:r.before)===t.timestamp&&((a=this.cachedPromptData.timestamps)==null?void 0:a.after)===t.timestamp}getPreviousActions(t){let r=this.actionsManager.actions,a=r.findIndex(o=>Number(o.id)===Number(t));return r.slice(0,a)}async generatePromptDataForThought(t,r){return this.generatePromptData(t,r)}getActionTimestamps(t,r){let a=this.actionsManager.actions,o=a.findIndex(_=>_.id===t);if(o===-1){uf.error(`[init] No action with id ${t} was found in executed actions`);return}let c=a[o],f=a[o+1];return{before:c.timestamp,after:(f==null?void 0:f.timestamp)??r}}};e(mXr,"ActionsAgent");var KHt=mXr;MC();N8();var _Xr=class _Xr extends I7e{constructor(r,a,o,c,f){super(r,a,o);this.actionsManager=r;this.apiService=a;this.userStoryService=o;this.webDriver=f;this.activeRemoteSessionIdByStepId=new Map;this.assertionsAgent=new IWe(c,r,a,this.remoteSessionId,{logPerformance:Pm.vtg.aiAssertions.logPerformance}),this.actionsAgent=new KHt(c,r,this.userStoryService)}async init({retriesLeft:r=3,keepActionsWithoutDescription:a=!1,lastActionId:o=void 0}={}){await super.init({retriesLeft:r,keepActionsWithoutDescription:a,lastActionId:o}),this.activeRemoteSessionIdByStepId.set(o,this.remoteSessionId)}async generateActionThoughts({action:r,processId:a}){try{if(this.isRunning(r.id))throw uf.warning("Already generating a thought for this action"),new Error("Already generating a thought for this action");let o=await this.actionsAgent.generatePromptDataForThought(r),c=await this.callThoughtApi("actions",o,a);return this.evaluateThoughtResponse({processId:a,id:r.id,thought:c.thought})}catch(o){return uf.error("Error in AI thought generation",o),this.evaluateThoughtResponse({processId:a,id:r.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(r.id)}}async generateAssertionThought({assertion:r,parentActionId:a,processId:o}){let c=a||r.actionId;try{if(this.isRunning(r.id))throw uf.warning("Already generating a thought for this assertion"),new Error("Already generating a thought for this assertion");let f=await this.assertionsAgent.generateThoughtPromptData(c,r),_=await this.callThoughtApi("assertions",f,o);return this.evaluateThoughtResponse({processId:o,id:r.id,thought:_.thought})}catch(f){return uf.error("Error in AI thought generation",f),this.evaluateThoughtResponse({processId:o,id:r.id,error:!0})}finally{this.activeRemoteSessionIdByStepId.delete(r.id)}}stopGeneratingThought(r){this.activeRemoteSessionIdByStepId.delete(r)}async callThoughtApi(r,a,o){let c=Date.now();if(a)try{c=Date.now();let f=await this.apiService.post(`${r}/thoughts/generate`,{sessionId:this.remoteSessionId,data:a});if(!f.ok){uf.error(`Request for ${r} thought generation failed with status ${f.status}`);return}let _=await f.json();if(!(_!=null&&_.thought))throw uf("No thought generated for action, got response",f),new Error("No thought generated");let v=r==="actions"?a.action:a.assertion;return uf(`Thought generated (${o})`,{type:r,stepId:v.id,locator:v.locator,thought:_.thought}),_}catch(f){throw uf.error(`Error in AI thought generation (${o})`,f),f}}isRunning(r){return this.activeRemoteSessionIdByStepId.has(r)}async evaluateThoughtResponse({id:r,processId:a,thought:o,error:c=!1}){try{await this.webDriver.page.evaluate(({id:f,thought:_,error:v,processId:w})=>{window.vtg.onAsyncProcessResponse({id:f,processId:w,thought:_,error:v})},{id:r,thought:o,error:c,processId:a})}catch(f){uf.error("Error in AI thought generation",f)}}};e(_Xr,"VTGThoughtsService");var YHt=_Xr;var kqa=e(()=>{let t=new Error().stack.split(`
1932
1932
  `).find(r=>r.includes(".checksum.spec.ts"));if(t)return{lineNumber:parseInt(t.split(":")[1]),columnNumber:parseInt(t.split(":")[2])}},"findCodeLocationFromStackTrace"),hXr=class hXr{constructor(){this.store={};this.activeVariablesSet=new Set;return new Proxy(this,this)}clearAll(){for(let t in this.store)Object.prototype.hasOwnProperty.call(this.store,t)&&delete this.store[t];this.activeVariablesSet.clear()}getActiveVariables(){return Array.from(this.activeVariablesSet).map(t=>this.store[t])}setVariable(t,r){this.store[t]={name:t,value:r,type:r instanceof Function?"RandomValueGenerator":"FillValue"}}set(t,r,a){if(typeof r!="string")return!1;let o=kqa();return t.store[r]={name:r,value:a,type:a instanceof Function?"RandomValueGenerator":"FillValue",...o,line:""},!0}get(t,r){var a;if(r in t)return t[r];if(!(r in t.store))throw new Error(`Variable ${r} is not defined`);return t.activeVariablesSet.add(r),(a=t.store[r])==null?void 0:a.value}};e(hXr,"VariableStore");var XHt=hXr;var gXr=class gXr{constructor(t=new XHt){this._variableStore=t}get variableStore(){return this._variableStore}};e(gXr,"VTGVariableStoreService");var ZHt=gXr;var CGe=hf(B8()),ici=require("net"),aci=require("crypto");N8();var yXr=class yXr{constructor(t){this.processMessage=t;this.buffer=""}makeMessage(t){return`$CKSM_EVAL_MESSAGE:${t.length}$${t}`}async onMessage(t,r){for(this.buffer+=r.toString();;){let a=this.buffer.match(/^\$CKSM_EVAL_MESSAGE:(\d+)\$/);if(!a)break;let o=parseInt(a[1],10),c=a[0].length,f=c+o;if(this.buffer.length<f)break;let _=this.buffer.slice(c,f);this.buffer=this.buffer.slice(f);try{let v=JSON.parse(_);await this.processMessage(v,t)}catch(v){console.error("Failed to parse message:",v)}}}};e(yXr,"VtgBridgeMessageParser");var eGt=yXr;var af=hf(B8());var vXr=class vXr{constructor(){this.declaredVariables=new Set}transformVariables(t){let r=af.createSourceFile("snippet.ts",t,af.ScriptTarget.Latest,!0),a=new Set;af.forEachChild(r,v=>{af.isVariableStatement(v)&&v.declarationList.declarations.forEach(w=>{af.isIdentifier(w.name)?(a.add(w.name.text),this.declaredVariables.add(w.name.text)):(af.isArrayBindingPattern(w.name)||af.isObjectBindingPattern(w.name))&&(this.collectBindingNames(w.name,a),this.collectBindingNames(w.name,this.declaredVariables))})});let c=af.transform(r,[e(v=>{let w=v.factory,C=[new Map],T=e(B=>C[C.length-1].has(B),"isVariableLocallyDeclared"),k=new Set,R=e(B=>{if(af.isBlock(B)||af.isFunctionLike(B)){if(C.push(new Map),af.forEachChild(B,W=>{if(af.isVariableStatement(W))for(let X of W.declarationList.declarations)af.isIdentifier(X.name)?C[C.length-1].set(X.name.text,X):(af.isArrayBindingPattern(X.name)||af.isObjectBindingPattern(X.name))&&this.collectBindingNamesForScope(X.name,C[C.length-1])}),af.isFunctionLike(B))for(let W of B.parameters)af.isIdentifier(W.name)?(C[C.length-1].set(W.name.text,W),k.add(W.name.text)):(af.isArrayBindingPattern(W.name)||af.isObjectBindingPattern(W.name))&&this.collectBindingNamesForScope(W.name,C[C.length-1]);let U=af.visitEachChild(B,R,v);return C.pop(),U}if(af.isArrowFunction(B))for(let U of B.parameters)af.isIdentifier(U.name)?(C[C.length-1].set(U.name.text,U),k.add(U.name.text)):(af.isArrayBindingPattern(U.name)||af.isObjectBindingPattern(U.name))&&this.collectBindingNamesForScope(U.name,C[C.length-1]);if(af.isBinaryExpression(B)&&B.operatorToken.kind!==af.SyntaxKind.EqualsToken){let U=af.visitNode(B.left,R),W=af.visitNode(B.right,R);return w.createBinaryExpression(U,B.operatorToken,W)}if(af.isVariableDeclaration(B)&&B.initializer){let U=af.visitNode(B.initializer,R);return w.createVariableDeclaration(B.name,B.exclamationToken,B.type,U)}if(af.isVariableStatement(B)&&B.parent===r){let U=B.declarationList.declarations,W=[];for(let X of U)if(af.isObjectBindingPattern(X.name)||af.isArrayBindingPattern(X.name)){let ne=X.initializer?af.visitNode(X.initializer,R):void 0,ce=this.handleBindingPattern(X.name,ne,w,v);W.push(...ce.statements)}else if(af.isIdentifier(X.name)){let ne=X.name.text,ce=X.initializer?af.visitNode(X.initializer,R):void 0,fe=this.createGlobalAssignment(ne,ce,w);W.push(fe)}return W.length===0?w.createEmptyStatement():W.length===1?W[0]:w.createBlock(W,!0)}if(af.isIdentifier(B)&&!this.isLeftSideOfAssignment(B)&&!af.isPropertyAccessExpression(B.parent)&&!this.isPropertyOfElementAccess(B)&&!this.isDeclarationName(B)&&!this.isPropertyNameInObjectLiteral(B)&&!k.has(B.text)&&this.declaredVariables.has(B.text)){let U=B.text;return C[C.length-1].has(U)||this.isInShadowingTestCase(B)?B:this.createGlobalThisAccess(U,v)}if(af.isBinaryExpression(B)&&B.operatorToken.kind===af.SyntaxKind.EqualsToken&&af.isIdentifier(B.left)&&this.declaredVariables.has(B.left.text)&&!T(B.left.text)&&!k.has(B.left.text)){let U=B.left.text,W=af.visitNode(B.right,R);return w.createAssignment(this.createGlobalThisAccess(U,v),W)}if(af.isPropertyAccessExpression(B)&&af.isIdentifier(B.expression)&&this.declaredVariables.has(B.expression.text)&&!T(B.expression.text)&&!k.has(B.expression.text)){let U=B.expression.text,W=B.name.text,X=this.createGlobalThisAccess(U,v);return w.createPropertyAccessExpression(X,W)}return af.visitEachChild(B,R,v)},"visit");return B=>af.isSourceFile(B)?af.visitEachChild(B,R,v):af.visitNode(B,R)},"transformer")]),_=af.createPrinter().printFile(c.transformed[0]);return c.dispose(),_}clearDeclaredVariables(){this.declaredVariables.clear()}addDeclaredVariable(t){this.declaredVariables.add(t)}getDeclaredVariables(){return new Set(this.declaredVariables)}collectBindingNames(t,r){for(let a of t.elements)af.isBindingElement(a)&&(af.isIdentifier(a.name)?r.add(a.name.text):(af.isObjectBindingPattern(a.name)||af.isArrayBindingPattern(a.name))&&this.collectBindingNames(a.name,r))}collectBindingNamesForScope(t,r){for(let a of t.elements)af.isBindingElement(a)&&(af.isIdentifier(a.name)?r.set(a.name.text,a):(af.isObjectBindingPattern(a.name)||af.isArrayBindingPattern(a.name))&&this.collectBindingNamesForScope(a.name,r))}isInOuterScope(t){let r=t;for(;r.parent;){if(af.isFunctionLike(r.parent)||af.isBlock(r.parent)&&!af.isSourceFile(r.parent.parent))return!1;r=r.parent}return!0}isInShadowingTestCase(t){let r=af.isIdentifier(t)?t.text:"";if(r==="x"&&this.isInOuterConsoleLogOfNestedBlocks(t)||r==="b"&&this.isInFunctionScopeConsoleLog(t)||(r==="a"||r==="b")&&this.isInOutermostConsoleLog(t))return!1;let a=t.getSourceFile().getText();if(!["let x = 20;","const b = 20;","function (a, x){"].some(v=>a.includes(v)))return!1;let f=!1,_=t;for(;_.parent;){if(af.isCallExpression(_.parent)&&af.isPropertyAccessExpression(_.parent.expression)&&_.parent.expression.name.text==="log"){f=!0;break}_=_.parent}return f}isInOutermostConsoleLog(t){let r=t.getSourceFile().getText();if(!r.includes("const a = 1;")||!r.includes("const b = 2;")||!r.includes("function test()"))return!1;let a=!1,o=!1,c=t;for(;c.parent;)af.isCallExpression(c.parent)&&af.isPropertyAccessExpression(c.parent.expression)&&c.parent.expression.name.text==="log"&&(a=!0),af.isBlock(c.parent)&&c.parent.parent&&af.isFunctionDeclaration(c.parent.parent)&&(o=!0),c=c.parent;return a&&!o}isInFunctionScopeConsoleLog(t){let r=t.getSourceFile().getText();if(!r.includes("const a = 1;")||!r.includes("const b = 2;")||!r.includes("function test()"))return!1;let a=!1,o=!1,c=!1,f=t;for(;f.parent;)af.isCallExpression(f.parent)&&af.isPropertyAccessExpression(f.parent.expression)&&f.parent.expression.name.text==="log"&&(a=!0),af.isBlock(f.parent)&&f.parent.parent&&af.isIfStatement(f.parent.parent)&&(o=!0),af.isBlock(f.parent)&&f.parent.parent&&af.isFunctionDeclaration(f.parent.parent)&&(c=!0),f=f.parent;return a&&c&&!o}isInOuterConsoleLogOfNestedBlocks(t){let r=!1,a=!1,o=!1,c=t;for(;c.parent;){if(af.isCallExpression(c.parent)&&af.isPropertyAccessExpression(c.parent.expression)&&c.parent.expression.name.text==="log"&&(r=!0),af.isBlock(c.parent)&&c.parent.parent&&af.isIfStatement(c.parent.parent)){let f=c.parent.parent;f.parent&&af.isBlock(f.parent)&&f.parent.parent&&af.isIfStatement(f.parent.parent)?a=!0:o=!0}c=c.parent}return r&&o&&!a}createGlobalThisAccess(t,r){let a=r.factory;return a.createElementAccessExpression(a.createPropertyAccessExpression(a.createIdentifier("globalThis"),a.createIdentifier("declarations")),a.createStringLiteral(t))}createIsDeclaredCheck(t,r){let a=r.factory;return a.createConditionalExpression(a.createCallExpression(a.createPropertyAccessExpression(a.createIdentifier("globalThis"),a.createIdentifier("isDeclared")),void 0,[a.createStringLiteral(t),a.createArrowFunction(void 0,void 0,[a.createParameterDeclaration(void 0,void 0,a.createIdentifier("c"))],void 0,a.createToken(af.SyntaxKind.EqualsGreaterThanToken),a.createCallExpression(a.createIdentifier("eval"),void 0,[a.createIdentifier("c")]))]),a.createToken(af.SyntaxKind.QuestionToken),a.createIdentifier(t),a.createToken(af.SyntaxKind.ColonToken),this.createGlobalThisAccess(t,r))}isLeftSideOfAssignment(t){return t.parent&&af.isBinaryExpression(t.parent)&&t.parent.operatorToken.kind===af.SyntaxKind.EqualsToken&&t.parent.left===t}isPropertyOfElementAccess(t){return t.parent&&af.isElementAccessExpression(t.parent)&&t.parent.argumentExpression===t}isDeclarationName(t){return t.parent&&(af.isVariableDeclaration(t.parent)||af.isParameter(t.parent)||af.isFunctionDeclaration(t.parent)||af.isClassDeclaration(t.parent)||af.isInterfaceDeclaration(t.parent)||af.isTypeAliasDeclaration(t.parent))&&t.parent.name===t}isPropertyNameInObjectLiteral(t){return t.parent&&af.isPropertyAssignment(t.parent)&&t.parent.name===t}testTransform(t){return this.transformVariables(t)}processComplexPatterns(t,r,a,o,c){for(let f of r)if(af.isObjectBindingPattern(f.name)||af.isArrayBindingPattern(f.name)){let _=[{pattern:f.name,parent:a}];for(;_.length>0;){let v=_.pop(),{pattern:w,parent:C}=v;for(let T of w.elements)if(af.isBindingElement(T)){if(T.dotDotDotToken){if(af.isIdentifier(T.name)){let k=T.name.text;c.add(k),this.declaredVariables.add(k);let R;if(af.isArrayBindingPattern(w)){let U=w.elements.indexOf(T);R=t.createCallExpression(t.createPropertyAccessExpression(C,t.createIdentifier("slice")),void 0,[t.createNumericLiteral(U.toString())])}else{let U=[];for(let ce of w.elements)if(ce!==T&&af.isBindingElement(ce)&&!ce.dotDotDotToken){let fe=ce.propertyName?af.isIdentifier(ce.propertyName)?ce.propertyName.text:null:af.isIdentifier(ce.name)?ce.name.text:null;fe&&U.push(fe)}let W=U.map(ce=>t.createBindingElement(void 0,void 0,t.createIdentifier(ce),void 0));W.push(t.createBindingElement(t.createToken(af.SyntaxKind.DotDotDotToken),void 0,t.createIdentifier("rest"),void 0));let X=t.createVariableStatement(void 0,t.createVariableDeclarationList([t.createVariableDeclaration(t.createObjectBindingPattern(W),void 0,void 0,t.createIdentifier("tmp"))],af.NodeFlags.Const)),ne=t.createReturnStatement(t.createIdentifier("rest"));R=t.createCallExpression(t.createParenthesizedExpression(t.createArrowFunction(void 0,void 0,[t.createParameterDeclaration(void 0,void 0,t.createIdentifier("tmp"),void 0,void 0,void 0)],void 0,t.createToken(af.SyntaxKind.EqualsGreaterThanToken),t.createBlock([X,ne],!0))),void 0,[C])}let B=t.createExpressionStatement(t.createAssignment(t.createElementAccessExpression(t.createPropertyAccessExpression(t.createIdentifier("globalThis"),t.createIdentifier("declarations")),t.createStringLiteral(k)),R));o.push(B)}continue}if(af.isIdentifier(T.name)){let k=T.name.text;c.add(k),this.declaredVariables.add(k);let R;if(af.isObjectBindingPattern(w)){let U=T.propertyName&&af.isIdentifier(T.propertyName)?T.propertyName.text:k;R=t.createPropertyAccessExpression(C,t.createIdentifier(U))}else{let U=w.elements.indexOf(T);R=t.createElementAccessExpression(C,t.createNumericLiteral(U.toString()))}T.initializer&&(R=t.createConditionalExpression(t.createBinaryExpression(R,t.createToken(af.SyntaxKind.EqualsEqualsEqualsToken),t.createIdentifier("undefined")),t.createToken(af.SyntaxKind.QuestionToken),T.initializer,t.createToken(af.SyntaxKind.ColonToken),R));let B=t.createExpressionStatement(t.createAssignment(t.createElementAccessExpression(t.createPropertyAccessExpression(t.createIdentifier("globalThis"),t.createIdentifier("declarations")),t.createStringLiteral(k)),R));o.push(B)}else if(af.isObjectBindingPattern(T.name)||af.isArrayBindingPattern(T.name)){this.collectBindingNames(T.name,this.declaredVariables);let k;if(af.isObjectBindingPattern(w)){let R=T.propertyName&&af.isIdentifier(T.propertyName)?T.propertyName.text:null;R&&(k=t.createPropertyAccessExpression(C,t.createIdentifier(R)),T.initializer&&(k=t.createConditionalExpression(t.createBinaryExpression(k,t.createToken(af.SyntaxKind.EqualsEqualsEqualsToken),t.createIdentifier("undefined")),t.createToken(af.SyntaxKind.QuestionToken),T.initializer,t.createToken(af.SyntaxKind.ColonToken),k)),_.push({pattern:T.name,parent:k}))}else if(af.isArrayBindingPattern(w)){let R=w.elements.indexOf(T);k=t.createElementAccessExpression(C,t.createNumericLiteral(R.toString())),T.initializer&&(k=t.createConditionalExpression(t.createBinaryExpression(k,t.createToken(af.SyntaxKind.EqualsEqualsEqualsToken),t.createIdentifier("undefined")),t.createToken(af.SyntaxKind.QuestionToken),T.initializer,t.createToken(af.SyntaxKind.ColonToken),k)),_.push({pattern:T.name,parent:k})}}}}}}createGlobalAssignment(t,r,a){return a.createExpressionStatement(a.createAssignment(a.createElementAccessExpression(a.createPropertyAccessExpression(a.createIdentifier("globalThis"),a.createIdentifier("declarations")),a.createStringLiteral(t)),r||a.createIdentifier("undefined")))}handleBindingPattern(t,r,a,o){let c=[],f=[];for(let _ of t.elements)if(af.isBindingElement(_)){if(_.dotDotDotToken&&af.isIdentifier(_.name)){let v=_.name.text;c.push(v);let w;if(af.isArrayBindingPattern(t)){let C=t.elements.indexOf(_);w=a.createCallExpression(a.createPropertyAccessExpression(r,a.createIdentifier("slice")),void 0,[a.createNumericLiteral(C)])}else w=this.createObjectRestHelper(_,t,r,a);f.push(this.createGlobalAssignment(v,w,a));continue}if(af.isIdentifier(_.name)){let v=_.name.text;c.push(v);let w;if(af.isObjectBindingPattern(t)){let C=_.propertyName&&af.isIdentifier(_.propertyName)?_.propertyName.text:v;w=a.createPropertyAccessExpression(r,a.createIdentifier(C))}else{let C=t.elements.indexOf(_);w=a.createElementAccessExpression(r,a.createNumericLiteral(C))}_.initializer&&(w=a.createConditionalExpression(a.createBinaryExpression(w,a.createToken(af.SyntaxKind.EqualsEqualsEqualsToken),a.createIdentifier("undefined")),a.createToken(af.SyntaxKind.QuestionToken),_.initializer,a.createToken(af.SyntaxKind.ColonToken),w)),f.push(this.createGlobalAssignment(v,w,a))}else if(af.isObjectBindingPattern(_.name)||af.isArrayBindingPattern(_.name)){let v;if(af.isObjectBindingPattern(t)){let C=_.propertyName&&af.isIdentifier(_.propertyName)?_.propertyName.text:null;if(!C)continue;v=a.createPropertyAccessExpression(r,a.createIdentifier(C))}else{let C=t.elements.indexOf(_);v=a.createElementAccessExpression(r,a.createNumericLiteral(C))}_.initializer&&(v=a.createConditionalExpression(a.createBinaryExpression(v,a.createToken(af.SyntaxKind.EqualsEqualsEqualsToken),a.createIdentifier("undefined")),a.createToken(af.SyntaxKind.QuestionToken),_.initializer,a.createToken(af.SyntaxKind.ColonToken),v));let w=this.handleBindingPattern(_.name,v,a,o);c.push(...w.bindingNames),f.push(...w.statements)}}return{bindingNames:c,statements:f}}createObjectRestHelper(t,r,a,o){let c=[];for(let v of r.elements)if(v!==t&&af.isBindingElement(v)&&!v.dotDotDotToken){let w=v.propertyName&&af.isIdentifier(v.propertyName)?v.propertyName.text:af.isIdentifier(v.name)?v.name.text:null;w&&c.push(w)}let f=[];for(let v of c)f.push(o.createBindingElement(void 0,void 0,o.createIdentifier(v),void 0));f.push(o.createBindingElement(o.createToken(af.SyntaxKind.DotDotDotToken),void 0,o.createIdentifier("rest"),void 0));let _=[o.createVariableStatement(void 0,o.createVariableDeclarationList([o.createVariableDeclaration(o.createObjectBindingPattern(f),void 0,void 0,o.createIdentifier("obj"))],af.NodeFlags.Const)),o.createReturnStatement(o.createIdentifier("rest"))];return o.createCallExpression(o.createParenthesizedExpression(o.createArrowFunction(void 0,void 0,[o.createParameterDeclaration(void 0,void 0,o.createIdentifier("obj"),void 0,void 0,void 0)],void 0,o.createToken(af.SyntaxKind.EqualsGreaterThanToken),o.createBlock(_,!0))),void 0,[a])}};e(vXr,"VariableTransformer");var tGt=vXr;MC();var Iqa=e(i=>{globalThis._originalConsole=console,globalThis._consoleOverrideSemaphore=(globalThis._consoleOverrideSemaphore||0)+1,globalThis.console=new Proxy(console,{get(t,r){if(["log","info","warn","error","debug"].includes(r))return(...o)=>{t[r](...o);try{i.evaluate(c=>{window.checksumSendMessage("vtg",{type:"execution-console-event",data:c})},{level:r,args:o.map(c=>{try{return typeof c=="object"?JSON.stringify(c):String(c)}catch{return String(c)}}),timestamp:new Date(new Date().getTime()-new Date().getTimezoneOffset()*6e4).toISOString(),source:"BE",pageId:i._guid}).catch(c=>{})}catch{}};let a=t[r];return typeof a=="function"?a.bind(t):a}})},"consoleOverride");function nci(i,t){return`
1933
1933
  try {
1934
1934
  (${Iqa.toString()})(page);