@checksum-ai/runtime 3.0.1 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/.env +1 -1
  2. package/cli.js +1 -1
  3. package/package.json +1 -1
package/.env CHANGED
@@ -1 +1 @@
1
- CHECKSUM_RUNTIME_BUILD_TIME=2026-04-17T10:28:22.079Z
1
+ CHECKSUM_RUNTIME_BUILD_TIME=2026-04-30T10:26:56.871Z
package/cli.js CHANGED
@@ -1793,7 +1793,7 @@ Actual: `+nt.attribValue);else{var oi=nt.tag,In=nt.tags[nt.tags.length-1]||nt;oi
1793
1793
  ${H6n}
1794
1794
  ${_}
1795
1795
  ${W6n}
1796
- ${(await s.getFormattedTestFileCode()).code}`)}loadVtgTestFileMirror(r){if(!r||!r.startsWith("/"))throw new Error("Currently vtg mode can only run with absolute path to file");let i=new u5e(r);return i.loadTestFromFile(),i}createActionJsonFileForExistingChecksumSpec(r,i){let s=r.testMirrors[0].translateStatementsToActions({mergeCustomCodeSteps:this.vtgSettingsService.getSettings().mergeCustomCodeSteps}),l=this.getActionJsonFilePath(i);(0,CY.writeFileSync)(l,JSON.stringify(s,null,2))}createFolderIfNotExists(r){return(0,CY.existsSync)(r)||(0,CY.mkdirSync)(r,{recursive:!0}),r}getSavePathForNewChecksumSpec(){return(0,Q0e.join)(this.draftsFolderPath,"test.checksum.spec.ts")}getActionJsonFilePath(r){let i=this.getFileName(r).replace(".spec.ts",".json");return(0,Q0e.join)(this.draftsFolderPath,i)}getEvalFilePath(r){let i=this.internalE2ETest?".eval.e2e.checksum.spec.ts":".eval.checksum.spec.ts";return(0,Q0e.join)(this.draftsFolderPath,i)}getFileName(r){return r.split("/").pop()}};e(GBr,"VtgTestRunner");var MBt=GBr;JDt();var FQe=require("fs"),PQe=require("path");var jBt=require("fs"),qP=e_(qS());var roa=/^[0-9a-zA-Z]+$/,noa=5;function aIn(n){return n?n.length===noa&&roa.test(n):!1}e(aIn,"isValidChecksumTestId");var ZBr=class ZBr{extract(r,i){if(!r)return;let s=r.split("/"),l=s[s.length-1];if(!l.endsWith(".checksum.spec.ts"))return;let _=l.replace(".checksum.spec.ts","").split(" - ").pop();return aIn(_)?_:void 0}};e(ZBr,"FileNameExtractionStrategy");var KBr=ZBr,eOr=class eOr{extract(r,i){if(!(!r||!(0,jBt.existsSync)(r)))try{let s=(0,jBt.readFileSync)(r,"utf-8"),l=qP.createSourceFile(r,s,qP.ScriptTarget.Latest,!0),f=new Map,_=e(b=>{if(qP.isCallExpression(b)){let E=b;if(this.isTestCall(E.expression)){let S=E.arguments[0];if(S&&qP.isCallExpression(S)&&qP.isIdentifier(S.expression)&&S.expression.text==="defineChecksumTest"){let T=this.extractDefineChecksumTestArgs(S);T&&aIn(T.checksumTestId)&&f.set(T.testTitle,T.checksumTestId)}}}qP.forEachChild(b,_)},"visit");return _(l),i&&f.has(i)?f.get(i):f.size>0?Array.from(f.values())[0]:void 0}catch{return}}isTestCall(r){return qP.isIdentifier(r)&&r.text==="test"?!0:qP.isPropertyAccessExpression(r)?qP.isIdentifier(r.expression)&&r.expression.text==="test":!1}extractDefineChecksumTestArgs(r){let i=r.arguments;if(i.length<2)return;let s=i[0],l=i[1],f=this.extractStringLiteral(s),_=this.extractStringLiteral(l);if(f&&_)return{testTitle:f,checksumTestId:_}}extractStringLiteral(r){if(qP.isStringLiteral(r)||qP.isNoSubstitutionTemplateLiteral(r))return r.text}};e(eOr,"FileContentExtractionStrategy");var YBr=eOr,tOr=class tOr{constructor(r){this.strategies=r||[new YBr,new KBr]}extract(r,i){for(let s of this.strategies){let l=s.extract(r,i);if(l)return l}}};e(tOr,"ChecksumTestIdExtractor");var XBr=tOr;var sIn=new XBr;var rOr=e(n=>isNaN(n)?0:n,"getStat"),ioa=e((n,r,i)=>{if(!n)return;let s=i||r,l;if((0,PQe.isAbsolute)(n))l=n;else{let _=(0,PQe.dirname)(r);l=(0,PQe.resolve)(_,n)}return l.replace(s+"/","")},"toRelativeFilePath"),oIn=e(n=>{let r=[];if(n.specs&&r.push(...n.specs),n.suites)for(let i of n.suites)r.push(...oIn(i));return r},"extractSpecsFromSuite"),aoa=e(n=>{let r=[];for(let i of n.suites)r.push(...oIn(i));return r},"extractFlatSpecsMap"),soa=e((n,r,i,s,l)=>{let{expected:f,unexpected:_,flaky:b}=n.stats,E=[];aoa(n).forEach(B=>{let N=ooa(B.id,r);N&&(B.recovered=!0);let j=B.tests[0],Q=B.tags.includes("bug")||j.annotations.some(ue=>ue.type==="bug"),z=j.annotations&&j.annotations.length>0?j.annotations.map(ue=>({type:ue.type,description:ue.description||""})):[],oe=B.tags||[],fe=i[B.id]||sIn.extract(B.file,B.title);E.push({checksumTestId:fe,playwrightTestId:B.id,success:!!B.ok,recovered:N,bug:Q,annotations:z,tags:oe,outcome:j.status,filePath:B.file,relativeFilePath:s?ioa(B.file,s,l):B.file})});let T={passed:rOr(b)+rOr(f),failed:rOr(_),bug:E.filter(B=>B.bug).length,recovered:E.filter(B=>B.recovered).length,tests:E};return E.forEach(B=>{B.bug&&(B.outcome==="expected"||B.outcome==="flaky"?T.passed--:B.outcome==="unexpected"&&T.failed--)}),T},"modifyStatsPerTestFile"),ooa=e((n,r)=>Object.values(r[n]||{}).some(i=>{var s,l;return(l=(s=i.autoRecoveryMetadata)==null?void 0:s.data)==null?void 0:l.autoRecovered}),"isAutoRecovered"),cIn=e((n,r,i,s,l)=>{(0,FQe.cpSync)(n,n+".backup");try{let f=JSON.parse((0,FQe.readFileSync)(n,"utf-8")),_=soa(f,r,i,s,l);return f.checksumMetadata=_,(0,FQe.writeFileSync)(n,JSON.stringify(f,null,2)),f}catch(f){return console.log("Error processing JSON report",f.message),null}},"processJSONReport");var iOr=class iOr extends jP{constructor(i,s=!1,l=!1){super(i,s);this.vtgMode=l;this.MAX_COMPLETION_WAIT=2*3600*1e3;this.didFail=!1;this.isolationMode=!1;this.trmMessagesBuffer="";this.completeIndicators={upload:!1,tests:!1,report:!1};this.uploadProgress=0;this.playwrightIdToReportMetadata={};this.pwTestIdToChecksumTestId={};this.logFilter={"upload-progress":{logEveryMS:1e3*30,lastLogTimestamp:0,logOnValueChange:!0,value:""}}}get replMode(){return this.getChecksumArg("repl")??!1}async run(){if(this.loadTracer(),this.validateAuthExists(),this.buildVolatileChecksumConfig(),this.vtgMode&&(this.config.options.hostReports=!1),!await this.getSession())return;this.testSuiteAnalytics=Est.getInstance(this.testSuiteRunInfo,this.isolationMode),this.testSuiteAnalytics.genericEvent(`Project root found at ${this.projectRootDirectory}`,{message:`Checksum root found at ${this.checksumRoot}`});let i={CHECKSUM_ROOT_FOLDER:this.checksumRoot,CHECKSUM_TEST_SUITE_INFO:JSON.stringify(this.testSuiteRunInfo)},s;try{s=await S4(this.startTestRunMonitor(this.testSuiteRunId),1e4,"test run monitor timeout"),i.CHECKSUM_UPLOAD_AGENT_PORT=s}catch{let E="Error starting test run monitor. Test results will not be available on checksum.";this.testSuiteAnalytics.testRunMonitorError({error:E}),this.log(E)}i.PW_TEST_HTML_REPORT_OPEN="never",this.isolationMode&&(i.CHECKSUM_ISOLATED_MODE="true"),this.testSuiteRunId&&(i.CHECKSUM_TEST_SUITE_ID=this.testSuiteRunId),this.replMode&&(i.CHECKSUM_REPL="true"),this.getChecksumArg("tm")&&(i.CHECKSUM_SHOW_TIME_MACHINE="true");let l=this.getNonChecksumArgs(),f=this.getChecksumArg("rerun-failed");if(f)try{let b=await this.fetchFailedTestPaths(typeof f=="string"?f:void 0);if(b.length===0){console.log("No non-passing tests found \u2014 nothing to rerun."),await this.shutdown(0);return}console.log(`Re-running ${b.length} non-passing test file(s)`),l.unshift(...b)}catch(b){this.printError(`Failed to fetch failed tests: ${b.message}`),await this.shutdown(1);return}this.vtgMode&&(await new MBt(this.getChecksumArg("id")||void 0,this.getChecksumArg("edit")||void 0,this.getChecksumArg("legacy")||!1,$h.vtg.isE2ETestMode,this.getChecksumArg("restore")||!1,this.checksumRoot,this.config,this.getInternalFilesDirPath()).initAndUpdateEnvAndPlaywrightArgs(i,l),$h.promptKillActivePlaywrightProcesses&&await this.promptKillActivePlaywrightProcesses()),this.replMode&&l.push("--debug");let _=`npx playwright test --config "${this.getPlaywrightConfigFilePath()}" ${l.map(b=>`"${b}"`).join(" ")}`;await this.patchPlaywright();try{console.log(`Tests running with @checksum-ai/runtime version ${this.checksumRuntimeVersion}`),this.replMode?(console.log("Running in REPL mode"),this.execCmd(_,i),await this.execCmd(`node ${__dirname}/repl.js`,i)):(this.testSuiteAnalytics.testSuiteStart(),await this.execCmd(_,i)),console.log(`Tests execution finished. Checksum is finalizing${this.isolationMode?"":" and uploading"} the report, please wait...`)}catch{this.didFail=!0,console.log("Error during test execution: Failed passing test"),this.testSuiteAnalytics.testsFailed()}finally{this.isolationMode||console.log("Waiting for test files to upload to Checksum..."),this.sendReportUploadRequest(),await this.patchPlaywright(!0),this.completeIndicators.tests=!0,await this.handleCompleteMessage()}}async uploadReport(){var l;if(this.loadTracer(),this.validateAuthExists(),this.buildVolatileChecksumConfig(),!await this.getSession())return;this.testSuiteAnalytics=Est.getInstance(this.testSuiteRunInfo,this.isolationMode);try{await S4(this.startTestRunMonitor(this.testSuiteRunId),1e4,"test run monitor timeout")}catch(f){this.printError(`Failed to start test run monitor: ${f.message}. Report will not be uploaded.`),await this.shutdown(1);return}this.tryLoadPlaywrightConfigFromFile(),this.loadPlaywrightConfigOptions();let i=this.resolveUserReportPathArg();i&&this.playwrightConfigOptions&&(this.playwrightConfigOptions.reportPath=i);let s=(l=this.playwrightConfigOptions)==null?void 0:l.reportPath;if(!s||!(0,gU.existsSync)(s)){this.printError(`Could not find report at ${s??"(unresolved)"}. Pass an explicit path: npx checksumai upload-report <path>`),await this.shutdown(1);return}console.log(`Uploading report from ${s} to Checksum...`),this.sendReportUploadRequest(),this.completeIndicators.tests=!0,await this.handleCompleteMessage()}tryLoadPlaywrightConfigFromFile(){if(!this.playwrightConfig)try{let i=this.getPlaywrightConfigFilePath();if((0,gU.existsSync)(i)){let s=require(i),l=(s==null?void 0:s.default)??s;l&&(this.playwrightConfig=l)}}catch(i){Xy("Could not load playwright config from file, falling back to defaults: "+i.message)}}resolveUserReportPathArg(){let i=this.args.find(l=>!l.startsWith("-")&&!l.includes("="));if(!i)return;let s=(0,$P.isAbsolute)(i)?i:(0,$P.resolve)(process.cwd(),i);if(!(0,gU.existsSync)(s))return s;try{if((0,gU.statSync)(s).isDirectory())return(0,$P.join)(s,"index.html")}catch{}return s}loadPlaywrightConfigOptions(){var S,T;let i=e(B=>(Xy("Using report folder",B),(0,$P.join)(B,"index.html")),"makeFilePath"),s=e(B=>(Xy("Using JSON report folder",B),(0,$P.join)(B,"report.json")),"makeJsonFilePath"),l,f,_=!1,b="never";process.env.PLAYWRIGHT_HTML_OUTPUT_DIR&&(l=i(process.env.PLAYWRIGHT_HTML_OUTPUT_DIR));let E=(S=this.playwrightConfig)==null?void 0:S.reporter;if(E instanceof Array){let B=E.filter(Q=>Q instanceof Array&&Q[0]==="html"),N=E.filter(Q=>Q instanceof Array&&Q[0]==="json");if(!process.env.PLAYWRIGHT_HTML_OUTPUT_DIR){let Q=B.find(z=>{var oe;return(oe=z[1])==null?void 0:oe.outputFolder});Q&&(l=i((0,$P.join)(this.checksumRoot,Q[1].outputFolder)))}let j=N.find(Q=>{var z;return(z=Q[1])==null?void 0:z.outputFile});j&&(_=!0,f=(0,$P.join)(this.checksumRoot,j[1].outputFile));for(let Q of B){let z=(T=Q[1])==null?void 0:T.open;if(z==="always"||z==="on-failure"){b=z;break}}}l||($h.isRepoMode?l=i((0,$P.join)($h.runtimeRoot,"playwright-report")):l=i((0,$P.join)(this.projectRootDirectory,"playwright-report"))),f||($h.isRepoMode?f=s((0,$P.join)($h.runtimeRoot,"playwright-report")):f=s((0,$P.join)(this.projectRootDirectory,"playwright-report"))),this.playwrightConfigOptions={openReportCriteria:b,reportPath:l,jsonReportPath:f,hasJsonReporter:_}}sendReportUploadRequest(){let i=e(T=>{this.testSuiteAnalytics.testSuiteError({error:T}),this.log(T),this.completeIndicators.report=!0,this.testRunMonitorProcess.stdin.write("cli:report=false")},"makeError");if(!this.playwrightConfigOptions)return i("No playwright config options");let{reportPath:s,openReportCriteria:l,jsonReportPath:f,hasJsonReporter:_}=this.playwrightConfigOptions;if(_&&((0,gU.existsSync)(f)?cIn(f,this.playwrightIdToReportMetadata,this.pwTestIdToChecksumTestId,this.checksumRoot,this.absoluteProjectRootDirectory):console.warn(`Could not find JSON report file at ${f}`)),!(0,gU.existsSync)(s))return i(`Could not find report file at ${s}`);Xy("Sending report upload request",s);let b=this.saveMetadataToFile((0,$P.dirname)(s)),E={reportPath:s,pathToChecksumMetadata:b,openReportCriteria:l,didFail:this.didFail,checksumRoot:this.checksumRoot,projectRoot:this.absoluteProjectRootDirectory},S=Buffer.from(JSON.stringify(E)).toString("base64");this.testRunMonitorProcess.stdin.write(`cli:report=${S}`)}saveMetadataToFile(i){try{let s=(0,$P.join)(i,`checksum-metadata-${(0,nOr.randomUUID)()}.json`);return(0,gU.writeFileSync)(s,JSON.stringify(this.playwrightIdToReportMetadata,null,2)),s}catch(s){let l=`Error saving metadata to file - ${s.message}`;this.testSuiteAnalytics.testSuiteError({error:l}),this.log(l);return}}startTestMonitorProcess(i){let l=[JSON.stringify({sessionId:i,apiURL:this.config.apiURL,apiKey:this.config.apiKey}),...this.isolationMode?["isolated"]:[]],f={command:"node",args:[(0,$P.join)(__dirname,"test-run-monitor.js"),...l]};return $h.isRepoMode&&(f.command="yarn",f.args=["test-run-monitor",...l]),uIn.spawn(f.command,f.args)}startTestRunMonitor(i){return new Promise(s=>{console.log("Starting test run monitor"),this.testRunMonitorProcess=this.startTestMonitorProcess(i),this.testRunMonitorProcess.stdout.on("data",l=>{let f=this.parseTRMMessages(l.toString().trim());if(f.length)for(let _ of f){if(_.startsWith("trace")){this.logTRMMessage(_),this.handleTestRunMonitorTrace(_.substring("trace".length+1));continue}if(!_.startsWith("monitor")){this.logTRMMessage(_);continue}let b=e(()=>{let B=_.substring("monitor".length+1),N=B.indexOf("=");if(N===-1)return{key:B,value:""};let[j,Q]=[B.substring(0,N),B.substring(N+1)];return{key:j,value:Q}},"getKeyAndValue"),{key:E,value:S}=b();if(!Object.values(mdr).includes(E)){this.logTRMMessage(`Received unknown monitor message: "${_}"`);continue}let T=E;this.logInterProcessEventMessage(T,S),E==="port"?s(S):this.handleTestRunMonitorMessage(T,S)}}),this.testRunMonitorProcess.on("exit",(l,f)=>{let _=`test run monitor process exited with code ${l} and signal ${f}`;this.testSuiteAnalytics.testRunMonitorError({error:_}),this.log(_)}),this.testRunMonitorProcess.stderr.on("data",l=>{let f=`TRM Error: ${l.toString().substring(0,300)}`;this.testSuiteAnalytics.testRunMonitorError({error:f}),this.log(f)}),this.testRunMonitorProcess.on("error",l=>{let f=`Error starting test run monitor: ${l.message}`;this.testSuiteAnalytics.testRunMonitorError({error:f}),this.log(f)})})}logInterProcessEventMessage(i,s){e(()=>{if(!this.logFilter[i])return!0;if(this.logFilter[i].logOnValueChange&&this.logFilter[i].value!==s)return this.logFilter[i].value=s,!0;if(this.logFilter[i].logEveryMS){let f=Date.now();if(f-this.logFilter[i].lastLogTimestamp>=this.logFilter[i].logEveryMS)return this.logFilter[i].lastLogTimestamp=f,!0}return!1},"shouldLog")()&&this.logTRMMessage(`Received monitor message: "${i}${s?`=${s}`:""}"`)}parseTRMMessages(i){let s=this.trmMessagesBuffer+i,l,f,_=e(()=>{l=s.indexOf("{trm}"),f=s.indexOf("{/trm}")},"findIndexes");_();let b=[];for(;l!==-1&&f!==-1&&f>l;){if(b.push(s.substring(l+"{trm}".length,f)),s=s.slice(f+"{/trm}".length).trim(),s.length&&!s.startsWith("{trm}"))return console.warn("Buffered data does not start with start delimiter",s),this.trmMessagesBuffer="",b;this.trmMessagesBuffer=s,_()}return b}setChecksumTestMetadata(i){let{retry:s,type:l,pwTestId:f,checksumTestId:_}=i;this.playwrightIdToReportMetadata[f]||(this.playwrightIdToReportMetadata[f]={}),this.playwrightIdToReportMetadata[f][s]||(this.playwrightIdToReportMetadata[f][s]={}),this.playwrightIdToReportMetadata[f][s][l]=i,this.pwTestIdToChecksumTestId[f]=_}async handleTestRunMonitorTrace(i){let s=i.indexOf("="),[l,f]=s>-1?[i.substring(0,s),i.substring(s+1)]:[i,""];if(!Object.values(ePt).includes(l)){Xy("Unknown trace event",l);return}try{let _=f?JSON.parse(f):{};switch(l){case"Upload Start":this.testSuiteAnalytics.uploadStart({filename:_.filename});break;case"Upload Complete":this.testSuiteAnalytics.uploadComplete({filename:_.filename});break;case"Upload Failed":this.testSuiteAnalytics.uploadFailed({filename:_.filename,error:_.error});break;case"Trace Processing Error":this.testSuiteAnalytics.traceProcessingError({error:_.error});break}}catch(_){Xy(`Error parsing trace payload, ${_.message}`)}}async handleTestRunMonitorMessage(i,s){var l;switch(i){case"uploads-complete-with-errors":console.log("Error uploading test files to Checksum");try{let _=JSON.parse(s);this.testSuiteAnalytics.uploadsCompleteWithErrors(_)}catch{}this.sendProcessingError().then(()=>{this.completeIndicators.upload=!0});break;case"checksumTestMetadata":try{let _=JSON.parse(s);this.setChecksumTestMetadata(_)}catch(_){let b=`Error parsing test metadata event - ${_.message}`;this.testSuiteAnalytics.testSuiteError({error:b}),this.log(b)}break;case"uploads-complete":this.isolationMode||console.log("Test files uploaded successfully"),this.testSuiteAnalytics.allUploadsComplete(),this.sendUploadsComplete().then(()=>{this.completeIndicators.upload=!0});break;case"report-complete":{if(this.isolationMode){this.completeIndicators.report=!0;break}let _=s.slice(0,s.indexOf(":"))==="true",b=s.slice(s.indexOf(":")+1),E="{}";try{if(b&&(0,gU.existsSync)(b)){E=(0,gU.readFileSync)(b,"utf-8");try{(0,gU.unlinkSync)(b)}catch{console.warn(`Failed to delete temporary stats file: ${b}`)}}else console.warn(`Stats file not found at: ${b}`)}catch(T){console.error(`Error reading stats file: ${T.message}`)}let S=this.handleStats(E);if(this.testSuiteAnalytics.testSuiteEnd({passed:S.passed,failed:S.failed,bug:S.bug,total:((l=S.tests)==null?void 0:l.length)||0}),await this.sendTestRunEnd(S),this.completeIndicators.report=!0,_){let T=`${this.checksumAppUrl}/#/test-runs/${this.testSuiteRunId}`,B=`Checksum report URL: ${T}`,N="*".repeat(B.length);console.log(`${N}
1796
+ ${(await s.getFormattedTestFileCode()).code}`)}loadVtgTestFileMirror(r){if(!r||!r.startsWith("/"))throw new Error("Currently vtg mode can only run with absolute path to file");let i=new u5e(r);return i.loadTestFromFile(),i}createActionJsonFileForExistingChecksumSpec(r,i){let s=r.testMirrors[0].translateStatementsToActions({mergeCustomCodeSteps:this.vtgSettingsService.getSettings().mergeCustomCodeSteps}),l=this.getActionJsonFilePath(i);(0,CY.writeFileSync)(l,JSON.stringify(s,null,2))}createFolderIfNotExists(r){return(0,CY.existsSync)(r)||(0,CY.mkdirSync)(r,{recursive:!0}),r}getSavePathForNewChecksumSpec(){return(0,Q0e.join)(this.draftsFolderPath,"test.checksum.spec.ts")}getActionJsonFilePath(r){let i=this.getFileName(r).replace(".spec.ts",".json");return(0,Q0e.join)(this.draftsFolderPath,i)}getEvalFilePath(r){let i=this.internalE2ETest?".eval.e2e.checksum.spec.ts":".eval.checksum.spec.ts";return(0,Q0e.join)(this.draftsFolderPath,i)}getFileName(r){return r.split("/").pop()}};e(GBr,"VtgTestRunner");var MBt=GBr;JDt();var FQe=require("fs"),PQe=require("path");var jBt=require("fs"),qP=e_(qS());var roa=/^[0-9a-zA-Z]+$/,noa=5;function aIn(n){return n?n.length===noa&&roa.test(n):!1}e(aIn,"isValidChecksumTestId");var ZBr=class ZBr{extract(r,i){if(!r)return;let s=r.split("/"),l=s[s.length-1];if(!l.endsWith(".checksum.spec.ts"))return;let _=l.replace(".checksum.spec.ts","").split(" - ").pop();return aIn(_)?_:void 0}};e(ZBr,"FileNameExtractionStrategy");var KBr=ZBr,eOr=class eOr{extract(r,i){if(!(!r||!(0,jBt.existsSync)(r)))try{let s=(0,jBt.readFileSync)(r,"utf-8"),l=qP.createSourceFile(r,s,qP.ScriptTarget.Latest,!0),f=new Map,_=e(b=>{if(qP.isCallExpression(b)){let E=b;if(this.isTestCall(E.expression)){let S=E.arguments[0];if(S&&qP.isCallExpression(S)&&qP.isIdentifier(S.expression)&&S.expression.text==="defineChecksumTest"){let T=this.extractDefineChecksumTestArgs(S);T&&aIn(T.checksumTestId)&&f.set(T.testTitle,T.checksumTestId)}}}qP.forEachChild(b,_)},"visit");return _(l),i&&f.has(i)?f.get(i):f.size>0?Array.from(f.values())[0]:void 0}catch{return}}isTestCall(r){return qP.isIdentifier(r)&&r.text==="test"?!0:qP.isPropertyAccessExpression(r)?qP.isIdentifier(r.expression)&&r.expression.text==="test":!1}extractDefineChecksumTestArgs(r){let i=r.arguments;if(i.length<2)return;let s=i[0],l=i[1],f=this.extractStringLiteral(s),_=this.extractStringLiteral(l);if(f&&_)return{testTitle:f,checksumTestId:_}}extractStringLiteral(r){if(qP.isStringLiteral(r)||qP.isNoSubstitutionTemplateLiteral(r))return r.text}};e(eOr,"FileContentExtractionStrategy");var YBr=eOr,tOr=class tOr{constructor(r){this.strategies=r||[new YBr,new KBr]}extract(r,i){for(let s of this.strategies){let l=s.extract(r,i);if(l)return l}}};e(tOr,"ChecksumTestIdExtractor");var XBr=tOr;var sIn=new XBr;var rOr=e(n=>isNaN(n)?0:n,"getStat"),ioa=e((n,r,i)=>{if(!n)return;let s=i||r,l;if((0,PQe.isAbsolute)(n))l=n;else{let _=(0,PQe.dirname)(r);l=(0,PQe.resolve)(_,n)}return l.replace(s+"/","")},"toRelativeFilePath"),oIn=e(n=>{let r=[];if(n.specs&&r.push(...n.specs),n.suites)for(let i of n.suites)r.push(...oIn(i));return r},"extractSpecsFromSuite"),aoa=e(n=>{let r=[];for(let i of n.suites)r.push(...oIn(i));return r},"extractFlatSpecsMap"),soa=e((n,r,i,s,l)=>{let{expected:f,unexpected:_,flaky:b}=n.stats,E=[];aoa(n).forEach(B=>{let N=ooa(B.id,r);N&&(B.recovered=!0);let j=B.tests[0],Q=B.tags.includes("bug")||j.annotations.some(ue=>ue.type==="bug"),z=j.annotations&&j.annotations.length>0?j.annotations.map(ue=>({type:ue.type,description:ue.description||""})):[],oe=B.tags||[],fe=i[B.id]||sIn.extract(B.file,B.title);E.push({checksumTestId:fe,playwrightTestId:B.id,success:!!B.ok,recovered:N,bug:Q,annotations:z,tags:oe,outcome:j.status,filePath:B.file,relativeFilePath:s?ioa(B.file,s,l):B.file})});let T={passed:rOr(b)+rOr(f),failed:rOr(_),bug:E.filter(B=>B.bug).length,recovered:E.filter(B=>B.recovered).length,tests:E};return E.forEach(B=>{B.bug&&(B.outcome==="expected"||B.outcome==="flaky"?T.passed--:B.outcome==="unexpected"&&T.failed--)}),T},"modifyStatsPerTestFile"),ooa=e((n,r)=>Object.values(r[n]||{}).some(i=>{var s,l;return(l=(s=i.autoRecoveryMetadata)==null?void 0:s.data)==null?void 0:l.autoRecovered}),"isAutoRecovered"),cIn=e((n,r,i,s,l)=>{(0,FQe.cpSync)(n,n+".backup");try{let f=JSON.parse((0,FQe.readFileSync)(n,"utf-8")),_=soa(f,r,i,s,l);return f.checksumMetadata=_,(0,FQe.writeFileSync)(n,JSON.stringify(f,null,2)),f}catch(f){return console.log("Error processing JSON report",f.message),null}},"processJSONReport");var iOr=class iOr extends jP{constructor(i,s=!1,l=!1){super(i,s);this.vtgMode=l;this.MAX_COMPLETION_WAIT=2*3600*1e3;this.didFail=!1;this.isolationMode=!1;this.trmMessagesBuffer="";this.completeIndicators={upload:!1,tests:!1,report:!1};this.uploadProgress=0;this.playwrightIdToReportMetadata={};this.pwTestIdToChecksumTestId={};this.logFilter={"upload-progress":{logEveryMS:1e3*30,lastLogTimestamp:0,logOnValueChange:!0,value:""}}}get replMode(){return this.getChecksumArg("repl")??!1}async run(){if(this.loadTracer(),this.validateAuthExists(),this.buildVolatileChecksumConfig(),this.vtgMode&&(this.config.options.hostReports=!1),!await this.getSession())return;this.testSuiteAnalytics=Est.getInstance(this.testSuiteRunInfo,this.isolationMode),this.testSuiteAnalytics.genericEvent(`Project root found at ${this.projectRootDirectory}`,{message:`Checksum root found at ${this.checksumRoot}`});let i={CHECKSUM_ROOT_FOLDER:this.checksumRoot,CHECKSUM_TEST_SUITE_INFO:JSON.stringify(this.testSuiteRunInfo)},s;try{s=await S4(this.startTestRunMonitor(this.testSuiteRunId),1e4,"test run monitor timeout"),i.CHECKSUM_UPLOAD_AGENT_PORT=s}catch{let E="Error starting test run monitor. Test results will not be available on checksum.";this.testSuiteAnalytics.testRunMonitorError({error:E}),this.log(E)}i.PW_TEST_HTML_REPORT_OPEN="never",this.isolationMode&&(i.CHECKSUM_ISOLATED_MODE="true"),this.testSuiteRunId&&(i.CHECKSUM_TEST_SUITE_ID=this.testSuiteRunId),this.replMode&&(i.CHECKSUM_REPL="true"),this.getChecksumArg("tm")&&(i.CHECKSUM_SHOW_TIME_MACHINE="true");let l=this.getNonChecksumArgs(),f=this.getChecksumArg("rerun-failed");if(f)try{let b=await this.fetchFailedTestPaths(typeof f=="string"?f:void 0);if(b.length===0){console.log("No non-passing tests found \u2014 nothing to rerun."),await this.shutdown(0);return}console.log(`Re-running ${b.length} non-passing test file(s)`),l.unshift(...b)}catch(b){this.printError(`Failed to fetch failed tests: ${b.message}`),await this.shutdown(1);return}this.vtgMode&&(await new MBt(this.getChecksumArg("id")||void 0,this.getChecksumArg("edit")||void 0,this.getChecksumArg("legacy")||!1,$h.vtg.isE2ETestMode,this.getChecksumArg("restore")||!1,this.checksumRoot,this.config,this.getInternalFilesDirPath()).initAndUpdateEnvAndPlaywrightArgs(i,l),$h.promptKillActivePlaywrightProcesses&&await this.promptKillActivePlaywrightProcesses()),this.replMode&&l.push("--debug");let _=`npx playwright test --config "${this.getPlaywrightConfigFilePath()}" ${l.map(b=>`"${b}"`).join(" ")}`;await this.patchPlaywright();try{console.log(`Tests running with @checksum-ai/runtime version ${this.checksumRuntimeVersion}`),this.replMode?(console.log("Running in REPL mode"),this.execCmd(_,i),await this.execCmd(`node ${__dirname}/repl.js`,i)):(this.testSuiteAnalytics.testSuiteStart(),await this.execCmd(_,i)),console.log(`Tests execution finished. Checksum is finalizing${this.isolationMode?"":" and uploading"} the report, please wait...`)}catch{this.didFail=!0,console.log("Error during test execution: Failed passing test"),this.testSuiteAnalytics.testsFailed()}finally{this.isolationMode||console.log("Waiting for test files to upload to Checksum..."),this.sendReportUploadRequest(),await this.patchPlaywright(!0),this.completeIndicators.tests=!0,await this.handleCompleteMessage()}}async uploadReport(){var l;if(this.loadTracer(),this.validateAuthExists(),this.buildVolatileChecksumConfig(),this.config.options.hostReports=!0,!await this.getSession())return;this.testSuiteAnalytics=Est.getInstance(this.testSuiteRunInfo,this.isolationMode);try{await S4(this.startTestRunMonitor(this.testSuiteRunId),1e4,"test run monitor timeout")}catch(f){this.printError(`Failed to start test run monitor: ${f.message}. Report will not be uploaded.`),await this.shutdown(1);return}this.tryLoadPlaywrightConfigFromFile(),this.loadPlaywrightConfigOptions();let i=this.resolveUserReportPathArg();i&&this.playwrightConfigOptions&&(this.playwrightConfigOptions.reportPath=i);let s=(l=this.playwrightConfigOptions)==null?void 0:l.reportPath;if(!s||!(0,gU.existsSync)(s)){this.printError(`Could not find report at ${s??"(unresolved)"}. Pass an explicit path: npx checksumai upload-report <path>`),await this.shutdown(1);return}console.log(`Uploading report from ${s} to Checksum...`),this.sendReportUploadRequest(),this.completeIndicators.tests=!0,await this.handleCompleteMessage()}tryLoadPlaywrightConfigFromFile(){if(!this.playwrightConfig)try{let i=this.getPlaywrightConfigFilePath();if((0,gU.existsSync)(i)){let s=require(i),l=(s==null?void 0:s.default)??s;l&&(this.playwrightConfig=l)}}catch(i){Xy("Could not load playwright config from file, falling back to defaults: "+i.message)}}resolveUserReportPathArg(){let i=this.args.find(l=>!l.startsWith("-")&&!l.includes("="));if(!i)return;let s=(0,$P.isAbsolute)(i)?i:(0,$P.resolve)(process.cwd(),i);if(!(0,gU.existsSync)(s))return s;try{if((0,gU.statSync)(s).isDirectory())return(0,$P.join)(s,"index.html")}catch{}return s}loadPlaywrightConfigOptions(){var S,T;let i=e(B=>(Xy("Using report folder",B),(0,$P.join)(B,"index.html")),"makeFilePath"),s=e(B=>(Xy("Using JSON report folder",B),(0,$P.join)(B,"report.json")),"makeJsonFilePath"),l,f,_=!1,b="never";process.env.PLAYWRIGHT_HTML_OUTPUT_DIR&&(l=i(process.env.PLAYWRIGHT_HTML_OUTPUT_DIR));let E=(S=this.playwrightConfig)==null?void 0:S.reporter;if(E instanceof Array){let B=E.filter(Q=>Q instanceof Array&&Q[0]==="html"),N=E.filter(Q=>Q instanceof Array&&Q[0]==="json");if(!process.env.PLAYWRIGHT_HTML_OUTPUT_DIR){let Q=B.find(z=>{var oe;return(oe=z[1])==null?void 0:oe.outputFolder});Q&&(l=i((0,$P.join)(this.checksumRoot,Q[1].outputFolder)))}let j=N.find(Q=>{var z;return(z=Q[1])==null?void 0:z.outputFile});j&&(_=!0,f=(0,$P.join)(this.checksumRoot,j[1].outputFile));for(let Q of B){let z=(T=Q[1])==null?void 0:T.open;if(z==="always"||z==="on-failure"){b=z;break}}}l||($h.isRepoMode?l=i((0,$P.join)($h.runtimeRoot,"playwright-report")):l=i((0,$P.join)(this.projectRootDirectory,"playwright-report"))),f||($h.isRepoMode?f=s((0,$P.join)($h.runtimeRoot,"playwright-report")):f=s((0,$P.join)(this.projectRootDirectory,"playwright-report"))),this.playwrightConfigOptions={openReportCriteria:b,reportPath:l,jsonReportPath:f,hasJsonReporter:_}}sendReportUploadRequest(){let i=e(T=>{this.testSuiteAnalytics.testSuiteError({error:T}),this.log(T),this.completeIndicators.report=!0,this.testRunMonitorProcess.stdin.write("cli:report=false")},"makeError");if(!this.playwrightConfigOptions)return i("No playwright config options");let{reportPath:s,openReportCriteria:l,jsonReportPath:f,hasJsonReporter:_}=this.playwrightConfigOptions;if(_&&((0,gU.existsSync)(f)?cIn(f,this.playwrightIdToReportMetadata,this.pwTestIdToChecksumTestId,this.checksumRoot,this.absoluteProjectRootDirectory):console.warn(`Could not find JSON report file at ${f}`)),!(0,gU.existsSync)(s))return i(`Could not find report file at ${s}`);Xy("Sending report upload request",s);let b=this.saveMetadataToFile((0,$P.dirname)(s)),E={reportPath:s,pathToChecksumMetadata:b,openReportCriteria:l,didFail:this.didFail,checksumRoot:this.checksumRoot,projectRoot:this.absoluteProjectRootDirectory},S=Buffer.from(JSON.stringify(E)).toString("base64");this.testRunMonitorProcess.stdin.write(`cli:report=${S}`)}saveMetadataToFile(i){try{let s=(0,$P.join)(i,`checksum-metadata-${(0,nOr.randomUUID)()}.json`);return(0,gU.writeFileSync)(s,JSON.stringify(this.playwrightIdToReportMetadata,null,2)),s}catch(s){let l=`Error saving metadata to file - ${s.message}`;this.testSuiteAnalytics.testSuiteError({error:l}),this.log(l);return}}startTestMonitorProcess(i){let l=[JSON.stringify({sessionId:i,apiURL:this.config.apiURL,apiKey:this.config.apiKey}),...this.isolationMode?["isolated"]:[]],f={command:"node",args:[(0,$P.join)(__dirname,"test-run-monitor.js"),...l]};return $h.isRepoMode&&(f.command="yarn",f.args=["test-run-monitor",...l]),uIn.spawn(f.command,f.args)}startTestRunMonitor(i){return new Promise(s=>{console.log("Starting test run monitor"),this.testRunMonitorProcess=this.startTestMonitorProcess(i),this.testRunMonitorProcess.stdout.on("data",l=>{let f=this.parseTRMMessages(l.toString().trim());if(f.length)for(let _ of f){if(_.startsWith("trace")){this.logTRMMessage(_),this.handleTestRunMonitorTrace(_.substring("trace".length+1));continue}if(!_.startsWith("monitor")){this.logTRMMessage(_);continue}let b=e(()=>{let B=_.substring("monitor".length+1),N=B.indexOf("=");if(N===-1)return{key:B,value:""};let[j,Q]=[B.substring(0,N),B.substring(N+1)];return{key:j,value:Q}},"getKeyAndValue"),{key:E,value:S}=b();if(!Object.values(mdr).includes(E)){this.logTRMMessage(`Received unknown monitor message: "${_}"`);continue}let T=E;this.logInterProcessEventMessage(T,S),E==="port"?s(S):this.handleTestRunMonitorMessage(T,S)}}),this.testRunMonitorProcess.on("exit",(l,f)=>{let _=`test run monitor process exited with code ${l} and signal ${f}`;this.testSuiteAnalytics.testRunMonitorError({error:_}),this.log(_)}),this.testRunMonitorProcess.stderr.on("data",l=>{let f=`TRM Error: ${l.toString().substring(0,300)}`;this.testSuiteAnalytics.testRunMonitorError({error:f}),this.log(f)}),this.testRunMonitorProcess.on("error",l=>{let f=`Error starting test run monitor: ${l.message}`;this.testSuiteAnalytics.testRunMonitorError({error:f}),this.log(f)})})}logInterProcessEventMessage(i,s){e(()=>{if(!this.logFilter[i])return!0;if(this.logFilter[i].logOnValueChange&&this.logFilter[i].value!==s)return this.logFilter[i].value=s,!0;if(this.logFilter[i].logEveryMS){let f=Date.now();if(f-this.logFilter[i].lastLogTimestamp>=this.logFilter[i].logEveryMS)return this.logFilter[i].lastLogTimestamp=f,!0}return!1},"shouldLog")()&&this.logTRMMessage(`Received monitor message: "${i}${s?`=${s}`:""}"`)}parseTRMMessages(i){let s=this.trmMessagesBuffer+i,l,f,_=e(()=>{l=s.indexOf("{trm}"),f=s.indexOf("{/trm}")},"findIndexes");_();let b=[];for(;l!==-1&&f!==-1&&f>l;){if(b.push(s.substring(l+"{trm}".length,f)),s=s.slice(f+"{/trm}".length).trim(),s.length&&!s.startsWith("{trm}"))return console.warn("Buffered data does not start with start delimiter",s),this.trmMessagesBuffer="",b;this.trmMessagesBuffer=s,_()}return b}setChecksumTestMetadata(i){let{retry:s,type:l,pwTestId:f,checksumTestId:_}=i;this.playwrightIdToReportMetadata[f]||(this.playwrightIdToReportMetadata[f]={}),this.playwrightIdToReportMetadata[f][s]||(this.playwrightIdToReportMetadata[f][s]={}),this.playwrightIdToReportMetadata[f][s][l]=i,this.pwTestIdToChecksumTestId[f]=_}async handleTestRunMonitorTrace(i){let s=i.indexOf("="),[l,f]=s>-1?[i.substring(0,s),i.substring(s+1)]:[i,""];if(!Object.values(ePt).includes(l)){Xy("Unknown trace event",l);return}try{let _=f?JSON.parse(f):{};switch(l){case"Upload Start":this.testSuiteAnalytics.uploadStart({filename:_.filename});break;case"Upload Complete":this.testSuiteAnalytics.uploadComplete({filename:_.filename});break;case"Upload Failed":this.testSuiteAnalytics.uploadFailed({filename:_.filename,error:_.error});break;case"Trace Processing Error":this.testSuiteAnalytics.traceProcessingError({error:_.error});break}}catch(_){Xy(`Error parsing trace payload, ${_.message}`)}}async handleTestRunMonitorMessage(i,s){var l;switch(i){case"uploads-complete-with-errors":console.log("Error uploading test files to Checksum");try{let _=JSON.parse(s);this.testSuiteAnalytics.uploadsCompleteWithErrors(_)}catch{}this.sendProcessingError().then(()=>{this.completeIndicators.upload=!0});break;case"checksumTestMetadata":try{let _=JSON.parse(s);this.setChecksumTestMetadata(_)}catch(_){let b=`Error parsing test metadata event - ${_.message}`;this.testSuiteAnalytics.testSuiteError({error:b}),this.log(b)}break;case"uploads-complete":this.isolationMode||console.log("Test files uploaded successfully"),this.testSuiteAnalytics.allUploadsComplete(),this.sendUploadsComplete().then(()=>{this.completeIndicators.upload=!0});break;case"report-complete":{if(this.isolationMode){this.completeIndicators.report=!0;break}let _=s.slice(0,s.indexOf(":"))==="true",b=s.slice(s.indexOf(":")+1),E="{}";try{if(b&&(0,gU.existsSync)(b)){E=(0,gU.readFileSync)(b,"utf-8");try{(0,gU.unlinkSync)(b)}catch{console.warn(`Failed to delete temporary stats file: ${b}`)}}else console.warn(`Stats file not found at: ${b}`)}catch(T){console.error(`Error reading stats file: ${T.message}`)}let S=this.handleStats(E);if(this.testSuiteAnalytics.testSuiteEnd({passed:S.passed,failed:S.failed,bug:S.bug,total:((l=S.tests)==null?void 0:l.length)||0}),await this.sendTestRunEnd(S),this.completeIndicators.report=!0,_){let T=`${this.checksumAppUrl}/#/test-runs/${this.testSuiteRunId}`,B=`Checksum report URL: ${T}`,N="*".repeat(B.length);console.log(`${N}
1797
1797
  ${B}
1798
1798
  ${N}`),this.testSuiteAnalytics.reportComplete({stats:S,reportUrl:T})}else this.testSuiteAnalytics.testSuiteError({error:"An error occurred while uploading the test report to Checksum"}),this.testSuiteAnalytics.reportUploadError(),console.log("An error occurred while uploading the test report to Checksum");break}case"upload-progress":{if(this.isolationMode)break;let _=parseInt(s);(_<this.uploadProgress||_>=this.uploadProgress+10||_===100&&this.uploadProgress!==100)&&(this.uploadProgress=_,console.log(`[ Uploads progress: ${this.uploadProgress}% ]`))}break;case"log":console.log(s);break;case"trace":let f=s;if(!Object.values(ePt).includes(f))return;this.testSuiteAnalytics.genericEvent(f);break;case"playwrightConfig":try{this.playwrightConfig||(this.playwrightConfig=JSON.parse(s),this.testSuiteAnalytics.playwrightConfig({config:this.playwrightConfig}),this.loadPlaywrightConfigOptions())}catch(_){let b=`Error parsing playwright config - ${_.message}`;this.testSuiteAnalytics.playwrightConfigError({error:b}),this.log(b)}break;default:this.testSuiteAnalytics.testRunMonitorError({error:`Unhandled test run monitor message: ${i}=${s}`}),this.log(`Unhandled test run monitor message: ${i}=${s}`)}}handleStats(i){let s={};try{i&&i.length>0?(s=JSON.parse(i),s.tests=s.tests.map(l=>{let f=this.playwrightIdToReportMetadata[l.playwrightTestId];if(!f)return l;let _=Object.keys(f??{}),b=!1,E=!1,S=[];_.forEach(B=>{var N;if(f[B]){let j=f[B].autoRecoverySummaries;(N=j==null?void 0:j.data)!=null&&N.length&&S.push(...j.data)}});let T=_[_.length-1];if(T&&f[T]){let B=f[T].autoRecoveryMetadata;b=(B==null?void 0:B.data.autoRecoveryTriggered)??!1,E=(B==null?void 0:B.data.autoRecovered)??!1}return{...l,recovered:E,autoRecoveryTriggered:b,autoRecoverySummaries:S}})):(this.testSuiteAnalytics.testSuiteError({error:"No stats received from test run monitor"}),Xy("No stats received from test run monitor"))}catch(l){this.testSuiteAnalytics.testSuiteError({error:`Error parsing stats - ${l.message}`}),this.log(`Error parsing stats - ${l.message}`)}return s}async handleCompleteMessage(){let i=Date.now(),s=12;for(;;){if(Date.now()-i>this.MAX_COMPLETION_WAIT){console.log("Warning: Checksum wasn't able to upload all test assets or expected a file the couldn't be found. This might cause issues when viewing the report/trace."),this.testSuiteAnalytics.runtimeTimeout(),this.shutdown(1);return}if(Object.keys(this.completeIndicators).find(l=>!this.completeIndicators[l]))Xy(this.completeIndicators),--s===0&&(this.testSuiteAnalytics.completionStatus({stats:this.completeIndicators}),s=12),await nD(5e3);else{this.testSuiteAnalytics.runtimeComplete(),this.writeOutputFile(),console.log("Checksum test suite run has completed"),await this.shutdown(this.didFail?1:0);return}}}writeOutputFile(){try{let i=(0,$P.join)(this.getInternalFilesDirPath(),"output.json"),s={testRunId:this.testSuiteRunId,reportUrl:`${this.checksumAppUrl}/#/test-runs/${this.testSuiteRunId}`,failed:this.didFail};(0,gU.writeFileSync)(i,JSON.stringify(s,null,2)),console.log(`Checksum output written to ${i}`)}catch(i){this.log(`Error writing output file: ${i.message}`)}}async fetchWithTimeout(i,s,l=3e4){let f=new AbortController,_=setTimeout(()=>f.abort(),l);try{return await fetch(i,{...s,signal:f.signal})}finally{clearTimeout(_)}}async fetchFailedTestPaths(i){let s=this.config.apiKey,l=this.config.apiURL,f={Accept:"application/json",ChecksumAppCode:s};if(!i){let T=await this.fetchWithTimeout(`${l}/public-api/v1/test-runs/latest`,{headers:f});if(!T.ok){let N=await T.text();throw new Error(`Failed to fetch latest test run: ${T.status} ${N}`)}let B=await T.json();i=B.id,console.log(`Using latest test run: ${i} (branch: ${B.branch})`)}let _=await this.fetchWithTimeout(`${l}/public-api/v1/test-runs/${i}/results`,{headers:f});if(!_.ok){let T=await _.text();throw new Error(`Failed to fetch test run results: ${_.status} ${T}`)}let E=((await _.json()).tests??[]).filter(T=>T.status!=="passed"&&T.status!=="skipped");return[...new Set(E.map(T=>T.testFilePath).filter(Boolean))]}async shutdown(i=0){await this.cleanup(),process.exit(i)}async cleanup(){await super.cleanup(),this.testRunMonitorProcess&&(this.testRunMonitorProcess.stdin.write("cli:shutdown"),this.testRunMonitorProcess.kill())}async getSession(){let i,s;try{if(!this.config.options.hostReports)return this.setIsolatedMode(),!0;if(s=this.config.apiKey,!s||s==="<API key>"){let S="No API key found in checksum config - please set it in the config file - checksum.config.ts";return this.runtimeTrace(S,"Checksum Config Error"),this.log(S,!0),this.shutdown(1),!1}let l=await this.getEnvInfo(),f=JSON.stringify({...l,isHidden:!!this.config.options.hideReports}),_=await fetch(`${this.config.apiURL}/client-api/test-runs`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:s},body:f}),{uuid:b,appName:E}=await _.json();return this.testSuiteRunId=b,l.commit=l.name,l.name=E,this.testSuiteRunInfo={appName:E,commitHash:l.commitHash,envName:l.name,branch:l.branch,testSuiteRunId:b,checksumRuntimeVersion:this.checksumRuntimeVersion},!0}catch(l){let f=`Error connecting to Checksum, the report will not be hosted - ${l.message}`;return this.runtimeTrace(f,"Test Suite Init Error"),this.log(f),this.setIsolatedMode(),!0}}setIsolatedMode(){this.testSuiteRunId=process.env.CHECKSUM_TEST_SUITE_ID||(0,nOr.randomUUID)(),this.isolationMode=!0,this.completeIndicators.upload=!0,$h.testRun.monitoring.debugAnalytics?this.testSuiteRunInfo=$6n(this.checksumRuntimeVersion,this.testSuiteRunId):this.testSuiteRunInfo=q6n(this.checksumRuntimeVersion,this.testSuiteRunId)}async sendTestRunEnd(i){if(!this.isolationMode)try{let s="{}";try{s=JSON.stringify({...i,endedAt:Date.now()})}catch(l){this.testSuiteAnalytics.testSuiteError({error:`Error stringifying stats ${l.message}`}),this.log(`Error stringifying stats ${l.message}`,!0)}await this.updateTestRun(`${this.config.apiURL}/client-api/test-runs/${this.testSuiteRunId}`,"PATCH",s)}catch(s){return this.testSuiteAnalytics.testSuiteError({error:`Error sending test run end ${s.message}`}),this.log(`Error sending test run end ${s.message}`,!0),null}}async sendUploadsComplete(){if(!this.isolationMode)try{await this.updateTestRun(`${this.config.apiURL}/client-api/test-runs/${this.testSuiteRunId}/uploads-completed`,"PATCH")}catch(i){this.testSuiteAnalytics.testSuiteError({error:`Error sending test run uploads complete - ${i.message}`}),this.log(`Error sending test run uploads complete - ${i.message}`,!0)}}async sendProcessingError(){if(!this.isolationMode)try{await this.updateTestRun(`${this.config.apiURL}/client-api/test-runs/${this.testSuiteRunId}/process-error`,"PATCH")}catch(i){this.testSuiteAnalytics.testSuiteError({error:`Error sending test run processing error - ${i.message}`}),this.log(`Error sending test run processing error - ${i.message}`,!0)}}async updateTestRun(i,s,l=void 0){let f=await fetch(i,{method:s,headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:l});return Xy("Received update test run response from url:",i),await this.logApiResponse(f),f}async logApiResponse(i){try{if(!i.ok){let{status:l,statusText:f}=i,_=await i.text();this.testSuiteAnalytics.testSuiteError({status:l,statusText:f,error:_});return}i.headers.get("Content-Type").includes("application/json")?i.json().then(l=>{Xy("API Response:",l)}):i.text().then(l=>{Xy("API Response:",l)})}catch(s){this.testSuiteAnalytics.testSuiteError({error:`Error logging API response - ${s.message}`})}}logTRMMessage(i){(Array.isArray(i)?i:[i]).forEach(s=>{Xy("[trm]",s)})}};e(iOr,"TestsRunner");var NQe=iOr;var aOr=class aOr extends jP{constructor(r,i=!1){super(r,i)}async run(r){switch(r){default:console.log(`
1799
1799
  Checksum CLI
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@checksum-ai/runtime",
3
- "version": "3.0.1",
3
+ "version": "3.0.2",
4
4
  "description": "Checksum.ai test runtime",
5
5
  "main": "index.js",
6
6
  "dependencies": {