@checksum-ai/runtime 2.0.17 → 2.0.18-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env +1 -1
- package/cli.js +1 -1
- package/index.js +2 -2
- package/package.json +1 -1
- package/vtg-pw-bridge-runner.js +1 -1
package/.env
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
CHECKSUM_RUNTIME_BUILD_TIME=2026-
|
|
1
|
+
CHECKSUM_RUNTIME_BUILD_TIME=2026-02-23T23:39:15.639Z
|
package/cli.js
CHANGED
|
@@ -611,7 +611,7 @@ Result: ${JSON.stringify(S)}`);else T=S;let N;qSe(r)&&(N=r.id),!N&&Jin(m)&&(N=m.
|
|
|
611
611
|
|
|
612
612
|
`),f=`Available pages (${s.length}):
|
|
613
613
|
|
|
614
|
-
${l}`;return{success:!0,pages:s,message:f}}async switchPageHandler(a){if(!a.pageId)return{success:!1,message:"pageId is required"};a.thought&&this.utils.createChecksumStep({title:a.thought});try{await this.utils.setActivePage(a.pageId);let s=await this.utils.captureApplicationState();return{success:!0,message:`Successfully switched to page ${a.pageId}`,appState:s}}catch(s){let l=s instanceof Error?s.message:String(s);return{success:!1,message:`Failed to switch to page ${a.pageId}: ${l}`}}}};e(uTt,"AutoRecoveryAgent");cTt=uTt});var z6r,lTt,bln=ss(()=>{"use strict";lmr();yOe();z6r=class z6r{constructor(r,a){this.sessionId=null;if(!Cpe.getCurrentTestInfo())throw new Error("TestRunAnalytics must be initialized with testInfo before RecoveryAnalytics can be used");let l=Cpe.getCurrentInstance();if(!l)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating RecoveryAnalytics");let f=l.getTestSuiteRunInfo();this.analytics=Qee.createFromConfig(f,Cpe.isolatedMode,!0),this.fallbackId=r,this.fallbackType=a}updateToSessionId(r){this.sessionId!==r&&(this.sessionId=r)}get tableName(){return"fallbacks"}get metadata(){return{...this.analytics.metadata,fallbackType:this.fallbackType,sessionId:this.sessionId||"unknown",fallbackId:this.fallbackId}}event(r){this.analytics.trackEventWithTable(r,this.metadata,this.tableName)}setFallbackType(r){this.fallbackType=r}aiFallbackStart(r){this.event({event:"AI Fallback Start",metadata:this.metadata,...r})}aiFallbackConfig(r){this.event({event:"AI Fallback Config",metadata:this.metadata,...r})}aiFallbackIterationResponse(r){this.event({event:"AI Fallback Iteration Response",metadata:this.metadata,...r})}aiFallbackAssertion(r){this.event({event:"AI Fallback Assertion Execution",metadata:this.metadata,...r})}aiFallbackChangeVariable(r){this.event({event:"AI Fallback Change Variable",metadata:this.metadata,...r})}aiFallbackSummary(r){this.event({event:"AI Fallback Summary",metadata:this.metadata,fallbackType:this.fallbackType,...r})}aiFallbackActionExecution(r){this.event({event:"AI Fallback Action Execution",metadata:this.metadata,...r})}aiFallbackActionExecutionFailure(r){this.event({event:"AI Fallback Action Execution Failure",metadata:this.metadata,...r})}aiFallbackEnd(r){this.event({event:"AI Fallback End",metadata:this.metadata,...r})}ARStart(){this.event({event:"Auto-Recovery Start",metadata:this.metadata})}ARConfig(r){this.event({event:"Auto-Recovery Config",metadata:this.metadata,...r})}ARGetState(r){this.event({event:"Auto-Recovery State",metadata:this.metadata,thought:r})}ARInvokeCode(r,a){this.event({event:"Auto-Recovery Invoke Code",metadata:this.metadata,thought:r,code:a})}ARFinalResult(r){this.event({event:"Auto-Recovery Final Result",metadata:this.metadata,...r})}autoRecoveryDisconnect(r){this.event({event:"Auto-Recovery Disconnect",metadata:this.metadata,...r})}ARFinish(r){this.event({event:"Auto-Recovery Finish",metadata:this.metadata,...r})}ARError(r){this.event({event:"Auto-Recovery Error",metadata:this.metadata,...r})}};e(z6r,"RecoveryAnalytics");lTt=z6r});var Eln=ss(()=>{"use strict"});function W6r(i){return i._guid}var Cln,Dln,dwe,pTt,Sln=ss(()=>{"use strict";Npr();Cln=require("fs"),Dln=Td(require("path"));bln();Eln();e(W6r,"getPageGuid");dwe=class dwe{constructor({page:r,evaluateWithChecksum:a,checksumPage:s,pageInteractor:l,arConfig:f,sessionId:m,runtimeFallbackData:A,fallbackData:E,variableStore:S,runtimePage:T,context:O}){this.reducedHtmlTimeoutMs=3e4;this.page=r,this.evaluateWithChecksum=a,this.checksumPage=s,this._pageInteractor=l,this.arConfig=f,this.sessionId=m,this.runtimeFallbackData=A,this.fallbackData=E,this.variableStore=S,this.runtimePage=T,this.context=O,this._activePageGuid=W6r(this.page),this._analytics=new lTt(this.sessionId,E.type)}get activePageGuid(){return this._activePageGuid}static async start(r){return new dwe({...r})}async getPageById(r){return(this.context||this.page.context()).pages().find(l=>W6r(l)===r)}async setActivePage(r){let a=await this.getPageById(r);if(!a||a.isClosed())throw new Error(`Page with ID ${r} is closed or not found`);this.page=a,this._activePageGuid=r}getMatcherResultFileData(r){let a=r.matcherResult;if((a==null?void 0:a.name)!=="toHaveScreenshot")return;let s=e((A,E=!0)=>{if(!A)return"";try{return(0,Cln.readFileSync)(A,E?"base64":"utf-8")}catch{return""}},"readFileSafe"),l=s(a==null?void 0:a.actual),f=s(a==null?void 0:a.diff),m=s(a==null?void 0:a.expected);if(!m)throw new Error("No expected file found for 'toHaveScreenshot'");return{...a,actual:l,diff:f,expected:m}}async getSelectionDataForChecksumId(r){return await this.evaluateWithChecksum(async s=>{let{selector:l,locator:f,clickOffset:m,parentFramesSelectors:A,invalid:E,rrwebId:S}=await window.checksum.testGenerator.getSelectorForChecksumId(s),T=await window.checksum.testGenerator.getElementForChecksumId(s),O=T instanceof HTMLOptionElement&&T.value?T.value:void 0;return{selector:l,locator:f,clickOffset:m,selectOptionValue:O,parentFramesSelectors:A,invalid:E,rrwebId:S}},r)}async getReducedHtml(r=dwe.currentChecksumId){if(this._pageInteractor.getCurrentURL()==="about:blank")return{reducedHTML:"Error: Page is about:blank. Cannot get reduced HTML - either wait or navigate to a valid page before continuing.",currentChecksumId:r};let{reducedHTML:a,currentChecksumId:s}=await this._pageInteractor.getCurrentReducedHTML({stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:r});return dwe.currentChecksumId=s,{reducedHTML:a,currentChecksumId:s}}async getApplicationState(){let{reducedHTML:r}=await this.getReducedHtml();return{reducedHTML:r,screenshot:await this.getPageScreenshot()}}async capturePageState(r,a){let s=this.page,l=this._activePageGuid;try{this.page=r,this._activePageGuid=a;let{reducedHTML:f}=await this.getReducedHtml(),m=await this.getPageScreenshot();return{pageId:a,reducedHTML:f,screenshot:m,url:r.url()}}finally{this.page=s,this._activePageGuid=l}}async captureAllPagesState(){let a=(this.context||this.page.context()).pages(),s=[],l=[];for(let m of a){if(m.isClosed())continue;let A=W6r(m);try{let E=await this.capturePageState(m,A);s.push(E)}catch(E){let S=E instanceof Error?E.message:String(E);l.push({pageId:A,url:m.url(),error:S}),console.warn(`Failed to capture state for page ${A} (${m.url()}):`,E)}}let f={pages:s};return l.length>0&&(f.failures=l),f}async captureApplicationState(r,a){if(a)return await this.captureAllPagesState();if(r&&r!==this._activePageGuid){let s=await this.getPageById(r);if(!s||s.isClosed())throw new Error(`Page with ID ${r} is closed or not found`);let l=await this.capturePageState(s,r);return{reducedHTML:l.reducedHTML,screenshot:l.screenshot}}else return await this.getApplicationState()}async buildFallbackData(){let a=(this.context||this.page.context()).pages().filter(m=>!m.isClosed()).length,s=new Promise((m,A)=>setTimeout(()=>A(new Error(`getReducedHtml timeout after ${this.reducedHtmlTimeoutMs/1e3} seconds`)),this.reducedHtmlTimeoutMs)),{reducedHTML:l,currentChecksumId:f}=await Promise.race([this.getReducedHtml(),s]);return{storyInfo:this.runtimeFallbackData.storyInfo,testIdentification:this.runtimeFallbackData.testIdentification,fallbackConfig:this.runtimeFallbackData.fallbackConfig,thoughts:this.runtimeFallbackData.thoughts,errorData:{error:{name:this.fallbackData.error.name,message:this.fallbackData.error.message,stack:this.fallbackData.error.stack},errorFileContent:await this.getErrorFileContent(this.fallbackData.error)},applicationState:{reducedHTML:l,screenshot:await this.getPageScreenshot()},stepData:{matcher:this.getMatcherResultFileData(this.fallbackData.error)},currentChecksumId:f,failingStepThought:this.runtimeFallbackData.thoughts.failing,type:this.fallbackData.type,config:this.runtimeFallbackData.config,sessionId:this.sessionId,variableStore:this.variableStore.reduce((m,A)=>(m[`variablesStore.${A.name}`]=A.value,m),{}),arConfig:this.arConfig,multiPageContext:{pageCount:a,hasMultiplePages:a>1}}}async scrollToElement(r){r&&await this._pageInteractor.scrollElementIntoViewByChecksumId(r)}async getPageScreenshot(r=this.arConfig){try{return this.checksumPage.wrapInternalSteps(async()=>{var s;return(await this.page.screenshot({fullPage:!0,type:((s=r.modelConfig)==null?void 0:s.provider)==="anthropic"?"jpeg":"png"})).toString("base64")})}catch{return}}async getErrorFileContent(r){try{let a=Dln.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return RNe.toRecord(r,a)}catch{throw new Error("Error while getting error file content for AI fallback")}}async wait(){await this.page.waitForTimeout(5e3)}async preprocessCode(r){var q;let a=r,s=r,l=[],f=r.match(/getByChecksumId\([^)]+\)\.([a-zA-Z]+)\(([^)]*)\)/),m=f==null?void 0:f[1],A=f==null?void 0:f[2],E=/(?:page\.)?getByChecksumId\(['"]([^'"]+)['"]\)/,S=(q=r.match(E))==null?void 0:q[1];if(!S)throw new Error("Checksum ID not found in the code");let T=await this.getSelectionDataForChecksumId(S);if(!(T!=null&&T.locator)||T.invalid)throw new Error(`Locator or selector not found for checksumId: ${S}`);s=s.replace(E,T.locator);let O=/variables?Store\.([a-zA-Z_$][a-zA-Z0-9_$]*)/g,N=null;for(;(N=O.exec(r))!==null;){let Q=N[1],z=this.variableStore.find(se=>se.name===Q);z&&(l.push(z),s=s.replace(N[0],`"${z.value}"`))}return{originalCode:a,modifiedCode:s,usedVariables:l,checksumId:S,locator:T.locator,method:m,methodArgs:A}}async invokeCode(r){try{let a=await this.preprocessCode(r),{modifiedCode:s}=a,l=new Function("page",`return (async () => { return page.${s}; })()`),f;return await this.step(s,async()=>f=await l(this.page),!1,{box:!0,noLocation:!0,obtainStep:e(m=>{this.checksumPage.addAutoRecoveryStepId(m.stepId)},"obtainStep")}),{success:!0,result:f}}catch(a){throw console.log("Error while invoking code",a.message),a}}addAutoRecoveryErrorToReport(r,a){let s=this.runtimeFallbackData.thoughts.failing,l=a?`\u2705 "${s}" auto-recovered`:`\u274C "${s}" failed`;this.checksumPage.addPwAnnotation({type:l,description:r.replace(/^"(.*)"$/,"$1")}),a&&this.checksumPage.addErrorMessage(this.fallbackData.error,`${l}:
|
|
614
|
+
${l}`;return{success:!0,pages:s,message:f}}async switchPageHandler(a){if(!a.pageId)return{success:!1,message:"pageId is required"};a.thought&&this.utils.createChecksumStep({title:a.thought});try{await this.utils.setActivePage(a.pageId);let s=await this.utils.captureApplicationState();return{success:!0,activePageId:a.pageId,message:`Successfully switched to page ${a.pageId}`,appState:s}}catch(s){let l=s instanceof Error?s.message:String(s);return{success:!1,activePageId:this.utils.activePageGuid,message:`Failed to switch to page ${a.pageId}: ${l}`}}}};e(uTt,"AutoRecoveryAgent");cTt=uTt});var z6r,lTt,bln=ss(()=>{"use strict";lmr();yOe();z6r=class z6r{constructor(r,a){this.sessionId=null;if(!Cpe.getCurrentTestInfo())throw new Error("TestRunAnalytics must be initialized with testInfo before RecoveryAnalytics can be used");let l=Cpe.getCurrentInstance();if(!l)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating RecoveryAnalytics");let f=l.getTestSuiteRunInfo();this.analytics=Qee.createFromConfig(f,Cpe.isolatedMode,!0),this.fallbackId=r,this.fallbackType=a}updateToSessionId(r){this.sessionId!==r&&(this.sessionId=r)}get tableName(){return"fallbacks"}get metadata(){return{...this.analytics.metadata,fallbackType:this.fallbackType,sessionId:this.sessionId||"unknown",fallbackId:this.fallbackId}}event(r){this.analytics.trackEventWithTable(r,this.metadata,this.tableName)}setFallbackType(r){this.fallbackType=r}aiFallbackStart(r){this.event({event:"AI Fallback Start",metadata:this.metadata,...r})}aiFallbackConfig(r){this.event({event:"AI Fallback Config",metadata:this.metadata,...r})}aiFallbackIterationResponse(r){this.event({event:"AI Fallback Iteration Response",metadata:this.metadata,...r})}aiFallbackAssertion(r){this.event({event:"AI Fallback Assertion Execution",metadata:this.metadata,...r})}aiFallbackChangeVariable(r){this.event({event:"AI Fallback Change Variable",metadata:this.metadata,...r})}aiFallbackSummary(r){this.event({event:"AI Fallback Summary",metadata:this.metadata,fallbackType:this.fallbackType,...r})}aiFallbackActionExecution(r){this.event({event:"AI Fallback Action Execution",metadata:this.metadata,...r})}aiFallbackActionExecutionFailure(r){this.event({event:"AI Fallback Action Execution Failure",metadata:this.metadata,...r})}aiFallbackEnd(r){this.event({event:"AI Fallback End",metadata:this.metadata,...r})}ARStart(){this.event({event:"Auto-Recovery Start",metadata:this.metadata})}ARConfig(r){this.event({event:"Auto-Recovery Config",metadata:this.metadata,...r})}ARGetState(r){this.event({event:"Auto-Recovery State",metadata:this.metadata,thought:r})}ARInvokeCode(r,a){this.event({event:"Auto-Recovery Invoke Code",metadata:this.metadata,thought:r,code:a})}ARFinalResult(r){this.event({event:"Auto-Recovery Final Result",metadata:this.metadata,...r})}autoRecoveryDisconnect(r){this.event({event:"Auto-Recovery Disconnect",metadata:this.metadata,...r})}ARFinish(r){this.event({event:"Auto-Recovery Finish",metadata:this.metadata,...r})}ARError(r){this.event({event:"Auto-Recovery Error",metadata:this.metadata,...r})}};e(z6r,"RecoveryAnalytics");lTt=z6r});var Eln=ss(()=>{"use strict"});function W6r(i){return i._guid}var Cln,Dln,dwe,pTt,Sln=ss(()=>{"use strict";Npr();Cln=require("fs"),Dln=Td(require("path"));bln();Eln();e(W6r,"getPageGuid");dwe=class dwe{constructor({page:r,evaluateWithChecksum:a,checksumPage:s,pageInteractor:l,arConfig:f,sessionId:m,runtimeFallbackData:A,fallbackData:E,variableStore:S,runtimePage:T,context:O}){this.reducedHtmlTimeoutMs=3e4;this.page=r,this._originalPage=r,this.evaluateWithChecksum=a,this.checksumPage=s,this._pageInteractor=l,this.arConfig=f,this.sessionId=m,this.runtimeFallbackData=A,this.fallbackData=E,this.variableStore=S,this.runtimePage=T,this.context=O,this._activePageGuid=W6r(this.page),this._analytics=new lTt(this.sessionId,E.type)}get activePageGuid(){return this._activePageGuid}static async start(r){return new dwe({...r})}async evaluateOnCurrentPage(r,a){return this.page!==this._originalPage?this.page.evaluate(r,a):this.evaluateWithChecksum(r,a)}async getPageById(r){return(this.context||this.page.context()).pages().find(l=>W6r(l)===r)}async setActivePage(r){let a=await this.getPageById(r);if(!a||a.isClosed())throw new Error(`Page with ID ${r} is closed or not found`);this.page=a,this._activePageGuid=r}getMatcherResultFileData(r){let a=r.matcherResult;if((a==null?void 0:a.name)!=="toHaveScreenshot")return;let s=e((A,E=!0)=>{if(!A)return"";try{return(0,Cln.readFileSync)(A,E?"base64":"utf-8")}catch{return""}},"readFileSafe"),l=s(a==null?void 0:a.actual),f=s(a==null?void 0:a.diff),m=s(a==null?void 0:a.expected);if(!m)throw new Error("No expected file found for 'toHaveScreenshot'");return{...a,actual:l,diff:f,expected:m}}async getSelectionDataForChecksumId(r){return await this.evaluateOnCurrentPage(async s=>{let{selector:l,locator:f,clickOffset:m,parentFramesSelectors:A,invalid:E,rrwebId:S}=await window.checksum.testGenerator.getSelectorForChecksumId(s),T=await window.checksum.testGenerator.getElementForChecksumId(s),O=T instanceof HTMLOptionElement&&T.value?T.value:void 0;return{selector:l,locator:f,clickOffset:m,selectOptionValue:O,parentFramesSelectors:A,invalid:E,rrwebId:S}},r)}async getReducedHtml(r=dwe.currentChecksumId,a=3){if(this.page.url()==="about:blank")return{reducedHTML:"Error: Page is about:blank. Cannot get reduced HTML - either wait or navigate to a valid page before continuing.",currentChecksumId:r};try{let s=await this.evaluateOnCurrentPage(async l=>window.checksum.testGenerator.reduceHTML({},l),{initialChecksumId:r,stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0});return dwe.currentChecksumId=s.currentChecksumId,{reducedHTML:s.reducedHTML,currentChecksumId:s.currentChecksumId}}catch(s){if(a>0)return await new Promise(f=>setTimeout(f,2e3)),this.getReducedHtml(r,a-1);let l=s instanceof Error?s.message:String(s);return{reducedHTML:`Unable to extract page DOM at ${this.page.url()}. Error: ${l}`,currentChecksumId:r}}}async getApplicationState(){let{reducedHTML:r}=await this.getReducedHtml();return{reducedHTML:r,screenshot:await this.getPageScreenshot()}}async capturePageState(r,a){let s=this.page,l=this._activePageGuid;try{this.page=r,this._activePageGuid=a;let{reducedHTML:f}=await this.getReducedHtml(),m=await this.getPageScreenshot();return{pageId:a,reducedHTML:f,screenshot:m,url:r.url()}}finally{this.page=s,this._activePageGuid=l}}async captureAllPagesState(){let a=(this.context||this.page.context()).pages(),s=[],l=[];for(let m of a){if(m.isClosed())continue;let A=W6r(m);try{let E=await this.capturePageState(m,A);s.push(E)}catch(E){let S=E instanceof Error?E.message:String(E);l.push({pageId:A,url:m.url(),error:S}),console.warn(`Failed to capture state for page ${A} (${m.url()}):`,E)}}let f={pages:s};return l.length>0&&(f.failures=l),f}async captureApplicationState(r,a){if(a)return await this.captureAllPagesState();if(r&&r!==this._activePageGuid){let s=await this.getPageById(r);if(!s||s.isClosed())throw new Error(`Page with ID ${r} is closed or not found`);let l=await this.capturePageState(s,r);return{reducedHTML:l.reducedHTML,screenshot:l.screenshot}}else return await this.getApplicationState()}async buildFallbackData(){let a=(this.context||this.page.context()).pages().filter(m=>!m.isClosed()).length,s=new Promise((m,A)=>setTimeout(()=>A(new Error(`getReducedHtml timeout after ${this.reducedHtmlTimeoutMs/1e3} seconds`)),this.reducedHtmlTimeoutMs)),{reducedHTML:l,currentChecksumId:f}=await Promise.race([this.getReducedHtml(),s]);return{storyInfo:this.runtimeFallbackData.storyInfo,testIdentification:this.runtimeFallbackData.testIdentification,fallbackConfig:this.runtimeFallbackData.fallbackConfig,thoughts:this.runtimeFallbackData.thoughts,errorData:{error:{name:this.fallbackData.error.name,message:this.fallbackData.error.message,stack:this.fallbackData.error.stack},errorFileContent:await this.getErrorFileContent(this.fallbackData.error)},applicationState:{reducedHTML:l,screenshot:await this.getPageScreenshot()},stepData:{matcher:this.getMatcherResultFileData(this.fallbackData.error)},currentChecksumId:f,failingStepThought:this.runtimeFallbackData.thoughts.failing,type:this.fallbackData.type,config:this.runtimeFallbackData.config,sessionId:this.sessionId,variableStore:this.variableStore.reduce((m,A)=>(m[`variablesStore.${A.name}`]=A.value,m),{}),arConfig:this.arConfig,multiPageContext:{pageCount:a,hasMultiplePages:a>1}}}async scrollToElement(r){r&&await this.evaluateOnCurrentPage(async a=>{let s=document.querySelector(`[checksumid="${a}"]`);s==null||s.scrollIntoView({block:"center"})},r)}async getPageScreenshot(r=this.arConfig){try{return this.checksumPage.wrapInternalSteps(async()=>{var s;return(await this.page.screenshot({fullPage:!0,type:((s=r.modelConfig)==null?void 0:s.provider)==="anthropic"?"jpeg":"png"})).toString("base64")})}catch{return}}async getErrorFileContent(r){try{let a=Dln.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return RNe.toRecord(r,a)}catch{throw new Error("Error while getting error file content for AI fallback")}}async wait(){await this.page.waitForTimeout(5e3)}async preprocessCode(r){var q;let a=r,s=r,l=[],f=r.match(/getByChecksumId\([^)]+\)\.([a-zA-Z]+)\(([^)]*)\)/),m=f==null?void 0:f[1],A=f==null?void 0:f[2],E=/(?:page\.)?getByChecksumId\(['"]([^'"]+)['"]\)/,S=(q=r.match(E))==null?void 0:q[1];if(!S)throw new Error("Checksum ID not found in the code");let T=await this.getSelectionDataForChecksumId(S);if(!(T!=null&&T.locator)||T.invalid)throw new Error(`Locator or selector not found for checksumId: ${S}`);s=s.replace(E,T.locator);let O=/variables?Store\.([a-zA-Z_$][a-zA-Z0-9_$]*)/g,N=null;for(;(N=O.exec(r))!==null;){let Q=N[1],z=this.variableStore.find(se=>se.name===Q);z&&(l.push(z),s=s.replace(N[0],`"${z.value}"`))}return{originalCode:a,modifiedCode:s,usedVariables:l,checksumId:S,locator:T.locator,method:m,methodArgs:A}}async invokeCode(r){try{let a=await this.preprocessCode(r),{modifiedCode:s}=a,l=new Function("page",`return (async () => { return page.${s}; })()`),f;return await this.step(s,async()=>f=await l(this.page),!1,{box:!0,noLocation:!0,obtainStep:e(m=>{this.checksumPage.addAutoRecoveryStepId(m.stepId)},"obtainStep")}),{success:!0,result:f}}catch(a){throw console.log("Error while invoking code",a.message),a}}addAutoRecoveryErrorToReport(r,a){let s=this.runtimeFallbackData.thoughts.failing,l=a?`\u2705 "${s}" auto-recovered`:`\u274C "${s}" failed`;this.checksumPage.addPwAnnotation({type:l,description:r.replace(/^"(.*)"$/,"$1")}),a&&this.checksumPage.addErrorMessage(this.fallbackData.error,`${l}:
|
|
615
615
|
${r}`)}get createChecksumStep(){return r=>this.checksumPage.createChecksumStep(r)}get step(){return this.checksumPage.step.bind(this.checksumPage)}get runConditionallyWithinStep(){return(r,a,s)=>this.checksumPage.runConditionallyWithinStep(r,a,s)}async getScreenshotForElement(r){var a;try{let s=await this.getSelectionDataForChecksumId(r);if(!s)throw new Error(`Locator not found for checksumId: ${r}`);let l=((a=this.arConfig.modelConfig)==null?void 0:a.provider)==="anthropic"?"jpeg":"png";return(await this.page.locator(s.selector).screenshot({type:l})).toString("base64")}catch{throw new Error(`Failed to get screenshot for element: ${r}`)}}get analytics(){return this._analytics}get pageInteractor(){return this._pageInteractor}};e(dwe,"AutoRecoveryRuntimeIteratorUtils"),dwe.currentChecksumId="0";pTt=dwe});var s1e,o1e,wln=ss(()=>{"use strict";ope();HXe();Aln();Sln();FAe();s1e=class s1e extends Spe{constructor(r,a,s,l,f,m,A){super(r,a,s,l,f,m,A),this.runtimePageContext=m}init(r){var a;return this.initializationData=r,(a=this.initializationData.fallbackConfig).arMode??(a.arMode="fast"),this}canResolve(r){return!0}get failingThought(){return this.initializationData.thoughts.failing}getRecoveryAttemptTitle(){switch(this.initializationData.type){case"action":return`Checksum Auto-Recovery: trying to achieve action "${this.failingThought}"...`;case"assertion":return`Checksum Auto-Recovery: trying to verify assertion "${this.failingThought}"...`}}static async registerSession(r){let a=r.config.apiURL,s=r.config.apiKey;return await(await fetch(`${a}${s1e.API_BASE_ROUTE}/register-auto-recovery-session`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:s},body:JSON.stringify({appName:r.testIdentification.testFileName,fallbackData:r})})).json()}async prepareSession(r){let a=await s1e.registerSession(this.initializationData);this.utils=new pTt({page:this.page,evaluateWithChecksum:this.evaluateWithChecksum,checksumPage:this.checksumPage,pageInteractor:this.pageInteractor,arConfig:a.arConfig,sessionId:a.sessionId,runtimeFallbackData:this.initializationData,fallbackData:r,variableStore:this.variables,runtimePage:this.runtimePageContext,context:this.context});try{this.agent=await cTt.build(this.utils)}catch(s){let l=s instanceof Error?s.message:String(s),f=s instanceof Error?s.stack:void 0;throw new Error(`Failed to prepare ARFallback: ${l}`)}}async resolve(r){let a=null,s=new Promise((f,m)=>{a=setTimeout(()=>{a=null,this.utils.analytics.ARError({error:`Auto-recovery timed out after ${s1e.TIMEOUT_MS/1e3} seconds`});let A="Auto-Recovery attempt finished unsuccessfully";this.utils.createChecksumStep({title:A,withError:!0}),this.utils.addAutoRecoveryErrorToReport(A,!1),m(new Error(A))},s1e.TIMEOUT_MS)}),l=Date.now();await this.prepareSession(r),this.utils.analytics.ARStart();try{let f=await Promise.race([this.agent.init(),s]);return a!==null&&(clearTimeout(a),a=null),this.utils.analytics.ARFinish({duration:Date.now()-l}),{fbResult:f.result,thought:f.finalThought,stepsThoughts:f.stepsThoughts,steps:[]}}catch(f){throw a!==null&&(clearTimeout(a),a=null),this.utils.analytics.ARFinish({duration:Date.now()-l}),f}}};e(s1e,"ARFallback"),s1e.API_BASE_ROUTE="/auto-recovery",s1e.TIMEOUT_MS=12e4;o1e=s1e});var Tln,kln=ss(()=>{"use strict";Tln=e(i=>{let r=i.info();return r.annotations.some(a=>a.type==="bug")||r.tags.some(a=>a==="@bug")},"isKnownBugTest")});var Iln={};aDe(Iln,{VtgUserStoryService:()=>fTt});var H6r,fTt,G6r=ss(()=>{"use strict";_S();Ez();tC();H6r=class H6r{constructor(r,a){this.apiService=r;this.config=a}getStory(){return this.story}getTestGenerationData(){return this.userStoryTestGeneration}hasTestGenerationData(){return!!this.userStoryTestGeneration}async fetchStory(r){if(Qh.vtg.useFakeStory){this.story={...Qh.vtg.fakeStory,id:"fake-story",environment:{name:void 0,userRole:void 0},internalTestId:"fake-internal-test-id"},Gv.info("Using fake flow data",this.story);return}if(!r)throw new Error("no story id provided");try{let s=await(await this.apiService.post(`test-generation/info/${r}`)).json();if(!(s!=null&&s.id))throw new Error(`Story ${r} not found`);let{id:l,title:f,steps:m,startUrl:A,userRole:E,environment:S,internalTestId:T,version:O,collectionName:N}=s;this.story={id:l,goal:f,instructions:m,url:A,internalTestId:T,environment:{userRole:E,name:S},version:O,collectionName:N}}catch(a){throw Gv.error(`Error fetching story by id ${r}:`,a),new Error(`Couldn't fetch story by id ${r}. Make sure the server is running and the story id is correct. Original error: ${JSON.stringify(a)}`)}}getEnvInfo(){return K6r(this.config,{role:this.story.environment.userRole,environment:this.story.environment.name})}async createTestGeneration(){if(!this.story.id)return;let r=await this.apiService.post(`test-generation/create/${this.story.id}`,{internalTestId:this.story.internalTestId}),{testGenerationId:a}=await r.json();return this.userStoryTestGeneration={testGenerationId:a},this.userStoryTestGeneration}setTestGenerationData(r){this.userStoryTestGeneration=r}};e(H6r,"VtgUserStoryService");fTt=H6r});var Y6r,ORe,X6r=ss(()=>{"use strict";Y6r=class Y6r{constructor(r,a){this.config=r;this.baseURL=r.apiURL+a}getBaseURL(){return this.baseURL}get(r){let a=`${this.baseURL}/${r}`;return fetch(a,{method:"GET",headers:{ChecksumAppCode:this.config.apiKey}})}put(r,a){return fetch(`${this.baseURL}/${r}`,{method:"PUT",headers:{"Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:a?JSON.stringify(a):void 0})}post(r,a){return fetch(`${this.baseURL}/${r}`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:a?JSON.stringify(a):void 0})}delete(r){return fetch(`${this.baseURL}/${r}`,{method:"DELETE",headers:{ChecksumAppCode:this.config.apiKey}})}putFile(r,a){return fetch(r,{method:"PUT",headers:{"Content-Type":a.type},body:a})}};e(Y6r,"RuntimeAPIService");ORe=Y6r});var Fln={};aDe(Fln,{VtgCloudAPIService:()=>BRe});var Z6r,BRe,dTt=ss(()=>{"use strict";X6r();Z6r=class Z6r extends ORe{constructor(a){super(a,"/client-api/runtime");this.config=a}};e(Z6r,"VtgCloudAPIService");BRe=Z6r});var p$,Oln,FK,eCr,c1e,Pln,Bln=ss(()=>{"use strict";yD();C6t();oK();FAe();rhe();I6t();ope();Cur();p$=require("fs"),Oln=Td(_pr()),FK=Td(require("path"));SUr();xpr();_S();Bzr();Rzr();Lzr();Mzr();jzr();Uen();Ez();Q2r();wln();hEr();kln();eCr=1e3*30,c1e=class c1e extends vet{constructor(a,s="normal",l,f,m,A,E,S,T,O,N,q,Q){var ue,le,_e;super(a,l,N,()=>this.pageInteractor,void 0);this.page=a;this.runMode=s;this.testRunAnalytics=f;this.monitorBridge=m;this.testInfo=A;this.checksumTestId=E;this.test=S;this.options=T;this.isReplMode=O;this.config=N;this.pageInteractorAPI=q;this.lastInteractionTime=Date.now();this.hasRuntimeStartedTrace=!1;this.unzippedHarData=[];this.fallbacks=[];this.hasUsedAutoRecovery=!1;this.arSummaries=[];this.arStepIds=[];this.arResults=[];this.failedSteps=[];this.thoughtsCounter=0;this.highLevelThoughts=[];this.framesMsgBroker=new kYe;this.previousSteps=[];this.scriptLoadWrapper=e(async(a,s)=>(!this.isTimeMachineFrame(s)&&this.navigationPromise&&await this.navigationPromise,this.wrapInternalSteps(a,s.page())),"scriptLoadWrapper");this.scriptLoadCheck=e(async a=>a.evaluate(()=>!!window.checksum),"scriptLoadCheck");this.scriptLoadCallback=e(async a=>{await a.evaluate(async({appSpecificRules:s,esraTimeout:l,sessionRecorder:f,showFrontendLogs:m,showTMSeeker:A,filesObserver:E,nativeDialogObserver:S,assertionsObserver:T,actionsObserver:O,recordOptions:N})=>{var q;(q=window.checksum)==null||q.testGenerator.init(s,{esraTimeout:l,showFrontendLogs:m,skipElementHighlighting:!0,recordOptions:N},{assertionGenerator:!1,sessionRecorder:f,filesObserver:E,nativeDialogObserver:S,assertionsObserver:T,actionsObserver:O});try{A&&window.checksum.timeMachine.openSeekbar()}catch{}},{appSpecificRules:this.appSpecificRules,esraTimeout:eCr,sessionRecorder:!!(!this.isTimeMachineFrame(a)&&(this.timeMachine||this.isVTG)),showFrontendLogs:Qh.isDevMode,showTMSeeker:this.isTimeMachineFrame(a)&&process.env.CHECKSUM_SHOW_TIME_MACHINE==="true",filesObserver:this.isVTG&&!this.isTimeMachineFrame(a),nativeDialogObserver:this.isVTG&&!this.isTimeMachineFrame(a),assertionsObserver:this.isVTG&&!this.isTimeMachineFrame(a),actionsObserver:this.isVTG&&!this.isTimeMachineFrame(a),recordOptions:this.isVTG?this.getVTGRecordOptions():void 0}),Gy(`[init] init script loaded for ${a.page().url()}`)},"scriptLoadCallback");_Tt(T.printLogs),this.isVTG&&(this.options={...this.options,useChecksumAI:{actions:!1,assertions:!1,arVersion:1,visualComparison:!1},useMockData:!1,useChecksumSelectors:!1,autoHealPRs:!1},Rln(this.page)),Tln(S)&&this.config.options.useChecksumAI.skipTestsWithKnownBugs&&(console.log("Auto recovery will not run for this test as it is marked as a known bug"),this.config.options.useChecksumAI.actions=!1,this.config.options.useChecksumAI.assertions=!1,this.config.options.useChecksumAI.visualComparison=!1),this.injectedScriptManager.setScriptLoadWrapper(this.scriptLoadWrapper).setScriptLoadCallback(this.scriptLoadCallback).setScriptLoadCheck(this.scriptLoadCheck);let z=tCr({config:this.config,throwIfAuthFailed:!0}),se=this.getPlaywrightProjectConfig();if(this.pageInteractor=new cDe(this.evaluateWithChecksum.bind(this),()=>this.page.mainFrame(),()=>this.timeMachine,{log:Gy,logError:Gy},{navigationTimeout:(ue=se.use)==null?void 0:ue.navigationTimeout,actionTimeout:(le=se.use)==null?void 0:le.actionTimeout,testAssetsDir:EYe(Cee()),waitActionDelay:1e3},this.pageInteractorAPI,z),this.checkForActiveTracing(),this.resetFallbacks(),Q&&(this.highLevelThoughts=Q.highLevelThoughts??[],this.timeMachineBrowserContext=Q.timeMachineBrowserContext,this.variableStore=Q.variableStore),Qh.testRun.timeMachine.active){let be=this.shouldRecordRRwebEvents()?{recordRRwebEventsToFile:!0,recordRRwebEventsToFilePath:jBr(this.checksumTestId,this.testInfo.retry)}:{};this.isVTG||(this.timeMachine=new nSt(this.framesMsgBroker,this.injectedScriptManager,{...be,headless:process.env.CHECKSUM_SHOW_TIME_MACHINE==="true"?!1:Qh.testRun.timeMachine.headless,webProxy:(_e=A.project.use)==null?void 0:_e.proxy}),this.timeMachineBrowserContext&&this.timeMachine.setTimeMachineBrowserContext(this.timeMachineBrowserContext))}}previousThoughtsAndTimestamps(){return this.previousSteps}static async init(a,s,l,f,m,A,E,S,T,O=!1){let N=!1;E||(E=await c1e.fetchVtgInternalTestId(T),E||(E=our(5),N=!0,console.warn(`Checksum test id was not defined for test "${A.title}" and was auto-generated. Please replace - "${A.title}" with -
|
|
616
616
|
test(defineChecksumTest("${A.title}", "${E}"), async ({ page }) => {...`))),f.addTestInfo(E,A.testId,N),T.options.useChecksumAI!==void 0&&typeof T.options.useChecksumAI=="boolean"&&(T.options.useChecksumAI={actions:T.options.useChecksumAI,assertions:!1,visualComparison:!1});let q=new fXe(T),Q=new c1e(a,T.runMode,s,l,f,A,E,S,{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:T.runMode!=="normal",useMockData:!1,printLogs:!1,...T.options},O,T,q,{variableStore:m});return s.pages().length===0&&(S._checksum.expect.setPage(Q),S._checksum.checksumAI.page=Q,m.clearAll(),Q.testRunAnalytics.testRunStart()),await Q.asyncInit(),Q.proxy}static async fetchVtgInternalTestId(a){try{let s=process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG;if(!s)return;let l=JSON.parse(s);if(l.mode!=="start"||!l.storyId)return;let{VtgUserStoryService:f}=await Promise.resolve().then(()=>(G6r(),Iln)),{VtgCloudAPIService:m}=await Promise.resolve().then(()=>(dTt(),Fln)),A=new m(a),E=new f(A,a);await E.fetchStory(l.storyId);let S=E.getStory();return S==null?void 0:S.internalTestId}catch(s){console.warn("Failed to fetch VTG internalTestId from story:",s);return}}async asyncInit(a=!1){await this.loadAppSpecificRules(),await this.wrapInternalSteps(async()=>{await this.page.addInitScript(()=>{window.sessionStorage.setItem("checksumai:disable","true")})}),this.timeMachine&&(await this.timeMachine.prepare(this.page.mainFrame()),this.timeMachineBrowserContext=this.timeMachine.getTimeMachineBrowserContext()),this.pageInteractor.init(),a||await this.prepareForTestArtifacts();let s=FK.resolve(__dirname,"mock-auto-heal-agent.js");await this.page.addInitScript({path:s})}async makePage(a){let s=new c1e(a,this.runMode,this._context,this.testRunAnalytics,this.monitorBridge,this.testInfo,this.checksumTestId,this.test,this.options,this.isReplMode,this.config,this.pageInteractorAPI,{highLevelThoughts:this.highLevelThoughts,timeMachineBrowserContext:this.timeMachineBrowserContext,variableStore:this.variableStore});return await s.asyncInit(!0),s.proxy}getTimeMachinePage(){var a;return(a=this.timeMachine)==null?void 0:a.getPage()}getFramesMessageBroker(){return this.framesMsgBroker}isTimeMachineFrame(a){var s;return a===((s=this.timeMachine)==null?void 0:s.getFrame())}shouldRecordRRwebEvents(){return Qh.testRun.timeMachine.recordRRwebEventsToFile&&this.config.options.hostReports}recordInteraction(){let a=this.getPageGuid(this.page);c1e.recentlyInteracted.set(a,Date.now()),this.lastInteractionTime=Date.now()}static getMostRecentPage(a){let s=a.pages(),l=s[0],f=0;for(let m of s){let A=m._guid,E=c1e.recentlyInteracted.get(A)||0;E>f&&(f=E,l=m)}return l}async goto(a,s){return this.recordInteraction(),this.page.goto(a,s)}async reload(a){return this.recordInteraction(),this.page.reload(a)}async goBack(a){return this.recordInteraction(),this.page.goBack(a)}async goForward(a){return this.recordInteraction(),this.page.goForward(a)}async click(a,s){return this.recordInteraction(),this.page.click(a,s)}async dblclick(a,s){return this.recordInteraction(),this.page.dblclick(a,s)}async fill(a,s,l){return this.recordInteraction(),this.page.fill(a,s,l)}async press(a,s,l){return this.recordInteraction(),this.page.press(a,s,l)}async check(a,s){return this.recordInteraction(),this.page.check(a,s)}async uncheck(a,s){return this.recordInteraction(),this.page.uncheck(a,s)}async selectOption(a,s,l){return this.recordInteraction(),this.page.selectOption(a,s,l)}async hover(a,s){return this.recordInteraction(),this.page.hover(a,s)}async type(a,s,l){return this.recordInteraction(),this.page.type(a,s,l)}async setInputFiles(a,s,l){return this.recordInteraction(),this.page.setInputFiles(a,s,l)}async tap(a,s){return this.recordInteraction(),this.page.tap(a,s)}async dragAndDrop(a,s,l){return this.recordInteraction(),this.page.dragAndDrop(a,s,l)}getPlaywrightProjectConfig(){return this.testInfo.project}checkForActiveTracing(){var l;let s=(l=this.getPlaywrightProjectConfig().use)==null?void 0:l.trace;this.traceMode=typeof s=="string"?s:s==null?void 0:s.mode}registerPageEvents(){super.registerPageEvents(),this.injectedScriptManager.addTrackedFrame(this.page),this.page.on("framenavigated",async a=>{this.injectedScriptManager.onFrameNavigated(a)})}checksumSelector(a){return this.checksumStepId=a,this.options.useChecksumSelectors&&this.setSelectorFallback(a),this.proxy}checksumAI(a,s,l){let f=this.addNewThought(a,"action",!!s);this.previousSteps.push({thought:f.thought,timestamp:Date.now()});let m=this.getPageGuid(this.page);return cDe.setLastAction(m,a),s&&typeof s=="function"?this.test.step(a,async A=>{var E;try{return l!=null&&l.withDialog&&this.pageInteractor.listenToDialog(),await s()}catch(S){if(f.children=[],!this.options.useChecksumAI.actions||l!=null&&l.withDialog||l!=null&&l.skipAutoRecovery)throw S;this.setAIFallback(a,"action");try{return await this.initiateFallbackSequence({type:"action",error:S,method:void 0,args:[],testInfo:this.testInfo,step:A},{fallbackTypes:[Ahe,o1e]})}catch(T){throw this.testRunAnalytics.testRunError({failedThought:a,error:(T==null?void 0:T.message)||"Unknown error"}),T}}finally{this.pageInteractor.removeListener("dialog"),this.currentThought=(E=this.currentThought)==null?void 0:E.parent}}):(this.options.useChecksumAI.actions&&!(l!=null&&l.skipAutoRecovery)&&this.setAIFallback(a,"action"),this.proxy)}resolveAssetsFolder(a){return a.map(s=>FK.join(EYe(Cee()),s))}getRuntimeOptions(){return this.options}addPwAnnotation(a){this.testInfo.annotations.push({type:a.type,description:`
|
|
617
617
|
${a.description}`})}async onTestComplete(a){this.testRunAnalytics.testRunEnd({success:a,autoRecoveryTriggered:this.hasUsedAutoRecovery,summaries:this.arSummaries}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoveryMetadata",data:{autoRecoveryTriggered:this.hasUsedAutoRecovery,autoRecovered:this.hasUsedAutoRecovery&&a}}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoverySummaries",data:this.arSummaries}),this.cleanupMockData()}async wrapInternalSteps(a,s=this.page){try{return s.mainFrame()._checksumInternal=!0,s._checksumInternal=!0,await a()}finally{s.mainFrame()._checksumInternal=!1,s._checksumInternal=!1}}async conditionallyWrapInternalSteps(a,s){return a?this.wrapInternalSteps(s):s()}async wrapNoLocationSteps(a){try{return this.testInfo._checksumNoLocation=!0,await a()}finally{this.testInfo._checksumNoLocation=!1}}findAllStepsRecursively(a,s,l=[]){for(let f of a){(f._stepId===s||f.stepId===s)&&l.push(f);let m=[f.steps,f._testInfoSteps,f._steps].filter(Boolean);for(let A of m)this.findAllStepsRecursively(A,s,l)}return l}makeChecksumStepFunction(a){return s=>{if(!a)return;let l=s._stepId||s.stepId;this.findAllStepsRecursively(s._testInfo._steps,l).forEach(m=>{m.error={message:"ChecksumStepError",stack:"Fallback Failed",cause:void 0}})}}async createChecksumStep(a){let s,l={box:!0,noLocation:!0,obtainStep:e(f=>{s=f},"obtainStep")};return await this.step(a.title,this.makeChecksumStepFunction(a.withError),!1,l),this.arStepIds.push(s.stepId),s}async step(a,s,l=!0,{obtainStep:f=void 0,box:m=!1,noLocation:A=void 0}={}){let E=this.testInfo._checksumNoLocation;try{this.testInfo._checksumInternal=l===!0,A!==void 0&&(this.testInfo._checksumNoLocation=A),await this.test.step(a,s||(()=>{}),{obtainStep:f,box:m})}finally{this.testInfo._checksumInternal=!1,this.testInfo._checksumNoLocation=E}}addErrorMessage(a,s){this.testInfo.addError(a,s)}async evaluateWithChecksum(a,s,l=!0){return this.navigationPromise&&await this.navigationPromise,this.conditionallyWrapInternalSteps(l,()=>this.page.evaluate(a,s))}getChecksumTestId(){return this.checksumTestId}addNewThought(a,s,l=!1){let f={id:void 0,thought:a,type:s,children:l?[]:void 0,parent:void 0};if(!this.currentThought)this.highLevelThoughts.push(f);else if(this.currentThought.children)this.currentThought.children.push(f),f.parent=this.currentThought;else{let m=this.currentThought.parent;m?(m.children.push(f),f.parent=m):this.highLevelThoughts.push(f)}return f.parent?f.id=`${f.parent.id}.${f.parent.children.length}`:f.id=`${++this.thoughtsCounter}`,this.currentThought=f,f}buildThoughtsChainForFallback(a=this.highLevelThoughts){let s=[];return a.forEach(l=>{s.push(l.thought),l.children&&s.push(...this.buildThoughtsChainForFallback(l.children))}),s}getVTGRecordOptions(){return{recordCanvas:!0,recordCrossOriginIframes:this.isVTG,sampling:{mousemove:!1},slimDOMOptions:"all"}}compoundSelection(...a){let s=super.compoundSelection(...a);return s.setAnalytics(()=>this.testRunAnalytics),this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),s}setSelectorFallback(a){let s={checksumId:a,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:eCr};this.pushFallback(this.constructFallback(XXe).init(s)),this.pushFallback(this.constructFallback(KXe).init(s))}setCompoundSelectorFallback(a){this.pushFallback(this.constructFallback(YXe).init({checksumId:a,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:eCr}))}setAIFallback(a,s){var A;let l=((A=this.options.useChecksumAI)==null?void 0:A.arVersion)===1,f=e(()=>{var q,Q;let E=this.buildThoughtsChainForFallback(),S={title:this.testInfo.title},T={testFileName:this.testInfo.file,testId:this.testInfo.testId,testSuiteId:process.env.CHECKSUM_TEST_SUITE_ID||""},O={previous:E.slice(0,-1),failing:a,next:E.slice(1)},N={storyInfo:S,testIdentification:T,fallbackConfig:{arMode:(q=this.options.useChecksumAI)==null?void 0:q.arMode,overrideOptions:(Q=this.options.useChecksumAI)==null?void 0:Q.overrideOptions},thoughts:O,config:{apiURL:this.config.apiURL,apiKey:this.config.apiKey},type:s};return this.constructFallback(o1e).init(N)},"createArFallback"),m=e(()=>{var E,S;return this.constructFallback(Ahe).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback(),benchmark:Qh.benchmark,arMode:(E=this.options.useChecksumAI)==null?void 0:E.arMode,overrideOptions:(S=this.options.useChecksumAI)==null?void 0:S.overrideOptions,fallbackType:s})},"createAIFallback");return l?this.pushFallback(m()):this.pushFallback(f()),this.proxy}pushFallback(a){this.fallbacks.push(a),this.sortFallbacks()}handleAIFallback(a,s,l,f){let m=a.fallbackAnalyticsPayload.iterationSteps,A=m.length>0?f/m.length:0;this.testRunAnalytics.testRunFallbackExecution({result:l.fbResult,failedThought:a.getFailedThought(),summary:l.summary,stepsPayload:a.fallbackAnalyticsPayload,type:a.fallbackType??s.type,benchmark:Qh.benchmark.toString(),duration:f,avgDuration:A,success:["finish","soft_assertion"].includes(l.fbResult)}),this.arResults.push({failedThought:a.getFailedThought(),result:l.fbResult,thought:l.thought})}handleAutoRecovery(a,s,l,f){let m=l.stepsThoughts.length>0?f/l.stepsThoughts.length:0;this.testRunAnalytics.testRunAutoRecovery({failingThought:a.failingThought,type:s.type,finalThought:l.thought,result:l.fbResult,duration:f,avgStepDuration:m,stepsThoughts:l.stepsThoughts,version:"v1"})}async runFallback(a,s){let l=Date.now(),f=a.resolve(s),m=await U4(f,a.timeout),A=Date.now()-l;a instanceof Ahe&&(this.hasUsedAutoRecovery=!0,this.handleAIFallback(a,s,m,A)),a instanceof o1e&&(this.hasUsedAutoRecovery=!0,this.handleAutoRecovery(a,s,m,A));let E=m.thought?`: ${m.thought}`:"";if(!m||m.fbResult==="failed")throw this.createChecksumStep({title:`Recovery Failed${E}`,withError:!0}),new Error("Fallback failed");if(m.fbResult==="hard_assertion")throw this.createChecksumStep({title:`Recovery Failed${E}`,withError:!0}),new pXe(m.fbResult);if(a instanceof Ahe&&m.summary&&this.arSummaries.push(m.summary),a instanceof o1e&&m.thought&&this.arSummaries.push(m.thought),this.createChecksumStep({title:`Recovery Complete${E}`}),m.steps.length===1){let S=m.steps[0];S.thought&&(this.currentThought.thought=S.thought)}else this.currentThought.children=m.steps.map((S,T)=>({id:`${this.currentThought.id}.${T+1}`,thought:S.thought,type:S.type,children:void 0,parent:this.currentThought}))}async runConditionallyWithinStep(a,s,l){return a?await this.step(s,l):await l()}async onExecutionError(a){try{return await this.initiateFallbackSequence({type:"action",...a})}catch(s){if(!this.currentThought){let{locator:l,method:f}=a;this.testRunAnalytics.testRunActionExecutionFailure({locator:l.toString(),selector:l._selector,method:f,checksumStepId:this.checksumStepId,error:s.toString()})}throw s}}async initiateFallbackSequence(a,{fallbackTypes:s=void 0}={}){Gy(`[initiateFallbackSequence] with type: ${a.type}...`);let l=this.fallbacks.find(A=>A instanceof Ahe);if(l){let A=l.getFailedThought(),E=this.variableStore.getActiveVariables();this.fallbacks.forEach(S=>{S.setThought(A),S.setVariables(E)})}let f=this.fallbacks.find(A=>A instanceof o1e);if(f){let A=f.failingThought;this.fallbacks.forEach(E=>{E instanceof o1e&&E.setVariables(this.variableStore.getActiveVariables()),E.setThought(A)})}let m=this.fallbacks;s&&(m=m.filter(A=>s.reduce((E,S)=>E||A instanceof S,!1))),m=m.filter(A=>A.canResolve(a));try{for(let A of m){let E=A==null?void 0:A.toString();E&&console.log(`Using ${E}`);let S;try{let T=await this.runConditionallyWithinStep(a.type!=="assertion"||!a.withChecksumAI,A.getRecoveryAttemptTitle(a),async()=>await this.runFallback(A,a));S=!0}catch(T){if(S=!1,a.withChecksumAI&&T.message==="fetch failed")throw new Error(SOe);T instanceof pXe&&T.fallbackResult==="hard_assertion"&&(a.error.fallbackResult="hard_assertion"),E&&console.log(`Failed to use ${E}`),A.cancel();continue}return!0}throw a.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(ZXe).init()]}async shutdown(){if(this.shouldRecordRRwebEvents()){try{await this.timeMachine.flushRRwebEventsToFile();let a=this.timeMachine.getRRwebFilePath();this.monitorBridge.addAsset({type:"rrweb-recording",path:a,testId:this.checksumTestId,fileName:FK.basename(a)})}catch(a){Gy("Error shutting down RRweb events recording",a)}if(this.testRunAnalytics)return Gy("Flushing analytics events......"),this.testRunAnalytics.close()}}sortFallbacks(){let a=[ZXe,YXe,XXe,KXe,Ahe];this.fallbacks.sort((s,l)=>a.indexOf(s.constructor)-a.indexOf(l.constructor))}constructFallback(a){return new a(this.page,this.evaluateWithChecksum.bind(this),this,this.pageInteractor,{generateSelectionData:this.runMode!=="normal"},this,this._context)}async prepareForTestArtifacts(){if((this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock(),this.traceMode&&this.traceMode!=="off"){let s=await this.getTraceFilePath();s&&this.monitorBridge.addAsset({type:"trace",path:s,testId:this.checksumTestId,project:this.testInfo.project.name})}if(!1){let s=MBr(S6t(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:s,testId:this.checksumTestId})}}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?UBr(S6t(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let a=pur(S6t(this.testInfo.file)),s=FK.join(a,`${this.checksumTestId}.har.zip`);if(!(0,p$.existsSync)(s))throw new Error("Could not find har file or zip file");let l=FK.join(a,"tmp");(0,p$.existsSync)(l)||(0,p$.mkdirSync)(l);let f=(0,p$.readFileSync)(s),m=await(0,Oln.loadAsync)(f);for(let E of Object.keys(m.files)){let S=await m.file(E).async("string"),T=FK.join(l,E);(0,p$.writeFileSync)(T,S),this.unzippedHarData.push(T)}let A=FK.join(l,"test.har");if(!(0,p$.existsSync)(A))throw this.cleanupMockData(),new Error(`Could not find har file ${A} after unzipping ${s}`);return A}cleanupMockData(){this.unzippedHarData.forEach(a=>{(0,p$.rmSync)(a)}),this.unzippedHarData.length>0&&(0,p$.rmSync)(FK.dirname(this.unzippedHarData[0]),{recursive:!0,force:!0})}async prepareAPIMock(){let a={GET:0,POST:0,PUT:0,DELETE:0};try{let s=await this.prepareMockData();await this.page.routeFromHAR(s,{url:"*/**",notFound:"fallback",update:!1});let l=this.page._routes[0].handler;await this.page.route("**/*",f=>{let m=f.request().headers(),A=f.request().method();m["Checksum-Id"]=(++a[A]).toString(),f.request()._applyFallbackOverrides({headers:m}),l(f)})}catch(s){Gy("Error setting up mock data",s.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let a=FK.join(sDe(Cee()),"settings.asr");if(!(0,p$.existsSync)(a)){Gy("Could not find ASR file");return}let{ungzip:s}=lur();try{let l=await s((0,p$.readFileSync)(a));this.appSpecificRules=JSON.parse(l)||{}}catch(l){Gy("Could not read ASR file",l.message)}}addAutoRecoveryStepId(a){this.arStepIds.push(a)}};e(c1e,"RuntimePage"),c1e.recentlyInteracted=new Map;Pln=c1e});function N6i(i,r){return r}function O6i(i,r){return i.filter(a=>a!==void 0)}function Mln(i){return typeof i!="object"||i===null?0:Array.isArray(i)?2:L6i(i)?1:i instanceof Set?3:i instanceof Map?4:5}function B6i(i){let r=new Set;for(let a of i)for(let s of[...Object.keys(a),...Object.getOwnPropertySymbols(a)])r.add(s);return r}function R6i(i,r){return typeof i=="object"&&Object.prototype.propertyIsEnumerable.call(i,r)}function Uln(i){var s;let r=0,a=(s=i[0])==null?void 0:s[Symbol.iterator]();return{[Symbol.iterator](){return{next(){var l;do{if(a===void 0)return{done:!0,value:void 0};let f=a.next();if(f.done===!0){r+=1,a=(l=i[r])==null?void 0:l[Symbol.iterator]();continue}return{done:!1,value:f.value}}while(!0)}}}}}function L6i(i){if(!jln.includes(Object.prototype.toString.call(i)))return!1;let{constructor:r}=i;if(r===void 0)return!0;let a=r.prototype;return!(a===null||typeof a!="object"||!jln.includes(Object.prototype.toString.call(a))||!a.hasOwnProperty("isPrototypeOf"))}function M6i(i,r,a){let s={};for(let l of B6i(i)){let f=[];for(let E of i)R6i(E,l)&&f.push(E[l]);if(f.length===0)continue;let m=r.metaDataUpdater(a,{key:l,parents:i}),A=qln(f,r,m);A!==Jbe.skip&&(l==="__proto__"?Object.defineProperty(s,l,{value:A,configurable:!0,enumerable:!0,writable:!0}):s[l]=A)}return s}function j6i(i){return i.flat()}function U6i(i){return new Set(Uln(i))}function Q6i(i){return new Map(Uln(i))}function q6i(i){return i.at(-1)}function Qln(...i){return $6i({})(...i)}function $6i(i,r){let a=V6i(i,s);function s(...l){return qln(l,a,r)}return e(s,"customizedDeepmerge"),s}function V6i(i,r){return{defaultMergeFunctions:mTt,mergeFunctions:{...mTt,...Object.fromEntries(Object.entries(i).filter(([a,s])=>Object.hasOwn(mTt,a)).map(([a,s])=>s===!1?[a,mTt.mergeOthers]:[a,s]))},metaDataUpdater:i.metaDataUpdater??N6i,deepmerge:r,useImplicitDefaultMerging:i.enableImplicitDefaultMerging??!1,filterValues:i.filterValues===!1?void 0:i.filterValues??O6i,actions:Jbe}}function qln(i,r,a){var f;let s=((f=r.filterValues)==null?void 0:f.call(r,i,a))??i;if(s.length===0)return;if(s.length===1)return rCr(s,r,a);let l=Mln(s[0]);if(l!==0&&l!==5){for(let m=1;m<s.length;m++)if(Mln(s[m])!==l)return rCr(s,r,a)}switch(l){case 1:return J6i(s,r,a);case 2:return z6i(s,r,a);case 3:return W6i(s,r,a);case 4:return H6i(s,r,a);default:return rCr(s,r,a)}}function J6i(i,r,a){let s=r.mergeFunctions.mergeRecords(i,r,a);return s===Jbe.defaultMerge||r.useImplicitDefaultMerging&&s===void 0&&r.mergeFunctions.mergeRecords!==r.defaultMergeFunctions.mergeRecords?r.defaultMergeFunctions.mergeRecords(i,r,a):s}function z6i(i,r,a){let s=r.mergeFunctions.mergeArrays(i,r,a);return s===Jbe.defaultMerge||r.useImplicitDefaultMerging&&s===void 0&&r.mergeFunctions.mergeArrays!==r.defaultMergeFunctions.mergeArrays?r.defaultMergeFunctions.mergeArrays(i):s}function W6i(i,r,a){let s=r.mergeFunctions.mergeSets(i,r,a);return s===Jbe.defaultMerge||r.useImplicitDefaultMerging&&s===void 0&&r.mergeFunctions.mergeSets!==r.defaultMergeFunctions.mergeSets?r.defaultMergeFunctions.mergeSets(i):s}function H6i(i,r,a){let s=r.mergeFunctions.mergeMaps(i,r,a);return s===Jbe.defaultMerge||r.useImplicitDefaultMerging&&s===void 0&&r.mergeFunctions.mergeMaps!==r.defaultMergeFunctions.mergeMaps?r.defaultMergeFunctions.mergeMaps(i):s}function rCr(i,r,a){let s=r.mergeFunctions.mergeOthers(i,r,a);return s===Jbe.defaultMerge||r.useImplicitDefaultMerging&&s===void 0&&r.mergeFunctions.mergeOthers!==r.defaultMergeFunctions.mergeOthers?r.defaultMergeFunctions.mergeOthers(i):s}var Jbe,h6a,Lln,jln,mTt,$ln=ss(()=>{Jbe={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},h6a={defaultMerge:Jbe.defaultMerge};e(N6i,"defaultMetaDataUpdater");e(O6i,"defaultFilterValues");(function(i){i[i.NOT=0]="NOT",i[i.RECORD=1]="RECORD",i[i.ARRAY=2]="ARRAY",i[i.SET=3]="SET",i[i.MAP=4]="MAP",i[i.OTHER=5]="OTHER"})(Lln||(Lln={}));e(Mln,"getObjectType");e(B6i,"getKeys");e(R6i,"objectHasProperty");e(Uln,"getIterableOfIterables");jln=["[object Object]","[object Module]"];e(L6i,"isRecord");e(M6i,"mergeRecords$1");e(j6i,"mergeArrays$1");e(U6i,"mergeSets$1");e(Q6i,"mergeMaps$1");e(q6i,"mergeOthers$1");mTt={mergeRecords:M6i,mergeArrays:j6i,mergeSets:U6i,mergeMaps:Q6i,mergeOthers:q6i};e(Qln,"deepmerge");e($6i,"deepmergeCustom");e(V6i,"getUtils");e(qln,"mergeUnknowns");e(J6i,"mergeRecords");e(z6i,"mergeArrays");e(W6i,"mergeSets");e(H6i,"mergeMaps");e(rCr,"mergeOthers")});function _Tt(i){Vln=i}function Gy(...i){Vln&&console.log(...i)}async function kzr(i,r,a,s=6e4){if(!(r in i))return i;let l=e(()=>i[r](...a),"executor");return s===null?l():U4(l(),s,"Execution timeout")}function K6r(i,{role:r,environment:a}={},s=!1){var A,E;let l;if(a&&(l=(A=i.environments)==null?void 0:A.find(({name:S})=>a===S)),l||(l=(E=i.environments)==null?void 0:E.find(({default:S})=>S)),!l)throw new Error("Environment not found. Please make sure your environments are properly defined in the checksum.config.ts file.");let f=l.users,m;if(f&&(r!==void 0&&(m=f.find(S=>S.role===r)),m||(m=f.find(S=>S.default))),!m)throw new Error(`User not found. Please make sure the users array for the "${l.name}" environment is properly defined in the checksum.config.ts file.`);if(a&&l.name!==a){if(s)throw new Error(`Could not find environment with name "${a}" in config file`);console.warn(`Could not find environment with name "${a}" in config file, trying to use default environment`)}if(r&&m.role!==r){if(s)throw new Error(`Could not find user with role "${r}" for environment "${a}" in config file`);console.warn(`Could not find user with role "${r}" for environment "${a}" in config file, trying to login with environment's default user`)}return{environment:l,user:m}}function G6i(i){let r=`${i??Cee()}/login.ts`;if(!(0,hTt.existsSync)(r))throw console.warn(`Could not locate the login.ts file. Please make sure your login file exists at ${r}`),new Error("Could not find login.ts file");try{return require(r).default}catch(a){throw console.warn("Error loading login.ts file",a),a}}async function K6i(i,r,{environment:a,user:s,config:l}){try{let f=e(()=>r(i,{environment:a,user:s,config:l}),"performLogin");"checksumAI"in i?await i.checksumAI(`Log in${s!=null&&s.role?` using ${s.role} role`:""}${a!=null&&a.name?` in ${a.name} environment`:""}`,f,{skipAutoRecovery:!0}):await f()}catch(f){throw console.warn(`The login method threw an exception, please check the login.ts file for the following error:
|
package/index.js
CHANGED
|
@@ -626,7 +626,7 @@ Result: ${JSON.stringify(C)}`);else w=C;let k;m7e(t)&&(k=t.id),!k&&KUn(f)&&(k=f.
|
|
|
626
626
|
|
|
627
627
|
`),c=`Available pages (${a.length}):
|
|
628
628
|
|
|
629
|
-
${o}`;return{success:!0,pages:a,message:c}}async switchPageHandler(r){if(!r.pageId)return{success:!1,message:"pageId is required"};r.thought&&this.utils.createChecksumStep({title:r.thought});try{await this.utils.setActivePage(r.pageId);let a=await this.utils.captureApplicationState();return{success:!0,message:`Successfully switched to page ${r.pageId}`,appState:a}}catch(a){let o=a instanceof Error?a.message:String(a);return{success:!1,message:`Failed to switch to page ${r.pageId}: ${o}`}}}};e(_zt,"AutoRecoveryAgent");mzt=_zt});var FVr,hzt,vJn=Vt(()=>{"use strict";Mjt();Kdt();FVr=class FVr{constructor(t,r){this.sessionId=null;if(!rie.getCurrentTestInfo())throw new Error("TestRunAnalytics must be initialized with testInfo before RecoveryAnalytics can be used");let o=rie.getCurrentInstance();if(!o)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating RecoveryAnalytics");let c=o.getTestSuiteRunInfo();this.analytics=Vme.createFromConfig(c,rie.isolatedMode,!0),this.fallbackId=t,this.fallbackType=r}updateToSessionId(t){this.sessionId!==t&&(this.sessionId=t)}get tableName(){return"fallbacks"}get metadata(){return{...this.analytics.metadata,fallbackType:this.fallbackType,sessionId:this.sessionId||"unknown",fallbackId:this.fallbackId}}event(t){this.analytics.trackEventWithTable(t,this.metadata,this.tableName)}setFallbackType(t){this.fallbackType=t}aiFallbackStart(t){this.event({event:"AI Fallback Start",metadata:this.metadata,...t})}aiFallbackConfig(t){this.event({event:"AI Fallback Config",metadata:this.metadata,...t})}aiFallbackIterationResponse(t){this.event({event:"AI Fallback Iteration Response",metadata:this.metadata,...t})}aiFallbackAssertion(t){this.event({event:"AI Fallback Assertion Execution",metadata:this.metadata,...t})}aiFallbackChangeVariable(t){this.event({event:"AI Fallback Change Variable",metadata:this.metadata,...t})}aiFallbackSummary(t){this.event({event:"AI Fallback Summary",metadata:this.metadata,fallbackType:this.fallbackType,...t})}aiFallbackActionExecution(t){this.event({event:"AI Fallback Action Execution",metadata:this.metadata,...t})}aiFallbackActionExecutionFailure(t){this.event({event:"AI Fallback Action Execution Failure",metadata:this.metadata,...t})}aiFallbackEnd(t){this.event({event:"AI Fallback End",metadata:this.metadata,...t})}ARStart(){this.event({event:"Auto-Recovery Start",metadata:this.metadata})}ARConfig(t){this.event({event:"Auto-Recovery Config",metadata:this.metadata,...t})}ARGetState(t){this.event({event:"Auto-Recovery State",metadata:this.metadata,thought:t})}ARInvokeCode(t,r){this.event({event:"Auto-Recovery Invoke Code",metadata:this.metadata,thought:t,code:r})}ARFinalResult(t){this.event({event:"Auto-Recovery Final Result",metadata:this.metadata,...t})}autoRecoveryDisconnect(t){this.event({event:"Auto-Recovery Disconnect",metadata:this.metadata,...t})}ARFinish(t){this.event({event:"Auto-Recovery Finish",metadata:this.metadata,...t})}ARError(t){this.event({event:"Auto-Recovery Error",metadata:this.metadata,...t})}};e(FVr,"RecoveryAnalytics");hzt=FVr});var bJn=Vt(()=>{"use strict"});function NVr(i){return i._guid}var xJn,AJn,SFe,gzt,EJn=Vt(()=>{"use strict";a5r();xJn=require("fs"),AJn=sf(require("path"));vJn();bJn();e(NVr,"getPageGuid");SFe=class SFe{constructor({page:t,evaluateWithChecksum:r,checksumPage:a,pageInteractor:o,arConfig:c,sessionId:f,runtimeFallbackData:_,fallbackData:v,variableStore:C,runtimePage:w,context:T}){this.reducedHtmlTimeoutMs=3e4;this.page=t,this.evaluateWithChecksum=r,this.checksumPage=a,this._pageInteractor=o,this.arConfig=c,this.sessionId=f,this.runtimeFallbackData=_,this.fallbackData=v,this.variableStore=C,this.runtimePage=w,this.context=T,this._activePageGuid=NVr(this.page),this._analytics=new hzt(this.sessionId,v.type)}get activePageGuid(){return this._activePageGuid}static async start(t){return new SFe({...t})}async getPageById(t){return(this.context||this.page.context()).pages().find(o=>NVr(o)===t)}async setActivePage(t){let r=await this.getPageById(t);if(!r||r.isClosed())throw new Error(`Page with ID ${t} is closed or not found`);this.page=r,this._activePageGuid=t}getMatcherResultFileData(t){let r=t.matcherResult;if((r==null?void 0:r.name)!=="toHaveScreenshot")return;let a=e((_,v=!0)=>{if(!_)return"";try{return(0,xJn.readFileSync)(_,v?"base64":"utf-8")}catch{return""}},"readFileSafe"),o=a(r==null?void 0:r.actual),c=a(r==null?void 0:r.diff),f=a(r==null?void 0:r.expected);if(!f)throw new Error("No expected file found for 'toHaveScreenshot'");return{...r,actual:o,diff:c,expected:f}}async getSelectionDataForChecksumId(t){return await this.evaluateWithChecksum(async a=>{let{selector:o,locator:c,clickOffset:f,parentFramesSelectors:_,invalid:v,rrwebId:C}=await window.checksum.testGenerator.getSelectorForChecksumId(a),w=await window.checksum.testGenerator.getElementForChecksumId(a),T=w instanceof HTMLOptionElement&&w.value?w.value:void 0;return{selector:o,locator:c,clickOffset:f,selectOptionValue:T,parentFramesSelectors:_,invalid:v,rrwebId:C}},t)}async getReducedHtml(t=SFe.currentChecksumId){if(this._pageInteractor.getCurrentURL()==="about:blank")return{reducedHTML:"Error: Page is about:blank. Cannot get reduced HTML - either wait or navigate to a valid page before continuing.",currentChecksumId:t};let{reducedHTML:r,currentChecksumId:a}=await this._pageInteractor.getCurrentReducedHTML({stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:t});return SFe.currentChecksumId=a,{reducedHTML:r,currentChecksumId:a}}async getApplicationState(){let{reducedHTML:t}=await this.getReducedHtml();return{reducedHTML:t,screenshot:await this.getPageScreenshot()}}async capturePageState(t,r){let a=this.page,o=this._activePageGuid;try{this.page=t,this._activePageGuid=r;let{reducedHTML:c}=await this.getReducedHtml(),f=await this.getPageScreenshot();return{pageId:r,reducedHTML:c,screenshot:f,url:t.url()}}finally{this.page=a,this._activePageGuid=o}}async captureAllPagesState(){let r=(this.context||this.page.context()).pages(),a=[],o=[];for(let f of r){if(f.isClosed())continue;let _=NVr(f);try{let v=await this.capturePageState(f,_);a.push(v)}catch(v){let C=v instanceof Error?v.message:String(v);o.push({pageId:_,url:f.url(),error:C}),console.warn(`Failed to capture state for page ${_} (${f.url()}):`,v)}}let c={pages:a};return o.length>0&&(c.failures=o),c}async captureApplicationState(t,r){if(r)return await this.captureAllPagesState();if(t&&t!==this._activePageGuid){let a=await this.getPageById(t);if(!a||a.isClosed())throw new Error(`Page with ID ${t} is closed or not found`);let o=await this.capturePageState(a,t);return{reducedHTML:o.reducedHTML,screenshot:o.screenshot}}else return await this.getApplicationState()}async buildFallbackData(){let r=(this.context||this.page.context()).pages().filter(f=>!f.isClosed()).length,a=new Promise((f,_)=>setTimeout(()=>_(new Error(`getReducedHtml timeout after ${this.reducedHtmlTimeoutMs/1e3} seconds`)),this.reducedHtmlTimeoutMs)),{reducedHTML:o,currentChecksumId:c}=await Promise.race([this.getReducedHtml(),a]);return{storyInfo:this.runtimeFallbackData.storyInfo,testIdentification:this.runtimeFallbackData.testIdentification,fallbackConfig:this.runtimeFallbackData.fallbackConfig,thoughts:this.runtimeFallbackData.thoughts,errorData:{error:{name:this.fallbackData.error.name,message:this.fallbackData.error.message,stack:this.fallbackData.error.stack},errorFileContent:await this.getErrorFileContent(this.fallbackData.error)},applicationState:{reducedHTML:o,screenshot:await this.getPageScreenshot()},stepData:{matcher:this.getMatcherResultFileData(this.fallbackData.error)},currentChecksumId:c,failingStepThought:this.runtimeFallbackData.thoughts.failing,type:this.fallbackData.type,config:this.runtimeFallbackData.config,sessionId:this.sessionId,variableStore:this.variableStore.reduce((f,_)=>(f[`variablesStore.${_.name}`]=_.value,f),{}),arConfig:this.arConfig,multiPageContext:{pageCount:r,hasMultiplePages:r>1}}}async scrollToElement(t){t&&await this._pageInteractor.scrollElementIntoViewByChecksumId(t)}async getPageScreenshot(t=this.arConfig){try{return this.checksumPage.wrapInternalSteps(async()=>{var a;return(await this.page.screenshot({fullPage:!0,type:((a=t.modelConfig)==null?void 0:a.provider)==="anthropic"?"jpeg":"png"})).toString("base64")})}catch{return}}async getErrorFileContent(t){try{let r=AJn.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return sVe.toRecord(t,r)}catch{throw new Error("Error while getting error file content for AI fallback")}}async wait(){await this.page.waitForTimeout(5e3)}async preprocessCode(t){var R;let r=t,a=t,o=[],c=t.match(/getByChecksumId\([^)]+\)\.([a-zA-Z]+)\(([^)]*)\)/),f=c==null?void 0:c[1],_=c==null?void 0:c[2],v=/(?:page\.)?getByChecksumId\(['"]([^'"]+)['"]\)/,C=(R=t.match(v))==null?void 0:R[1];if(!C)throw new Error("Checksum ID not found in the code");let w=await this.getSelectionDataForChecksumId(C);if(!(w!=null&&w.locator)||w.invalid)throw new Error(`Locator or selector not found for checksumId: ${C}`);a=a.replace(v,w.locator);let T=/variables?Store\.([a-zA-Z_$][a-zA-Z0-9_$]*)/g,k=null;for(;(k=T.exec(t))!==null;){let B=k[1],U=this.variableStore.find(W=>W.name===B);U&&(o.push(U),a=a.replace(k[0],`"${U.value}"`))}return{originalCode:r,modifiedCode:a,usedVariables:o,checksumId:C,locator:w.locator,method:f,methodArgs:_}}async invokeCode(t){try{let r=await this.preprocessCode(t),{modifiedCode:a}=r,o=new Function("page",`return (async () => { return page.${a}; })()`),c;return await this.step(a,async()=>c=await o(this.page),!1,{box:!0,noLocation:!0,obtainStep:e(f=>{this.checksumPage.addAutoRecoveryStepId(f.stepId)},"obtainStep")}),{success:!0,result:c}}catch(r){throw console.log("Error while invoking code",r.message),r}}addAutoRecoveryErrorToReport(t,r){let a=this.runtimeFallbackData.thoughts.failing,o=r?`\u2705 "${a}" auto-recovered`:`\u274C "${a}" failed`;this.checksumPage.addPwAnnotation({type:o,description:t.replace(/^"(.*)"$/,"$1")}),r&&this.checksumPage.addErrorMessage(this.fallbackData.error,`${o}:
|
|
629
|
+
${o}`;return{success:!0,pages:a,message:c}}async switchPageHandler(r){if(!r.pageId)return{success:!1,message:"pageId is required"};r.thought&&this.utils.createChecksumStep({title:r.thought});try{await this.utils.setActivePage(r.pageId);let a=await this.utils.captureApplicationState();return{success:!0,activePageId:r.pageId,message:`Successfully switched to page ${r.pageId}`,appState:a}}catch(a){let o=a instanceof Error?a.message:String(a);return{success:!1,activePageId:this.utils.activePageGuid,message:`Failed to switch to page ${r.pageId}: ${o}`}}}};e(_zt,"AutoRecoveryAgent");mzt=_zt});var FVr,hzt,vJn=Vt(()=>{"use strict";Mjt();Kdt();FVr=class FVr{constructor(t,r){this.sessionId=null;if(!rie.getCurrentTestInfo())throw new Error("TestRunAnalytics must be initialized with testInfo before RecoveryAnalytics can be used");let o=rie.getCurrentInstance();if(!o)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating RecoveryAnalytics");let c=o.getTestSuiteRunInfo();this.analytics=Vme.createFromConfig(c,rie.isolatedMode,!0),this.fallbackId=t,this.fallbackType=r}updateToSessionId(t){this.sessionId!==t&&(this.sessionId=t)}get tableName(){return"fallbacks"}get metadata(){return{...this.analytics.metadata,fallbackType:this.fallbackType,sessionId:this.sessionId||"unknown",fallbackId:this.fallbackId}}event(t){this.analytics.trackEventWithTable(t,this.metadata,this.tableName)}setFallbackType(t){this.fallbackType=t}aiFallbackStart(t){this.event({event:"AI Fallback Start",metadata:this.metadata,...t})}aiFallbackConfig(t){this.event({event:"AI Fallback Config",metadata:this.metadata,...t})}aiFallbackIterationResponse(t){this.event({event:"AI Fallback Iteration Response",metadata:this.metadata,...t})}aiFallbackAssertion(t){this.event({event:"AI Fallback Assertion Execution",metadata:this.metadata,...t})}aiFallbackChangeVariable(t){this.event({event:"AI Fallback Change Variable",metadata:this.metadata,...t})}aiFallbackSummary(t){this.event({event:"AI Fallback Summary",metadata:this.metadata,fallbackType:this.fallbackType,...t})}aiFallbackActionExecution(t){this.event({event:"AI Fallback Action Execution",metadata:this.metadata,...t})}aiFallbackActionExecutionFailure(t){this.event({event:"AI Fallback Action Execution Failure",metadata:this.metadata,...t})}aiFallbackEnd(t){this.event({event:"AI Fallback End",metadata:this.metadata,...t})}ARStart(){this.event({event:"Auto-Recovery Start",metadata:this.metadata})}ARConfig(t){this.event({event:"Auto-Recovery Config",metadata:this.metadata,...t})}ARGetState(t){this.event({event:"Auto-Recovery State",metadata:this.metadata,thought:t})}ARInvokeCode(t,r){this.event({event:"Auto-Recovery Invoke Code",metadata:this.metadata,thought:t,code:r})}ARFinalResult(t){this.event({event:"Auto-Recovery Final Result",metadata:this.metadata,...t})}autoRecoveryDisconnect(t){this.event({event:"Auto-Recovery Disconnect",metadata:this.metadata,...t})}ARFinish(t){this.event({event:"Auto-Recovery Finish",metadata:this.metadata,...t})}ARError(t){this.event({event:"Auto-Recovery Error",metadata:this.metadata,...t})}};e(FVr,"RecoveryAnalytics");hzt=FVr});var bJn=Vt(()=>{"use strict"});function NVr(i){return i._guid}var xJn,AJn,SFe,gzt,EJn=Vt(()=>{"use strict";a5r();xJn=require("fs"),AJn=sf(require("path"));vJn();bJn();e(NVr,"getPageGuid");SFe=class SFe{constructor({page:t,evaluateWithChecksum:r,checksumPage:a,pageInteractor:o,arConfig:c,sessionId:f,runtimeFallbackData:_,fallbackData:v,variableStore:C,runtimePage:w,context:T}){this.reducedHtmlTimeoutMs=3e4;this.page=t,this._originalPage=t,this.evaluateWithChecksum=r,this.checksumPage=a,this._pageInteractor=o,this.arConfig=c,this.sessionId=f,this.runtimeFallbackData=_,this.fallbackData=v,this.variableStore=C,this.runtimePage=w,this.context=T,this._activePageGuid=NVr(this.page),this._analytics=new hzt(this.sessionId,v.type)}get activePageGuid(){return this._activePageGuid}static async start(t){return new SFe({...t})}async evaluateOnCurrentPage(t,r){return this.page!==this._originalPage?this.page.evaluate(t,r):this.evaluateWithChecksum(t,r)}async getPageById(t){return(this.context||this.page.context()).pages().find(o=>NVr(o)===t)}async setActivePage(t){let r=await this.getPageById(t);if(!r||r.isClosed())throw new Error(`Page with ID ${t} is closed or not found`);this.page=r,this._activePageGuid=t}getMatcherResultFileData(t){let r=t.matcherResult;if((r==null?void 0:r.name)!=="toHaveScreenshot")return;let a=e((_,v=!0)=>{if(!_)return"";try{return(0,xJn.readFileSync)(_,v?"base64":"utf-8")}catch{return""}},"readFileSafe"),o=a(r==null?void 0:r.actual),c=a(r==null?void 0:r.diff),f=a(r==null?void 0:r.expected);if(!f)throw new Error("No expected file found for 'toHaveScreenshot'");return{...r,actual:o,diff:c,expected:f}}async getSelectionDataForChecksumId(t){return await this.evaluateOnCurrentPage(async a=>{let{selector:o,locator:c,clickOffset:f,parentFramesSelectors:_,invalid:v,rrwebId:C}=await window.checksum.testGenerator.getSelectorForChecksumId(a),w=await window.checksum.testGenerator.getElementForChecksumId(a),T=w instanceof HTMLOptionElement&&w.value?w.value:void 0;return{selector:o,locator:c,clickOffset:f,selectOptionValue:T,parentFramesSelectors:_,invalid:v,rrwebId:C}},t)}async getReducedHtml(t=SFe.currentChecksumId,r=3){if(this.page.url()==="about:blank")return{reducedHTML:"Error: Page is about:blank. Cannot get reduced HTML - either wait or navigate to a valid page before continuing.",currentChecksumId:t};try{let a=await this.evaluateOnCurrentPage(async o=>window.checksum.testGenerator.reduceHTML({},o),{initialChecksumId:t,stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0});return SFe.currentChecksumId=a.currentChecksumId,{reducedHTML:a.reducedHTML,currentChecksumId:a.currentChecksumId}}catch(a){if(r>0)return await new Promise(c=>setTimeout(c,2e3)),this.getReducedHtml(t,r-1);let o=a instanceof Error?a.message:String(a);return{reducedHTML:`Unable to extract page DOM at ${this.page.url()}. Error: ${o}`,currentChecksumId:t}}}async getApplicationState(){let{reducedHTML:t}=await this.getReducedHtml();return{reducedHTML:t,screenshot:await this.getPageScreenshot()}}async capturePageState(t,r){let a=this.page,o=this._activePageGuid;try{this.page=t,this._activePageGuid=r;let{reducedHTML:c}=await this.getReducedHtml(),f=await this.getPageScreenshot();return{pageId:r,reducedHTML:c,screenshot:f,url:t.url()}}finally{this.page=a,this._activePageGuid=o}}async captureAllPagesState(){let r=(this.context||this.page.context()).pages(),a=[],o=[];for(let f of r){if(f.isClosed())continue;let _=NVr(f);try{let v=await this.capturePageState(f,_);a.push(v)}catch(v){let C=v instanceof Error?v.message:String(v);o.push({pageId:_,url:f.url(),error:C}),console.warn(`Failed to capture state for page ${_} (${f.url()}):`,v)}}let c={pages:a};return o.length>0&&(c.failures=o),c}async captureApplicationState(t,r){if(r)return await this.captureAllPagesState();if(t&&t!==this._activePageGuid){let a=await this.getPageById(t);if(!a||a.isClosed())throw new Error(`Page with ID ${t} is closed or not found`);let o=await this.capturePageState(a,t);return{reducedHTML:o.reducedHTML,screenshot:o.screenshot}}else return await this.getApplicationState()}async buildFallbackData(){let r=(this.context||this.page.context()).pages().filter(f=>!f.isClosed()).length,a=new Promise((f,_)=>setTimeout(()=>_(new Error(`getReducedHtml timeout after ${this.reducedHtmlTimeoutMs/1e3} seconds`)),this.reducedHtmlTimeoutMs)),{reducedHTML:o,currentChecksumId:c}=await Promise.race([this.getReducedHtml(),a]);return{storyInfo:this.runtimeFallbackData.storyInfo,testIdentification:this.runtimeFallbackData.testIdentification,fallbackConfig:this.runtimeFallbackData.fallbackConfig,thoughts:this.runtimeFallbackData.thoughts,errorData:{error:{name:this.fallbackData.error.name,message:this.fallbackData.error.message,stack:this.fallbackData.error.stack},errorFileContent:await this.getErrorFileContent(this.fallbackData.error)},applicationState:{reducedHTML:o,screenshot:await this.getPageScreenshot()},stepData:{matcher:this.getMatcherResultFileData(this.fallbackData.error)},currentChecksumId:c,failingStepThought:this.runtimeFallbackData.thoughts.failing,type:this.fallbackData.type,config:this.runtimeFallbackData.config,sessionId:this.sessionId,variableStore:this.variableStore.reduce((f,_)=>(f[`variablesStore.${_.name}`]=_.value,f),{}),arConfig:this.arConfig,multiPageContext:{pageCount:r,hasMultiplePages:r>1}}}async scrollToElement(t){t&&await this.evaluateOnCurrentPage(async r=>{let a=document.querySelector(`[checksumid="${r}"]`);a==null||a.scrollIntoView({block:"center"})},t)}async getPageScreenshot(t=this.arConfig){try{return this.checksumPage.wrapInternalSteps(async()=>{var a;return(await this.page.screenshot({fullPage:!0,type:((a=t.modelConfig)==null?void 0:a.provider)==="anthropic"?"jpeg":"png"})).toString("base64")})}catch{return}}async getErrorFileContent(t){try{let r=AJn.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return sVe.toRecord(t,r)}catch{throw new Error("Error while getting error file content for AI fallback")}}async wait(){await this.page.waitForTimeout(5e3)}async preprocessCode(t){var R;let r=t,a=t,o=[],c=t.match(/getByChecksumId\([^)]+\)\.([a-zA-Z]+)\(([^)]*)\)/),f=c==null?void 0:c[1],_=c==null?void 0:c[2],v=/(?:page\.)?getByChecksumId\(['"]([^'"]+)['"]\)/,C=(R=t.match(v))==null?void 0:R[1];if(!C)throw new Error("Checksum ID not found in the code");let w=await this.getSelectionDataForChecksumId(C);if(!(w!=null&&w.locator)||w.invalid)throw new Error(`Locator or selector not found for checksumId: ${C}`);a=a.replace(v,w.locator);let T=/variables?Store\.([a-zA-Z_$][a-zA-Z0-9_$]*)/g,k=null;for(;(k=T.exec(t))!==null;){let B=k[1],U=this.variableStore.find(W=>W.name===B);U&&(o.push(U),a=a.replace(k[0],`"${U.value}"`))}return{originalCode:r,modifiedCode:a,usedVariables:o,checksumId:C,locator:w.locator,method:f,methodArgs:_}}async invokeCode(t){try{let r=await this.preprocessCode(t),{modifiedCode:a}=r,o=new Function("page",`return (async () => { return page.${a}; })()`),c;return await this.step(a,async()=>c=await o(this.page),!1,{box:!0,noLocation:!0,obtainStep:e(f=>{this.checksumPage.addAutoRecoveryStepId(f.stepId)},"obtainStep")}),{success:!0,result:c}}catch(r){throw console.log("Error while invoking code",r.message),r}}addAutoRecoveryErrorToReport(t,r){let a=this.runtimeFallbackData.thoughts.failing,o=r?`\u2705 "${a}" auto-recovered`:`\u274C "${a}" failed`;this.checksumPage.addPwAnnotation({type:o,description:t.replace(/^"(.*)"$/,"$1")}),r&&this.checksumPage.addErrorMessage(this.fallbackData.error,`${o}:
|
|
630
630
|
${t}`)}get createChecksumStep(){return t=>this.checksumPage.createChecksumStep(t)}get step(){return this.checksumPage.step.bind(this.checksumPage)}get runConditionallyWithinStep(){return(t,r,a)=>this.checksumPage.runConditionallyWithinStep(t,r,a)}async getScreenshotForElement(t){var r;try{let a=await this.getSelectionDataForChecksumId(t);if(!a)throw new Error(`Locator not found for checksumId: ${t}`);let o=((r=this.arConfig.modelConfig)==null?void 0:r.provider)==="anthropic"?"jpeg":"png";return(await this.page.locator(a.selector).screenshot({type:o})).toString("base64")}catch{throw new Error(`Failed to get screenshot for element: ${t}`)}}get analytics(){return this._analytics}get pageInteractor(){return this._pageInteractor}};e(SFe,"AutoRecoveryRuntimeIteratorUtils"),SFe.currentChecksumId="0";gzt=SFe});var Lbe,Mbe,CJn=Vt(()=>{"use strict";jne();r0t();yJn();EJn();Eve();Lbe=class Lbe extends Wme{constructor(t,r,a,o,c,f,_){super(t,r,a,o,c,f,_),this.runtimePageContext=f}init(t){var r;return this.initializationData=t,(r=this.initializationData.fallbackConfig).arMode??(r.arMode="fast"),this}canResolve(t){return!0}get failingThought(){return this.initializationData.thoughts.failing}getRecoveryAttemptTitle(){switch(this.initializationData.type){case"action":return`Checksum Auto-Recovery: trying to achieve action "${this.failingThought}"...`;case"assertion":return`Checksum Auto-Recovery: trying to verify assertion "${this.failingThought}"...`}}static async registerSession(t){let r=t.config.apiURL,a=t.config.apiKey;return await(await fetch(`${r}${Lbe.API_BASE_ROUTE}/register-auto-recovery-session`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:a},body:JSON.stringify({appName:t.testIdentification.testFileName,fallbackData:t})})).json()}async prepareSession(t){let r=await Lbe.registerSession(this.initializationData);this.utils=new gzt({page:this.page,evaluateWithChecksum:this.evaluateWithChecksum,checksumPage:this.checksumPage,pageInteractor:this.pageInteractor,arConfig:r.arConfig,sessionId:r.sessionId,runtimeFallbackData:this.initializationData,fallbackData:t,variableStore:this.variables,runtimePage:this.runtimePageContext,context:this.context});try{this.agent=await mzt.build(this.utils)}catch(a){let o=a instanceof Error?a.message:String(a),c=a instanceof Error?a.stack:void 0;throw new Error(`Failed to prepare ARFallback: ${o}`)}}async resolve(t){let r=null,a=new Promise((c,f)=>{r=setTimeout(()=>{r=null,this.utils.analytics.ARError({error:`Auto-recovery timed out after ${Lbe.TIMEOUT_MS/1e3} seconds`});let _="Auto-Recovery attempt finished unsuccessfully";this.utils.createChecksumStep({title:_,withError:!0}),this.utils.addAutoRecoveryErrorToReport(_,!1),f(new Error(_))},Lbe.TIMEOUT_MS)}),o=Date.now();await this.prepareSession(t),this.utils.analytics.ARStart();try{let c=await Promise.race([this.agent.init(),a]);return r!==null&&(clearTimeout(r),r=null),this.utils.analytics.ARFinish({duration:Date.now()-o}),{fbResult:c.result,thought:c.finalThought,stepsThoughts:c.stepsThoughts,steps:[]}}catch(c){throw r!==null&&(clearTimeout(r),r=null),this.utils.analytics.ARFinish({duration:Date.now()-o}),c}}};e(Lbe,"ARFallback"),Lbe.API_BASE_ROUTE="/auto-recovery",Lbe.TIMEOUT_MS=12e4;Mbe=Lbe});var wJn,SJn=Vt(()=>{"use strict";wJn=e(i=>{let t=i.info();return t.annotations.some(r=>r.type==="bug")||t.tags.some(r=>r==="@bug")},"isKnownBugTest")});var DJn={};CR(DJn,{VtgUserStoryService:()=>G_t});var OVr,G_t,BVr=Vt(()=>{"use strict";vT();fQ();qw();OVr=class OVr{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(V0.vtg.useFakeStory){this.story={...V0.vtg.fakeStory,id:"fake-story",environment:{name:void 0,userRole:void 0},internalTestId:"fake-internal-test-id"},tf.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`);let{id:o,title:c,steps:f,startUrl:_,userRole:v,environment:C,internalTestId:w,version:T,collectionName:k}=a;this.story={id:o,goal:c,instructions:f,url:_,internalTestId:w,environment:{userRole:v,name:C},version:T,collectionName:k}}catch(r){throw tf.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 K_t(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(OVr,"VtgUserStoryService");G_t=OVr});var RVr,yzt,TJn=Vt(()=>{"use strict";RVr=class RVr{constructor(t,r){this.config=t;this.baseURL=t.apiURL+r}getBaseURL(){return this.baseURL}get(t){let r=`${this.baseURL}/${t}`;return fetch(r,{method:"GET",headers:{ChecksumAppCode:this.config.apiKey}})}put(t,r){return fetch(`${this.baseURL}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:r?JSON.stringify(r):void 0})}post(t,r){return fetch(`${this.baseURL}/${t}`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:r?JSON.stringify(r):void 0})}delete(t){return fetch(`${this.baseURL}/${t}`,{method:"DELETE",headers:{ChecksumAppCode:this.config.apiKey}})}putFile(t,r){return fetch(t,{method:"PUT",headers:{"Content-Type":r.type},body:r})}};e(RVr,"RuntimeAPIService");yzt=RVr});var kJn={};CR(kJn,{VtgCloudAPIService:()=>Y_t});var LVr,Y_t,MVr=Vt(()=>{"use strict";TJn();LVr=class LVr extends yzt{constructor(r){super(r,"/client-api/runtime");this.config=r}};e(LVr,"VtgCloudAPIService");Y_t=LVr});var Tz,IJn,wZ,jVr,jbe,vzt,UVr=Vt(()=>{"use strict";v7();BCn();JH();Eve();i4e();SRt();jne();YTr();Tz=require("fs"),IJn=sf(qkr()),wZ=sf(require("path"));F7n();Wkr();vT();Q5n();$5n();V5n();z5n();J5n();WRn();fQ();fMr();CJn();r$r();SJn();jVr=1e3*30,jbe=class jbe extends cJe{constructor(r,a="normal",o,c,f,_,v,C,w,T,k,R,B){var X,ne,ce;super(r,o,k,()=>this.pageInteractor,void 0);this.page=r;this.runMode=a;this.testRunAnalytics=c;this.monitorBridge=f;this.testInfo=_;this.checksumTestId=v;this.test=C;this.options=w;this.isReplMode=T;this.config=k;this.pageInteractorAPI=R;this.lastInteractionTime=Date.now();this.hasRuntimeStartedTrace=!1;this.unzippedHarData=[];this.fallbacks=[];this.hasUsedAutoRecovery=!1;this.arSummaries=[];this.arStepIds=[];this.arResults=[];this.failedSteps=[];this.thoughtsCounter=0;this.highLevelThoughts=[];this.framesMsgBroker=new I$e;this.previousSteps=[];this.scriptLoadWrapper=e(async(r,a)=>(!this.isTimeMachineFrame(a)&&this.navigationPromise&&await this.navigationPromise,this.wrapInternalSteps(r,a.page())),"scriptLoadWrapper");this.scriptLoadCheck=e(async r=>r.evaluate(()=>!!window.checksum),"scriptLoadCheck");this.scriptLoadCallback=e(async r=>{await r.evaluate(async({appSpecificRules:a,esraTimeout:o,sessionRecorder:c,showFrontendLogs:f,showTMSeeker:_,filesObserver:v,nativeDialogObserver:C,assertionsObserver:w,actionsObserver:T,recordOptions:k})=>{var R;(R=window.checksum)==null||R.testGenerator.init(a,{esraTimeout:o,showFrontendLogs:f,skipElementHighlighting:!0,recordOptions:k},{assertionGenerator:!1,sessionRecorder:c,filesObserver:v,nativeDialogObserver:C,assertionsObserver:w,actionsObserver:T});try{_&&window.checksum.timeMachine.openSeekbar()}catch{}},{appSpecificRules:this.appSpecificRules,esraTimeout:jVr,sessionRecorder:!!(!this.isTimeMachineFrame(r)&&(this.timeMachine||this.isVTG)),showFrontendLogs:V0.isDevMode,showTMSeeker:this.isTimeMachineFrame(r)&&process.env.CHECKSUM_SHOW_TIME_MACHINE==="true",filesObserver:this.isVTG&&!this.isTimeMachineFrame(r),nativeDialogObserver:this.isVTG&&!this.isTimeMachineFrame(r),assertionsObserver:this.isVTG&&!this.isTimeMachineFrame(r),actionsObserver:this.isVTG&&!this.isTimeMachineFrame(r),recordOptions:this.isVTG?this.getVTGRecordOptions():void 0}),Dv(`[init] init script loaded for ${r.page().url()}`)},"scriptLoadCallback");PJn(w.printLogs),this.isVTG&&(this.options={...this.options,useChecksumAI:{actions:!1,assertions:!1,arVersion:1,visualComparison:!1},useMockData:!1,useChecksumSelectors:!1,autoHealPRs:!1},bzt(this.page)),wJn(C)&&this.config.options.useChecksumAI.skipTestsWithKnownBugs&&(console.log("Auto recovery will not run for this test as it is marked as a known bug"),this.config.options.useChecksumAI.actions=!1,this.config.options.useChecksumAI.assertions=!1,this.config.options.useChecksumAI.visualComparison=!1),this.injectedScriptManager.setScriptLoadWrapper(this.scriptLoadWrapper).setScriptLoadCallback(this.scriptLoadCallback).setScriptLoadCheck(this.scriptLoadCheck);let U=Ube({config:this.config,throwIfAuthFailed:!0}),W=this.getPlaywrightProjectConfig();if(this.pageInteractor=new wve(this.evaluateWithChecksum.bind(this),()=>this.page.mainFrame(),()=>this.timeMachine,{log:Dv,logError:Dv},{navigationTimeout:(X=W.use)==null?void 0:X.navigationTimeout,actionTimeout:(ne=W.use)==null?void 0:ne.actionTimeout,testAssetsDir:Nft(Mne()),waitActionDelay:1e3},this.pageInteractorAPI,U),this.checkForActiveTracing(),this.resetFallbacks(),B&&(this.highLevelThoughts=B.highLevelThoughts??[],this.timeMachineBrowserContext=B.timeMachineBrowserContext,this.variableStore=B.variableStore),V0.testRun.timeMachine.active){let fe=this.shouldRecordRRwebEvents()?{recordRRwebEventsToFile:!0,recordRRwebEventsToFilePath:QCn(this.checksumTestId,this.testInfo.retry)}:{};this.isVTG||(this.timeMachine=new Zqt(this.framesMsgBroker,this.injectedScriptManager,{...fe,headless:process.env.CHECKSUM_SHOW_TIME_MACHINE==="true"?!1:V0.testRun.timeMachine.headless,webProxy:(ce=_.project.use)==null?void 0:ce.proxy}),this.timeMachineBrowserContext&&this.timeMachine.setTimeMachineBrowserContext(this.timeMachineBrowserContext))}}previousThoughtsAndTimestamps(){return this.previousSteps}static async init(r,a,o,c,f,_,v,C,w,T=!1){let k=!1;v||(v=await jbe.fetchVtgInternalTestId(w),v||(v=bRt(5),k=!0,console.warn(`Checksum test id was not defined for test "${_.title}" and was auto-generated. Please replace - "${_.title}" with -
|
|
631
631
|
test(defineChecksumTest("${_.title}", "${v}"), async ({ page }) => {...`))),c.addTestInfo(v,_.testId,k),w.options.useChecksumAI!==void 0&&typeof w.options.useChecksumAI=="boolean"&&(w.options.useChecksumAI={actions:w.options.useChecksumAI,assertions:!1,visualComparison:!1});let R=new iVe(w),B=new jbe(r,w.runMode,a,o,c,_,v,C,{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:w.runMode!=="normal",useMockData:!1,printLogs:!1,...w.options},T,w,R,{variableStore:f});return a.pages().length===0&&(C._checksum.expect.setPage(B),C._checksum.checksumAI.page=B,f.clearAll(),B.testRunAnalytics.testRunStart()),await B.asyncInit(),B.proxy}static async fetchVtgInternalTestId(r){try{let a=process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG;if(!a)return;let o=JSON.parse(a);if(o.mode!=="start"||!o.storyId)return;let{VtgUserStoryService:c}=await Promise.resolve().then(()=>(BVr(),DJn)),{VtgCloudAPIService:f}=await Promise.resolve().then(()=>(MVr(),kJn)),_=new f(r),v=new c(_,r);await v.fetchStory(o.storyId);let C=v.getStory();return C==null?void 0:C.internalTestId}catch(a){console.warn("Failed to fetch VTG internalTestId from story:",a);return}}async asyncInit(r=!1){await this.loadAppSpecificRules(),await this.wrapInternalSteps(async()=>{await this.page.addInitScript(()=>{window.sessionStorage.setItem("checksumai:disable","true")})}),this.timeMachine&&(await this.timeMachine.prepare(this.page.mainFrame()),this.timeMachineBrowserContext=this.timeMachine.getTimeMachineBrowserContext()),this.pageInteractor.init(),r||await this.prepareForTestArtifacts();let a=wZ.resolve(__dirname,"mock-auto-heal-agent.js");await this.page.addInitScript({path:a})}async makePage(r){let a=new jbe(r,this.runMode,this._context,this.testRunAnalytics,this.monitorBridge,this.testInfo,this.checksumTestId,this.test,this.options,this.isReplMode,this.config,this.pageInteractorAPI,{highLevelThoughts:this.highLevelThoughts,timeMachineBrowserContext:this.timeMachineBrowserContext,variableStore:this.variableStore});return await a.asyncInit(!0),a.proxy}getTimeMachinePage(){var r;return(r=this.timeMachine)==null?void 0:r.getPage()}getFramesMessageBroker(){return this.framesMsgBroker}isTimeMachineFrame(r){var a;return r===((a=this.timeMachine)==null?void 0:a.getFrame())}shouldRecordRRwebEvents(){return V0.testRun.timeMachine.recordRRwebEventsToFile&&this.config.options.hostReports}recordInteraction(){let r=this.getPageGuid(this.page);jbe.recentlyInteracted.set(r,Date.now()),this.lastInteractionTime=Date.now()}static getMostRecentPage(r){let a=r.pages(),o=a[0],c=0;for(let f of a){let _=f._guid,v=jbe.recentlyInteracted.get(_)||0;v>c&&(c=v,o=f)}return o}async goto(r,a){return this.recordInteraction(),this.page.goto(r,a)}async reload(r){return this.recordInteraction(),this.page.reload(r)}async goBack(r){return this.recordInteraction(),this.page.goBack(r)}async goForward(r){return this.recordInteraction(),this.page.goForward(r)}async click(r,a){return this.recordInteraction(),this.page.click(r,a)}async dblclick(r,a){return this.recordInteraction(),this.page.dblclick(r,a)}async fill(r,a,o){return this.recordInteraction(),this.page.fill(r,a,o)}async press(r,a,o){return this.recordInteraction(),this.page.press(r,a,o)}async check(r,a){return this.recordInteraction(),this.page.check(r,a)}async uncheck(r,a){return this.recordInteraction(),this.page.uncheck(r,a)}async selectOption(r,a,o){return this.recordInteraction(),this.page.selectOption(r,a,o)}async hover(r,a){return this.recordInteraction(),this.page.hover(r,a)}async type(r,a,o){return this.recordInteraction(),this.page.type(r,a,o)}async setInputFiles(r,a,o){return this.recordInteraction(),this.page.setInputFiles(r,a,o)}async tap(r,a){return this.recordInteraction(),this.page.tap(r,a)}async dragAndDrop(r,a,o){return this.recordInteraction(),this.page.dragAndDrop(r,a,o)}getPlaywrightProjectConfig(){return this.testInfo.project}checkForActiveTracing(){var o;let a=(o=this.getPlaywrightProjectConfig().use)==null?void 0:o.trace;this.traceMode=typeof a=="string"?a:a==null?void 0:a.mode}registerPageEvents(){super.registerPageEvents(),this.injectedScriptManager.addTrackedFrame(this.page),this.page.on("framenavigated",async r=>{this.injectedScriptManager.onFrameNavigated(r)})}checksumSelector(r){return this.checksumStepId=r,this.options.useChecksumSelectors&&this.setSelectorFallback(r),this.proxy}checksumAI(r,a,o){let c=this.addNewThought(r,"action",!!a);this.previousSteps.push({thought:c.thought,timestamp:Date.now()});let f=this.getPageGuid(this.page);return wve.setLastAction(f,r),a&&typeof a=="function"?this.test.step(r,async _=>{var v;try{return o!=null&&o.withDialog&&this.pageInteractor.listenToDialog(),await a()}catch(C){if(c.children=[],!this.options.useChecksumAI.actions||o!=null&&o.withDialog||o!=null&&o.skipAutoRecovery)throw C;this.setAIFallback(r,"action");try{return await this.initiateFallbackSequence({type:"action",error:C,method:void 0,args:[],testInfo:this.testInfo,step:_},{fallbackTypes:[Vve,Mbe]})}catch(w){throw this.testRunAnalytics.testRunError({failedThought:r,error:(w==null?void 0:w.message)||"Unknown error"}),w}}finally{this.pageInteractor.removeListener("dialog"),this.currentThought=(v=this.currentThought)==null?void 0:v.parent}}):(this.options.useChecksumAI.actions&&!(o!=null&&o.skipAutoRecovery)&&this.setAIFallback(r,"action"),this.proxy)}resolveAssetsFolder(r){return r.map(a=>wZ.join(Nft(Mne()),a))}getRuntimeOptions(){return this.options}addPwAnnotation(r){this.testInfo.annotations.push({type:r.type,description:`
|
|
632
632
|
${r.description}`})}async onTestComplete(r){this.testRunAnalytics.testRunEnd({success:r,autoRecoveryTriggered:this.hasUsedAutoRecovery,summaries:this.arSummaries}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoveryMetadata",data:{autoRecoveryTriggered:this.hasUsedAutoRecovery,autoRecovered:this.hasUsedAutoRecovery&&r}}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoverySummaries",data:this.arSummaries}),this.cleanupMockData()}async wrapInternalSteps(r,a=this.page){try{return a.mainFrame()._checksumInternal=!0,a._checksumInternal=!0,await r()}finally{a.mainFrame()._checksumInternal=!1,a._checksumInternal=!1}}async conditionallyWrapInternalSteps(r,a){return r?this.wrapInternalSteps(a):a()}async wrapNoLocationSteps(r){try{return this.testInfo._checksumNoLocation=!0,await r()}finally{this.testInfo._checksumNoLocation=!1}}findAllStepsRecursively(r,a,o=[]){for(let c of r){(c._stepId===a||c.stepId===a)&&o.push(c);let f=[c.steps,c._testInfoSteps,c._steps].filter(Boolean);for(let _ of f)this.findAllStepsRecursively(_,a,o)}return o}makeChecksumStepFunction(r){return a=>{if(!r)return;let o=a._stepId||a.stepId;this.findAllStepsRecursively(a._testInfo._steps,o).forEach(f=>{f.error={message:"ChecksumStepError",stack:"Fallback Failed",cause:void 0}})}}async createChecksumStep(r){let a,o={box:!0,noLocation:!0,obtainStep:e(c=>{a=c},"obtainStep")};return await this.step(r.title,this.makeChecksumStepFunction(r.withError),!1,o),this.arStepIds.push(a.stepId),a}async step(r,a,o=!0,{obtainStep:c=void 0,box:f=!1,noLocation:_=void 0}={}){let v=this.testInfo._checksumNoLocation;try{this.testInfo._checksumInternal=o===!0,_!==void 0&&(this.testInfo._checksumNoLocation=_),await this.test.step(r,a||(()=>{}),{obtainStep:c,box:f})}finally{this.testInfo._checksumInternal=!1,this.testInfo._checksumNoLocation=v}}addErrorMessage(r,a){this.testInfo.addError(r,a)}async evaluateWithChecksum(r,a,o=!0){return this.navigationPromise&&await this.navigationPromise,this.conditionallyWrapInternalSteps(o,()=>this.page.evaluate(r,a))}getChecksumTestId(){return this.checksumTestId}addNewThought(r,a,o=!1){let c={id:void 0,thought:r,type:a,children:o?[]:void 0,parent:void 0};if(!this.currentThought)this.highLevelThoughts.push(c);else if(this.currentThought.children)this.currentThought.children.push(c),c.parent=this.currentThought;else{let f=this.currentThought.parent;f?(f.children.push(c),c.parent=f):this.highLevelThoughts.push(c)}return c.parent?c.id=`${c.parent.id}.${c.parent.children.length}`:c.id=`${++this.thoughtsCounter}`,this.currentThought=c,c}buildThoughtsChainForFallback(r=this.highLevelThoughts){let a=[];return r.forEach(o=>{a.push(o.thought),o.children&&a.push(...this.buildThoughtsChainForFallback(o.children))}),a}getVTGRecordOptions(){return{recordCanvas:!0,recordCrossOriginIframes:this.isVTG,sampling:{mousemove:!1},slimDOMOptions:"all"}}compoundSelection(...r){let a=super.compoundSelection(...r);return a.setAnalytics(()=>this.testRunAnalytics),this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),a}setSelectorFallback(r){let a={checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:jVr};this.pushFallback(this.constructFallback(s0t).init(a)),this.pushFallback(this.constructFallback(i0t).init(a))}setCompoundSelectorFallback(r){this.pushFallback(this.constructFallback(a0t).init({checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:jVr}))}setAIFallback(r,a){var _;let o=((_=this.options.useChecksumAI)==null?void 0:_.arVersion)===1,c=e(()=>{var R,B;let v=this.buildThoughtsChainForFallback(),C={title:this.testInfo.title},w={testFileName:this.testInfo.file,testId:this.testInfo.testId,testSuiteId:process.env.CHECKSUM_TEST_SUITE_ID||""},T={previous:v.slice(0,-1),failing:r,next:v.slice(1)},k={storyInfo:C,testIdentification:w,fallbackConfig:{arMode:(R=this.options.useChecksumAI)==null?void 0:R.arMode,overrideOptions:(B=this.options.useChecksumAI)==null?void 0:B.overrideOptions},thoughts:T,config:{apiURL:this.config.apiURL,apiKey:this.config.apiKey},type:a};return this.constructFallback(Mbe).init(k)},"createArFallback"),f=e(()=>{var v,C;return this.constructFallback(Vve).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback(),benchmark:V0.benchmark,arMode:(v=this.options.useChecksumAI)==null?void 0:v.arMode,overrideOptions:(C=this.options.useChecksumAI)==null?void 0:C.overrideOptions,fallbackType:a})},"createAIFallback");return o?this.pushFallback(f()):this.pushFallback(c()),this.proxy}pushFallback(r){this.fallbacks.push(r),this.sortFallbacks()}handleAIFallback(r,a,o,c){let f=r.fallbackAnalyticsPayload.iterationSteps,_=f.length>0?c/f.length:0;this.testRunAnalytics.testRunFallbackExecution({result:o.fbResult,failedThought:r.getFailedThought(),summary:o.summary,stepsPayload:r.fallbackAnalyticsPayload,type:r.fallbackType??a.type,benchmark:V0.benchmark.toString(),duration:c,avgDuration:_,success:["finish","soft_assertion"].includes(o.fbResult)}),this.arResults.push({failedThought:r.getFailedThought(),result:o.fbResult,thought:o.thought})}handleAutoRecovery(r,a,o,c){let f=o.stepsThoughts.length>0?c/o.stepsThoughts.length:0;this.testRunAnalytics.testRunAutoRecovery({failingThought:r.failingThought,type:a.type,finalThought:o.thought,result:o.fbResult,duration:c,avgStepDuration:f,stepsThoughts:o.stepsThoughts,version:"v1"})}async runFallback(r,a){let o=Date.now(),c=r.resolve(a),f=await fD(c,r.timeout),_=Date.now()-o;r instanceof Vve&&(this.hasUsedAutoRecovery=!0,this.handleAIFallback(r,a,f,_)),r instanceof Mbe&&(this.hasUsedAutoRecovery=!0,this.handleAutoRecovery(r,a,f,_));let v=f.thought?`: ${f.thought}`:"";if(!f||f.fbResult==="failed")throw this.createChecksumStep({title:`Recovery Failed${v}`,withError:!0}),new Error("Fallback failed");if(f.fbResult==="hard_assertion")throw this.createChecksumStep({title:`Recovery Failed${v}`,withError:!0}),new vdt(f.fbResult);if(r instanceof Vve&&f.summary&&this.arSummaries.push(f.summary),r instanceof Mbe&&f.thought&&this.arSummaries.push(f.thought),this.createChecksumStep({title:`Recovery Complete${v}`}),f.steps.length===1){let C=f.steps[0];C.thought&&(this.currentThought.thought=C.thought)}else this.currentThought.children=f.steps.map((C,w)=>({id:`${this.currentThought.id}.${w+1}`,thought:C.thought,type:C.type,children:void 0,parent:this.currentThought}))}async runConditionallyWithinStep(r,a,o){return r?await this.step(a,o):await o()}async onExecutionError(r){try{return await this.initiateFallbackSequence({type:"action",...r})}catch(a){if(!this.currentThought){let{locator:o,method:c}=r;this.testRunAnalytics.testRunActionExecutionFailure({locator:o.toString(),selector:o._selector,method:c,checksumStepId:this.checksumStepId,error:a.toString()})}throw a}}async initiateFallbackSequence(r,{fallbackTypes:a=void 0}={}){Dv(`[initiateFallbackSequence] with type: ${r.type}...`);let o=this.fallbacks.find(_=>_ instanceof Vve);if(o){let _=o.getFailedThought(),v=this.variableStore.getActiveVariables();this.fallbacks.forEach(C=>{C.setThought(_),C.setVariables(v)})}let c=this.fallbacks.find(_=>_ instanceof Mbe);if(c){let _=c.failingThought;this.fallbacks.forEach(v=>{v instanceof Mbe&&v.setVariables(this.variableStore.getActiveVariables()),v.setThought(_)})}let f=this.fallbacks;a&&(f=f.filter(_=>a.reduce((v,C)=>v||_ instanceof C,!1))),f=f.filter(_=>_.canResolve(r));try{for(let _ of f){let v=_==null?void 0:_.toString();v&&console.log(`Using ${v}`);let C;try{let w=await this.runConditionallyWithinStep(r.type!=="assertion"||!r.withChecksumAI,_.getRecoveryAttemptTitle(r),async()=>await this.runFallback(_,r));C=!0}catch(w){if(C=!1,r.withChecksumAI&&w.message==="fetch failed")throw new Error(B4e);w instanceof vdt&&w.fallbackResult==="hard_assertion"&&(r.error.fallbackResult="hard_assertion"),v&&console.log(`Failed to use ${v}`),_.cancel();continue}return!0}throw r.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(o0t).init()]}async shutdown(){if(this.shouldRecordRRwebEvents()){try{await this.timeMachine.flushRRwebEventsToFile();let r=this.timeMachine.getRRwebFilePath();this.monitorBridge.addAsset({type:"rrweb-recording",path:r,testId:this.checksumTestId,fileName:wZ.basename(r)})}catch(r){Dv("Error shutting down RRweb events recording",r)}if(this.testRunAnalytics)return Dv("Flushing analytics events......"),this.testRunAnalytics.close()}}sortFallbacks(){let r=[o0t,a0t,s0t,i0t,Vve];this.fallbacks.sort((a,o)=>r.indexOf(a.constructor)-r.indexOf(o.constructor))}constructFallback(r){return new r(this.page,this.evaluateWithChecksum.bind(this),this,this.pageInteractor,{generateSelectionData:this.runMode!=="normal"},this,this._context)}async prepareForTestArtifacts(){if((this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock(),this.traceMode&&this.traceMode!=="off"){let a=await this.getTraceFilePath();a&&this.monitorBridge.addAsset({type:"trace",path:a,testId:this.checksumTestId,project:this.testInfo.project.name})}if(!1){let a=qCn(ARt(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:a,testId:this.checksumTestId})}}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?$Cn(ARt(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let r=LTr(ARt(this.testInfo.file)),a=wZ.join(r,`${this.checksumTestId}.har.zip`);if(!(0,Tz.existsSync)(a))throw new Error("Could not find har file or zip file");let o=wZ.join(r,"tmp");(0,Tz.existsSync)(o)||(0,Tz.mkdirSync)(o);let c=(0,Tz.readFileSync)(a),f=await(0,IJn.loadAsync)(c);for(let v of Object.keys(f.files)){let C=await f.file(v).async("string"),w=wZ.join(o,v);(0,Tz.writeFileSync)(w,C),this.unzippedHarData.push(w)}let _=wZ.join(o,"test.har");if(!(0,Tz.existsSync)(_))throw this.cleanupMockData(),new Error(`Could not find har file ${_} after unzipping ${a}`);return _}cleanupMockData(){this.unzippedHarData.forEach(r=>{(0,Tz.rmSync)(r)}),this.unzippedHarData.length>0&&(0,Tz.rmSync)(wZ.dirname(this.unzippedHarData[0]),{recursive:!0,force:!0})}async prepareAPIMock(){let r={GET:0,POST:0,PUT:0,DELETE:0};try{let a=await this.prepareMockData();await this.page.routeFromHAR(a,{url:"*/**",notFound:"fallback",update:!1});let o=this.page._routes[0].handler;await this.page.route("**/*",c=>{let f=c.request().headers(),_=c.request().method();f["Checksum-Id"]=(++r[_]).toString(),c.request()._applyFallbackOverrides({headers:f}),o(c)})}catch(a){Dv("Error setting up mock data",a.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let r=wZ.join(b9e(Mne()),"settings.asr");if(!(0,Tz.existsSync)(r)){Dv("Could not find ASR file");return}let{ungzip:a}=RTr();try{let o=await a((0,Tz.readFileSync)(r));this.appSpecificRules=JSON.parse(o)||{}}catch(o){Dv("Could not read ASR file",o.message)}}addAutoRecoveryStepId(r){this.arStepIds.push(r)}};e(jbe,"RuntimePage"),jbe.recentlyInteracted=new Map;vzt=jbe});function FCa(i,t){return t}function NCa(i,t){return i.filter(r=>r!==void 0)}function NJn(i){return typeof i!="object"||i===null?0:Array.isArray(i)?2:RCa(i)?1:i instanceof Set?3:i instanceof Map?4:5}function OCa(i){let t=new Set;for(let r of i)for(let a of[...Object.keys(r),...Object.getOwnPropertySymbols(r)])t.add(a);return t}function BCa(i,t){return typeof i=="object"&&Object.prototype.propertyIsEnumerable.call(i,t)}function BJn(i){var a;let t=0,r=(a=i[0])==null?void 0:a[Symbol.iterator]();return{[Symbol.iterator](){return{next(){var o;do{if(r===void 0)return{done:!0,value:void 0};let c=r.next();if(c.done===!0){t+=1,r=(o=i[t])==null?void 0:o[Symbol.iterator]();continue}return{done:!1,value:c.value}}while(!0)}}}}}function RCa(i){if(!OJn.includes(Object.prototype.toString.call(i)))return!1;let{constructor:t}=i;if(t===void 0)return!0;let r=t.prototype;return!(r===null||typeof r!="object"||!OJn.includes(Object.prototype.toString.call(r))||!r.hasOwnProperty("isPrototypeOf"))}function LCa(i,t,r){let a={};for(let o of OCa(i)){let c=[];for(let v of i)BCa(v,o)&&c.push(v[o]);if(c.length===0)continue;let f=t.metaDataUpdater(r,{key:o,parents:i}),_=RJn(c,t,f);_!==D7e.skip&&(o==="__proto__"?Object.defineProperty(a,o,{value:_,configurable:!0,enumerable:!0,writable:!0}):a[o]=_)}return a}function MCa(i){return i.flat()}function jCa(i){return new Set(BJn(i))}function UCa(i){return new Map(BJn(i))}function qCa(i){return i.at(-1)}function Azt(...i){return QCa({})(...i)}function QCa(i,t){let r=$Ca(i,a);function a(...o){return RJn(o,r,t)}return e(a,"customizedDeepmerge"),a}function $Ca(i,t){return{defaultMergeFunctions:xzt,mergeFunctions:{...xzt,...Object.fromEntries(Object.entries(i).filter(([r,a])=>Object.hasOwn(xzt,r)).map(([r,a])=>a===!1?[r,xzt.mergeOthers]:[r,a]))},metaDataUpdater:i.metaDataUpdater??FCa,deepmerge:t,useImplicitDefaultMerging:i.enableImplicitDefaultMerging??!1,filterValues:i.filterValues===!1?void 0:i.filterValues??NCa,actions:D7e}}function RJn(i,t,r){var c;let a=((c=t.filterValues)==null?void 0:c.call(t,i,r))??i;if(a.length===0)return;if(a.length===1)return qVr(a,t,r);let o=NJn(a[0]);if(o!==0&&o!==5){for(let f=1;f<a.length;f++)if(NJn(a[f])!==o)return qVr(a,t,r)}switch(o){case 1:return VCa(a,t,r);case 2:return zCa(a,t,r);case 3:return JCa(a,t,r);case 4:return WCa(a,t,r);default:return qVr(a,t,r)}}function VCa(i,t,r){let a=t.mergeFunctions.mergeRecords(i,t,r);return a===D7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeRecords!==t.defaultMergeFunctions.mergeRecords?t.defaultMergeFunctions.mergeRecords(i,t,r):a}function zCa(i,t,r){let a=t.mergeFunctions.mergeArrays(i,t,r);return a===D7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeArrays!==t.defaultMergeFunctions.mergeArrays?t.defaultMergeFunctions.mergeArrays(i):a}function JCa(i,t,r){let a=t.mergeFunctions.mergeSets(i,t,r);return a===D7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeSets!==t.defaultMergeFunctions.mergeSets?t.defaultMergeFunctions.mergeSets(i):a}function WCa(i,t,r){let a=t.mergeFunctions.mergeMaps(i,t,r);return a===D7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeMaps!==t.defaultMergeFunctions.mergeMaps?t.defaultMergeFunctions.mergeMaps(i):a}function qVr(i,t,r){let a=t.mergeFunctions.mergeOthers(i,t,r);return a===D7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeOthers!==t.defaultMergeFunctions.mergeOthers?t.defaultMergeFunctions.mergeOthers(i):a}var D7e,Y9s,FJn,OJn,xzt,QVr=Vt(()=>{D7e={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},Y9s={defaultMerge:D7e.defaultMerge};e(FCa,"defaultMetaDataUpdater");e(NCa,"defaultFilterValues");(function(i){i[i.NOT=0]="NOT",i[i.RECORD=1]="RECORD",i[i.ARRAY=2]="ARRAY",i[i.SET=3]="SET",i[i.MAP=4]="MAP",i[i.OTHER=5]="OTHER"})(FJn||(FJn={}));e(NJn,"getObjectType");e(OCa,"getKeys");e(BCa,"objectHasProperty");e(BJn,"getIterableOfIterables");OJn=["[object Object]","[object Module]"];e(RCa,"isRecord");e(LCa,"mergeRecords$1");e(MCa,"mergeArrays$1");e(jCa,"mergeSets$1");e(UCa,"mergeMaps$1");e(qCa,"mergeOthers$1");xzt={mergeRecords:LCa,mergeArrays:MCa,mergeSets:jCa,mergeMaps:UCa,mergeOthers:qCa};e(Azt,"deepmerge");e(QCa,"deepmergeCustom");e($Ca,"getUtils");e(RJn,"mergeUnknowns");e(VCa,"mergeRecords");e(zCa,"mergeArrays");e(JCa,"mergeSets");e(WCa,"mergeMaps");e(qVr,"mergeOthers")});function PJn(i){LJn=i}function Dv(...i){LJn&&console.log(...i)}async function R5n(i,t,r,a=6e4){if(!(t in i))return i;let o=e(()=>i[t](...r),"executor");return a===null?o():fD(o(),a,"Execution timeout")}function K_t(i,{role:t,environment:r}={},a=!1){var _,v;let o;if(r&&(o=(_=i.environments)==null?void 0:_.find(({name:C})=>r===C)),o||(o=(v=i.environments)==null?void 0:v.find(({default:C})=>C)),!o)throw new Error("Environment not found. Please make sure your environments are properly defined in the checksum.config.ts file.");let c=o.users,f;if(c&&(t!==void 0&&(f=c.find(C=>C.role===t)),f||(f=c.find(C=>C.default))),!f)throw new Error(`User not found. Please make sure the users array for the "${o.name}" environment is properly defined in the checksum.config.ts file.`);if(r&&o.name!==r){if(a)throw new Error(`Could not find environment with name "${r}" in config file`);console.warn(`Could not find environment with name "${r}" in config file, trying to use default environment`)}if(t&&f.role!==t){if(a)throw new Error(`Could not find user with role "${t}" for environment "${r}" in config file`);console.warn(`Could not find user with role "${t}" for environment "${r}" in config file, trying to login with environment's default user`)}return{environment:o,user:f}}function HCa(i){let t=`${i??Mne()}/login.ts`;if(!(0,Ezt.existsSync)(t))throw console.warn(`Could not locate the login.ts file. Please make sure your login file exists at ${t}`),new Error("Could not find login.ts file");try{return require(t).default}catch(r){throw console.warn("Error loading login.ts file",r),r}}async function GCa(i,t,{environment:r,user:a,config:o}){try{let c=e(()=>t(i,{environment:r,user:a,config:o}),"performLogin");"checksumAI"in i?await i.checksumAI(`Log in${a!=null&&a.role?` using ${a.role} role`:""}${r!=null&&r.name?` in ${r.name} environment`:""}`,c,{skipAutoRecovery:!0}):await c()}catch(c){throw console.warn(`The login method threw an exception, please check the login.ts file for the following error:
|
|
@@ -2040,7 +2040,7 @@ Supported model providers are: ${f}`)}}}catch(f){if("code"in f&&f.code.includes(
|
|
|
2040
2040
|
`)}),r.on("response",c=>{if(!c.ok()){let f=new Date().toISOString();a.write(`[${f}] [RESPONSE_ERROR] [${r.url()}] ${c.url()} - ${c.status()} ${c.statusText()}
|
|
2041
2041
|
`)}}),r.context().on("page",c=>{c!==r&&this.setupFrontendLogging(c)})}writeConsoleMessageToLog(r,a){var w;let o=r.text(),c=r.type(),f=r.location(),_=new Date().toISOString(),v=((w=r.page())==null?void 0:w.url())||"unknown",C=`[${_}] [${c.toUpperCase()}] [${v}] ${o}`;f&&(C+=`
|
|
2042
2042
|
at ${f.url}:${f.lineNumber}:${f.columnNumber}`),a.write(C+`
|
|
2043
|
-
`)}async run(r){await this.init(r),this.buildServices(r),this.buildServer(),await this.loadIfNecessary(),await this.start()}async loadIfNecessary(){let r=await this.getInitialServicesData();r&&(this.actionsManager.setActions(r.actions),this.testAssetsManager.setCurrentSaveAsLocation(this.editLocationPath),this.storyId=r.storyId,r.testGenerationData&&this.userStoryService.setTestGenerationData(r.testGenerationData))}async init(r){tf.info(`Initializing VTG with runtime version ${this.checksumRuntimeVersion}...`),await this.patchPlaywright(),this.loadPlaywrightConfigForVTG(),this.webDriver=this.buildWebDriver(r),this.webDriver.registerEventListener(this),this.taskTimeMachine=new cbe(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!V0.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0,taskTimeout:V0.vtg.taskTimeMachine.taskTimeout,debugPort:V0.vtg.isSeparateProcess?V0.vtg.taskTimeMachine.debugPort:void 0,frameMsgBrokerRegisterName:"task-time-machine",logPerformance:V0.vtg.taskTimeMachine.logPerformance,webProxy:this.getPlaywrightProxySettings()}),this.pageInteractor=new wve(this.webDriver.evaluateWithChecksum.bind(this.webDriver),()=>this.webDriver.appMainFrame,this.webDriver.getTimeMachine.bind(this.webDriver),{log:e((a,...o)=>o!=null&&o.length?tf.info(a,...o):tf.info(a),"log"),logError:e((a,...o)=>o!=null&&o.length?tf.error(a,...o):tf.error(a),"logError")},{...this.getTimeoutParams(),waitActionDelay:1e3,testAssetsDir:__dirname,listenToDialog:!0,listenToFileChooser:!1},new iVe(this.checksumConfig)),this.testAssetsManager=new cGt(this.projectRootDirectory,this.checksumRoot,this.vtgInternalFilesDir,this.vtgTestFileRunConfig)}buildServices(r){this.actionsManager=new BWt,this.settingsService=new sgt(this.checksumRoot,this.apiService,this.vtgInternalFilesDir),this.apiService=new Y_t(this.checksumConfig),this.settingsService=new sgt(this.checksumRoot,this.apiService),this.userStoryService=new G_t(this.apiService,this.checksumConfig),this.variableStoreService=new hGt,this.evaluatorService=new yGt(this.variableStoreService,this.settingsService,this.vtgTestFileMode,r,this.port),this.actionsService=new dJt(this.checksumConfig,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver,this.evaluatorService,this.vtgInternalFilesDir),this.assertionsService=new AJt(this.webDriver,this.actionsManager,this.evaluatorService),this.locatorsService=new FJt(this.webDriver,this.taskTimeMachine,this.apiService,this.userStoryService,this.evaluatorService),this.aiTestGenerationService=new _Jt(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new xJt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver,this.evaluatorService,{logPerformance:V0.vtg.aiAssertions.logPerformance}),this.aiThoughtsService=new _Gt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new OWt(this.checksumConfig,this.userStoryService,this.apiService,this.actionsManager,this.testAssetsManager,this.actionsService,this.vtgTestFileRunConfig,this.evaluatorService,this.settingsService,this.taskTimeMachine),this.actionsManager.setStorageService(this.storageService),this.monacoService=new bGt,this.aiChatService=new prr(this.taskTimeMachine,this.evaluatorService)}buildServer(){this.reactAppServer=new oGt(this.actionsService,this.assertionsService,this.locatorsService,this.aiTestGenerationService,this.aiAssertionsService,this.aiThoughtsService,this.actionsManager,this.storageService,this.settingsService,this.monacoService,this.evaluatorService,this.aiChatService)}loadPlaywrightConfigForVTG(){try{let r=`${this.checksumRoot}/playwright.config.ts`;if((0,F3e.existsSync)(r)){let a=require(r).default;a&&(this.playwrightConfigForVTG=a)}}catch{tf.warning("Could not find playwright config file, will run with defaults")}}async getInitialServicesData(){switch(this.vtgMode){case"cloud":return this.getInitialServicesDataFromCloud();case"edit":return this.vtgTestFileMode?await this.getInitialServicesDataForEditedFile():this.getInitialServicesDataFromJSON("local");case"start":if(this.vtgTestFileRunConfig.restoreFromAutoSave)return this.getInitialServicesDataFromJSON("auto-save")}}getInitialServicesDataFromJSON(r){let a=this.storageService.getLocalSavedJSONFilePath(r,this.storyId),o=this.storageService.readLocalSavedDataFromJSONFile(a);if(!o)throw new Error(`No data found in ${r} while reading from ${a}`);return{actions:o.executedActions,storyId:o.story.id}}async getInitialServicesDataFromCloud(){let a=await(await this.apiService.post(`test-generation/${this.cloudTestGenerationId}/info`)).json(),{actionsDownloadSignedURL:o}=a,c=await fetch(o,{mode:"cors",credentials:"same-origin",headers:{"Content-Type":"application/json"}});if(!c.ok)throw new Error(`HTTP error! Status: ${c.status}`);let f=await c.json();return{actions:this.initializeTestStepsWithIds(f),storyId:a.story.id}}initializeTestStepsWithIds(r){return r.map((a,o)=>({...a,id:(0,Chn.randomUUID)(),assertions:(a.assertions??[]).map(c=>({...c,id:(0,Chn.randomUUID)()}))}))}async getInitialServicesDataForEditedFile(){var a,o,c,f,_,v,C;if(((a=this.vtgTestFileRunConfig)==null?void 0:a.mode)!=="edit")return;let r=[];if(!this.vtgTestFileRunConfig.restoreFromAutoSave){let w=(o=this.vtgTestFileRunConfig)==null?void 0:o.actionsJsonFilePath;r=this.storageService.readJsonFile(w),(0,F3e.rmSync)(w,{force:!0}),r=this.initializeTestStepsWithIds(r)}if((c=this.vtgTestFileRunConfig)!=null&&c.internalTestId)try{let w=await this.apiService.post(`test-generation-by-internal-test-id/${(f=this.vtgTestFileRunConfig)==null?void 0:f.internalTestId}/info`);if(!w.ok){let k=w.statusText;try{let R=await w.text();try{k=JSON.parse(R).message||R||w.statusText}catch{k=R||w.statusText}}catch{k="Test id not found or invalid"}throw new Error(`Error fetching test generation data: ${k}`)}let T=await w.json();if(this.vtgTestFileRunConfig.restoreFromAutoSave){let k=this.storageService.getLocalSavedJSONFilePath("auto-save"),R=this.storageService.readLocalSavedDataFromJSONFile(k);if(!R)throw new Error(`No data found in auto-save while reading from ${k}`);r=R==null?void 0:R.executedActions}return{actions:r,storyId:T.story.id,testGenerationData:T.testGenerationData}}catch{tf.warning(`Could not find data matching internal test id: ${(_=this.vtgTestFileRunConfig)==null?void 0:_.internalTestId}`)}if((v=this.vtgTestFileRunConfig)!=null&&v.storyId)return{actions:r,storyId:(C=this.vtgTestFileRunConfig)==null?void 0:C.storyId};throw new Error("Cannot edit file without either valid internal test id or story id")}async start({createAssetsFolder:r=!0}={}){var o,c;await this.userStoryService.fetchStory(this.storyId),r&&this.testAssetsManager.createTestAssetsFolders(),this.testAssetsManager.createTestGenerationLocalAutoSaveFolder(),await this.reactAppServer.start();let{environment:a}=this.userStoryService.getEnvInfo();await this.webDriver.prepare({baseURL:a.baseURL,shutdown:!this.vtgTestFileMode},{serverPort:await this.reactAppServer.getPort()}),V0.vtg.writeLogFile&&this.setupFrontendLogging(this.webDriver.page),await this.webDriver.page.evaluate(()=>{"checksumRRWeb"in window&&console.log(`Using forked rrweb. ${JSON.stringify(window.checksumRRWeb)}`)}),await this.webDriver.addHARMockAPIRecordings(this.testAssetsManager.getHarFilePath()),await this.initTimeMachine(),this.pageInteractor.init(),this.assertionsService.setPage(this.webDriver.appMainFrame.page()),this.actionsService.setPage(this.webDriver.appMainFrame.page()),this.evaluatorService.setPage(this.webDriver.appMainFrame.page()),this.aiChatService.setPage(this.webDriver.appMainFrame.page()),await this.taskTimeMachine.prepare(this.webDriver.appMainFrame,void 0,f=>this.webDriver.registerTimeMachineFrame(f)),await this.reactAppServer.evaluateServerPort(this.webDriver.page),await this.webDriver.appMainFrame.goto("about:blank",{waitUntil:"domcontentloaded",timeout:0}),await this.webDriver.getTimeMachine().toggleTimeMachineHandleEvents(!1),this.vtgMode==="start"&&!this.vtgTestFileRunConfig.restoreFromAutoSave&&(await this.actionsService.addInitialLoginAction(),await this.actionsService.addStartURLNavigationAction(),this.vtgTestFileMode&&await this.storageService.saveTestFile()),tf.info("VTG is ready with story:",{goal:(o=this.userStoryService.getStory())==null?void 0:o.goal}),await this.webDriver.page.evaluate(({localSaveFolderPath:f,stepsData:_,appViewport:v,userStoryGoal:C,isLoadedFromFile:w})=>{window.vtg.initClient(f,_,v,this.checksumRuntimeVersion,C,w)},{localSaveFolderPath:this.editLocationPath,stepsData:await this.actionsManager.buildStepDataWithCode(this.actionsManager.actions,{loadingFromFile:["edit","cloud"].includes(this.vtgMode)}),appViewport:this.webDriver.getApplicationViewport(),userStoryGoal:(c=this.userStoryService.getStory())==null?void 0:c.goal,isLoadedFromFile:this.vtgTestFileMode}),this.vtgTestFileMode||await new Promise(()=>{})}getTimeoutParams(){var o,c,f,_;let r=((c=(o=this.playwrightConfigForVTG)==null?void 0:o.use)==null?void 0:c.navigationTimeout)||3e4,a=((_=(f=this.playwrightConfigForVTG)==null?void 0:f.use)==null?void 0:_.actionTimeout)||5e3;return{navigationTimeout:r,actionTimeout:a}}getPlaywrightProxySettings(){var f,_;let r=(_=(f=this.playwrightConfigForVTG)==null?void 0:f.use)==null?void 0:_.proxy,{server:a,username:o,password:c}=r||{};if(o&&c&&a)return{username:o,password:c,server:a}}getPlaywrightViewportSettings(){var o,c;let{width:r=1280,height:a=720}=((c=(o=this.playwrightConfigForVTG)==null?void 0:o.use)==null?void 0:c.viewport)||{};return{width:r,height:a}}buildWebDriver(r){var c,f,_,v,C,w;let a=this.getPlaywrightProxySettings(),o=this.getPlaywrightViewportSettings();return new fGt({scriptSource:V0.checksumScript.source,scriptURL:V0.checksumScript.url,scriptFile:V0.checksumScript.path,isScriptFileAbsolute:!0,fullScreenResolution:!1,hostWindowViewport:!0,baseURL:(c=this.checksumConfig.environments.find(T=>T.default))==null?void 0:c.baseURL,useProxy:!!a,webProxy:a,disableWebSecurity:!0,allowFileAccess:!0,remoteDebugging:V0.vtg.remoteDebugging,remoteDebuggingPort:V0.vtg.vtgRemoteDebuggingPort},{devtools:!1,headless:V0.CI},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"},viewport:o,completeOriginHeaderOnLivePage:!V0.vtg.isSeparateProcess&&!((v=(_=(f=this.checksumConfig.options)==null?void 0:f.modelConfig)==null?void 0:_.browserArgs)!=null&&v.skipDisableWebSecurity)&&!((w=(C=this.checksumConfig.options)==null?void 0:C.modelConfig)!=null&&w.skipCompleteOriginHeaderOnDisableWebSecurity)},r)}async onWebDriverContextClose(){var r,a,o;this.evaluatorService.stopListening(),(r=this.vtgTestFileRunConfig)!=null&&r.evalFilePath&&(0,F3e.rmSync)((a=this.vtgTestFileRunConfig)==null?void 0:a.evalFilePath,{force:!0}),this.vtgTestFileRunConfig.mode==="edit"&&(0,F3e.rmSync)((o=this.vtgTestFileRunConfig)==null?void 0:o.actionsJsonFilePath,{force:!0})}initializeAccordingToVTGMode(r){var c;let a=r.indexOf("--edit"),o=r.indexOf("--cloud");if(r.indexOf("--test-file")!==-1){this.vtgTestFileMode=!0,this.vtgTestFileRunConfig=JSON.parse(process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG),this.vtgMode=this.vtgTestFileRunConfig.mode,this.storyId=((c=this.vtgTestFileRunConfig)==null?void 0:c.mode)==="start"?this.vtgTestFileRunConfig.storyId:void 0;return}a!==-1&&(this.vtgMode="edit",this.editLocationPath=r[a+1]),o!==-1&&(this.vtgMode="cloud",this.cloudTestGenerationId=r[o+1]),this.vtgMode==="start"&&(this.storyId=r[0])}getWebDriver(){return this.webDriver}async eval(r){return this.evaluatorService.listenForExecution(r)}};e(whn,"VisualTestGenerator");var frr=whn;Eve();var iEi=require("child_process"),Dhn=require("net");vT();var aEi=require("path");v7();var nEi=sf(vht());fQ();var Shn=e(async(i,t,r,a,o={})=>{let{preventDialogFromAutoDismissing:c=!1,retry:f=!0,maxRetries:_=void 0,numberOfRetries:v=0}=o;try{console.log(`${i} attempting to connect to ${t} on port ${r}...`);let w=(await nEi.chromium.connectOverCDP("http://127.0.0.1:"+r)).contexts()[0],T=a(w.pages());for(;!T;)await TA(1e3),T=a(w.pages());return console.log(`${i} is connected to ${t} on port ${r}`,T.url()),c&&bzt(T),T}catch(C){if(!f||_&&v>=_)throw console.error(`${i} failed to connect to ${t}, retries were exhausted or disabled`,C),C;return console.log(`${i} is waiting and retrying connection to ${t} on port ${r}...`),await TA(1e3),Shn(i,t,r,a,{...o,numberOfRetries:v+1})}},"connectToPage");qw();var Thn=class Thn{constructor(t){this.checksumConfig=t;this.isReady=!1;this.onMessage=e(async(t,r)=>{let{id:a,err:o,result:c}=await this.execute(t);r.write(this.messageParser.makeMessage(JSON.stringify({id:a,err:this.serializedErr(o),result:c})))},"onMessage");this.messageParser=new BGe(this.onMessage),this.isReadyPromise=new Promise(r=>{this.isReadyResolve=r}),this.routeInterceptor=new qWe({completeOriginHeader:!0})}async eval(t){return this.listenForExecution(t)}async run(t){this.liveAppPage=t,await this.applyRouteInterceptorsIfNecessary(),await this.createServer(),this.startRunner()}async applyRouteInterceptorsIfNecessary(){var r,a,o,c,f,_;if(!((o=(a=(r=this.checksumConfig.options)==null?void 0:r.modelConfig)==null?void 0:a.browserArgs)!=null&&o.skipDisableWebSecurity)&&!((f=(c=this.checksumConfig.options)==null?void 0:c.modelConfig)!=null&&f.skipCompleteOriginHeaderOnDisableWebSecurity))try{await((_=this.liveAppPage)==null?void 0:_.route("**/*",async(v,C)=>this.routeInterceptor.intercept(v,C,{page:this.liveAppPage},{completeOriginHeader:!0})))}catch(v){tf.error("[WebDriver] applyRouteInterceptors error",v)}}startRunner(){let t=V0.isRepoMode?"yarn vtg-pw-bridge":`ts-node ${(0,aEi.join)(__dirname,"vtg-pw-bridge-runner.js")}`;Yes(t,{CHECKSUM_PORT:this.port.toString(),CHECKSUM_CONFIG:JSON.stringify(this.checksumConfig)})}async createServer(){this.server=(0,Dhn.createServer)(t=>{t.on("data",async r=>{try{await this.messageParser.onMessage(t,r)}catch(a){t.write(JSON.stringify({err:a.message}))}}),t.on("end",()=>{}),t.on("error",r=>{}),this.connectToVTG()}),this.port=await this.acquirePortNumber(),this.server.listen(this.port,()=>tf.info(`VTG PW Bridge Server listening on port ${this.port}...`))}serializedErr(t){return t&&JSON.stringify(t,Object.getOwnPropertyNames(t))}async connectToVTG(){tf.info("[VTG PW Bridge] Connecting to VTG...");let t=e(r=>r.frames().find(a=>a.name()==="time-machine-iframe"),"findTimeMachineIframe");this.vtgPage=await this.connectToPage("VTG page",V0.vtg.vtgRemoteDebuggingPort,r=>r.find(a=>t(a))),this.vtgTimeMachineFrame=t(this.vtgPage),this.taskTimeMachinePage=await this.connectToPage("Task Time Machine page",V0.vtg.taskTimeMachine.debugPort,r=>r[0]),tf.info("[VTG PW Bridge] Connected to VTG."),this.isReady=!0,this.isReadyResolve()}async connectToPage(t,r,a){return Shn("Playwright via Bridge",t,r,a,{preventDialogFromAutoDismissing:!0})}async acquirePortNumber(){return await new Promise((t,r)=>{let a=(0,Dhn.createServer)();a.unref(),a.on("error",r),a.listen(0,()=>{let o=a.address().port;a.close(()=>{t(o)})})})}async listenForExecution(t){return new Promise(r=>{this.resolveEvaluator=r,this.listener=t})}stopListening(){var t;(t=this.resolveEvaluator)==null||t.call(this)}buildContext(t){let{frame:r,expectConfig:a}=t,o={};switch(r){case"task-time-machine":o.page=this.taskTimeMachinePage.frameLocator("iframe");break;case"vtg-time-machine":o.page=this.vtgTimeMachineFrame.frameLocator("iframe");break;case"live":default:break}return a&&(o.expect=Jbe.expect.configure(a)),o}wrapCodeInContext(t,r){return`(async ({${Object.keys(r).join(", ")}}) => { ${t} })`}async execute(t){this.isReady||tf.warning("[VTG PW Bridge] Execute called before ready"),await this.isReadyPromise;let{id:r,code:a,options:o}=t,c=this.buildContext(o),f=this.wrapCodeInContext(a,c)+"(context)";return new Promise(_=>{this.listener&&this.listener(f,c,(v,C)=>{_({id:r,err:v,result:C})})})}};e(Thn,"VtgPwBridge");var drr=Thn;async function Yes(i,t={}){let r={...process.env,...t};(0,iEi.spawn)(i,{env:r,shell:!0,stdio:["inherit","inherit","inherit"],detached:!1}).on("exit",o=>{process.exit(o)})}e(Yes,"spawnCmd");var PEi=require("@playwright/test"),FEi=sf(IEi());var lae=class lae{constructor(t){this.options=t;this.importPluginPackages()}importPluginPackages(){lae.pw??(lae.pw=vht()),lae.StealthPlugin??(lae.StealthPlugin=require("puppeteer-extra-plugin-stealth"))}static createFreshInstance(){try{let{addExtra:t}=vht(),r=t(lae.pw.chromium);return console.log("[StealthProvider] Created fresh playwright-extra instance for testing"),r}catch(t){throw console.error("[StealthProvider] Error creating fresh instance:",t),t}}buildChromiumWithPlugins(t){let{project:r}=this.options,a=r.use.userAgent,o=r.use.playwrightExtra||[],c=lae.StealthPlugin();if(o.push(c),this.isCustomUserAgent(a)){c.enabledEvasions.delete("user-agent-override");let v=require("puppeteer-extra-plugin-stealth/evasions/user-agent-override")({userAgent:a});o.push(v)}let f=t??lae.pw.chromium;return o.forEach((_,v)=>{try{!(_ instanceof FEi.PuppeteerExtraPlugin)&&_!==c&&console.warn(`Plugin at index ${v} in the project's checksum.config.ts file is not an instance of PuppeteerExtraPlugin.`),f.use(_)}catch(C){console.warn(C)}}),f}isCustomUserAgent(t){return t?!Object.values(PEi.devices).some(r=>t===r.userAgent):!1}};e(lae,"StealthProvider");var hrr=lae;Mjt();function NEi(i,t){return{testSuiteRunId:t,appName:"generic-app",commitHash:"generic-commit-hash",envName:"generic-env-name",branch:"generic-branch",checksumRuntimeVersion:i}}e(NEi,"createDefaultTestSuiteRunInfo");var BEi=require("crypto");UVr();var N3e=class N3e{constructor(t,r){this.context=t;this.isVTG=r;this._pages={};this._pagesInProgress=new Map;this._testAssets=null;this.pageGuidMap=new WeakMap;this.instanceId=++N3e.instanceCounter,this.setContextProxy()}static makeContext(t,r){return new N3e(t,r).proxy}_rawContext(){return this.context}setTestAssets(t){this._testAssets=t,this.setupPageListener()}getTestAssets(){return this._testAssets}cleanup(){this._pagesInProgress.clear(),this._pages={}}async newPage(){let t=await this.context.newPage();return await this.makePage(t)}async makePage(t){if(t._isChecksumPage===!0)return t;let r=this.getPageGuid(t);if(this.hasPage(r))return this.getPageByGuid(r);if(this._pagesInProgress.has(r))return this._pagesInProgress.get(r);let a=this._createPageInstance(t);this._pagesInProgress.set(r,a);try{let o=await a;return this._pagesInProgress.delete(r),this.addPage(o),o}catch(o){throw this._pagesInProgress.delete(r),o}}addPage(t){let r=this.getPageGuid(t);this._pages[r]=t,t.once("close",()=>{this.removePage(r)})}removePage(t){this._pages[t]&&delete this._pages[t]}async _createPageInstance(t){if(this._testAssets)try{return await vzt.init(t,this.proxy,this._testAssets.testRunAnalytics,this._testAssets.monitorBridge,this._testAssets.variableStore,this._testAssets.testInfo,this._testAssets.checksumTestId,this._testAssets.test,this._testAssets.config,this._testAssets.isReplMode)}catch(r){throw new Error(`Failed to initialize RuntimePage: ${r instanceof Error?r.message:String(r)}. Test assets must be properly configured.`)}throw new Error("Cannot create page: Test assets not set. Use setTestAssets() before creating pages.")}setContextProxy(){this.proxy=new Proxy(this,{get:e(function(r,a){return r.getContextMethod(a)},"get")})}setupPageListener(){this.context.on("page",async t=>{try{await this.makePage(t)}catch(r){throw console.error("[ChecksumBrowserContext] Failed to initialize page created by application:",r),r}})}getPageGuid(t){let r=this.pageGuidMap.get(t);return r||(r=`page@checksumctx_${this.instanceId}_${++N3e.guidCounter}`,this.pageGuidMap.set(t,r)),r}getPageByGuid(t){return this._pages[t]}hasPage(t){return t in this._pages}getAllPages(){return Object.values(this._pages)}getContextMethod(t){if(t in this){let a=this[t];return typeof a=="function"?a.bind(this):a}let r=this.context[t];return typeof r=="function"?r.bind(this.context):r}pages(){return this.getAllPages()}getPage(t){let r=this.getAllPages(),a=r[t];if(!a)throw new Error(`Page with index ${t} not found. Total pages: ${r.length}`);return a}};e(N3e,"ChecksumBrowserContext"),N3e.instanceCounter=0,N3e.guidCounter=0;var grr=N3e;var Nhn={},pZe=!!process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG,REi=e((i,t,r={},a=!1)=>{let{runMode:o,environments:c}=t,f=c.find(v=>v.default),_=i.extend({baseURL:f.baseURL,bypassCSP:!0,...pZe?{trace:"off",video:"off",screenshot:"off",ignoreHTTPSErrors:!0}:{},permissions:e(async({},v,C)=>{if(!pZe)await v(C.project.use.permissions);else{let w=new Set(C.project.use.permissions);w.add("clipboard-read"),w.add("clipboard-write"),w.add("camera"),w.add("storage-access"),w.add("notifications"),w.add("geolocation"),w.add("microphone"),await v(Array.from(w))}},"permissions"),proxy:e(async({proxy:v},C)=>{v?await C({...v,bypass:"127.0.0.1,localhost"}):await C(v)},"proxy"),browser:e(async({browser:v,browserName:C,launchOptions:w},T,k)=>{let R=e(()=>(k.project.use.playwrightExtra||[]).some(X=>X.constructor.name==="StealthPlugin"),"checkIfStealthPluginExists"),B=e(async()=>{let W=await(await new hrr({project:k.project}).buildChromiumWithPlugins()).launch(w);await T(W)},"launchBrowserWithStealthPlugin");pZe?V0.vtg.isSeparateProcess?await T(v):R()?(console.log("StealthPlugin already configured"),await T(v)):await B():V0.useRemoteDebugging.enabled&&R()?await B():await T(v)},"browser"),launchOptions:e(async({launchOptions:v},C)=>{var k;let w=v!=null&&v.args?[...v.args]:[],T=e(R=>{w.includes(R)||w.push(R)},"pushArg");if(r.useMockData&&T("--disable-web-security"),V0.bypassProxyForLocalhost&&T("--proxy-bypass-list=localhost,127.0.0.1"),pZe){T("--proxy-bypass-list=localhost,127.0.0.1"),V0.vtg.isSeparateProcess&&T(`--remote-debugging-port=${V0.vtg.appRemoteDebuggingPort}`);let R=((k=r.modelConfig)==null?void 0:k.browserArgs)??{};R.skipDisableWebSecurity||T("--disable-web-security"),R.skipAllowFileAccessFromFiles||T("--allow-file-access-from-files"),R.skipDisableSiteIsolationTrials||T("--disable-site-isolation-trials"),R.skipAllowRunningInsecureContent||T("--allow-running-insecure-content")}V0.useRemoteDebugging.enabled&&T(`--remote-debugging-port=${V0.useRemoteDebugging.port}`),await C({...v,args:w})},"launchOptions"),variableStore:e(async({},v)=>{let C=new yWe;await v(C)},"variableStore"),vs:e(async({variableStore:v},C)=>{await C(v)},"vs"),variablesStore:e(async({variableStore:v},C)=>{await C(v)},"variablesStore"),testRunAnalytics:e(async({},v,C)=>{let w=(()=>{try{if(process.env.CHECKSUM_TEST_SUITE_INFO)return JSON.parse(process.env.CHECKSUM_TEST_SUITE_INFO);throw new Error("Missing Checksum test suite info")}catch{return console.warn("\u26A0\uFE0F Warning: It seems like you ran the test suite directly via Playwright. This can lead to degraded functionality and unexpected issues. To ensure a fully supported and stable test run, please use: 'npx checksumai test'."),NEi("playwright-run-version-unknown",(0,BEi.randomUUID)())}})(),T=OEi(C),k=rie.getTestRunInstance({...w,checksumTestId:T},process.env.CHECKSUM_ISOLATED_MODE==="true",C);await v(k)},"testRunAnalytics"),monitorBridge:[async({},v,C)=>{let w=new wzt(C);await v(w)},{scope:"worker"}],context:e(async({context:v,monitorBridge:C,variableStore:w,testRunAnalytics:T},k,R)=>{let B=grr.makeContext(v,pZe);B.setTestAssets({testRunAnalytics:T,monitorBridge:C,variableStore:w,testInfo:R,checksumTestId:OEi(R),test:_,config:t,isReplMode:a}),await k(B),B.cleanup()},"context"),page:e(async({page:v,context:C},w,T)=>{let k=await C.makePage(v);Object.defineProperty(k.constructor,"name",{value:"Page"}),await w(k),k&&typeof k.onTestComplete=="function"&&await k.onTestComplete(T.status==="passed"),k&&typeof k.shutdown=="function"&&await k.shutdown()},"page"),vtg:e(async({page:v},C)=>{if(!pZe)C(null);else if(V0.vtg.isSeparateProcess){let w=new drr(t);await w.run(v),await C(w)}else{let w=new frr(["--test-file"],!1,t);await w.run(v),await C(w)}},"vtg")});return{test:_,defineChecksumTest:dts}},"createChecksumTestExtension"),dts=e((i,t,r)=>{let o=new Error().stack.split(`
|
|
2043
|
+
`)}async run(r){await this.init(r),this.buildServices(r),this.buildServer(),await this.loadIfNecessary(),await this.start()}async loadIfNecessary(){let r=await this.getInitialServicesData();r&&(this.actionsManager.setActions(r.actions),this.testAssetsManager.setCurrentSaveAsLocation(this.editLocationPath),this.storyId=r.storyId,r.testGenerationData&&this.userStoryService.setTestGenerationData(r.testGenerationData))}async init(r){tf.info(`Initializing VTG with runtime version ${this.checksumRuntimeVersion}...`),await this.patchPlaywright(),this.loadPlaywrightConfigForVTG(),this.webDriver=this.buildWebDriver(r),this.webDriver.registerEventListener(this),this.taskTimeMachine=new cbe(this.webDriver.frameMsgBroker,this.webDriver.injectedScriptManager,{headless:!V0.vtg.taskTimeMachine.showTaskTimeMachine,timestampBatchingEnabled:!1,sortByTimestamp:!0,taskTimeout:V0.vtg.taskTimeMachine.taskTimeout,debugPort:V0.vtg.isSeparateProcess?V0.vtg.taskTimeMachine.debugPort:void 0,frameMsgBrokerRegisterName:"task-time-machine",logPerformance:V0.vtg.taskTimeMachine.logPerformance,webProxy:this.getPlaywrightProxySettings()}),this.pageInteractor=new wve(this.webDriver.evaluateWithChecksum.bind(this.webDriver),()=>this.webDriver.appMainFrame,this.webDriver.getTimeMachine.bind(this.webDriver),{log:e((a,...o)=>o!=null&&o.length?tf.info(a,...o):tf.info(a),"log"),logError:e((a,...o)=>o!=null&&o.length?tf.error(a,...o):tf.error(a),"logError")},{...this.getTimeoutParams(),waitActionDelay:1e3,testAssetsDir:__dirname,listenToDialog:!0,listenToFileChooser:!1},new iVe(this.checksumConfig)),this.testAssetsManager=new cGt(this.projectRootDirectory,this.checksumRoot,this.vtgInternalFilesDir,this.vtgTestFileRunConfig)}buildServices(r){this.actionsManager=new BWt,this.settingsService=new sgt(this.checksumRoot,this.apiService,this.vtgInternalFilesDir),this.apiService=new Y_t(this.checksumConfig),this.settingsService=new sgt(this.checksumRoot,this.apiService),this.userStoryService=new G_t(this.apiService,this.checksumConfig),this.variableStoreService=new hGt,this.evaluatorService=new yGt(this.variableStoreService,this.settingsService,this.vtgTestFileMode,r,this.port),this.actionsService=new dJt(this.checksumConfig,this.checksumRoot,this.pageInteractor,this.apiService,this.userStoryService,this.actionsManager,this.testAssetsManager,this.webDriver,this.evaluatorService,this.vtgInternalFilesDir),this.assertionsService=new AJt(this.webDriver,this.actionsManager,this.evaluatorService),this.locatorsService=new FJt(this.webDriver,this.taskTimeMachine,this.apiService,this.userStoryService,this.evaluatorService),this.aiTestGenerationService=new _Jt(this.webDriver,this.pageInteractor,this.actionsService,this.actionsManager,this.apiService,this.userStoryService),this.aiAssertionsService=new xJt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver,this.evaluatorService,{logPerformance:V0.vtg.aiAssertions.logPerformance}),this.aiThoughtsService=new _Gt(this.actionsManager,this.apiService,this.userStoryService,this.taskTimeMachine,this.webDriver),this.storageService=new OWt(this.checksumConfig,this.userStoryService,this.apiService,this.actionsManager,this.testAssetsManager,this.actionsService,this.vtgTestFileRunConfig,this.evaluatorService,this.settingsService,this.taskTimeMachine),this.actionsManager.setStorageService(this.storageService),this.monacoService=new bGt,this.aiChatService=new prr(this.taskTimeMachine,this.evaluatorService)}buildServer(){this.reactAppServer=new oGt(this.actionsService,this.assertionsService,this.locatorsService,this.aiTestGenerationService,this.aiAssertionsService,this.aiThoughtsService,this.actionsManager,this.storageService,this.settingsService,this.monacoService,this.evaluatorService,this.aiChatService)}loadPlaywrightConfigForVTG(){try{let r=`${this.checksumRoot}/playwright.config.ts`;if((0,F3e.existsSync)(r)){let a=require(r).default;a&&(this.playwrightConfigForVTG=a)}}catch{tf.warning("Could not find playwright config file, will run with defaults")}}async getInitialServicesData(){switch(this.vtgMode){case"cloud":return this.getInitialServicesDataFromCloud();case"edit":return this.vtgTestFileMode?await this.getInitialServicesDataForEditedFile():this.getInitialServicesDataFromJSON("local");case"start":if(this.vtgTestFileRunConfig.restoreFromAutoSave)return this.getInitialServicesDataFromJSON("auto-save")}}getInitialServicesDataFromJSON(r){let a=this.storageService.getLocalSavedJSONFilePath(r,this.storyId),o=this.storageService.readLocalSavedDataFromJSONFile(a);if(!o)throw new Error(`No data found in ${r} while reading from ${a}`);return{actions:o.executedActions,storyId:o.story.id}}async getInitialServicesDataFromCloud(){let a=await(await this.apiService.post(`test-generation/${this.cloudTestGenerationId}/info`)).json(),{actionsDownloadSignedURL:o}=a,c=await fetch(o,{mode:"cors",credentials:"same-origin",headers:{"Content-Type":"application/json"}});if(!c.ok)throw new Error(`HTTP error! Status: ${c.status}`);let f=await c.json();return{actions:this.initializeTestStepsWithIds(f),storyId:a.story.id}}initializeTestStepsWithIds(r){return r.map((a,o)=>({...a,id:(0,Chn.randomUUID)(),assertions:(a.assertions??[]).map(c=>({...c,id:(0,Chn.randomUUID)()}))}))}async getInitialServicesDataForEditedFile(){var a,o,c,f,_,v,C;if(((a=this.vtgTestFileRunConfig)==null?void 0:a.mode)!=="edit")return;let r=[];if(!this.vtgTestFileRunConfig.restoreFromAutoSave){let w=(o=this.vtgTestFileRunConfig)==null?void 0:o.actionsJsonFilePath;r=this.storageService.readJsonFile(w),(0,F3e.rmSync)(w,{force:!0}),r=this.initializeTestStepsWithIds(r)}if((c=this.vtgTestFileRunConfig)!=null&&c.internalTestId)try{let w=await this.apiService.post(`test-generation-by-internal-test-id/${(f=this.vtgTestFileRunConfig)==null?void 0:f.internalTestId}/info`);if(!w.ok){let k=w.statusText;try{let R=await w.text();try{k=JSON.parse(R).message||R||w.statusText}catch{k=R||w.statusText}}catch{k="Test id not found or invalid"}throw new Error(`Error fetching test generation data: ${k}`)}let T=await w.json();if(this.vtgTestFileRunConfig.restoreFromAutoSave){let k=this.storageService.getLocalSavedJSONFilePath("auto-save"),R=this.storageService.readLocalSavedDataFromJSONFile(k);if(!R)throw new Error(`No data found in auto-save while reading from ${k}`);r=R==null?void 0:R.executedActions}return{actions:r,storyId:T.story.id,testGenerationData:T.testGenerationData}}catch{tf.warning(`Could not find data matching internal test id: ${(_=this.vtgTestFileRunConfig)==null?void 0:_.internalTestId}`)}if((v=this.vtgTestFileRunConfig)!=null&&v.storyId)return{actions:r,storyId:(C=this.vtgTestFileRunConfig)==null?void 0:C.storyId};throw new Error("Cannot edit file without either valid internal test id or story id")}async start({createAssetsFolder:r=!0}={}){var o,c;await this.userStoryService.fetchStory(this.storyId),r&&this.testAssetsManager.createTestAssetsFolders(),this.testAssetsManager.createTestGenerationLocalAutoSaveFolder(),await this.reactAppServer.start();let{environment:a}=this.userStoryService.getEnvInfo();await this.webDriver.prepare({baseURL:a.baseURL,shutdown:!this.vtgTestFileMode},{serverPort:await this.reactAppServer.getPort()}),V0.vtg.writeLogFile&&this.setupFrontendLogging(this.webDriver.page),await this.webDriver.page.evaluate(()=>{"checksumRRWeb"in window&&console.log(`Using forked rrweb. ${JSON.stringify(window.checksumRRWeb)}`)}),await this.webDriver.addHARMockAPIRecordings(this.testAssetsManager.getHarFilePath()),await this.initTimeMachine(),this.pageInteractor.init(),this.assertionsService.setPage(this.webDriver.appMainFrame.page()),this.actionsService.setPage(this.webDriver.appMainFrame.page()),this.evaluatorService.setPage(this.webDriver.appMainFrame.page()),this.aiChatService.setPage(this.webDriver.appMainFrame.page()),await this.taskTimeMachine.prepare(this.webDriver.appMainFrame,void 0,f=>this.webDriver.registerTimeMachineFrame(f)),await this.reactAppServer.evaluateServerPort(this.webDriver.page),await this.webDriver.appMainFrame.goto("about:blank",{waitUntil:"domcontentloaded",timeout:0}),await this.webDriver.getTimeMachine().toggleTimeMachineHandleEvents(!1),this.vtgMode==="start"&&!this.vtgTestFileRunConfig.restoreFromAutoSave&&(await this.actionsService.addInitialLoginAction(),await this.actionsService.addStartURLNavigationAction(),this.vtgTestFileMode&&await this.storageService.saveTestFile()),tf.info("VTG is ready with story:",{goal:(o=this.userStoryService.getStory())==null?void 0:o.goal}),await this.webDriver.page.evaluate(({localSaveFolderPath:f,stepsData:_,appViewport:v,userStoryGoal:C,isLoadedFromFile:w})=>{window.vtg.initClient(f,_,v,this.checksumRuntimeVersion,C,w)},{localSaveFolderPath:this.editLocationPath,stepsData:await this.actionsManager.buildStepDataWithCode(this.actionsManager.actions,{loadingFromFile:["edit","cloud"].includes(this.vtgMode)}),appViewport:this.webDriver.getApplicationViewport(),userStoryGoal:(c=this.userStoryService.getStory())==null?void 0:c.goal,isLoadedFromFile:this.vtgTestFileMode}),this.vtgTestFileMode||await new Promise(()=>{})}getTimeoutParams(){var o,c,f,_;let r=((c=(o=this.playwrightConfigForVTG)==null?void 0:o.use)==null?void 0:c.navigationTimeout)||3e4,a=((_=(f=this.playwrightConfigForVTG)==null?void 0:f.use)==null?void 0:_.actionTimeout)||5e3;return{navigationTimeout:r,actionTimeout:a}}getPlaywrightProxySettings(){var f,_;let r=(_=(f=this.playwrightConfigForVTG)==null?void 0:f.use)==null?void 0:_.proxy,{server:a,username:o,password:c}=r||{};if(o&&c&&a)return{username:o,password:c,server:a}}getPlaywrightViewportSettings(){var o,c;let{width:r=1280,height:a=720}=((c=(o=this.playwrightConfigForVTG)==null?void 0:o.use)==null?void 0:c.viewport)||{};return{width:r,height:a}}buildWebDriver(r){var c,f,_,v,C,w;let a=this.getPlaywrightProxySettings(),o=this.getPlaywrightViewportSettings();return new fGt({scriptSource:V0.checksumScript.source,scriptURL:V0.checksumScript.url,scriptFile:V0.checksumScript.path,isScriptFileAbsolute:!0,fullScreenResolution:!1,hostWindowViewport:!0,baseURL:(c=this.checksumConfig.environments.find(T=>T.default))==null?void 0:c.baseURL,useProxy:!!a,webProxy:a,disableWebSecurity:!0,allowFileAccess:!0,remoteDebugging:V0.vtg.remoteDebugging,remoteDebuggingPort:V0.vtg.vtgRemoteDebuggingPort},{devtools:!1,headless:V0.CI},{frontendAppSpecificRules:{},frontendTestGenerationConfig:{logPrefix:"$checksum"},viewport:o,completeOriginHeaderOnLivePage:!V0.vtg.isSeparateProcess&&!((v=(_=(f=this.checksumConfig.options)==null?void 0:f.modelConfig)==null?void 0:_.browserArgs)!=null&&v.skipDisableWebSecurity)&&!((w=(C=this.checksumConfig.options)==null?void 0:C.modelConfig)!=null&&w.skipCompleteOriginHeaderOnDisableWebSecurity)},r)}async onWebDriverContextClose(){var r,a,o;this.evaluatorService.stopListening(),(r=this.vtgTestFileRunConfig)!=null&&r.evalFilePath&&(0,F3e.rmSync)((a=this.vtgTestFileRunConfig)==null?void 0:a.evalFilePath,{force:!0}),this.vtgTestFileRunConfig.mode==="edit"&&(0,F3e.rmSync)((o=this.vtgTestFileRunConfig)==null?void 0:o.actionsJsonFilePath,{force:!0})}initializeAccordingToVTGMode(r){var c;let a=r.indexOf("--edit"),o=r.indexOf("--cloud");if(r.indexOf("--test-file")!==-1){this.vtgTestFileMode=!0,this.vtgTestFileRunConfig=JSON.parse(process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG),this.vtgMode=this.vtgTestFileRunConfig.mode,this.storyId=((c=this.vtgTestFileRunConfig)==null?void 0:c.mode)==="start"?this.vtgTestFileRunConfig.storyId:void 0;return}a!==-1&&(this.vtgMode="edit",this.editLocationPath=r[a+1]),o!==-1&&(this.vtgMode="cloud",this.cloudTestGenerationId=r[o+1]),this.vtgMode==="start"&&(this.storyId=r[0])}getWebDriver(){return this.webDriver}async eval(r){return this.evaluatorService.listenForExecution(r)}};e(whn,"VisualTestGenerator");var frr=whn;Eve();var iEi=require("child_process"),Dhn=require("net");vT();var aEi=require("path");v7();var nEi=sf(vht());fQ();var Shn=e(async(i,t,r,a,o={})=>{let{preventDialogFromAutoDismissing:c=!1,retry:f=!0,maxRetries:_=void 0,numberOfRetries:v=0}=o;try{console.log(`${i} attempting to connect to ${t} on port ${r}...`);let w=(await nEi.chromium.connectOverCDP("http://127.0.0.1:"+r)).contexts()[0],T=a(w.pages());for(;!T;)await TA(1e3),T=a(w.pages());return console.log(`${i} is connected to ${t} on port ${r}`,T.url()),c&&bzt(T),T}catch(C){if(!f||_&&v>=_)throw console.error(`${i} failed to connect to ${t}, retries were exhausted or disabled`,C),C;return console.log(`${i} is waiting and retrying connection to ${t} on port ${r}...`),await TA(1e3),Shn(i,t,r,a,{...o,numberOfRetries:v+1})}},"connectToPage");qw();var Thn=class Thn{constructor(t){this.checksumConfig=t;this.isReady=!1;this.onMessage=e(async(t,r)=>{let{id:a,err:o,result:c}=await this.execute(t);r.write(this.messageParser.makeMessage(JSON.stringify({id:a,err:this.serializedErr(o),result:c})))},"onMessage");this.messageParser=new BGe(this.onMessage),this.isReadyPromise=new Promise(r=>{this.isReadyResolve=r}),this.routeInterceptor=new qWe({completeOriginHeader:!0})}async eval(t){return this.listenForExecution(t)}async run(t){this.liveAppPage=t,await this.applyRouteInterceptorsIfNecessary(),await this.createServer(),this.startRunner()}async applyRouteInterceptorsIfNecessary(){var r,a,o,c,f,_;if(!((o=(a=(r=this.checksumConfig.options)==null?void 0:r.modelConfig)==null?void 0:a.browserArgs)!=null&&o.skipDisableWebSecurity)&&!((f=(c=this.checksumConfig.options)==null?void 0:c.modelConfig)!=null&&f.skipCompleteOriginHeaderOnDisableWebSecurity))try{await((_=this.liveAppPage)==null?void 0:_.route("**/*",async(v,C)=>this.routeInterceptor.intercept(v,C,{page:this.liveAppPage},{completeOriginHeader:!0})))}catch(v){tf.error("[WebDriver] applyRouteInterceptors error",v)}}startRunner(){let t=V0.isRepoMode?"yarn vtg-pw-bridge":`ts-node ${(0,aEi.join)(__dirname,"vtg-pw-bridge-runner.js")}`;Yes(t,{CHECKSUM_PORT:this.port.toString(),CHECKSUM_CONFIG:JSON.stringify(this.checksumConfig)})}async createServer(){this.server=(0,Dhn.createServer)(t=>{t.on("data",async r=>{try{await this.messageParser.onMessage(t,r)}catch(a){t.write(JSON.stringify({err:a.message}))}}),t.on("end",()=>{}),t.on("error",r=>{}),this.connectToVTG()}),this.port=await this.acquirePortNumber(),this.server.listen(this.port,()=>tf.info(`VTG PW Bridge Server listening on port ${this.port}...`))}serializedErr(t){return t&&JSON.stringify(t,Object.getOwnPropertyNames(t))}async connectToVTG(){tf.info("[VTG PW Bridge] Connecting to VTG...");let t=e(r=>r.frames().find(a=>a.name()==="time-machine-iframe"),"findTimeMachineIframe");this.vtgPage=await this.connectToPage("VTG page",V0.vtg.vtgRemoteDebuggingPort,r=>r.find(a=>t(a))),this.vtgTimeMachineFrame=t(this.vtgPage),this.taskTimeMachinePage=await this.connectToPage("Task Time Machine page",V0.vtg.taskTimeMachine.debugPort,r=>r[0]),tf.info("[VTG PW Bridge] Connected to VTG."),this.isReady=!0,this.isReadyResolve()}async connectToPage(t,r,a){return Shn("Playwright via Bridge",t,r,a,{preventDialogFromAutoDismissing:!0})}async acquirePortNumber(){return await new Promise((t,r)=>{let a=(0,Dhn.createServer)();a.unref(),a.on("error",r),a.listen(0,()=>{let o=a.address().port;a.close(()=>{t(o)})})})}async listenForExecution(t){return new Promise(r=>{this.resolveEvaluator=r,this.listener=t})}stopListening(){var t;(t=this.resolveEvaluator)==null||t.call(this)}buildContext(t){let{frame:r,expectConfig:a}=t,o={};switch(r){case"task-time-machine":o.page=this.taskTimeMachinePage.frameLocator("iframe");break;case"vtg-time-machine":o.page=this.vtgTimeMachineFrame.frameLocator("iframe");break;case"live":default:break}return a&&(o.expect=Jbe.expect.configure(a)),o}wrapCodeInContext(t,r){return`(async ({${Object.keys(r).join(", ")}}) => { ${t} })`}async execute(t){this.isReady||tf.warning("[VTG PW Bridge] Execute called before ready"),await this.isReadyPromise;let{id:r,code:a,options:o}=t,c=this.buildContext(o),f=this.wrapCodeInContext(a,c)+"(context)";return new Promise(_=>{this.listener&&this.listener(f,c,(v,C)=>{_({id:r,err:v,result:C})})})}};e(Thn,"VtgPwBridge");var drr=Thn;async function Yes(i,t={}){let r={...process.env,...t};(0,iEi.spawn)(i,{env:r,shell:!0,stdio:["inherit","inherit","inherit"],detached:!1}).on("exit",o=>{process.exit(o)})}e(Yes,"spawnCmd");var PEi=require("@playwright/test"),FEi=sf(IEi());var lae=class lae{constructor(t){this.options=t;this.importPluginPackages()}importPluginPackages(){lae.pw??(lae.pw=vht()),lae.StealthPlugin??(lae.StealthPlugin=require("puppeteer-extra-plugin-stealth"))}static createFreshInstance(){try{let{addExtra:t}=vht(),r=t(lae.pw.chromium);return console.log("[StealthProvider] Created fresh playwright-extra instance for testing"),r}catch(t){throw console.error("[StealthProvider] Error creating fresh instance:",t),t}}buildChromiumWithPlugins(t){let{project:r}=this.options,a=r.use.userAgent,o=r.use.playwrightExtra||[],c=lae.StealthPlugin();if(o.push(c),this.isCustomUserAgent(a)){c.enabledEvasions.delete("user-agent-override");let v=require("puppeteer-extra-plugin-stealth/evasions/user-agent-override")({userAgent:a});o.push(v)}let f=t??lae.pw.chromium;return o.forEach((_,v)=>{try{!(_ instanceof FEi.PuppeteerExtraPlugin)&&_!==c&&console.warn(`Plugin at index ${v} in the project's checksum.config.ts file is not an instance of PuppeteerExtraPlugin.`),f.use(_)}catch(C){console.warn(C)}}),f}isCustomUserAgent(t){return t?!Object.values(PEi.devices).some(r=>t===r.userAgent):!1}};e(lae,"StealthProvider");var hrr=lae;Mjt();function NEi(i,t){return{testSuiteRunId:t,appName:"generic-app",commitHash:"generic-commit-hash",envName:"generic-env-name",branch:"generic-branch",checksumRuntimeVersion:i}}e(NEi,"createDefaultTestSuiteRunInfo");var BEi=require("crypto");UVr();var N3e=class N3e{constructor(t,r){this.context=t;this.isVTG=r;this._pages={};this._pagesInProgress=new Map;this._testAssets=null;this.pageGuidMap=new WeakMap;this.instanceId=++N3e.instanceCounter,this.setContextProxy()}static makeContext(t,r){return new N3e(t,r).proxy}_rawContext(){return this.context}setTestAssets(t){this._testAssets=t,this.setupPageListener()}getTestAssets(){return this._testAssets}cleanup(){this._pagesInProgress.clear(),this._pages={}}async newPage(){let t=await this.context.newPage();return await this.makePage(t)}async makePage(t){if(t._isChecksumPage===!0)return t;if(t.isClosed())throw new Error("Cannot initialize closed page");let r=this.getPageGuid(t);if(this.hasPage(r))return this.getPageByGuid(r);if(this._pagesInProgress.has(r))return this._pagesInProgress.get(r);let a=this._createPageInstance(t);this._pagesInProgress.set(r,a);try{let o=await a;return this._pagesInProgress.delete(r),this.addPage(o),o}catch(o){throw this._pagesInProgress.delete(r),o}}addPage(t){let r=this.getPageGuid(t);this._pages[r]=t,t.once("close",()=>{this.removePage(r)})}removePage(t){this._pages[t]&&delete this._pages[t]}async _createPageInstance(t){if(t.isClosed())throw new Error("Cannot initialize page: Page has already been closed");if(this._testAssets)try{return await vzt.init(t,this.proxy,this._testAssets.testRunAnalytics,this._testAssets.monitorBridge,this._testAssets.variableStore,this._testAssets.testInfo,this._testAssets.checksumTestId,this._testAssets.test,this._testAssets.config,this._testAssets.isReplMode)}catch(r){throw new Error(`Failed to initialize RuntimePage: ${r instanceof Error?r.message:String(r)}. Test assets must be properly configured.`)}throw new Error("Cannot create page: Test assets not set. Use setTestAssets() before creating pages.")}setContextProxy(){this.proxy=new Proxy(this,{get:e(function(r,a){return r.getContextMethod(a)},"get")})}setupPageListener(){this.context.on("page",async t=>{try{if(t.isClosed())return;await this.makePage(t)}catch(r){let a=r instanceof Error?r.message:String(r);if(a.includes("Page has already been closed")||a.includes("Target page, context or browser has been closed")){console.debug("[ChecksumBrowserContext] Skipping initialization of closed page");return}throw console.error("[ChecksumBrowserContext] Failed to initialize page created by application:",r),r}})}getPageGuid(t){let r=this.pageGuidMap.get(t);return r||(r=`page@checksumctx_${this.instanceId}_${++N3e.guidCounter}`,this.pageGuidMap.set(t,r)),r}getPageByGuid(t){return this._pages[t]}hasPage(t){return t in this._pages}getAllPages(){return Object.values(this._pages)}getContextMethod(t){if(t in this){let a=this[t];return typeof a=="function"?a.bind(this):a}let r=this.context[t];return typeof r=="function"?r.bind(this.context):r}pages(){return this.getAllPages()}getPage(t){let r=this.getAllPages(),a=r[t];if(!a)throw new Error(`Page with index ${t} not found. Total pages: ${r.length}`);return a}};e(N3e,"ChecksumBrowserContext"),N3e.instanceCounter=0,N3e.guidCounter=0;var grr=N3e;var Nhn={},pZe=!!process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG,REi=e((i,t,r={},a=!1)=>{let{runMode:o,environments:c}=t,f=c.find(v=>v.default),_=i.extend({baseURL:f.baseURL,bypassCSP:!0,...pZe?{trace:"off",video:"off",screenshot:"off",ignoreHTTPSErrors:!0}:{},permissions:e(async({},v,C)=>{if(!pZe)await v(C.project.use.permissions);else{let w=new Set(C.project.use.permissions);w.add("clipboard-read"),w.add("clipboard-write"),w.add("camera"),w.add("storage-access"),w.add("notifications"),w.add("geolocation"),w.add("microphone"),await v(Array.from(w))}},"permissions"),proxy:e(async({proxy:v},C)=>{v?await C({...v,bypass:"127.0.0.1,localhost"}):await C(v)},"proxy"),browser:e(async({browser:v,browserName:C,launchOptions:w},T,k)=>{let R=e(()=>(k.project.use.playwrightExtra||[]).some(X=>X.constructor.name==="StealthPlugin"),"checkIfStealthPluginExists"),B=e(async()=>{let W=await(await new hrr({project:k.project}).buildChromiumWithPlugins()).launch(w);await T(W)},"launchBrowserWithStealthPlugin");pZe?V0.vtg.isSeparateProcess?await T(v):R()?(console.log("StealthPlugin already configured"),await T(v)):await B():V0.useRemoteDebugging.enabled&&R()?await B():await T(v)},"browser"),launchOptions:e(async({launchOptions:v},C)=>{var k;let w=v!=null&&v.args?[...v.args]:[],T=e(R=>{w.includes(R)||w.push(R)},"pushArg");if(r.useMockData&&T("--disable-web-security"),V0.bypassProxyForLocalhost&&T("--proxy-bypass-list=localhost,127.0.0.1"),pZe){T("--proxy-bypass-list=localhost,127.0.0.1"),V0.vtg.isSeparateProcess&&T(`--remote-debugging-port=${V0.vtg.appRemoteDebuggingPort}`);let R=((k=r.modelConfig)==null?void 0:k.browserArgs)??{};R.skipDisableWebSecurity||T("--disable-web-security"),R.skipAllowFileAccessFromFiles||T("--allow-file-access-from-files"),R.skipDisableSiteIsolationTrials||T("--disable-site-isolation-trials"),R.skipAllowRunningInsecureContent||T("--allow-running-insecure-content")}V0.useRemoteDebugging.enabled&&T(`--remote-debugging-port=${V0.useRemoteDebugging.port}`),await C({...v,args:w})},"launchOptions"),variableStore:e(async({},v)=>{let C=new yWe;await v(C)},"variableStore"),vs:e(async({variableStore:v},C)=>{await C(v)},"vs"),variablesStore:e(async({variableStore:v},C)=>{await C(v)},"variablesStore"),testRunAnalytics:e(async({},v,C)=>{let w=(()=>{try{if(process.env.CHECKSUM_TEST_SUITE_INFO)return JSON.parse(process.env.CHECKSUM_TEST_SUITE_INFO);throw new Error("Missing Checksum test suite info")}catch{return console.warn("\u26A0\uFE0F Warning: It seems like you ran the test suite directly via Playwright. This can lead to degraded functionality and unexpected issues. To ensure a fully supported and stable test run, please use: 'npx checksumai test'."),NEi("playwright-run-version-unknown",(0,BEi.randomUUID)())}})(),T=OEi(C),k=rie.getTestRunInstance({...w,checksumTestId:T},process.env.CHECKSUM_ISOLATED_MODE==="true",C);await v(k)},"testRunAnalytics"),monitorBridge:[async({},v,C)=>{let w=new wzt(C);await v(w)},{scope:"worker"}],context:e(async({context:v,monitorBridge:C,variableStore:w,testRunAnalytics:T},k,R)=>{let B=grr.makeContext(v,pZe);B.setTestAssets({testRunAnalytics:T,monitorBridge:C,variableStore:w,testInfo:R,checksumTestId:OEi(R),test:_,config:t,isReplMode:a}),await k(B),B.cleanup()},"context"),page:e(async({page:v,context:C},w,T)=>{let k=await C.makePage(v);Object.defineProperty(k.constructor,"name",{value:"Page"}),await w(k),k&&typeof k.onTestComplete=="function"&&await k.onTestComplete(T.status==="passed"),k&&typeof k.shutdown=="function"&&await k.shutdown()},"page"),vtg:e(async({page:v},C)=>{if(!pZe)C(null);else if(V0.vtg.isSeparateProcess){let w=new drr(t);await w.run(v),await C(w)}else{let w=new frr(["--test-file"],!1,t);await w.run(v),await C(w)}},"vtg")});return{test:_,defineChecksumTest:dts}},"createChecksumTestExtension"),dts=e((i,t,r)=>{let o=new Error().stack.split(`
|
|
2044
2044
|
`).filter(c=>c.includes(".checksum.spec.ts"))[0];if(!o)throw new Error("Could not locate test location. Make sure test is run from valid checksum test file");return Nhn[o]=t,i},"defineChecksumTest");function OEi(i){let{file:t,line:r}=i,a=Object.keys(Nhn).filter(c=>c.trim().includes(t.trim()));if(!a.length)return;let o=4;for(let c=0;c<o;c++)for(let f of a){let _;try{_=parseInt(f.split(":").reverse()[1])}catch{continue}if(_-c===parseInt(r))return Nhn[f]}}e(OEi,"getCurrentTestIdFromMapping");fQ();JH();jne();fQ();var mts=["toPass"],_ts=["toBeOK"],hts=["toBeAttached","toBeChecked","toBeDisabled","toBeEditable","toBeEmpty","toBeEnabled","toBeFocused","toBeHidden","toBeInViewport","toBeVisible","toContainClass","toContainText","toHaveAccessibleDescription","toHaveAccessibleErrorMessage","toHaveAccessibleName","toHaveAttribute","toHaveClass","toHaveCount","toHaveCSS","toHaveId","toHaveJSProperty","toHaveRole","toHaveScreenshot","toHaveText","toHaveValue","toHaveValues","toMatchAriaSnapshot"],gts=["toHaveScreenshot","toHaveTitle","toHaveURL"],yts=["toMatchSnapshot"],vts=["toBe","toBeCloseTo","toBeDefined","toBeFalsy","toBeGreaterThan","toBeGreaterThanOrEqual","toBeInstanceOf","toBeLessThan","toBeLessThanOrEqual","toBeNaN","toBeNull","toBeTruthy","toBeUndefined","toContain","toContainEqual","toEqual","toHaveLength","toHaveProperty","toMatch","toMatchObject","toStrictEqual","toThrow","toThrowError"],LEi=[...vts,...yts],Nqo=[...mts,..._ts,...hts,...gts];var Ohn=class Ohn{constructor(t,r,a=!1,o=!1,c={}){this.page=t;this.soft=a;this.skipAutoRecovery=o;this.configuration=c;this.fallbackEnabled=!1;this.withChecksumAI=!1;this.withChecksumAIMatcher=e(async()=>{throw this.withChecksumAI=!0,new Error},"withChecksumAIMatcher");this.setThought(r)}setThought(t){var r,a;t&&(this.checksumAIThought=this.page.addNewThought(t,"assertion"),this.useChecksumAIOptions=(r=this.page.getRuntimeOptions())==null?void 0:r.useChecksumAI,(a=this.useChecksumAIOptions)!=null&&a.assertions&&(this.page.setAIFallback(t,"assertion"),this.fallbackEnabled=!0))}get(t,r,a){if(typeof r!="string")return t[r];if(r==="checksumAI")return o=>(this.setThought(o),a);if(r==="withChecksumAI"||typeof t[r]=="function"){let o=r==="withChecksumAI"?this.withChecksumAIMatcher:t[r];return(...c)=>LEi.includes(r)?o.call(t,...c):this.checksumAIThought?this.executeMatcherWithinStep(o,t,...c):this.executeMatcher(o,t,...c)}else{let o=t[r];return new Proxy(o,this)}}findNestedErrors(t,r){t.error&&t.infectParentStepsWithError&&r.push(t.error);for(let a of t.steps)this.findNestedErrors(a,r)}async callMatcher(t,r,...a){this.beforeMatcherCall();let o=t.call(r,...a),c=o instanceof Promise?await o:o;if(this.step){let f=[];if(this.step.error?f.push(this.step.error):this.findNestedErrors(this.step,f),f.length)throw f[0]}return c}executeMatcherWithinStep(t,r,...a){return this.page.step(this.checksumAIThought.thought,()=>this.callMatcher(t,r,...a).catch(this.onMatcherFailure.bind(this)),!1,{obtainStep:e(o=>this.step=o,"obtainStep")}).catch(o=>{if(!this.soft&&!(this.withChecksumAI&&o.message===B4e))throw o}).finally(this.afterMatcherExecute.bind(this))}async executeMatcher(t,r,...a){try{return await this.callMatcher(t,r,...a)}catch(o){await this.onMatcherFailure(o)}finally{this.afterMatcherExecute()}}beforeMatcherCall(){this.page.setExpectConfiguration(this.configuration)}afterMatcherExecute(){this.checksumAIThought=void 0,this.fallbackEnabled=!1,this.withChecksumAI=!1,this.page.resetFallbacks(),this.page.setExpectConfiguration(void 0)}shouldInitiateFallback(t){var a;return!(!this.fallbackEnabled||((a=t.matcherResult)==null?void 0:a.name)==="toHaveScreenshot"&&!this.useChecksumAIOptions.visualComparison)}async onMatcherFailure(t){var r,a;if(!this.shouldInitiateFallback(t))throw Dv("[onMatcherFailure] fallback disabled, continuing with error."),this.page.testRunAnalytics.testRunAssertionExecutionFailure({failedThought:(r=this.checksumAIThought)==null?void 0:r.thought,error:t.message,matcher:(a=t.matcherResult)==null?void 0:a.name}),t;if(Dv("[onMatcherFailure] initiating fallback sequence with thought:",this.checksumAIThought.thought),this.skipAutoRecovery){if(this.soft)return;throw t}try{await this.page.initiateFallbackSequence({type:"assertion",error:t,withChecksumAI:this.withChecksumAI,testInfo:this.page.testInfo})}catch(o){if(this.soft)return;throw o}throw this.soft=!0,t}};e(Ohn,"ExpectCallProxyHandler");var yrr=Ohn;var Yvt=class Yvt{constructor(t=void 0,r={}){this.page=t;this.configuration=r}get(t,r){return r==="setPage"?a=>{this.page=a}:r==="extend"?(...a)=>{let o=t.extend(...a);return new Proxy(o,this)}:r==="configure"?a=>{let o=t.configure(a);return new Proxy(o,new Yvt(this.page,{...this.configuration,...a}))}:r==="soft"?(...a)=>{let o=this.manipulateArgsAndExtractThought(a),c=t.soft(...a);return new Proxy(c,this.makeExpectCallProxyHandler(o,!0))}:r==="poll"?(...a)=>{let o=this.manipulateArgsAndExtractThought(a),c=t.poll(...a);return new Proxy(c,this.makeExpectCallProxyHandler(o))}:r==="skipAutoRecovery"?new Proxy(()=>{},{apply:e((o,c,f)=>{let _=this.manipulateArgsAndExtractThought(f),v=t.apply(c,f);return new Proxy(v,this.makeExpectCallProxyHandler(_,void 0,!0))},"apply"),get:e((o,c)=>new Proxy(t,new Yvt(this.page,{...this.configuration,skipAutoRecovery:!0}))[c],"get")}):t[r]instanceof Function?t[r].bind(t):t[r]}apply(t,r,a){let o=this.manipulateArgsAndExtractThought(a),c=t.apply(r,a);return new Proxy(c,this.makeExpectCallProxyHandler(o))}makeExpectCallProxyHandler(t,r,a){var o,c;return new yrr(this.page,t,r===!0?!0:(o=this.configuration)==null?void 0:o.soft,a===!0?!0:(c=this.configuration)==null?void 0:c.skipAutoRecovery,this.configuration)}manipulateArgsAndExtractThought(t){let r,a=t[1];if(typeof a=="string")r=a,t[1]=void 0;else if(typeof a=="object"){if(a.checksumAI===!1){t[1].checksumAI=void 0;return}a.checksumAI&&typeof a.checksumAI=="string"?(r=a.checksumAI,t[1].checksumAI=void 0):a.message&&(r=a.message,t[1].message=void 0)}return r}};e(Yvt,"ExpectProxyHandler");var vrr=Yvt;var xrr=class xrr{constructor(t){this.expect=t;this.proxy=new Proxy(this.expect,new vrr)}static init(t){return new xrr(t).proxy}};e(xrr,"ChecksumExpect");var brr=xrr;v7();var UEi=require("@playwright/test");fQ();var MEi=sf(bT()),Arr=require("fs");var Xvt=sf(require("path"));var bts=e(i=>{let t=H7e(i),r=new G7e(t),a=r1t();return r.transformSourceFile([new rNe(i),new nGe(i,a,{newRequireIdentifier:"checksumHotRequire",extraImportArguments:[MEi.factory.createIdentifier("__filename")]})]),`${iri}
|
|
2045
2045
|
${r.getTestFileCode().code}`},"transformFileToHoRequireFormat"),xts=e(i=>{let t=Xvt.default.dirname(i),a=Xvt.default.basename(i).split(".")[0],o=Math.random().toString(36).substring(2,15),c=Xvt.default.extname(i);return Xvt.default.join(t,`${a}-${Date.now()}-${o}${c}`)},"generateTempFilePath"),Ats=e((i,t)=>{let r=r1t();return new K7e(t,r).getResolvedPath(i)},"resolveFilePath"),Ets=e((i,t=__filename)=>{let r;try{let a=require.resolve(Ats(i,t)),o=bts(a);r=xts(a),(0,Arr.writeFileSync)(r,o);let c=require(r);return require.cache[a]=require.cache[r],c}catch(a){throw console.error("Error in require",a),a}finally{r&&(0,Arr.unlinkSync)(r)}},"checksumHotRequire"),jEi=Ets;Eve();function Cts(i){let t=sQt(),{options:r,apiKey:a,environments:o}=t,c=o.find(R=>R.default);if(!c)throw new Error("No default environment found. Please set the default field to true on one of the environments in the checksum.config.ts file.");if(!c.baseURL)throw new Error("A baseURL is required. Please set the baseURL field in the default environment in the checksum.config.ts file.");if(!c.users.find(R=>R.default))throw new Error("A default user within the default environment is required. Please set one of the default environment users as default in the checksum.config.ts file.");if(!a)throw new Error("An API key is required. Please set the apiKey field in the checksum.config.ts file.");let _=process.env.CHECKSUM_REPL==="true",{test:v,defineChecksumTest:C}=REi(i??UEi.test,t,r,_),w=brr.init(v.expect),T=wts();v._checksum={expect:w,checksumAI:T},_&&(console.log("Detected REPL mode"),v.beforeEach(async()=>{v.setTimeout(0)}),v.afterEach(async()=>{for(;;)await TA(1e3)}));let k=e(({name:R,userRole:B})=>{let{environment:U,user:W}=K_t(t,{environment:R,role:B},!0),X=MJn({config:t,throwIfEnvInfoInvalid:!0},{environmentName:U.name,userRole:W.role});return{environment:U,user:W,login:X}},"getEnvironment");return{test:v,expect:w,login:Ube({config:t}),defineChecksumTest:C,getEnvironment:k,checksumAI:T}}e(Cts,"init");var Bhn=e(i=>new Proxy(i,{apply:e(function(r,a,o){let c={...r.options,...o[2]};return r.page.checksumAI(o[0],o[1],c)},"apply"),get:e(function(r,a){return a==="withDialog"?(r.options.withDialog=!0,Bhn(i)):a==="skipAutoRecovery"?(r.options.skipAutoRecovery=!0,Bhn(i)):r[a]},"get"),set:e(function(r,a,o){if(a==="page")return r[a]=o},"set")}),"makeChecksumAIProxy"),wts=e(()=>{let i=e(function(){},"func");return i.page=void 0,i.options={withDialog:!1,withTomer:!1,skipAutoRecovery:!1},Bhn(i)},"makeChecksumAI");0&&(module.exports={AutoRecoveryMode,RunMode,checksumHotRequire,getChecksumConfig,getLogin,init});
|
|
2046
2046
|
/*! Bundled license information:
|
package/package.json
CHANGED
package/vtg-pw-bridge-runner.js
CHANGED
|
@@ -637,7 +637,7 @@ Result: ${JSON.stringify(w)}`);else C=w;let k;h7e(t)&&(k=t.id),!k&&r$n(f)&&(k=f.
|
|
|
637
637
|
|
|
638
638
|
`),c=`Available pages (${a.length}):
|
|
639
639
|
|
|
640
|
-
${o}`;return{success:!0,pages:a,message:c}}async switchPageHandler(r){if(!r.pageId)return{success:!1,message:"pageId is required"};r.thought&&this.utils.createChecksumStep({title:r.thought});try{await this.utils.setActivePage(r.pageId);let a=await this.utils.captureApplicationState();return{success:!0,message:`Successfully switched to page ${r.pageId}`,appState:a}}catch(a){let o=a instanceof Error?a.message:String(a);return{success:!1,message:`Failed to switch to page ${r.pageId}: ${o}`}}}};e(Bzt,"AutoRecoveryAgent");Ozt=Bzt});var Nzr,Rzt,CHn=Vt(()=>{"use strict";AMr();I0t();Nzr=class Nzr{constructor(t,r){this.sessionId=null;if(!l_e.getCurrentTestInfo())throw new Error("TestRunAnalytics must be initialized with testInfo before RecoveryAnalytics can be used");let o=l_e.getCurrentInstance();if(!o)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating RecoveryAnalytics");let c=o.getTestSuiteRunInfo();this.analytics=e_e.createFromConfig(c,l_e.isolatedMode,!0),this.fallbackId=t,this.fallbackType=r}updateToSessionId(t){this.sessionId!==t&&(this.sessionId=t)}get tableName(){return"fallbacks"}get metadata(){return{...this.analytics.metadata,fallbackType:this.fallbackType,sessionId:this.sessionId||"unknown",fallbackId:this.fallbackId}}event(t){this.analytics.trackEventWithTable(t,this.metadata,this.tableName)}setFallbackType(t){this.fallbackType=t}aiFallbackStart(t){this.event({event:"AI Fallback Start",metadata:this.metadata,...t})}aiFallbackConfig(t){this.event({event:"AI Fallback Config",metadata:this.metadata,...t})}aiFallbackIterationResponse(t){this.event({event:"AI Fallback Iteration Response",metadata:this.metadata,...t})}aiFallbackAssertion(t){this.event({event:"AI Fallback Assertion Execution",metadata:this.metadata,...t})}aiFallbackChangeVariable(t){this.event({event:"AI Fallback Change Variable",metadata:this.metadata,...t})}aiFallbackSummary(t){this.event({event:"AI Fallback Summary",metadata:this.metadata,fallbackType:this.fallbackType,...t})}aiFallbackActionExecution(t){this.event({event:"AI Fallback Action Execution",metadata:this.metadata,...t})}aiFallbackActionExecutionFailure(t){this.event({event:"AI Fallback Action Execution Failure",metadata:this.metadata,...t})}aiFallbackEnd(t){this.event({event:"AI Fallback End",metadata:this.metadata,...t})}ARStart(){this.event({event:"Auto-Recovery Start",metadata:this.metadata})}ARConfig(t){this.event({event:"Auto-Recovery Config",metadata:this.metadata,...t})}ARGetState(t){this.event({event:"Auto-Recovery State",metadata:this.metadata,thought:t})}ARInvokeCode(t,r){this.event({event:"Auto-Recovery Invoke Code",metadata:this.metadata,thought:t,code:r})}ARFinalResult(t){this.event({event:"Auto-Recovery Final Result",metadata:this.metadata,...t})}autoRecoveryDisconnect(t){this.event({event:"Auto-Recovery Disconnect",metadata:this.metadata,...t})}ARFinish(t){this.event({event:"Auto-Recovery Finish",metadata:this.metadata,...t})}ARError(t){this.event({event:"Auto-Recovery Error",metadata:this.metadata,...t})}};e(Nzr,"RecoveryAnalytics");Rzt=Nzr});var SHn=Vt(()=>{"use strict"});function Ozr(i){return i._guid}var DHn,THn,TFe,Lzt,kHn=Vt(()=>{"use strict";xMr();DHn=require("fs"),THn=hf(require("path"));CHn();SHn();e(Ozr,"getPageGuid");TFe=class TFe{constructor({page:t,evaluateWithChecksum:r,checksumPage:a,pageInteractor:o,arConfig:c,sessionId:f,runtimeFallbackData:_,fallbackData:v,variableStore:w,runtimePage:C,context:T}){this.reducedHtmlTimeoutMs=3e4;this.page=t,this.evaluateWithChecksum=r,this.checksumPage=a,this._pageInteractor=o,this.arConfig=c,this.sessionId=f,this.runtimeFallbackData=_,this.fallbackData=v,this.variableStore=w,this.runtimePage=C,this.context=T,this._activePageGuid=Ozr(this.page),this._analytics=new Rzt(this.sessionId,v.type)}get activePageGuid(){return this._activePageGuid}static async start(t){return new TFe({...t})}async getPageById(t){return(this.context||this.page.context()).pages().find(o=>Ozr(o)===t)}async setActivePage(t){let r=await this.getPageById(t);if(!r||r.isClosed())throw new Error(`Page with ID ${t} is closed or not found`);this.page=r,this._activePageGuid=t}getMatcherResultFileData(t){let r=t.matcherResult;if((r==null?void 0:r.name)!=="toHaveScreenshot")return;let a=e((_,v=!0)=>{if(!_)return"";try{return(0,DHn.readFileSync)(_,v?"base64":"utf-8")}catch{return""}},"readFileSafe"),o=a(r==null?void 0:r.actual),c=a(r==null?void 0:r.diff),f=a(r==null?void 0:r.expected);if(!f)throw new Error("No expected file found for 'toHaveScreenshot'");return{...r,actual:o,diff:c,expected:f}}async getSelectionDataForChecksumId(t){return await this.evaluateWithChecksum(async a=>{let{selector:o,locator:c,clickOffset:f,parentFramesSelectors:_,invalid:v,rrwebId:w}=await window.checksum.testGenerator.getSelectorForChecksumId(a),C=await window.checksum.testGenerator.getElementForChecksumId(a),T=C instanceof HTMLOptionElement&&C.value?C.value:void 0;return{selector:o,locator:c,clickOffset:f,selectOptionValue:T,parentFramesSelectors:_,invalid:v,rrwebId:w}},t)}async getReducedHtml(t=TFe.currentChecksumId){if(this._pageInteractor.getCurrentURL()==="about:blank")return{reducedHTML:"Error: Page is about:blank. Cannot get reduced HTML - either wait or navigate to a valid page before continuing.",currentChecksumId:t};let{reducedHTML:r,currentChecksumId:a}=await this._pageInteractor.getCurrentReducedHTML({stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0,initialChecksumId:t});return TFe.currentChecksumId=a,{reducedHTML:r,currentChecksumId:a}}async getApplicationState(){let{reducedHTML:t}=await this.getReducedHtml();return{reducedHTML:t,screenshot:await this.getPageScreenshot()}}async capturePageState(t,r){let a=this.page,o=this._activePageGuid;try{this.page=t,this._activePageGuid=r;let{reducedHTML:c}=await this.getReducedHtml(),f=await this.getPageScreenshot();return{pageId:r,reducedHTML:c,screenshot:f,url:t.url()}}finally{this.page=a,this._activePageGuid=o}}async captureAllPagesState(){let r=(this.context||this.page.context()).pages(),a=[],o=[];for(let f of r){if(f.isClosed())continue;let _=Ozr(f);try{let v=await this.capturePageState(f,_);a.push(v)}catch(v){let w=v instanceof Error?v.message:String(v);o.push({pageId:_,url:f.url(),error:w}),console.warn(`Failed to capture state for page ${_} (${f.url()}):`,v)}}let c={pages:a};return o.length>0&&(c.failures=o),c}async captureApplicationState(t,r){if(r)return await this.captureAllPagesState();if(t&&t!==this._activePageGuid){let a=await this.getPageById(t);if(!a||a.isClosed())throw new Error(`Page with ID ${t} is closed or not found`);let o=await this.capturePageState(a,t);return{reducedHTML:o.reducedHTML,screenshot:o.screenshot}}else return await this.getApplicationState()}async buildFallbackData(){let r=(this.context||this.page.context()).pages().filter(f=>!f.isClosed()).length,a=new Promise((f,_)=>setTimeout(()=>_(new Error(`getReducedHtml timeout after ${this.reducedHtmlTimeoutMs/1e3} seconds`)),this.reducedHtmlTimeoutMs)),{reducedHTML:o,currentChecksumId:c}=await Promise.race([this.getReducedHtml(),a]);return{storyInfo:this.runtimeFallbackData.storyInfo,testIdentification:this.runtimeFallbackData.testIdentification,fallbackConfig:this.runtimeFallbackData.fallbackConfig,thoughts:this.runtimeFallbackData.thoughts,errorData:{error:{name:this.fallbackData.error.name,message:this.fallbackData.error.message,stack:this.fallbackData.error.stack},errorFileContent:await this.getErrorFileContent(this.fallbackData.error)},applicationState:{reducedHTML:o,screenshot:await this.getPageScreenshot()},stepData:{matcher:this.getMatcherResultFileData(this.fallbackData.error)},currentChecksumId:c,failingStepThought:this.runtimeFallbackData.thoughts.failing,type:this.fallbackData.type,config:this.runtimeFallbackData.config,sessionId:this.sessionId,variableStore:this.variableStore.reduce((f,_)=>(f[`variablesStore.${_.name}`]=_.value,f),{}),arConfig:this.arConfig,multiPageContext:{pageCount:r,hasMultiplePages:r>1}}}async scrollToElement(t){t&&await this._pageInteractor.scrollElementIntoViewByChecksumId(t)}async getPageScreenshot(t=this.arConfig){try{return this.checksumPage.wrapInternalSteps(async()=>{var a;return(await this.page.screenshot({fullPage:!0,type:((a=t.modelConfig)==null?void 0:a.provider)==="anthropic"?"jpeg":"png"})).toString("base64")})}catch{return}}async getErrorFileContent(t){try{let r=THn.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return oJe.toRecord(t,r)}catch{throw new Error("Error while getting error file content for AI fallback")}}async wait(){await this.page.waitForTimeout(5e3)}async preprocessCode(t){var R;let r=t,a=t,o=[],c=t.match(/getByChecksumId\([^)]+\)\.([a-zA-Z]+)\(([^)]*)\)/),f=c==null?void 0:c[1],_=c==null?void 0:c[2],v=/(?:page\.)?getByChecksumId\(['"]([^'"]+)['"]\)/,w=(R=t.match(v))==null?void 0:R[1];if(!w)throw new Error("Checksum ID not found in the code");let C=await this.getSelectionDataForChecksumId(w);if(!(C!=null&&C.locator)||C.invalid)throw new Error(`Locator or selector not found for checksumId: ${w}`);a=a.replace(v,C.locator);let T=/variables?Store\.([a-zA-Z_$][a-zA-Z0-9_$]*)/g,k=null;for(;(k=T.exec(t))!==null;){let B=k[1],U=this.variableStore.find(W=>W.name===B);U&&(o.push(U),a=a.replace(k[0],`"${U.value}"`))}return{originalCode:r,modifiedCode:a,usedVariables:o,checksumId:w,locator:C.locator,method:f,methodArgs:_}}async invokeCode(t){try{let r=await this.preprocessCode(t),{modifiedCode:a}=r,o=new Function("page",`return (async () => { return page.${a}; })()`),c;return await this.step(a,async()=>c=await o(this.page),!1,{box:!0,noLocation:!0,obtainStep:e(f=>{this.checksumPage.addAutoRecoveryStepId(f.stepId)},"obtainStep")}),{success:!0,result:c}}catch(r){throw console.log("Error while invoking code",r.message),r}}addAutoRecoveryErrorToReport(t,r){let a=this.runtimeFallbackData.thoughts.failing,o=r?`\u2705 "${a}" auto-recovered`:`\u274C "${a}" failed`;this.checksumPage.addPwAnnotation({type:o,description:t.replace(/^"(.*)"$/,"$1")}),r&&this.checksumPage.addErrorMessage(this.fallbackData.error,`${o}:
|
|
640
|
+
${o}`;return{success:!0,pages:a,message:c}}async switchPageHandler(r){if(!r.pageId)return{success:!1,message:"pageId is required"};r.thought&&this.utils.createChecksumStep({title:r.thought});try{await this.utils.setActivePage(r.pageId);let a=await this.utils.captureApplicationState();return{success:!0,activePageId:r.pageId,message:`Successfully switched to page ${r.pageId}`,appState:a}}catch(a){let o=a instanceof Error?a.message:String(a);return{success:!1,activePageId:this.utils.activePageGuid,message:`Failed to switch to page ${r.pageId}: ${o}`}}}};e(Bzt,"AutoRecoveryAgent");Ozt=Bzt});var Nzr,Rzt,CHn=Vt(()=>{"use strict";AMr();I0t();Nzr=class Nzr{constructor(t,r){this.sessionId=null;if(!l_e.getCurrentTestInfo())throw new Error("TestRunAnalytics must be initialized with testInfo before RecoveryAnalytics can be used");let o=l_e.getCurrentInstance();if(!o)throw new Error("TestRunAnalytics instance not found. Make sure TestRunAnalytics is initialized before creating RecoveryAnalytics");let c=o.getTestSuiteRunInfo();this.analytics=e_e.createFromConfig(c,l_e.isolatedMode,!0),this.fallbackId=t,this.fallbackType=r}updateToSessionId(t){this.sessionId!==t&&(this.sessionId=t)}get tableName(){return"fallbacks"}get metadata(){return{...this.analytics.metadata,fallbackType:this.fallbackType,sessionId:this.sessionId||"unknown",fallbackId:this.fallbackId}}event(t){this.analytics.trackEventWithTable(t,this.metadata,this.tableName)}setFallbackType(t){this.fallbackType=t}aiFallbackStart(t){this.event({event:"AI Fallback Start",metadata:this.metadata,...t})}aiFallbackConfig(t){this.event({event:"AI Fallback Config",metadata:this.metadata,...t})}aiFallbackIterationResponse(t){this.event({event:"AI Fallback Iteration Response",metadata:this.metadata,...t})}aiFallbackAssertion(t){this.event({event:"AI Fallback Assertion Execution",metadata:this.metadata,...t})}aiFallbackChangeVariable(t){this.event({event:"AI Fallback Change Variable",metadata:this.metadata,...t})}aiFallbackSummary(t){this.event({event:"AI Fallback Summary",metadata:this.metadata,fallbackType:this.fallbackType,...t})}aiFallbackActionExecution(t){this.event({event:"AI Fallback Action Execution",metadata:this.metadata,...t})}aiFallbackActionExecutionFailure(t){this.event({event:"AI Fallback Action Execution Failure",metadata:this.metadata,...t})}aiFallbackEnd(t){this.event({event:"AI Fallback End",metadata:this.metadata,...t})}ARStart(){this.event({event:"Auto-Recovery Start",metadata:this.metadata})}ARConfig(t){this.event({event:"Auto-Recovery Config",metadata:this.metadata,...t})}ARGetState(t){this.event({event:"Auto-Recovery State",metadata:this.metadata,thought:t})}ARInvokeCode(t,r){this.event({event:"Auto-Recovery Invoke Code",metadata:this.metadata,thought:t,code:r})}ARFinalResult(t){this.event({event:"Auto-Recovery Final Result",metadata:this.metadata,...t})}autoRecoveryDisconnect(t){this.event({event:"Auto-Recovery Disconnect",metadata:this.metadata,...t})}ARFinish(t){this.event({event:"Auto-Recovery Finish",metadata:this.metadata,...t})}ARError(t){this.event({event:"Auto-Recovery Error",metadata:this.metadata,...t})}};e(Nzr,"RecoveryAnalytics");Rzt=Nzr});var SHn=Vt(()=>{"use strict"});function Ozr(i){return i._guid}var DHn,THn,TFe,Lzt,kHn=Vt(()=>{"use strict";xMr();DHn=require("fs"),THn=hf(require("path"));CHn();SHn();e(Ozr,"getPageGuid");TFe=class TFe{constructor({page:t,evaluateWithChecksum:r,checksumPage:a,pageInteractor:o,arConfig:c,sessionId:f,runtimeFallbackData:_,fallbackData:v,variableStore:w,runtimePage:C,context:T}){this.reducedHtmlTimeoutMs=3e4;this.page=t,this._originalPage=t,this.evaluateWithChecksum=r,this.checksumPage=a,this._pageInteractor=o,this.arConfig=c,this.sessionId=f,this.runtimeFallbackData=_,this.fallbackData=v,this.variableStore=w,this.runtimePage=C,this.context=T,this._activePageGuid=Ozr(this.page),this._analytics=new Rzt(this.sessionId,v.type)}get activePageGuid(){return this._activePageGuid}static async start(t){return new TFe({...t})}async evaluateOnCurrentPage(t,r){return this.page!==this._originalPage?this.page.evaluate(t,r):this.evaluateWithChecksum(t,r)}async getPageById(t){return(this.context||this.page.context()).pages().find(o=>Ozr(o)===t)}async setActivePage(t){let r=await this.getPageById(t);if(!r||r.isClosed())throw new Error(`Page with ID ${t} is closed or not found`);this.page=r,this._activePageGuid=t}getMatcherResultFileData(t){let r=t.matcherResult;if((r==null?void 0:r.name)!=="toHaveScreenshot")return;let a=e((_,v=!0)=>{if(!_)return"";try{return(0,DHn.readFileSync)(_,v?"base64":"utf-8")}catch{return""}},"readFileSafe"),o=a(r==null?void 0:r.actual),c=a(r==null?void 0:r.diff),f=a(r==null?void 0:r.expected);if(!f)throw new Error("No expected file found for 'toHaveScreenshot'");return{...r,actual:o,diff:c,expected:f}}async getSelectionDataForChecksumId(t){return await this.evaluateOnCurrentPage(async a=>{let{selector:o,locator:c,clickOffset:f,parentFramesSelectors:_,invalid:v,rrwebId:w}=await window.checksum.testGenerator.getSelectorForChecksumId(a),C=await window.checksum.testGenerator.getElementForChecksumId(a),T=C instanceof HTMLOptionElement&&C.value?C.value:void 0;return{selector:o,locator:c,clickOffset:f,selectOptionValue:T,parentFramesSelectors:_,invalid:v,rrwebId:w}},t)}async getReducedHtml(t=TFe.currentChecksumId,r=3){if(this.page.url()==="about:blank")return{reducedHTML:"Error: Page is about:blank. Cannot get reduced HTML - either wait or navigate to a valid page before continuing.",currentChecksumId:t};try{let a=await this.evaluateOnCurrentPage(async o=>window.checksum.testGenerator.reduceHTML({},o),{initialChecksumId:t,stopFlashingElementsDetection:!0,assignChecksumIdsToAllElements:!0});return TFe.currentChecksumId=a.currentChecksumId,{reducedHTML:a.reducedHTML,currentChecksumId:a.currentChecksumId}}catch(a){if(r>0)return await new Promise(c=>setTimeout(c,2e3)),this.getReducedHtml(t,r-1);let o=a instanceof Error?a.message:String(a);return{reducedHTML:`Unable to extract page DOM at ${this.page.url()}. Error: ${o}`,currentChecksumId:t}}}async getApplicationState(){let{reducedHTML:t}=await this.getReducedHtml();return{reducedHTML:t,screenshot:await this.getPageScreenshot()}}async capturePageState(t,r){let a=this.page,o=this._activePageGuid;try{this.page=t,this._activePageGuid=r;let{reducedHTML:c}=await this.getReducedHtml(),f=await this.getPageScreenshot();return{pageId:r,reducedHTML:c,screenshot:f,url:t.url()}}finally{this.page=a,this._activePageGuid=o}}async captureAllPagesState(){let r=(this.context||this.page.context()).pages(),a=[],o=[];for(let f of r){if(f.isClosed())continue;let _=Ozr(f);try{let v=await this.capturePageState(f,_);a.push(v)}catch(v){let w=v instanceof Error?v.message:String(v);o.push({pageId:_,url:f.url(),error:w}),console.warn(`Failed to capture state for page ${_} (${f.url()}):`,v)}}let c={pages:a};return o.length>0&&(c.failures=o),c}async captureApplicationState(t,r){if(r)return await this.captureAllPagesState();if(t&&t!==this._activePageGuid){let a=await this.getPageById(t);if(!a||a.isClosed())throw new Error(`Page with ID ${t} is closed or not found`);let o=await this.capturePageState(a,t);return{reducedHTML:o.reducedHTML,screenshot:o.screenshot}}else return await this.getApplicationState()}async buildFallbackData(){let r=(this.context||this.page.context()).pages().filter(f=>!f.isClosed()).length,a=new Promise((f,_)=>setTimeout(()=>_(new Error(`getReducedHtml timeout after ${this.reducedHtmlTimeoutMs/1e3} seconds`)),this.reducedHtmlTimeoutMs)),{reducedHTML:o,currentChecksumId:c}=await Promise.race([this.getReducedHtml(),a]);return{storyInfo:this.runtimeFallbackData.storyInfo,testIdentification:this.runtimeFallbackData.testIdentification,fallbackConfig:this.runtimeFallbackData.fallbackConfig,thoughts:this.runtimeFallbackData.thoughts,errorData:{error:{name:this.fallbackData.error.name,message:this.fallbackData.error.message,stack:this.fallbackData.error.stack},errorFileContent:await this.getErrorFileContent(this.fallbackData.error)},applicationState:{reducedHTML:o,screenshot:await this.getPageScreenshot()},stepData:{matcher:this.getMatcherResultFileData(this.fallbackData.error)},currentChecksumId:c,failingStepThought:this.runtimeFallbackData.thoughts.failing,type:this.fallbackData.type,config:this.runtimeFallbackData.config,sessionId:this.sessionId,variableStore:this.variableStore.reduce((f,_)=>(f[`variablesStore.${_.name}`]=_.value,f),{}),arConfig:this.arConfig,multiPageContext:{pageCount:r,hasMultiplePages:r>1}}}async scrollToElement(t){t&&await this.evaluateOnCurrentPage(async r=>{let a=document.querySelector(`[checksumid="${r}"]`);a==null||a.scrollIntoView({block:"center"})},t)}async getPageScreenshot(t=this.arConfig){try{return this.checksumPage.wrapInternalSteps(async()=>{var a;return(await this.page.screenshot({fullPage:!0,type:((a=t.modelConfig)==null?void 0:a.provider)==="anthropic"?"jpeg":"png"})).toString("base64")})}catch{return}}async getErrorFileContent(t){try{let r=THn.default.dirname(this.runtimeFallbackData.testIdentification.testFileName);return oJe.toRecord(t,r)}catch{throw new Error("Error while getting error file content for AI fallback")}}async wait(){await this.page.waitForTimeout(5e3)}async preprocessCode(t){var R;let r=t,a=t,o=[],c=t.match(/getByChecksumId\([^)]+\)\.([a-zA-Z]+)\(([^)]*)\)/),f=c==null?void 0:c[1],_=c==null?void 0:c[2],v=/(?:page\.)?getByChecksumId\(['"]([^'"]+)['"]\)/,w=(R=t.match(v))==null?void 0:R[1];if(!w)throw new Error("Checksum ID not found in the code");let C=await this.getSelectionDataForChecksumId(w);if(!(C!=null&&C.locator)||C.invalid)throw new Error(`Locator or selector not found for checksumId: ${w}`);a=a.replace(v,C.locator);let T=/variables?Store\.([a-zA-Z_$][a-zA-Z0-9_$]*)/g,k=null;for(;(k=T.exec(t))!==null;){let B=k[1],U=this.variableStore.find(W=>W.name===B);U&&(o.push(U),a=a.replace(k[0],`"${U.value}"`))}return{originalCode:r,modifiedCode:a,usedVariables:o,checksumId:w,locator:C.locator,method:f,methodArgs:_}}async invokeCode(t){try{let r=await this.preprocessCode(t),{modifiedCode:a}=r,o=new Function("page",`return (async () => { return page.${a}; })()`),c;return await this.step(a,async()=>c=await o(this.page),!1,{box:!0,noLocation:!0,obtainStep:e(f=>{this.checksumPage.addAutoRecoveryStepId(f.stepId)},"obtainStep")}),{success:!0,result:c}}catch(r){throw console.log("Error while invoking code",r.message),r}}addAutoRecoveryErrorToReport(t,r){let a=this.runtimeFallbackData.thoughts.failing,o=r?`\u2705 "${a}" auto-recovered`:`\u274C "${a}" failed`;this.checksumPage.addPwAnnotation({type:o,description:t.replace(/^"(.*)"$/,"$1")}),r&&this.checksumPage.addErrorMessage(this.fallbackData.error,`${o}:
|
|
641
641
|
${t}`)}get createChecksumStep(){return t=>this.checksumPage.createChecksumStep(t)}get step(){return this.checksumPage.step.bind(this.checksumPage)}get runConditionallyWithinStep(){return(t,r,a)=>this.checksumPage.runConditionallyWithinStep(t,r,a)}async getScreenshotForElement(t){var r;try{let a=await this.getSelectionDataForChecksumId(t);if(!a)throw new Error(`Locator not found for checksumId: ${t}`);let o=((r=this.arConfig.modelConfig)==null?void 0:r.provider)==="anthropic"?"jpeg":"png";return(await this.page.locator(a.selector).screenshot({type:o})).toString("base64")}catch{throw new Error(`Failed to get screenshot for element: ${t}`)}}get analytics(){return this._analytics}get pageInteractor(){return this._pageInteractor}};e(TFe,"AutoRecoveryRuntimeIteratorUtils"),TFe.currentChecksumId="0";Lzt=TFe});var Lbe,Mbe,IHn=Vt(()=>{"use strict";Ume();bmt();wHn();kHn();Q9e();Lbe=class Lbe extends f_e{constructor(t,r,a,o,c,f,_){super(t,r,a,o,c,f,_),this.runtimePageContext=f}init(t){var r;return this.initializationData=t,(r=this.initializationData.fallbackConfig).arMode??(r.arMode="fast"),this}canResolve(t){return!0}get failingThought(){return this.initializationData.thoughts.failing}getRecoveryAttemptTitle(){switch(this.initializationData.type){case"action":return`Checksum Auto-Recovery: trying to achieve action "${this.failingThought}"...`;case"assertion":return`Checksum Auto-Recovery: trying to verify assertion "${this.failingThought}"...`}}static async registerSession(t){let r=t.config.apiURL,a=t.config.apiKey;return await(await fetch(`${r}${Lbe.API_BASE_ROUTE}/register-auto-recovery-session`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:a},body:JSON.stringify({appName:t.testIdentification.testFileName,fallbackData:t})})).json()}async prepareSession(t){let r=await Lbe.registerSession(this.initializationData);this.utils=new Lzt({page:this.page,evaluateWithChecksum:this.evaluateWithChecksum,checksumPage:this.checksumPage,pageInteractor:this.pageInteractor,arConfig:r.arConfig,sessionId:r.sessionId,runtimeFallbackData:this.initializationData,fallbackData:t,variableStore:this.variables,runtimePage:this.runtimePageContext,context:this.context});try{this.agent=await Ozt.build(this.utils)}catch(a){let o=a instanceof Error?a.message:String(a),c=a instanceof Error?a.stack:void 0;throw new Error(`Failed to prepare ARFallback: ${o}`)}}async resolve(t){let r=null,a=new Promise((c,f)=>{r=setTimeout(()=>{r=null,this.utils.analytics.ARError({error:`Auto-recovery timed out after ${Lbe.TIMEOUT_MS/1e3} seconds`});let _="Auto-Recovery attempt finished unsuccessfully";this.utils.createChecksumStep({title:_,withError:!0}),this.utils.addAutoRecoveryErrorToReport(_,!1),f(new Error(_))},Lbe.TIMEOUT_MS)}),o=Date.now();await this.prepareSession(t),this.utils.analytics.ARStart();try{let c=await Promise.race([this.agent.init(),a]);return r!==null&&(clearTimeout(r),r=null),this.utils.analytics.ARFinish({duration:Date.now()-o}),{fbResult:c.result,thought:c.finalThought,stepsThoughts:c.stepsThoughts,steps:[]}}catch(c){throw r!==null&&(clearTimeout(r),r=null),this.utils.analytics.ARFinish({duration:Date.now()-o}),c}}};e(Lbe,"ARFallback"),Lbe.API_BASE_ROUTE="/auto-recovery",Lbe.TIMEOUT_MS=12e4;Mbe=Lbe});var PHn,FHn=Vt(()=>{"use strict";PHn=e(i=>{let t=i.info();return t.annotations.some(r=>r.type==="bug")||t.tags.some(r=>r==="@bug")},"isKnownBugTest")});var NHn={};cj(NHn,{VtgUserStoryService:()=>Y_t});var Bzr,Y_t,Rzr=Vt(()=>{"use strict";N8();yie();MC();Bzr=class Bzr{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(Pm.vtg.useFakeStory){this.story={...Pm.vtg.fakeStory,id:"fake-story",environment:{name:void 0,userRole:void 0},internalTestId:"fake-internal-test-id"},uf.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`);let{id:o,title:c,steps:f,startUrl:_,userRole:v,environment:w,internalTestId:C,version:T,collectionName:k}=a;this.story={id:o,goal:c,instructions:f,url:_,internalTestId:C,environment:{userRole:v,name:w},version:T,collectionName:k}}catch(r){throw uf.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 Lzr(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(Bzr,"VtgUserStoryService");Y_t=Bzr});var Mzr,Mzt,OHn=Vt(()=>{"use strict";Mzr=class Mzr{constructor(t,r){this.config=t;this.baseURL=t.apiURL+r}getBaseURL(){return this.baseURL}get(t){let r=`${this.baseURL}/${t}`;return fetch(r,{method:"GET",headers:{ChecksumAppCode:this.config.apiKey}})}put(t,r){return fetch(`${this.baseURL}/${t}`,{method:"PUT",headers:{"Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:r?JSON.stringify(r):void 0})}post(t,r){return fetch(`${this.baseURL}/${t}`,{method:"POST",headers:{"Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:r?JSON.stringify(r):void 0})}delete(t){return fetch(`${this.baseURL}/${t}`,{method:"DELETE",headers:{ChecksumAppCode:this.config.apiKey}})}putFile(t,r){return fetch(t,{method:"PUT",headers:{"Content-Type":r.type},body:r})}};e(Mzr,"RuntimeAPIService");Mzt=Mzr});var BHn={};cj(BHn,{VtgCloudAPIService:()=>X_t});var jzr,X_t,Uzr=Vt(()=>{"use strict";OHn();jzr=class jzr extends Mzt{constructor(r){super(r,"/client-api/runtime");this.config=r}};e(jzr,"VtgCloudAPIService");X_t=jzr});var Sz,LHn,CZ,qzr,jbe,RHn,MHn=Vt(()=>{"use strict";fD();ENn();fie();Q9e();w4e();mMt();Ume();ARr();Sz=require("fs"),LHn=hf(fMr()),CZ=hf(require("path"));YLn();yMr();N8();$Mn();VMn();zMn();JMn();WMn();XMn();yie();djr();IHn();nVr();FHn();qzr=1e3*30,jbe=class jbe extends vJe{constructor(r,a="normal",o,c,f,_,v,w,C,T,k,R,B){var X,ne,ce;super(r,o,k,()=>this.pageInteractor,void 0);this.page=r;this.runMode=a;this.testRunAnalytics=c;this.monitorBridge=f;this.testInfo=_;this.checksumTestId=v;this.test=w;this.options=C;this.isReplMode=T;this.config=k;this.pageInteractorAPI=R;this.lastInteractionTime=Date.now();this.hasRuntimeStartedTrace=!1;this.unzippedHarData=[];this.fallbacks=[];this.hasUsedAutoRecovery=!1;this.arSummaries=[];this.arStepIds=[];this.arResults=[];this.failedSteps=[];this.thoughtsCounter=0;this.highLevelThoughts=[];this.framesMsgBroker=new Fze;this.previousSteps=[];this.scriptLoadWrapper=e(async(r,a)=>(!this.isTimeMachineFrame(a)&&this.navigationPromise&&await this.navigationPromise,this.wrapInternalSteps(r,a.page())),"scriptLoadWrapper");this.scriptLoadCheck=e(async r=>r.evaluate(()=>!!window.checksum),"scriptLoadCheck");this.scriptLoadCallback=e(async r=>{await r.evaluate(async({appSpecificRules:a,esraTimeout:o,sessionRecorder:c,showFrontendLogs:f,showTMSeeker:_,filesObserver:v,nativeDialogObserver:w,assertionsObserver:C,actionsObserver:T,recordOptions:k})=>{var R;(R=window.checksum)==null||R.testGenerator.init(a,{esraTimeout:o,showFrontendLogs:f,skipElementHighlighting:!0,recordOptions:k},{assertionGenerator:!1,sessionRecorder:c,filesObserver:v,nativeDialogObserver:w,assertionsObserver:C,actionsObserver:T});try{_&&window.checksum.timeMachine.openSeekbar()}catch{}},{appSpecificRules:this.appSpecificRules,esraTimeout:qzr,sessionRecorder:!!(!this.isTimeMachineFrame(r)&&(this.timeMachine||this.isVTG)),showFrontendLogs:Pm.isDevMode,showTMSeeker:this.isTimeMachineFrame(r)&&process.env.CHECKSUM_SHOW_TIME_MACHINE==="true",filesObserver:this.isVTG&&!this.isTimeMachineFrame(r),nativeDialogObserver:this.isVTG&&!this.isTimeMachineFrame(r),assertionsObserver:this.isVTG&&!this.isTimeMachineFrame(r),actionsObserver:this.isVTG&&!this.isTimeMachineFrame(r),recordOptions:this.isVTG?this.getVTGRecordOptions():void 0}),ix(`[init] init script loaded for ${r.page().url()}`)},"scriptLoadCallback");jHn(C.printLogs),this.isVTG&&(this.options={...this.options,useChecksumAI:{actions:!1,assertions:!1,arVersion:1,visualComparison:!1},useMockData:!1,useChecksumSelectors:!1,autoHealPRs:!1},Uzt(this.page)),PHn(w)&&this.config.options.useChecksumAI.skipTestsWithKnownBugs&&(console.log("Auto recovery will not run for this test as it is marked as a known bug"),this.config.options.useChecksumAI.actions=!1,this.config.options.useChecksumAI.assertions=!1,this.config.options.useChecksumAI.visualComparison=!1),this.injectedScriptManager.setScriptLoadWrapper(this.scriptLoadWrapper).setScriptLoadCallback(this.scriptLoadCallback).setScriptLoadCheck(this.scriptLoadCheck);let U=jzt({config:this.config,throwIfAuthFailed:!0}),W=this.getPlaywrightProjectConfig();if(this.pageInteractor=new qve(this.evaluateWithChecksum.bind(this),()=>this.page.mainFrame(),()=>this.timeMachine,{log:ix,logError:ix},{navigationTimeout:(X=W.use)==null?void 0:X.navigationTimeout,actionTimeout:(ne=W.use)==null?void 0:ne.actionTimeout,testAssetsDir:Ldt(Gne()),waitActionDelay:1e3},this.pageInteractorAPI,U),this.checkForActiveTracing(),this.resetFallbacks(),B&&(this.highLevelThoughts=B.highLevelThoughts??[],this.timeMachineBrowserContext=B.timeMachineBrowserContext,this.variableStore=B.variableStore),Pm.testRun.timeMachine.active){let fe=this.shouldRecordRRwebEvents()?{recordRRwebEventsToFile:!0,recordRRwebEventsToFilePath:sTn(this.checksumTestId,this.testInfo.retry)}:{};this.isVTG||(this.timeMachine=new bQt(this.framesMsgBroker,this.injectedScriptManager,{...fe,headless:process.env.CHECKSUM_SHOW_TIME_MACHINE==="true"?!1:Pm.testRun.timeMachine.headless,webProxy:(ce=_.project.use)==null?void 0:ce.proxy}),this.timeMachineBrowserContext&&this.timeMachine.setTimeMachineBrowserContext(this.timeMachineBrowserContext))}}previousThoughtsAndTimestamps(){return this.previousSteps}static async init(r,a,o,c,f,_,v,w,C,T=!1){let k=!1;v||(v=await jbe.fetchVtgInternalTestId(C),v||(v=iRt(5),k=!0,console.warn(`Checksum test id was not defined for test "${_.title}" and was auto-generated. Please replace - "${_.title}" with -
|
|
642
642
|
test(defineChecksumTest("${_.title}", "${v}"), async ({ page }) => {...`))),c.addTestInfo(v,_.testId,k),C.options.useChecksumAI!==void 0&&typeof C.options.useChecksumAI=="boolean"&&(C.options.useChecksumAI={actions:C.options.useChecksumAI,assertions:!1,visualComparison:!1});let R=new sJe(C),B=new jbe(r,C.runMode,a,o,c,_,v,w,{useChecksumSelectors:!0,useChecksumAI:{actions:!0,assertions:!1},newAssertionsEnabled:C.runMode!=="normal",useMockData:!1,printLogs:!1,...C.options},T,C,R,{variableStore:f});return a.pages().length===0&&(w._checksum.expect.setPage(B),w._checksum.checksumAI.page=B,f.clearAll(),B.testRunAnalytics.testRunStart()),await B.asyncInit(),B.proxy}static async fetchVtgInternalTestId(r){try{let a=process.env.CHECKSUM_VTG_TEST_FILE_RUN_CONFIG;if(!a)return;let o=JSON.parse(a);if(o.mode!=="start"||!o.storyId)return;let{VtgUserStoryService:c}=await Promise.resolve().then(()=>(Rzr(),NHn)),{VtgCloudAPIService:f}=await Promise.resolve().then(()=>(Uzr(),BHn)),_=new f(r),v=new c(_,r);await v.fetchStory(o.storyId);let w=v.getStory();return w==null?void 0:w.internalTestId}catch(a){console.warn("Failed to fetch VTG internalTestId from story:",a);return}}async asyncInit(r=!1){await this.loadAppSpecificRules(),await this.wrapInternalSteps(async()=>{await this.page.addInitScript(()=>{window.sessionStorage.setItem("checksumai:disable","true")})}),this.timeMachine&&(await this.timeMachine.prepare(this.page.mainFrame()),this.timeMachineBrowserContext=this.timeMachine.getTimeMachineBrowserContext()),this.pageInteractor.init(),r||await this.prepareForTestArtifacts();let a=CZ.resolve(__dirname,"mock-auto-heal-agent.js");await this.page.addInitScript({path:a})}async makePage(r){let a=new jbe(r,this.runMode,this._context,this.testRunAnalytics,this.monitorBridge,this.testInfo,this.checksumTestId,this.test,this.options,this.isReplMode,this.config,this.pageInteractorAPI,{highLevelThoughts:this.highLevelThoughts,timeMachineBrowserContext:this.timeMachineBrowserContext,variableStore:this.variableStore});return await a.asyncInit(!0),a.proxy}getTimeMachinePage(){var r;return(r=this.timeMachine)==null?void 0:r.getPage()}getFramesMessageBroker(){return this.framesMsgBroker}isTimeMachineFrame(r){var a;return r===((a=this.timeMachine)==null?void 0:a.getFrame())}shouldRecordRRwebEvents(){return Pm.testRun.timeMachine.recordRRwebEventsToFile&&this.config.options.hostReports}recordInteraction(){let r=this.getPageGuid(this.page);jbe.recentlyInteracted.set(r,Date.now()),this.lastInteractionTime=Date.now()}static getMostRecentPage(r){let a=r.pages(),o=a[0],c=0;for(let f of a){let _=f._guid,v=jbe.recentlyInteracted.get(_)||0;v>c&&(c=v,o=f)}return o}async goto(r,a){return this.recordInteraction(),this.page.goto(r,a)}async reload(r){return this.recordInteraction(),this.page.reload(r)}async goBack(r){return this.recordInteraction(),this.page.goBack(r)}async goForward(r){return this.recordInteraction(),this.page.goForward(r)}async click(r,a){return this.recordInteraction(),this.page.click(r,a)}async dblclick(r,a){return this.recordInteraction(),this.page.dblclick(r,a)}async fill(r,a,o){return this.recordInteraction(),this.page.fill(r,a,o)}async press(r,a,o){return this.recordInteraction(),this.page.press(r,a,o)}async check(r,a){return this.recordInteraction(),this.page.check(r,a)}async uncheck(r,a){return this.recordInteraction(),this.page.uncheck(r,a)}async selectOption(r,a,o){return this.recordInteraction(),this.page.selectOption(r,a,o)}async hover(r,a){return this.recordInteraction(),this.page.hover(r,a)}async type(r,a,o){return this.recordInteraction(),this.page.type(r,a,o)}async setInputFiles(r,a,o){return this.recordInteraction(),this.page.setInputFiles(r,a,o)}async tap(r,a){return this.recordInteraction(),this.page.tap(r,a)}async dragAndDrop(r,a,o){return this.recordInteraction(),this.page.dragAndDrop(r,a,o)}getPlaywrightProjectConfig(){return this.testInfo.project}checkForActiveTracing(){var o;let a=(o=this.getPlaywrightProjectConfig().use)==null?void 0:o.trace;this.traceMode=typeof a=="string"?a:a==null?void 0:a.mode}registerPageEvents(){super.registerPageEvents(),this.injectedScriptManager.addTrackedFrame(this.page),this.page.on("framenavigated",async r=>{this.injectedScriptManager.onFrameNavigated(r)})}checksumSelector(r){return this.checksumStepId=r,this.options.useChecksumSelectors&&this.setSelectorFallback(r),this.proxy}checksumAI(r,a,o){let c=this.addNewThought(r,"action",!!a);this.previousSteps.push({thought:c.thought,timestamp:Date.now()});let f=this.getPageGuid(this.page);return qve.setLastAction(f,r),a&&typeof a=="function"?this.test.step(r,async _=>{var v;try{return o!=null&&o.withDialog&&this.pageInteractor.listenToDialog(),await a()}catch(w){if(c.children=[],!this.options.useChecksumAI.actions||o!=null&&o.withDialog||o!=null&&o.skipAutoRecovery)throw w;this.setAIFallback(r,"action");try{return await this.initiateFallbackSequence({type:"action",error:w,method:void 0,args:[],testInfo:this.testInfo,step:_},{fallbackTypes:[cbe,Mbe]})}catch(C){throw this.testRunAnalytics.testRunError({failedThought:r,error:(C==null?void 0:C.message)||"Unknown error"}),C}}finally{this.pageInteractor.removeListener("dialog"),this.currentThought=(v=this.currentThought)==null?void 0:v.parent}}):(this.options.useChecksumAI.actions&&!(o!=null&&o.skipAutoRecovery)&&this.setAIFallback(r,"action"),this.proxy)}resolveAssetsFolder(r){return r.map(a=>CZ.join(Ldt(Gne()),a))}getRuntimeOptions(){return this.options}addPwAnnotation(r){this.testInfo.annotations.push({type:r.type,description:`
|
|
643
643
|
${r.description}`})}async onTestComplete(r){this.testRunAnalytics.testRunEnd({success:r,autoRecoveryTriggered:this.hasUsedAutoRecovery,summaries:this.arSummaries}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoveryMetadata",data:{autoRecoveryTriggered:this.hasUsedAutoRecovery,autoRecovered:this.hasUsedAutoRecovery&&r}}),this.monitorBridge.addChecksumTestMetadata({checksumTestId:this.checksumTestId,pwTestId:this.testInfo.testId,retry:this.testInfo.retry,type:"autoRecoverySummaries",data:this.arSummaries}),this.cleanupMockData()}async wrapInternalSteps(r,a=this.page){try{return a.mainFrame()._checksumInternal=!0,a._checksumInternal=!0,await r()}finally{a.mainFrame()._checksumInternal=!1,a._checksumInternal=!1}}async conditionallyWrapInternalSteps(r,a){return r?this.wrapInternalSteps(a):a()}async wrapNoLocationSteps(r){try{return this.testInfo._checksumNoLocation=!0,await r()}finally{this.testInfo._checksumNoLocation=!1}}findAllStepsRecursively(r,a,o=[]){for(let c of r){(c._stepId===a||c.stepId===a)&&o.push(c);let f=[c.steps,c._testInfoSteps,c._steps].filter(Boolean);for(let _ of f)this.findAllStepsRecursively(_,a,o)}return o}makeChecksumStepFunction(r){return a=>{if(!r)return;let o=a._stepId||a.stepId;this.findAllStepsRecursively(a._testInfo._steps,o).forEach(f=>{f.error={message:"ChecksumStepError",stack:"Fallback Failed",cause:void 0}})}}async createChecksumStep(r){let a,o={box:!0,noLocation:!0,obtainStep:e(c=>{a=c},"obtainStep")};return await this.step(r.title,this.makeChecksumStepFunction(r.withError),!1,o),this.arStepIds.push(a.stepId),a}async step(r,a,o=!0,{obtainStep:c=void 0,box:f=!1,noLocation:_=void 0}={}){let v=this.testInfo._checksumNoLocation;try{this.testInfo._checksumInternal=o===!0,_!==void 0&&(this.testInfo._checksumNoLocation=_),await this.test.step(r,a||(()=>{}),{obtainStep:c,box:f})}finally{this.testInfo._checksumInternal=!1,this.testInfo._checksumNoLocation=v}}addErrorMessage(r,a){this.testInfo.addError(r,a)}async evaluateWithChecksum(r,a,o=!0){return this.navigationPromise&&await this.navigationPromise,this.conditionallyWrapInternalSteps(o,()=>this.page.evaluate(r,a))}getChecksumTestId(){return this.checksumTestId}addNewThought(r,a,o=!1){let c={id:void 0,thought:r,type:a,children:o?[]:void 0,parent:void 0};if(!this.currentThought)this.highLevelThoughts.push(c);else if(this.currentThought.children)this.currentThought.children.push(c),c.parent=this.currentThought;else{let f=this.currentThought.parent;f?(f.children.push(c),c.parent=f):this.highLevelThoughts.push(c)}return c.parent?c.id=`${c.parent.id}.${c.parent.children.length}`:c.id=`${++this.thoughtsCounter}`,this.currentThought=c,c}buildThoughtsChainForFallback(r=this.highLevelThoughts){let a=[];return r.forEach(o=>{a.push(o.thought),o.children&&a.push(...this.buildThoughtsChainForFallback(o.children))}),a}getVTGRecordOptions(){return{recordCanvas:!0,recordCrossOriginIframes:this.isVTG,sampling:{mousemove:!1},slimDOMOptions:"all"}}compoundSelection(...r){let a=super.compoundSelection(...r);return a.setAnalytics(()=>this.testRunAnalytics),this.checksumStepId&&this.options.useChecksumSelectors&&this.setCompoundSelectorFallback(this.checksumStepId),a}setSelectorFallback(r){let a={checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:qzr};this.pushFallback(this.constructFallback(wmt).init(a)),this.pushFallback(this.constructFallback(Amt).init(a))}setCompoundSelectorFallback(r){this.pushFallback(this.constructFallback(Emt).init({checksumId:r,fileName:this.testInfo.file,testId:this.checksumTestId,apiKey:this.config.apiKey,apiURL:this.config.apiURL,timeout:qzr}))}setAIFallback(r,a){var _;let o=((_=this.options.useChecksumAI)==null?void 0:_.arVersion)===1,c=e(()=>{var R,B;let v=this.buildThoughtsChainForFallback(),w={title:this.testInfo.title},C={testFileName:this.testInfo.file,testId:this.testInfo.testId,testSuiteId:process.env.CHECKSUM_TEST_SUITE_ID||""},T={previous:v.slice(0,-1),failing:r,next:v.slice(1)},k={storyInfo:w,testIdentification:C,fallbackConfig:{arMode:(R=this.options.useChecksumAI)==null?void 0:R.arMode,overrideOptions:(B=this.options.useChecksumAI)==null?void 0:B.overrideOptions},thoughts:T,config:{apiURL:this.config.apiURL,apiKey:this.config.apiKey},type:a};return this.constructFallback(Mbe).init(k)},"createArFallback"),f=e(()=>{var v,w;return this.constructFallback(cbe).init({goal:this.testInfo.title,testFile:this.testInfo.file,apiKey:this.config.apiKey,apiURL:this.config.apiURL,testId:this.checksumTestId,thoughts:this.buildThoughtsChainForFallback(),benchmark:Pm.benchmark,arMode:(v=this.options.useChecksumAI)==null?void 0:v.arMode,overrideOptions:(w=this.options.useChecksumAI)==null?void 0:w.overrideOptions,fallbackType:a})},"createAIFallback");return o?this.pushFallback(f()):this.pushFallback(c()),this.proxy}pushFallback(r){this.fallbacks.push(r),this.sortFallbacks()}handleAIFallback(r,a,o,c){let f=r.fallbackAnalyticsPayload.iterationSteps,_=f.length>0?c/f.length:0;this.testRunAnalytics.testRunFallbackExecution({result:o.fbResult,failedThought:r.getFailedThought(),summary:o.summary,stepsPayload:r.fallbackAnalyticsPayload,type:r.fallbackType??a.type,benchmark:Pm.benchmark.toString(),duration:c,avgDuration:_,success:["finish","soft_assertion"].includes(o.fbResult)}),this.arResults.push({failedThought:r.getFailedThought(),result:o.fbResult,thought:o.thought})}handleAutoRecovery(r,a,o,c){let f=o.stepsThoughts.length>0?c/o.stepsThoughts.length:0;this.testRunAnalytics.testRunAutoRecovery({failingThought:r.failingThought,type:a.type,finalThought:o.thought,result:o.fbResult,duration:c,avgStepDuration:f,stepsThoughts:o.stepsThoughts,version:"v1"})}async runFallback(r,a){let o=Date.now(),c=r.resolve(a),f=await pD(c,r.timeout),_=Date.now()-o;r instanceof cbe&&(this.hasUsedAutoRecovery=!0,this.handleAIFallback(r,a,f,_)),r instanceof Mbe&&(this.hasUsedAutoRecovery=!0,this.handleAutoRecovery(r,a,f,_));let v=f.thought?`: ${f.thought}`:"";if(!f||f.fbResult==="failed")throw this.createChecksumStep({title:`Recovery Failed${v}`,withError:!0}),new Error("Fallback failed");if(f.fbResult==="hard_assertion")throw this.createChecksumStep({title:`Recovery Failed${v}`,withError:!0}),new dmt(f.fbResult);if(r instanceof cbe&&f.summary&&this.arSummaries.push(f.summary),r instanceof Mbe&&f.thought&&this.arSummaries.push(f.thought),this.createChecksumStep({title:`Recovery Complete${v}`}),f.steps.length===1){let w=f.steps[0];w.thought&&(this.currentThought.thought=w.thought)}else this.currentThought.children=f.steps.map((w,C)=>({id:`${this.currentThought.id}.${C+1}`,thought:w.thought,type:w.type,children:void 0,parent:this.currentThought}))}async runConditionallyWithinStep(r,a,o){return r?await this.step(a,o):await o()}async onExecutionError(r){try{return await this.initiateFallbackSequence({type:"action",...r})}catch(a){if(!this.currentThought){let{locator:o,method:c}=r;this.testRunAnalytics.testRunActionExecutionFailure({locator:o.toString(),selector:o._selector,method:c,checksumStepId:this.checksumStepId,error:a.toString()})}throw a}}async initiateFallbackSequence(r,{fallbackTypes:a=void 0}={}){ix(`[initiateFallbackSequence] with type: ${r.type}...`);let o=this.fallbacks.find(_=>_ instanceof cbe);if(o){let _=o.getFailedThought(),v=this.variableStore.getActiveVariables();this.fallbacks.forEach(w=>{w.setThought(_),w.setVariables(v)})}let c=this.fallbacks.find(_=>_ instanceof Mbe);if(c){let _=c.failingThought;this.fallbacks.forEach(v=>{v instanceof Mbe&&v.setVariables(this.variableStore.getActiveVariables()),v.setThought(_)})}let f=this.fallbacks;a&&(f=f.filter(_=>a.reduce((v,w)=>v||_ instanceof w,!1))),f=f.filter(_=>_.canResolve(r));try{for(let _ of f){let v=_==null?void 0:_.toString();v&&console.log(`Using ${v}`);let w;try{let C=await this.runConditionallyWithinStep(r.type!=="assertion"||!r.withChecksumAI,_.getRecoveryAttemptTitle(r),async()=>await this.runFallback(_,r));w=!0}catch(C){if(w=!1,r.withChecksumAI&&C.message==="fetch failed")throw new Error(_Je);C instanceof dmt&&C.fallbackResult==="hard_assertion"&&(r.error.fallbackResult="hard_assertion"),v&&console.log(`Failed to use ${v}`),_.cancel();continue}return!0}throw r.error}finally{this.resetFallbacks()}}resetFallbacks(){this.fallbacks=[this.constructFallback(Cmt).init()]}async shutdown(){if(this.shouldRecordRRwebEvents()){try{await this.timeMachine.flushRRwebEventsToFile();let r=this.timeMachine.getRRwebFilePath();this.monitorBridge.addAsset({type:"rrweb-recording",path:r,testId:this.checksumTestId,fileName:CZ.basename(r)})}catch(r){ix("Error shutting down RRweb events recording",r)}if(this.testRunAnalytics)return ix("Flushing analytics events......"),this.testRunAnalytics.close()}}sortFallbacks(){let r=[Cmt,Emt,wmt,Amt,cbe];this.fallbacks.sort((a,o)=>r.indexOf(a.constructor)-r.indexOf(o.constructor))}constructFallback(r){return new r(this.page,this.evaluateWithChecksum.bind(this),this,this.pageInteractor,{generateSelectionData:this.runMode!=="normal"},this,this._context)}async prepareForTestArtifacts(){if((this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock(),this.traceMode&&this.traceMode!=="off"){let a=await this.getTraceFilePath();a&&this.monitorBridge.addAsset({type:"trace",path:a,testId:this.checksumTestId,project:this.testInfo.project.name})}if(!1){let a=aTn(dMt(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:a,testId:this.checksumTestId})}}async getTraceFilePath(){try{return this.hasRuntimeStartedTrace?oTn(dMt(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}catch{return}}async prepareMockData(){let r=ZIr(dMt(this.testInfo.file)),a=CZ.join(r,`${this.checksumTestId}.har.zip`);if(!(0,Sz.existsSync)(a))throw new Error("Could not find har file or zip file");let o=CZ.join(r,"tmp");(0,Sz.existsSync)(o)||(0,Sz.mkdirSync)(o);let c=(0,Sz.readFileSync)(a),f=await(0,LHn.loadAsync)(c);for(let v of Object.keys(f.files)){let w=await f.file(v).async("string"),C=CZ.join(o,v);(0,Sz.writeFileSync)(C,w),this.unzippedHarData.push(C)}let _=CZ.join(o,"test.har");if(!(0,Sz.existsSync)(_))throw this.cleanupMockData(),new Error(`Could not find har file ${_} after unzipping ${a}`);return _}cleanupMockData(){this.unzippedHarData.forEach(r=>{(0,Sz.rmSync)(r)}),this.unzippedHarData.length>0&&(0,Sz.rmSync)(CZ.dirname(this.unzippedHarData[0]),{recursive:!0,force:!0})}async prepareAPIMock(){let r={GET:0,POST:0,PUT:0,DELETE:0};try{let a=await this.prepareMockData();await this.page.routeFromHAR(a,{url:"*/**",notFound:"fallback",update:!1});let o=this.page._routes[0].handler;await this.page.route("**/*",c=>{let f=c.request().headers(),_=c.request().method();f["Checksum-Id"]=(++r[_]).toString(),c.request()._applyFallbackOverrides({headers:f}),o(c)})}catch(a){ix("Error setting up mock data",a.message)}}async loadAppSpecificRules(){this.appSpecificRules={};let r=CZ.join(q9e(Gne()),"settings.asr");if(!(0,Sz.existsSync)(r)){ix("Could not find ASR file");return}let{ungzip:a}=XIr();try{let o=await a((0,Sz.readFileSync)(r));this.appSpecificRules=JSON.parse(o)||{}}catch(o){ix("Could not read ASR file",o.message)}}addAutoRecoveryStepId(r){this.arStepIds.push(r)}};e(jbe,"RuntimePage"),jbe.recentlyInteracted=new Map;RHn=jbe});function dCa(i,t){return t}function mCa(i,t){return i.filter(r=>r!==void 0)}function qHn(i){return typeof i!="object"||i===null?0:Array.isArray(i)?2:gCa(i)?1:i instanceof Set?3:i instanceof Map?4:5}function _Ca(i){let t=new Set;for(let r of i)for(let a of[...Object.keys(r),...Object.getOwnPropertySymbols(r)])t.add(a);return t}function hCa(i,t){return typeof i=="object"&&Object.prototype.propertyIsEnumerable.call(i,t)}function $Hn(i){var a;let t=0,r=(a=i[0])==null?void 0:a[Symbol.iterator]();return{[Symbol.iterator](){return{next(){var o;do{if(r===void 0)return{done:!0,value:void 0};let c=r.next();if(c.done===!0){t+=1,r=(o=i[t])==null?void 0:o[Symbol.iterator]();continue}return{done:!1,value:c.value}}while(!0)}}}}}function gCa(i){if(!QHn.includes(Object.prototype.toString.call(i)))return!1;let{constructor:t}=i;if(t===void 0)return!0;let r=t.prototype;return!(r===null||typeof r!="object"||!QHn.includes(Object.prototype.toString.call(r))||!r.hasOwnProperty("isPrototypeOf"))}function yCa(i,t,r){let a={};for(let o of _Ca(i)){let c=[];for(let v of i)hCa(v,o)&&c.push(v[o]);if(c.length===0)continue;let f=t.metaDataUpdater(r,{key:o,parents:i}),_=VHn(c,t,f);_!==k7e.skip&&(o==="__proto__"?Object.defineProperty(a,o,{value:_,configurable:!0,enumerable:!0,writable:!0}):a[o]=_)}return a}function vCa(i){return i.flat()}function bCa(i){return new Set($Hn(i))}function xCa(i){return new Map($Hn(i))}function ACa(i){return i.at(-1)}function Qzt(...i){return ECa({})(...i)}function ECa(i,t){let r=wCa(i,a);function a(...o){return VHn(o,r,t)}return e(a,"customizedDeepmerge"),a}function wCa(i,t){return{defaultMergeFunctions:qzt,mergeFunctions:{...qzt,...Object.fromEntries(Object.entries(i).filter(([r,a])=>Object.hasOwn(qzt,r)).map(([r,a])=>a===!1?[r,qzt.mergeOthers]:[r,a]))},metaDataUpdater:i.metaDataUpdater??dCa,deepmerge:t,useImplicitDefaultMerging:i.enableImplicitDefaultMerging??!1,filterValues:i.filterValues===!1?void 0:i.filterValues??mCa,actions:k7e}}function VHn(i,t,r){var c;let a=((c=t.filterValues)==null?void 0:c.call(t,i,r))??i;if(a.length===0)return;if(a.length===1)return Qzr(a,t,r);let o=qHn(a[0]);if(o!==0&&o!==5){for(let f=1;f<a.length;f++)if(qHn(a[f])!==o)return Qzr(a,t,r)}switch(o){case 1:return CCa(a,t,r);case 2:return SCa(a,t,r);case 3:return DCa(a,t,r);case 4:return TCa(a,t,r);default:return Qzr(a,t,r)}}function CCa(i,t,r){let a=t.mergeFunctions.mergeRecords(i,t,r);return a===k7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeRecords!==t.defaultMergeFunctions.mergeRecords?t.defaultMergeFunctions.mergeRecords(i,t,r):a}function SCa(i,t,r){let a=t.mergeFunctions.mergeArrays(i,t,r);return a===k7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeArrays!==t.defaultMergeFunctions.mergeArrays?t.defaultMergeFunctions.mergeArrays(i):a}function DCa(i,t,r){let a=t.mergeFunctions.mergeSets(i,t,r);return a===k7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeSets!==t.defaultMergeFunctions.mergeSets?t.defaultMergeFunctions.mergeSets(i):a}function TCa(i,t,r){let a=t.mergeFunctions.mergeMaps(i,t,r);return a===k7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeMaps!==t.defaultMergeFunctions.mergeMaps?t.defaultMergeFunctions.mergeMaps(i):a}function Qzr(i,t,r){let a=t.mergeFunctions.mergeOthers(i,t,r);return a===k7e.defaultMerge||t.useImplicitDefaultMerging&&a===void 0&&t.mergeFunctions.mergeOthers!==t.defaultMergeFunctions.mergeOthers?t.defaultMergeFunctions.mergeOthers(i):a}var k7e,fNs,UHn,QHn,qzt,$zr=Vt(()=>{k7e={defaultMerge:Symbol("deepmerge-ts: default merge"),skip:Symbol("deepmerge-ts: skip")},fNs={defaultMerge:k7e.defaultMerge};e(dCa,"defaultMetaDataUpdater");e(mCa,"defaultFilterValues");(function(i){i[i.NOT=0]="NOT",i[i.RECORD=1]="RECORD",i[i.ARRAY=2]="ARRAY",i[i.SET=3]="SET",i[i.MAP=4]="MAP",i[i.OTHER=5]="OTHER"})(UHn||(UHn={}));e(qHn,"getObjectType");e(_Ca,"getKeys");e(hCa,"objectHasProperty");e($Hn,"getIterableOfIterables");QHn=["[object Object]","[object Module]"];e(gCa,"isRecord");e(yCa,"mergeRecords$1");e(vCa,"mergeArrays$1");e(bCa,"mergeSets$1");e(xCa,"mergeMaps$1");e(ACa,"mergeOthers$1");qzt={mergeRecords:yCa,mergeArrays:vCa,mergeSets:bCa,mergeMaps:xCa,mergeOthers:ACa};e(Qzt,"deepmerge");e(ECa,"deepmergeCustom");e(wCa,"getUtils");e(VHn,"mergeUnknowns");e(CCa,"mergeRecords");e(SCa,"mergeArrays");e(DCa,"mergeSets");e(TCa,"mergeMaps");e(Qzr,"mergeOthers")});function jHn(i){JHn=i}function ix(...i){JHn&&console.log(...i)}async function LMn(i,t,r,a=6e4){if(!(t in i))return i;let o=e(()=>i[t](...r),"executor");return a===null?o():pD(o(),a,"Execution timeout")}function Lzr(i,{role:t,environment:r}={},a=!1){var _,v;let o;if(r&&(o=(_=i.environments)==null?void 0:_.find(({name:w})=>r===w)),o||(o=(v=i.environments)==null?void 0:v.find(({default:w})=>w)),!o)throw new Error("Environment not found. Please make sure your environments are properly defined in the checksum.config.ts file.");let c=o.users,f;if(c&&(t!==void 0&&(f=c.find(w=>w.role===t)),f||(f=c.find(w=>w.default))),!f)throw new Error(`User not found. Please make sure the users array for the "${o.name}" environment is properly defined in the checksum.config.ts file.`);if(r&&o.name!==r){if(a)throw new Error(`Could not find environment with name "${r}" in config file`);console.warn(`Could not find environment with name "${r}" in config file, trying to use default environment`)}if(t&&f.role!==t){if(a)throw new Error(`Could not find user with role "${t}" for environment "${r}" in config file`);console.warn(`Could not find user with role "${t}" for environment "${r}" in config file, trying to login with environment's default user`)}return{environment:o,user:f}}function kCa(i){let t=`${i??Gne()}/login.ts`;if(!(0,$zt.existsSync)(t))throw console.warn(`Could not locate the login.ts file. Please make sure your login file exists at ${t}`),new Error("Could not find login.ts file");try{return require(t).default}catch(r){throw console.warn("Error loading login.ts file",r),r}}async function ICa(i,t,{environment:r,user:a,config:o}){try{let c=e(()=>t(i,{environment:r,user:a,config:o}),"performLogin");"checksumAI"in i?await i.checksumAI(`Log in${a!=null&&a.role?` using ${a.role} role`:""}${r!=null&&r.name?` in ${r.name} environment`:""}`,c,{skipAutoRecovery:!0}):await c()}catch(c){throw console.warn(`The login method threw an exception, please check the login.ts file for the following error:
|