@checksum-ai/runtime 1.0.31 → 1.0.33

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.
@@ -37,7 +37,7 @@ export default defineConfig({
37
37
  locale: "en-US",
38
38
  timezoneId: "America/Los_Angeles",
39
39
  permissions: ["clipboard-read"],
40
- actionTimeout: undefined, // Keep action timeout undefined as Checksum implements its own timeout
40
+ actionTimeout: 1000 * 5, // set action timeout for 5 seconds. In case an aciton times out, checksum's selectors will kick in.
41
41
  },
42
42
  expect: {
43
43
  toHaveScreenshot: { maxDiffPixelRatio: 0.05, maxDiffPixels: 200 },
package/cli.js CHANGED
@@ -10,10 +10,10 @@ show-report [options] [report] show HTML report
10
10
  `);break;case"test":try{let e="npx playwright test --help",s=(await this.getCmdOutput(e)).replace(/npx playwright/g,"yarn checksum").split(`
11
11
  `);s.splice(5,0," --checksum-config=<config> Checksum configuration in JSON format").join(`
12
12
  `),console.log(s.join(`
13
- `))}catch(e){console.log("Error",e.message)}break;case"show-report":try{let e="npx playwright show-report --help",s=(await this.getCmdOutput(e)).replace(/npx playwright/g,"yarn checksum");console.log(s)}catch(e){console.log("Error",e.message)}break}}async showReport(t){let e=`npx playwright show-report ${t.join(" ")}`;try{await this.execCmd(e)}catch(s){console.log("Error showing report",s.message)}}async test(t){this.processChecksumArguments(t),this.setChecksumConfig(),await this.getSession();let e;try{e=await this.guardReturn(this.startTestRunMonitor(this.testSession),1e4,"test run monitor timeout")}catch{console.log("Error starting test run monitor. Test results will not be available on checksum.")}this.buildVolatileConfig();let s=`${e?`CHECKSUM_UPLOAD_AGENT_PORT=${e} `:""}${this.config.options.hostReports&&!this.isolatedMode?" PW_TEST_HTML_REPORT_OPEN=never":""} npx playwright test --config ${this.getPlaywrightConfigFile()} ${t.join(" ")}`;await this.patchPlaywright();try{await this.execCmd(s),console.log("Tests execution finished")}catch(o){this.didFail=!0,console.log("Error during test",o.message)}finally{let o=this.getPlaywrightReportPath();(0,i.existsSync)(o)?this.testRunMonitorProcess.stdin.write(`cli:report=${o}`):console.log(`Could not find report file at ${o}`),await this.patchPlaywright(!0),this.completeIndicators.tests=!0,await this.handleCompleteMessage()}}async patchPlaywright(t=!1){let e=`bash ${(0,r.join)(__dirname,"scripts/patch.sh")}${t?" off":""}`;try{await this.execCmd(e)}catch(s){console.log("Error patching playwright",s.message)}}getPlaywrightReportPath(){var o,a;let t=(0,r.join)(process.cwd(),"playwright-report"),e=require(this.getPlaywrightConfigFile()),{reporter:s}=e;return s instanceof Array&&s.length>1&&((o=s[1])!=null&&o.outputFolder)&&(t=(a=s[1])==null?void 0:a.outputFolder),process.env.PLAYWRIGHT_HTML_REPORT&&(t=process.env.PLAYWRIGHT_HTML_REPORT),(0,r.join)(t,"index.html")}getPlaywrightConfigFile(){return(0,r.join)(this.getRootDirPath(),"playwright.config.ts")}startTestRunMonitor(t){return new Promise(e=>{console.log("Starting test run monitor"),this.testRunMonitorProcess=l.spawn("node",[this.TEST_RUN_MONITOR_PATH,JSON.stringify({sessionId:t,checksumApiURL:this.CHECKSUM_API_URL,apiKey:this.config.apiKey}),...this.isolatedMode?["isolated"]:[]]),this.testRunMonitorProcess.stdout.on("data",s=>{var p,d;let o=s.toString().trim();if(!o.startsWith("monitor")){(d=(p=this.config)==null?void 0:p.options)!=null&&d.printLogs&&console.log(`Message from test run monitor: ${o}`);return}let[a,c]=o.substring(o.indexOf(":")+1).split("=");a==="port"?e(c):this.handleTestRunMonitorMessage(a,c)}),this.testRunMonitorProcess.on("exit",(s,o)=>{console.log(`test run monitor process exited with code ${s} and signal ${o}`)}),this.testRunMonitorProcess.on("error",s=>{console.error(`Error starting test run monitor: ${s.message}`)})})}async handleTestRunMonitorMessage(t,e){switch(t){case"complete":this.isolatedMode||console.log("Test artifacts uploaded successfully"),this.sendUploadsComplete().then(()=>{this.completeIndicators.upload=!0});break;case"report-uploaded":{if(this.isolatedMode){this.completeIndicators.report=!0;break}console.log("Report generated and uploaded to checksum");let s={};try{s=JSON.parse(e)}catch(o){console.log("Error parsing stats",o.message)}await this.sendTestRunEnd(s),this.completeIndicators.report=!0,console.log(`*******************
13
+ `))}catch(e){console.log("Error",e.message)}break;case"show-report":try{let e="npx playwright show-report --help",s=(await this.getCmdOutput(e)).replace(/npx playwright/g,"yarn checksum");console.log(s)}catch(e){console.log("Error",e.message)}break}}async showReport(t){let e=`npx playwright show-report ${t.join(" ")}`;try{await this.execCmd(e)}catch(s){console.log("Error showing report",s.message)}}async test(t){this.processChecksumArguments(t),this.setChecksumConfig(),await this.getSession();let e;try{e=await this.guardReturn(this.startTestRunMonitor(this.testSession),1e4,"test run monitor timeout")}catch{console.log("Error starting test run monitor. Test results will not be available on checksum.")}this.buildVolatileConfig();let s=`${e?`CHECKSUM_UPLOAD_AGENT_PORT=${e} `:""}${this.config.options.hostReports&&!this.isolatedMode?" PW_TEST_HTML_REPORT_OPEN=never":""} npx playwright test --config ${this.getPlaywrightConfigFile()} ${t.join(" ")}`;await this.patchPlaywright();try{await this.execCmd(s),console.log("Tests execution finished")}catch(o){this.didFail=!0,console.log("Error during test",o.message)}finally{let o=this.getPlaywrightReportPath();(0,i.existsSync)(o)?this.testRunMonitorProcess.stdin.write(`cli:report=${o}`):console.log(`Could not find report file at ${o}`),await this.patchPlaywright(!0),this.completeIndicators.tests=!0,await this.handleCompleteMessage()}}async patchPlaywright(t=!1){let e=`bash ${(0,r.join)(__dirname,"scripts/patch.sh")}${t?" off":""}`;try{await this.execCmd(e)}catch(s){console.log("Error patching playwright",s.message)}}getPlaywrightReportPath(){var o,a;let t=(0,r.join)(process.cwd(),"playwright-report"),e=require(this.getPlaywrightConfigFile()),{reporter:s}=e;return s instanceof Array&&s.length>1&&((o=s[1])!=null&&o.outputFolder)&&(t=(a=s[1])==null?void 0:a.outputFolder),process.env.PLAYWRIGHT_HTML_REPORT&&(t=process.env.PLAYWRIGHT_HTML_REPORT),(0,r.join)(t,"index.html")}getPlaywrightConfigFile(){return(0,r.join)(this.getRootDirPath(),"playwright.config.ts")}startTestRunMonitor(t){return new Promise(e=>{console.log("Starting test run monitor"),this.testRunMonitorProcess=l.spawn("node",[this.TEST_RUN_MONITOR_PATH,JSON.stringify({sessionId:t,checksumApiURL:this.CHECKSUM_API_URL,apiKey:this.config.apiKey}),...this.isolatedMode?["isolated"]:[]]),this.testRunMonitorProcess.stdout.on("data",s=>{var p,d;let o=s.toString().trim();if(!o.startsWith("monitor")){(d=(p=this.config)==null?void 0:p.options)!=null&&d.printLogs&&console.log(`Message from test run monitor: ${o}`);return}let[a,c]=o.substring(o.indexOf(":")+1).split("=");a==="port"?e(c):this.handleTestRunMonitorMessage(a,c)}),this.testRunMonitorProcess.on("exit",(s,o)=>{console.log(`test run monitor process exited with code ${s} and signal ${o}`)}),this.testRunMonitorProcess.on("error",s=>{console.error(`Error starting test run monitor: ${s.message}`)})})}async handleTestRunMonitorMessage(t,e){switch(t){case"complete":this.isolatedMode||console.log("Test artifacts uploaded successfully"),this.sendUploadsComplete().then(()=>{this.completeIndicators.upload=!0});break;case"report-uploaded":{if(this.isolatedMode){this.completeIndicators.report=!0;break}console.log("Report generated and uploaded to Checksum");let s={};try{s=JSON.parse(e)}catch(o){console.log("Error parsing stats",o.message)}await this.sendTestRunEnd(s),this.completeIndicators.report=!0,console.log(`*******************
14
14
  * Checksum report URL: ${this.CHECKSUM_APP_URL}/#/test-runs/${this.testSession}
15
15
  *******************`);break}default:console.warn(`Unhandled test run monitor message: ${t}=${e}`)}}async handleCompleteMessage(){for(;;)Object.keys(this.completeIndicators).find(t=>!this.completeIndicators[t])?await this.awaitSleep(1e3):(console.log("Checksum test run complete"),this.shutdown(this.didFail?1:0))}shutdown(t=0){this.cleanup(),process.exit(t)}buildVolatileConfig(){if(!this.volatileChecksumConfig)return;let t=this.getVolatileConfigPath(),e=`
16
16
  import { RunMode, getChecksumConfig } from "@checksum-ai/runtime";
17
17
 
18
18
  export default getChecksumConfig(${JSON.stringify(this.config,null,2)});
19
- `;(0,i.writeFileSync)(t,e)}cleanup(){this.deleteVolatileConfig(),this.testRunMonitorProcess.stdin.write("cli:shutdown"),this.testRunMonitorProcess.kill()}async getSession(){try{if(!this.config.options.hostReports){this.setIsolatedMode();return}let t=this.config.apiKey;(!t||t==="<API key>")&&(console.error("No API key found in checksum config"),this.shutdown(1));let e=JSON.stringify(await this.getEnvInfo()),s=await fetch(`${this.CHECKSUM_API_URL}/client-api/test-runs`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:t},body:e});this.testSession=(await s.json()).uuid}catch{console.log("Error getting checksum test session, will run in isolation mode"),this.setIsolatedMode()}}setIsolatedMode(){this.isolatedMode=!0,this.testSession="isolated-session"}async sendTestRunEnd(t){if(!this.isolatedMode)try{let e=JSON.stringify({...t,endedAt:Date.now()});await this.updateTestRun(`${this.CHECKSUM_API_URL}/client-api/test-runs/${this.testSession}`,"PATCH",e)}catch(e){return console.log("Error sending test run end",e.message),null}}async sendUploadsComplete(){if(!this.isolatedMode)try{await this.updateTestRun(`${this.CHECKSUM_API_URL}/client-api/test-runs/${this.testSession}/uploads-completed`,"PATCH")}catch(t){console.log("Error sending test run uploads complete",t.message)}}async updateTestRun(t,e,s=void 0){return(await fetch(t,{method:e,headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:s})).json()}async getEnvInfo(){let t={commitHash:"",branch:"branch",environment:process.env.CI?"CI":"local",name:"name",startedAt:Date.now()};try{t.commitHash=(await this.getCmdOutput("git rev-parse HEAD")).toString().trim()}catch(e){console.log("Error getting git hash",e.message)}try{t.branch=(await this.getCmdOutput("git rev-parse --abbrev-ref HEAD")).toString().trim()}catch(e){console.log("Error getting branch name",e.message)}return t}getVolatileConfigPath(){return(0,r.join)(this.getRootDirPath(),"checksum.config.tmp.ts")}deleteVolatileConfig(){let t=this.getVolatileConfigPath();(0,i.existsSync)(t)&&(0,i.rmSync)(t)}setChecksumConfig(){this.config={...require((0,r.join)(this.getRootDirPath(),"checksum.config.ts")).default||{},...this.volatileChecksumConfig||{}},this.config.apiURL&&(this.CHECKSUM_API_URL=this.config.apiURL)}processChecksumArguments(t){this.deleteVolatileConfig();for(let e of t)if(e.startsWith("--checksum-config"))try{this.volatileChecksumConfig=JSON.parse(e.split("=")[1]),t=t.filter(s=>s!==e)}catch(s){console.log("Error parsing checksum config",s.message),this.volatileChecksumConfig=void 0}}install(){console.log("Creating Checksum directory and necessary files to run your tests");let t=this.getRootDirPath();if((0,i.existsSync)(this.getRootDirPath())||(0,i.mkdirSync)(t),!(0,i.existsSync)(this.getChecksumRootOrigin()))throw new Error("Could not find checksum root directory, please install @checksum-ai/runtime package");["checksum.config.ts","playwright.config.ts","login.ts","README.md"].forEach(e=>{(0,i.copyFileSync)((0,r.join)(this.getChecksumRootOrigin(),e),(0,r.join)(t,e))}),(0,i.mkdirSync)((0,r.join)(t,"tests"),{recursive:!0}),["esra","har","trace","log"].forEach(e=>{(0,i.mkdirSync)((0,r.join)(t,"test-data",e),{recursive:!0})})}getRootDirPath(){return(0,r.join)(process.cwd(),m)}getChecksumRootOrigin(){return(0,r.join)(process.cwd(),"node_modules","@checksum-ai","runtime","checksum-root")}};u(h,"ChecksumCLI");(async()=>await new h().execute())();
19
+ `;(0,i.writeFileSync)(t,e)}cleanup(){this.deleteVolatileConfig(),this.testRunMonitorProcess.stdin.write("cli:shutdown"),this.testRunMonitorProcess.kill()}async getSession(){try{if(!this.config.options.hostReports){this.setIsolatedMode();return}let t=this.config.apiKey;(!t||t==="<API key>")&&(console.error("No API key found in checksum config"),this.shutdown(1));let e=JSON.stringify(await this.getEnvInfo()),s=await fetch(`${this.CHECKSUM_API_URL}/client-api/test-runs`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:t},body:e});this.testSession=(await s.json()).uuid}catch{console.log("Error connecting to Checksum, the report will not be hosted"),this.setIsolatedMode()}}setIsolatedMode(){this.isolatedMode=!0,this.testSession="isolated-session"}async sendTestRunEnd(t){if(!this.isolatedMode)try{let e=JSON.stringify({...t,endedAt:Date.now()});await this.updateTestRun(`${this.CHECKSUM_API_URL}/client-api/test-runs/${this.testSession}`,"PATCH",e)}catch(e){return console.log("Error sending test run end",e.message),null}}async sendUploadsComplete(){if(!this.isolatedMode)try{await this.updateTestRun(`${this.CHECKSUM_API_URL}/client-api/test-runs/${this.testSession}/uploads-completed`,"PATCH")}catch(t){console.log("Error sending test run uploads complete",t.message)}}async updateTestRun(t,e,s=void 0){return(await fetch(t,{method:e,headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:s})).json()}async getEnvInfo(){let t={commitHash:"",branch:"branch",environment:process.env.CI?"CI":"local",name:"name",startedAt:Date.now()};try{t.commitHash=(await this.getCmdOutput("git rev-parse HEAD")).toString().trim()}catch(e){console.log("Error getting git hash",e.message)}try{t.branch=(await this.getCmdOutput("git rev-parse --abbrev-ref HEAD")).toString().trim()}catch(e){console.log("Error getting branch name",e.message)}return t}getVolatileConfigPath(){return(0,r.join)(this.getRootDirPath(),"checksum.config.tmp.ts")}deleteVolatileConfig(){let t=this.getVolatileConfigPath();(0,i.existsSync)(t)&&(0,i.rmSync)(t)}setChecksumConfig(){this.config={...require((0,r.join)(this.getRootDirPath(),"checksum.config.ts")).default||{},...this.volatileChecksumConfig||{}},this.config.apiURL&&(this.CHECKSUM_API_URL=this.config.apiURL)}processChecksumArguments(t){this.deleteVolatileConfig();for(let e of t)if(e.startsWith("--checksum-config"))try{this.volatileChecksumConfig=JSON.parse(e.split("=")[1]),t=t.filter(s=>s!==e)}catch(s){console.log("Error parsing checksum config",s.message),this.volatileChecksumConfig=void 0}}install(){console.log("Creating Checksum directory and necessary files to run your tests");let t=this.getRootDirPath();if((0,i.existsSync)(this.getRootDirPath())||(0,i.mkdirSync)(t),!(0,i.existsSync)(this.getChecksumRootOrigin()))throw new Error("Could not find checksum root directory, please install @checksum-ai/runtime package");["checksum.config.ts","playwright.config.ts","login.ts","README.md"].forEach(e=>{(0,i.copyFileSync)((0,r.join)(this.getChecksumRootOrigin(),e),(0,r.join)(t,e))}),(0,i.mkdirSync)((0,r.join)(t,"tests"),{recursive:!0}),["esra","har","trace","log"].forEach(e=>{(0,i.mkdirSync)((0,r.join)(t,"test-data",e),{recursive:!0})})}getRootDirPath(){return(0,r.join)(process.cwd(),m)}getChecksumRootOrigin(){return(0,r.join)(process.cwd(),"node_modules","@checksum-ai","runtime","checksum-root")}};u(h,"ChecksumCLI");(async()=>await new h().execute())();
package/index.js CHANGED
@@ -270,10 +270,10 @@ m2: `).concat(this.mapper2.__debugToString().split(`
270
270
  current running checksum id index: ${this.runningChecksumIdIndex[this.runningChecksumIdIndex.length-1]}`),await this.page.evaluate(async O=>window.checksum.testGenerator.getSelectorForChecksumId(O),y))}getFailedThought(){return Gf.thoughts[Gf.thoughts.length-1]}toString(){return`Checksum AI Selector ${this.getFailedThought()}`}},hp=Gf;n(hp,"AIFallback"),hp.API_BASE_URL="https://api.checksum.ai/client-api/runtime/ai-fallback",hp.CLIENT_MAX_ITERATIONS=10,hp.thoughts=[];var DS=P1(require("path")),bS=require("fs");var cF="checksum-playwright-runtime.js",uF=__dirname+"/checksumlib.js";var $p=class{constructor(a,y="normal",v,O,h,B,re,z,p){this.page=a;this.runMode=y;this.testIdSelector=v;this.codeMirror=O;this.monitorBridge=h;this.testInfo=B;this.options=re;this.apiKey=z;this.apiURL=p;this.locatorTypeEnumToFieldMap={[0]:"element",[1]:"visibleElement",[2]:"atPointElement"};this.minSelectionScore=.5;this.phasePayload=void 0;this.locatorStack=[];this.fallbacks=[];this.checksumStepStack=[];this.isTracingActive=!1;this.hasRuntimeStartedTrace=!1;this.didFail=!1;this.didHeal=!1;this.phaseMap={};this.setPhase=a=>{let{phase:y,payload:v,clear:O}=a;O&&(this.phase=void 0,this.phasePayload=void 0),y&&(this.phase=y),v&&(this.phasePayload=v)};T6(re.printLogs),this.proxy=new Proxy(this,{get:n(function(fe,le){return fe.getPageMethod(le)},"get")}),this.registerPageEvents(),this.resetFallbacks(),this.setupStepInterceptors(),this.phase="script"}async prepareAPIMock(){let a={GET:0,POST:0,PUT:0,DELETE:0},y=DS.join(gS(Ym(this.testInfo.file),this.checksumTestId),"test.har");if(!(0,bS.existsSync)(y)){wc("Could not find har file for test, will not use mock");return}await this.page.routeFromHAR(y,{url:"*/**",notFound:"fallback",update:!1});let v=this.page._routes[0].handler;await this.page.route("**/*",O=>{let h=O.request().headers(),B=O.request().method();h["Checksum-Id"]=(++a[B]).toString(),O.request()._applyFallbackOverrides({headers:h}),v(O)})}getPlaywrightConfig(){let a=DS.join(xh(),"playwright.config.ts");if((0,bS.existsSync)(a))return require(a).default}registerPageEvents(){var O;this.page.on("framenavigated",async h=>{h===this.page.mainFrame()&&(this.navigationPromise=new Promise((B,re)=>this.loadScript().then(B).catch(re)))});let y=(O=this.getPlaywrightConfig().use)==null?void 0:O.trace;!y||y==="off"||(this.isTracingActive=!0)}getPageMethod(a){return this.phase=void 0,typeof this[a]=="function"?this[a].bind(this):!Object.values(I1).includes(a)||!this.testInfo?this.page[a]:(this.locatorStack.length===0&&(this.pageInitialCallInTestFile=this.getFirstStackTraceFromTestFile()),this.pushToLocatorStack([{type:a,base:this.page,line:this.pageInitialCallInTestFile.line}]),n(function(v,O){try{return this.executeLocator(v,O)}catch(h){throw this.popLocatorChain(),h}},"Page").bind(this))}static async init(a,y,v,O,{runMode:h="normal",testIdSelector:B=void 0,apiKey:re,apiURL:z,options:p={}}){let m=new $p(a,h,B,y,v,O,{useChecksumSelectors:!0,useChecksumAI:!0,newAssertionsEnabled:!0,useMockData:!1,printLogs:!1,...p},re,z);return v.addTestInfo(m.getChecksumTestId(),O.testId),await m.asyncInit(),m.proxy}popLocatorChain(){return this.locatorStack.pop()}async asyncInit(){await this.page.addInitScript(()=>{window.sessionStorage.setItem("checksumai:disable","true")})}async onTestComplete(){await this.sendTestArtifacts(),this.monitorBridge.addSingleTestStats(!this.didFail,this.didHeal&&!this.didFail)}async sendTestArtifacts(){this.runMode!=="normal"&&(await this.codeMirror.write()).forEach(a=>this.monitorBridge.addAsset(a))}async getTraceFilePath(){if(this.isTracingActive)return this.hasRuntimeStartedTrace?C6(Ym(this.testInfo.file),this.checksumTestId).replace(".zip",".original.zip"):this.testInfo.outputPath("trace.zip")}didTestFail(){return this.didFail}async testId(a){a||(a=Ch(5),console.warn(`Checksum test id was not defined for test, will auto-generate. Please replace - "${this.testInfo.title}" with -
