@checksum-ai/runtime 2.0.8-alpha → 2.0.9-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.
@@ -1917,7 +1917,7 @@ ${JSON.stringify(t,null,2)}
1917
1917
  ${Z_t}`})).join(`
1918
1918
  ${Z_t}`),c=new hHe(r.sourceFile),f=(k=this.userStoryService.getStory())==null?void 0:k.internalTestId,_=(R=this.userStoryService.getStory())==null?void 0:R.goal,b=(B=this.userStoryService.getStory())==null?void 0:B.id;c.transformSourceFile([new oJt(r.sourceFile),new dJt(r.sourceFile,{internalTestId:f,title:_}),new sJt(r.sourceFile,r.testMirrors.filter(U=>U.internalTestId===f||U.storyId===b).map(U=>U.testBody),TXn(o))]);let C=this.testAssetsManager.getSavedTestFilePath(),{error:w}=await c.write(C,Z_t);return{filePath:(0,yHe.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 tht(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:BXn(),userMessage:RXn(r,t)});try{let o=await a.text(),c=JSON.parse(o),f=0;t.forEach((_,b)=>{var w,T;let C=c.map[b];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 pf.error("Failed to merge actions",o),null}}async getReloadTestImportCodeOfNewPackages(t,r,a){let o=new hHe(r);o.transformSourceFile([new oht(t,a,{filterOutChecksumImports:!0,filterOutLocalModules:!0,filterOutTypes:!0,filterSideEffectImports:!0,filterOutNotImportOrRequireStatements:!0}),new rht(t),new uht,new sht]);let c=await this.getDeclaredVariableNames(o.sourceFile);return o.transformSourceFile([new nht(r,c,{filterOutDefinedVariableNames:!0})]),(await o.getFormattedTestFileCode()).code}async getDeclaredVariableNames(t){return new pJt(this.evaluationService).extractDeclaredVariableNames(t)}async getReloadTestEnvironmentCode(){let t=this.testAssetsManager.getSavedTestFilePath(),r=mHe(t),a=IXn(),o=await this.getReloadCodeWithoutPackages(t,r,a);return[await this.getReloadTestImportCodeOfNewPackages(t,r,a),o].join(`
1919
1919
  `)}async getReloadCodeWithoutPackages(t,r,a){let o=new hHe(r);o.transformSourceFile([new fJt({shouldRemoveTestExpression:!0,shouldRemoveTestCalls:!0}),new uJt,new oht(t,a,{filterOutNodeModules:!0,filterOutTypes:!0,filterSideEffectImports:!0,filterOutChecksumImports:!0}),new rht(t),new cJt(t,a,{newRequireIdentifier:"checksumHotRequire",extraImportArguments:[qXn.default.factory.createIdentifier("__filename")]}),new uht,new sht]);let c=await this.getDeclaredVariableNames(o.sourceFile);return o.transformSourceFile([new nht(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,C7e.readFileSync)(t,"utf-8");return JSON.parse(r)}catch(r){return pf.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),t!=null&&t.testFlowDescription&&(o.testFlowDescription=t.testFlowDescription),{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();Gzn(c,a,this.testAssetsManager.getLocalSavePath())}catch(r){throw pf.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,C7e.writeFileSync)(`${r}/${a}`,t),(0,C7e.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,yHe.dirname)(this.testAssetsManager.getSavedTestFilePath()),a=(0,yHe.join)(r,"test.extended.json");return(0,C7e.writeFileSync)(a,JSON.stringify(t,null,2)),{executedActions:t}}async localBackup(t){if(t){this.testAssetsManager.setCurrentSaveAsLocation(t);let r=this.testAssetsManager.getLocalSaveAsPath();Kzn(this.testAssetsManager.getLocalAutoSavePath(),r)}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||Vpt(o.eventCode)),{fullHTML:b,outerHTML:C,parentHTML:w,rrwebSnapshot:T}=o.timestamp?await this.getHTMLsForTimestamp(c,o.locator):{fullHTML:"",outerHTML:"",parentHTML:void 0,rrwebSnapshot:""},k=f?Die.generateSingleAssertionCode(o):Die.generateSingleActionCode(o,{newLineSeparator:`