271
271
  test(defineChecksumTest("${this.testInfo.title}", "${a}"), async ({ page }) => {...`)),this.checksumTestId=a,(this.options.useMockData||this.runMode==="refactor")&&await this.prepareAPIMock();let y=await this.getTraceFilePath();if(y&&this.monitorBridge.addAsset({type:"trace",path:y,testId:this.checksumTestId}),!1){let O=gS(Ym(this.testInfo.file),this.checksumTestId);this.monitorBridge.addAsset({type:"har",path:O,testId:this.checksumTestId})}}getChecksumTestId(){return this.checksumTestId}checksumSelector(a){return this.options.useChecksumSelectors&&(this.fallbacks.push(this.constructFallback(Kv).init({checksumId:a,fileName:this.testInfo.file,testId:this.checksumTestId})),this.sortFallbacks()),this.checksumStepId=a,this.proxy}checksumAI(...a){if(a.length===0)throw new Error("checksumAI missing arguments");if(!this.options.useChecksumAI)return this.proxy;let{apiKey:y,apiURL:v}=this;if(this.fallbacks.push(this.constructFallback(hp).init({goal:this.testInfo.title,apiKey:y,apiURL:v})),this.sortFallbacks(),this.fallbacks.filter(O=>O instanceof hp).forEach(O=>O.addMetadata({thought:a[0]})),this.checksumStepInitialCallInTestFile=this.getFirstStackTraceFromTestFile(),a.length===1)return this.proxy;if(typeof a[1]!="function")throw new Error("Second argument for withChecksumStep must be a function");this.checksumStepStack.push(a[0]);try{console.log("=== running test function");let O=this;return n(async function(){await a[1](),console.log("==== done running test function"),O.checksumStepStack.pop()},"Page")()}catch(O){console.log(O),this.checksumStepStack.pop()}}async loadScript(){try{return this.navigationPromise&&await this.navigationPromise,await this.page.addScriptTag({path:uF}),await this.page.evaluate(async({initModules:a,ESRAselectionRules:y})=>{window.checksum.testRunner.init(y,[],a)},{ESRAselectionRules:{testIdSelector:this.testIdSelector},initModules:{assertionGenerator:!0}}),wc(`[init] init script loaded for ${this.page.url()}`),!0}catch{return!1}}pushToLocatorStack(a){this.locatorStack.push(a)}getCurrentLocatorChain(){if(this.locatorStack.length)return this.locatorStack[this.locatorStack.length-1]}getCurrentLocatorInChain(){let a=this.getCurrentLocatorChain();return a==null?void 0:a[a.length-1]}getMessage(a,{initialSelector:y,selector:v,thought:O}={}){switch(a){case"script":return"Firing up checksum";case"initial":return`${y} failed, trying some checksum magic...`;case"force":return"check/uncheck methods failed, falling back to click action";case"esra-search":return"Checksum is looking for potential alternatives to resolve the issue...";case"esra-action":return`AI: use selector ${v}`;case"llm-prompt":return`Checksum is trying to achieve step "${O}" using AI...`;case"llm-action":return`AI: "${O}" using selector "${v}"`;case"fail":return`Checksum couldn't resolve the issue executing ${y}`}}onFallbackSuccess(){let a=this.testInfo._steps[this.testInfo._steps.length-1];a&&!a.endWallTime&&a.complete({error:{message:`Failed to resolve ${this.initialLocatorTitle}`,stack:""}})}setupStepInterceptors(){let a=["checksum-page.ts","checksum-test-extension.ts","checksum-playwright-runtime.js","code-mirror.ts","utils.ts","fallback/esra-fallback.ts","fallback/force-fallback.ts","fallback/llm-fallback.ts","index.js"].map(B=>(0,A6.join)(__dirname,B)),y={},v=n(B=>{var z,p,m,fe;return y[B.stepId]!==void 0?y[B.stepId]:B.location&&!a.includes(B.location.file)?!1:!!(B.stepId.includes(".evaluate@")||B.stepId.includes(".addScriptTag@")||(z=B.title)!=null&&z.includes("evaluate")||(p=B.title)!=null&&p.includes("addScriptTag")||(m=B.title)!=null&&m.includes("waitForLoadState")||B.category==="fixture"||(fe=B.title)!=null&&fe.includes("tracing.stop"))},"shouldFilterStep"),O=this.testInfo._onStepBegin;this.testInfo._onStepBegin=B=>{if(!this.phase&&v(B)){y[B.stepId]=!0;return}return y[B.stepId]=!1,this.phase==="initial"&&(this.initialLocatorTitle=B.title,B.location=this.pageInitialCallInTestFile),B.title.startsWith("proxy.")&&(B.title=B.title.replace("proxy.","page.")),this.phase&&this.phase!=="initial"&&(this.phaseMap[B.stepId]={phase:this.phase,payload:this.phasePayload,initialLocatorTitle:this.initialLocatorTitle},B.location=void 0,B.title=this.getMessage(this.phase,{initialSelector:this.initialLocatorTitle,...this.phasePayload})),this.phase=void 0,this.phasePayload=void 0,O(B)};let h=this.testInfo._onStepEnd;this.testInfo._onStepEnd=B=>{if(!y[B.stepId]){if(this.phaseMap[B.stepId]){let{phase:re,initialLocatorTitle:z,payload:p}=this.phaseMap[B.stepId];re==="fail"&&(B.error={message:`Failed to resolve ${z}`,stack:""})}return h(B)}}}getFirstStackTraceFromTestFile(){let a=this.getTestFileStackTrace()[0];if(!a)throw new Error(`Could not find test file location from stack trace ${$p.getStackTrace()}`);let v=[/\((.*):(\d+):(\d+)\)$/,/.*at (.*):(\d+):(\d+)$/].map(re=>re.exec(a)).find(re=>re!==null);if(!v)throw new Error(`Could not find test file location from stack trace ${a}`);let[,O,h,B]=v;return{file:O,line:parseInt(h),column:parseInt(B)}}getTestFileStackTrace(){return $p.getStackTrace().filter(y=>y.includes(this.testInfo.file))}isCalledDirectlyFromTestFunction(){let a=this.getTestFileStackTrace();if(a.length!==1+this.checksumStepStack.length)return!1;let y=a[0],v=/.*at (.*):(\d+):(\d+)$/;return this.checksumStepStack.length===0&&!v.exec(y)?!1:!this.isCalledThroughMethodInAnotherFile(y)}isCalledThroughMethodInAnotherFile(a){let y=$p.getStackTrace(),v=["node:internal","/node_modules/@playwright"],O=y.indexOf(a)-1;for(;O>=0&&v.some(B=>y[O].includes(B));)O--;let h=y[O];return!h.includes("checksum-page.ts")&&!h.includes(cF)}static getStackTrace(){return new Error().stack.split(`
272
272
  `)}getLocator(a,y){let v=this.getCurrentLocatorInChain();return v.base[v.type](a,y)}executeLocator(a,y){try{wc(`
273
- Executing locator ${this.getCurrentLocatorInChain().type} with ${typeof a=="string"?`selector ${a}`:"locator"}`);let v=this.getLocator(a,y);return new Proxy(v,{get:n(function(h,B){return this.getLocatorMethod(v,h,B)},"get").bind(this)})}catch(v){wc("Failed to locate",v)}}getLocatorMethod(a,y,v){return v==="constructor"?n(function(...h){return this.popLocatorChain(),y.constructor(...h)},"Locator"):v in y&&typeof y[v]!="function"||v===Symbol.toPrimitive||v in Object?(this.popLocatorChain(),y[v]):[...Object.values(I1),...Object.values(w1)].includes(v)?v==="or"?(wc("'Or' locator not supported, will execute normally"),this.popLocatorChain(),y[v]):(this.getCurrentLocatorChain().push({type:v,base:a}),n(function(...h){return this.executeLocator(...h)},"Locator").bind(this)):n(async function(...h){let B=await this.executeLocatorAction(a,v,h);return this.popLocatorChain(),B},"Locator").bind(this)}async executeLocatorAction(a,y,v){this.selector=a._selector;let O=this.getChecksumStepId();wc("Executing",y,this.selector);let h=y==="_expect";try{wc("Running initial locator..."),await this.navigationPromise,await this.page.evaluate(()=>!!window.checksum)||wc("[loadScript] checksum libs missing, marking as failed"),await this.stepWillExecute(h),this.phase="initial";let re=await L1(a,y,v,this.getTimeout(y,v));if(h&&(re==null?void 0:re.timedOut)===!0)return wc("Expect timeout"),this.didFail=!0,re;if(re!==!1)return await this.onStepSuccess(O,y==="_expect"),re;await this.onStepFailure()}catch(B){wc("Failed initial execution. Exception:",B.message)}return this.initiateFallbackSequence(O,a,y,v)}getChecksumStepId(){let a=this.checksumStepId;return this.checksumStepId=void 0,a}async stepWillExecute(a){this.selectionData=void 0,this.runMode==="refactor"&&(wc(`stepWillExecute called for line ${this.pageInitialCallInTestFile.line}`),this.isCalledDirectlyFromTestFunction()&&(await this.evaluateWithChecksum(async()=>await window.checksum.testRunner.startMonitoringForAssertions()),this.selectionData=[await M1(this.selector,this.page)].filter(y=>y),Object.values(this.selectionData).length===0?wc(`Failed fetching selection data ${a?"- maybe because it is not visible and running inside expect":""}`):wc("Successfully fetched selection data")))}async onStepSuccess(a,y,v=!1){var B,re,z,p;let O=(B=this.fallbacks.find(m=>m instanceof hp))==null?void 0:B.getFailedThought();if(this.resetFallbacks(),this.runMode==="normal"||this.runMode==="heal"&&!v||!this.codeMirror||!this.getCurrentLocatorChain())return;if(!this.isCalledDirectlyFromTestFunction()){wc("<!> Step called from helper function, will not refactor step");return}if(this.runMode==="refactor"&&!this.selectionData.length){wc("Failed fetching selection data, will not refactor step");return}wc("Will update in-memory code"+(this.selectionData&&this.selectionData.length>0?`
273
+ Executing locator ${this.getCurrentLocatorInChain().type} with ${typeof a=="string"?`selector ${a}`:"locator"}`);let v=this.getLocator(a,y);return new Proxy(v,{get:n(function(h,B){return this.getLocatorMethod(v,h,B)},"get").bind(this)})}catch(v){wc("Failed to locate",v)}}getLocatorMethod(a,y,v){return v==="constructor"?n(function(...h){return this.popLocatorChain(),y.constructor(...h)},"Locator"):v in y&&typeof y[v]!="function"||v===Symbol.toPrimitive||v in Object?(this.popLocatorChain(),y[v]):[...Object.values(I1),...Object.values(w1)].includes(v)?v==="or"?(wc("'Or' locator not supported, will execute normally"),this.popLocatorChain(),y[v]):(this.getCurrentLocatorChain().push({type:v,base:a}),n(function(...h){return this.executeLocator(...h)},"Locator").bind(this)):n(async function(...h){let B=await this.executeLocatorAction(a,v,h);return this.popLocatorChain(),B},"Locator").bind(this)}async executeLocatorAction(a,y,v){this.originalActionError=void 0,this.selector=a._selector;let O=this.getChecksumStepId();wc("Executing",y,this.selector);let h=y==="_expect";try{wc("Running initial locator..."),await this.navigationPromise,await this.page.evaluate(()=>!!window.checksum)||wc("[loadScript] checksum libs missing, marking as failed"),await this.stepWillExecute(h),this.phase="initial";let re=await L1(a,y,v,this.getTimeout(y,v));if(h&&(re==null?void 0:re.timedOut)===!0)return wc("Expect timeout"),this.didFail=!0,re;if(re!==!1)return await this.onStepSuccess(O,y==="_expect"),re;await this.onStepFailure()}catch(B){this.originalActionError=B,wc("Failed initial execution. Exception:",B.message)}return this.initiateFallbackSequence(O,a,y,v)}getChecksumStepId(){let a=this.checksumStepId;return this.checksumStepId=void 0,a}async stepWillExecute(a){this.selectionData=void 0,this.runMode==="refactor"&&(wc(`stepWillExecute called for line ${this.pageInitialCallInTestFile.line}`),this.isCalledDirectlyFromTestFunction()&&(await this.evaluateWithChecksum(async()=>await window.checksum.testRunner.startMonitoringForAssertions()),this.selectionData=[await M1(this.selector,this.page)].filter(y=>y),Object.values(this.selectionData).length===0?wc(`Failed fetching selection data ${a?"- maybe because it is not visible and running inside expect":""}`):wc("Successfully fetched selection data")))}async onStepSuccess(a,y,v=!1){var B,re,z,p;let O=(B=this.fallbacks.find(m=>m instanceof hp))==null?void 0:B.getFailedThought();if(this.resetFallbacks(),this.runMode==="normal"||this.runMode==="heal"&&!v||!this.codeMirror||!this.getCurrentLocatorChain())return;if(!this.isCalledDirectlyFromTestFunction()){wc("<!> Step called from helper function, will not refactor step");return}if(this.runMode==="refactor"&&!this.selectionData.length){wc("Failed fetching selection data, will not refactor step");return}wc("Will update in-memory code"+(this.selectionData&&this.selectionData.length>0?`
274
274
  locators:
275
275
  ${this.selectionData.map(m=>m.generatedLocator).join(`
276
- `)}`:"")),await O1(this.page.waitForLoadState("networkidle"));let h=y||!this.options.newAssertionsEnabled?[]:await this.evaluateWithChecksum(async()=>await window.checksum.testRunner.stopMonitoringAndGenerateAssertions());this.selectionData.forEach(m=>{y&&(m.esraMetadata=void 0,m.generatedLocator=void 0)}),this.runMode==="heal"&&(this.didHeal=!0),this.codeMirror.load(this.testInfo.file,this.checksumTestId),(z=(re=this.selectionData)==null?void 0:re[0].method)!=null&&z.name?this.codeMirror.updateChecksumStep(this.checksumStepInitialCallInTestFile.line,O,this.selectionData,!this.checksumStepStack.length):this.codeMirror.updateCommandFromLine((p=this.getCurrentLocatorChain())==null?void 0:p[0].line,this.getCurrentLocatorChain(),a,h,this.selectionData[0])}async onStepFailure(){await this.evaluateWithChecksum(async()=>{var a,y;return await((y=(a=window.checksum)==null?void 0:a.testRunner)==null?void 0:y.stopMonitoring())})}async initiateFallbackSequence(a,y,v,O){for(let B of this.fallbacks)try{B.toString()&&console.log(`Executing ${B.toString()}`);let re=await B.resolve({locator:y,method:v,args:O});if(!re){B.toString()&&console.log("Execution failed.");continue}return console.log("Executed successfully."),this.onFallbackSuccess(),this.runMode==="heal"&&(this.selectionData=re),await this.onStepSuccess(a,!1,!0),this.resetFallbacks(),!0}catch(re){wc(`Exception during ${B.toString()} `,re);continue}this.didFail=!0,await this.addFailPhase(),this.resetFallbacks();let h=new Error("Checksum failed to recover from the errors. Please review the test, fix the code and try again.");throw h.stack="",h}async addFailPhase(){return this.phase="fail",this.page.evaluate(async()=>!0)}getTimeout(a,y){let v=["fill","dragTo"].includes(a)?1:0;return(y[v]??{}).timeout??5e3}async evaluateWithChecksum(a,y){return this.navigationPromise&&await this.navigationPromise,this.page.evaluate(a,y)}resetFallbacks(){this.fallbacks=[this.constructFallback(Qv).init()]}sortFallbacks(){let a=[Qv,Kv,hp];this.fallbacks.sort((y,v)=>a.indexOf(y.constructor)-a.indexOf(v.constructor))}constructFallback(a){return new a(this.page,this.setPhase,{generateSelectionData:this.runMode!=="normal"})}};n($p,"ChecksumPage");var tv=P1(lA()),fA=P1(require("path")),kg=require("fs");var iv=class{constructor(a){this.appRules=a}toAssertionCode(a){switch(a.type){case"text_element_appear":case"text_element_disappear":return this.makeTextElementAssertion(a);case"page_url_change":{let y=this.appRules?this.appRules.resolvePageIdFromUrl(a.url):null;if(y!==a.url&&y!==null&&y!=="unknown-page"){let v=this.appRules.getPageRegexMatchingUrl(a.url);if(v){let O=v.toString().replace(/\//g,"\\/");return O.startsWith("^")&&(O=O.substring(1)),O.endsWith("$")&&(O=O.substring(0,O.length-1)),`await expect(page).toHaveURL(/${O}(\\?.*)?(\\#.*)?$/)`}throw new Error("None of the page URLs matched the assertion url.")}else return`await expect(page).toHaveURL("${a.url.toString().replace(/"/g,'\\"')}")`}default:throw new Error(`Unexpected value for assertion.type: ${a.type} in TestGeneratorCodegen.addAssertion`)}}makeTextElementAssertion(a){let v=`await expect(page.getByText("${iv.escapeString(a.text.toString())}", { exact: true }))`;switch(a.type){case"text_element_appear":return`${v}.toBeVisible()`;case"text_element_disappear":return`${v}.not.toBeVisible()`}}static escapeString(a){let y=this.replaceAll(a,"'","\\'");return y=this.replaceAll(a,/\\/g,"\\\\"),y=this.replaceAll(a,/"/g,'\\"'),y=this.replaceAll(a,`
276
+ `)}`:"")),await O1(this.page.waitForLoadState("networkidle"));let h=y||!this.options.newAssertionsEnabled?[]:await this.evaluateWithChecksum(async()=>await window.checksum.testRunner.stopMonitoringAndGenerateAssertions());this.selectionData.forEach(m=>{y&&(m.esraMetadata=void 0,m.generatedLocator=void 0)}),this.runMode==="heal"&&(this.didHeal=!0),this.codeMirror.load(this.testInfo.file,this.checksumTestId),(z=(re=this.selectionData)==null?void 0:re[0].method)!=null&&z.name?this.codeMirror.updateChecksumStep(this.checksumStepInitialCallInTestFile.line,O,this.selectionData,!this.checksumStepStack.length):this.codeMirror.updateCommandFromLine((p=this.getCurrentLocatorChain())==null?void 0:p[0].line,this.getCurrentLocatorChain(),a,h,this.selectionData[0])}async onStepFailure(){await this.evaluateWithChecksum(async()=>{var a,y;return await((y=(a=window.checksum)==null?void 0:a.testRunner)==null?void 0:y.stopMonitoring())})}async initiateFallbackSequence(a,y,v,O){for(let B of this.fallbacks)try{B.toString()&&console.log(`Executing ${B.toString()}`);let re=await B.resolve({locator:y,method:v,args:O});if(!re){B.toString()&&console.log("Execution failed.");continue}return console.log("Executed successfully."),this.onFallbackSuccess(),this.runMode==="heal"&&(this.selectionData=re),await this.onStepSuccess(a,!1,!0),this.resetFallbacks(),!0}catch(re){wc(`Exception during ${B.toString()} `,re);continue}if(this.didFail=!0,await this.addFailPhase(),this.resetFallbacks(),this.originalActionError)throw this.originalActionError;let h=new Error("Checksum failed to recover from the errors. Please review the test, fix the code and try again.");throw h.stack="",h}async addFailPhase(){return this.phase="fail",this.page.evaluate(async()=>!0)}getTimeout(a,y){let v=["fill","dragTo"].includes(a)?1:0;return(y[v]??{}).timeout??3e4}async evaluateWithChecksum(a,y){return this.navigationPromise&&await this.navigationPromise,this.page.evaluate(a,y)}resetFallbacks(){this.fallbacks=[this.constructFallback(Qv).init()]}sortFallbacks(){let a=[Qv,Kv,hp];this.fallbacks.sort((y,v)=>a.indexOf(y.constructor)-a.indexOf(v.constructor))}constructFallback(a){return new a(this.page,this.setPhase,{generateSelectionData:this.runMode!=="normal"})}};n($p,"ChecksumPage");var tv=P1(lA()),fA=P1(require("path")),kg=require("fs");var iv=class{constructor(a){this.appRules=a}toAssertionCode(a){switch(a.type){case"text_element_appear":case"text_element_disappear":return this.makeTextElementAssertion(a);case"page_url_change":{let y=this.appRules?this.appRules.resolvePageIdFromUrl(a.url):null;if(y!==a.url&&y!==null&&y!=="unknown-page"){let v=this.appRules.getPageRegexMatchingUrl(a.url);if(v){let O=v.toString().replace(/\//g,"\\/");return O.startsWith("^")&&(O=O.substring(1)),O.endsWith("$")&&(O=O.substring(0,O.length-1)),`await expect(page).toHaveURL(/${O}(\\?.*)?(\\#.*)?$/)`}throw new Error("None of the page URLs matched the assertion url.")}else return`await expect(page).toHaveURL("${a.url.toString().replace(/"/g,'\\"')}")`}default:throw new Error(`Unexpected value for assertion.type: ${a.type} in TestGeneratorCodegen.addAssertion`)}}makeTextElementAssertion(a){let v=`await expect(page.getByText("${iv.escapeString(a.text.toString())}", { exact: true }))`;switch(a.type){case"text_element_appear":return`${v}.toBeVisible()`;case"text_element_disappear":return`${v}.not.toBeVisible()`}}static escapeString(a){let y=this.replaceAll(a,"'","\\'");return y=this.replaceAll(a,/\\/g,"\\\\"),y=this.replaceAll(a,/"/g,'\\"'),y=this.replaceAll(a,`
277
277
  `,"\\n"),y}static replaceAll(a,y,v){return a&&a.replace(new RegExp(y,"g"),v)}};n(iv,"AssertionCodeGenerator");var pm=class{constructor(a){this.runMode=a;this.lines=[];this.linesOffsetFromOriginalFile=0;let y={getPageRegexMatchingUrl:()=>null,resolvePageIdFromUrl:()=>null};this.assertionCodeGenerator=new iv(y)}static init(a){return new pm(a)}static initWithContent(a,y){let v=new pm("normal");return v.lines=[a],v}async load(a,y){if(this.filename)return;this.filename=a,this.testId=y;let v=this.getProcessedFilename(this.filename);(0,kg.existsSync)(v)&&(0,kg.unlinkSync)(v),this.lines=["",...(0,kg.readFileSync)(this.filename,"utf-8").split(`
278
278
  `)];try{this.esraMetadataMap=await F1(Ym(v),y)}catch{console.log("[CodeMirror] Failed loading ESRA metadata for test file, creating new ESRA map"),this.esraMetadataMap={}}}addTestToCode(a,y){let v=tv.createSourceFile("",this.lines.join(""),tv.ScriptTarget.ES2015),O=this.findTitleInParentNode(this.getSourceFileChildren(v),v,a.description);if(O){let re=v.text.substring(0,O.pos)+y.generateSingleTestCode(a)+v.text.substring(O.end);return y.styleCode(re)}let h=this.getLastDescribeNode(this.getSourceFileChildren(v),v);if(h){let re=v.text.substring(0,v.text.substring(0,h.end).lastIndexOf("}")-1)+y.generateSingleTestCode(a)+"});";return y.styleCode(re)}let B=v.text+`
279
279
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@checksum-ai/runtime",
3
- "version": "1.0.31",
3
+ "version": "1.0.33",
4
4
  "description": "Checksum.ai test runtime",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -6,4 +6,4 @@ GFS4: `),console.error(e)},"debug"));H[se]||(Vn=global[se]||[],Bn(H,Vn),H.close=
6
6
 
7
7
  see https://github.com/jprichardson/node-fs-extra/issues/269`,"Warning","fs-extra-WARN0002");let{srcStat:t,destStat:i}=Vp.checkPathsSync(e,a,"copy",p);if(Vp.checkParentPathsSync(e,t,a,"copy"),p.filter&&!p.filter(e,a))return;let d=Rp.dirname(a);return _e.existsSync(d)||Xo(d),t3(i,e,a,p)}r(em,"copySync");function t3(e,a,p,t){let d=(t.dereference?_e.statSync:_e.lstatSync)(a);if(d.isDirectory())return nm(d,e,a,p,t);if(d.isFile()||d.isCharacterDevice()||d.isBlockDevice())return am(d,e,a,p,t);if(d.isSymbolicLink())return om(e,a,p,t);throw d.isSocket()?new Error(`Cannot copy a socket file: ${a}`):d.isFIFO()?new Error(`Cannot copy a FIFO pipe: ${a}`):new Error(`Unknown file: ${a}`)}r(t3,"getStats");function am(e,a,p,t,i){return a?pm(e,p,t,i):i3(e,p,t,i)}r(am,"onFile");function pm(e,a,p,t){if(t.overwrite)return _e.unlinkSync(p),i3(e,a,p,t);if(t.errorOnExist)throw new Error(`'${p}' already exists`)}r(pm,"mayCopyFile");function i3(e,a,p,t){return _e.copyFileSync(a,p),t.preserveTimestamps&&tm(e.mode,a,p),cd(p,e.mode)}r(i3,"copyFile");function tm(e,a,p){return im(e)&&dm(p,e),rm(a,p)}r(tm,"handleTimestamps");function im(e){return(e&128)===0}r(im,"fileIsNotWritable");function dm(e,a){return cd(e,a|128)}r(dm,"makeFileWritable");function cd(e,a){return _e.chmodSync(e,a)}r(cd,"setDestMode");function rm(e,a){let p=_e.statSync(e);return Qo(a,p.atime,p.mtime)}r(rm,"setDestTimestamps");function nm(e,a,p,t,i){return a?d3(p,t,i):lm(e.mode,p,t,i)}r(nm,"onDir");function lm(e,a,p,t){return _e.mkdirSync(p),d3(a,p,t),cd(p,e)}r(lm,"mkDirAndCopy");function d3(e,a,p){_e.readdirSync(e).forEach(t=>sm(t,e,a,p))}r(d3,"copyDir");function sm(e,a,p,t){let i=Rp.join(a,e),d=Rp.join(p,e);if(t.filter&&!t.filter(i,d))return;let{destStat:n}=Vp.checkPathsSync(i,d,"copy",t);return t3(n,i,d,t)}r(sm,"copyDirItem");function om(e,a,p,t){let i=_e.readlinkSync(a);if(t.dereference&&(i=Rp.resolve(process.cwd(),i)),e){let d;try{d=_e.readlinkSync(p)}catch(n){if(n.code==="EINVAL"||n.code==="UNKNOWN")return _e.symlinkSync(i,p);throw n}if(t.dereference&&(d=Rp.resolve(process.cwd(),d)),Vp.isSrcSubdir(i,d))throw new Error(`Cannot copy '${i}' to a subdirectory of itself, '${d}'.`);if(Vp.isSrcSubdir(d,i))throw new Error(`Cannot overwrite '${d}' with '${i}'.`);return mm(i,p)}else return _e.symlinkSync(i,p)}r(om,"onLink");function mm(e,a){return _e.unlinkSync(a),_e.symlinkSync(e,a)}r(mm,"copyLink");r3.exports=em});var Zt=v((qc,l3)=>{"use strict";var um=Se().fromCallback;l3.exports={copy:um(p3()),copySync:n3()}});var Ip=v((Uc,o3)=>{"use strict";var s3=be(),fm=Se().fromCallback;function hm(e,a){s3.rm(e,{recursive:!0,force:!0},a)}r(hm,"remove");function cm(e){s3.rmSync(e,{recursive:!0,force:!0})}r(cm,"removeSync");o3.exports={remove:fm(hm),removeSync:cm}});var _3=v((zc,w3)=>{"use strict";var vm=Se().fromPromise,f3=Q1(),h3=require("path"),c3=ze(),v3=Ip(),m3=vm(r(async function(a){let p;try{p=await f3.readdir(a)}catch{return c3.mkdirs(a)}return Promise.all(p.map(t=>v3.remove(h3.join(a,t))))},"emptyDir"));function u3(e){let a;try{a=f3.readdirSync(e)}catch{return c3.mkdirsSync(e)}a.forEach(p=>{p=h3.join(e,p),v3.removeSync(p)})}r(u3,"emptyDirSync");w3.exports={emptyDirSync:u3,emptydirSync:u3,emptyDir:m3,emptydir:m3}});var b3=v((Zc,S3)=>{"use strict";var wm=Se().fromCallback,g3=require("path"),O1=be(),y3=ze();function _m(e,a){function p(){O1.writeFile(e,"",t=>{if(t)return a(t);a()})}r(p,"makeFile"),O1.stat(e,(t,i)=>{if(!t&&i.isFile())return a();let d=g3.dirname(e);O1.stat(d,(n,l)=>{if(n)return n.code==="ENOENT"?y3.mkdirs(d,s=>{if(s)return a(s);p()}):a(n);l.isDirectory()?p():O1.readdir(d,s=>{if(s)return a(s)})})})}r(_m,"createFile");function gm(e){let a;try{a=O1.statSync(e)}catch{}if(a&&a.isFile())return;let p=g3.dirname(e);try{O1.statSync(p).isDirectory()||O1.readdirSync(p)}catch(t){if(t&&t.code==="ENOENT")y3.mkdirsSync(p);else throw t}O1.writeFileSync(e,"")}r(gm,"createFileSync");S3.exports={createFile:wm(_m),createFileSync:gm}});var E3=v((Hc,D3)=>{"use strict";var ym=Se().fromCallback,x3=require("path"),R1=be(),T3=ze(),Sm=F1().pathExists,{areIdentical:N3}=ea();function bm(e,a,p){function t(i,d){R1.link(i,d,n=>{if(n)return p(n);p(null)})}r(t,"makeLink"),R1.lstat(a,(i,d)=>{R1.lstat(e,(n,l)=>{if(n)return n.message=n.message.replace("lstat","ensureLink"),p(n);if(d&&N3(l,d))return p(null);let s=x3.dirname(a);Sm(s,(m,o)=>{if(m)return p(m);if(o)return t(e,a);T3.mkdirs(s,c=>{if(c)return p(c);t(e,a)})})})})}r(bm,"createLink");function xm(e,a){let p;try{p=R1.lstatSync(a)}catch{}try{let d=R1.lstatSync(e);if(p&&N3(d,p))return}catch(d){throw d.message=d.message.replace("lstat","ensureLink"),d}let t=x3.dirname(a);return R1.existsSync(t)||T3.mkdirsSync(t),R1.linkSync(e,a)}r(xm,"createLinkSync");D3.exports={createLink:ym(bm),createLinkSync:xm}});var A3=v((Gc,k3)=>{"use strict";var V1=require("path"),Bp=be(),Tm=F1().pathExists;function Nm(e,a,p){if(V1.isAbsolute(e))return Bp.lstat(e,t=>t?(t.message=t.message.replace("lstat","ensureSymlink"),p(t)):p(null,{toCwd:e,toDst:e}));{let t=V1.dirname(a),i=V1.join(t,e);return Tm(i,(d,n)=>d?p(d):n?p(null,{toCwd:i,toDst:e}):Bp.lstat(e,l=>l?(l.message=l.message.replace("lstat","ensureSymlink"),p(l)):p(null,{toCwd:e,toDst:V1.relative(t,e)})))}}r(Nm,"symlinkPaths");function Dm(e,a){let p;if(V1.isAbsolute(e)){if(p=Bp.existsSync(e),!p)throw new Error("absolute srcpath does not exist");return{toCwd:e,toDst:e}}else{let t=V1.dirname(a),i=V1.join(t,e);if(p=Bp.existsSync(i),p)return{toCwd:i,toDst:e};if(p=Bp.existsSync(e),!p)throw new Error("relative srcpath does not exist");return{toCwd:e,toDst:V1.relative(t,e)}}}r(Dm,"symlinkPathsSync");k3.exports={symlinkPaths:Nm,symlinkPathsSync:Dm}});var O3=v((Kc,F3)=>{"use strict";var C3=be();function Em(e,a,p){if(p=typeof a=="function"?a:p,a=typeof a=="function"?!1:a,a)return p(null,a);C3.lstat(e,(t,i)=>{if(t)return p(null,"file");a=i&&i.isDirectory()?"dir":"file",p(null,a)})}r(Em,"symlinkType");function km(e,a){let p;if(a)return a;try{p=C3.lstatSync(e)}catch{return"file"}return p&&p.isDirectory()?"dir":"file"}r(km,"symlinkTypeSync");F3.exports={symlinkType:Em,symlinkTypeSync:km}});var U3=v((Xc,q3)=>{"use strict";var Am=Se().fromCallback,V3=require("path"),je=Q1(),I3=ze(),Cm=I3.mkdirs,Fm=I3.mkdirsSync,B3=A3(),Om=B3.symlinkPaths,Rm=B3.symlinkPathsSync,P3=O3(),Vm=P3.symlinkType,Im=P3.symlinkTypeSync,Bm=F1().pathExists,{areIdentical:L3}=ea();function Pm(e,a,p,t){t=typeof p=="function"?p:t,p=typeof p=="function"?!1:p,je.lstat(a,(i,d)=>{!i&&d.isSymbolicLink()?Promise.all([je.stat(e),je.stat(a)]).then(([n,l])=>{if(L3(n,l))return t(null);R3(e,a,p,t)}):R3(e,a,p,t)})}r(Pm,"createSymlink");function R3(e,a,p,t){Om(e,a,(i,d)=>{if(i)return t(i);e=d.toDst,Vm(d.toCwd,p,(n,l)=>{if(n)return t(n);let s=V3.dirname(a);Bm(s,(m,o)=>{if(m)return t(m);if(o)return je.symlink(e,a,l,t);Cm(s,c=>{if(c)return t(c);je.symlink(e,a,l,t)})})})})}r(R3,"_createSymlink");function Lm(e,a,p){let t;try{t=je.lstatSync(a)}catch{}if(t&&t.isSymbolicLink()){let l=je.statSync(e),s=je.statSync(a);if(L3(l,s))return}let i=Rm(e,a);e=i.toDst,p=Im(i.toCwd,p);let d=V3.dirname(a);return je.existsSync(d)||Fm(d),je.symlinkSync(e,a,p)}r(Lm,"createSymlinkSync");q3.exports={createSymlink:Am(Pm),createSymlinkSync:Lm}});var G3=v((ev,$3)=>{"use strict";var{createFile:M3,createFileSync:z3}=b3(),{createLink:j3,createLinkSync:Z3}=E3(),{createSymlink:W3,createSymlinkSync:H3}=U3();$3.exports={createFile:M3,createFileSync:z3,ensureFile:M3,ensureFileSync:z3,createLink:j3,createLinkSync:Z3,ensureLink:j3,ensureLinkSync:Z3,createSymlink:W3,createSymlinkSync:H3,ensureSymlink:W3,ensureSymlinkSync:H3}});var Wt=v((av,J3)=>{function qm(e,{EOL:a=`
8
8
  `,finalEOL:p=!0,replacer:t=null,spaces:i}={}){let d=p?a:"";return JSON.stringify(e,t,i).replace(/\n/g,a)+d}r(qm,"stringify");function Um(e){return Buffer.isBuffer(e)&&(e=e.toString("utf8")),e.replace(/^\uFEFF/,"")}r(Um,"stripBom");J3.exports={stringify:qm,stripBom:Um}});var Q3=v((tv,X3)=>{var qa;try{qa=be()}catch{qa=require("fs")}var Ht=Se(),{stringify:K3,stripBom:Y3}=Wt();async function Mm(e,a={}){typeof a=="string"&&(a={encoding:a});let p=a.fs||qa,t="throws"in a?a.throws:!0,i=await Ht.fromCallback(p.readFile)(e,a);i=Y3(i);let d;try{d=JSON.parse(i,a?a.reviver:null)}catch(n){if(t)throw n.message=`${e}: ${n.message}`,n;return null}return d}r(Mm,"_readFile");var zm=Ht.fromPromise(Mm);function jm(e,a={}){typeof a=="string"&&(a={encoding:a});let p=a.fs||qa,t="throws"in a?a.throws:!0;try{let i=p.readFileSync(e,a);return i=Y3(i),JSON.parse(i,a.reviver)}catch(i){if(t)throw i.message=`${e}: ${i.message}`,i;return null}}r(jm,"readFileSync");async function Zm(e,a,p={}){let t=p.fs||qa,i=K3(a,p);await Ht.fromCallback(t.writeFile)(e,i,p)}r(Zm,"_writeFile");var Wm=Ht.fromPromise(Zm);function Hm(e,a,p={}){let t=p.fs||qa,i=K3(a,p);return t.writeFileSync(e,i,p)}r(Hm,"writeFileSync");var $m={readFile:zm,readFileSync:jm,writeFile:Wm,writeFileSync:Hm};X3.exports=$m});var a9=v((dv,e9)=>{"use strict";var $t=Q3();e9.exports={readJson:$t.readFile,readJsonSync:$t.readFileSync,writeJson:$t.writeFile,writeJsonSync:$t.writeFileSync}});var Gt=v((rv,i9)=>{"use strict";var Gm=Se().fromCallback,Pp=be(),p9=require("path"),t9=ze(),Jm=F1().pathExists;function Km(e,a,p,t){typeof p=="function"&&(t=p,p="utf8");let i=p9.dirname(e);Jm(i,(d,n)=>{if(d)return t(d);if(n)return Pp.writeFile(e,a,p,t);t9.mkdirs(i,l=>{if(l)return t(l);Pp.writeFile(e,a,p,t)})})}r(Km,"outputFile");function Ym(e,...a){let p=p9.dirname(e);if(Pp.existsSync(p))return Pp.writeFileSync(e,...a);t9.mkdirsSync(p),Pp.writeFileSync(e,...a)}r(Ym,"outputFileSync");i9.exports={outputFile:Gm(Km),outputFileSync:Ym}});var r9=v((lv,d9)=>{"use strict";var{stringify:Xm}=Wt(),{outputFile:Qm}=Gt();async function eu(e,a,p={}){let t=Xm(a,p);await Qm(e,t,p)}r(eu,"outputJson");d9.exports=eu});var l9=v((ov,n9)=>{"use strict";var{stringify:au}=Wt(),{outputFileSync:pu}=Gt();function tu(e,a,p){let t=au(a,p);pu(e,t,p)}r(tu,"outputJsonSync");n9.exports=tu});var o9=v((uv,s9)=>{"use strict";var iu=Se().fromPromise,ge=a9();ge.outputJson=iu(r9());ge.outputJsonSync=l9();ge.outputJSON=ge.outputJson;ge.outputJSONSync=ge.outputJsonSync;ge.writeJSON=ge.writeJson;ge.writeJSONSync=ge.writeJsonSync;ge.readJSON=ge.readJson;ge.readJSONSync=ge.readJsonSync;s9.exports=ge});var c9=v((fv,h9)=>{"use strict";var du=be(),wd=require("path"),ru=Zt().copy,f9=Ip().remove,nu=ze().mkdirp,lu=F1().pathExists,m9=ea();function su(e,a,p,t){typeof p=="function"&&(t=p,p={}),p=p||{};let i=p.overwrite||p.clobber||!1;m9.checkPaths(e,a,"move",p,(d,n)=>{if(d)return t(d);let{srcStat:l,isChangingCase:s=!1}=n;m9.checkParentPaths(e,l,a,"move",m=>{if(m)return t(m);if(ou(a))return u9(e,a,i,s,t);nu(wd.dirname(a),o=>o?t(o):u9(e,a,i,s,t))})})}r(su,"move");function ou(e){let a=wd.dirname(e);return wd.parse(a).root===a}r(ou,"isParentRoot");function u9(e,a,p,t,i){if(t)return vd(e,a,p,i);if(p)return f9(a,d=>d?i(d):vd(e,a,p,i));lu(a,(d,n)=>d?i(d):n?i(new Error("dest already exists.")):vd(e,a,p,i))}r(u9,"doRename");function vd(e,a,p,t){du.rename(e,a,i=>i?i.code!=="EXDEV"?t(i):mu(e,a,p,t):t())}r(vd,"rename");function mu(e,a,p,t){ru(e,a,{overwrite:p,errorOnExist:!0},d=>d?t(d):f9(e,t))}r(mu,"moveAcrossDevice");h9.exports=su});var y9=v((cv,g9)=>{"use strict";var w9=be(),gd=require("path"),uu=Zt().copySync,_9=Ip().removeSync,fu=ze().mkdirpSync,v9=ea();function hu(e,a,p){p=p||{};let t=p.overwrite||p.clobber||!1,{srcStat:i,isChangingCase:d=!1}=v9.checkPathsSync(e,a,"move",p);return v9.checkParentPathsSync(e,i,a,"move"),cu(a)||fu(gd.dirname(a)),vu(e,a,t,d)}r(hu,"moveSync");function cu(e){let a=gd.dirname(e);return gd.parse(a).root===a}r(cu,"isParentRoot");function vu(e,a,p,t){if(t)return _d(e,a,p);if(p)return _9(a),_d(e,a,p);if(w9.existsSync(a))throw new Error("dest already exists.");return _d(e,a,p)}r(vu,"doRename");function _d(e,a,p){try{w9.renameSync(e,a)}catch(t){if(t.code!=="EXDEV")throw t;return wu(e,a,p)}}r(_d,"rename");function wu(e,a,p){return uu(e,a,{overwrite:p,errorOnExist:!0}),_9(e)}r(wu,"moveAcrossDevice");g9.exports=hu});var b9=v((wv,S9)=>{"use strict";var _u=Se().fromCallback;S9.exports={move:_u(c9()),moveSync:y9()}});var T9=v((_v,x9)=>{"use strict";x9.exports={...Q1(),...Zt(),..._3(),...G3(),...o9(),...ze(),...b9(),...Gt(),...F1(),...Ip()}});var gu={};L9(gu,{TestRunMonitor:()=>Lp});module.exports=q9(gu);var C9=I1(require("net")),Ua=require("fs"),yd=I1(rr());var na=r(e=>new Promise(a=>setTimeout(a,e)),"awaitSleep"),nr=r(async(e,a=1e3,p="action hang guard timed out")=>{let t="guard-timed-out",i=r(async()=>(await na(a+1e3),t),"guard"),d=await Promise.race([e,i()]);if(typeof d=="string"&&d===t)throw new Error(p);return d},"guardReturn");var Yt=require("path");var xn=require("fs"),Tn=require("jsdom"),Nn=require("fs/promises"),Dn=I1(Pt());var kp=class{constructor(a,p,t,i="https://api.checksum.ai/api/test-runs"){this.reportHTMLFilePath=a;this.testRunUUID=p;this.pwTestIdToChecksumTestId=t;this.assetsBaseURL=i;this.supportVideo=!1}async process(){await this.initializeDOM(),this.makeLightModeOnly(),await this.editZipFile(),await this.writeFile()}async initializeDOM(){return this.dom=await Tn.JSDOM.fromFile(this.reportHTMLFilePath,{resources:"usable",runScripts:"dangerously"}),new Promise(a=>this.dom.window.addEventListener("load",a))}async writeFile(){let a=this.dom.serialize();a=a.replace(/window.playwrightReportBase64 = ".*";/,`window.playwrightReportBase64 = "${this.newBase64Zip}";`),await(0,Nn.cp)(this.reportHTMLFilePath,this.reportHTMLFilePath.replace(".html",".backup.html")),(0,xn.writeFileSync)(this.reportHTMLFilePath,a)}makeLightModeOnly(){this.dom.window.document.querySelector('meta[name="color-scheme"]').setAttribute("content","light");let p=this.dom.window.document.querySelector("head style"),t=p.innerHTML,i=/@media\s*\(prefers-color-scheme:\s*dark\)\s*{[^}]*}/g,d=t.replace(i,"");p.innerHTML=d}async editZipFile(){let a=this.dom.window.playwrightReportBase64.replace("data:application/zip;base64,",""),p=await(0,Dn.loadAsync)(a,{base64:!0});for(let i of Object.keys(p.files)){let d=p.file(i);if(d){let n=await d.async("string"),l=JSON.parse(n);i.startsWith("report")?this.handleReportJSON(l):this.handleFileReportJSON(l),p.file(i,JSON.stringify(l))}}let t=await p.generateAsync({type:"base64"});this.newBase64Zip=`data:application/zip;base64,${t}`}getCloudPath(a){return`${this.assetsBaseURL}/${this.testRunUUID}/${this.pwTestIdToChecksumTestId[a]}`}handleReportJSON(a){a.files.forEach(p=>p.tests.forEach(t=>{t.results.forEach(i=>{this.processAttachments(i.attachments,t.testId)})}))}handleFileReportJSON(a){var p;(p=a.tests)==null||p.forEach(t=>{var i;(i=t.results)==null||i.forEach(d=>{this.processAttachments(d.attachments,t.testId)})})}processAttachments(a,p){if(a.forEach(t=>this.updateAttachment(t,p)),!this.supportVideo){let t=a.findIndex(i=>i.name==="video");t!==-1&&a.splice(t,1)}}updateAttachment(a,p){["trace","video"].includes(a.name)&&(a.path=`${this.getCloudPath(p)}/${a.name}`)}};r(kp,"PlaywrightReportProcessor");var F9=require("http");var ue=require("fs"),ad=I1(Pt()),pd=require("readline/promises");var Ap=class{constructor(a,p,t,i){this.mode=a;this.inputZipFilePath=p;this.outputZipFilePath=t;this.frontendLogPrefix=i;this.originalTraceFileNames=[];this.remainingTraceFileNames=[];this.wallTimesToBeRemoved={};this.callIdsRemovals={};this.consoleLogGUIDs=[];this.numberOfLinesPerFile={};this.generationAllowedAPIName=["page.goto","page.waitForNavigation","locator.fill","locator.click","locator.hover","locator.check","locator.uncheck"]}async process(){await this.unzipAndWriteTraceFiles();for(let a of this.originalTraceFileNames)await this.preprocessFile(a);for(this.remainingTraceFileNames=[...this.originalTraceFileNames];this.remainingTraceFileNames.length>0;)for(let a of this.remainingTraceFileNames)await this.processFile(a);await this.reZip()}getBackupZipFilePath(){return this.inputZipFilePath.replace(".zip",".trace-files-backup.zip")}async unzipAndWriteTraceFiles(){let a=(0,ue.readFileSync)(this.inputZipFilePath);this.zipped=await(0,ad.loadAsync)(a),this.originalTraceFileNames=Object.keys(this.zipped.files).filter(i=>i.endsWith(".trace"));let p=await(0,ad.loadAsync)("UEsFBgAAAAAAAAAAAAAAAAAAAAAAAA==",{base64:!0});for(let i of this.originalTraceFileNames){let d=await this.zipped.file(i).async("string");(0,ue.writeFileSync)(i,d),p.file(i,d)}let t=await p.generateAsync({type:"nodebuffer"});(0,ue.writeFileSync)(this.getBackupZipFilePath(),t)}async reZip(){for(let p of this.originalTraceFileNames){let t=(0,ue.readFileSync)(p);this.zipped.remove(p),this.zipped.file(p,t)}let a=await this.zipped.generateAsync({type:"nodebuffer"});(0,ue.existsSync)(this.outputZipFilePath)&&(0,ue.rmSync)(this.outputZipFilePath),(0,ue.writeFileSync)(this.outputZipFilePath,a);for(let p of this.originalTraceFileNames)(0,ue.rmSync)(p)}async preprocessFile(a){this.callIdsRemovals[a]={callIdsToBeRemoved:{},arrayOfCallIdsToBeRemoved:new Set};let p=(0,ue.createReadStream)(a),t=(0,pd.createInterface)({input:p,crlfDelay:1/0}),i=0;for await(let d of t){i++;let n=JSON.parse(d);this.shouldLineBeRemoved(n)&&(n.wallTime&&(this.wallTimesToBeRemoved[n.wallTime]=!0),n.callId&&(this.callIdsRemovals[a].callIdsToBeRemoved[n.callId]=!0,this.callIdsRemovals[a].arrayOfCallIdsToBeRemoved.add(n.callId)))}this.numberOfLinesPerFile[a]=i}async processFile(a){var n,l;let p=[],t=(0,ue.createReadStream)(a),i=(0,pd.createInterface)({input:t,crlfDelay:1/0}),d=a;for await(let s of i){let m=JSON.parse(s),o=!1;if(this.frontendLogPrefix){if(this.isChecksumConsoleLog(m)){this.consoleLogGUIDs.push(m.guid);continue}if(this.isConsoleLogMetadata(m)&&this.consoleLogGUIDs.includes((l=(n=m.params)==null?void 0:n.message)==null?void 0:l.guid))continue}if(this.lineCanBeRemoved(m)&&(this.wallTimesToBeRemoved[m.wallTime]||this.callIdsRemovals[d].callIdsToBeRemoved[m.callId]||Array.from(this.callIdsRemovals[d].arrayOfCallIdsToBeRemoved).some(c=>s.includes(`"${c}"`)))&&(o=!0),o){m.callId&&(this.callIdsRemovals[d].callIdsToBeRemoved[m.callId]=!0,this.callIdsRemovals[d].arrayOfCallIdsToBeRemoved.add(m.callId));continue}p.push(s)}if(p.length===this.numberOfLinesPerFile[d]){let s=this.remainingTraceFileNames.indexOf(d);s>-1&&this.remainingTraceFileNames.splice(s,1)}else this.numberOfLinesPerFile[d]=p.length,(0,ue.writeFileSync)(a,p.join(`
9
- `))}isChecksumConsoleLog(a){var p,t;return a.class==="ConsoleMessage"&&((t=(p=a.initializer)==null?void 0:p.text)==null?void 0:t.startsWith(this.frontendLogPrefix))}isConsoleLogMetadata(a){return a.class==="BrowserContext"&&a.method==="console"}lineCanBeRemoved(a){return!["frame-snapshot"].includes(a.type)}shouldLineBeRemoved(a){switch(this.mode){case"runtime":return this.shouldLineBeRemoved_runtime(a);case"generation":return this.shouldLineBeRemoved_generation(a)}return!1}shouldLineBeRemoved_runtime(a){var p;return(p=a.stack)==null?void 0:p.find(t=>!t.file.endsWith("spec.ts")&&!["executePlaywrightMethodWithTimeout"].includes(t.function))}shouldLineBeRemoved_generation(a){return!!a.apiName&&!this.generationAllowedAPIName.includes(a.apiName)}};r(Ap,"PlaywrightTraceProcessor");var N9=I1(Pt()),Jt=I1(T9()),Kt=I1(require("path")),D9=require("fs");async function E9(e,a){let p=await Jt.default.readdir(a);await Promise.all(p.map(async t=>{let i=Kt.default.join(a,t);if((await Jt.default.stat(i)).isDirectory()){let n=e.folder(t);await E9(n,i)}else{let n=await Jt.default.readFile(i);e.file(t,n)}}))}r(E9,"addFolderToZip");async function k9(e){let a=new N9.default;try{await E9(a,e);let p=await a.generateAsync({type:"nodebuffer"}),t=`${(0,Kt.basename)(e)}.zip`;return(0,D9.writeFileSync)(t,p),t}catch(p){return console.error("Error creating zip:",p),null}}r(k9,"zipFolder");var Lp=class{constructor(a,p=!1){this.config=a;this.isolatedMode=p;this.MAX_UPLOADS=5;this.MONITOR_INTERVAL=5e3;this.UPLOAD_TIMEOUT=6e5;this.assets=[];this.stats={passed:0,failed:0,healed:0};this.reportComplete=!1;this.pwTestIdToChecksumTestId={};setInterval(this.monitorUploads.bind(this),this.MONITOR_INTERVAL),this.listenForMessages(),this.startServer()}listenForMessages(){process.stdin.on("data",async a=>{let p=a.toString().trim();if(!p.startsWith("cli:"))return;let[t,i]=p.substring(4).split("=");switch(t){case"report":await this.handleReport(i),this.monitorUploadsCompletion();break;case"shutdown":this.shutdown();break}})}sendMessage(a){console.log(`${"monitor"}:${a}`)}async handleReport(a){if(!this.isolatedMode)return this.reportAsset=this.initAsset({type:"report",path:a}),await new kp(a,this.config.sessionId,this.pwTestIdToChecksumTestId).process(),this.uploadAsset(this.reportAsset)}shutdown(){console.log("Received shutdown message from CLI"),this.server.close(),process.exit(0)}async monitorUploadsCompletion(){if(this.isolatedMode||!this.reportComplete&&this.reportAsset&&this.reportAsset.complete){this.reportComplete=!0;let a="{}";try{a=JSON.stringify(this.stats)}catch(p){console.log("Error stringifying stats",p)}this.sendMessage(`report-uploaded=${a}`)}if(this.reportComplete&&this.assets.filter(a=>a.complete||a.error).length===this.assets.length){await na(100),this.sendMessage("complete");return}await na(1e3),this.monitorUploadsCompletion()}async startServer(){let a=await this.acquirePortNumber();this.sendMessage(`port=${a}`),this.server=(0,F9.createServer)((p,t)=>{let i=r(n=>{t.writeHead(400,{"Content-Type":"text/plain"}),t.end(n)},"returnErrorWithMessage");if(p.method!=="POST"){t.writeHead(404,{"Content-Type":"text/plain"}),t.end("Method not allowed");return}let d="";p.on("data",n=>{d+=n.toString()}),p.on("end",()=>{let n;try{n=JSON.parse(d)}catch{return i("Invalid body")}let{type:l,payload:s,watch:m}=n;switch(l){case"asset":if(!s.path||!s.type)return i("Missing arguments");m?this.watchAsset(s):this.processAsset(s);break;case"testInfo":if(!s.pwTestId||!s.checksumTestId)return i("Missing arguments");this.pwTestIdToChecksumTestId[s.pwTestId]=s.checksumTestId;break;case"testStats":this.stats[s.passed?"passed":"failed"]++,s.healed&&this.stats.healed++;break;default:return i("Invalid message type")}t.writeHead(200,{"Content-Type":"text/plain"}),t.end("OK")})}),this.server.listen(a)}monitorUploads(){let a=r(()=>this.assets.filter(t=>t.response&&!t.complete&&!t.error),"getActiveUploads"),p=this.assets.filter(t=>!t.response);if(p.length!==0&&!(a().length>=this.MAX_UPLOADS))for(;p.length>0&&a().length<this.MAX_UPLOADS;){let t=p.pop();this.uploadAsset(t)}}async uploadAsset(a){if(this.isolatedMode){a.response=new Promise((l,s)=>{setTimeout(()=>{a.complete=!0,l(new Response)},Math.random()*100)});return}let{path:p}=a.info;if(console.log("uploading asset",p),await this.getSignedURLForUpload(a),!a.uploadURL){console.log("Error getting signed URL for asset",p),a.error=!0;return}let i=(0,Ua.statSync)(p).size,d=(0,Ua.createReadStream)(p),n=nr((0,yd.default)(a.uploadURL,{method:"PUT",headers:{"Content-length":i.toString()},body:d}),this.UPLOAD_TIMEOUT);n.then(l=>{if(!l.ok)throw l.json().then(s=>{console.log(s)}),new Error("Upload failed");console.log("Asset uploaded successfully",p),a.complete=!0}).catch(l=>{console.log("Error uploading asset",p,l),a.error=!0}),a.response=n}async getSignedURLForUpload(a){try{let{apiKey:p,sessionId:t,checksumApiURL:i}=this.config,d=a.info,n=await(0,yd.default)(`${i}/client-api/test-runs/${t}/get-upload-url`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:p},body:JSON.stringify(d)}),{url:l}=await n.json();a.uploadURL=l}catch(p){return console.error("Error getting signed URL for artifact",p),null}}watchAsset(a){let p=(0,Yt.dirname)(a.path),t=(0,Yt.basename)(a.path),i=(0,Ua.watch)(p,(d,n)=>{n===t&&(this.processAsset(a),i.close())})}processAsset(a){if(!this.isolatedMode)switch(a.type){case"trace":return this.processTrace(a.path,a.testId);case"har":return this.processHar(a.path,a.testId);case"esra":case"test-files":return this.addAsset(a)}}async processHar(a,p){await na(1e3);let t=await k9(a);if(console.log("processed har, sending for upload"),t)return this.addAsset({type:"har",path:t,testId:p})}async processTrace(a,p){await na(1e3);let t=a.replace(".zip",".processed.zip");await new Ap("runtime",a,t,"$checksum").process(),console.log("processed trace files, sending for upload"),this.addAsset({type:"trace",path:t,testId:p}),this.addAsset({type:"trace-backup-file",path:a,testId:p})}addAsset(a){if(this.isolatedMode)return;console.log("adding asset",a.path);let p=this.initAsset(a);return this.assets.push(p),p}initAsset(a){return{complete:!1,error:!1,response:void 0,info:a}}async acquirePortNumber(){return await new Promise((a,p)=>{let t=C9.createServer();t.unref(),t.on("error",p),t.listen(0,()=>{let i=t.address().port;t.close(()=>{a(i)})})})}};r(Lp,"TestRunMonitor");var O9;try{O9=JSON.parse(process.argv[2])}catch(e){console.log("Error starting test run monitor",e),process.exit(1)}var A9;new Lp(O9,((A9=process.argv)==null?void 0:A9[3])==="isolated");0&&(module.exports={TestRunMonitor});
9
+ `))}isChecksumConsoleLog(a){var p,t;return a.class==="ConsoleMessage"&&((t=(p=a.initializer)==null?void 0:p.text)==null?void 0:t.startsWith(this.frontendLogPrefix))}isConsoleLogMetadata(a){return a.class==="BrowserContext"&&a.method==="console"}lineCanBeRemoved(a){return!["frame-snapshot"].includes(a.type)}shouldLineBeRemoved(a){switch(this.mode){case"runtime":return this.shouldLineBeRemoved_runtime(a);case"generation":return this.shouldLineBeRemoved_generation(a)}return!1}shouldLineBeRemoved_runtime(a){var p;return(p=a.stack)==null?void 0:p.find(t=>!t.file.endsWith("spec.ts")&&!["executePlaywrightMethodWithTimeout"].includes(t.function))}shouldLineBeRemoved_generation(a){return!!a.apiName&&!this.generationAllowedAPIName.includes(a.apiName)}};r(Ap,"PlaywrightTraceProcessor");var N9=I1(Pt()),Jt=I1(T9()),Kt=I1(require("path")),D9=require("fs");async function E9(e,a){let p=await Jt.default.readdir(a);await Promise.all(p.map(async t=>{let i=Kt.default.join(a,t);if((await Jt.default.stat(i)).isDirectory()){let n=e.folder(t);await E9(n,i)}else{let n=await Jt.default.readFile(i);e.file(t,n)}}))}r(E9,"addFolderToZip");async function k9(e){let a=new N9.default;try{await E9(a,e);let p=await a.generateAsync({type:"nodebuffer"}),t=`${(0,Kt.basename)(e)}.zip`;return(0,D9.writeFileSync)(t,p),t}catch(p){return console.error("Error creating zip:",p),null}}r(k9,"zipFolder");var Lp=class{constructor(a,p=!1){this.config=a;this.isolatedMode=p;this.MAX_UPLOADS=5;this.MONITOR_INTERVAL=5e3;this.UPLOAD_TIMEOUT=6e5;this.assets=[];this.stats={passed:0,failed:0,healed:0};this.reportComplete=!1;this.pwTestIdToChecksumTestId={};setInterval(this.monitorUploads.bind(this),this.MONITOR_INTERVAL),this.listenForMessages(),this.startServer()}listenForMessages(){process.stdin.on("data",async a=>{let p=a.toString().trim();if(!p.startsWith("cli:"))return;let[t,i]=p.substring(4).split("=");switch(t){case"report":await this.handleReport(i),this.monitorUploadsCompletion();break;case"shutdown":this.shutdown();break}})}sendMessage(a){console.log(`${"monitor"}:${a}`)}async handleReport(a){if(!this.isolatedMode)return this.reportAsset=this.initAsset({type:"report",path:a}),await new kp(a,this.config.sessionId,this.pwTestIdToChecksumTestId).process(),this.uploadAsset(this.reportAsset)}shutdown(){console.log("Received shutdown message from CLI"),this.server.close(),process.exit(0)}async monitorUploadsCompletion(){if(this.isolatedMode||!this.reportComplete&&this.reportAsset&&this.reportAsset.complete){this.reportComplete=!0;let a="{}";try{a=JSON.stringify(this.stats)}catch(p){console.log("Error stringifying stats",p)}this.sendMessage(`report-uploaded=${a}`)}if(this.reportComplete&&this.assets.filter(a=>a.complete||a.error).length===this.assets.length){await na(100),this.sendMessage("complete");return}await na(1e3),this.monitorUploadsCompletion()}async startServer(){let a=await this.acquirePortNumber();this.sendMessage(`port=${a}`),this.server=(0,F9.createServer)((p,t)=>{let i=r(n=>{t.writeHead(400,{"Content-Type":"text/plain"}),t.end(n)},"returnErrorWithMessage");if(p.method!=="POST"){t.writeHead(404,{"Content-Type":"text/plain"}),t.end("Method not allowed");return}let d="";p.on("data",n=>{d+=n.toString()}),p.on("end",()=>{let n;try{n=JSON.parse(d)}catch{return i("Invalid body")}let{type:l,payload:s,watch:m}=n;switch(l){case"asset":if(!s.path||!s.type)return i("Missing arguments");m?this.watchAsset(s):this.processAsset(s);break;case"testInfo":if(!s.pwTestId||!s.checksumTestId)return i("Missing arguments");this.pwTestIdToChecksumTestId[s.pwTestId]=s.checksumTestId;break;case"testStats":this.stats[s.passed?"passed":"failed"]++,s.healed&&this.stats.healed++;break;default:return i("Invalid message type")}t.writeHead(200,{"Content-Type":"text/plain"}),t.end("OK")})}),this.server.listen(a)}monitorUploads(){let a=r(()=>this.assets.filter(t=>t.response&&!t.complete&&!t.error),"getActiveUploads"),p=this.assets.filter(t=>!t.response);if(p.length!==0&&!(a().length>=this.MAX_UPLOADS))for(;p.length>0&&a().length<this.MAX_UPLOADS;){let t=p.pop();this.uploadAsset(t)}}async uploadAsset(a){if(this.isolatedMode){a.response=new Promise((l,s)=>{setTimeout(()=>{a.complete=!0,l(new Response)},Math.random()*100)});return}let{path:p}=a.info;if(console.log("Uploading file",p),await this.getSignedURLForUpload(a),!a.uploadURL){console.log("Error getting signed URL for asset",p),a.error=!0;return}let i=(0,Ua.statSync)(p).size,d=(0,Ua.createReadStream)(p),n=nr((0,yd.default)(a.uploadURL,{method:"PUT",headers:{"Content-length":i.toString()},body:d}),this.UPLOAD_TIMEOUT);n.then(l=>{if(!l.ok)throw l.json().then(s=>{console.log(s)}),new Error("Upload failed");console.log("File uploaded successfully",p),a.complete=!0}).catch(l=>{console.log("Error uploading asset",p,l),a.error=!0}),a.response=n}async getSignedURLForUpload(a){try{let{apiKey:p,sessionId:t,checksumApiURL:i}=this.config,d=a.info,n=await(0,yd.default)(`${i}/client-api/test-runs/${t}/get-upload-url`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:p},body:JSON.stringify(d)}),{url:l}=await n.json();a.uploadURL=l}catch(p){return console.error("Error getting signed URL for artifact",p),null}}watchAsset(a){let p=(0,Yt.dirname)(a.path),t=(0,Yt.basename)(a.path),i=(0,Ua.watch)(p,(d,n)=>{n===t&&(this.processAsset(a),i.close())})}processAsset(a){if(!this.isolatedMode)switch(a.type){case"trace":return this.processTrace(a.path,a.testId);case"har":return this.processHar(a.path,a.testId);case"esra":case"test-files":return this.addAsset(a)}}async processHar(a,p){await na(1e3);let t=await k9(a);if(console.log("Processed har, sending for upload"),t)return this.addAsset({type:"har",path:t,testId:p})}async processTrace(a,p){await na(1e3);let t=a.replace(".zip",".processed.zip");await new Ap("runtime",a,t,"$checksum").process(),console.log("Processed trace files, sending for upload"),this.addAsset({type:"trace",path:t,testId:p}),this.addAsset({type:"trace-backup-file",path:a,testId:p})}addAsset(a){if(this.isolatedMode)return;console.log("Adding file",a.path);let p=this.initAsset(a);return this.assets.push(p),p}initAsset(a){return{complete:!1,error:!1,response:void 0,info:a}}async acquirePortNumber(){return await new Promise((a,p)=>{let t=C9.createServer();t.unref(),t.on("error",p),t.listen(0,()=>{let i=t.address().port;t.close(()=>{a(i)})})})}};r(Lp,"TestRunMonitor");var O9;try{O9=JSON.parse(process.argv[2])}catch(e){console.log("Error starting test run monitor",e),process.exit(1)}var A9;new Lp(O9,((A9=process.argv)==null?void 0:A9[3])==="isolated");0&&(module.exports={TestRunMonitor});