1920
- ${Z_t}`,generateAssertionsCode:!1}),R=_?await this.takeElementSnapshot(o.locator,c):void 0;return{code:k,fullHTML:b,outerHTML:C,parentHTML:w,timestamp:c,image:R,rrwebSnapshot:T}},"extractDataForStep");for(let o=0;o<t.length;o++){pf.info(`processing action ${o} of ${t.length}`);let c=t[o],f=await a(c);r.push(f);for(let _ of c.assertions||[]){pf.info(`processing assertion of ${c.assertions.length} assertions`);try{let b=await a(_);r.push(b)}catch(b){pf.error("Failed to extract data for assertion",b)}}}return r}async takeElementSnapshot(t,r){try{return`data:image/jpeg;base64,${(await this.taskTimeMachine.executeTask(async o=>(await this.evaluationService.getLocator(`return ${aj(t)}`,o.frameLocator("iframe"))).screenshot({omitBackground:!0,type:"jpeg"}),r)).toString("base64")}`}catch(a){pf.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 ${aj(r)}`,o.frameLocator("iframe")),f=await c.elementHandle(),{fullHTML:_,outerHTML:b,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 LXn(c);return{fullHTML:_,outerHTML:b,parentHTML:w,rrwebSnapshot:C}},t):{fullHTML:"",outerHTML:""}}catch(a){return pf.error("Failed to get HTML data for extended JSON backup",a),{}}}doesFolderExistInSaveDir(t){try{let r=`${this.testAssetsManager.getLocalSavePath()}/${t}`;return(0,C7e.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();if(await this.saveTestFile(),!await this.settingsService.getIsGitReflectionEnabled()){let _=new Lzt(this.apiService.getBaseURL(),this.config.apiKey,null,()=>`test-generation/${r}/get-upload-url`),b=e(T=>({complete:!1,error:!1,response:void 0,info:T}),"buildUploadAsset"),C=[],w=(t=this.userStoryService.getStory())==null?void 0:t.internalTestId;await _.uploadAsset(b({type:"test-fix-files",path:this.testAssetsManager.getSavedTestFilePath(),fileName:`test-${w}.fix.checksum.spec.ts`})),C.push(b({type:"trace",path:this.testAssetsManager.getTraceFilePath()})),C.push(b({type:"har",path:await UXn(this.testAssetsManager.getHarFolderPath())})),this.actionsManager.actions.filter(T=>T.eventCode==="upload_files").forEach(T=>{var k;(k=T.files)==null||k.forEach(R=>{C.push(b({type:"test-files",path:R}))})}),await Promise.all(C)}let o=this.actionsManager.actions.map(_=>({..._,parentFramesSelectors:_.parentFramesSelectors?_.parentFramesSelectors.filter(b=>b!=="iframe"):void 0})),c=this.userStoryService.getStory(),f={};c!=null&&c.version&&(f.version=c.version),c!=null&&c.testFlowDescription&&(f.testFlowDescription=c.testFlowDescription),await this.apiService.post(`test-generation/${r}/completed`,{actions:o,metadata:Object.keys(f).length>0?f:void 0})}catch(r){pf.error("Failed to upload test",r)}}};e(TWr,"VtgStorageService");var mJt=TWr;var kWr=class kWr{constructor(t,r){this.apiService=t;this.config=r}getStory(){return this.story}getTestGenerationData(){return this.userStoryTestGeneration}hasTestGenerationData(){return!!this.userStoryTestGeneration}async fetchStory(t){if(i_.vtg.useFakeStory){this.story={...i_.vtg.fakeStory,id:"fake-story",environment:{name:void 0,userRole:void 0},internalTestId:"fake-internal-test-id"},pf.info("Using fake flow data",this.story);return}if(!t)throw new Error("no story id provided");try{let a=await(await this.apiService.post(`test-generation/info/${t}`)).json();if(!(a!=null&&a.id))throw new Error(`Story ${t} not found`);pf.info("Received flow data:",a);let{id:o,title:c,steps:f,startUrl:_,userRole:b,environment:C,internalTestId:w,version:T,collectionName:k}=a;this.story={id:o,goal:c,instructions:f,url:_,internalTestId:w,environment:{userRole:b,name:C},version:T,testFlowDescription:f,collectionName:k}}catch(r){throw pf.error(`Error fetching story by id ${t}:`,r),new Error(`Couldn't fetch story by id ${t}. Make sure the server is running and the story id is correct. Original error: ${JSON.stringify(r)}`)}}getEnvInfo(){return nVr(this.config,{role:this.story.environment.userRole,environment:this.story.environment.name})}async createTestGeneration(){if(!this.story.id)return;let t=await this.apiService.post(`test-generation/create/${this.story.id}`,{internalTestId:this.story.internalTestId}),{testGenerationId:r}=await t.json();return this.userStoryTestGeneration={testGenerationId:r},this.userStoryTestGeneration}setTestGenerationData(t){this.userStoryTestGeneration=t}};e(kWr,"VtgUserStoryService");var _Jt=kWr;var IWr=class IWr{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:b})=>b===r.id)),_={...o};return f?_.assertions=o.assertions.map(b=>{if(b.id===r.id){let C={...b,...r};return a=C,C}return b}):_.assertions=[...o.assertions??[],r],{..._,assertions:_.assertions.sort((b,C)=>b.timestamp!==C.timestamp?b.timestamp-C.timestamp:b.createdAt-C.createdAt)}}return o}),a}setStorageService(t){this.storageService=t}createAction(t){var b,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=(b=T.action)==null?void 0:b.assertions)!=null&&C.length){let R=T.assertion??T.action.assertions[0],{before:B,after:U}=Cka(((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 f7e(t);return r}async buildStepDataWithCode(t,{loadingFromFile:r}={loadingFromFile:!1}){let a=wka(t);return await Promise.all(a.map(async({step:o,type:c})=>{let f=await SFe(_He([o],void 0,{generateAssertionsCode:!1},(_,b)=>{o=b}));return{type:c,step:{...o,loadedFromFile:r},code:f}}))}};e(IWr,"VtgActionsManager");var hJt=IWr,Cka=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"),wka=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 qWt=kf(kWt()),Gai=kf(require("net")),Kai=kf(pGr()),Yai=kf(Wai());var fKr=class fKr extends Error{constructor(t){super(t),this.name="ValidationError"}};e(fKr,"ValidationError");var zHe=fKr,dKr=class dKr extends Error{constructor(t){super(t),this.name="NotFoundError"}};e(dKr,"NotFoundError");var JHe=dKr;var kv=e(i=>(t,r,a)=>{Promise.resolve(i(t,r,a)).catch(o=>{if(pf.error(`${t.method} ${t.path} error:`,o),o instanceof f7e)return r.status(200).json({error:o.message});if(o instanceof zHe)return r.status(400).send({error:o.message});if(o instanceof JHe)return r.status(404).send(o.message);a(o)})},"asyncErrorHandler");var mKr=kf(kWt());var WHe=class WHe{constructor(){this.routesLogRules={};this.router=(0,mKr.Router)()}getRoutesLogRules(){return this.routesLogRules}getRouter(){return this.router}createPrefixedRouter(t){let r=(0,mKr.Router)(),a=t.startsWith(WHe.DEFAULT_API_PREFIX)?t:`${WHe.DEFAULT_API_PREFIX}${t.startsWith("/")?t:`/${t}`}`;return this.router.use(a,r),r}startAsyncProcess(t,r,a,o="unknown"){pf.info(`Starting async ${o} process: ${r} for step: ${a}`),t().catch(c=>{pf.error(`Async process ${r} failed:`,c)})}};e(WHe,"VTGController"),WHe.DEFAULT_API_PREFIX="/api";var i5=WHe;var _Kr=class _Kr extends i5{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 b=await SFe(_He([_],void 0,{generateAssertionsCode:!1},(C,w)=>{_=w}));return c.status(200).json({step:_,code:b})})),r.patch("/updateStep",kv(async(o,c)=>{let f=o.body,_=f==null?void 0:f.options,b;f.type==="Assertion"&&(b=await this.assertionsService.updateAssertion({id:f.id,data:f.data})),f.type==="Action"&&(b=this.actionsManager.updateExecutedAction({...f.data,id:f.id}));let C;_!=null&&_.forceUpdateTimestamp||(f.data.thought===""&&(b.thought=void 0),C=await SFe(_He([b],void 0,{generateAssertionsCode:!1},(w,T)=>{b=T}))),c.status(200).json({step:b,code:C})})),r.delete("/deleteStep",kv(async(o,c)=>{let{id:f,options:_,type:b}=o.body;return this.actionsManager.deleteStep(f,b,_),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 gMa(f)?_=await this.aiTestGenerationService.executeAction(f):yMa(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 _=PXn(o.body.code).map(b=>b&&"isChecksumAiWithDirectExpression"in b?{...b,isChecksumAiWithDirectExpression:!1}:b);return c.status(200).send(_)})),r.post("/steps-to-code",kv(async(o,c)=>{let f=_He(o.body.steps,void 0,{generateAssertionsCode:!1});return c.status(200).send(f)}))}};e(_Kr,"VtgStepsController");var IWt=_Kr;function gMa(i){var t;return((t=i.options)==null?void 0:t.isAISuggestion)===!0}e(gMa,"isAIExecuteActionArgs");function yMa(i){var t;return((t=i.options)==null?void 0:t.isAISuggestion)===!1}e(yMa,"isManualExecuteActionArgs");var hKr=class hKr extends i5{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:b}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.generateAILocators(f,_,b),b,_.id,"AI locators generation");let C={processId:b,stepId:_.id,success:!0};return c.status(200).json(C)}catch(C){return pf.error("Error generating AI locators:",C),c.status(500).send({processId:b,error:C.message})}})),a.post("/extract-css",kv(async(o,c)=>{let{step:f,target:_,processId:b,llmLocators:C}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.extractCSS(f,_,b,C),b,_.id,"CSS extraction");let w={processId:b,stepId:_.id,success:!0};return c.status(200).json(w)}catch(w){return pf.error("Error extracting CSS locators:",w),c.status(500).send({processId:b,error:w.message})}})),a.post("/filter",kv(async(o,c)=>{let{step:f,target:_,processId:b,candidates:C}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.filterLocators(f,_,b,C),b,_.id,"locators filtering");let w={processId:b,stepId:_.id,success:!0};return c.status(200).json(w)}catch(w){return pf.error("Error filtering locators:",w),c.status(500).send({processId:b,error:w.message})}})),a.delete("/process/:id",kv(async(o,c)=>{let{id:f}=o.params;return await this.locatorsService.cancelProcess(f),pf.info("Cancelled process",f),c.status(200).send({success:!0})})),r.post("/identical",kv(async(o,c)=>{let{locator:f,compareLocator:_,timestamp:b}=o.body;try{let C=await this.locatorsService.verifyAndCompareLocatorOnTimemachine(f,_,b);return c.status(200).send(C)}catch(C){return c.status(400).send({error:C.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(hKr,"VtgLocatorsController");var PWt=hKr;var gKr=class gKr extends i5{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(gKr,"MonacoController");var FWt=gKr;NI();var vMa=Nh.enum(["openai","anthropic","google-vertexai","groq"]),Hai=Nh.strictObject({message:Nh.string(),selection:Nh.object({locator:Nh.string()}).optional(),stepCode:Nh.string().optional(),messageHistory:Nh.array(Nh.object({type:Nh.enum(["user","assistant"]),content:Nh.string(),timestamp:Nh.string(),stepId:Nh.string()})).optional(),model:Nh.object({id:Nh.string(),name:Nh.string(),type:vMa,model:Nh.string(),thinking:Nh.boolean().optional()}).optional(),includeImage:Nh.boolean().optional(),includeHtml:Nh.boolean().optional(),includeCode:Nh.boolean().optional(),timestamp:Nh.number(),error:Nh.string().optional()});var yKr=class yKr extends i5{constructor(r){super();this.aiChatService=r;this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/ai-chat").post("/message",kv(async(a,o)=>{let c=Hai.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(yKr,"AIChatController");var NWt=yKr;var Xai=kf(require("path"));var vKr=class vKr extends i5{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 JHe("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(!Yzn(f))throw pf.error("Invalid folder name",{backupFolderName:f}),new zHe("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(vKr,"VtgStorageController");var OWt=vKr;var bKr=class bKr extends i5{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(bKr,"VtgAITestGenerationController");var BWt=bKr;var xKr=class xKr extends i5{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 b={processId:f,stepId:_,success:!0};o.status(200).send(b)}catch(b){return o.status(400).send({processId:f,error:b.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 b={processId:f,stepId:_,success:!0};o.status(200).send(b)}catch(b){return o.status(400).send({processId:f,error:b.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(xKr,"VtgThoughtsController");var RWt=xKr;var AKr=class AKr extends i5{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:b}=f;try{this.startAsyncProcess(()=>this.aiAssertionsService.generateAiAssertions(f),_,b,"AI assertion generation");let C={processId:_,stepId:b,success:!0};return c.status(200).json(C)}catch(C){return c.status(500).send({processId:_,error:C.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),b=_.success?200:404;return c.status(b).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(AKr,"VtgAssertionsController");var LWt=AKr;var EKr=class EKr extends i5{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(EKr,"VtgSettingsController");var MWt=EKr;var Zai=kf(kWt());var CKr=class CKr extends i5{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(CKr,"VtgEvaluatorController");var jWt=CKr;var wKr=class wKr{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){i_.vtg.logAPIServer.interval&&this.handleIntervalLog(t,r,a),!(i_.vtg.logAPIServer.httpTransactions&&this.handleTransactionLog(t,r,a))&&a()}logInterval(){i_.vtg.logAPIServer.interval&&!this.intervalTimer&&(this.intervalTimer=setInterval(()=>{let t=Object.values(this.reqInProcess);t.length&&(pf.info("HTTP REQUESTS IN PROCESS"),pf.info(t.map(r=>JSON.stringify(r,null,2)).join(`
1920
+ ${Z_t}`,generateAssertionsCode:!1}),R=_?await this.takeElementSnapshot(o.locator,c):void 0;return{code:k,fullHTML:b,outerHTML:C,parentHTML:w,timestamp:c,image:R,rrwebSnapshot:T}},"extractDataForStep");for(let o=0;o<t.length;o++){pf.info(`processing action ${o} of ${t.length}`);let c=t[o],f=await a(c);r.push(f);for(let _ of c.assertions||[]){pf.info(`processing assertion of ${c.assertions.length} assertions`);try{let b=await a(_);r.push(b)}catch(b){pf.error("Failed to extract data for assertion",b)}}}return r}async takeElementSnapshot(t,r){try{return`data:image/jpeg;base64,${(await this.taskTimeMachine.executeTask(async o=>(await this.evaluationService.getLocator(`return ${aj(t)}`,o.frameLocator("iframe"))).screenshot({omitBackground:!0,type:"jpeg"}),r)).toString("base64")}`}catch(a){pf.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 ${aj(r)}`,o.frameLocator("iframe")),f=await c.elementHandle(),{fullHTML:_,outerHTML:b,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 LXn(c);return{fullHTML:_,outerHTML:b,parentHTML:w,rrwebSnapshot:C}},t):{fullHTML:"",outerHTML:""}}catch(a){return pf.error("Failed to get HTML data for extended JSON backup",a),{}}}doesFolderExistInSaveDir(t){try{let r=`${this.testAssetsManager.getLocalSavePath()}/${t}`;return(0,C7e.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 Lzt(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"),b=[],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`})),b.push(_({type:"trace",path:this.testAssetsManager.getTraceFilePath()})),b.push(_({type:"har",path:await UXn(this.testAssetsManager.getHarFolderPath())})),this.actionsManager.actions.filter(w=>w.eventCode==="upload_files").forEach(w=>{var T;(T=w.files)==null||T.forEach(k=>{b.push(_({type:"test-files",path:k}))})}),await Promise.all(b)}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),f!=null&&f.testFlowDescription&&(c.testFlowDescription=f.testFlowDescription)}await this.apiService.post(`test-generation/${r}/completed`,{actions:o,metadata:Object.keys(c).length>0?c:void 0})}catch(r){pf.error("Failed to upload test",r)}}};e(TWr,"VtgStorageService");var mJt=TWr;var kWr=class kWr{constructor(t,r){this.apiService=t;this.config=r}getStory(){return this.story}getTestGenerationData(){return this.userStoryTestGeneration}hasTestGenerationData(){return!!this.userStoryTestGeneration}async fetchStory(t){if(i_.vtg.useFakeStory){this.story={...i_.vtg.fakeStory,id:"fake-story",environment:{name:void 0,userRole:void 0},internalTestId:"fake-internal-test-id"},pf.info("Using fake flow data",this.story);return}if(!t)throw new Error("no story id provided");try{let a=await(await this.apiService.post(`test-generation/info/${t}`)).json();if(!(a!=null&&a.id))throw new Error(`Story ${t} not found`);pf.info("Received flow data:",a);let{id:o,title:c,steps:f,startUrl:_,userRole:b,environment:C,internalTestId:w,version:T,collectionName:k}=a;this.story={id:o,goal:c,instructions:f,url:_,internalTestId:w,environment:{userRole:b,name:C},version:T,testFlowDescription:f,collectionName:k}}catch(r){throw pf.error(`Error fetching story by id ${t}:`,r),new Error(`Couldn't fetch story by id ${t}. Make sure the server is running and the story id is correct. Original error: ${JSON.stringify(r)}`)}}getEnvInfo(){return nVr(this.config,{role:this.story.environment.userRole,environment:this.story.environment.name})}async createTestGeneration(){if(!this.story.id)return;let t=await this.apiService.post(`test-generation/create/${this.story.id}`,{internalTestId:this.story.internalTestId}),{testGenerationId:r}=await t.json();return this.userStoryTestGeneration={testGenerationId:r},this.userStoryTestGeneration}setTestGenerationData(t){this.userStoryTestGeneration=t}};e(kWr,"VtgUserStoryService");var _Jt=kWr;var IWr=class IWr{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:b})=>b===r.id)),_={...o};return f?_.assertions=o.assertions.map(b=>{if(b.id===r.id){let C={...b,...r};return a=C,C}return b}):_.assertions=[...o.assertions??[],r],{..._,assertions:_.assertions.sort((b,C)=>b.timestamp!==C.timestamp?b.timestamp-C.timestamp:b.createdAt-C.createdAt)}}return o}),a}setStorageService(t){this.storageService=t}createAction(t){var b,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=(b=T.action)==null?void 0:b.assertions)!=null&&C.length){let R=T.assertion??T.action.assertions[0],{before:B,after:U}=Cka(((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 f7e(t);return r}async buildStepDataWithCode(t,{loadingFromFile:r}={loadingFromFile:!1}){let a=wka(t);return await Promise.all(a.map(async({step:o,type:c})=>{let f=await SFe(_He([o],void 0,{generateAssertionsCode:!1},(_,b)=>{o=b}));return{type:c,step:{...o,loadedFromFile:r},code:f}}))}};e(IWr,"VtgActionsManager");var hJt=IWr,Cka=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"),wka=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 qWt=kf(kWt()),Gai=kf(require("net")),Kai=kf(pGr()),Yai=kf(Wai());var fKr=class fKr extends Error{constructor(t){super(t),this.name="ValidationError"}};e(fKr,"ValidationError");var zHe=fKr,dKr=class dKr extends Error{constructor(t){super(t),this.name="NotFoundError"}};e(dKr,"NotFoundError");var JHe=dKr;var kv=e(i=>(t,r,a)=>{Promise.resolve(i(t,r,a)).catch(o=>{if(pf.error(`${t.method} ${t.path} error:`,o),o instanceof f7e)return r.status(200).json({error:o.message});if(o instanceof zHe)return r.status(400).send({error:o.message});if(o instanceof JHe)return r.status(404).send(o.message);a(o)})},"asyncErrorHandler");var mKr=kf(kWt());var WHe=class WHe{constructor(){this.routesLogRules={};this.router=(0,mKr.Router)()}getRoutesLogRules(){return this.routesLogRules}getRouter(){return this.router}createPrefixedRouter(t){let r=(0,mKr.Router)(),a=t.startsWith(WHe.DEFAULT_API_PREFIX)?t:`${WHe.DEFAULT_API_PREFIX}${t.startsWith("/")?t:`/${t}`}`;return this.router.use(a,r),r}startAsyncProcess(t,r,a,o="unknown"){pf.info(`Starting async ${o} process: ${r} for step: ${a}`),t().catch(c=>{pf.error(`Async process ${r} failed:`,c)})}};e(WHe,"VTGController"),WHe.DEFAULT_API_PREFIX="/api";var i5=WHe;var _Kr=class _Kr extends i5{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 b=await SFe(_He([_],void 0,{generateAssertionsCode:!1},(C,w)=>{_=w}));return c.status(200).json({step:_,code:b})})),r.patch("/updateStep",kv(async(o,c)=>{let f=o.body,_=f==null?void 0:f.options,b;f.type==="Assertion"&&(b=await this.assertionsService.updateAssertion({id:f.id,data:f.data})),f.type==="Action"&&(b=this.actionsManager.updateExecutedAction({...f.data,id:f.id}));let C;_!=null&&_.forceUpdateTimestamp||(f.data.thought===""&&(b.thought=void 0),C=await SFe(_He([b],void 0,{generateAssertionsCode:!1},(w,T)=>{b=T}))),c.status(200).json({step:b,code:C})})),r.delete("/deleteStep",kv(async(o,c)=>{let{id:f,options:_,type:b}=o.body;return this.actionsManager.deleteStep(f,b,_),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 gMa(f)?_=await this.aiTestGenerationService.executeAction(f):yMa(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 _=PXn(o.body.code).map(b=>b&&"isChecksumAiWithDirectExpression"in b?{...b,isChecksumAiWithDirectExpression:!1}:b);return c.status(200).send(_)})),r.post("/steps-to-code",kv(async(o,c)=>{let f=_He(o.body.steps,void 0,{generateAssertionsCode:!1});return c.status(200).send(f)}))}};e(_Kr,"VtgStepsController");var IWt=_Kr;function gMa(i){var t;return((t=i.options)==null?void 0:t.isAISuggestion)===!0}e(gMa,"isAIExecuteActionArgs");function yMa(i){var t;return((t=i.options)==null?void 0:t.isAISuggestion)===!1}e(yMa,"isManualExecuteActionArgs");var hKr=class hKr extends i5{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:b}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.generateAILocators(f,_,b),b,_.id,"AI locators generation");let C={processId:b,stepId:_.id,success:!0};return c.status(200).json(C)}catch(C){return pf.error("Error generating AI locators:",C),c.status(500).send({processId:b,error:C.message})}})),a.post("/extract-css",kv(async(o,c)=>{let{step:f,target:_,processId:b,llmLocators:C}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.extractCSS(f,_,b,C),b,_.id,"CSS extraction");let w={processId:b,stepId:_.id,success:!0};return c.status(200).json(w)}catch(w){return pf.error("Error extracting CSS locators:",w),c.status(500).send({processId:b,error:w.message})}})),a.post("/filter",kv(async(o,c)=>{let{step:f,target:_,processId:b,candidates:C}=o.body;f.isDefaultThought&&(f.thought=null);try{this.startAsyncProcess(()=>this.locatorsService.filterLocators(f,_,b,C),b,_.id,"locators filtering");let w={processId:b,stepId:_.id,success:!0};return c.status(200).json(w)}catch(w){return pf.error("Error filtering locators:",w),c.status(500).send({processId:b,error:w.message})}})),a.delete("/process/:id",kv(async(o,c)=>{let{id:f}=o.params;return await this.locatorsService.cancelProcess(f),pf.info("Cancelled process",f),c.status(200).send({success:!0})})),r.post("/identical",kv(async(o,c)=>{let{locator:f,compareLocator:_,timestamp:b}=o.body;try{let C=await this.locatorsService.verifyAndCompareLocatorOnTimemachine(f,_,b);return c.status(200).send(C)}catch(C){return c.status(400).send({error:C.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(hKr,"VtgLocatorsController");var PWt=hKr;var gKr=class gKr extends i5{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(gKr,"MonacoController");var FWt=gKr;NI();var vMa=Nh.enum(["openai","anthropic","google-vertexai","groq"]),Hai=Nh.strictObject({message:Nh.string(),selection:Nh.object({locator:Nh.string()}).optional(),stepCode:Nh.string().optional(),messageHistory:Nh.array(Nh.object({type:Nh.enum(["user","assistant"]),content:Nh.string(),timestamp:Nh.string(),stepId:Nh.string()})).optional(),model:Nh.object({id:Nh.string(),name:Nh.string(),type:vMa,model:Nh.string(),thinking:Nh.boolean().optional()}).optional(),includeImage:Nh.boolean().optional(),includeHtml:Nh.boolean().optional(),includeCode:Nh.boolean().optional(),timestamp:Nh.number(),error:Nh.string().optional()});var yKr=class yKr extends i5{constructor(r){super();this.aiChatService=r;this.setupRoutes()}setupRoutes(){this.createPrefixedRouter("/ai-chat").post("/message",kv(async(a,o)=>{let c=Hai.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(yKr,"AIChatController");var NWt=yKr;var Xai=kf(require("path"));var vKr=class vKr extends i5{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 JHe("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(!Yzn(f))throw pf.error("Invalid folder name",{backupFolderName:f}),new zHe("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(vKr,"VtgStorageController");var OWt=vKr;var bKr=class bKr extends i5{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(bKr,"VtgAITestGenerationController");var BWt=bKr;var xKr=class xKr extends i5{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 b={processId:f,stepId:_,success:!0};o.status(200).send(b)}catch(b){return o.status(400).send({processId:f,error:b.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 b={processId:f,stepId:_,success:!0};o.status(200).send(b)}catch(b){return o.status(400).send({processId:f,error:b.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(xKr,"VtgThoughtsController");var RWt=xKr;var AKr=class AKr extends i5{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:b}=f;try{this.startAsyncProcess(()=>this.aiAssertionsService.generateAiAssertions(f),_,b,"AI assertion generation");let C={processId:_,stepId:b,success:!0};return c.status(200).json(C)}catch(C){return c.status(500).send({processId:_,error:C.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),b=_.success?200:404;return c.status(b).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(AKr,"VtgAssertionsController");var LWt=AKr;var EKr=class EKr extends i5{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(EKr,"VtgSettingsController");var MWt=EKr;var Zai=kf(kWt());var CKr=class CKr extends i5{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(CKr,"VtgEvaluatorController");var jWt=CKr;var wKr=class wKr{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){i_.vtg.logAPIServer.interval&&this.handleIntervalLog(t,r,a),!(i_.vtg.logAPIServer.httpTransactions&&this.handleTransactionLog(t,r,a))&&a()}logInterval(){i_.vtg.logAPIServer.interval&&!this.intervalTimer&&(this.intervalTimer=setInterval(()=>{let t=Object.values(this.reqInProcess);t.length&&(pf.info("HTTP REQUESTS IN PROCESS"),pf.info(t.map(r=>JSON.stringify(r,null,2)).join(`
1921
1921
  `)))},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"),_="";pf.info("REQUEST INFO",JSON.stringify(f,null,2));let b=r.write,C=r.end;return r.write=function(w,...T){return w&&(_+=w.toString()),b.call(this,w,...T)},r.end=function(w,...T){return w&&(_+=w.toString()),C.call(this,w,...T)},r.on("finish",()=>{if(i_.vtg.logAPIServer.httpTransactions){let w=Date.now()-c,T=this.buildLogInfo(t,r,w,_,"RESPONSE");pf.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(wKr,"VTGExpressServerRoutesLoggerMiddleware");var UWt=wKr;var SKr=class SKr{constructor(t,r,a,o,c,f,_,b,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=b;this.settingsService=C;this.monacoService=w;this.evaluatorService=T;this.aiChatService=k;this.errorHandler=e((t,r,a,o)=>{pf.error("Error catch in middleware:",t),a.status(500).send({error:t.message})},"errorHandler");this.routesLoggerMiddleware=new UWt}async getPort(){return this.acquirePortNumber()}async start(){return this.app=(0,qWt.default)(),this.app.use((0,Yai.default)()),this.app.use(Kai.default.json({limit:"50mb"})),this.app.use(qWt.default.raw({type:"multipart/form-data",limit:"50mb"})),this.app.use(qWt.default.static(Xai.default.join(i_.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,()=>{pf.info(`Express server running on port ${this.port}`),t()}).on("close",()=>{this.shutdown()})})}shutdown(){this.routesLoggerMiddleware.cleanup(),pf.info("Express server shutdown complete")}async acquirePortNumber(){return this.port||(this.port=await new Promise((t,r)=>{let a=Gai.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 IWt(this.assertionsService,this.actionsManager,this.actionsService,this.aiTestGenerationService),r=new OWt(this.storageService,this.actionsManager,this.actionsService),a=new BWt(this.aiTestGenerationService),o=new RWt(this.aiThoughtsService),c=new LWt(this.assertionsService,this.aiAssertionsService),f=new MWt(this.settingsService),_=new PWt(this.locatorsService),b=new FWt(this.monacoService),C=new NWt(this.aiChatService),w=new jWt(this.evaluatorService),T=[t,r,a,o,c,f,_,b,w,C],k=(0,Zai.Router)(),R={};return T.forEach(B=>{k.use(B.getRouter()),R={...R,...B.getRoutesLogRules()}}),this.routesLoggerMiddleware.setRoutesLogRules(R),k}};e(SKr,"VtgExpressServer");var QWt=SKr;var $Wt=require("fs");var i1t=class i1t{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,$Wt.mkdirSync)(this.assetsFolderPath,{recursive:!0}),(0,$Wt.mkdirSync)(this.getHarFolderPath(),{recursive:!0})}createTestGenerationLocalAutoSaveFolder(){(0,$Wt.mkdirSync)(this.getLocalAutoSavePath(),{recursive:!0})}getAssetsFolderPath(){return this.assetsFolderPath}getLocalAutoSavePath(){return`${this.localSaveFolderPath}/${i1t.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(i1t,"VtgTestAssetsManager"),i1t.AUTO_SAVE_FOLDER_NAME="auto-save";var VWt=i1t;var bMa={useCDPSession:!0,trackLoadedResources:!0},DKr=class DKr extends XVt{constructor(r={},a={devtools:!1},o={},c,f){super({...bMa,...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 b=await this.takePageSnapshot(c);return await this.clearHighlights(),{snapshot:f,bodySnapshot:b}}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,_,b,C])=>{window.checksum.testGenerator.highlightElement(f,{highlightStyle:{outline:_},mousePosition:b,scroll:C})},[await r.elementHandle(),o,a,c])}async clearHighlights(){return this.evaluateWithChecksum(async()=>window.checksum.testGenerator.clearHighlights())}};e(DKr,"ChecksumWebDriver");var zWt=DKr;var esi=require("fs"),tsi=kf(require("path"));var TKr=require("fs");var kKr=class kKr{constructor(t,r,a=i_.vtg.localBuildPath){this.page=t;this.serverPort=r;this.filePath=a;this.filePath=a,pf.info("[VTG] FrontendLauncher initialized with:",{serverPort:r,filePath:a,appSource:i_.vtg.appSource,cwd:process.cwd()})}async start(){try{await this.modifyVTGBuildHtmlFile(),await this.startReactApp()}catch(t){throw pf.error("An error occurred:",t),t}}async startReactApp(){if(!this.page)throw new Error("Page not initialized");let t;switch(i_.vtg.appSource){case"served-app":t=i_.vtg.appURL;break;case"served-build-file":t=`http://localhost:${this.serverPort}/index.html`;break;case"build-file":t=i_.vtg.localUrl;break;default:throw new Error(`Invalid app source: ${i_.vtg.appSource}`)}await this.page.goto(t,{waitUntil:"networkidle",timeout:6e4})}async modifyVTGBuildHtmlFile(){if(i_.vtg.appSource==="build-file")try{let t=await TKr.promises.readFile(this.filePath,"utf8"),r=/(src|href)=(["'])(\/)static/g,a=t.replace(r,"$1=$2.$3static");await TKr.promises.writeFile(this.filePath,a,"utf8"),pf(`Successfully modified ${this.filePath}`)}catch(t){pf.error(`Error processing file ${this.filePath}:`,t)}}};e(kKr,"VtgFrontendLauncher");var JWt=kKr;var xMa=1e3,HWt=class HWt extends zWt{constructor(r={},a={devtools:!1},o={},c){var f;super(r,a,HWt.makeSettings(o),(f=c==null?void 0:c.getFramesMessageBroker)==null?void 0:f.call(c),i_.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,i_.vtg.writeRrwebEventsToFile),this.setEvaluateWithChecksumTargetFrame(this.appFrame)},"onAppFrameCreated");this.timeMachine=new i4e(this.frameMsgBroker,this.injectedScriptManager,{webProxy:r.webProxy}),this.liveTimeMachine=new i4e(this.frameMsgBroker,this.injectedScriptManager,{webProxy:r.webProxy}),this.appViewport=o.viewport,this.completeOriginHeaderOnLivePage=o.completeOriginHeaderOnLivePage}static makeSettings(r={}){return MVt({frontendTestGenerationConfig:{showFrontendLogs:i_.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",()=>{pf.error("Page closed")}),this.liveAppPage&&!i_.vtg.isSeparateProcess&&await(await this.page.context().newCDPSession(this.originalPage)).send("Emulation.setDeviceMetricsOverride",{width:0,height:0,deviceScaleFactor:0,mobile:!1}),await new JWt(this.page,a.serverPort).start();let c=e(async(_=2)=>{if(this.timeMachineFrame=this.page.frames().find(b=>b.name()==="time-machine-iframe"),this.liveFrame=this.page.frames().find(b=>b.name()==="live-iframe"),!this.timeMachineFrame||!this.liveFrame){if(_>0)return pf.info("Waiting for frames to be available"),await FE(xMa),c(_-1);{let b="Could not connect to VTG frontend, check that the app is available";throw pf.error(b),new Error(b)}}},"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)){pf.info("checksumGetFilesFromLive already exposed, skipping");return}await this.page.exposeFunction("checksumGetFilesFromLive",async a=>{let o=this.appFrame;if(!o){pf.info("no live frame detected");return}try{return o.evaluate(c=>window.checksum.testGenerator.filesObserver.getFilesByRrwebId(c),a)}catch(c){pf.error("Error getting frame window",c)}})}catch(r){pf.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 A9e(this.evaluateWithChecksum.bind(this),()=>this.appFrame,()=>this.timeMachine,{log:pf.info,logError:pf.error},{navigationTimeout:3e4,actionTimeout:5e3,waitActionDelay:1e3,testAssetsDir:__dirname}),a=await super.createPage();return $0t.makePage(a,r,this.injectedScriptManager)}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 esi.promises.readFile(o,"utf8")}catch(c){return pf.error(`Error reading file ${o}:`,c),null}}e(r,"readLocalFile");function a(o){switch(tsi.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 b=await o.fetch(),C=b.status();if(C>299&&C<400){f++;let w=b.headers().location;if(!w){pf.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:b,headers:{...b.headers(),...w,"content-security-policy":"","X-Frame-Options":"","x-frame-options":""}});return}}pf.warning(`Max redirects (${_}) exceeded`),await o.abort()}}catch(c){pf.warning("intercept error",c)}})}};e(HWt,"ChecksumVTGWebDriver");var WWt=HWt;var HHe=require("fs");var rsi=".settings.json",IKr=class IKr{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}/${rsi}`:`${this.checksumRoot}/${rsi}`,this.readSettings()}getSettings(){return{...this.settings,autoGenerateAssertions:i_.vtg.aiAssertions.disabled?!1:this.settings.autoGenerateAssertions,disableAutoGenerateAssertions:i_.vtg.aiAssertions.disabled,disableAILocators:i_.vtg.aiLocators.disabled}}updateSettings(t){this.settings=Object.assign(this.settings,t),this.writeSettingsData()}readSettings(){if(!(0,HHe.existsSync)(this.settingsFilePath)){this.writeSettingsData();return}let t=(0,HHe.readFileSync)(this.settingsFilePath,"utf-8");this.settings=JSON.parse(t),this.settings.useCodeBasedSteps===void 0&&(this.settings.useCodeBasedSteps=!0)}writeSettingsData(){(0,HHe.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(IKr,"VtgSettingsService");var a1t=IKr;var i3e=require("fs");var PKr=class PKr{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),b=this.userStoryService.getStory();return this.cachedPromptData={reducedHTML:_,previousReducedHTML:f,actionId:o,previousActions:this.getPreviousActions(o),action:t,title:b.goal,steps:b.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){pf.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(PKr,"ActionsAgent");var GWt=PKr;var FKr=class FKr extends p7e{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 eWe(c,r,a,this.remoteSessionId,{logPerformance:i_.vtg.aiAssertions.logPerformance}),this.actionsAgent=new GWt(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 pf.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 pf.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 pf.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 pf.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){pf.error(`Request for ${r} thought generation failed with status ${f.status}`);return}let _=await f.json();if(!(_!=null&&_.thought))throw pf("No thought generated for action, got response",f),new Error("No thought generated");let b=r==="actions"?a.action:a.assertion;return pf(`Thought generated (${o})`,{type:r,stepId:b.id,locator:b.locator,thought:_.thought}),_}catch(f){throw pf.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:b,processId:C})=>{window.vtg.onAsyncProcessResponse({id:f,processId:C,thought:_,error:b})},{id:r,thought:o,error:c,processId:a})}catch(f){pf.error("Error in AI thought generation",f)}}};e(FKr,"VTGThoughtsService");var KWt=FKr;var AMa=e(()=>{let t=new Error().stack.split(`
1922
1922
  `).find(r=>r.includes(".checksum.spec.ts"));if(t)return{lineNumber:parseInt(t.split(":")[1]),columnNumber:parseInt(t.split(":")[2])}},"findCodeLocationFromStackTrace"),NKr=class NKr{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=AMa();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(NKr,"VariableStore");var YWt=NKr;var OKr=class OKr{constructor(t=new YWt){this._variableStore=t}get variableStore(){return this._variableStore}};e(OKr,"VTGVariableStoreService");var XWt=OKr;var GHe=kf(I8()),isi=require("net"),asi=require("crypto");var BKr=class BKr{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 b=JSON.parse(_);await this.processMessage(b,t)}catch(b){console.error("Failed to parse message:",b)}}}};e(BKr,"VtgBridgeMessageParser");var ZWt=BKr;var af=kf(I8());var RKr=class RKr{constructor(){this.declaredVariables=new Set}transformVariables(t){let r=af.createSourceFile("snippet.ts",t,af.ScriptTarget.Latest,!0),a=new Set;af.forEachChild(r,b=>{af.isVariableStatement(b)&&b.declarationList.declarations.forEach(C=>{af.isIdentifier(C.name)?(a.add(C.name.text),this.declaredVariables.add(C.name.text)):(af.isArrayBindingPattern(C.name)||af.isObjectBindingPattern(C.name))&&(this.collectBindingNames(C.name,a),this.collectBindingNames(C.name,this.declaredVariables))})});let c=af.transform(r,[e(b=>{let C=b.factory,w=[new Map],T=e(B=>w[w.length-1].has(B),"isVariableLocallyDeclared"),k=new Set,R=e(B=>{if(af.isBlock(B)||af.isFunctionLike(B)){if(w.push(new Map),af.forEachChild(B,W=>{if(af.isVariableStatement(W))for(let X of W.declarationList.declarations)af.isIdentifier(X.name)?w[w.length-1].set(X.name.text,X):(af.isArrayBindingPattern(X.name)||af.isObjectBindingPattern(X.name))&&this.collectBindingNamesForScope(X.name,w[w.length-1])}),af.isFunctionLike(B))for(let W of B.parameters)af.isIdentifier(W.name)?(w[w.length-1].set(W.name.text,W),k.add(W.name.text)):(af.isArrayBindingPattern(W.name)||af.isObjectBindingPattern(W.name))&&this.collectBindingNamesForScope(W.name,w[w.length-1]);let U=af.visitEachChild(B,R,b);return w.pop(),U}if(af.isArrowFunction(B))for(let U of B.parameters)af.isIdentifier(U.name)?(w[w.length-1].set(U.name.text,U),k.add(U.name.text)):(af.isArrayBindingPattern(U.name)||af.isObjectBindingPattern(U.name))&&this.collectBindingNamesForScope(U.name,w[w.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 C.createBinaryExpression(U,B.operatorToken,W)}if(af.isVariableDeclaration(B)&&B.initializer){let U=af.visitNode(B.initializer,R);return C.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,C,b);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,C);W.push(fe)}return W.length===0?C.createEmptyStatement():W.length===1?W[0]:C.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 w[w.length-1].has(U)||this.isInShadowingTestCase(B)?B:this.createGlobalThisAccess(U,b)}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 C.createAssignment(this.createGlobalThisAccess(U,b),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,b);return C.createPropertyAccessExpression(X,W)}return af.visitEachChild(B,R,b)},"visit");return B=>af.isSourceFile(B)?af.visitEachChild(B,R,b):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(b=>a.includes(b)))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 b=_.pop(),{pattern:C,parent:w}=b;for(let T of C.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(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&&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,[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(af.isIdentifier(T.name)){let k=T.name.text;c.add(k),this.declaredVariables.add(k);let R;if(af.isObjectBindingPattern(C)){let U=T.propertyName&&af.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(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(C)){let R=T.propertyName&&af.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(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(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(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 b=_.name.text;c.push(b);let C;if(af.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(b,C,a));continue}if(af.isIdentifier(_.name)){let b=_.name.text;c.push(b);let C;if(af.isObjectBindingPattern(t)){let w=_.propertyName&&af.isIdentifier(_.propertyName)?_.propertyName.text:b;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(af.SyntaxKind.EqualsEqualsEqualsToken),a.createIdentifier("undefined")),a.createToken(af.SyntaxKind.QuestionToken),_.initializer,a.createToken(af.SyntaxKind.ColonToken),C)),f.push(this.createGlobalAssignment(b,C,a))}else if(af.isObjectBindingPattern(_.name)||af.isArrayBindingPattern(_.name)){let b;if(af.isObjectBindingPattern(t)){let w=_.propertyName&&af.isIdentifier(_.propertyName)?_.propertyName.text:null;if(!w)continue;b=a.createPropertyAccessExpression(r,a.createIdentifier(w))}else{let w=t.elements.indexOf(_);b=a.createElementAccessExpression(r,a.createNumericLiteral(w))}_.initializer&&(b=a.createConditionalExpression(a.createBinaryExpression(b,a.createToken(af.SyntaxKind.EqualsEqualsEqualsToken),a.createIdentifier("undefined")),a.createToken(af.SyntaxKind.QuestionToken),_.initializer,a.createToken(af.SyntaxKind.ColonToken),b));let C=this.handleBindingPattern(_.name,b,a,o);c.push(...C.bindingNames),f.push(...C.statements)}}return{bindingNames:c,statements:f}}createObjectRestHelper(t,r,a,o){let c=[];for(let b of r.elements)if(b!==t&&af.isBindingElement(b)&&!b.dotDotDotToken){let C=b.propertyName&&af.isIdentifier(b.propertyName)?b.propertyName.text:af.isIdentifier(b.name)?b.name.text:null;C&&c.push(C)}let f=[];for(let b of c)f.push(o.createBindingElement(void 0,void 0,o.createIdentifier(b),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(RKr,"VariableTransformer");var eHt=RKr;var EMa=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 nsi(i,t){return`
1923
1923
  try {
@@ -2030,7 +2030,7 @@ Supported model providers are: ${f}`)}}}catch(f){if("code"in f&&f.code.includes(
2030
2030
  `)}),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()}
2031
2031
  `)}}),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(),b=((w=r.page())==null?void 0:w.url())||"unknown",C=`[${_}] [${c.toUpperCase()}] [${b}] ${o}`;f&&(C+=`
2032
2032
  at ${f.url}:${f.lineNumber}:${f.columnNumber}`),a.write(C+`
2033
- `)}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){pf.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 i4e(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!i_.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0,taskTimeout:i_.vtg.taskTimeMachine.taskTimeout,debugPort:i_.vtg.isSeparateProcess?i_.vtg.taskTimeMachine.debugPort:void 0,frameMsgBrokerRegisterName:"task-time-machine",logPerformance:i_.vtg.taskTimeMachine.logPerformance,webProxy:this.getPlaywrightProxySettings()}),this.pageInteractor=new A9e(this.webDriver.evaluateWithChecksum.bind(this.webDriver),()=>this.webDriver.appMainFrame,this.webDriver.getTimeMachine.bind(this.webDriver),{log:e((a,...o)=>o!=null&&o.length?pf.info(a,...o):pf.info(a),"log"),logError:e((a,...o)=>o!=null&&o.length?pf.error(a,...o):pf.error(a),"logError")},{...this.getTimeoutParams(),waitActionDelay:1e3,testAssetsDir:__dirname,listenToDialog:!0,listenToFileChooser:!1},new O0t(this.checksumConfig)),this.testAssetsManager=new VWt(this.projectRootDirectory,this.checksumRoot,this.vtgInternalFilesDir,this.vtgTestFileRunConfig)}buildServices(r){this.actionsManager=new hJt,this.settingsService=new a1t(this.checksumRoot,this.apiService,this.vtgInternalFilesDir),this.apiService=new WVt(this.checksumConfig),this.settingsService=new a1t(this.checksumRoot,this.apiService),this.userStoryService=new _Jt(this.apiService,this.checksumConfig),this.variableStoreService=new XWt,this.evaluatorService=new tHt(this.variableStoreService,this.settingsService,this.vtgTestFileMode,r,this.port),this.actionsService=new $Vt(this.checksumConfig,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver,this.evaluatorService,this.vtgInternalFilesDir),this.assertionsService=new tzt(this.webDriver,this.actionsManager,this.evaluatorService),this.locatorsService=new pzt(this.webDriver,this.taskTimeMachine,this.apiService,this.userStoryService,this.evaluatorService),this.aiTestGenerationService=new zVt(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new ezt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver,this.evaluatorService,{logPerformance:i_.vtg.aiAssertions.logPerformance}),this.aiThoughtsService=new KWt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new mJt(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 nHt,this.aiChatService=new Her(this.taskTimeMachine,this.evaluatorService)}buildServer(){this.reactAppServer=new QWt(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,i3e.existsSync)(r)){let a=require(r).default;a&&(this.playwrightConfigForVTG=a)}}catch{pf.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,story:c,testGenerationData:f}=a,_=await fetch(o,{mode:"cors",credentials:"same-origin",headers:{"Content-Type":"application/json"}});if(!_.ok)throw new Error(`HTTP error! Status: ${_.status}`);let b=await _.json();return{actions:this.initializeTestStepsWithIds(b),storyId:a.story.id}}initializeTestStepsWithIds(r){return r.map((a,o)=>({...a,id:(0,hmn.randomUUID)(),assertions:(a.assertions??[]).map(c=>({...c,id:(0,hmn.randomUUID)()}))}))}async getInitialServicesDataForEditedFile(){var a,o,c,f,_,b,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,i3e.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)throw new Error(`Error fetching test generation data: ${w.statusText}`);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{pf.warning(`Could not find data matching internal test id: ${(_=this.vtgTestFileRunConfig)==null?void 0:_.internalTestId}`)}if((b=this.vtgTestFileRunConfig)!=null&&b.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()}),i_.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()),pf.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:b,userStoryGoal:C,isLoadedFromFile:w})=>{window.vtg.initClient(f,_,b,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,_,b,C,w;let a=this.getPlaywrightProxySettings(),o=this.getPlaywrightViewportSettings();return new WWt({scriptSource:i_.checksumScript.source,scriptURL:i_.checksumScript.url,scriptFile:i_.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:i_.vtg.remoteDebugging,remoteDebuggingPort:i_.vtg.vtgRemoteDebuggingPort},{devtools:!1,headless:i_.CI},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"},viewport:o,completeOriginHeaderOnLivePage:!i_.vtg.isSeparateProcess&&!((b=(_=(f=this.checksumConfig.options)==null?void 0:f.modelConfig)==null?void 0:_.browserArgs)!=null&&b.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,i3e.rmSync)((a=this.vtgTestFileRunConfig)==null?void 0:a.evalFilePath,{force:!0}),this.vtgTestFileRunConfig.mode==="edit"&&(0,i3e.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(gmn,"VisualTestGenerator");var Ger=gmn;var Svi=kf(DVr());var ymn=e(async(i,t,r,a,o={})=>{let{preventDialogFromAutoDismissing:c=!1,retry:f=!0,maxRetries:_=void 0,numberOfRetries:b=0}=o;try{console.log(`${i} attempting to connect to ${t} on port ${r}...`);let w=(await Svi.chromium.connectOverCDP("http://127.0.0.1:"+r)).contexts()[0],T=a(w.pages());for(;!T;)await FE(1e3),T=a(w.pages());return console.log(`${i} is connected to ${t} on port ${r}`,T.url()),c&&tVr(T),T}catch(C){if(!f||_&&b>=_)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 FE(1e3),ymn(i,t,r,a,{...o,numberOfRetries:b+1})}},"connectToPage");(async()=>{pf.info("[VTG PW Bridge Runner] Started.");let i=new Ger(["--test-file"],!1,JSON.parse(process.env.CHECKSUM_CONFIG),parseInt(process.env.CHECKSUM_PORT)),t=i_.vtg.appRemoteDebuggingPort,r=await ymn("VTG via Bridge","Live App Page",t,a=>a[0],{preventDialogFromAutoDismissing:!0});pf.info("[VTG PW Bridge Runner] Running VTG..."),await i.run(r)})();
2033
+ `)}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){pf.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 i4e(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!i_.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0,taskTimeout:i_.vtg.taskTimeMachine.taskTimeout,debugPort:i_.vtg.isSeparateProcess?i_.vtg.taskTimeMachine.debugPort:void 0,frameMsgBrokerRegisterName:"task-time-machine",logPerformance:i_.vtg.taskTimeMachine.logPerformance,webProxy:this.getPlaywrightProxySettings()}),this.pageInteractor=new A9e(this.webDriver.evaluateWithChecksum.bind(this.webDriver),()=>this.webDriver.appMainFrame,this.webDriver.getTimeMachine.bind(this.webDriver),{log:e((a,...o)=>o!=null&&o.length?pf.info(a,...o):pf.info(a),"log"),logError:e((a,...o)=>o!=null&&o.length?pf.error(a,...o):pf.error(a),"logError")},{...this.getTimeoutParams(),waitActionDelay:1e3,testAssetsDir:__dirname,listenToDialog:!0,listenToFileChooser:!1},new O0t(this.checksumConfig)),this.testAssetsManager=new VWt(this.projectRootDirectory,this.checksumRoot,this.vtgInternalFilesDir,this.vtgTestFileRunConfig)}buildServices(r){this.actionsManager=new hJt,this.settingsService=new a1t(this.checksumRoot,this.apiService,this.vtgInternalFilesDir),this.apiService=new WVt(this.checksumConfig),this.settingsService=new a1t(this.checksumRoot,this.apiService),this.userStoryService=new _Jt(this.apiService,this.checksumConfig),this.variableStoreService=new XWt,this.evaluatorService=new tHt(this.variableStoreService,this.settingsService,this.vtgTestFileMode,r,this.port),this.actionsService=new $Vt(this.checksumConfig,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver,this.evaluatorService,this.vtgInternalFilesDir),this.assertionsService=new tzt(this.webDriver,this.actionsManager,this.evaluatorService),this.locatorsService=new pzt(this.webDriver,this.taskTimeMachine,this.apiService,this.userStoryService,this.evaluatorService),this.aiTestGenerationService=new zVt(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new ezt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver,this.evaluatorService,{logPerformance:i_.vtg.aiAssertions.logPerformance}),this.aiThoughtsService=new KWt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new mJt(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 nHt,this.aiChatService=new Her(this.taskTimeMachine,this.evaluatorService)}buildServer(){this.reactAppServer=new QWt(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,i3e.existsSync)(r)){let a=require(r).default;a&&(this.playwrightConfigForVTG=a)}}catch{pf.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,hmn.randomUUID)(),assertions:(a.assertions??[]).map(c=>({...c,id:(0,hmn.randomUUID)()}))}))}async getInitialServicesDataForEditedFile(){var a,o,c,f,_,b,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,i3e.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)throw new Error(`Error fetching test generation data: ${w.statusText}`);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{pf.warning(`Could not find data matching internal test id: ${(_=this.vtgTestFileRunConfig)==null?void 0:_.internalTestId}`)}if((b=this.vtgTestFileRunConfig)!=null&&b.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()}),i_.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()),pf.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:b,userStoryGoal:C,isLoadedFromFile:w})=>{window.vtg.initClient(f,_,b,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,_,b,C,w;let a=this.getPlaywrightProxySettings(),o=this.getPlaywrightViewportSettings();return new WWt({scriptSource:i_.checksumScript.source,scriptURL:i_.checksumScript.url,scriptFile:i_.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:i_.vtg.remoteDebugging,remoteDebuggingPort:i_.vtg.vtgRemoteDebuggingPort},{devtools:!1,headless:i_.CI},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"},viewport:o,completeOriginHeaderOnLivePage:!i_.vtg.isSeparateProcess&&!((b=(_=(f=this.checksumConfig.options)==null?void 0:f.modelConfig)==null?void 0:_.browserArgs)!=null&&b.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,i3e.rmSync)((a=this.vtgTestFileRunConfig)==null?void 0:a.evalFilePath,{force:!0}),this.vtgTestFileRunConfig.mode==="edit"&&(0,i3e.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(gmn,"VisualTestGenerator");var Ger=gmn;var Svi=kf(DVr());var ymn=e(async(i,t,r,a,o={})=>{let{preventDialogFromAutoDismissing:c=!1,retry:f=!0,maxRetries:_=void 0,numberOfRetries:b=0}=o;try{console.log(`${i} attempting to connect to ${t} on port ${r}...`);let w=(await Svi.chromium.connectOverCDP("http://127.0.0.1:"+r)).contexts()[0],T=a(w.pages());for(;!T;)await FE(1e3),T=a(w.pages());return console.log(`${i} is connected to ${t} on port ${r}`,T.url()),c&&tVr(T),T}catch(C){if(!f||_&&b>=_)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 FE(1e3),ymn(i,t,r,a,{...o,numberOfRetries:b+1})}},"connectToPage");(async()=>{pf.info("[VTG PW Bridge Runner] Started.");let i=new Ger(["--test-file"],!1,JSON.parse(process.env.CHECKSUM_CONFIG),parseInt(process.env.CHECKSUM_PORT)),t=i_.vtg.appRemoteDebuggingPort,r=await ymn("VTG via Bridge","Live App Page",t,a=>a[0],{preventDialogFromAutoDismissing:!0});pf.info("[VTG PW Bridge Runner] Running VTG..."),await i.run(r)})();
2034
2034
  /*! Bundled license information:
2035
2035
 
2036
2036
  undici/lib/web/fetch/body.js: