@testrelic/playwright-analytics 2.16.1-next.132 → 2.16.1-next.136

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.
@@ -1,9 +1,9 @@
1
- 'use strict';var crypto=require('crypto'),fs$1=require('fs'),path=require('path'),os$1=require('os'),core=require('@testrelic/core'),child_process=require('child_process'),http=require('http'),readline=require('readline'),promises=require('fs/promises'),zlib=require('zlib'),util=require('util'),stream=require('stream');var nn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var on=".testrelic-report";function Be(e,t,r,a){let n=`${e}|${t.join("|")}|${r}|${a}`;return crypto.createHash("sha256").update(n).digest("hex").substring(0,12)}function Oe(e,t,r){let a=`${e}|${t.join("|")}|${r}`;return crypto.createHash("sha256").update(a).digest("hex").substring(0,12)}var ie=class{constructor(t){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=path.join(t,on),this.testsDir=path.join(this.reportDir,"tests"),fs$1.mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(t,r,a){try{let n=path.join(this.testsDir,t);fs$1.mkdirSync(n,{recursive:!0});let s=path.join(n,"meta.json"),l=s+".tmp",i=JSON.stringify(r);return fs$1.writeFileSync(l,i,"utf-8"),fs$1.renameSync(l,s),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),a?.networkRequestsFile&&this.moveFile(a.networkRequestsFile,path.join(n,"network.jsonl")),a?.consoleLogsFile&&this.moveFile(a.consoleLogsFile,path.join(n,"console.jsonl")),a?.apiCallsFile&&this.moveFile(a.apiCallsFile,path.join(n,"api-calls.jsonl")),!0}catch(n){let s=n instanceof Error?n.message:String(n);return this.writeErrors.push({testId:t,error:s,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${t}: ${s}
1
+ 'use strict';var crypto=require('crypto'),fs$1=require('fs'),path=require('path'),os$1=require('os'),core=require('@testrelic/core'),child_process=require('child_process'),http=require('http'),readline=require('readline'),promises=require('fs/promises'),zlib=require('zlib'),util=require('util'),stream=require('stream');var nn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var on=".testrelic-report";function Be(e,t,r,a){let n=`${e}|${t.join("|")}|${r}|${a}`;return crypto.createHash("sha256").update(n).digest("hex").substring(0,12)}function Oe(e,t,r){let a=`${e}|${t.join("|")}|${r}`;return crypto.createHash("sha256").update(a).digest("hex").substring(0,12)}var ie=class{constructor(t){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=path.join(t,on),this.testsDir=path.join(this.reportDir,"tests"),fs$1.mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(t,r,a){try{let n=path.join(this.testsDir,t);fs$1.mkdirSync(n,{recursive:!0});let s=path.join(n,"meta.json"),o=s+".tmp",i=JSON.stringify(r);return fs$1.writeFileSync(o,i,"utf-8"),fs$1.renameSync(o,s),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),a?.networkRequestsFile&&this.moveFile(a.networkRequestsFile,path.join(n,"network.jsonl")),a?.consoleLogsFile&&this.moveFile(a.consoleLogsFile,path.join(n,"console.jsonl")),a?.apiCallsFile&&this.moveFile(a.apiCallsFile,path.join(n,"api-calls.jsonl")),!0}catch(n){let s=n instanceof Error?n.message:String(n);return this.writeErrors.push({testId:t,error:s,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${t}: ${s}
2
2
  `),false}}moveFile(t,r){try{fs$1.renameSync(t,r);}catch{try{let{copyFileSync:a}=nn("fs");a(t,r);try{fs$1.unlinkSync(t);}catch{}}catch(a){process.stderr.write(`[testrelic] Failed to move file ${t} \u2192 ${r}: ${a instanceof Error?a.message:String(a)}
3
- `);}}}writeIndex(t){let r=path.join(this.reportDir,"index.json"),a=r+".tmp",n=JSON.stringify(t);fs$1.writeFileSync(a,n,"utf-8"),fs$1.renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeCompactIndex(t){let r=path.join(this.reportDir,"index-compact.json"),a=r+".tmp",n=t.map(({titlePath:l,project:i,...d})=>d),s=JSON.stringify(n);fs$1.writeFileSync(a,s,"utf-8"),fs$1.renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeSummary(t){let r=path.join(this.reportDir,"summary.json"),a=r+".tmp",n=JSON.stringify(t);fs$1.writeFileSync(a,n,"utf-8"),fs$1.renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeManifest(t){let r=path.join(this.reportDir,"manifest.json"),a=r+".tmp",n=JSON.stringify(t);fs$1.writeFileSync(a,n,"utf-8"),fs$1.renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var or=".testrelic",fn="testrelic-config.json",gn=".testrelic",hn=5,mn=new Set(["__proto__","constructor","prototype"]),sr=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,uploadBudgetMs:12e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${or}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),vn={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function lr(e){let t=path.resolve(e);for(let r=0;r<=hn;r++){let a=path.join(t,or,fn);if(fs$1.existsSync(a))try{if(fs$1.statSync(a).isFile())return a}catch{}let n=path.join(t,gn);if(fs$1.existsSync(n))try{if(fs$1.statSync(n).isFile())return process.stderr.write(`[testrelic] Deprecation: config file ".testrelic" has moved to ".testrelic/testrelic-config.json". Please migrate your config file to the new location.
4
- `),n}catch{}let s=path.dirname(t);if(s===t)break;t=s;}return null}function dr(e){try{let t=fs$1.readFileSync(e,"utf-8"),r=JSON.parse(t);return typeof r!="object"||r===null||Array.isArray(r)||!cr(r)?null:r}catch{return null}}function cr(e){for(let t of Object.keys(e)){if(mn.has(t))return false;let r=e[t];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!cr(r))return false}return true}function ur(e){let t=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(e);if(t)return process.env[t[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(e);return r?process.env[r[1]]??null:e}function Ue(e){let t=Object.create(null);for(let r of Object.keys(e)){let a=e[r];typeof a=="string"&&a.startsWith("$")?t[r]=ur(a):typeof a=="object"&&a!==null&&!Array.isArray(a)?t[r]=Ue(a):t[r]=a;}return t}function ir(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let r=parseInt(t[1],10),a=t[2],n=vn[a];return !n||r<=0?null:r*n}function pr(e,t){let r=Object.create(null);if(Object.assign(r,sr),e){let d=e.cloud;d&&typeof d=="object"&&(typeof d.endpoint=="string"&&(r.endpoint=d.endpoint),typeof d.upload=="string"&&(r.uploadStrategy=d.upload),typeof d.timeout=="number"&&(r.timeout=d.timeout),typeof d.uploadBudgetMs=="number"&&(r.uploadBudgetMs=d.uploadBudgetMs),typeof d.apiKey=="string"&&d.apiKey.length>0&&(r.apiKey=d.apiKey));let o=e["testrelic-repo"]??e.project;o&&typeof o=="object"&&typeof o.name=="string"&&(r.projectName=o.name),e.project&&!e["testrelic-repo"]&&process.stderr.write(`[testrelic] Deprecation: "project" key in config is deprecated. Rename it to "testrelic-repo".
5
- `);let c=e.queue;if(c&&typeof c=="object"){if(typeof c.maxAge=="string"){let p=ir(c.maxAge);p!==null&&(r.queueMaxAge=p);}typeof c.directory=="string"&&(r.queueDirectory=c.directory);}}if(t){if(typeof t.apiKey=="string"&&t.apiKey.length>0){let d=t.apiKey.startsWith("$")?ur(t.apiKey):t.apiKey;d&&(r.apiKey=d);}if(typeof t.endpoint=="string"&&(r.endpoint=t.endpoint),typeof t.upload=="string"&&(r.uploadStrategy=t.upload),typeof t.timeout=="number"&&(r.timeout=t.timeout),typeof t.uploadBudgetMs=="number"&&(r.uploadBudgetMs=t.uploadBudgetMs),typeof t.projectName=="string"&&(r.projectName=t.projectName),typeof t.queueMaxAge=="string"){let d=ir(t.queueMaxAge);d!==null&&(r.queueMaxAge=d);}typeof t.queueDirectory=="string"&&(r.queueDirectory=t.queueDirectory),typeof t.uploadArtifacts=="boolean"&&(r.uploadArtifacts=t.uploadArtifacts),typeof t.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=t.artifactMaxSizeMb);}let a=process.env.TESTRELIC_API_KEY;a&&a.length>0&&(r.apiKey=a);let n=process.env.TESTRELIC_CLOUD_ENDPOINT;n&&core.isValidEndpointUrl(n)&&(r.endpoint=n);let s=process.env.TESTRELIC_UPLOAD_STRATEGY;s&&["batch","realtime","both"].includes(s)&&(r.uploadStrategy=s);let l=process.env.TESTRELIC_CLOUD_TIMEOUT;if(l){let d=parseInt(l,10);!isNaN(d)&&d>=1e3&&d<=12e4&&(r.timeout=d);}let i=Object.freeze(r);return core.isValidCloudConfig(i)?i:sr}var wn=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],kn=["authorization","cookie","set-cookie","x-api-key"],Sn=["password","secret","token","apiKey","api_key"];function fr(e){let t=Object.create(null);return t.trackApiCalls=e?.trackApiCalls??true,t.captureRequestHeaders=e?.captureRequestHeaders??true,t.captureResponseHeaders=e?.captureResponseHeaders??true,t.captureRequestBody=e?.captureRequestBody??true,t.captureResponseBody=e?.captureResponseBody??true,t.captureAssertions=e?.captureAssertions??true,t.redactHeaders=e?.redactHeaders??[...kn],t.redactBodyFields=e?.redactBodyFields??[...Sn],t.apiIncludeUrls=e?.apiIncludeUrls??[],t.apiExcludeUrls=e?.apiExcludeUrls??[],Object.freeze(t)}function gr(e){if(e!==void 0&&!core.isValidConfig(e))throw core.createError(core.ErrorCode.CONFIG_INVALID,"Invalid reporter configuration");let t=Object.create(null);t.outputPath=e?.outputPath??"./test-results/analytics-timeline.json",t.includeStackTrace=e?.includeStackTrace??false,t.includeCodeSnippets=e?.includeCodeSnippets??true,t.codeContextLines=e?.codeContextLines??3,t.includeNetworkStats=e?.includeNetworkStats??true,t.captureNavigation=e?.captureNavigation??true,t.navigationTypes=e?.navigationTypes??null,t.redactPatterns=[...wn,...e?.redactPatterns??[]],t.testRunId=e?.testRunId??null,t.metadata=e?.metadata??null;let r=t.outputPath;t.openReport=e?.openReport??true,t.htmlReportPath=e?.htmlReportPath??r.replace(/\.json$/,".html"),t.includeArtifacts=e?.includeArtifacts??true,t.trackApiCalls=e?.trackApiCalls??true,t.quiet=e?.quiet??false,t.includeActionSteps=e?.includeActionSteps??true,t.captureConsoleLogs=e?.captureConsoleLogs??true;let a=lr(process.cwd()),n=a?dr(a):null,s=n?Ue(n):null,l=pr(s,e?.cloud);return t.cloud=l.apiKey?l:null,t.reportMode=e?.reportMode??"streaming",t.streamingThreshold=e?.streamingThreshold??0,Object.freeze(t)}var ze="1.6.0";function hr(e,t,r){try{let n=fs$1.readFileSync(e,"utf-8").split(`
6
- `);if(t<1||t>n.length)return null;let s=Math.max(1,t-r),l=Math.min(n.length,t+r),i=[];for(let d=s;d<=l;d++){let o=d===t?">":" ",c=String(d).padStart(String(l).length," ");i.push(`${o} ${c} | ${n[d-1]}`);}return i.join(`
3
+ `);}}}writeIndex(t){let r=path.join(this.reportDir,"index.json"),a=r+".tmp",n=JSON.stringify(t);fs$1.writeFileSync(a,n,"utf-8"),fs$1.renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeCompactIndex(t){let r=path.join(this.reportDir,"index-compact.json"),a=r+".tmp",n=t.map(({titlePath:o,project:i,...d})=>d),s=JSON.stringify(n);fs$1.writeFileSync(a,s,"utf-8"),fs$1.renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeSummary(t){let r=path.join(this.reportDir,"summary.json"),a=r+".tmp",n=JSON.stringify(t);fs$1.writeFileSync(a,n,"utf-8"),fs$1.renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeManifest(t){let r=path.join(this.reportDir,"manifest.json"),a=r+".tmp",n=JSON.stringify(t);fs$1.writeFileSync(a,n,"utf-8"),fs$1.renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var or=".testrelic",fn="testrelic-config.json",gn=".testrelic",hn=5,mn=new Set(["__proto__","constructor","prototype"]),sr=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,uploadBudgetMs:12e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${or}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),vn={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function lr(e){let t=path.resolve(e);for(let r=0;r<=hn;r++){let a=path.join(t,or,fn);if(fs$1.existsSync(a))try{if(fs$1.statSync(a).isFile())return a}catch{}let n=path.join(t,gn);if(fs$1.existsSync(n))try{if(fs$1.statSync(n).isFile())return process.stderr.write(`[testrelic] Deprecation: config file ".testrelic" has moved to ".testrelic/testrelic-config.json". Please migrate your config file to the new location.
4
+ `),n}catch{}let s=path.dirname(t);if(s===t)break;t=s;}return null}function dr(e){try{let t=fs$1.readFileSync(e,"utf-8"),r=JSON.parse(t);return typeof r!="object"||r===null||Array.isArray(r)||!cr(r)?null:r}catch{return null}}function cr(e){for(let t of Object.keys(e)){if(mn.has(t))return false;let r=e[t];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!cr(r))return false}return true}function ur(e){let t=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(e);if(t)return process.env[t[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(e);return r?process.env[r[1]]??null:e}function Ue(e){let t=Object.create(null);for(let r of Object.keys(e)){let a=e[r];typeof a=="string"&&a.startsWith("$")?t[r]=ur(a):typeof a=="object"&&a!==null&&!Array.isArray(a)?t[r]=Ue(a):t[r]=a;}return t}function ir(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let r=parseInt(t[1],10),a=t[2],n=vn[a];return !n||r<=0?null:r*n}function pr(e,t){let r=Object.create(null);if(Object.assign(r,sr),e){let d=e.cloud;d&&typeof d=="object"&&(typeof d.endpoint=="string"&&(r.endpoint=d.endpoint),typeof d.upload=="string"&&(r.uploadStrategy=d.upload),typeof d.timeout=="number"&&(r.timeout=d.timeout),typeof d.uploadBudgetMs=="number"&&(r.uploadBudgetMs=d.uploadBudgetMs),typeof d.apiKey=="string"&&d.apiKey.length>0&&(r.apiKey=d.apiKey));let l=e["testrelic-repo"]??e.project;l&&typeof l=="object"&&typeof l.name=="string"&&(r.projectName=l.name),e.project&&!e["testrelic-repo"]&&process.stderr.write(`[testrelic] Deprecation: "project" key in config is deprecated. Rename it to "testrelic-repo".
5
+ `);let c=e.queue;if(c&&typeof c=="object"){if(typeof c.maxAge=="string"){let p=ir(c.maxAge);p!==null&&(r.queueMaxAge=p);}typeof c.directory=="string"&&(r.queueDirectory=c.directory);}}if(t){if(typeof t.apiKey=="string"&&t.apiKey.length>0){let d=t.apiKey.startsWith("$")?ur(t.apiKey):t.apiKey;d&&(r.apiKey=d);}if(typeof t.endpoint=="string"&&(r.endpoint=t.endpoint),typeof t.upload=="string"&&(r.uploadStrategy=t.upload),typeof t.timeout=="number"&&(r.timeout=t.timeout),typeof t.uploadBudgetMs=="number"&&(r.uploadBudgetMs=t.uploadBudgetMs),typeof t.projectName=="string"&&(r.projectName=t.projectName),typeof t.queueMaxAge=="string"){let d=ir(t.queueMaxAge);d!==null&&(r.queueMaxAge=d);}typeof t.queueDirectory=="string"&&(r.queueDirectory=t.queueDirectory),typeof t.uploadArtifacts=="boolean"&&(r.uploadArtifacts=t.uploadArtifacts),typeof t.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=t.artifactMaxSizeMb);}let a=process.env.TESTRELIC_API_KEY;a&&a.length>0&&(r.apiKey=a);let n=process.env.TESTRELIC_CLOUD_ENDPOINT;n&&core.isValidEndpointUrl(n)&&(r.endpoint=n);let s=process.env.TESTRELIC_UPLOAD_STRATEGY;s&&["batch","realtime","both"].includes(s)&&(r.uploadStrategy=s);let o=process.env.TESTRELIC_CLOUD_TIMEOUT;if(o){let d=parseInt(o,10);!isNaN(d)&&d>=1e3&&d<=12e4&&(r.timeout=d);}let i=Object.freeze(r);return core.isValidCloudConfig(i)?i:sr}var wn=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],kn=["authorization","cookie","set-cookie","x-api-key"],Sn=["password","secret","token","apiKey","api_key"];function fr(e){let t=Object.create(null);return t.trackApiCalls=e?.trackApiCalls??true,t.captureRequestHeaders=e?.captureRequestHeaders??true,t.captureResponseHeaders=e?.captureResponseHeaders??true,t.captureRequestBody=e?.captureRequestBody??true,t.captureResponseBody=e?.captureResponseBody??true,t.captureAssertions=e?.captureAssertions??true,t.redactHeaders=e?.redactHeaders??[...kn],t.redactBodyFields=e?.redactBodyFields??[...Sn],t.apiIncludeUrls=e?.apiIncludeUrls??[],t.apiExcludeUrls=e?.apiExcludeUrls??[],Object.freeze(t)}function gr(e){if(e!==void 0&&!core.isValidConfig(e))throw core.createError(core.ErrorCode.CONFIG_INVALID,"Invalid reporter configuration");let t=Object.create(null);t.outputPath=e?.outputPath??"./test-results/analytics-timeline.json",t.includeStackTrace=e?.includeStackTrace??false,t.includeCodeSnippets=e?.includeCodeSnippets??true,t.codeContextLines=e?.codeContextLines??3,t.includeNetworkStats=e?.includeNetworkStats??true,t.captureNavigation=e?.captureNavigation??true,t.navigationTypes=e?.navigationTypes??null,t.redactPatterns=[...wn,...e?.redactPatterns??[]],t.testRunId=e?.testRunId??null,t.metadata=e?.metadata??null;let r=t.outputPath;t.openReport=e?.openReport??true,t.htmlReportPath=e?.htmlReportPath??r.replace(/\.json$/,".html"),t.includeArtifacts=e?.includeArtifacts??true,t.trackApiCalls=e?.trackApiCalls??true,t.quiet=e?.quiet??false,t.includeActionSteps=e?.includeActionSteps??true,t.captureConsoleLogs=e?.captureConsoleLogs??true;let a=lr(process.cwd()),n=a?dr(a):null,s=n?Ue(n):null,o=pr(s,e?.cloud);return t.cloud=o.apiKey?o:null,t.reportMode=e?.reportMode??"streaming",t.streamingThreshold=e?.streamingThreshold??0,Object.freeze(t)}var ze="1.6.0";function hr(e,t,r){try{let n=fs$1.readFileSync(e,"utf-8").split(`
6
+ `);if(t<1||t>n.length)return null;let s=Math.max(1,t-r),o=Math.min(n.length,t+r),i=[];for(let d=s;d<=o;d++){let l=d===t?">":" ",c=String(d).padStart(String(o).length," ");i.push(`${l} ${c} | ${n[d-1]}`);}return i.join(`
7
7
  `)}catch{return null}}function mr(e){return t=>{let r=t;for(let a of e)if(typeof a=="string"){let n=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(n,"g"),"[REDACTED]");}else {let n=a.flags.includes("g")?a.flags:a.flags+"g",s=new RegExp(a.source,n);r=r.replace(s,"[REDACTED]");}return r}}function Tn(e){return e.GITHUB_ACTIONS!=="true"?null:{provider:"github-actions",buildId:e.GITHUB_RUN_ID??null,commitSha:e.GITHUB_SHA??null,branch:e.GITHUB_REF_NAME??null,runUrl:e.GITHUB_SERVER_URL&&e.GITHUB_REPOSITORY&&e.GITHUB_RUN_ID?`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`:null}}function Rn(e){return e.GITLAB_CI!=="true"?null:{provider:"gitlab-ci",buildId:e.CI_PIPELINE_ID??null,commitSha:e.CI_COMMIT_SHA??null,branch:e.CI_COMMIT_BRANCH??e.CI_COMMIT_REF_NAME??null,runUrl:e.CI_PIPELINE_URL??null}}function An(e){if(!e.JENKINS_URL)return null;let t=e.GIT_BRANCH??null;return t?.startsWith("origin/")&&(t=t.slice(7)),{provider:"jenkins",buildId:e.BUILD_ID??null,commitSha:e.GIT_COMMIT??null,branch:t,runUrl:e.BUILD_URL??null}}function _n(e){return e.CIRCLECI!=="true"?null:{provider:"circleci",buildId:e.CIRCLE_BUILD_NUM??null,commitSha:e.CIRCLE_SHA1??null,branch:e.CIRCLE_BRANCH??null,runUrl:e.CIRCLE_BUILD_URL??null}}function In(e){if(!e.BITBUCKET_PIPELINE_UUID)return null;let t=e.BITBUCKET_WORKSPACE&&e.BITBUCKET_REPO_SLUG&&e.BITBUCKET_PIPELINE_UUID?`https://bitbucket.org/${e.BITBUCKET_WORKSPACE}/${e.BITBUCKET_REPO_SLUG}/pipelines/results/${e.BITBUCKET_PIPELINE_UUID}`:null;return {provider:"bitbucket-pipelines",buildId:e.BITBUCKET_BUILD_NUMBER??null,commitSha:e.BITBUCKET_COMMIT??null,branch:e.BITBUCKET_BRANCH??null,runUrl:t}}var Mn=[Tn,Rn,An,_n,In];function U(e){let t=process.env;for(let r of Mn){let a=r(t);if(a)return a}return null}var He=`
8
8
  /* Theme Variables */
9
9
  :root,[data-theme="dark"]{
@@ -571,11 +571,11 @@ body{
571
571
  <path fill-rule="evenodd" clip-rule="evenodd" d="M4.75 1.08009C2.034 2.66209 -0.130999 7.63009 0.610001 10.5821C0.969001 12.0121 3.021 15.2131 5.17 17.6971C14.375 28.3321 18 39.7791 18 58.2101V71.0001H12.434C1.16501 71.0001 0 73.4641 0 97.3051C0 106.858 0.298003 128.922 0.662003 146.337L1.323 178H33.606C65.786 178 65.897 178.007 68.544 180.284C72.228 183.453 72.244 189.21 68.579 192.877L65.957 195.5L33.479 195.801L1 196.103V204.551V213H24.577H48.154L51.077 215.923C55.007 219.853 55.007 224.147 51.077 228.077L48.154 231H26.469H4.783L5.41901 233.534C5.76901 234.927 7.143 238.527 8.472 241.534L10.89 247H40.945H71L71.006 241.75C71.017 230.748 76.027 221.606 84.697 216.767C97.854 209.424 114.086 213.895 121.323 226.857C123.659 231.041 124.418 233.833 124.789 239.607L125.263 247H155.187H185.11L187.528 241.534C188.857 238.527 190.231 234.927 190.581 233.534L191.217 231H169.531H147.846L144.923 228.077C142.928 226.082 142 224.152 142 222C142 219.848 142.928 217.918 144.923 215.923L147.846 213H171.423H195V204.551V196.103L162.521 195.801L130.043 195.5L127.421 192.877C123.991 189.445 123.835 183.869 127.074 180.421L129.349 178H162.013H194.677L195.338 146.337C195.702 128.922 196 106.858 196 97.3051C196 73.4641 194.835 71.0001 183.566 71.0001H178V58.2101C178 39.6501 181.397 28.7731 190.538 18.0651C195.631 12.0971 196.572 9.00809 194.511 5.02109C192.672 1.46509 190.197 9.12233e-05 186.028 9.12233e-05C179.761 9.12233e-05 168.713 14.8831 163.388 30.5001C160.975 37.5771 160.608 40.3751 160.213 54.7501L159.765 71.0001H150.732H141.7L142.286 53.2501C142.904 34.5511 144.727 24.3761 148.938 16.1211C151.823 10.4671 151.628 5.90109 148.364 2.63609C145 -0.726907 140.105 -0.887909 136.596 2.25009C133.481 5.03609 128.686 17.0811 126.507 27.5921C125.569 32.1191 124.617 43.0901 124.28 53.2501L123.69 71.0001H115.345H107V38.4231V5.84609L104.077 2.92309C102.082 0.928088 100.152 9.12233e-05 98 9.12233e-05C95.848 9.12233e-05 93.918 0.928088 91.923 2.92309L89 5.84609V38.4231V71.0001H80.655H72.31L71.72 53.2501C71.383 43.0901 70.431 32.1191 69.493 27.5921C67.314 17.0811 62.519 5.03609 59.404 2.25009C55.998 -0.795909 51.059 -0.710905 47.646 2.45209C44.221 5.62609 44.191 9.92109 47.539 17.4911C51.71 26.9241 53.007 34.4791 53.676 53.2501L54.31 71.0001H45.272H36.235L35.787 54.7501C35.392 40.3751 35.025 37.5771 32.612 30.5001C27.194 14.6091 16.228 -0.02891 9.787 0.03009C7.979 0.04709 5.712 0.519093 4.75 1.08009ZM42.687 108.974C33.431 112.591 20.036 125.024 18.408 131.512C17.476 135.223 20.677 140.453 28.253 147.599C37.495 156.319 44.191 159.471 53.5 159.485C59.317 159.494 61.645 158.953 67.274 156.289C77.634 151.385 88.987 139.161 88.996 132.9C89.004 127.304 76.787 114.707 66.745 109.956C59.16 106.368 50.285 106.006 42.687 108.974ZM129.255 109.904C119.151 114.768 106.996 127.33 107.004 132.9C107.013 139.108 118.562 151.475 128.939 156.389C134.338 158.945 136.744 159.496 142.521 159.498C152.526 159.501 160.369 155.502 169.771 145.605C180.444 134.368 180.278 130.975 168.486 119.388C160.043 111.094 152.727 107.595 143 107.201C136.364 106.933 134.78 107.244 129.255 109.904ZM48.5 125.922C46.3 126.969 43.152 128.945 41.505 130.314L38.511 132.802L40.504 135.005C41.601 136.216 44.434 138.342 46.8 139.728C52.577 143.114 57.36 142.466 64.009 137.395L68.978 133.606L66.756 131.24C60.944 125.054 54.357 123.135 48.5 125.922ZM138.386 125.063C136.674 125.571 133.375 127.677 131.057 129.743L126.841 133.5L131.901 137.343C138.65 142.468 143.407 143.124 149.2 139.728C151.566 138.342 154.351 136.269 155.389 135.122C157.684 132.587 156.742 131.097 150.58 127.511C145.438 124.519 142.329 123.895 138.386 125.063ZM91.923 162.923C89.043 165.804 89 166.008 89 176.973C89 184.805 89.435 188.941 90.47 190.941C92.356 194.589 96.918 196.273 101.03 194.84C105.82 193.17 107 189.638 107 176.973C107 166.008 106.957 165.804 104.077 162.923C102.082 160.928 100.152 160 98 160C95.848 160 93.918 160.928 91.923 162.923ZM94.5 232.155C91.026 234.055 90 236.229 90 241.691V247H98H106V242.082C106 235.732 105.37 234.242 101.928 232.463C98.591 230.737 97.197 230.679 94.5 232.155Z" fill="url(#paint0_linear_55_11)"/>
572
572
  <defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
573
573
  <stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
574
- </linearGradient></defs></svg>`,$e=`<svg width="32" height="40" viewBox="0 0 196 247" fill="none" xmlns="http://www.w3.org/2000/svg">
574
+ </linearGradient></defs></svg>`,Ve=`<svg width="32" height="40" viewBox="0 0 196 247" fill="none" xmlns="http://www.w3.org/2000/svg">
575
575
  <path fill-rule="evenodd" clip-rule="evenodd" d="M4.75 1.08009C2.034 2.66209 -0.130999 7.63009 0.610001 10.5821C0.969001 12.0121 3.021 15.2131 5.17 17.6971C14.375 28.3321 18 39.7791 18 58.2101V71.0001H12.434C1.16501 71.0001 0 73.4641 0 97.3051C0 106.858 0.298003 128.922 0.662003 146.337L1.323 178H33.606C65.786 178 65.897 178.007 68.544 180.284C72.228 183.453 72.244 189.21 68.579 192.877L65.957 195.5L33.479 195.801L1 196.103V204.551V213H24.577H48.154L51.077 215.923C55.007 219.853 55.007 224.147 51.077 228.077L48.154 231H26.469H4.783L5.41901 233.534C5.76901 234.927 7.143 238.527 8.472 241.534L10.89 247H40.945H71L71.006 241.75C71.017 230.748 76.027 221.606 84.697 216.767C97.854 209.424 114.086 213.895 121.323 226.857C123.659 231.041 124.418 233.833 124.789 239.607L125.263 247H155.187H185.11L187.528 241.534C188.857 238.527 190.231 234.927 190.581 233.534L191.217 231H169.531H147.846L144.923 228.077C142.928 226.082 142 224.152 142 222C142 219.848 142.928 217.918 144.923 215.923L147.846 213H171.423H195V204.551V196.103L162.521 195.801L130.043 195.5L127.421 192.877C123.991 189.445 123.835 183.869 127.074 180.421L129.349 178H162.013H194.677L195.338 146.337C195.702 128.922 196 106.858 196 97.3051C196 73.4641 194.835 71.0001 183.566 71.0001H178V58.2101C178 39.6501 181.397 28.7731 190.538 18.0651C195.631 12.0971 196.572 9.00809 194.511 5.02109C192.672 1.46509 190.197 9.12233e-05 186.028 9.12233e-05C179.761 9.12233e-05 168.713 14.8831 163.388 30.5001C160.975 37.5771 160.608 40.3751 160.213 54.7501L159.765 71.0001H150.732H141.7L142.286 53.2501C142.904 34.5511 144.727 24.3761 148.938 16.1211C151.823 10.4671 151.628 5.90109 148.364 2.63609C145 -0.726907 140.105 -0.887909 136.596 2.25009C133.481 5.03609 128.686 17.0811 126.507 27.5921C125.569 32.1191 124.617 43.0901 124.28 53.2501L123.69 71.0001H115.345H107V38.4231V5.84609L104.077 2.92309C102.082 0.928088 100.152 9.12233e-05 98 9.12233e-05C95.848 9.12233e-05 93.918 0.928088 91.923 2.92309L89 5.84609V38.4231V71.0001H80.655H72.31L71.72 53.2501C71.383 43.0901 70.431 32.1191 69.493 27.5921C67.314 17.0811 62.519 5.03609 59.404 2.25009C55.998 -0.795909 51.059 -0.710905 47.646 2.45209C44.221 5.62609 44.191 9.92109 47.539 17.4911C51.71 26.9241 53.007 34.4791 53.676 53.2501L54.31 71.0001H45.272H36.235L35.787 54.7501C35.392 40.3751 35.025 37.5771 32.612 30.5001C27.194 14.6091 16.228 -0.02891 9.787 0.03009C7.979 0.04709 5.712 0.519093 4.75 1.08009ZM42.687 108.974C33.431 112.591 20.036 125.024 18.408 131.512C17.476 135.223 20.677 140.453 28.253 147.599C37.495 156.319 44.191 159.471 53.5 159.485C59.317 159.494 61.645 158.953 67.274 156.289C77.634 151.385 88.987 139.161 88.996 132.9C89.004 127.304 76.787 114.707 66.745 109.956C59.16 106.368 50.285 106.006 42.687 108.974ZM129.255 109.904C119.151 114.768 106.996 127.33 107.004 132.9C107.013 139.108 118.562 151.475 128.939 156.389C134.338 158.945 136.744 159.496 142.521 159.498C152.526 159.501 160.369 155.502 169.771 145.605C180.444 134.368 180.278 130.975 168.486 119.388C160.043 111.094 152.727 107.595 143 107.201C136.364 106.933 134.78 107.244 129.255 109.904ZM48.5 125.922C46.3 126.969 43.152 128.945 41.505 130.314L38.511 132.802L40.504 135.005C41.601 136.216 44.434 138.342 46.8 139.728C52.577 143.114 57.36 142.466 64.009 137.395L68.978 133.606L66.756 131.24C60.944 125.054 54.357 123.135 48.5 125.922ZM138.386 125.063C136.674 125.571 133.375 127.677 131.057 129.743L126.841 133.5L131.901 137.343C138.65 142.468 143.407 143.124 149.2 139.728C151.566 138.342 154.351 136.269 155.389 135.122C157.684 132.587 156.742 131.097 150.58 127.511C145.438 124.519 142.329 123.895 138.386 125.063ZM91.923 162.923C89.043 165.804 89 166.008 89 176.973C89 184.805 89.435 188.941 90.47 190.941C92.356 194.589 96.918 196.273 101.03 194.84C105.82 193.17 107 189.638 107 176.973C107 166.008 106.957 165.804 104.077 162.923C102.082 160.928 100.152 160 98 160C95.848 160 93.918 160.928 91.923 162.923ZM94.5 232.155C91.026 234.055 90 236.229 90 241.691V247H98H106V242.082C106 235.732 105.37 234.242 101.928 232.463C98.591 230.737 97.197 230.679 94.5 232.155Z" fill="url(#paint0_linear_55_11)"/>
576
576
  <defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
577
577
  <stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
578
- </linearGradient></defs></svg>`;var Ve=`
578
+ </linearGradient></defs></svg>`;var $e=`
579
579
  /* \u2500\u2500 Utilities \u2500\u2500 */
580
580
  function esc(s){if(!s)return '';return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;')}
581
581
  function stripAnsi(s){return s?s.replace(/\\u001b\\[[0-9;]*m/g,'').replace(/\\x1b\\[[0-9;]*m/g,''):''}
@@ -4002,7 +4002,7 @@ function _updateCard(cls,val){
4002
4002
  `;var En=`
4003
4003
  (function(){
4004
4004
  var data=JSON.parse(document.getElementById('report-data').textContent);
4005
- ${Ve}
4005
+ ${$e}
4006
4006
  ${Ke}
4007
4007
  ${Je}
4008
4008
  ${je}
@@ -4041,7 +4041,7 @@ ${""}
4041
4041
  <div class="wrap">
4042
4042
  <div class="top-bar">
4043
4043
  <div class="brand">
4044
- ${$e}
4044
+ ${Ve}
4045
4045
  <div class="brand-text">
4046
4046
  <span class="brand-title">TestRelic AI</span>
4047
4047
  <span class="brand-sub">Analytics Report</span>
@@ -4080,7 +4080,7 @@ ${""}
4080
4080
  ${n?`<script id="artifact-manifest-data" type="application/json">${n}</script>`:""}
4081
4081
  <script>${En}</script>
4082
4082
  </body>
4083
- </html>`}function ot(e,t,r,a){let n=e.replace(/<\//g,"<\\/"),s=t.replace(/<\//g,"<\\/"),l=a?a.replace(/<\//g,"<\\/"):null,i={};try{i=JSON.parse(e);}catch{}let d=`{
4083
+ </html>`}function ot(e,t,r,a){let n=e.replace(/<\//g,"<\\/"),s=t.replace(/<\//g,"<\\/"),o=a?a.replace(/<\//g,"<\\/"):null,i={};try{i=JSON.parse(e);}catch{}let d=`{
4084
4084
  "schemaVersion":"2.0",
4085
4085
  "reportMode":"streaming",
4086
4086
  "serverPort":${r??"null"},
@@ -4094,7 +4094,7 @@ ${n?`<script id="artifact-manifest-data" type="application/json">${n}</script>`:
4094
4094
  "ci":${i.ci?JSON.stringify(i.ci).replace(/<\//g,"<\\/"):"null"},
4095
4095
  "metadata":${i.metadata?JSON.stringify(i.metadata).replace(/<\//g,"<\\/"):"null"},
4096
4096
  "shardRunIds":${i.shardRunIds?JSON.stringify(i.shardRunIds).replace(/<\//g,"<\\/"):"null"}
4097
- }`,o=`
4097
+ }`,l=`
4098
4098
  (function(){
4099
4099
  var data=JSON.parse(document.getElementById('report-data').textContent);
4100
4100
  var _serverPort=data.serverPort||null;
@@ -4164,7 +4164,7 @@ ${n?`<script id="artifact-manifest-data" type="application/json">${n}</script>`:
4164
4164
  window.__trServerPort=_serverPort;
4165
4165
  window.__trIsStreaming=true;
4166
4166
 
4167
- ${Ve}
4167
+ ${$e}
4168
4168
  ${Ke}
4169
4169
  ${Je}
4170
4170
  ${je}
@@ -4207,7 +4207,7 @@ ${r?`<meta name="artifact-server-port" content="${r}">`:""}
4207
4207
  <div class="wrap">
4208
4208
  <div class="top-bar">
4209
4209
  <div class="brand">
4210
- ${$e}
4210
+ ${Ve}
4211
4211
  <div class="brand-text">
4212
4212
  <span class="brand-title">TestRelic AI</span>
4213
4213
  <span class="brand-sub">Analytics Report</span>
@@ -4243,41 +4243,41 @@ ${r?`<meta name="artifact-server-port" content="${r}">`:""}
4243
4243
  <div class="filter-drawer-body" id="filter-drawer-body"></div>
4244
4244
  </aside>
4245
4245
  <script id="report-data" type="application/json">${d}</script>
4246
- ${l?`<script id="artifact-manifest-data" type="application/json">${l}</script>`:""}
4247
- <script>${o}</script>
4246
+ ${o?`<script id="artifact-manifest-data" type="application/json">${o}</script>`:""}
4247
+ <script>${l}</script>
4248
4248
  </body>
4249
4249
  </html>`}function lt(e){try{let t=process.platform,r,a;t==="darwin"?(r="open",a=[e]):t==="win32"?(r="cmd",a=["/c","start","",e]):(r="xdg-open",a=[e]),child_process.execFile(r,a,n=>{n&&process.stderr.write(`[testrelic] Failed to open browser: ${n.message}
4250
- `);});}catch{}}path.join(os$1.tmpdir(),"testrelic-data");async function br(e,t,r,a){let n=(t-1)*r,s=[],l=0,i=readline.createInterface({input:fs$1.createReadStream(e,{encoding:"utf-8"}),crlfDelay:1/0});for await(let c of i)if(c.length!==0){if(l>=n&&s.length<r)try{s.push(JSON.parse(c));}catch{}if(l++,s.length>=r&&a!==void 0)break}let d=a??l,o=Math.max(1,Math.ceil(d/r));return {items:s,total:d,page:t,pageSize:r,totalPages:o}}var kr=/^[a-f0-9]{12}$/,ut=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Sr=500;function k(e,t,r){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(r));}function Cr(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type");}function he(e){try{return fs$1.existsSync(e)?JSON.parse(fs$1.readFileSync(e,"utf-8")):null}catch{return null}}function me(e){let t=0;try{let r=fs$1.readdirSync(e,{withFileTypes:!0});for(let a of r){let n=path.join(e,a.name);a.isFile()?t+=fs$1.statSync(n).size:a.isDirectory()&&(t+=me(n));}}catch{}return t}function Tr(e,t,r,a){let n=he(path.join(r,"index.json"));k(t,200,{status:"ok",reportMode:"streaming",testCount:n?.length??0,uptime:Math.floor((Date.now()-a)/1e3)});}function Rr(e,t,r){let a=he(path.join(r,"summary.json"));if(!a){k(t,404,{error:"Summary not found"});return}k(t,200,a);}function Ar(e,t,r){let a=he(path.join(r,"index.json"));if(!a){k(t,404,{error:"Test index not found"});return}let s=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,l=Math.max(1,parseInt(s.get("page")??"1",10)||1),i=Math.min(Sr,Math.max(1,parseInt(s.get("pageSize")??"100",10)||100)),d=s.get("status")?.split(",").filter(Boolean)??null,o=s.get("file")??null,c=s.get("search")?.toLowerCase()??null,p=s.get("tag")?.split(",").filter(Boolean)??null,v=s.get("sort")??"file",g=s.get("order")==="desc"?-1:1,f=a;d&&d.length>0&&(f=f.filter(y=>d.includes(y.status))),o&&(f=f.filter(y=>y.filePath===o||y.filePath.startsWith(o+"/"))),c&&(f=f.filter(y=>y.title.toLowerCase().includes(c)||y.filePath.toLowerCase().includes(c))),p&&p.length>0&&(f=f.filter(y=>p.some(w=>y.tags.includes(w)))),f=[...f].sort((y,w)=>{let C=0;switch(v){case "duration":C=y.duration-w.duration;break;case "status":C=y.status.localeCompare(w.status);break;case "title":C=y.title.localeCompare(w.title);break;default:C=y.filePath.localeCompare(w.filePath);break}return C*g});let m=f.length,u=Math.max(1,Math.ceil(m/i)),h=(l-1)*i,b=f.slice(h,h+i);k(t,200,{tests:b,pagination:{page:l,pageSize:i,totalItems:m,totalPages:u},filters:{status:d,file:o,search:c,tag:p}});}function _r(e,t,r,a){if(!kr.test(a)){k(t,400,{error:"Invalid test ID format"});return}let n=path.join(r,"tests",a,"meta.json"),s=path.join(r,"tests",`${a}.json`),l=fs$1.existsSync(n)?n:fs$1.existsSync(s)?s:null;if(!l){k(t,404,{error:`Test not found: ${a}`});return}try{let i=fs$1.readFileSync(l,"utf-8");t.writeHead(200,{"Content-Type":"application/json"}),t.end(i);}catch(i){k(t,500,{error:i instanceof Error?i.message:String(i)});}}async function Ir(e,t,r,a,n){if(!kr.test(a)){k(t,400,{error:"Invalid test ID format"});return}let l=path.join(r,"tests",a,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[n]);if(!fs$1.existsSync(l)){k(t,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let d=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,o=Math.max(1,parseInt(d.get("page")??"1",10)||1),c=Math.min(Sr,Math.max(1,parseInt(d.get("pageSize")??"50",10)||50)),p,v=path.join(r,"tests",a,"meta.json");if(fs$1.existsSync(v))try{let f=JSON.parse(fs$1.readFileSync(v,"utf-8"));switch(n){case "network":p=f.networkRequestsCount;break;case "console":p=f.consoleLogsCount;break;case "api-calls":p=f.apiCallsCount;break}}catch{}let g=await br(l,o,c,p);k(t,200,g);}catch(i){k(t,500,{error:i instanceof Error?i.message:String(i)});}}function Mr(e,t,r){let a=he(path.join(r,"index.json"));if(!a){k(t,404,{error:"Test index not found"});return}let n=new Map;for(let l of a){if(l.isRetry)continue;let i=n.get(l.filePath);switch(i||(i={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},n.set(l.filePath,i)),i.total++,l.status){case "passed":i.passed++;break;case "failed":i.failed++;break;case "flaky":i.flaky++;break;case "skipped":i.skipped++;break;case "timedout":i.timedOut++;break}}let s=Array.from(n.entries()).map(([l,i])=>({filePath:l,...i})).sort((l,i)=>l.filePath.localeCompare(i.filePath));k(t,200,{files:s});}function Er(e,t,r){if(!fs$1.existsSync(r)){k(t,200,{runs:[],totalSizeBytes:0});return}try{let a=[],n=0,s=fs$1.readdirSync(r,{withFileTypes:!0});for(let l of s){if(!l.isDirectory()||!ut.test(l.name))continue;let i=path.join(r,l.name),d=me(i),o=fs$1.readdirSync(i,{withFileTypes:!0}).filter(c=>c.isDirectory());a.push({folderName:l.name,totalSizeBytes:d,testCount:o.length}),n+=d;}a.sort((l,i)=>i.folderName.localeCompare(l.folderName)),k(t,200,{runs:a,totalSizeBytes:n});}catch(a){k(t,500,{error:a instanceof Error?a.message:String(a)});}}function Pr(e,t,r){try{let a=0,n=0;if(fs$1.existsSync(r)){let s=fs$1.readdirSync(r,{withFileTypes:!0});for(let l of s){if(!l.isDirectory()||!ut.test(l.name))continue;let i=path.join(r,l.name),d=me(i);fs$1.rmSync(i,{recursive:!0,force:!0}),n+=d,a++;}}k(t,200,{deletedCount:a,freedBytes:n});}catch(a){k(t,500,{error:a instanceof Error?a.message:String(a)});}}function Lr(e,t,r,a){if(!ut.test(a)){k(t,400,{error:"Invalid folder name"});return}let n=path.join(r,a);try{if(!fs$1.statSync(n).isDirectory()){k(t,404,{error:"Not found"});return}}catch{k(t,404,{error:"Not found"});return}try{let s=me(n);fs$1.rmSync(n,{recursive:!0,force:!0}),k(t,200,{deleted:a,freedBytes:s});}catch(s){k(t,500,{error:s instanceof Error?s.message:String(s)});}}function Dr(e,t,r){k(t,200,{status:"shutting_down"}),r.close();}function pt(e,t,r){if(!fs$1.existsSync(r)){k(t,404,{error:"File not found"});return}try{let a=fs$1.statSync(r).size,n=path.extname(r).toLowerCase(),s=Un[n]??"application/octet-stream",l=On(e.headers.range,a);if(l==="unsatisfiable"){t.writeHead(416,{"Content-Range":`bytes */${a}`,"Accept-Ranges":"bytes"}),t.end();return}if(l){t.writeHead(206,{"Content-Type":s,"Content-Length":l.end-l.start+1,"Content-Range":`bytes ${l.start}-${l.end}/${a}`,"Accept-Ranges":"bytes"}),xr(fs$1.createReadStream(r,{start:l.start,end:l.end}),t);return}t.writeHead(200,{"Content-Type":s,"Content-Length":a,"Accept-Ranges":"bytes"}),xr(fs$1.createReadStream(r),t);}catch(a){k(t,500,{error:a instanceof Error?a.message:String(a)});}}function xr(e,t){e.on("error",()=>{e.destroy(),t.destroy();}),t.on("close",()=>{e.destroy();}),e.pipe(t);}function On(e,t){if(!e)return null;let r=/^bytes=(\d*)-(\d*)$/.exec(e.trim());if(!r)return null;let[,a,n]=r;if(a===""&&n==="")return null;let s,l;if(a===""){let i=Number(n);if(i<=0)return "unsatisfiable";s=Math.max(0,t-i),l=t-1;}else s=Number(a),l=n===""?t-1:Math.min(Number(n),t-1);return !Number.isFinite(s)||!Number.isFinite(l)?null:t===0||s>=t||s>l?"unsatisfiable":{start:s,end:l}}var Un={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".json":"application/json",".html":"text/html",".css":"text/css",".js":"text/javascript",".svg":"image/svg+xml"};var $n=9323,Vn=10,jn=1800*1e3;function oe(e,t){return new Promise((r,a)=>{let n=t?.port??$n,s=Date.now(),l,i=0,d=fs$1.existsSync(path.join(e,"artifacts"))?path.join(e,"artifacts"):fs$1.existsSync(path.join(e,"..","artifacts"))?path.join(e,"..","artifacts"):path.join(e,"artifacts");function o(){clearTimeout(l),l=setTimeout(()=>{p.close();},jn);}let c=t?.htmlPath??null;if(!c){let g=path.dirname(e);try{let f=fs$1.readdirSync(g).find(m=>m.endsWith(".html"));f&&(c=path.join(g,f));}catch{}}let p=http.createServer((g,f)=>{if(o(),Cr(f),g.method==="OPTIONS"){f.writeHead(204),f.end();return}let m;try{m=new URL(g.url??"/",`http://${g.headers.host??"localhost"}`).pathname;}catch{k(f,400,{error:"Invalid URL"});return}if(g.method==="GET"&&(m==="/"||m==="/index.html")){if(c&&fs$1.existsSync(c)){pt(g,f,c);return}k(f,404,{error:"HTML report not found"});return}if(g.method==="GET"&&m==="/api/health"){Tr(g,f,e,s);return}if(g.method==="GET"&&m==="/api/summary"){Rr(g,f,e);return}if(g.method==="GET"&&m==="/api/tests"){Ar(g,f,e);return}if(g.method==="GET"&&m==="/api/files"){Mr(g,f,e);return}let u=m.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(g.method==="GET"&&u){Ir(g,f,e,u[1],u[2]);return}let h=m.match(/^\/api\/tests\/([a-f0-9]+)$/);if(g.method==="GET"&&h){_r(g,f,e,h[1]);return}if(g.method==="GET"&&m==="/api/artifacts"){Er(g,f,d);return}if(g.method==="DELETE"&&m==="/api/artifacts"){Pr(g,f,d);return}let b=m.match(/^\/api\/artifacts\/(.+)$/);if(g.method==="DELETE"&&b){Lr(g,f,d,decodeURIComponent(b[1]));return}if(g.method==="GET"&&m.startsWith("/artifacts/")){let y=decodeURIComponent(m.slice(11));if(y.includes("..")||y.includes("\0")){k(f,400,{error:"Invalid path"});return}pt(g,f,path.join(d,y));return}if(g.method==="POST"&&m==="/api/shutdown"){Dr(g,f,p);return}k(f,404,{error:"Not found"});});function v(g){let f=m=>{m.code==="EADDRINUSE"&&i<Vn?(i++,v(g+1)):a(m);};p.once("error",f),p.listen(g,"127.0.0.1",()=>{p.removeListener("error",f);let m=p.address();if(!m||typeof m=="string"){a(new Error("Failed to get server address"));return}o(),r({port:m.port,dispose:()=>new Promise(u=>{clearTimeout(l),p.close(()=>u());})});});}v(n);})}async function Nr(e){let t=await oe(e);return {port:t.port,dispose:t.dispose}}function Kn(e,t,r){let a=JSON.stringify(e),n=r?JSON.stringify(r):null;return vr(a,t,n)}async function gt(e,t,r){try{let a=null,n=null,s=t.reportMode==="streaming"||t.reportMode==="auto"&&e.timeline.length===0&&e.summary.total>=t.streamingThreshold,l,i=t.htmlReportPath,d=path.dirname(i);fs$1.mkdirSync(d,{recursive:!0});let o="",c="[]",p=null;if(s){o=JSON.stringify({...e.summary,testRunId:e.testRunId,startedAt:e.startedAt,completedAt:e.completedAt,totalDuration:e.totalDuration,ci:e.ci,metadata:e.metadata,shardRunIds:e.shardRunIds});let g=path.dirname(t.outputPath),f=path.join(g,".testrelic-report");try{let m=path.join(f,"index-compact.json"),u=path.join(f,"index.json");fs$1.existsSync(m)?c=fs$1.readFileSync(m,"utf-8"):fs$1.existsSync(u)&&(c=fs$1.readFileSync(u,"utf-8"));}catch{}p=r?JSON.stringify(r):null,l=ot(o,c,null,p);}else l=Kn(e,null,r);let v=i+".tmp";if(fs$1.writeFileSync(v,l,"utf-8"),fs$1.renameSync(v,i),s){if(e.ci===null){let g=path.dirname(t.outputPath),f=path.join(g,".testrelic-report"),m=path.resolve(i);try{if(await Yn(),a=await Xn(f),!a){n=await oe(f,{htmlPath:m}),a=n.port;let u=setInterval(()=>{},6e4),h=()=>{clearInterval(u),n?.dispose();};process.on("SIGINT",h),process.on("SIGTERM",h),setTimeout(h,1800*1e3).unref();}if(a){process.stderr.write(`
4250
+ `);});}catch{}}path.join(os$1.tmpdir(),"testrelic-data");async function br(e,t,r,a){let n=(t-1)*r,s=[],o=0,i=readline.createInterface({input:fs$1.createReadStream(e,{encoding:"utf-8"}),crlfDelay:1/0});for await(let c of i)if(c.length!==0){if(o>=n&&s.length<r)try{s.push(JSON.parse(c));}catch{}if(o++,s.length>=r&&a!==void 0)break}let d=a??o,l=Math.max(1,Math.ceil(d/r));return {items:s,total:d,page:t,pageSize:r,totalPages:l}}var kr=/^[a-f0-9]{12}$/,ut=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Sr=500;function k(e,t,r){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(r));}function Cr(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type");}function he(e){try{return fs$1.existsSync(e)?JSON.parse(fs$1.readFileSync(e,"utf-8")):null}catch{return null}}function me(e){let t=0;try{let r=fs$1.readdirSync(e,{withFileTypes:!0});for(let a of r){let n=path.join(e,a.name);a.isFile()?t+=fs$1.statSync(n).size:a.isDirectory()&&(t+=me(n));}}catch{}return t}function Tr(e,t,r,a){let n=he(path.join(r,"index.json"));k(t,200,{status:"ok",reportMode:"streaming",testCount:n?.length??0,uptime:Math.floor((Date.now()-a)/1e3)});}function Rr(e,t,r){let a=he(path.join(r,"summary.json"));if(!a){k(t,404,{error:"Summary not found"});return}k(t,200,a);}function Ar(e,t,r){let a=he(path.join(r,"index.json"));if(!a){k(t,404,{error:"Test index not found"});return}let s=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,o=Math.max(1,parseInt(s.get("page")??"1",10)||1),i=Math.min(Sr,Math.max(1,parseInt(s.get("pageSize")??"100",10)||100)),d=s.get("status")?.split(",").filter(Boolean)??null,l=s.get("file")??null,c=s.get("search")?.toLowerCase()??null,p=s.get("tag")?.split(",").filter(Boolean)??null,v=s.get("sort")??"file",g=s.get("order")==="desc"?-1:1,f=a;d&&d.length>0&&(f=f.filter(y=>d.includes(y.status))),l&&(f=f.filter(y=>y.filePath===l||y.filePath.startsWith(l+"/"))),c&&(f=f.filter(y=>y.title.toLowerCase().includes(c)||y.filePath.toLowerCase().includes(c))),p&&p.length>0&&(f=f.filter(y=>p.some(w=>y.tags.includes(w)))),f=[...f].sort((y,w)=>{let C=0;switch(v){case "duration":C=y.duration-w.duration;break;case "status":C=y.status.localeCompare(w.status);break;case "title":C=y.title.localeCompare(w.title);break;default:C=y.filePath.localeCompare(w.filePath);break}return C*g});let m=f.length,u=Math.max(1,Math.ceil(m/i)),h=(o-1)*i,b=f.slice(h,h+i);k(t,200,{tests:b,pagination:{page:o,pageSize:i,totalItems:m,totalPages:u},filters:{status:d,file:l,search:c,tag:p}});}function _r(e,t,r,a){if(!kr.test(a)){k(t,400,{error:"Invalid test ID format"});return}let n=path.join(r,"tests",a,"meta.json"),s=path.join(r,"tests",`${a}.json`),o=fs$1.existsSync(n)?n:fs$1.existsSync(s)?s:null;if(!o){k(t,404,{error:`Test not found: ${a}`});return}try{let i=fs$1.readFileSync(o,"utf-8");t.writeHead(200,{"Content-Type":"application/json"}),t.end(i);}catch(i){k(t,500,{error:i instanceof Error?i.message:String(i)});}}async function Ir(e,t,r,a,n){if(!kr.test(a)){k(t,400,{error:"Invalid test ID format"});return}let o=path.join(r,"tests",a,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[n]);if(!fs$1.existsSync(o)){k(t,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let d=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,l=Math.max(1,parseInt(d.get("page")??"1",10)||1),c=Math.min(Sr,Math.max(1,parseInt(d.get("pageSize")??"50",10)||50)),p,v=path.join(r,"tests",a,"meta.json");if(fs$1.existsSync(v))try{let f=JSON.parse(fs$1.readFileSync(v,"utf-8"));switch(n){case "network":p=f.networkRequestsCount;break;case "console":p=f.consoleLogsCount;break;case "api-calls":p=f.apiCallsCount;break}}catch{}let g=await br(o,l,c,p);k(t,200,g);}catch(i){k(t,500,{error:i instanceof Error?i.message:String(i)});}}function Mr(e,t,r){let a=he(path.join(r,"index.json"));if(!a){k(t,404,{error:"Test index not found"});return}let n=new Map;for(let o of a){if(o.isRetry)continue;let i=n.get(o.filePath);switch(i||(i={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},n.set(o.filePath,i)),i.total++,o.status){case "passed":i.passed++;break;case "failed":i.failed++;break;case "flaky":i.flaky++;break;case "skipped":i.skipped++;break;case "timedout":i.timedOut++;break}}let s=Array.from(n.entries()).map(([o,i])=>({filePath:o,...i})).sort((o,i)=>o.filePath.localeCompare(i.filePath));k(t,200,{files:s});}function Er(e,t,r){if(!fs$1.existsSync(r)){k(t,200,{runs:[],totalSizeBytes:0});return}try{let a=[],n=0,s=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of s){if(!o.isDirectory()||!ut.test(o.name))continue;let i=path.join(r,o.name),d=me(i),l=fs$1.readdirSync(i,{withFileTypes:!0}).filter(c=>c.isDirectory());a.push({folderName:o.name,totalSizeBytes:d,testCount:l.length}),n+=d;}a.sort((o,i)=>i.folderName.localeCompare(o.folderName)),k(t,200,{runs:a,totalSizeBytes:n});}catch(a){k(t,500,{error:a instanceof Error?a.message:String(a)});}}function Pr(e,t,r){try{let a=0,n=0;if(fs$1.existsSync(r)){let s=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of s){if(!o.isDirectory()||!ut.test(o.name))continue;let i=path.join(r,o.name),d=me(i);fs$1.rmSync(i,{recursive:!0,force:!0}),n+=d,a++;}}k(t,200,{deletedCount:a,freedBytes:n});}catch(a){k(t,500,{error:a instanceof Error?a.message:String(a)});}}function Lr(e,t,r,a){if(!ut.test(a)){k(t,400,{error:"Invalid folder name"});return}let n=path.join(r,a);try{if(!fs$1.statSync(n).isDirectory()){k(t,404,{error:"Not found"});return}}catch{k(t,404,{error:"Not found"});return}try{let s=me(n);fs$1.rmSync(n,{recursive:!0,force:!0}),k(t,200,{deleted:a,freedBytes:s});}catch(s){k(t,500,{error:s instanceof Error?s.message:String(s)});}}function Dr(e,t,r){k(t,200,{status:"shutting_down"}),r.close();}function pt(e,t,r){if(!fs$1.existsSync(r)){k(t,404,{error:"File not found"});return}try{let a=fs$1.statSync(r).size,n=path.extname(r).toLowerCase(),s=Un[n]??"application/octet-stream",o=On(e.headers.range,a);if(o==="unsatisfiable"){t.writeHead(416,{"Content-Range":`bytes */${a}`,"Accept-Ranges":"bytes"}),t.end();return}if(o){t.writeHead(206,{"Content-Type":s,"Content-Length":o.end-o.start+1,"Content-Range":`bytes ${o.start}-${o.end}/${a}`,"Accept-Ranges":"bytes"}),xr(fs$1.createReadStream(r,{start:o.start,end:o.end}),t);return}t.writeHead(200,{"Content-Type":s,"Content-Length":a,"Accept-Ranges":"bytes"}),xr(fs$1.createReadStream(r),t);}catch(a){k(t,500,{error:a instanceof Error?a.message:String(a)});}}function xr(e,t){e.on("error",()=>{e.destroy(),t.destroy();}),t.on("close",()=>{e.destroy();}),e.pipe(t);}function On(e,t){if(!e)return null;let r=/^bytes=(\d*)-(\d*)$/.exec(e.trim());if(!r)return null;let[,a,n]=r;if(a===""&&n==="")return null;let s,o;if(a===""){let i=Number(n);if(i<=0)return "unsatisfiable";s=Math.max(0,t-i),o=t-1;}else s=Number(a),o=n===""?t-1:Math.min(Number(n),t-1);return !Number.isFinite(s)||!Number.isFinite(o)?null:t===0||s>=t||s>o?"unsatisfiable":{start:s,end:o}}var Un={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".json":"application/json",".html":"text/html",".css":"text/css",".js":"text/javascript",".svg":"image/svg+xml"};var Vn=9323,$n=10,jn=1800*1e3;function oe(e,t){return new Promise((r,a)=>{let n=t?.port??Vn,s=Date.now(),o,i=0,d=fs$1.existsSync(path.join(e,"artifacts"))?path.join(e,"artifacts"):fs$1.existsSync(path.join(e,"..","artifacts"))?path.join(e,"..","artifacts"):path.join(e,"artifacts");function l(){clearTimeout(o),o=setTimeout(()=>{p.close();},jn);}let c=t?.htmlPath??null;if(!c){let g=path.dirname(e);try{let f=fs$1.readdirSync(g).find(m=>m.endsWith(".html"));f&&(c=path.join(g,f));}catch{}}let p=http.createServer((g,f)=>{if(l(),Cr(f),g.method==="OPTIONS"){f.writeHead(204),f.end();return}let m;try{m=new URL(g.url??"/",`http://${g.headers.host??"localhost"}`).pathname;}catch{k(f,400,{error:"Invalid URL"});return}if(g.method==="GET"&&(m==="/"||m==="/index.html")){if(c&&fs$1.existsSync(c)){pt(g,f,c);return}k(f,404,{error:"HTML report not found"});return}if(g.method==="GET"&&m==="/api/health"){Tr(g,f,e,s);return}if(g.method==="GET"&&m==="/api/summary"){Rr(g,f,e);return}if(g.method==="GET"&&m==="/api/tests"){Ar(g,f,e);return}if(g.method==="GET"&&m==="/api/files"){Mr(g,f,e);return}let u=m.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(g.method==="GET"&&u){Ir(g,f,e,u[1],u[2]);return}let h=m.match(/^\/api\/tests\/([a-f0-9]+)$/);if(g.method==="GET"&&h){_r(g,f,e,h[1]);return}if(g.method==="GET"&&m==="/api/artifacts"){Er(g,f,d);return}if(g.method==="DELETE"&&m==="/api/artifacts"){Pr(g,f,d);return}let b=m.match(/^\/api\/artifacts\/(.+)$/);if(g.method==="DELETE"&&b){Lr(g,f,d,decodeURIComponent(b[1]));return}if(g.method==="GET"&&m.startsWith("/artifacts/")){let y=decodeURIComponent(m.slice(11));if(y.includes("..")||y.includes("\0")){k(f,400,{error:"Invalid path"});return}pt(g,f,path.join(d,y));return}if(g.method==="POST"&&m==="/api/shutdown"){Dr(g,f,p);return}k(f,404,{error:"Not found"});});function v(g){let f=m=>{m.code==="EADDRINUSE"&&i<$n?(i++,v(g+1)):a(m);};p.once("error",f),p.listen(g,"127.0.0.1",()=>{p.removeListener("error",f);let m=p.address();if(!m||typeof m=="string"){a(new Error("Failed to get server address"));return}l(),r({port:m.port,dispose:()=>new Promise(u=>{clearTimeout(o),p.close(()=>u());})});});}v(n);})}async function Nr(e){let t=await oe(e);return {port:t.port,dispose:t.dispose}}function Kn(e,t,r){let a=JSON.stringify(e),n=r?JSON.stringify(r):null;return vr(a,t,n)}async function gt(e,t,r){try{let a=null,n=null,s=t.reportMode==="streaming"||t.reportMode==="auto"&&e.timeline.length===0&&e.summary.total>=t.streamingThreshold,o,i=t.htmlReportPath,d=path.dirname(i);fs$1.mkdirSync(d,{recursive:!0});let l="",c="[]",p=null;if(s){l=JSON.stringify({...e.summary,testRunId:e.testRunId,startedAt:e.startedAt,completedAt:e.completedAt,totalDuration:e.totalDuration,ci:e.ci,metadata:e.metadata,shardRunIds:e.shardRunIds});let g=path.dirname(t.outputPath),f=path.join(g,".testrelic-report");try{let m=path.join(f,"index-compact.json"),u=path.join(f,"index.json");fs$1.existsSync(m)?c=fs$1.readFileSync(m,"utf-8"):fs$1.existsSync(u)&&(c=fs$1.readFileSync(u,"utf-8"));}catch{}p=r?JSON.stringify(r):null,o=ot(l,c,null,p);}else o=Kn(e,null,r);let v=i+".tmp";if(fs$1.writeFileSync(v,o,"utf-8"),fs$1.renameSync(v,i),s){if(e.ci===null){let g=path.dirname(t.outputPath),f=path.join(g,".testrelic-report"),m=path.resolve(i);try{if(await Yn(),a=await Xn(f),!a){n=await oe(f,{htmlPath:m}),a=n.port;let u=setInterval(()=>{},6e4),h=()=>{clearInterval(u),n?.dispose();};process.on("SIGINT",h),process.on("SIGTERM",h),setTimeout(h,1800*1e3).unref();}if(a){process.stderr.write(`
4251
4251
  Report server: http://127.0.0.1:${a}
4252
- `);try{let u=ot(o,c,a,p),h=i+".tmp";fs$1.writeFileSync(h,u,"utf-8"),fs$1.renameSync(h,i);}catch{}}}catch{}}}else if(t.openReport&&e.ci===null&&t.includeArtifacts){let g=path.dirname(t.outputPath),f=path.join(g,"artifacts");if(fs$1.existsSync(f))try{let m=await Nr(f);a=m.port,process.on("exit",()=>{m.dispose();});}catch{}}if(t.openReport&&e.ci===null)if(s&&a)lt(`http://127.0.0.1:${a}`);else {let g=path.resolve(i);lt(g);}}catch(a){process.stderr.write(`[testrelic] Failed to write HTML report: ${a instanceof Error?a.message:String(a)}
4253
- `);}}var ye=9323,zr=10;async function Jn(){for(let e=ye;e<ye+zr;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),500),a=await fetch(`http://127.0.0.1:${e}/api/health`,{signal:t.signal});if(clearTimeout(r),a.ok)return e}catch{}return null}async function Yn(){for(let e=ye;e<ye+zr;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),1e3);await fetch(`http://127.0.0.1:${e}/api/shutdown`,{method:"POST",signal:t.signal}),clearTimeout(r);}catch{}await new Promise(e=>setTimeout(e,300));}async function Xn(e){let r=[path.join(__dirname,"cli.cjs"),path.join(__dirname,"cli.js"),path.join(__dirname,"..","dist","cli.cjs"),path.join(__dirname,"..","dist","cli.js")].find(a=>fs$1.existsSync(a));if(!r){let a=await oe(e);return process.on("exit",()=>{a?.dispose();}),a.port}return new Promise(a=>{let n=child_process.spawn(process.execPath,[r,"serve",e],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),s="",l=false,i=setTimeout(()=>{l||(l=true,n.stderr?.removeAllListeners(),Jn().then(a));},5e3);n.stderr?.on("data",d=>{s+=d.toString();let o=s.match(/127\.0\.0\.1:(\d+)/);o&&!l&&(l=true,clearTimeout(i),n.stderr?.removeAllListeners(),n.unref(),a(Number(o[1])));}),n.on("error",()=>{l||(l=true,clearTimeout(i),a(null));}),n.on("exit",()=>{l||(l=true,clearTimeout(i),a(null));}),n.unref();})}var Hr=Buffer.from([137,80,78,71,13,10,26,10]),Zn=16,Qn=20,xe=24;function qr(e){if(e.length<xe||!e.subarray(0,Hr.length).equals(Hr))return null;let t=e.readUInt32BE(Zn),r=e.readUInt32BE(Qn);return t===0||r===0?null:{width:t,height:r}}var es=/(\d+) pixels \(ratio [\d.]+ of all image pixels\) are different/,$r=/Expected an image (\d+)px by (\d+)px, received (\d+)px by (\d+)px/;function Vr(e){return e?$r.test(e):false}var ts=/^\s*Snapshot:\s*(.+?)\s*$/m;function jr(e){if(!e)return {};let t={},r=es.exec(e);if(r){let s=Number.parseInt(r[1],10);Number.isFinite(s)&&(t.diffPixels=s);}let a=$r.exec(e);if(a){let[,s,l,i,d]=a,o=[s,l,i,d].map(c=>Number.parseInt(c,10));o.every(c=>Number.isFinite(c))&&(t.expectedWidth=o[0],t.expectedHeight=o[1],t.actualWidth=o[2],t.actualHeight=o[3]);}let n=ts.exec(e);return n&&(t.snapshotName=n[1]),t}function Gr(e,t){if(e===void 0||!t)return;let r=t.width*t.height;if(!(r<=0))return e/r}var os=20,ht=0,mt=[];async function le(e,t){ht>=os&&await new Promise(r=>mt.push(r)),ht++;try{return await promises.copyFile(e,t),!0}catch{return false}finally{ht--,mt.length>0&&mt.shift()();}}var H=[];async function Kr(){H.length!==0&&(await Promise.allSettled(H),H.length=0);}function Jr(e){let t=new Date,r=s=>String(s).padStart(2,"0"),a=`${t.getFullYear()}-${r(t.getMonth()+1)}-${r(t.getDate())}T${r(t.getHours())}-${r(t.getMinutes())}-${r(t.getSeconds())}`;if(!fs$1.existsSync(path.join(e,a)))return a;let n=1;for(;fs$1.existsSync(path.join(e,`${a}-${n}`));)n++;return `${a}-${n}`}function vt(e){let t=e.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return t.length>100&&(t=t.substring(0,100).replace(/-+$/,"")),t||"unnamed-test"}var ls=8;function Yr(e,t,r){let a=vt(e),n=r?vt(r).substring(0,ls):"";return n&&(a+=`--${n}`),t>0&&(a+=`--retry-${t}`),a}function Xr(e,t,r,a,n,s){let l=e.find(f=>f.name==="screenshot"&&f.path),i=e.find(f=>f.name==="video"&&f.path),d=e.find(f=>f.name==="trace"&&f.path);if(!l&&!i&&!d)return null;let o=Yr(t,r,s),c=n?["artifacts",n,o]:["artifacts",o],p=path.join(a,...c),v=c,g={};try{fs$1.mkdirSync(p,{recursive:!0});}catch{return null}if(l?.path&&fs$1.existsSync(l.path)){let m=`screenshot${path.extname(l.path)||".png"}`,u=path.join(p,m);H.push(le(l.path,u).then(()=>{})),g.screenshot=`${v.join("/")}/${m}`;}if(i?.path&&fs$1.existsSync(i.path)){let m=`video${path.extname(i.path)||".webm"}`,u=path.join(p,m);H.push(le(i.path,u).then(()=>{})),g.video=`${v.join("/")}/${m}`;}if(d?.path&&fs$1.existsSync(d.path)){let m=`trace${path.extname(d.path)||".zip"}`,u=path.join(p,m);H.push(le(d.path,u).then(()=>{})),g.trace=`${v.join("/")}/${m}`;}return !g.screenshot&&!g.video&&!g.trace?null:g}var bt="visual",ds=6;function cs(e){let t=crypto.createHash("sha256").update(e).digest("hex").substring(0,ds);return `${vt(e)}--${t}`}function Wr(e){let t=null;try{t=fs$1.openSync(e,"r");let r=Buffer.alloc(xe),a=fs$1.readSync(t,r,0,xe,0);return qr(r.subarray(0,a))}catch{return null}finally{if(t!==null)try{fs$1.closeSync(t);}catch{}}}var us=[{key:"expectedPath",dest:"baseline",field:"baseline"},{key:"actualPath",dest:"actual",field:"actual"},{key:"diffPath",dest:"diff",field:"diff"},{key:"previousPath",dest:"previous",field:"previous"}],ps=[{key:"baselineDomPath",dest:"baseline.dom.json",field:"baselineDom"},{key:"actualDomPath",dest:"actual.dom.json",field:"actualDom"}];function fs(e,t,r){let a=cs(e.name),n=path.join(t,a);try{fs$1.mkdirSync(n,{recursive:!0});}catch{return null}let s={},l=false;for(let c of us){let p=e[c.key];if(!p||!fs$1.existsSync(p))continue;let v=path.extname(p)||".png",g=`${c.dest}${v}`;H.push(le(p,path.join(n,g)).then(()=>{})),s[c.field]=`${r}/${bt}/${a}/${g}`,l=true;}let i=e.dom;if(i)for(let c of ps){let p=i[c.key];!p||!fs$1.existsSync(p)||(H.push(le(p,path.join(n,c.dest)).then(()=>{})),s[c.field]=`${r}/${bt}/${a}/${c.dest}`);}if(!l)return null;let d=e.expectedPath?Wr(e.expectedPath):e.actualPath?Wr(e.actualPath):null,o=Gr(e.diffPixels,d);return {name:e.name,status:e.status,source:e.source,...s,...d?{width:d.width,height:d.height}:{},...e.actualWidth!==void 0?{actualWidth:e.actualWidth}:{},...e.actualHeight!==void 0?{actualHeight:e.actualHeight}:{},...e.diffPixels!==void 0?{diffPixels:e.diffPixels}:{},...o!==void 0?{diffPixelRatio:o}:{},...i?{domChanges:i.changes,domChangeCount:i.total,domRootCauses:i.rootCauses,domTruncated:i.truncated,domCaptureBox:i.captureBox}:{}}}function Zr(e,t,r,a,n,s){if(e.length===0)return null;let l=Yr(t,r,s),i=n?["artifacts",n,l]:["artifacts",l],d=path.join(a,...i,bt),o=i.join("/");try{fs$1.mkdirSync(d,{recursive:!0});}catch{return null}let c=[];for(let p of e){let v=fs(p,d,o);v&&c.push(v);}return c.length>0?c:null}var Qr="testrelic-visual-dom";var gs="testrelic-visual",hs=/^(.+)-(expected|actual|diff|previous)(\.[A-Za-z0-9]+)$/;function ms(e){let t=new Map;for(let r of e)if(!(r.name!==gs||!r.body))try{let a=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(a))continue;for(let n of a){let s=bs(n);s&&t.set(s.stem,s);}}catch{}return t}var vs=["passed","failed","new","updated"];function bs(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.stem!="string"||!t.stem||typeof t.name!="string"||!t.name||typeof t.status!="string"||!vs.includes(t.status)?null:{stem:t.stem,name:t.name,status:t.status}}function ys(e){let t=new Map;for(let r of e)if(!(r.name!==Qr||!r.body))try{let a=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(a))continue;for(let n of a){if(typeof n!="object"||n===null)continue;let s=n;typeof s.stem!="string"||!Array.isArray(s.changes)||t.set(s.stem,n);}}catch{}return t}function xs(e){let t=new Map;for(let r of e){if(!r.path)continue;let a=hs.exec(r.name);if(!a)continue;let[,n,s]=a,l=t.get(n)??{};l[s]=r.path,t.set(n,l);}return t}function ws(e){return !!(e.actual&&(e.expected||e.diff))}function ks(e,t,r){return e.diff||Vr(r)?"failed":t?"updated":"new"}function Ss(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;let r=t.replace(/\.[A-Za-z0-9]+$/,""),a=e.filter(n=>n===r||n.endsWith(`/${r}`));return a.length===1?a[0]:null}function ta(e,t={}){if(e.length===0)return [];let r=ms(e),a=ys(e),n=xs(e);if(n.size===0)return [];let s=t.updatingSnapshots===true,l=[];for(let[i,d]of n){let o=r.get(i);!o&&!ws(d)||l.push({name:o?.name??i,status:o?.status??ks(d,s,t.failureMessage),source:o?"toMatchVisualBaseline":"toHaveScreenshot",...d.expected?{expectedPath:d.expected}:{},...d.actual?{actualPath:d.actual}:{},...d.diff?{diffPath:d.diff}:{},...d.previous?{previousPath:d.previous}:{},...a.has(i)?{dom:a.get(i)}:{}});}return Cs(l,n,t.failureMessage)}function Cs(e,t,r){let a=jr(r);if(a.diffPixels===void 0&&a.actualWidth===void 0)return [...e];let n=e.filter(l=>l.status==="failed").map(l=>ea(l,t)),s=Ss(n,a.snapshotName);return s===null?[...e]:e.map(l=>ea(l,t)===s?{...l,...a.diffPixels!==void 0?{diffPixels:a.diffPixels}:{},...a.actualWidth!==void 0?{actualWidth:a.actualWidth}:{},...a.actualHeight!==void 0?{actualHeight:a.actualHeight}:{}}:l)}function ea(e,t){if(t.has(e.name))return e.name;for(let[r,a]of t)if(a.actual===e.actualPath&&a.expected===e.expectedPath&&a.diff===e.diffPath)return r;return e.name}var Ts=new RegExp("[\x1B\x9B][[\\]()#;?]*(?:\\d{1,4}(?:;\\d{0,4})*)?[0-9A-PR-TZcf-nqry=><]","g");function ke(e){return !e||e.indexOf("\x1B")===-1&&e.indexOf("\x9B")===-1?e:e.replace(Ts,"")}function ra(e){return e==null?null:ke(e)}var Rs=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,As="1.0",xt="visual";function ia(e){let t=path.extname(e).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(t)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(t)?"video":t===".zip"&&path.basename(e,t)==="trace"?"trace":"other"}function _s(e){if(e.endsWith(".dom.json"))return "dom";let t=path.basename(e,path.extname(e));return t==="baseline"?"baseline":t==="diff"?"diff":ia(e)}function Is(e,t,r){let a=[];try{for(let n of fs$1.readdirSync(e,{withFileTypes:!0})){if(!n.isFile())continue;let s=fs$1.statSync(path.join(e,n.name));a.push({name:`${xt}/${r}/${n.name}`,type:_s(n.name),relativePath:`${t}/${xt}/${r}/${n.name}`,sizeBytes:s.size});}}catch{}return a}function oa(e,t,r){let a=[],n=`artifacts/${t}/${r}`;try{let s=fs$1.readdirSync(e,{withFileTypes:!0});for(let l of s){if(l.isDirectory()&&l.name===xt){let o=path.join(e,l.name);for(let c of fs$1.readdirSync(o,{withFileTypes:!0}))c.isDirectory()&&a.push(...Is(path.join(o,c.name),n,c.name));continue}if(!l.isFile())continue;let i=path.join(e,l.name),d=fs$1.statSync(i);a.push({name:l.name,type:ia(l.name),relativePath:`${n}/${l.name}`,sizeBytes:d.size});}}catch{}return {testName:r,files:a}}function Ms(e,t){let r=path.join(e,t),a=[],n=0;try{let l=fs$1.readdirSync(r,{withFileTypes:!0});for(let i of l){if(!i.isDirectory())continue;let d=oa(path.join(r,i.name),t,i.name);a.push(d);for(let o of d.files)n+=o.sizeBytes;}}catch{}let s=t.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return a.sort((l,i)=>l.testName.localeCompare(i.testName)),{folderName:t,timestamp:s,totalSizeBytes:n,testCount:a.length,tests:a,isCurrentRun:false}}function la(e,t){let r=path.join(e,"artifacts"),a=[],n=[],s=0;try{let i=fs$1.readdirSync(r,{withFileTypes:!0});for(let d of i)if(d.isDirectory())if(Rs.test(d.name)){let o=Ms(r,d.name);a.push({...o,isCurrentRun:d.name===t});}else {let o=oa(path.join(r,d.name),d.name,d.name);n.push(o);for(let c of o.files)s+=c.sizeBytes;}}catch{}a.sort((i,d)=>d.timestamp.localeCompare(i.timestamp)),n.length>0&&(n.sort((i,d)=>i.testName.localeCompare(d.testName)),a.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}));let l=a.reduce((i,d)=>i+d.totalSizeBytes,0);return {schemaVersion:As,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:l,runs:a,serverPort:null}}var Fs=256;function Bs(e){let t=path.resolve(e);for(let r=0;r<Fs;r++){if(fs$1.existsSync(path.join(t,".git")))return t;let a=path.dirname(t);if(a===t)return null;t=a;}return null}function ua(e){try{let t=Bs(e);if(!t)return;let r=path.join(t,".gitignore"),a=path.relative(t,e).replace(/\\/g,"/"),n=a.endsWith("/")?a:`${a}/`;if(fs$1.existsSync(r)&&fs$1.readFileSync(r,"utf-8").split(`
4252
+ `);try{let u=ot(l,c,a,p),h=i+".tmp";fs$1.writeFileSync(h,u,"utf-8"),fs$1.renameSync(h,i);}catch{}}}catch{}}}else if(t.openReport&&e.ci===null&&t.includeArtifacts){let g=path.dirname(t.outputPath),f=path.join(g,"artifacts");if(fs$1.existsSync(f))try{let m=await Nr(f);a=m.port,process.on("exit",()=>{m.dispose();});}catch{}}if(t.openReport&&e.ci===null)if(s&&a)lt(`http://127.0.0.1:${a}`);else {let g=path.resolve(i);lt(g);}}catch(a){process.stderr.write(`[testrelic] Failed to write HTML report: ${a instanceof Error?a.message:String(a)}
4253
+ `);}}var ye=9323,zr=10;async function Jn(){for(let e=ye;e<ye+zr;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),500),a=await fetch(`http://127.0.0.1:${e}/api/health`,{signal:t.signal});if(clearTimeout(r),a.ok)return e}catch{}return null}async function Yn(){for(let e=ye;e<ye+zr;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),1e3);await fetch(`http://127.0.0.1:${e}/api/shutdown`,{method:"POST",signal:t.signal}),clearTimeout(r);}catch{}await new Promise(e=>setTimeout(e,300));}async function Xn(e){let r=[path.join(__dirname,"cli.cjs"),path.join(__dirname,"cli.js"),path.join(__dirname,"..","dist","cli.cjs"),path.join(__dirname,"..","dist","cli.js")].find(a=>fs$1.existsSync(a));if(!r){let a=await oe(e);return process.on("exit",()=>{a?.dispose();}),a.port}return new Promise(a=>{let n=child_process.spawn(process.execPath,[r,"serve",e],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),s="",o=false,i=setTimeout(()=>{o||(o=true,n.stderr?.removeAllListeners(),Jn().then(a));},5e3);n.stderr?.on("data",d=>{s+=d.toString();let l=s.match(/127\.0\.0\.1:(\d+)/);l&&!o&&(o=true,clearTimeout(i),n.stderr?.removeAllListeners(),n.unref(),a(Number(l[1])));}),n.on("error",()=>{o||(o=true,clearTimeout(i),a(null));}),n.on("exit",()=>{o||(o=true,clearTimeout(i),a(null));}),n.unref();})}var Hr=Buffer.from([137,80,78,71,13,10,26,10]),Zn=16,Qn=20,xe=24;function qr(e){if(e.length<xe||!e.subarray(0,Hr.length).equals(Hr))return null;let t=e.readUInt32BE(Zn),r=e.readUInt32BE(Qn);return t===0||r===0?null:{width:t,height:r}}var es=/(\d+) pixels \(ratio [\d.]+ of all image pixels\) are different/,Vr=/Expected an image (\d+)px by (\d+)px, received (\d+)px by (\d+)px/;function $r(e){return e?Vr.test(e):false}var ts=/^\s*Snapshot:\s*(.+?)\s*$/m;function jr(e){if(!e)return {};let t={},r=es.exec(e);if(r){let s=Number.parseInt(r[1],10);Number.isFinite(s)&&(t.diffPixels=s);}let a=Vr.exec(e);if(a){let[,s,o,i,d]=a,l=[s,o,i,d].map(c=>Number.parseInt(c,10));l.every(c=>Number.isFinite(c))&&(t.expectedWidth=l[0],t.expectedHeight=l[1],t.actualWidth=l[2],t.actualHeight=l[3]);}let n=ts.exec(e);return n&&(t.snapshotName=n[1]),t}function Gr(e,t){if(e===void 0||!t)return;let r=t.width*t.height;if(!(r<=0))return e/r}var os=20,ht=0,mt=[];async function le(e,t){ht>=os&&await new Promise(r=>mt.push(r)),ht++;try{return await promises.copyFile(e,t),!0}catch{return false}finally{ht--,mt.length>0&&mt.shift()();}}var H=[];async function Kr(){H.length!==0&&(await Promise.allSettled(H),H.length=0);}function Jr(e){let t=new Date,r=s=>String(s).padStart(2,"0"),a=`${t.getFullYear()}-${r(t.getMonth()+1)}-${r(t.getDate())}T${r(t.getHours())}-${r(t.getMinutes())}-${r(t.getSeconds())}`;if(!fs$1.existsSync(path.join(e,a)))return a;let n=1;for(;fs$1.existsSync(path.join(e,`${a}-${n}`));)n++;return `${a}-${n}`}function vt(e){let t=e.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return t.length>100&&(t=t.substring(0,100).replace(/-+$/,"")),t||"unnamed-test"}var ls=8;function Yr(e,t,r){let a=vt(e),n=r?vt(r).substring(0,ls):"";return n&&(a+=`--${n}`),t>0&&(a+=`--retry-${t}`),a}function Xr(e,t,r,a,n,s){let o=e.find(f=>f.name==="screenshot"&&f.path),i=e.find(f=>f.name==="video"&&f.path),d=e.find(f=>f.name==="trace"&&f.path);if(!o&&!i&&!d)return null;let l=Yr(t,r,s),c=n?["artifacts",n,l]:["artifacts",l],p=path.join(a,...c),v=c,g={};try{fs$1.mkdirSync(p,{recursive:!0});}catch{return null}if(o?.path&&fs$1.existsSync(o.path)){let m=`screenshot${path.extname(o.path)||".png"}`,u=path.join(p,m);H.push(le(o.path,u).then(()=>{})),g.screenshot=`${v.join("/")}/${m}`;}if(i?.path&&fs$1.existsSync(i.path)){let m=`video${path.extname(i.path)||".webm"}`,u=path.join(p,m);H.push(le(i.path,u).then(()=>{})),g.video=`${v.join("/")}/${m}`;}if(d?.path&&fs$1.existsSync(d.path)){let m=`trace${path.extname(d.path)||".zip"}`,u=path.join(p,m);H.push(le(d.path,u).then(()=>{})),g.trace=`${v.join("/")}/${m}`;}return !g.screenshot&&!g.video&&!g.trace?null:g}var bt="visual",ds=6;function cs(e){let t=crypto.createHash("sha256").update(e).digest("hex").substring(0,ds);return `${vt(e)}--${t}`}function Wr(e){let t=null;try{t=fs$1.openSync(e,"r");let r=Buffer.alloc(xe),a=fs$1.readSync(t,r,0,xe,0);return qr(r.subarray(0,a))}catch{return null}finally{if(t!==null)try{fs$1.closeSync(t);}catch{}}}var us=[{key:"expectedPath",dest:"baseline",field:"baseline"},{key:"actualPath",dest:"actual",field:"actual"},{key:"diffPath",dest:"diff",field:"diff"},{key:"previousPath",dest:"previous",field:"previous"}],ps=[{key:"baselineDomPath",dest:"baseline.dom.json",field:"baselineDom"},{key:"actualDomPath",dest:"actual.dom.json",field:"actualDom"}];function fs(e,t,r){let a=cs(e.name),n=path.join(t,a);try{fs$1.mkdirSync(n,{recursive:!0});}catch{return null}let s={},o=false;for(let c of us){let p=e[c.key];if(!p||!fs$1.existsSync(p))continue;let v=path.extname(p)||".png",g=`${c.dest}${v}`;H.push(le(p,path.join(n,g)).then(()=>{})),s[c.field]=`${r}/${bt}/${a}/${g}`,o=true;}let i=e.dom;if(i)for(let c of ps){let p=i[c.key];!p||!fs$1.existsSync(p)||(H.push(le(p,path.join(n,c.dest)).then(()=>{})),s[c.field]=`${r}/${bt}/${a}/${c.dest}`);}if(!o)return null;let d=e.expectedPath?Wr(e.expectedPath):e.actualPath?Wr(e.actualPath):null,l=Gr(e.diffPixels,d);return {name:e.name,status:e.status,source:e.source,...s,...d?{width:d.width,height:d.height}:{},...e.actualWidth!==void 0?{actualWidth:e.actualWidth}:{},...e.actualHeight!==void 0?{actualHeight:e.actualHeight}:{},...e.diffPixels!==void 0?{diffPixels:e.diffPixels}:{},...l!==void 0?{diffPixelRatio:l}:{},...i?{domChanges:i.changes,domChangeCount:i.total,domRootCauses:i.rootCauses,domTruncated:i.truncated,domCaptureBox:i.captureBox}:{}}}function Zr(e,t,r,a,n,s){if(e.length===0)return null;let o=Yr(t,r,s),i=n?["artifacts",n,o]:["artifacts",o],d=path.join(a,...i,bt),l=i.join("/");try{fs$1.mkdirSync(d,{recursive:!0});}catch{return null}let c=[];for(let p of e){let v=fs(p,d,l);v&&c.push(v);}return c.length>0?c:null}var Qr="testrelic-visual-dom";var gs="testrelic-visual",hs=/^(.+)-(expected|actual|diff|previous)(\.[A-Za-z0-9]+)$/;function ms(e){let t=new Map;for(let r of e)if(!(r.name!==gs||!r.body))try{let a=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(a))continue;for(let n of a){let s=bs(n);s&&t.set(s.stem,s);}}catch{}return t}var vs=["passed","failed","new","updated"];function bs(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.stem!="string"||!t.stem||typeof t.name!="string"||!t.name||typeof t.status!="string"||!vs.includes(t.status)?null:{stem:t.stem,name:t.name,status:t.status}}function ys(e){let t=new Map;for(let r of e)if(!(r.name!==Qr||!r.body))try{let a=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(a))continue;for(let n of a){if(typeof n!="object"||n===null)continue;let s=n;typeof s.stem!="string"||!Array.isArray(s.changes)||t.set(s.stem,n);}}catch{}return t}function xs(e){let t=new Map;for(let r of e){if(!r.path)continue;let a=hs.exec(r.name);if(!a)continue;let[,n,s]=a,o=t.get(n)??{};o[s]=r.path,t.set(n,o);}return t}function ws(e){return !!(e.actual&&(e.expected||e.diff))}function ks(e,t,r){return e.diff||$r(r)?"failed":t?"updated":"new"}function Ss(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;let r=t.replace(/\.[A-Za-z0-9]+$/,""),a=e.filter(n=>n===r||n.endsWith(`/${r}`));return a.length===1?a[0]:null}function ta(e,t={}){if(e.length===0)return [];let r=ms(e),a=ys(e),n=xs(e);if(n.size===0)return [];let s=t.updatingSnapshots===true,o=[];for(let[i,d]of n){let l=r.get(i);!l&&!ws(d)||o.push({name:l?.name??i,status:l?.status??ks(d,s,t.failureMessage),source:l?"toMatchVisualBaseline":"toHaveScreenshot",...d.expected?{expectedPath:d.expected}:{},...d.actual?{actualPath:d.actual}:{},...d.diff?{diffPath:d.diff}:{},...d.previous?{previousPath:d.previous}:{},...a.has(i)?{dom:a.get(i)}:{}});}return Ts(Cs(o),n,t.failureMessage)}function Cs(e){let t=new Map;for(let a of e)a.source==="toMatchVisualBaseline"&&t.set(a.name,a);if(t.size===0)return [...e];let r=[];for(let a of e){if(a.source==="toMatchVisualBaseline"){r.push(a);continue}let n=t.get(a.name);if(!n){r.push(a);continue}let s={...n,...n.expectedPath===void 0&&a.expectedPath?{expectedPath:a.expectedPath}:{},...n.actualPath===void 0&&a.actualPath?{actualPath:a.actualPath}:{},...n.diffPath===void 0&&a.diffPath?{diffPath:a.diffPath}:{},...n.previousPath===void 0&&a.previousPath?{previousPath:a.previousPath}:{},...n.dom===void 0&&a.dom?{dom:a.dom}:{}},o=r.indexOf(n);o>=0&&(r[o]=s),t.set(a.name,s);}return r}function Ts(e,t,r){let a=jr(r);if(a.diffPixels===void 0&&a.actualWidth===void 0)return [...e];let n=e.filter(o=>o.status==="failed").map(o=>ea(o,t)),s=Ss(n,a.snapshotName);return s===null?[...e]:e.map(o=>ea(o,t)===s?{...o,...a.diffPixels!==void 0?{diffPixels:a.diffPixels}:{},...a.actualWidth!==void 0?{actualWidth:a.actualWidth}:{},...a.actualHeight!==void 0?{actualHeight:a.actualHeight}:{}}:o)}function ea(e,t){if(t.has(e.name))return e.name;for(let[r,a]of t)if(a.actual===e.actualPath&&a.expected===e.expectedPath&&a.diff===e.diffPath)return r;return e.name}var Rs=new RegExp("[\x1B\x9B][[\\]()#;?]*(?:\\d{1,4}(?:;\\d{0,4})*)?[0-9A-PR-TZcf-nqry=><]","g");function ke(e){return !e||e.indexOf("\x1B")===-1&&e.indexOf("\x9B")===-1?e:e.replace(Rs,"")}function ra(e){return e==null?null:ke(e)}var As=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,_s="1.0",xt="visual";function ia(e){let t=path.extname(e).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(t)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(t)?"video":t===".zip"&&path.basename(e,t)==="trace"?"trace":"other"}function Is(e){if(e.endsWith(".dom.json"))return "dom";let t=path.basename(e,path.extname(e));return t==="baseline"?"baseline":t==="diff"?"diff":ia(e)}function Ms(e,t,r){let a=[];try{for(let n of fs$1.readdirSync(e,{withFileTypes:!0})){if(!n.isFile())continue;let s=fs$1.statSync(path.join(e,n.name));a.push({name:`${xt}/${r}/${n.name}`,type:Is(n.name),relativePath:`${t}/${xt}/${r}/${n.name}`,sizeBytes:s.size});}}catch{}return a}function oa(e,t,r){let a=[],n=`artifacts/${t}/${r}`;try{let s=fs$1.readdirSync(e,{withFileTypes:!0});for(let o of s){if(o.isDirectory()&&o.name===xt){let l=path.join(e,o.name);for(let c of fs$1.readdirSync(l,{withFileTypes:!0}))c.isDirectory()&&a.push(...Ms(path.join(l,c.name),n,c.name));continue}if(!o.isFile())continue;let i=path.join(e,o.name),d=fs$1.statSync(i);a.push({name:o.name,type:ia(o.name),relativePath:`${n}/${o.name}`,sizeBytes:d.size});}}catch{}return {testName:r,files:a}}function Es(e,t){let r=path.join(e,t),a=[],n=0;try{let o=fs$1.readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let d=oa(path.join(r,i.name),t,i.name);a.push(d);for(let l of d.files)n+=l.sizeBytes;}}catch{}let s=t.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return a.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:t,timestamp:s,totalSizeBytes:n,testCount:a.length,tests:a,isCurrentRun:false}}function la(e,t){let r=path.join(e,"artifacts"),a=[],n=[],s=0;try{let i=fs$1.readdirSync(r,{withFileTypes:!0});for(let d of i)if(d.isDirectory())if(As.test(d.name)){let l=Es(r,d.name);a.push({...l,isCurrentRun:d.name===t});}else {let l=oa(path.join(r,d.name),d.name,d.name);n.push(l);for(let c of l.files)s+=c.sizeBytes;}}catch{}a.sort((i,d)=>d.timestamp.localeCompare(i.timestamp)),n.length>0&&(n.sort((i,d)=>i.testName.localeCompare(d.testName)),a.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}));let o=a.reduce((i,d)=>i+d.totalSizeBytes,0);return {schemaVersion:_s,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:a,serverPort:null}}var Bs=256;function Os(e){let t=path.resolve(e);for(let r=0;r<Bs;r++){if(fs$1.existsSync(path.join(t,".git")))return t;let a=path.dirname(t);if(a===t)return null;t=a;}return null}function ua(e){try{let t=Os(e);if(!t)return;let r=path.join(t,".gitignore"),a=path.relative(t,e).replace(/\\/g,"/"),n=a.endsWith("/")?a:`${a}/`;if(fs$1.existsSync(r)&&fs$1.readFileSync(r,"utf-8").split(`
4254
4254
  `).map(d=>d.trim()).some(d=>d===n||d===a))return;let s=`
4255
4255
  # TestRelic test artifacts
4256
4256
  ${n}
4257
4257
  `;fs$1.appendFileSync(r,s,"utf-8");}catch{}}var pa=Symbol("testrelic.timeout"),fa=3e4,wt=12e4,kt=6e4,ga=15e3;async function J(e,t,r){let a,n=new Promise(s=>{a=setTimeout(()=>s(pa),t),typeof a?.unref=="function"&&a.unref();});try{let s=await Promise.race([e(),n]);if(s===pa){process.stderr.write(`[testrelic] ${r} timed out after ${Math.round(t/1e3)}s \u2014 continuing without it. Your tests are unaffected.
4258
4258
  `);return}return s}catch(s){process.stderr.write(`[testrelic] ${r} failed \u2014 continuing without it. Your tests are unaffected. (${s instanceof Error?s.message:String(s)})
4259
- `);return}finally{a&&clearTimeout(a);}}function va(e,t){let r=[];for(let a of e){let n=Os(a),s=Us(a),l=zs(a,n,s,t),i=Hs(a,n,s);if(l.length===0&&i.length===0){r.push({type:"navigation",url:"about:blank",timestamp:a.startedAt,durationOnUrl:a.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:a.specFile,test:n,tests:[s],_testTitle:a.title});continue}r.push(...l,...i);}return r.sort(qs),$s(r,e),r.map((a,n)=>a.type==="navigation"?{...{index:n,type:"navigation",url:a.url,timestamp:a.timestamp,durationOnUrl:a.durationOnUrl??0,navigationType:a.navigationType,domContentLoadedAt:a.domContentLoadedAt??null,networkIdleAt:a.networkIdleAt??null,networkStats:a.networkStats??null,specFile:a.specFile,test:a.test},tests:a.tests}:{...{index:n,type:"api_call",callId:a.callId,method:a.method,url:a.url,timestamp:a.timestamp,responseTime:a.responseTime??null,request:a.request,response:a.response??null,...a.error?{error:a.error}:{},assertions:a.assertions??[],specFile:a.specFile,test:a.test},tests:a.tests})}function Os(e){return {title:e.title,fullTitle:e.titlePath,status:e.status,duration:e.duration,retries:e.retryCount,retry:e.retry,tags:e.tags,failure:e.failure}}function Us(e){return {title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,retryStatus:e.retryStatus,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,networkRequests:e.networkRequests,apiCalls:e.apiCalls,apiAssertions:e.apiAssertions,actions:e.actions,consoleLogs:e.consoleLogs}}function zs(e,t,r,a){let n=[];for(let s of e.navigations)a.navigationTypes!==null&&!a.navigationTypes.includes(s.navigationType)||n.push({type:"navigation",url:s.url,timestamp:s.timestamp,durationOnUrl:0,navigationType:s.navigationType,domContentLoadedAt:s.domContentLoadedAt??null,networkIdleAt:s.networkIdleAt??null,networkStats:s.networkStats??null,specFile:e.specFile,test:t,tests:[r],_testTitle:e.title});return n}function Hs(e,t,r){if(!e.apiCalls||e.apiCalls.length===0)return [];let a=e.apiAssertions??[];return e.apiCalls.map(n=>{let s=a.filter(i=>i.callId===n.id).map(i=>({type:i.type,expected:i.expected,actual:i.actual,status:i.status,location:i.location,...i.expression!==void 0?{expression:i.expression}:{}})),l=null;return n.responseStatusCode!==null&&n.responseStatusText!==null&&(l={statusCode:n.responseStatusCode,statusText:n.responseStatusText,headers:n.responseHeaders,body:ma(n.responseBody)}),{type:"api_call",callId:n.id,method:n.method,url:n.url,timestamp:n.timestamp,responseTime:n.error?null:n.responseTimeMs,request:{headers:n.requestHeaders,body:ma(n.requestBody)},response:l,...n.error?{error:n.error}:{},assertions:s,specFile:e.specFile,test:t,tests:[r],_testTitle:e.title}})}function qs(e,t){let r=new Date(e.timestamp).getTime(),a=new Date(t.timestamp).getTime();if(r!==a)return r-a;let n={navigation:0,api_call:1},s=n[e.type],l=n[t.type];return s!==l?s-l:e.type==="api_call"&&t.type==="api_call"&&e.callId&&t.callId?ha(e.callId)-ha(t.callId):0}function ha(e){let t=e.match(/(\d+)$/);return t?parseInt(t[1],10):0}function $s(e,t){for(let r=0;r<e.length;r++){let a=e[r];if(a.type!=="navigation")continue;let n=new Date(a.timestamp).getTime(),s=null;for(let l=r+1;l<e.length;l++)if(e[l]._testTitle===a._testTitle){s=new Date(e[l].timestamp).getTime();break}if(s!==null)a.durationOnUrl=Math.max(0,s-n);else {let l=t.find(i=>i.title===a._testTitle);if(l){let i=new Date(l.completedAt).getTime();a.durationOnUrl=Math.max(0,i-n);}}}}function ma(e){if(e==null)return null;try{return JSON.parse(e)}catch{return e}}function Y(e,t){let r=e.length,a=Math.min(Math.ceil(t/100*r)-1,r-1);return e[Math.max(0,a)]}function St(e){try{let t=new URL(e);return t.origin+t.pathname}catch{return e}}function Vs(e){return e==null?"error":e>=200&&e<300?"2xx":e>=300&&e<400?"3xx":e>=400&&e<500?"4xx":e>=500&&e<600?"5xx":"error"}function ba(e,t){let r=0,a=0,n=0,s=0,l=0;for(let x of e)switch(x.status){case "passed":r++;break;case "failed":a++;break;case "flaky":n++;break;case "skipped":s++;break;case "timedout":l++;break}let i=[];for(let x of e)x.apiCalls&&i.push(...x.apiCalls);let d=i.length,o=new Set,c={},p={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},v=[];for(let x of i)o.add(St(x.url)),c[x.method]=(c[x.method]??0)+1,p[Vs(x.responseStatusCode)]+=1,v.push(x.responseTimeMs);let g=null;if(v.length>0){let x=[...v].sort((X,G)=>X-G),S=x.reduce((X,G)=>X+G,0);g={avg:Math.round(S/x.length),min:x[0],max:x[x.length-1],p50:Y(x,50),p95:Y(x,95),p99:Y(x,99)};}let f=0,m=0,u=0;for(let x of e)if(x.apiAssertions)for(let S of x.apiAssertions)f++,S.status==="passed"?m++:u++;let h=0,b=new Set;for(let x of e){h+=x.navigations.length;for(let S of x.navigations)b.add(S.url);}let y=0,w={};function C(x){for(let S of x)y++,w[S.category]=(w[S.category]??0)+1,S.children.length>0&&C(S.children);}for(let x of e)x.actions&&C(x.actions);let P=0,A=0,R=0,L=0;for(let x of e)if(x.visual)for(let S of x.visual)P++,S.status==="failed"?A++:(S.status==="new"||S.status==="updated")&&R++,L+=S.domChangeCount??0;return {total:e.length,passed:r,failed:a,flaky:n,skipped:s,timedout:l,totalApiCalls:d,uniqueApiUrls:o.size,apiCallsByMethod:c,apiCallsByStatusRange:p,apiResponseTime:g,totalAssertions:f,passedAssertions:m,failedAssertions:u,totalNavigations:h,uniqueNavigationUrls:b.size,totalTimelineSteps:t,totalActionSteps:y,actionStepsByCategory:w,visualChecks:P,visualFailures:A,visualNew:R,visualDomChanges:L}}function js(e){let t=56-e.length;return t>0?e+" ".repeat(t):e}function E(e){return `\u2502 ${js(e)} \u2502
4259
+ `);return}finally{a&&clearTimeout(a);}}function va(e,t){let r=[];for(let a of e){let n=Us(a),s=zs(a),o=Hs(a,n,s,t),i=qs(a,n,s);if(o.length===0&&i.length===0){r.push({type:"navigation",url:"about:blank",timestamp:a.startedAt,durationOnUrl:a.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:a.specFile,test:n,tests:[s],_testTitle:a.title});continue}r.push(...o,...i);}return r.sort(Vs),$s(r,e),r.map((a,n)=>a.type==="navigation"?{...{index:n,type:"navigation",url:a.url,timestamp:a.timestamp,durationOnUrl:a.durationOnUrl??0,navigationType:a.navigationType,domContentLoadedAt:a.domContentLoadedAt??null,networkIdleAt:a.networkIdleAt??null,networkStats:a.networkStats??null,specFile:a.specFile,test:a.test},tests:a.tests}:{...{index:n,type:"api_call",callId:a.callId,method:a.method,url:a.url,timestamp:a.timestamp,responseTime:a.responseTime??null,request:a.request,response:a.response??null,...a.error?{error:a.error}:{},assertions:a.assertions??[],specFile:a.specFile,test:a.test},tests:a.tests})}function Us(e){return {title:e.title,fullTitle:e.titlePath,status:e.status,duration:e.duration,retries:e.retryCount,retry:e.retry,tags:e.tags,failure:e.failure}}function zs(e){return {title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,retryStatus:e.retryStatus,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,networkRequests:e.networkRequests,apiCalls:e.apiCalls,apiAssertions:e.apiAssertions,actions:e.actions,consoleLogs:e.consoleLogs}}function Hs(e,t,r,a){let n=[];for(let s of e.navigations)a.navigationTypes!==null&&!a.navigationTypes.includes(s.navigationType)||n.push({type:"navigation",url:s.url,timestamp:s.timestamp,durationOnUrl:0,navigationType:s.navigationType,domContentLoadedAt:s.domContentLoadedAt??null,networkIdleAt:s.networkIdleAt??null,networkStats:s.networkStats??null,specFile:e.specFile,test:t,tests:[r],_testTitle:e.title});return n}function qs(e,t,r){if(!e.apiCalls||e.apiCalls.length===0)return [];let a=e.apiAssertions??[];return e.apiCalls.map(n=>{let s=a.filter(i=>i.callId===n.id).map(i=>({type:i.type,expected:i.expected,actual:i.actual,status:i.status,location:i.location,...i.expression!==void 0?{expression:i.expression}:{}})),o=null;return n.responseStatusCode!==null&&n.responseStatusText!==null&&(o={statusCode:n.responseStatusCode,statusText:n.responseStatusText,headers:n.responseHeaders,body:ma(n.responseBody)}),{type:"api_call",callId:n.id,method:n.method,url:n.url,timestamp:n.timestamp,responseTime:n.error?null:n.responseTimeMs,request:{headers:n.requestHeaders,body:ma(n.requestBody)},response:o,...n.error?{error:n.error}:{},assertions:s,specFile:e.specFile,test:t,tests:[r],_testTitle:e.title}})}function Vs(e,t){let r=new Date(e.timestamp).getTime(),a=new Date(t.timestamp).getTime();if(r!==a)return r-a;let n={navigation:0,api_call:1},s=n[e.type],o=n[t.type];return s!==o?s-o:e.type==="api_call"&&t.type==="api_call"&&e.callId&&t.callId?ha(e.callId)-ha(t.callId):0}function ha(e){let t=e.match(/(\d+)$/);return t?parseInt(t[1],10):0}function $s(e,t){for(let r=0;r<e.length;r++){let a=e[r];if(a.type!=="navigation")continue;let n=new Date(a.timestamp).getTime(),s=null;for(let o=r+1;o<e.length;o++)if(e[o]._testTitle===a._testTitle){s=new Date(e[o].timestamp).getTime();break}if(s!==null)a.durationOnUrl=Math.max(0,s-n);else {let o=t.find(i=>i.title===a._testTitle);if(o){let i=new Date(o.completedAt).getTime();a.durationOnUrl=Math.max(0,i-n);}}}}function ma(e){if(e==null)return null;try{return JSON.parse(e)}catch{return e}}function Y(e,t){let r=e.length,a=Math.min(Math.ceil(t/100*r)-1,r-1);return e[Math.max(0,a)]}function St(e){try{let t=new URL(e);return t.origin+t.pathname}catch{return e}}function js(e){return e==null?"error":e>=200&&e<300?"2xx":e>=300&&e<400?"3xx":e>=400&&e<500?"4xx":e>=500&&e<600?"5xx":"error"}function ba(e,t){let r=0,a=0,n=0,s=0,o=0;for(let x of e)switch(x.status){case "passed":r++;break;case "failed":a++;break;case "flaky":n++;break;case "skipped":s++;break;case "timedout":o++;break}let i=[];for(let x of e)x.apiCalls&&i.push(...x.apiCalls);let d=i.length,l=new Set,c={},p={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},v=[];for(let x of i)l.add(St(x.url)),c[x.method]=(c[x.method]??0)+1,p[js(x.responseStatusCode)]+=1,v.push(x.responseTimeMs);let g=null;if(v.length>0){let x=[...v].sort((X,G)=>X-G),S=x.reduce((X,G)=>X+G,0);g={avg:Math.round(S/x.length),min:x[0],max:x[x.length-1],p50:Y(x,50),p95:Y(x,95),p99:Y(x,99)};}let f=0,m=0,u=0;for(let x of e)if(x.apiAssertions)for(let S of x.apiAssertions)f++,S.status==="passed"?m++:u++;let h=0,b=new Set;for(let x of e){h+=x.navigations.length;for(let S of x.navigations)b.add(S.url);}let y=0,w={};function C(x){for(let S of x)y++,w[S.category]=(w[S.category]??0)+1,S.children.length>0&&C(S.children);}for(let x of e)x.actions&&C(x.actions);let P=0,A=0,R=0,L=0;for(let x of e)if(x.visual)for(let S of x.visual)P++,S.status==="failed"?A++:(S.status==="new"||S.status==="updated")&&R++,L+=S.domChangeCount??0;return {total:e.length,passed:r,failed:a,flaky:n,skipped:s,timedout:o,totalApiCalls:d,uniqueApiUrls:l.size,apiCallsByMethod:c,apiCallsByStatusRange:p,apiResponseTime:g,totalAssertions:f,passedAssertions:m,failedAssertions:u,totalNavigations:h,uniqueNavigationUrls:b.size,totalTimelineSteps:t,totalActionSteps:y,actionStepsByCategory:w,visualChecks:P,visualFailures:A,visualNew:R,visualDomChanges:L}}function Gs(e){let t=56-e.length;return t>0?e+" ".repeat(t):e}function E(e){return `\u2502 ${Gs(e)} \u2502
4260
4260
  `}function Ct(e,t,r,a){if(a||e.total===0)return;let n=`\u250C${"\u2500".repeat(58)}\u2510
4261
4261
  `,s=`\u2514${"\u2500".repeat(58)}\u2518
4262
- `,l=E(""),i=n;i+=E("TestRelic AI - Playwright Test Report"),i+=l;let d=[];if(e.passed>0&&d.push(`${e.passed} \u2713`),e.failed>0&&d.push(`${e.failed} \u2717`),e.flaky>0&&d.push(`${e.flaky} \u26A0`),e.skipped>0&&d.push(`${e.skipped} skipped`),e.timedout>0&&d.push(`${e.timedout} timedout`),i+=E(`Tests: ${e.total} total (${d.join(" ")})`),e.totalNavigations>0&&(i+=E(`Navigations: ${e.totalNavigations} visits across ${e.uniqueNavigationUrls} unique URLs`)),e.totalApiCalls>0){i+=E(`API Calls: ${e.totalApiCalls} calls across ${e.uniqueApiUrls} unique endpoints`);let o=Object.entries(e.apiCallsByMethod).filter(([,p])=>p>0).map(([p,v])=>`${p}: ${v}`);o.length>0&&(i+=E(` ${o.join(" ")}`));let c=Object.entries(e.apiCallsByStatusRange).filter(([,p])=>p>0).map(([p,v])=>`${p}: ${v}`);c.length>0&&(i+=E(` ${c.join(" ")}`)),e.apiResponseTime&&(i+=E(` Avg response: ${e.apiResponseTime.avg}ms P95: ${e.apiResponseTime.p95}ms`));}if(e.totalAssertions>0&&(i+=E(`Assertions: ${e.totalAssertions} total (${e.passedAssertions} \u2713 ${e.failedAssertions} \u2717)`)),e.totalActionSteps>0){let o=[],c=e.actionStepsByCategory;c.ui_action&&o.push(`${c.ui_action} UI`),c.assertion&&o.push(`${c.assertion} assertions`),c.custom_step&&o.push(`${c.custom_step} custom`);let p=o.length>0?` (${o.join(" ")})`:"";i+=E(`Actions: ${e.totalActionSteps} steps${p}`);}i+=E(`Report: ${r}`),i+=E(`Data: ${t}`),i+=s,i+=`For more information visit us at https://docs.testrelic.ai
4263
- `,process.stderr.write(i);}var Gs=new Set(["pw:api","expect","test.step"]);function Ws(e){return e==="expect"?"assertion":e==="test.step"?"custom_step":"ui_action"}function Tt(e,t,r){if(Gs.has(e.category)){let a=[];for(let s of e.steps)Tt(s,t,a);let n=e.startTime.getTime()-t.getTime();r.push({title:e.title,category:Ws(e.category),timestamp:e.startTime.toISOString(),duration:e.duration,videoOffset:n>=0?n/1e3:null,status:e.error?"failed":"passed",error:ra(e.error?.message),children:a});}else for(let a of e.steps)Tt(a,t,r);}function ya(e,t){let r=[];for(let a of e)Tt(a,t,r);return r}var Ys=new Set(["localhost","127.0.0.1","0.0.0.0"]);function wa(e){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&Ys.has(t.hostname)))throw core.createError(core.ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${t.protocol}//${t.hostname}`)}var Xs=3e3;async function Rt(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Xs);try{return (await fetch(`${e}/health`,{method:"GET",signal:t.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function ka(e){return new Promise(t=>setTimeout(t,e))}async function xa(e){try{let r=(await e.json()).error;if(r&&typeof r.message=="string"){let a=r.details;if(Array.isArray(a)&&a.length>0){let n=a.map(s=>`${s.field}: ${s.message}`).join(", ");return `${r.message} (${n})`}return r.message}}catch{}return `HTTP ${e.status}`}async function At(e,t,r){let a=new AbortController,n=setTimeout(()=>a.abort(),r);try{let s=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:a.signal});if(s.ok){let i=await s.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,orgId:i.orgId,orgName:i.orgName,userId:i.userId,userName:i.userName}}if(s.status===429){let i=s.headers.get("Retry-After"),d=i?parseInt(i,10)*1e3:5e3;if(!isNaN(d)&&d>0){await ka(d);let o=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:a.signal});if(o.ok){let c=await o.json();return {accessToken:c.accessToken,refreshToken:c.refreshToken,expiresIn:c.expiresIn,orgId:c.orgId,orgName:c.orgName,userId:c.userId,userName:c.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return s.status===400?{code:"validation_error",message:await xa(s),statusCode:400}:s.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:s.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await xa(s),statusCode:s.status}}catch(s){return s instanceof DOMException&&s.name==="AbortError"?{code:"timeout",message:"Token exchange timed out.",statusCode:null}:{code:"network_error",message:"Failed to reach cloud for token exchange.",statusCode:null}}finally{clearTimeout(n);}}function _t(e){return "code"in e&&typeof e.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(e.code)}async function Sa(e,t,r){let a=new AbortController,n=setTimeout(()=>a.abort(),r);try{let s=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:a.signal});if(s.status===429){let i=s.headers.get("Retry-After"),d=i?parseInt(i,10)*1e3:5e3;!isNaN(d)&&d>0&&(await ka(d),s=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:a.signal}));}if(!s.ok)return null;let l=await s.json();return {accessToken:l.accessToken,refreshToken:l.refreshToken,expiresIn:l.expiresIn}}catch{return null}finally{clearTimeout(n);}}async function Ca(e,t,r,a,n,s){let l=new AbortController,i=setTimeout(()=>l.abort(),n);try{let d={gitId:r,displayName:a};s&&(d.branch=s);let o=await fetch(`${e}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(d),signal:l.signal});if(!o.ok)return null;let c=await o.json();return {repoId:c.repoId,displayName:c.displayName}}catch{return null}finally{clearTimeout(i);}}var ri=5e3;function $(e,t){try{return child_process.execSync(e,{cwd:t,timeout:ri,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function Ta(e){let t=$("git rev-parse --abbrev-ref HEAD",e),r=$("git rev-parse --short HEAD",e),a=$("git log -1 --pretty=%s",e),n=$("git log -1 --format=%an",e)??$("git config user.name",e),s=ai(e),l=s?ce(s):null;return {branch:t,commitSha:r,commitMessage:a,commitAuthor:n,remoteUrl:l}}function ai(e){let t=$("git remote get-url origin",e);if(t)return t;let r=$("git remote",e);if(!r)return null;let a=r.split(`
4264
- `)[0]?.trim();return a?$(`git remote get-url ${a}`,e):null}function ce(e){let t=e.trim();return t=t.replace(/^[a-z+]+:\/\//,""),t=t.replace(/^[^@]+@/,""),t=t.replace(/:(?!\d)/,"/"),t=t.replace(/\.git$/,""),t=t.replace(/\/+$/,""),t=t.replace(/^[^@/]+@/,""),t.toLowerCase()}function Ra(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function It(e){try{let t=fs$1.readFileSync(path.join(e,"package.json"),"utf-8"),r=JSON.parse(t);return typeof r.name=="string"&&r.name.length>0?r.name:null}catch{return null}}function ue(e){let t=It(e);return t||`local/${path.basename(e)}`}var ni=new Set(["smoke","regression","nightly","ci"]);function Se(){let e=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(e&&ni.has(e))return e}async function V(e,t,r){let a=new AbortController,n=setTimeout(()=>a.abort(),Math.max(1,r));try{return await fetch(e,{...t,signal:a.signal})}finally{clearTimeout(n);}}function Aa(e,t){let r=t+Math.ceil(Math.max(0,e)/1e3);return Math.min(6e5,Math.max(3e4,r))}var Ce=class{constructor(t=12e4,r=Date.now()){this.deadline=r+Math.max(0,t);}remaining(t=Date.now()){return Math.max(0,this.deadline-t)}expired(t=Date.now()){return this.remaining(t)===0}slice(t,r=Date.now()){return Math.min(t,this.remaining(r))}};var oi=1048576,Te=[1e3,3e3,9e3],Re=3,Ia=3e4,li=90*1048576,di=new Set(["e2e","mobile","unit"]);function Et(e){if(e&&e.length>0&&e.every(n=>n.testType==="api")){let n=new Map;for(let i of e){let d=i.apiProtocol??"rest";n.set(d,(n.get(d)??0)+1);}let s="rest",l=0;for(let[i,d]of n)d>l&&(l=d,s=i);return {testType:"api",apiProtocol:s,metadata:{testType:"api",primaryProtocol:s}}}let t=new Map;for(let n of e??[])di.has(n.testType)&&t.set(n.testType,(t.get(n.testType)??0)+1);let r=null,a=0;for(let[n,s]of t)s>a&&(a=s,r=n);return {testType:r??"e2e"}}function Pt(e,t,r,a,n,s){let l=s?.cloudPlatform?s.cloudPlatform:a?.provider&&a.provider!=="unknown"?a.provider:"local",i=Se(),d=Et(n),o=d.testType==="api"?d:null,c=o&&n?n.map(v=>v.apiProtocol?v:{...v,apiProtocol:o.apiProtocol}):n;return {runId:e.testRunId,repoGitId:t,startedAt:e.startedAt,summary:e.summary,timeline:e.timeline,environment:l,...i?{runType:i}:{},...o?{testType:o.testType,apiProtocol:o.apiProtocol,metadata:o.metadata}:{testType:d.testType},...c&&c.length>0?{tests:c}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...e.completedAt?{finishedAt:e.completedAt}:{},...e.totalDuration?{duration:e.totalDuration}:{},...a?.provider?{ciProvider:a.provider}:{},...a?.runUrl?{ciRunUrl:a.runUrl}:{},...s?.cloudPlatform?{cloudPlatform:s.cloudPlatform}:{},...s?.cloudBuildId?{cloudBuildId:s.cloudBuildId}:{},...s?.cloudSessionId?{cloudSessionId:s.cloudSessionId}:{}}}function Mt(e){return typeof e=="string"?Buffer.byteLength(e,"utf-8"):0}function Lt(e){return Array.isArray(e)?e.map(t=>{let r=t.statusCode??t.responseStatusCode??null;return {...t.id!=null?{id:t.id}:{},...t.protocol!=null?{protocol:t.protocol}:{},method:t.method??null,url:t.url??null,statusCode:r,statusText:t.statusText??t.responseStatusText??null,ok:typeof r=="number"?r<400:t.ok??null,durationMs:t.durationMs??t.responseTimeMs??null,bytesIn:typeof t.bytesIn=="number"?t.bytesIn:Mt(t.responseBody),bytesOut:typeof t.bytesOut=="number"?t.bytesOut:Mt(t.requestBody),requestHeaders:t.requestHeaders??null,responseHeaders:t.responseHeaders??null,requestBody:t.requestBody??null,responseBody:t.responseBody??null,requestCookies:t.requestCookies??null,responseCookies:t.responseCookies??null}}):[]}function Dt(e){return Array.isArray(e)?e.map(t=>{let r=t.responseStatusCode??t.statusCode??0,a=t.timestamp??null;return {method:t.method??"GET",url:t.url??"",status:r,statusCode:r,type:"xhr",size:Mt(t.responseBody),duration:t.responseTimeMs??t.durationMs??0,responseTimeMs:t.responseTimeMs??t.durationMs??0,requestHeaders:t.requestHeaders??null,responseHeaders:t.responseHeaders??null,requestBody:t.requestBody??null,responseBody:t.responseBody??null,timestamp:a,startedAt:a}}):[]}function Nt(e){if(!Array.isArray(e))return [];let t=r=>{if(r==null)return String(r);if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}};return e.map(r=>{let a=r.status==="failed"?"failed":"passed",n=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,s=r.kind??r.type??"assertion",l=a==="failed"?`expected ${t(r.expected)}, received ${t(r.actual)}`:r.expected!==void 0?`expected ${t(r.expected)}`:null;return {...r.callId!=null?{callId:r.callId}:{},kind:s,description:n??r.description??`${s} assertion`,status:a,detail:l}})}async function Ae(e){return new Promise(t=>setTimeout(t,e))}function ci(e){let t={};for(let[r,a]of Object.entries(e))a!=null&&(t[r]=a);return t}async function Ma(e,t,r,a=Ia,n){for(let s=0;s<Re;s++){if(n?.expired())return null;let l=n?n.slice(a):a;if(l<=0)return null;try{let i=await V(e,t,l);if(i.ok)return i;if(i.status===401&&r&&s===0){let d=await r();if(d){let o={...t,headers:{...t.headers,Authorization:`Bearer ${d}`}},c=await V(e,o,l);if(c.ok)return c}return null}if(i.status===429&&s<Re-1){let d=i.headers.get("Retry-After"),o=d?parseInt(d,10)*1e3:Te[s];!isNaN(o)&&o>0?await Ae(o):await Ae(Te[s]);continue}if(i.status>=500&&s<Re-1){await Ae(Te[s]);continue}return i}catch{if(s<Re-1){await Ae(Te[s]);continue}return null}}return null}var ui=util.promisify(zlib.gzip);function _a(e,t){if(!Array.isArray(e.tests))return e;let r=e.tests.map(a=>{let{consoleLogs:n,networkRequests:s,apiCalls:l,...i}=a;return t?i:{...i,...l!==void 0?{apiCalls:l}:{}}});return {...e,tests:r}}var pi=["consoleLogs","networkRequests","apiCalls","actions","navigations","protocolAssertions","visual"];function fi(e){if(!Array.isArray(e.tests))return e;let t=new Set(pi),r=e.tests.map(a=>{let n={};for(let s in a)if(!t.has(s))if(s==="failure"&&a[s]&&typeof a[s]=="object"){let l=a[s];n.failure={message:l.message??null,line:l.line??null};}else n[s]=a[s];return n});return {...e,tests:r}}function gi(e){let t=new Set(["tests","timeline","unifiedTimeline","navigations"]),r={};for(let a in e)t.has(a)||(r[a]=e[a]);return r.tests=[],r}async function Ft(e,t=li){let r={"Content-Type":"application/json"},a=JSON.stringify(e),n=e,s=Array.isArray(n?.tests)?n.tests.length:0,l=i=>Buffer.byteLength(i,"utf-8")>t;if(s>0&&l(a)){let i=Math.max(1,Math.round(t/1048576));process.stderr.write(`[testrelic] WARNING: batch payload exceeds ${i}MB \u2014 dropping consoleLogs/networkRequests from ${s} test(s) to avoid HTTP 413. Console/network detail will be missing in the cloud.
4265
- `),a=JSON.stringify(_a(n,false)),l(a)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${i}MB after dropping logs \u2014 also dropping apiCalls from ${s} test(s). API request/response detail will be missing in the cloud.
4266
- `),a=JSON.stringify(_a(n,true))),l(a)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${i}MB \u2014 shedding remaining per-test detail (actions/navigations/assertions) from ${s} test(s). Only test results + summary will reach the cloud.
4267
- `),a=JSON.stringify(fi(n))),l(a)&&(process.stderr.write(`[testrelic] ERROR: batch still exceeds ${i}MB after shedding all per-test detail \u2014 uploading run summary only (${s} per-test result(s) omitted) to avoid losing the run to HTTP 413.
4268
- `),a=JSON.stringify(gi(n)));}if(Buffer.byteLength(a,"utf-8")>oi){r["Content-Encoding"]="gzip";let i=await ui(Buffer.from(a,"utf-8")),d=i.buffer;return {body:new Uint8Array(d,i.byteOffset,i.byteLength),headers:r}}return {body:a,headers:r}}async function Ea(e,t,r,a,n,s){let l=`${e}/runs`,{body:i,headers:d}=await Ft(r);d.Authorization=`Bearer ${t}`;let o=await Ma(l,{method:"POST",headers:d,body:i},a,n,s);return o?.ok?{success:true,statusCode:o.status,error:null}:o?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:o?`Upload failed with status ${o.status}`:"Upload failed after retries",statusCode:o?.status??null,payload:r,targetEndpoint:l,method:"POST"}}async function Pa(e,t,r,a){let n=`${e}/runs/init`;try{let s=await V(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(ci(r))},a??Ia);return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function La(e,t,r,a){let n=`${e}/runs/${r}/tests`;fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a)}).catch(()=>{});}async function Da(e,t,r,a){let n=`${e}/runs/${r}/finalize`;return (await Ma(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a)}))?.ok??false}function Bt(e,t,r,a){let n=`${e}/runs/${r}/finalize`,s=new Date,l={finishedAt:s.toISOString(),duration:s.getTime()-new Date(a).getTime(),summary:{}};fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(l)}).catch(()=>{});}var yi="1.0.0",Na=10;function Fa(e){return e instanceof Error?e.message:String(e)}function xi(e){return e>=400&&e<500&&e!==408&&e!==429}function pe(e,t,r,a,n,s,l,i){try{fs$1.mkdirSync(e,{recursive:!0});let d=Date.now(),o=`${d}-${t}-${r}.json`,c=path.join(e,o),p={version:yi,queuedAt:new Date(d).toISOString(),reason:a,retryCount:0,targetEndpoint:n,method:s,payload:l,headers:i},v=c+".tmp";fs$1.writeFileSync(v,JSON.stringify(p,null,2),"utf-8"),fs$1.renameSync(v,c);}catch(d){d.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
4262
+ `,o=E(""),i=n;i+=E("TestRelic AI - Playwright Test Report"),i+=o;let d=[];if(e.passed>0&&d.push(`${e.passed} \u2713`),e.failed>0&&d.push(`${e.failed} \u2717`),e.flaky>0&&d.push(`${e.flaky} \u26A0`),e.skipped>0&&d.push(`${e.skipped} skipped`),e.timedout>0&&d.push(`${e.timedout} timedout`),i+=E(`Tests: ${e.total} total (${d.join(" ")})`),e.totalNavigations>0&&(i+=E(`Navigations: ${e.totalNavigations} visits across ${e.uniqueNavigationUrls} unique URLs`)),e.totalApiCalls>0){i+=E(`API Calls: ${e.totalApiCalls} calls across ${e.uniqueApiUrls} unique endpoints`);let l=Object.entries(e.apiCallsByMethod).filter(([,p])=>p>0).map(([p,v])=>`${p}: ${v}`);l.length>0&&(i+=E(` ${l.join(" ")}`));let c=Object.entries(e.apiCallsByStatusRange).filter(([,p])=>p>0).map(([p,v])=>`${p}: ${v}`);c.length>0&&(i+=E(` ${c.join(" ")}`)),e.apiResponseTime&&(i+=E(` Avg response: ${e.apiResponseTime.avg}ms P95: ${e.apiResponseTime.p95}ms`));}if(e.totalAssertions>0&&(i+=E(`Assertions: ${e.totalAssertions} total (${e.passedAssertions} \u2713 ${e.failedAssertions} \u2717)`)),e.totalActionSteps>0){let l=[],c=e.actionStepsByCategory;c.ui_action&&l.push(`${c.ui_action} UI`),c.assertion&&l.push(`${c.assertion} assertions`),c.custom_step&&l.push(`${c.custom_step} custom`);let p=l.length>0?` (${l.join(" ")})`:"";i+=E(`Actions: ${e.totalActionSteps} steps${p}`);}i+=E(`Report: ${r}`),i+=E(`Data: ${t}`),i+=s,i+=`For more information visit us at https://docs.testrelic.ai
4263
+ `,process.stderr.write(i);}var Ws=new Set(["pw:api","expect","test.step"]);function Ks(e){return e==="expect"?"assertion":e==="test.step"?"custom_step":"ui_action"}function Tt(e,t,r){if(Ws.has(e.category)){let a=[];for(let s of e.steps)Tt(s,t,a);let n=e.startTime.getTime()-t.getTime();r.push({title:e.title,category:Ks(e.category),timestamp:e.startTime.toISOString(),duration:e.duration,videoOffset:n>=0?n/1e3:null,status:e.error?"failed":"passed",error:ra(e.error?.message),children:a});}else for(let a of e.steps)Tt(a,t,r);}function ya(e,t){let r=[];for(let a of e)Tt(a,t,r);return r}var Xs=new Set(["localhost","127.0.0.1","0.0.0.0"]);function wa(e){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&Xs.has(t.hostname)))throw core.createError(core.ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${t.protocol}//${t.hostname}`)}var Zs=3e3;async function Rt(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Zs);try{return (await fetch(`${e}/health`,{method:"GET",signal:t.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function ka(e){return new Promise(t=>setTimeout(t,e))}async function xa(e){try{let r=(await e.json()).error;if(r&&typeof r.message=="string"){let a=r.details;if(Array.isArray(a)&&a.length>0){let n=a.map(s=>`${s.field}: ${s.message}`).join(", ");return `${r.message} (${n})`}return r.message}}catch{}return `HTTP ${e.status}`}async function At(e,t,r){let a=new AbortController,n=setTimeout(()=>a.abort(),r);try{let s=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:a.signal});if(s.ok){let i=await s.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,orgId:i.orgId,orgName:i.orgName,userId:i.userId,userName:i.userName}}if(s.status===429){let i=s.headers.get("Retry-After"),d=i?parseInt(i,10)*1e3:5e3;if(!isNaN(d)&&d>0){await ka(d);let l=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:a.signal});if(l.ok){let c=await l.json();return {accessToken:c.accessToken,refreshToken:c.refreshToken,expiresIn:c.expiresIn,orgId:c.orgId,orgName:c.orgName,userId:c.userId,userName:c.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return s.status===400?{code:"validation_error",message:await xa(s),statusCode:400}:s.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:s.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await xa(s),statusCode:s.status}}catch(s){return s instanceof DOMException&&s.name==="AbortError"?{code:"timeout",message:"Token exchange timed out.",statusCode:null}:{code:"network_error",message:"Failed to reach cloud for token exchange.",statusCode:null}}finally{clearTimeout(n);}}function _t(e){return "code"in e&&typeof e.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(e.code)}async function Sa(e,t,r){let a=new AbortController,n=setTimeout(()=>a.abort(),r);try{let s=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:a.signal});if(s.status===429){let i=s.headers.get("Retry-After"),d=i?parseInt(i,10)*1e3:5e3;!isNaN(d)&&d>0&&(await ka(d),s=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:a.signal}));}if(!s.ok)return null;let o=await s.json();return {accessToken:o.accessToken,refreshToken:o.refreshToken,expiresIn:o.expiresIn}}catch{return null}finally{clearTimeout(n);}}async function Ca(e,t,r,a,n,s){let o=new AbortController,i=setTimeout(()=>o.abort(),n);try{let d={gitId:r,displayName:a};s&&(d.branch=s);let l=await fetch(`${e}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(d),signal:o.signal});if(!l.ok)return null;let c=await l.json();return {repoId:c.repoId,displayName:c.displayName}}catch{return null}finally{clearTimeout(i);}}var ai=5e3;function V(e,t){try{return child_process.execSync(e,{cwd:t,timeout:ai,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function Ta(e){let t=V("git rev-parse --abbrev-ref HEAD",e),r=V("git rev-parse --short HEAD",e),a=V("git log -1 --pretty=%s",e),n=V("git log -1 --format=%an",e)??V("git config user.name",e),s=ni(e),o=s?ce(s):null;return {branch:t,commitSha:r,commitMessage:a,commitAuthor:n,remoteUrl:o}}function ni(e){let t=V("git remote get-url origin",e);if(t)return t;let r=V("git remote",e);if(!r)return null;let a=r.split(`
4264
+ `)[0]?.trim();return a?V(`git remote get-url ${a}`,e):null}function ce(e){let t=e.trim();return t=t.replace(/^[a-z+]+:\/\//,""),t=t.replace(/^[^@]+@/,""),t=t.replace(/:(?!\d)/,"/"),t=t.replace(/\.git$/,""),t=t.replace(/\/+$/,""),t=t.replace(/^[^@/]+@/,""),t.toLowerCase()}function Ra(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function It(e){try{let t=fs$1.readFileSync(path.join(e,"package.json"),"utf-8"),r=JSON.parse(t);return typeof r.name=="string"&&r.name.length>0?r.name:null}catch{return null}}function ue(e){let t=It(e);return t||`local/${path.basename(e)}`}var si=new Set(["smoke","regression","nightly","ci"]);function Se(){let e=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(e&&si.has(e))return e}async function $(e,t,r){let a=new AbortController,n=setTimeout(()=>a.abort(),Math.max(1,r));try{return await fetch(e,{...t,signal:a.signal})}finally{clearTimeout(n);}}function Aa(e,t){let r=t+Math.ceil(Math.max(0,e)/1e3);return Math.min(6e5,Math.max(3e4,r))}var Ce=class{constructor(t=12e4,r=Date.now()){this.deadline=r+Math.max(0,t);}remaining(t=Date.now()){return Math.max(0,this.deadline-t)}expired(t=Date.now()){return this.remaining(t)===0}slice(t,r=Date.now()){return Math.min(t,this.remaining(r))}};var li=1048576,Te=[1e3,3e3,9e3],Re=3,Ia=3e4,di=90*1048576,ci=new Set(["e2e","mobile","unit"]);function Et(e){if(e&&e.length>0&&e.every(n=>n.testType==="api")){let n=new Map;for(let i of e){let d=i.apiProtocol??"rest";n.set(d,(n.get(d)??0)+1);}let s="rest",o=0;for(let[i,d]of n)d>o&&(o=d,s=i);return {testType:"api",apiProtocol:s,metadata:{testType:"api",primaryProtocol:s}}}let t=new Map;for(let n of e??[])ci.has(n.testType)&&t.set(n.testType,(t.get(n.testType)??0)+1);let r=null,a=0;for(let[n,s]of t)s>a&&(a=s,r=n);return {testType:r??"e2e"}}function Pt(e,t,r,a,n,s){let o=s?.cloudPlatform?s.cloudPlatform:a?.provider&&a.provider!=="unknown"?a.provider:"local",i=Se(),d=Et(n),l=d.testType==="api"?d:null,c=l&&n?n.map(v=>v.apiProtocol?v:{...v,apiProtocol:l.apiProtocol}):n;return {runId:e.testRunId,repoGitId:t,startedAt:e.startedAt,summary:e.summary,timeline:e.timeline,environment:o,...i?{runType:i}:{},...l?{testType:l.testType,apiProtocol:l.apiProtocol,metadata:l.metadata}:{testType:d.testType},...c&&c.length>0?{tests:c}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...e.completedAt?{finishedAt:e.completedAt}:{},...e.totalDuration?{duration:e.totalDuration}:{},...a?.provider?{ciProvider:a.provider}:{},...a?.runUrl?{ciRunUrl:a.runUrl}:{},...s?.cloudPlatform?{cloudPlatform:s.cloudPlatform}:{},...s?.cloudBuildId?{cloudBuildId:s.cloudBuildId}:{},...s?.cloudSessionId?{cloudSessionId:s.cloudSessionId}:{}}}function Mt(e){return typeof e=="string"?Buffer.byteLength(e,"utf-8"):0}function Lt(e){return Array.isArray(e)?e.map(t=>{let r=t.statusCode??t.responseStatusCode??null;return {...t.id!=null?{id:t.id}:{},...t.protocol!=null?{protocol:t.protocol}:{},method:t.method??null,url:t.url??null,statusCode:r,statusText:t.statusText??t.responseStatusText??null,ok:typeof r=="number"?r<400:t.ok??null,durationMs:t.durationMs??t.responseTimeMs??null,bytesIn:typeof t.bytesIn=="number"?t.bytesIn:Mt(t.responseBody),bytesOut:typeof t.bytesOut=="number"?t.bytesOut:Mt(t.requestBody),requestHeaders:t.requestHeaders??null,responseHeaders:t.responseHeaders??null,requestBody:t.requestBody??null,responseBody:t.responseBody??null,requestCookies:t.requestCookies??null,responseCookies:t.responseCookies??null}}):[]}function Dt(e){return Array.isArray(e)?e.map(t=>{let r=t.responseStatusCode??t.statusCode??0,a=t.timestamp??null;return {method:t.method??"GET",url:t.url??"",status:r,statusCode:r,type:"xhr",size:Mt(t.responseBody),duration:t.responseTimeMs??t.durationMs??0,responseTimeMs:t.responseTimeMs??t.durationMs??0,requestHeaders:t.requestHeaders??null,responseHeaders:t.responseHeaders??null,requestBody:t.requestBody??null,responseBody:t.responseBody??null,timestamp:a,startedAt:a}}):[]}function Nt(e){if(!Array.isArray(e))return [];let t=r=>{if(r==null)return String(r);if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}};return e.map(r=>{let a=r.status==="failed"?"failed":"passed",n=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,s=r.kind??r.type??"assertion",o=a==="failed"?`expected ${t(r.expected)}, received ${t(r.actual)}`:r.expected!==void 0?`expected ${t(r.expected)}`:null;return {...r.callId!=null?{callId:r.callId}:{},kind:s,description:n??r.description??`${s} assertion`,status:a,detail:o}})}async function Ae(e){return new Promise(t=>setTimeout(t,e))}function ui(e){let t={};for(let[r,a]of Object.entries(e))a!=null&&(t[r]=a);return t}async function Ma(e,t,r,a=Ia,n){for(let s=0;s<Re;s++){if(n?.expired())return null;let o=n?n.slice(a):a;if(o<=0)return null;try{let i=await $(e,t,o);if(i.ok)return i;if(i.status===401&&r&&s===0){let d=await r();if(d){let l={...t,headers:{...t.headers,Authorization:`Bearer ${d}`}},c=await $(e,l,o);if(c.ok)return c}return null}if(i.status===429&&s<Re-1){let d=i.headers.get("Retry-After"),l=d?parseInt(d,10)*1e3:Te[s];!isNaN(l)&&l>0?await Ae(l):await Ae(Te[s]);continue}if(i.status>=500&&s<Re-1){await Ae(Te[s]);continue}return i}catch{if(s<Re-1){await Ae(Te[s]);continue}return null}}return null}var pi=util.promisify(zlib.gzip);function _a(e,t){if(!Array.isArray(e.tests))return e;let r=e.tests.map(a=>{let{consoleLogs:n,networkRequests:s,apiCalls:o,...i}=a;return t?i:{...i,...o!==void 0?{apiCalls:o}:{}}});return {...e,tests:r}}var fi=["consoleLogs","networkRequests","apiCalls","actions","navigations","protocolAssertions","visual"];function gi(e){if(!Array.isArray(e.tests))return e;let t=new Set(fi),r=e.tests.map(a=>{let n={};for(let s in a)if(!t.has(s))if(s==="failure"&&a[s]&&typeof a[s]=="object"){let o=a[s];n.failure={message:o.message??null,line:o.line??null};}else n[s]=a[s];return n});return {...e,tests:r}}function hi(e){let t=new Set(["tests","timeline","unifiedTimeline","navigations"]),r={};for(let a in e)t.has(a)||(r[a]=e[a]);return r.tests=[],r}async function Ft(e,t=di){let r={"Content-Type":"application/json"},a=JSON.stringify(e),n=e,s=Array.isArray(n?.tests)?n.tests.length:0,o=i=>Buffer.byteLength(i,"utf-8")>t;if(s>0&&o(a)){let i=Math.max(1,Math.round(t/1048576));process.stderr.write(`[testrelic] WARNING: batch payload exceeds ${i}MB \u2014 dropping consoleLogs/networkRequests from ${s} test(s) to avoid HTTP 413. Console/network detail will be missing in the cloud.
4265
+ `),a=JSON.stringify(_a(n,false)),o(a)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${i}MB after dropping logs \u2014 also dropping apiCalls from ${s} test(s). API request/response detail will be missing in the cloud.
4266
+ `),a=JSON.stringify(_a(n,true))),o(a)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${i}MB \u2014 shedding remaining per-test detail (actions/navigations/assertions) from ${s} test(s). Only test results + summary will reach the cloud.
4267
+ `),a=JSON.stringify(gi(n))),o(a)&&(process.stderr.write(`[testrelic] ERROR: batch still exceeds ${i}MB after shedding all per-test detail \u2014 uploading run summary only (${s} per-test result(s) omitted) to avoid losing the run to HTTP 413.
4268
+ `),a=JSON.stringify(hi(n)));}if(Buffer.byteLength(a,"utf-8")>li){r["Content-Encoding"]="gzip";let i=await pi(Buffer.from(a,"utf-8")),d=i.buffer;return {body:new Uint8Array(d,i.byteOffset,i.byteLength),headers:r}}return {body:a,headers:r}}async function Ea(e,t,r,a,n,s){let o=`${e}/runs`,{body:i,headers:d}=await Ft(r);d.Authorization=`Bearer ${t}`;let l=await Ma(o,{method:"POST",headers:d,body:i},a,n,s);return l?.ok?{success:true,statusCode:l.status,error:null}:l?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:l?`Upload failed with status ${l.status}`:"Upload failed after retries",statusCode:l?.status??null,payload:r,targetEndpoint:o,method:"POST"}}async function Pa(e,t,r,a){let n=`${e}/runs/init`;try{let s=await $(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(ui(r))},a??Ia);return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function La(e,t,r,a){let n=`${e}/runs/${r}/tests`;fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a)}).catch(()=>{});}async function Da(e,t,r,a){let n=`${e}/runs/${r}/finalize`;return (await Ma(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a)}))?.ok??false}function Bt(e,t,r,a){let n=`${e}/runs/${r}/finalize`,s=new Date,o={finishedAt:s.toISOString(),duration:s.getTime()-new Date(a).getTime(),summary:{}};fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(o)}).catch(()=>{});}var xi="1.0.0",Na=10;function Fa(e){return e instanceof Error?e.message:String(e)}function wi(e){return e>=400&&e<500&&e!==408&&e!==429}function pe(e,t,r,a,n,s,o,i){try{fs$1.mkdirSync(e,{recursive:!0});let d=Date.now(),l=`${d}-${t}-${r}.json`,c=path.join(e,l),p={version:xi,queuedAt:new Date(d).toISOString(),reason:a,retryCount:0,targetEndpoint:n,method:s,payload:o,headers:i},v=c+".tmp";fs$1.writeFileSync(v,JSON.stringify(p,null,2),"utf-8"),fs$1.renameSync(v,c);}catch(d){d.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
4269
4269
  `):process.stderr.write(`\u26A0 TestRelic: Unable to queue upload data.
4270
- `);}}async function za(e,t,r){let a;try{a=fs$1.readdirSync(e).filter(s=>s.endsWith(".json")&&!s.endsWith(".tmp")).sort();}catch{return}if(a.length===0)return;let n=[];for(let s=0;s<a.length;s+=Na)n.push(a.slice(s,s+Na));for(let s of n)for(let l of s){let i=path.join(e,l),d;try{if(!fs$1.statSync(i).isFile())continue;let c=JSON.parse(fs$1.readFileSync(i,"utf-8"));if(!core.isValidQueueEntry(c)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${l}
4271
- `),fs$1.unlinkSync(i);continue}d=c;}catch(o){process.stderr.write(`\u26A0 TestRelic: Skipping unreadable queue file ${l}: ${Fa(o)}
4272
- `);try{fs$1.unlinkSync(i);}catch{}continue}try{let{body:o,headers:c}=await Ft(d.payload),p={...d.headers,...c,Authorization:`Bearer ${r}`},v=await fetch(d.targetEndpoint,{method:d.method,headers:p,body:o});if(v.ok)fs$1.unlinkSync(i);else if(xi(v.status)){process.stderr.write(`\u26A0 TestRelic: Queue entry ${l} rejected (HTTP ${v.status}) \u2014 moving aside; it will not be retried.
4273
- `);try{fs$1.renameSync(i,`${i}.failed`);}catch{try{fs$1.unlinkSync(i);}catch{}}}else {process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 server returned HTTP ${v.status} for ${l}; will retry later.
4274
- `);return}}catch(o){process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 ${Fa(o)}; will retry later.
4275
- `);return}}}function Ha(e,t){try{let r=fs$1.readdirSync(e).filter(n=>(n.endsWith(".json")||n.endsWith(".failed"))&&!n.endsWith(".tmp")),a=Date.now();for(let n of r){let s=path.join(e,n);try{let l=fs$1.readFileSync(s,"utf-8"),d=JSON.parse(l).queuedAt;if(typeof d=="string"){let o=new Date(d).getTime();a-o>t&&fs$1.unlinkSync(s);}}catch{try{fs$1.unlinkSync(s);}catch{}}}}catch{}}var Ai=3e5,_i=864e5,Ii=6e4,qa=3e4,zt="https://platform.testrelic.ai/settings/api-keys";function $a(e){return new Promise(t=>{let r=setTimeout(t,e);typeof r?.unref=="function"&&r.unref();})}var _e=class{constructor(t){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=t,this.authState={mode:"pending",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null};}async initialize(){if(!this.config||!this.config.apiKey){this.setLocalMode("no_api_key"),process.stderr.write(`\u2139 TestRelic: No API key configured. Running in local mode.
4270
+ `);}}async function za(e,t,r){let a;try{a=fs$1.readdirSync(e).filter(s=>s.endsWith(".json")&&!s.endsWith(".tmp")).sort();}catch{return}if(a.length===0)return;let n=[];for(let s=0;s<a.length;s+=Na)n.push(a.slice(s,s+Na));for(let s of n)for(let o of s){let i=path.join(e,o),d;try{if(!fs$1.statSync(i).isFile())continue;let c=JSON.parse(fs$1.readFileSync(i,"utf-8"));if(!core.isValidQueueEntry(c)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${o}
4271
+ `),fs$1.unlinkSync(i);continue}d=c;}catch(l){process.stderr.write(`\u26A0 TestRelic: Skipping unreadable queue file ${o}: ${Fa(l)}
4272
+ `);try{fs$1.unlinkSync(i);}catch{}continue}try{let{body:l,headers:c}=await Ft(d.payload),p={...d.headers,...c,Authorization:`Bearer ${r}`},v=await fetch(d.targetEndpoint,{method:d.method,headers:p,body:l});if(v.ok)fs$1.unlinkSync(i);else if(wi(v.status)){process.stderr.write(`\u26A0 TestRelic: Queue entry ${o} rejected (HTTP ${v.status}) \u2014 moving aside; it will not be retried.
4273
+ `);try{fs$1.renameSync(i,`${i}.failed`);}catch{try{fs$1.unlinkSync(i);}catch{}}}else {process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 server returned HTTP ${v.status} for ${o}; will retry later.
4274
+ `);return}}catch(l){process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 ${Fa(l)}; will retry later.
4275
+ `);return}}}function Ha(e,t){try{let r=fs$1.readdirSync(e).filter(n=>(n.endsWith(".json")||n.endsWith(".failed"))&&!n.endsWith(".tmp")),a=Date.now();for(let n of r){let s=path.join(e,n);try{let o=fs$1.readFileSync(s,"utf-8"),d=JSON.parse(o).queuedAt;if(typeof d=="string"){let l=new Date(d).getTime();a-l>t&&fs$1.unlinkSync(s);}}catch{try{fs$1.unlinkSync(s);}catch{}}}}catch{}}var _i=3e5,Ii=864e5,Mi=6e4,qa=3e4,zt="https://platform.testrelic.ai/settings/api-keys";function Va(e){return new Promise(t=>{let r=setTimeout(t,e);typeof r?.unref=="function"&&r.unref();})}var _e=class{constructor(t){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=t,this.authState={mode:"pending",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null};}async initialize(){if(!this.config||!this.config.apiKey){this.setLocalMode("no_api_key"),process.stderr.write(`\u2139 TestRelic: No API key configured. Running in local mode.
4276
4276
  `);return}try{if(wa(this.config.endpoint),this.gitMetadata=Ta(),!await Rt(this.config.endpoint)){this.setLocalMode("cloud_unreachable"),process.stderr.write(`\u26A0 TestRelic: Cloud unreachable. Switching to local mode. Data will be queued for later upload.
4277
4277
  `);return}let r=await At(this.config.endpoint,this.config.apiKey,this.config.timeout);if(_t(r)){this.handleAuthError(r.code,r.statusCode);return}let a=r;this.authState={mode:"cloud",accessToken:a.accessToken,refreshToken:a.refreshToken,expiresAt:Date.now()+a.expiresIn*1e3,orgId:a.orgId,orgName:a.orgName,userId:a.userId,userName:a.userName},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${a.orgName} / ${a.userName})
4278
4278
  `),await this.resolveRepoId(),this.config.queueDirectory&&(Ha(this.config.queueDirectory,this.config.queueMaxAge),this.startBackgroundFlush()),this.startHealthCheck();}catch(t){this.setLocalMode("unexpected_error"),process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. Running in local mode. ${t instanceof Error?t.message:String(t)}
4279
- `);}}getMode(){return this.authState.mode}isCloudMode(){return this.authState.mode==="cloud"}isLocalMode(){return this.authState.mode==="local"}getAccessToken(){return this.authState.accessToken}getRepoId(){return this.repoId}getGitMetadata(){return this.gitMetadata}getConfig(){return this.config}getFailureReason(){return this.failureReason}getEndpoint(){return this.config?.endpoint??"https://platform.testrelic.ai/api/v1"}async ensureValidToken(){if(!this.isCloudMode()||!this.authState.accessToken)return false;let t=this.authState.expiresAt??0;if(Date.now()+Ai<t)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await Sa(this.config.endpoint,this.authState.refreshToken,this.config.timeout);return r?(this.authState.accessToken=r.accessToken,this.authState.refreshToken=r.refreshToken,this.authState.expiresAt=Date.now()+r.expiresIn*1e3,!0):(this.switchToLocalMode("token_refresh_failed"),!1)}catch{return this.switchToLocalMode("token_refresh_error"),false}}switchToLocalMode(t){this.authState.mode!=="local"&&(this.authState.mode="local",this.failureReason=t,process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${t}).
4280
- `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,$a(qa)]);}catch{}this.flushPromise=null;}this.authState={mode:"local",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null},this.repoId=null,this.gitMetadata=null;}setLocalMode(t){this.authState.mode="local",this.failureReason=t;}handleAuthError(t,r){switch(t){case "invalid_key":this.setLocalMode("invalid_api_key"),process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
4279
+ `);}}getMode(){return this.authState.mode}isCloudMode(){return this.authState.mode==="cloud"}isLocalMode(){return this.authState.mode==="local"}getAccessToken(){return this.authState.accessToken}getRepoId(){return this.repoId}getGitMetadata(){return this.gitMetadata}getConfig(){return this.config}getFailureReason(){return this.failureReason}getEndpoint(){return this.config?.endpoint??"https://platform.testrelic.ai/api/v1"}async ensureValidToken(){if(!this.isCloudMode()||!this.authState.accessToken)return false;let t=this.authState.expiresAt??0;if(Date.now()+_i<t)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await Sa(this.config.endpoint,this.authState.refreshToken,this.config.timeout);return r?(this.authState.accessToken=r.accessToken,this.authState.refreshToken=r.refreshToken,this.authState.expiresAt=Date.now()+r.expiresIn*1e3,!0):(this.switchToLocalMode("token_refresh_failed"),!1)}catch{return this.switchToLocalMode("token_refresh_error"),false}}switchToLocalMode(t){this.authState.mode!=="local"&&(this.authState.mode="local",this.failureReason=t,process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${t}).
4280
+ `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,Va(qa)]);}catch{}this.flushPromise=null;}this.authState={mode:"local",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null},this.repoId=null,this.gitMetadata=null;}setLocalMode(t){this.authState.mode="local",this.failureReason=t;}handleAuthError(t,r){switch(t){case "invalid_key":this.setLocalMode("invalid_api_key"),process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
4281
4281
  \u2192 Manage keys: ${zt}
4282
4282
  `);break;case "expired_key":this.setLocalMode("expired_api_key"),process.stderr.write(`\u26A0 TestRelic: API key has expired. Running in local mode.
4283
4283
  \u2192 Generate a new key: ${zt}
@@ -4287,31 +4287,31 @@ ${n}
4287
4287
  `);break;case "timeout":this.setLocalMode("auth_timeout"),process.stderr.write(`\u26A0 TestRelic: Authentication timed out. Running in local mode.
4288
4288
  `);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
4289
4289
  `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let t=this.gitMetadata?.remoteUrl?ce(this.gitMetadata.remoteUrl):null,r=t?Ra(t):this.config.projectName??ue(process.cwd()),a=t??this.config.projectName??ue(process.cwd()),n=this.readRepoCache(a);if(n){this.repoId=n.repoId;return}try{let s=await Ca(this.config.endpoint,this.authState.accessToken,a,r,this.config.timeout,this.gitMetadata?.branch);s&&(this.repoId=s.repoId,this.writeRepoCache(a,s.repoId,s.displayName));}catch{}!t&&!this.config.projectName&&!It(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
4290
- `);}readRepoCache(t){if(!this.config)return null;let r=path.join(this.config.queueDirectory,"..","cache","repo.json");try{if(!fs$1.existsSync(r))return null;let a=fs$1.readFileSync(r,"utf-8"),n=JSON.parse(a);if(n.gitId!==t||Date.now()-n.resolvedAt>_i)return null;let s=this.hashApiKey();return s&&n.apiKeyHash!==s?null:n}catch{return null}}writeRepoCache(t,r,a){if(!this.config)return;let n=path.join(this.config.queueDirectory,"..","cache"),s=path.join(n,"repo.json");try{fs$1.mkdirSync(n,{recursive:!0});let l={repoId:r,gitId:t,displayName:a,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=s+".tmp";fs$1.writeFileSync(i,JSON.stringify(l,null,2),"utf-8"),fs$1.renameSync(i,s);}catch{}}hashApiKey(){return this.config?.apiKey?crypto.createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let t=this.authState.accessToken,r=this.config.queueDirectory,a=this.config.endpoint;this.flushPromise=Promise.race([za(r,a,t),$a(qa)]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let t=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await Rt(t))return;if(this.config?.apiKey){let a=await At(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!_t(a)){let n=a;this.authState={mode:"cloud",accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:Date.now()+n.expiresIn*1e3,orgId:n.orgId,orgName:n.orgName,userId:n.userId,userName:n.userName},this.failureReason=null,process.stderr.write(`\u2713 TestRelic: Cloud connectivity restored.
4291
- `),this.startBackgroundFlush();}}}catch{}},Ii),typeof this.healthCheckTimer?.unref=="function"&&this.healthCheckTimer.unref();}};function Li(e,t){return t?e?{"2xx":e["2xx"]+t["2xx"],"3xx":e["3xx"]+t["3xx"],"4xx":e["4xx"]+t["4xx"],"5xx":e["5xx"]+t["5xx"],error:e.error+t.error}:{...t}:e}function Va(e,t,r,a){let n=[],s=[],l=null,i=0,d=null,o=0,c=null,p=0,v=null,g=e.filter(u=>u.name===core.ATTACHMENT_NAME&&u.body),f=false;if(g.length>0)for(let u of g)try{let h=JSON.parse(u.body.toString());if(core.isTestRelicFilePayload(h)){n=n.concat(h.navigations),s=s.concat(h.apiAssertions),h.networkRequestsFile&&(l=h.networkRequestsFile,i+=h.networkRequestsCount),h.consoleLogsFile&&(d=h.consoleLogsFile,o+=h.consoleLogsCount),h.apiCallsFile&&(c=h.apiCallsFile,p+=h.apiCallsCount),v=Li(v,h.apiStatusMix),f=!0;continue}if(core.isTestRelicDataPayload(h)){n=n.concat(h.navigations),Array.isArray(h.apiAssertions)&&(s=s.concat(h.apiAssertions)),i+=h.networkRequests?.length??0,p+=h.apiCalls?.length??0;let b=h.consoleLogs;Array.isArray(b)&&(o+=b.length),f=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
4290
+ `);}readRepoCache(t){if(!this.config)return null;let r=path.join(this.config.queueDirectory,"..","cache","repo.json");try{if(!fs$1.existsSync(r))return null;let a=fs$1.readFileSync(r,"utf-8"),n=JSON.parse(a);if(n.gitId!==t||Date.now()-n.resolvedAt>Ii)return null;let s=this.hashApiKey();return s&&n.apiKeyHash!==s?null:n}catch{return null}}writeRepoCache(t,r,a){if(!this.config)return;let n=path.join(this.config.queueDirectory,"..","cache"),s=path.join(n,"repo.json");try{fs$1.mkdirSync(n,{recursive:!0});let o={repoId:r,gitId:t,displayName:a,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=s+".tmp";fs$1.writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),fs$1.renameSync(i,s);}catch{}}hashApiKey(){return this.config?.apiKey?crypto.createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let t=this.authState.accessToken,r=this.config.queueDirectory,a=this.config.endpoint;this.flushPromise=Promise.race([za(r,a,t),Va(qa)]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let t=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await Rt(t))return;if(this.config?.apiKey){let a=await At(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!_t(a)){let n=a;this.authState={mode:"cloud",accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:Date.now()+n.expiresIn*1e3,orgId:n.orgId,orgName:n.orgName,userId:n.userId,userName:n.userName},this.failureReason=null,process.stderr.write(`\u2713 TestRelic: Cloud connectivity restored.
4291
+ `),this.startBackgroundFlush();}}}catch{}},Mi),typeof this.healthCheckTimer?.unref=="function"&&this.healthCheckTimer.unref();}};function Di(e,t){return t?e?{"2xx":e["2xx"]+t["2xx"],"3xx":e["3xx"]+t["3xx"],"4xx":e["4xx"]+t["4xx"],"5xx":e["5xx"]+t["5xx"],error:e.error+t.error}:{...t}:e}function $a(e,t,r,a){let n=[],s=[],o=null,i=0,d=null,l=0,c=null,p=0,v=null,g=e.filter(u=>u.name===core.ATTACHMENT_NAME&&u.body),f=false;if(g.length>0)for(let u of g)try{let h=JSON.parse(u.body.toString());if(core.isTestRelicFilePayload(h)){n=n.concat(h.navigations),s=s.concat(h.apiAssertions),h.networkRequestsFile&&(o=h.networkRequestsFile,i+=h.networkRequestsCount),h.consoleLogsFile&&(d=h.consoleLogsFile,l+=h.consoleLogsCount),h.apiCallsFile&&(c=h.apiCallsFile,p+=h.apiCallsCount),v=Di(v,h.apiStatusMix),f=!0;continue}if(core.isTestRelicDataPayload(h)){n=n.concat(h.navigations),Array.isArray(h.apiAssertions)&&(s=s.concat(h.apiAssertions)),i+=h.networkRequests?.length??0,p+=h.apiCalls?.length??0;let b=h.consoleLogs;Array.isArray(b)&&(l+=b.length),f=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
4292
4292
  `);}return f||(n=t.filter(u=>u.type==="lambdatest-navigation"&&u.description).map(u=>{try{return JSON.parse(u.description)}catch{return null}}).filter(u=>u!==null)),n.length===0&&i===0&&p===0&&!a&&!f&&process.stderr.write(`[testrelic] Warning: No data found for test "${r}". Make sure your tests import { test, expect } from '@testrelic/playwright-analytics/fixture' instead of '@playwright/test'. Without the TestRelic fixture, network logs, video sync, and Test Navigation data cannot be captured.
4293
- `),{navigations:n,apiAssertions:s,networkRequestsFile:l,networkRequestsCount:i,consoleLogsFile:d,consoleLogsCount:o,apiCallsFile:c,apiCallsCount:p,apiStatusMix:v}}function Ie(e=process.env){let t=Di(e.TESTRELIC_CLOUD_PLATFORM);if(t)return {cloudPlatform:t,cloudBuildId:e.TESTRELIC_CLOUD_BUILD_ID||void 0,cloudSessionId:e.TESTRELIC_CLOUD_SESSION_ID||void 0};if(e.BROWSERSTACK_USERNAME||e.BROWSERSTACK_ACCESS_KEY)return {cloudPlatform:"browserstack",cloudBuildId:e.BROWSERSTACK_BUILD_NAME||e.BROWSERSTACK_BUILD_ID||void 0,cloudSessionId:e.BROWSERSTACK_SESSION_ID||void 0};if(e.LT_USERNAME||e.LAMBDATEST_USERNAME||e.LT_ACCESS_KEY||e.LAMBDATEST_ACCESS_KEY)return {cloudPlatform:"lambdatest",cloudBuildId:e.LT_BUILD||e.LAMBDATEST_BUILD||void 0,cloudSessionId:e.LT_SESSION_ID||e.LAMBDATEST_SESSION_ID||void 0};let r=e.PLAYWRIGHT_WS_ENDPOINT;if(r){if(/cdp\.lambdatest\.com/i.test(r))return {cloudPlatform:"lambdatest"};if(/cdp\.browserstack\.com/i.test(r))return {cloudPlatform:"browserstack"}}return {}}function Di(e){if(!e)return;let t=e.toLowerCase().trim();if(t==="browserstack"||t==="bs")return "browserstack";if(t==="lambdatest"||t==="lt")return "lambdatest"}var Ui=5,Me=[1e3,3e3,9e3],te=3,$t=3e4,zi={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip",".json":"application/json"},Ht=0,qt=[];async function Hi(){Ht>=Ui&&await new Promise(e=>qt.push(e)),Ht++;}function qi(){Ht--,qt.length>0&&qt.shift()();}async function Ee(e){return new Promise(t=>setTimeout(t,e))}function $i(e){let t=e.substring(e.lastIndexOf(".")).toLowerCase();return zi[t]??"application/octet-stream"}function Vi(e){try{return fs$1.statSync(e).size}catch{return 0}}async function ji(e,t,r,a,n){let s=`${e}/artifacts/upload-url`,l=JSON.stringify({runId:r.runId,testId:r.testId,fileName:path.basename(r.filePath),contentType:n,type:r.type,sizeBytes:a});for(let i=0;i<te;i++)try{let d=await V(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:l},$t);if(d.ok)return await d.json();if(d.status>=500&&i<te-1){await Ee(Me[i]);continue}return null}catch{if(i<te-1){await Ee(Me[i]);continue}return null}return null}async function Gi(e,t,r,a){let n=Aa(a,$t);for(let s=0;s<te;s++)try{let l=fs$1.createReadStream(t),i=stream.Readable.toWeb(l),d=await V(e,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(a)},body:i,duplex:"half"},n);if(d.ok)return !0;if(d.status>=500&&s<te-1){await Ee(Me[s]);continue}return !1}catch{if(s<te-1){await Ee(Me[s]);continue}return false}return false}async function Wi(e,t,r){let a=`${e}/artifacts/confirm`;try{return (await V(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({artifactId:r})},$t)).ok}catch{return false}}async function Ki(e,t,r,a){let n=Vi(r.filePath);if(n===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(n>a*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let s=$i(r.filePath);await Hi();try{let l=await ji(e,t,r,n,s);if(!l)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await Gi(l.uploadUrl,r.filePath,s,n))return {success:!1,storageKey:l.storageKey,artifactId:l.artifactId,error:"presigned_put_failed"};let d=await Wi(e,t,l.artifactId);return {success:d,storageKey:l.storageKey,artifactId:l.artifactId,error:d?null:"confirm_failed"}}finally{qi();}}async function ja(e,t,r,a,n){let s=new Map,l=r.map(async i=>{if(n?.expired()){s.set(i.filePath,{success:false,storageKey:null,artifactId:null,error:"upload_budget_exhausted"});return}let d=await Ki(e,t,i,a);s.set(i.filePath,d);});return await Promise.allSettled(l),s}function jt(e){let r=e.getGitMetadata()?.remoteUrl;return r?ce(r):e.getConfig()?.projectName??ue(process.cwd())}async function Ga(e,t,r,a,n){if(!e.isCloudMode()||t!=="realtime"&&t!=="both"||!await e.ensureValidToken())return null;let l=e.getGitMetadata(),i=U(),d=Ie(),o=Se();return (await Pa(e.getEndpoint(),e.getAccessToken(),{runId:r,repoGitId:jt(e),branch:l?.branch??null,commit:l?.commitSha??null,commitMessage:l?.commitMessage??null,commitAuthor:l?.commitAuthor??null,startedAt:a,totalTests:null,ciProvider:i?.provider??null,ciRunUrl:i?.runUrl??null,environment:n??d.cloudPlatform??null,cloudPlatform:d.cloudPlatform??null,cloudBuildId:d.cloudBuildId??null,cloudSessionId:d.cloudSessionId??null,...o?{runType:o}:{},testType:"e2e"}))?.runId??null}var Yi=[{field:"baseline",keyField:"baselineKey",type:"baseline"},{field:"actual",keyField:"actualKey",type:"screenshot"},{field:"diff",keyField:"diffKey",type:"diff"},{field:"baselineDom",keyField:"baselineDomKey",type:"dom"},{field:"actualDom",keyField:"actualDomKey",type:"dom"}],Xi=true,Zi=50,Vt={keyMap:new Map,visualKeyMap:new Map,total:0,uploaded:0};async function Qi(e,t,r,a,n){let s=new Map,l=new Map;if(!(t?.uploadArtifacts??Xi)||!await e.ensureValidToken())return Vt;let o=[],c=new Map,p=new Map;for(let u of a){if(u.artifacts.screenshot){let b=path.join(u.outputDir,u.artifacts.screenshot);o.push({filePath:b,runId:r,testId:u.testId,type:"screenshot"}),c.set(b,{testId:u.testId,field:"screenshot"});}if(u.artifacts.video){let b=path.join(u.outputDir,u.artifacts.video);o.push({filePath:b,runId:r,testId:u.testId,type:"video"}),c.set(b,{testId:u.testId,field:"video"});}if(u.artifacts.trace){let b=path.join(u.outputDir,u.artifacts.trace);o.push({filePath:b,runId:r,testId:u.testId,type:"trace"}),c.set(b,{testId:u.testId,field:"trace"});}let h=u.visual??[];for(let b=0;b<h.length;b++){let y=h[b];if(y)for(let w of Yi){let C=y[w.field];if(!C)continue;let P=path.join(u.outputDir,C);o.push({filePath:P,runId:r,testId:u.testId,type:w.type}),c.set(P,{testId:u.testId,field:"visual",visualIndex:b,visualKey:w.keyField});}}}if(o.length===0)return Vt;let v=t?.artifactMaxSizeMb??Zi,g=await ja(e.getEndpoint(),e.getAccessToken(),o,v,n),f=new Map;for(let[u,h]of g){if(!h.success||!h.storageKey)continue;let b=c.get(u);if(!b)continue;let y=f.get(b.testId)??{};if(b.field==="screenshot"&&(y.screenshotKey=h.storageKey),b.field==="video"&&(y.videoKey=h.storageKey),b.field==="trace"&&(y.traceKey=h.storageKey),b.field==="visual"&&b.visualIndex!==void 0&&b.visualKey){let w=p.get(b.testId)??new Map,C=w.get(b.visualIndex)??{};C[b.visualKey]=h.storageKey,w.set(b.visualIndex,C),p.set(b.testId,w);}f.set(b.testId,y);}for(let u of a){if(u.visual&&u.visual.length>0){let b=p.get(u.testId);l.set(u.testId,u.visual.map((y,w)=>({...y,...b?.get(w)??{}})));}let h=f.get(u.testId);s.set(u.testId,{...u.artifacts,...h?.screenshotKey?{screenshotKey:h.screenshotKey}:{},...h?.videoKey?{videoKey:h.videoKey}:{},...h?.traceKey?{traceKey:h.traceKey}:{}});}let m=Array.from(g.values()).filter(u=>u.success).length;return m>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${m} artifact(s) to cloud storage.
4294
- `),{keyMap:s,visualKeyMap:l,total:o.length,uploaded:m}}async function Gt(e,t,r,a,n,s,l,i,d,o,c){let p={realtimeFinalizeAttempted:false,realtimeFinalized:false,batchAttempted:false,batchAcknowledged:false,artifactsTotal:0,artifactsUploaded:0,failureReason:null},v=new Ce(t?.uploadBudgetMs??12e4),g=f=>{p.failureReason||(p.failureReason=f);};try{if(e.isCloudMode()&&n&&(r==="realtime"||r==="both")){p.realtimeFinalizeAttempted=!0;let u=await e.ensureValidToken(),h=e.getGitMetadata(),b=Et(c),y={finishedAt:l,duration:i,summary:d,...h?.commitMessage?{commitMessage:h.commitMessage}:{},testType:b.testType,...b.testType==="api"?{apiProtocol:b.apiProtocol,metadata:b.metadata}:{}};if(u){let w=await Da(e.getEndpoint(),e.getAccessToken(),n,y);if(p.realtimeFinalized=w,!w){g("finalize_failed_after_retries");let C=t?.queueDirectory??".testrelic/queue";pe(C,a,"finalize","finalize_failed_after_retries",`${e.getEndpoint()}/runs/${n}/finalize`,"POST",y,{"Content-Type":"application/json"});}}else {g(e.getFailureReason()??"token_invalid");let w=t?.queueDirectory??".testrelic/queue";pe(w,a,"finalize",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs/${n}/finalize`,"POST",y,{"Content-Type":"application/json"});}}let f=new Map,m=new Map;if(e.isCloudMode()&&o&&o.length>0){let u=await Qi(e,t,a,o,v);f=u.keyMap,m=u.visualKeyMap,p.artifactsTotal=u.total,p.artifactsUploaded=u.uploaded;}if(e.isCloudMode()&&(!r||r==="batch"||r==="both"))if(p.batchAttempted=!0,await e.ensureValidToken()){let h=e.getGitMetadata(),b=U(),y=jt(e),w=to(ro(s,f),m),C=Pt(w,y,h,b,eo(c,m),Ie()),P=await Ea(e.getEndpoint(),e.getAccessToken(),C,async()=>await e.ensureValidToken()?e.getAccessToken():null,t?.timeout,v);if(p.batchAcknowledged=P.success,!P.success){let A=P;g(A.reason);let R=t?.queueDirectory??".testrelic/queue";pe(R,a,"batch",A.reason,A.targetEndpoint,A.method,A.payload,{"Content-Type":"application/json"});}}else {g(e.getFailureReason()??"token_invalid");let h=t?.queueDirectory??".testrelic/queue",b=e.getGitMetadata(),y=U(),w=jt(e),C=Pt(s,w,b,y,void 0,Ie());pe(h,a,"batch",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs`,"POST",C,{"Content-Type":"application/json"});}await e.dispose();}catch(f){g(f instanceof Error?f.message:"unexpected_upload_error");try{await e.dispose();}catch{}}return p}function eo(e,t){return !e||t.size===0?e:e.map(r=>{let a=t.get(r.testId);return a?{...r,visual:a}:r})}function to(e,t){if(t.size===0)return e;let r=e.timeline.map(a=>{let n=a.tests;if(!Array.isArray(n))return a;let s=false,l=n.map(i=>{let d=i.testId;if(!d)return i;let o=t.get(d);return o?(s=true,{...i,visual:o}):i});return s?{...a,tests:l}:a});return {...e,timeline:r}}function ro(e,t){if(t.size===0)return e;let r=e.timeline.map(a=>{let n=a.testId;if(!n)return a;let s=t.get(n);return s?{...a,...s.screenshotKey?{screenshotKey:s.screenshotKey}:{},...s.videoKey?{videoKey:s.videoKey}:{}}:a});return {...e,timeline:r}}var ao=new Set(["batch","realtime","both"]),fe=Object.freeze({attempted:false,acknowledged:false,runId:null,endpoint:null,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:"cloud reporting was never initialised"});function no(e){switch(e){case "no_api_key":return "cloud mode off \u2014 no API key configured";case "cloud_unreachable":case "network_error":return "cloud endpoint unreachable \u2014 the run stayed local";case "invalid_api_key":return "API key rejected as invalid or revoked \u2014 the run stayed local";case "expired_api_key":return "API key has expired \u2014 the run stayed local";case "validation_error":return "API key format rejected \u2014 the run stayed local";case "rate_limited":return "rate limited during authentication \u2014 the run stayed local";case "auth_timeout":return "authentication timed out \u2014 the run stayed local";case "token_expired_no_refresh":case "token_refresh_failed":case "token_refresh_error":return "access token could not be refreshed \u2014 the run stayed local";case "init_error":return "cloud initialisation timed out \u2014 the run stayed local";case "unexpected_error":return "cloud initialisation failed \u2014 the run stayed local";default:return e?`cloud mode off (${e}) \u2014 the run stayed local`:"cloud mode off \u2014 the run stayed local"}}function Wa(e,t,r){if(!e)return fe;if(!e.isCloudMode())return {...fe,detail:no(e.getFailureReason())};let a=t??"batch";if(!ao.has(a))return {...fe,detail:`upload strategy '${a}' is not recognised \u2014 nothing was sent`};let n=e.getEndpoint(),s=a==="realtime"||a==="both";return s&&r?{attempted:true,acknowledged:true,runId:r,endpoint:n,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:null}:{attempted:true,acknowledged:false,runId:null,endpoint:n,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:s?"run init failed \u2014 the platform did not acknowledge this run":`upload runs at the end of the run under the '${a}' strategy \u2014 not sent yet`}}function Wt(e,t,r){if(!e.attempted)return e;if(!t)return {...e,detail:e.acknowledged?"upload timed out before it completed \u2014 the run may be incomplete on the platform":"upload timed out before the platform acknowledged this run",acknowledged:e.acknowledged};let a=e.acknowledged||t.batchAcknowledged,n=e.runId??(t.batchAcknowledged?r:null),s=t.realtimeFinalizeAttempted?t.realtimeFinalized:t.batchAcknowledged,l=null;return a?s||(l="run acknowledged but not closed out \u2014 finalize failed and was queued for retry"):l=t.failureReason?`upload failed (${t.failureReason}) \u2014 queued locally for retry`:"upload failed \u2014 the platform did not acknowledge this run",{attempted:true,acknowledged:a,runId:n,endpoint:e.endpoint,finalized:s,artifactsUploaded:t.artifactsUploaded,artifactsTotal:t.artifactsTotal,detail:l}}function j(e){try{return fs$1.readFileSync(e,"utf-8").split(`
4295
- `).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function po(e){if(!e)return null;let t=e.split(`
4296
- `).map(s=>s.trim()).filter(Boolean);if(t.length===0)return null;let r=t.filter(s=>!/^Error:\s*expect\(/.test(s));if(r.length===0)return t[0]??null;let a=r[0],n=r[1];return n!==void 0&&/^Received:/.test(n)&&/^Expected:/.test(a)?`${a} \xB7 ${n}`:a}function Jt(e){switch(e){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function fo(e,t,r){let a=`${e}::${t}::${r}`;return crypto.createHash("sha256").update(a).digest("hex").substring(0,16)}function go(e){return e.length<=3?"":e[e.length-2]}function ho(e){let t=e.findIndex(r=>r.status==="passed");return t>0?`passed on retry ${t}`:null}function en(e){return e===null?"error":e>=200&&e<300?"2xx":e>=300&&e<400?"3xx":e>=400&&e<500?"4xx":e>=500&&e<600?"5xx":"error"}function mo(e){let t={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},r=t;for(let a of e){let n=typeof a.responseStatusCode=="number"?a.responseStatusCode:null;r[en(n)]++;}return t}function Xa(e){if(e){for(let t of e)if(t.status==="failed")return {type:t.type,expected:Za(t.expected),actual:Za(t.actual),...t.expression?{expression:t.expression}:{}}}}function Za(e){if(e===void 0)return "undefined";if(e===null)return "null";let t;if(typeof e=="string")t=e;else try{t=JSON.stringify(e)??String(e);}catch{t=String(e);}return t.length>200?t.slice(0,200)+"\u2026":t}function Le(e,t){if(!e)return 0;let r=0;for(let a of e)a.status===t&&r++;return r}function tn(e,t){for(let r of e)t[r.category]=(t[r.category]??0)+1,r.children.length>0&&tn(r.children,t);}function vo(e){if(e.length===0)return null;let t=[...e].sort((a,n)=>a-n),r=t.reduce((a,n)=>a+n,0);return {avg:Math.round(r/t.length),min:t[0],max:t[t.length-1],p50:Y(t,50),p95:Y(t,95),p99:Y(t,99)}}var rn=2e5,De=1e5;function Qa(e,t,r,a,n,s,l){let i={retryIndex:e,apiCalls:t?.length??0,apiUrls:[],methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,assertions:r.length,navigations:a.length,navUrls:[],networkRequests:n,consoleLogs:s,actionSteps:l?.length??0,actionCategories:{}};if(t){let o=new Set;for(let c of t){let p=typeof c.method=="string"?c.method:"OTHER";i.methodCounts[p]=(i.methodCounts[p]??0)+1;let v=typeof c.url=="string"?c.url:null;v&&o.size<De&&o.add(St(v));let g=typeof c.responseStatusCode=="number"?c.responseStatusCode:typeof c.statusCode=="number"?c.statusCode:null,f=g!==null&&Number.isFinite(g)?g:null;i.statusRanges[en(f)]++;let m=typeof c.responseTimeMs=="number"?c.responseTimeMs:typeof c.durationMs=="number"?c.durationMs:null;m!==null&&Number.isFinite(m)&&i.responseTimes.length<rn&&i.responseTimes.push(m);}i.apiUrls=Array.from(o);}for(let o of r)o.status==="passed"?i.passedAssertions++:i.failedAssertions++;let d=new Set;for(let o of a)o.url&&d.size<De&&d.add(o.url);return i.navUrls=Array.from(d),l&&tn(l,i.actionCategories),i}function bo(){return {apiUrlSet:new Set,methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,navUrlSet:new Set,actionCategoryCounts:{},volApiCalls:0,volAssertions:0,volNavigations:0,volNetworkRequests:0,volConsoleLogs:0,volActionSteps:0}}function yo(e){return process.env.BROWSERSTACK_USERNAME?"BrowserStack":e?{"github-actions":"GitHub Actions","gitlab-ci":"GitLab CI",jenkins:"Jenkins",circleci:"CircleCI","bitbucket-pipelines":"Bitbucket Pipelines"}[e.provider]??"CI":"Local"}function xo(){let e=os$1.platform();return e==="win32"?"Windows":e==="darwin"?"macOS":"Linux"}function wo(e){let t=e.parent?.project?.()?.use;if(!t)return;let{browserName:r,channel:a}=t;if(a){let s=a.toLowerCase();return s==="chrome"||s==="chrome-stable"?"Chrome":s.startsWith("chrome-beta")?"Chrome Beta":s.startsWith("chrome-dev")?"Chrome Dev":s.startsWith("chrome-canary")?"Chrome Canary":s==="msedge"||s==="msedge-stable"?"Microsoft Edge":s.startsWith("msedge-beta")?"Edge Beta":s.startsWith("msedge-dev")?"Edge Dev":s.startsWith("msedge-canary")?"Edge Canary":a}if(r){let s=r.toLowerCase();return s==="chromium"?"Chromium":s==="firefox"?"Firefox":s==="webkit"?"WebKit":r}let n=t.defaultBrowserType;if(n){let s=n.toLowerCase();return s==="chromium"?"Chromium":s==="firefox"?"Firefox":s==="webkit"?"WebKit":n}}function ko(e,t,r){let a=r.parent?.project?.(),n="unknown";a!==void 0&&(a.use.isMobile===true?n="mobile":n="e2e");let s=["e2e","api","unit","mobile"];for(let d of s)if(e.some(o=>o===`@${d}`||o===d))return d;let l=t.replace(/\\/g,"/"),i=["e2e","api","unit"];for(let d of i)if(l.includes(`/${d}/`))return d;return n}var So="__testrelic_api_config";function Co(e){return JSON.stringify(e,(t,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var Ne=class{constructor(t){this.rootDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.navigationsCaptured=false;this.memoryPressureWarned=false;this.testCount=0;this.cloudClient=null;this.cloudRunId=null;this.runTimestamp="";this.updatingSnapshots=false;this.cloudReceipt=fe;this.pendingArtifactEntries=[];this.detectedOs="";this.detectedSource="";this.cloudTestsBuffer=[];this.activeReportMode="embedded";this.streamingWriter=null;this.testIndex=[];this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0,visualChecks:0,visualFailures:0,visualDomChanges:0};this.streamingTestAgg=new Map;this.config=gr(t),this.apiConfig=fr(t);}upsertAggContribution(t,r){let a=this.streamingTestAgg.get(t);(!a||r.retryIndex>a.retryIndex)&&this.streamingTestAgg.set(t,r);}async onBegin(t,r){try{this.rootDir=t.rootDir;let a=t.updateSnapshots;if(this.updatingSnapshots=a==="all"||a==="changed",this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??crypto.randomUUID(),this.config.reportMode==="auto"){let i=r.allTests().length;this.activeReportMode=i>=this.config.streamingThreshold?"streaming":"embedded";}else this.activeReportMode=this.config.reportMode;let n=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${n} tests)
4297
- `),this.activeReportMode==="streaming"){let i=path.dirname(this.config.outputPath);this.streamingWriter=new ie(i);let d=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let o={testRunId:this.testRunId??"",startedAt:this.startedAt,completedAt:new Date().toISOString(),totalDuration:Date.now()-new Date(this.startedAt).getTime(),...this.summaryCounters,metadata:null,reportMode:"streaming",files:[],enrichedSummary:null,validation:null,writeErrors:this.streamingWriter.getWriteErrors(),cloudUpload:this.cloudReceipt};this.streamingWriter.writeSummary(o);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let o=this.cloudClient.getAccessToken();o&&Bt(this.cloudClient.getEndpoint(),o,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",d),process.on("SIGINT",d);}if(this.config.includeArtifacts){let i=path.dirname(this.config.outputPath);this.runTimestamp=Jr(path.join(i,"artifacts"));try{ua(path.join(i,"artifacts"));}catch{}}let s=U();this.detectedOs=xo(),this.detectedSource=yo(s);let l=await J(async()=>(this.cloudClient=new _e(this.config.cloud),await this.cloudClient.initialize(),Ga(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource)),fa,"Cloud initialization");if(this.cloudRunId=l??null,l===void 0&&this.cloudClient?.switchToLocalMode("init_error"),this.cloudReceipt=Wa(this.cloudClient,this.config.cloud?.uploadStrategy,this.cloudRunId),this.activeReportMode!=="streaming"){let i=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let d=this.cloudClient.getAccessToken();d&&Bt(this.cloudClient.getEndpoint(),d,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",i),process.on("SIGINT",i);}}catch{}}onTestBegin(t,r){try{t.annotations.push({type:So,description:Co(this.apiConfig)});}catch{}}onTestEnd(t,r){try{let a=r,n=t.outcome(),s;n==="flaky"?s="flaky":n==="skipped"?s="skipped":s=Jt(a.status);let l=a.startTime.toISOString(),i=new Date(a.startTime.getTime()+a.duration).toISOString(),d=t.tags?[...t.tags]:t.annotations.filter(_=>_.type==="tag").map(_=>_.description??""),o=Va(a.attachments,t.annotations,t.title,s==="skipped");(o.navigations.length>0||o.networkRequestsCount>0||o.apiCallsCount>0)&&(this.fixtureDataReceived=!0),o.navigations.length>0&&(this.navigationsCaptured=!0),!this.config.captureNavigation&&o.navigations.length>0&&(o={...o,navigations:[]});let c=null;if(s==="failed"||s==="flaky"){let T=(s==="flaky"?t.results.find(F=>F.status!=="passed")?.errors??[]:a.errors)[0];if(T){let F=mr(this.config.redactPatterns),ae=T.location?.file??null,I=o.apiAssertions.find(an=>an.status==="failed")?.location??null,Z=I!==null&&(ae===null||path.resolve(ae)!==path.resolve(t.location.file)),Qt=Z?I.file:ae,Fe=Z?I.line:T.location?.line??null,ne=null;this.config.includeCodeSnippets&&Fe!==null&&Qt&&(ne=hr(Qt,Fe,this.config.codeContextLines),ne&&(ne=F(ne))),c={message:F(ke(T.message??"Unknown error")),line:Fe,code:ne,stack:this.config.includeStackTrace&&T.stack?F(ke(T.stack)):null};}}let p=t.titlePath().filter(Boolean),v=path.relative(this.rootDir||".",t.location.file).replace(/\\/g,"/"),g=go(p),f=p.join(" > "),m=v,u=fo(m,g,f),h=ko(d,m,t),b=h!=="mobile"&&o.apiCallsCount>0?"api":h,y=n==="flaky",w=ho(t.results),C=Jt(t.expectedStatus),P=Jt(a.status),A=null;if(this.config.includeArtifacts&&s!=="skipped"&&a.attachments){let _=path.dirname(this.config.outputPath),T=p[p.length-1]??t.title;A=Xr(a.attachments,T,a.retry,_,this.runTimestamp||void 0,u);}let R=null;if(this.config.includeArtifacts&&s!=="skipped"&&a.attachments)try{let _=ta(a.attachments,{updatingSnapshots:this.updatingSnapshots,failureMessage:a.errors.map(T=>T.message??"").join(`
4298
- `)});if(_.length>0){let T=path.dirname(this.config.outputPath),F=p[p.length-1]??t.title;R=Zr(_,F,a.retry,T,this.runTimestamp||void 0,u);}}catch{}let L=this.config.includeActionSteps&&a.steps?ya(a.steps,a.startTime):null,x=wo(t),S={titlePath:p,title:f,status:s,duration:a.duration,startedAt:l,completedAt:i,retryCount:t.results.length-1,retry:a.retry,tags:d,failure:c,specFile:v,navigations:o.navigations,testId:u,filePath:m,suiteName:g,testType:b,isFlaky:y,retryStatus:w,expectedStatus:C,actualStatus:P,artifacts:A,visual:R,apiAssertions:o.apiAssertions,actions:L,networkRequestsFile:o.networkRequestsFile,networkRequestsCount:o.networkRequestsCount,consoleLogsFile:o.consoleLogsFile,consoleLogsCount:o.consoleLogsCount,apiCallsFile:o.apiCallsFile,apiCallsCount:o.apiCallsCount,apiStatusMix:o.apiStatusMix,browser:x,os:this.detectedOs||void 0,source:this.detectedSource||void 0},X=o.consoleLogsFile&&o.consoleLogsCount>0?j(o.consoleLogsFile):void 0,G=o.networkRequestsFile&&o.networkRequestsCount>0?j(o.networkRequestsFile):void 0,re=o.apiCallsFile&&o.apiCallsCount>0?j(o.apiCallsFile):void 0,Yt=re?Lt(re):void 0,Xt=!G&&re?Dt(re):void 0,Zt=o.apiAssertions&&o.apiAssertions.length>0?Nt(o.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:u,title:f,status:s,duration:a.duration,suiteName:g,filePath:m,testType:b,isFlaky:y,startedAt:l,completedAt:i,tags:d,failure:c,retry:a.retry,retryCount:t.results.length-1,retryStatus:w,browser:x,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...L&&L.length>0?{actions:L}:{},...o.navigations&&o.navigations.length>0?{navigations:o.navigations}:{},...X?{consoleLogs:X}:{},...G?{networkRequests:G}:Xt?{networkRequests:Xt}:{},...Yt?{apiCalls:Yt}:{},...Zt?{protocolAssertions:Zt}:{},...R&&R.length>0?{visual:R}:{}});try{let _=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(_==="realtime"||_==="both")){let T=this.cloudClient.getAccessToken();T&&La(this.cloudClient.getEndpoint(),T,this.cloudRunId,this.buildCloudTestPayload(S));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let _=Be(m,p,t.id??"",a.retry),T=a.retry===t.results.length-1,F={id:_,navigations:o.navigations,apiAssertions:o.apiAssertions,actions:L??[],artifacts:A,visual:R,failureDiagnostic:c,hasNetworkFile:o.networkRequestsFile!==null,networkRequestsCount:o.networkRequestsCount,hasConsoleFile:o.consoleLogsFile!==null,consoleLogsCount:o.consoleLogsCount,hasApiCallsFile:o.apiCallsFile!==null,apiCallsCount:o.apiCallsCount,startedAt:l};this.streamingWriter.writeTestDetail(_,F,{networkRequestsFile:o.networkRequestsFile,consoleLogsFile:o.consoleLogsFile,apiCallsFile:o.apiCallsFile});let ae={id:_,title:p[p.length-1]??t.title,titlePath:p,filePath:m,status:s,duration:a.duration,project:p[1]??"",retryIndex:a.retry,tags:d,hasNetworkData:o.networkRequestsCount>0,hasConsoleData:o.consoleLogsCount>0,hasArtifacts:A!==null,hasActionSteps:(L?.length??0)>0,visualCount:R?.length??0,visualFailedCount:R?.filter(I=>I.status==="failed").length??0,domChangeCount:R?.reduce((I,Z)=>I+(Z.domChangeCount??0),0)??0,...(()=>{let I=R?.find(Z=>Z.diff);return I?.diff?{visualDiffPath:I.diff}:{}})(),errorMessage:po(c?.message),networkCount:o.networkRequestsCount,consoleCount:o.consoleLogsCount,actionCount:L?.length??0,testType:b,apiCallCount:o.apiCallsCount,...o.apiStatusMix?{apiStatusMix:o.apiStatusMix}:{},assertionsPassed:Le(o.apiAssertions,"passed"),assertionsFailed:Le(o.apiAssertions,"failed"),...(()=>{let I=Xa(o.apiAssertions);return I?{firstFailedAssertion:I}:{}})(),isRetry:!T,retryGroupKey:Oe(m,p,t.id??"")};if(this.testIndex.push(ae),T)switch(this.summaryCounters.total++,s){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.upsertAggContribution(`${m}::${p.join(" > ")}`,Qa(a.retry,re,o.apiAssertions,o.navigations,o.networkRequestsCount,o.consoleLogsCount,L)),(A||R)&&this.pendingArtifactEntries.push({testId:u,artifacts:A??{},visual:R,outputDir:path.dirname(this.config.outputPath)}),S.actions=null,S.apiAssertions=null,S.navigations=[],S.artifacts=null,S.failure=null,S.networkRequestsFile=null,S.consoleLogsFile=null,S.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(S),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(t){try{let r=new Date().toISOString(),a=new Date(this.startedAt).getTime(),s=new Date(r).getTime()-a,l=this.activeReportMode==="streaming"?this.testIndex.some(d=>d.status!=="skipped"):this.collectedTests.some(d=>d.status!=="skipped");!this.fixtureDataReceived&&l&&process.stderr.write(`
4293
+ `),{navigations:n,apiAssertions:s,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:d,consoleLogsCount:l,apiCallsFile:c,apiCallsCount:p,apiStatusMix:v}}function Ie(e=process.env){let t=Ni(e.TESTRELIC_CLOUD_PLATFORM);if(t)return {cloudPlatform:t,cloudBuildId:e.TESTRELIC_CLOUD_BUILD_ID||void 0,cloudSessionId:e.TESTRELIC_CLOUD_SESSION_ID||void 0};if(e.BROWSERSTACK_USERNAME||e.BROWSERSTACK_ACCESS_KEY)return {cloudPlatform:"browserstack",cloudBuildId:e.BROWSERSTACK_BUILD_NAME||e.BROWSERSTACK_BUILD_ID||void 0,cloudSessionId:e.BROWSERSTACK_SESSION_ID||void 0};if(e.LT_USERNAME||e.LAMBDATEST_USERNAME||e.LT_ACCESS_KEY||e.LAMBDATEST_ACCESS_KEY)return {cloudPlatform:"lambdatest",cloudBuildId:e.LT_BUILD||e.LAMBDATEST_BUILD||void 0,cloudSessionId:e.LT_SESSION_ID||e.LAMBDATEST_SESSION_ID||void 0};let r=e.PLAYWRIGHT_WS_ENDPOINT;if(r){if(/cdp\.lambdatest\.com/i.test(r))return {cloudPlatform:"lambdatest"};if(/cdp\.browserstack\.com/i.test(r))return {cloudPlatform:"browserstack"}}return {}}function Ni(e){if(!e)return;let t=e.toLowerCase().trim();if(t==="browserstack"||t==="bs")return "browserstack";if(t==="lambdatest"||t==="lt")return "lambdatest"}var zi=5,Me=[1e3,3e3,9e3],te=3,Vt=3e4,Hi={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip",".json":"application/json"},Ht=0,qt=[];async function qi(){Ht>=zi&&await new Promise(e=>qt.push(e)),Ht++;}function Vi(){Ht--,qt.length>0&&qt.shift()();}async function Ee(e){return new Promise(t=>setTimeout(t,e))}function $i(e){let t=e.substring(e.lastIndexOf(".")).toLowerCase();return Hi[t]??"application/octet-stream"}function ji(e){try{return fs$1.statSync(e).size}catch{return 0}}async function Gi(e,t,r,a,n){let s=`${e}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:path.basename(r.filePath),contentType:n,type:r.type,sizeBytes:a});for(let i=0;i<te;i++)try{let d=await $(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:o},Vt);if(d.ok)return await d.json();if(d.status>=500&&i<te-1){await Ee(Me[i]);continue}return null}catch{if(i<te-1){await Ee(Me[i]);continue}return null}return null}async function Wi(e,t,r,a){let n=Aa(a,Vt);for(let s=0;s<te;s++)try{let o=fs$1.createReadStream(t),i=stream.Readable.toWeb(o),d=await $(e,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(a)},body:i,duplex:"half"},n);if(d.ok)return !0;if(d.status>=500&&s<te-1){await Ee(Me[s]);continue}return !1}catch{if(s<te-1){await Ee(Me[s]);continue}return false}return false}async function Ki(e,t,r){let a=`${e}/artifacts/confirm`;try{return (await $(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({artifactId:r})},Vt)).ok}catch{return false}}async function Ji(e,t,r,a){let n=ji(r.filePath);if(n===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(n>a*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let s=$i(r.filePath);await qi();try{let o=await Gi(e,t,r,n,s);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await Wi(o.uploadUrl,r.filePath,s,n))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let d=await Ki(e,t,o.artifactId);return {success:d,storageKey:o.storageKey,artifactId:o.artifactId,error:d?null:"confirm_failed"}}finally{Vi();}}async function ja(e,t,r,a,n){let s=new Map,o=r.map(async i=>{if(n?.expired()){s.set(i.filePath,{success:false,storageKey:null,artifactId:null,error:"upload_budget_exhausted"});return}let d=await Ji(e,t,i,a);s.set(i.filePath,d);});return await Promise.allSettled(o),s}function jt(e){let r=e.getGitMetadata()?.remoteUrl;return r?ce(r):e.getConfig()?.projectName??ue(process.cwd())}async function Ga(e,t,r,a,n){if(!e.isCloudMode()||t!=="realtime"&&t!=="both"||!await e.ensureValidToken())return null;let o=e.getGitMetadata(),i=U(),d=Ie(),l=Se();return (await Pa(e.getEndpoint(),e.getAccessToken(),{runId:r,repoGitId:jt(e),branch:o?.branch??null,commit:o?.commitSha??null,commitMessage:o?.commitMessage??null,commitAuthor:o?.commitAuthor??null,startedAt:a,totalTests:null,ciProvider:i?.provider??null,ciRunUrl:i?.runUrl??null,environment:n??d.cloudPlatform??null,cloudPlatform:d.cloudPlatform??null,cloudBuildId:d.cloudBuildId??null,cloudSessionId:d.cloudSessionId??null,...l?{runType:l}:{},testType:"e2e"}))?.runId??null}var Xi=[{field:"baseline",keyField:"baselineKey",type:"baseline"},{field:"actual",keyField:"actualKey",type:"screenshot"},{field:"diff",keyField:"diffKey",type:"diff"},{field:"baselineDom",keyField:"baselineDomKey",type:"dom"},{field:"actualDom",keyField:"actualDomKey",type:"dom"}],Zi=true,Qi=50,$t={keyMap:new Map,visualKeyMap:new Map,total:0,uploaded:0};async function eo(e,t,r,a,n){let s=new Map,o=new Map;if(!(t?.uploadArtifacts??Zi)||!await e.ensureValidToken())return $t;let l=[],c=new Map,p=new Map;for(let u of a){if(u.artifacts.screenshot){let b=path.join(u.outputDir,u.artifacts.screenshot);l.push({filePath:b,runId:r,testId:u.testId,type:"screenshot"}),c.set(b,{testId:u.testId,field:"screenshot"});}if(u.artifacts.video){let b=path.join(u.outputDir,u.artifacts.video);l.push({filePath:b,runId:r,testId:u.testId,type:"video"}),c.set(b,{testId:u.testId,field:"video"});}if(u.artifacts.trace){let b=path.join(u.outputDir,u.artifacts.trace);l.push({filePath:b,runId:r,testId:u.testId,type:"trace"}),c.set(b,{testId:u.testId,field:"trace"});}let h=u.visual??[];for(let b=0;b<h.length;b++){let y=h[b];if(y)for(let w of Xi){let C=y[w.field];if(!C)continue;let P=path.join(u.outputDir,C);l.push({filePath:P,runId:r,testId:u.testId,type:w.type}),c.set(P,{testId:u.testId,field:"visual",visualIndex:b,visualKey:w.keyField});}}}if(l.length===0)return $t;let v=t?.artifactMaxSizeMb??Qi,g=await ja(e.getEndpoint(),e.getAccessToken(),l,v,n),f=new Map;for(let[u,h]of g){if(!h.success||!h.storageKey)continue;let b=c.get(u);if(!b)continue;let y=f.get(b.testId)??{};if(b.field==="screenshot"&&(y.screenshotKey=h.storageKey),b.field==="video"&&(y.videoKey=h.storageKey),b.field==="trace"&&(y.traceKey=h.storageKey),b.field==="visual"&&b.visualIndex!==void 0&&b.visualKey){let w=p.get(b.testId)??new Map,C=w.get(b.visualIndex)??{};C[b.visualKey]=h.storageKey,w.set(b.visualIndex,C),p.set(b.testId,w);}f.set(b.testId,y);}for(let u of a){if(u.visual&&u.visual.length>0){let b=p.get(u.testId);o.set(u.testId,u.visual.map((y,w)=>({...y,...b?.get(w)??{}})));}let h=f.get(u.testId);s.set(u.testId,{...u.artifacts,...h?.screenshotKey?{screenshotKey:h.screenshotKey}:{},...h?.videoKey?{videoKey:h.videoKey}:{},...h?.traceKey?{traceKey:h.traceKey}:{}});}let m=Array.from(g.values()).filter(u=>u.success).length;return m>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${m} artifact(s) to cloud storage.
4294
+ `),{keyMap:s,visualKeyMap:o,total:l.length,uploaded:m}}async function Gt(e,t,r,a,n,s,o,i,d,l,c){let p={realtimeFinalizeAttempted:false,realtimeFinalized:false,batchAttempted:false,batchAcknowledged:false,artifactsTotal:0,artifactsUploaded:0,failureReason:null},v=new Ce(t?.uploadBudgetMs??12e4),g=f=>{p.failureReason||(p.failureReason=f);};try{if(e.isCloudMode()&&n&&(r==="realtime"||r==="both")){p.realtimeFinalizeAttempted=!0;let u=await e.ensureValidToken(),h=e.getGitMetadata(),b=Et(c),y={finishedAt:o,duration:i,summary:d,...h?.commitMessage?{commitMessage:h.commitMessage}:{},testType:b.testType,...b.testType==="api"?{apiProtocol:b.apiProtocol,metadata:b.metadata}:{}};if(u){let w=await Da(e.getEndpoint(),e.getAccessToken(),n,y);if(p.realtimeFinalized=w,!w){g("finalize_failed_after_retries");let C=t?.queueDirectory??".testrelic/queue";pe(C,a,"finalize","finalize_failed_after_retries",`${e.getEndpoint()}/runs/${n}/finalize`,"POST",y,{"Content-Type":"application/json"});}}else {g(e.getFailureReason()??"token_invalid");let w=t?.queueDirectory??".testrelic/queue";pe(w,a,"finalize",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs/${n}/finalize`,"POST",y,{"Content-Type":"application/json"});}}let f=new Map,m=new Map;if(e.isCloudMode()&&l&&l.length>0){let u=await eo(e,t,a,l,v);f=u.keyMap,m=u.visualKeyMap,p.artifactsTotal=u.total,p.artifactsUploaded=u.uploaded;}if(e.isCloudMode()&&(!r||r==="batch"||r==="both"))if(p.batchAttempted=!0,await e.ensureValidToken()){let h=e.getGitMetadata(),b=U(),y=jt(e),w=ro(ao(s,f),m),C=Pt(w,y,h,b,to(c,m),Ie()),P=await Ea(e.getEndpoint(),e.getAccessToken(),C,async()=>await e.ensureValidToken()?e.getAccessToken():null,t?.timeout,v);if(p.batchAcknowledged=P.success,!P.success){let A=P;g(A.reason);let R=t?.queueDirectory??".testrelic/queue";pe(R,a,"batch",A.reason,A.targetEndpoint,A.method,A.payload,{"Content-Type":"application/json"});}}else {g(e.getFailureReason()??"token_invalid");let h=t?.queueDirectory??".testrelic/queue",b=e.getGitMetadata(),y=U(),w=jt(e),C=Pt(s,w,b,y,void 0,Ie());pe(h,a,"batch",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs`,"POST",C,{"Content-Type":"application/json"});}await e.dispose();}catch(f){g(f instanceof Error?f.message:"unexpected_upload_error");try{await e.dispose();}catch{}}return p}function to(e,t){return !e||t.size===0?e:e.map(r=>{let a=t.get(r.testId);return a?{...r,visual:a}:r})}function ro(e,t){if(t.size===0)return e;let r=e.timeline.map(a=>{let n=a.tests;if(!Array.isArray(n))return a;let s=false,o=n.map(i=>{let d=i.testId;if(!d)return i;let l=t.get(d);return l?(s=true,{...i,visual:l}):i});return s?{...a,tests:o}:a});return {...e,timeline:r}}function ao(e,t){if(t.size===0)return e;let r=e.timeline.map(a=>{let n=a.testId;if(!n)return a;let s=t.get(n);return s?{...a,...s.screenshotKey?{screenshotKey:s.screenshotKey}:{},...s.videoKey?{videoKey:s.videoKey}:{}}:a});return {...e,timeline:r}}var no=new Set(["batch","realtime","both"]),fe=Object.freeze({attempted:false,acknowledged:false,runId:null,endpoint:null,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:"cloud reporting was never initialised"});function so(e){switch(e){case "no_api_key":return "cloud mode off \u2014 no API key configured";case "cloud_unreachable":case "network_error":return "cloud endpoint unreachable \u2014 the run stayed local";case "invalid_api_key":return "API key rejected as invalid or revoked \u2014 the run stayed local";case "expired_api_key":return "API key has expired \u2014 the run stayed local";case "validation_error":return "API key format rejected \u2014 the run stayed local";case "rate_limited":return "rate limited during authentication \u2014 the run stayed local";case "auth_timeout":return "authentication timed out \u2014 the run stayed local";case "token_expired_no_refresh":case "token_refresh_failed":case "token_refresh_error":return "access token could not be refreshed \u2014 the run stayed local";case "init_error":return "cloud initialisation timed out \u2014 the run stayed local";case "unexpected_error":return "cloud initialisation failed \u2014 the run stayed local";default:return e?`cloud mode off (${e}) \u2014 the run stayed local`:"cloud mode off \u2014 the run stayed local"}}function Wa(e,t,r){if(!e)return fe;if(!e.isCloudMode())return {...fe,detail:so(e.getFailureReason())};let a=t??"batch";if(!no.has(a))return {...fe,detail:`upload strategy '${a}' is not recognised \u2014 nothing was sent`};let n=e.getEndpoint(),s=a==="realtime"||a==="both";return s&&r?{attempted:true,acknowledged:true,runId:r,endpoint:n,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:null}:{attempted:true,acknowledged:false,runId:null,endpoint:n,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:s?"run init failed \u2014 the platform did not acknowledge this run":`upload runs at the end of the run under the '${a}' strategy \u2014 not sent yet`}}function Wt(e,t,r){if(!e.attempted)return e;if(!t)return {...e,detail:e.acknowledged?"upload timed out before it completed \u2014 the run may be incomplete on the platform":"upload timed out before the platform acknowledged this run",acknowledged:e.acknowledged};let a=e.acknowledged||t.batchAcknowledged,n=e.runId??(t.batchAcknowledged?r:null),s=t.realtimeFinalizeAttempted?t.realtimeFinalized:t.batchAcknowledged,o=null;return a?s||(o="run acknowledged but not closed out \u2014 finalize failed and was queued for retry"):o=t.failureReason?`upload failed (${t.failureReason}) \u2014 queued locally for retry`:"upload failed \u2014 the platform did not acknowledge this run",{attempted:true,acknowledged:a,runId:n,endpoint:e.endpoint,finalized:s,artifactsUploaded:t.artifactsUploaded,artifactsTotal:t.artifactsTotal,detail:o}}function j(e){try{return fs$1.readFileSync(e,"utf-8").split(`
4295
+ `).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function fo(e){if(!e)return null;let t=e.split(`
4296
+ `).map(s=>s.trim()).filter(Boolean);if(t.length===0)return null;let r=t.filter(s=>!/^Error:\s*expect\(/.test(s));if(r.length===0)return t[0]??null;let a=r[0],n=r[1];return n!==void 0&&/^Received:/.test(n)&&/^Expected:/.test(a)?`${a} \xB7 ${n}`:a}function Jt(e){switch(e){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function go(e,t,r){let a=`${e}::${t}::${r}`;return crypto.createHash("sha256").update(a).digest("hex").substring(0,16)}function ho(e){return e.length<=3?"":e[e.length-2]}function mo(e){let t=e.findIndex(r=>r.status==="passed");return t>0?`passed on retry ${t}`:null}function en(e){return e===null?"error":e>=200&&e<300?"2xx":e>=300&&e<400?"3xx":e>=400&&e<500?"4xx":e>=500&&e<600?"5xx":"error"}function vo(e){let t={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},r=t;for(let a of e){let n=typeof a.responseStatusCode=="number"?a.responseStatusCode:null;r[en(n)]++;}return t}function Xa(e){if(e){for(let t of e)if(t.status==="failed")return {type:t.type,expected:Za(t.expected),actual:Za(t.actual),...t.expression?{expression:t.expression}:{}}}}function Za(e){if(e===void 0)return "undefined";if(e===null)return "null";let t;if(typeof e=="string")t=e;else try{t=JSON.stringify(e)??String(e);}catch{t=String(e);}return t.length>200?t.slice(0,200)+"\u2026":t}function Le(e,t){if(!e)return 0;let r=0;for(let a of e)a.status===t&&r++;return r}function tn(e,t){for(let r of e)t[r.category]=(t[r.category]??0)+1,r.children.length>0&&tn(r.children,t);}function bo(e){if(e.length===0)return null;let t=[...e].sort((a,n)=>a-n),r=t.reduce((a,n)=>a+n,0);return {avg:Math.round(r/t.length),min:t[0],max:t[t.length-1],p50:Y(t,50),p95:Y(t,95),p99:Y(t,99)}}var rn=2e5,De=1e5;function Qa(e,t,r,a,n,s,o){let i={retryIndex:e,apiCalls:t?.length??0,apiUrls:[],methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,assertions:r.length,navigations:a.length,navUrls:[],networkRequests:n,consoleLogs:s,actionSteps:o?.length??0,actionCategories:{}};if(t){let l=new Set;for(let c of t){let p=typeof c.method=="string"?c.method:"OTHER";i.methodCounts[p]=(i.methodCounts[p]??0)+1;let v=typeof c.url=="string"?c.url:null;v&&l.size<De&&l.add(St(v));let g=typeof c.responseStatusCode=="number"?c.responseStatusCode:typeof c.statusCode=="number"?c.statusCode:null,f=g!==null&&Number.isFinite(g)?g:null;i.statusRanges[en(f)]++;let m=typeof c.responseTimeMs=="number"?c.responseTimeMs:typeof c.durationMs=="number"?c.durationMs:null;m!==null&&Number.isFinite(m)&&i.responseTimes.length<rn&&i.responseTimes.push(m);}i.apiUrls=Array.from(l);}for(let l of r)l.status==="passed"?i.passedAssertions++:i.failedAssertions++;let d=new Set;for(let l of a)l.url&&d.size<De&&d.add(l.url);return i.navUrls=Array.from(d),o&&tn(o,i.actionCategories),i}function yo(){return {apiUrlSet:new Set,methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,navUrlSet:new Set,actionCategoryCounts:{},volApiCalls:0,volAssertions:0,volNavigations:0,volNetworkRequests:0,volConsoleLogs:0,volActionSteps:0}}function xo(e){return process.env.BROWSERSTACK_USERNAME?"BrowserStack":e?{"github-actions":"GitHub Actions","gitlab-ci":"GitLab CI",jenkins:"Jenkins",circleci:"CircleCI","bitbucket-pipelines":"Bitbucket Pipelines"}[e.provider]??"CI":"Local"}function wo(){let e=os$1.platform();return e==="win32"?"Windows":e==="darwin"?"macOS":"Linux"}function ko(e){let t=e.parent?.project?.()?.use;if(!t)return;let{browserName:r,channel:a}=t;if(a){let s=a.toLowerCase();return s==="chrome"||s==="chrome-stable"?"Chrome":s.startsWith("chrome-beta")?"Chrome Beta":s.startsWith("chrome-dev")?"Chrome Dev":s.startsWith("chrome-canary")?"Chrome Canary":s==="msedge"||s==="msedge-stable"?"Microsoft Edge":s.startsWith("msedge-beta")?"Edge Beta":s.startsWith("msedge-dev")?"Edge Dev":s.startsWith("msedge-canary")?"Edge Canary":a}if(r){let s=r.toLowerCase();return s==="chromium"?"Chromium":s==="firefox"?"Firefox":s==="webkit"?"WebKit":r}let n=t.defaultBrowserType;if(n){let s=n.toLowerCase();return s==="chromium"?"Chromium":s==="firefox"?"Firefox":s==="webkit"?"WebKit":n}}function So(e,t,r){let a=r.parent?.project?.(),n="unknown";a!==void 0&&(a.use.isMobile===true?n="mobile":n="e2e");let s=["e2e","api","unit","mobile"];for(let d of s)if(e.some(l=>l===`@${d}`||l===d))return d;let o=t.replace(/\\/g,"/"),i=["e2e","api","unit"];for(let d of i)if(o.includes(`/${d}/`))return d;return n}var Co="__testrelic_api_config";function To(e){return JSON.stringify(e,(t,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var Ne=class{constructor(t){this.rootDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.navigationsCaptured=false;this.memoryPressureWarned=false;this.testCount=0;this.cloudClient=null;this.cloudRunId=null;this.runTimestamp="";this.updatingSnapshots=false;this.cloudReceipt=fe;this.pendingArtifactEntries=[];this.detectedOs="";this.detectedSource="";this.cloudTestsBuffer=[];this.activeReportMode="embedded";this.streamingWriter=null;this.testIndex=[];this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0,visualChecks:0,visualFailures:0,visualDomChanges:0};this.streamingTestAgg=new Map;this.config=gr(t),this.apiConfig=fr(t);}upsertAggContribution(t,r){let a=this.streamingTestAgg.get(t);(!a||r.retryIndex>a.retryIndex)&&this.streamingTestAgg.set(t,r);}async onBegin(t,r){try{this.rootDir=t.rootDir;let a=t.updateSnapshots;if(this.updatingSnapshots=a==="all"||a==="changed",this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??crypto.randomUUID(),this.config.reportMode==="auto"){let i=r.allTests().length;this.activeReportMode=i>=this.config.streamingThreshold?"streaming":"embedded";}else this.activeReportMode=this.config.reportMode;let n=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${n} tests)
4297
+ `),this.activeReportMode==="streaming"){let i=path.dirname(this.config.outputPath);this.streamingWriter=new ie(i);let d=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let l={testRunId:this.testRunId??"",startedAt:this.startedAt,completedAt:new Date().toISOString(),totalDuration:Date.now()-new Date(this.startedAt).getTime(),...this.summaryCounters,metadata:null,reportMode:"streaming",files:[],enrichedSummary:null,validation:null,writeErrors:this.streamingWriter.getWriteErrors(),cloudUpload:this.cloudReceipt};this.streamingWriter.writeSummary(l);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let l=this.cloudClient.getAccessToken();l&&Bt(this.cloudClient.getEndpoint(),l,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",d),process.on("SIGINT",d);}if(this.config.includeArtifacts){let i=path.dirname(this.config.outputPath);this.runTimestamp=Jr(path.join(i,"artifacts"));try{ua(path.join(i,"artifacts"));}catch{}}let s=U();this.detectedOs=wo(),this.detectedSource=xo(s);let o=await J(async()=>(this.cloudClient=new _e(this.config.cloud),await this.cloudClient.initialize(),Ga(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource)),fa,"Cloud initialization");if(this.cloudRunId=o??null,o===void 0&&this.cloudClient?.switchToLocalMode("init_error"),this.cloudReceipt=Wa(this.cloudClient,this.config.cloud?.uploadStrategy,this.cloudRunId),this.activeReportMode!=="streaming"){let i=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let d=this.cloudClient.getAccessToken();d&&Bt(this.cloudClient.getEndpoint(),d,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",i),process.on("SIGINT",i);}}catch{}}onTestBegin(t,r){try{t.annotations.push({type:Co,description:To(this.apiConfig)});}catch{}}onTestEnd(t,r){try{let a=r,n=t.outcome(),s;n==="flaky"?s="flaky":n==="skipped"?s="skipped":s=Jt(a.status);let o=a.startTime.toISOString(),i=new Date(a.startTime.getTime()+a.duration).toISOString(),d=t.tags?[...t.tags]:t.annotations.filter(_=>_.type==="tag").map(_=>_.description??""),l=$a(a.attachments,t.annotations,t.title,s==="skipped");(l.navigations.length>0||l.networkRequestsCount>0||l.apiCallsCount>0)&&(this.fixtureDataReceived=!0),l.navigations.length>0&&(this.navigationsCaptured=!0),!this.config.captureNavigation&&l.navigations.length>0&&(l={...l,navigations:[]});let c=null;if(s==="failed"||s==="flaky"){let T=(s==="flaky"?t.results.find(F=>F.status!=="passed")?.errors??[]:a.errors)[0];if(T){let F=mr(this.config.redactPatterns),ae=T.location?.file??null,I=l.apiAssertions.find(an=>an.status==="failed")?.location??null,Z=I!==null&&(ae===null||path.resolve(ae)!==path.resolve(t.location.file)),Qt=Z?I.file:ae,Fe=Z?I.line:T.location?.line??null,ne=null;this.config.includeCodeSnippets&&Fe!==null&&Qt&&(ne=hr(Qt,Fe,this.config.codeContextLines),ne&&(ne=F(ne))),c={message:F(ke(T.message??"Unknown error")),line:Fe,code:ne,stack:this.config.includeStackTrace&&T.stack?F(ke(T.stack)):null};}}let p=t.titlePath().filter(Boolean),v=path.relative(this.rootDir||".",t.location.file).replace(/\\/g,"/"),g=ho(p),f=p.join(" > "),m=v,u=go(m,g,f),h=So(d,m,t),b=h!=="mobile"&&l.apiCallsCount>0?"api":h,y=n==="flaky",w=mo(t.results),C=Jt(t.expectedStatus),P=Jt(a.status),A=null;if(this.config.includeArtifacts&&s!=="skipped"&&a.attachments){let _=path.dirname(this.config.outputPath),T=p[p.length-1]??t.title;A=Xr(a.attachments,T,a.retry,_,this.runTimestamp||void 0,u);}let R=null;if(this.config.includeArtifacts&&s!=="skipped"&&a.attachments)try{let _=ta(a.attachments,{updatingSnapshots:this.updatingSnapshots,failureMessage:a.errors.map(T=>T.message??"").join(`
4298
+ `)});if(_.length>0){let T=path.dirname(this.config.outputPath),F=p[p.length-1]??t.title;R=Zr(_,F,a.retry,T,this.runTimestamp||void 0,u);}}catch{}let L=this.config.includeActionSteps&&a.steps?ya(a.steps,a.startTime):null,x=ko(t),S={titlePath:p,title:f,status:s,duration:a.duration,startedAt:o,completedAt:i,retryCount:t.results.length-1,retry:a.retry,tags:d,failure:c,specFile:v,navigations:l.navigations,testId:u,filePath:m,suiteName:g,testType:b,isFlaky:y,retryStatus:w,expectedStatus:C,actualStatus:P,artifacts:A,visual:R,apiAssertions:l.apiAssertions,actions:L,networkRequestsFile:l.networkRequestsFile,networkRequestsCount:l.networkRequestsCount,consoleLogsFile:l.consoleLogsFile,consoleLogsCount:l.consoleLogsCount,apiCallsFile:l.apiCallsFile,apiCallsCount:l.apiCallsCount,apiStatusMix:l.apiStatusMix,browser:x,os:this.detectedOs||void 0,source:this.detectedSource||void 0},X=l.consoleLogsFile&&l.consoleLogsCount>0?j(l.consoleLogsFile):void 0,G=l.networkRequestsFile&&l.networkRequestsCount>0?j(l.networkRequestsFile):void 0,re=l.apiCallsFile&&l.apiCallsCount>0?j(l.apiCallsFile):void 0,Yt=re?Lt(re):void 0,Xt=!G&&re?Dt(re):void 0,Zt=l.apiAssertions&&l.apiAssertions.length>0?Nt(l.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:u,title:f,status:s,duration:a.duration,suiteName:g,filePath:m,testType:b,isFlaky:y,startedAt:o,completedAt:i,tags:d,failure:c,retry:a.retry,retryCount:t.results.length-1,retryStatus:w,browser:x,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...L&&L.length>0?{actions:L}:{},...l.navigations&&l.navigations.length>0?{navigations:l.navigations}:{},...X?{consoleLogs:X}:{},...G?{networkRequests:G}:Xt?{networkRequests:Xt}:{},...Yt?{apiCalls:Yt}:{},...Zt?{protocolAssertions:Zt}:{},...R&&R.length>0?{visual:R}:{}});try{let _=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(_==="realtime"||_==="both")){let T=this.cloudClient.getAccessToken();T&&La(this.cloudClient.getEndpoint(),T,this.cloudRunId,this.buildCloudTestPayload(S));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let _=Be(m,p,t.id??"",a.retry),T=a.retry===t.results.length-1,F={id:_,navigations:l.navigations,apiAssertions:l.apiAssertions,actions:L??[],artifacts:A,visual:R,failureDiagnostic:c,hasNetworkFile:l.networkRequestsFile!==null,networkRequestsCount:l.networkRequestsCount,hasConsoleFile:l.consoleLogsFile!==null,consoleLogsCount:l.consoleLogsCount,hasApiCallsFile:l.apiCallsFile!==null,apiCallsCount:l.apiCallsCount,startedAt:o};this.streamingWriter.writeTestDetail(_,F,{networkRequestsFile:l.networkRequestsFile,consoleLogsFile:l.consoleLogsFile,apiCallsFile:l.apiCallsFile});let ae={id:_,title:p[p.length-1]??t.title,titlePath:p,filePath:m,status:s,duration:a.duration,project:p[1]??"",retryIndex:a.retry,tags:d,hasNetworkData:l.networkRequestsCount>0,hasConsoleData:l.consoleLogsCount>0,hasArtifacts:A!==null,hasActionSteps:(L?.length??0)>0,visualCount:R?.length??0,visualFailedCount:R?.filter(I=>I.status==="failed").length??0,domChangeCount:R?.reduce((I,Z)=>I+(Z.domChangeCount??0),0)??0,...(()=>{let I=R?.find(Z=>Z.diff);return I?.diff?{visualDiffPath:I.diff}:{}})(),errorMessage:fo(c?.message),networkCount:l.networkRequestsCount,consoleCount:l.consoleLogsCount,actionCount:L?.length??0,testType:b,apiCallCount:l.apiCallsCount,...l.apiStatusMix?{apiStatusMix:l.apiStatusMix}:{},assertionsPassed:Le(l.apiAssertions,"passed"),assertionsFailed:Le(l.apiAssertions,"failed"),...(()=>{let I=Xa(l.apiAssertions);return I?{firstFailedAssertion:I}:{}})(),isRetry:!T,retryGroupKey:Oe(m,p,t.id??"")};if(this.testIndex.push(ae),T)switch(this.summaryCounters.total++,s){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.upsertAggContribution(`${m}::${p.join(" > ")}`,Qa(a.retry,re,l.apiAssertions,l.navigations,l.networkRequestsCount,l.consoleLogsCount,L)),(A||R)&&this.pendingArtifactEntries.push({testId:u,artifacts:A??{},visual:R,outputDir:path.dirname(this.config.outputPath)}),S.actions=null,S.apiAssertions=null,S.navigations=[],S.artifacts=null,S.failure=null,S.networkRequestsFile=null,S.consoleLogsFile=null,S.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(S),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(t){try{let r=new Date().toISOString(),a=new Date(this.startedAt).getTime(),s=new Date(r).getTime()-a,o=this.activeReportMode==="streaming"?this.testIndex.some(d=>d.status!=="skipped"):this.collectedTests.some(d=>d.status!=="skipped");!this.fixtureDataReceived&&o&&process.stderr.write(`
4299
4299
  \u26A0 TestRelic: No fixture data received from any test.
4300
4300
  To enable network logs, video sync, and Test Navigation tracking, import the TestRelic fixture:
4301
4301
  import { test, expect } from '@testrelic/playwright-analytics/fixture';
4302
4302
  instead of:
4303
4303
  import { test, expect } from '@playwright/test';
4304
4304
 
4305
- `),this.config.captureNavigation?this.fixtureDataReceived&&!this.navigationsCaptured&&l&&process.stderr.write(`[testrelic] Test Navigation: 0 navigation events captured this run. Navigation is recorded automatically on page.goto()/clicks; if you expected a navigation graph, ensure your tests drive page navigations (and use the '@testrelic/playwright-analytics/fixture' import).
4305
+ `),this.config.captureNavigation?this.fixtureDataReceived&&!this.navigationsCaptured&&o&&process.stderr.write(`[testrelic] Test Navigation: 0 navigation events captured this run. Navigation is recorded automatically on page.goto()/clicks; if you expected a navigation graph, ensure your tests drive page navigations (and use the '@testrelic/playwright-analytics/fixture' import).
4306
4306
  `):process.stderr.write(`[testrelic] Test Navigation capture is disabled (captureNavigation: false). Remove the option or set it to true to capture the navigation graph.
4307
- `),await J(()=>Kr(),kt,"Artifact flush");let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let d=path.dirname(this.config.outputPath);i=la(d,this.runTimestamp);let o=path.join(d,"artifact-manifest.json"),c=JSON.stringify(i),p=o+".tmp";fs$1.writeFileSync(p,c,"utf-8"),fs$1.renameSync(p,o);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await J(()=>this.finalizeStreamingReport(r,s,t,i),wt,"Report finalization");else {let d=this.buildTimeline(),o=new Map;for(let g of this.collectedTests){let f=o.get(g.testId);(!f||g.retry>f.retry)&&o.set(g.testId,g);}let c=Array.from(o.values()),p=ba(c,d.length),v={schemaVersion:ze,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:s,summary:p,ci:U(),metadata:this.config.metadata,timeline:d,shardRunIds:null};if(this.writeReport(v),await J(()=>gt(v,this.config,i),kt,"HTML report write"),Ct(p,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient){let g=this.collectArtifactEntries(),f=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0;let m=await J(()=>Gt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,v,r,s,p,g,f),wt,"Cloud upload");this.cloudReceipt=Wt(this.cloudReceipt,m,this.testRunId);}}}catch{}finally{await this.disposeCloudClient();}}async disposeCloudClient(){let t=this.cloudClient;t&&(this.cloudClient=null,await J(()=>t.dispose(),ga,"Cloud client shutdown"));}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let t=path.dirname(this.config.outputPath),r=[];for(let a of this.collectedTests)(a.artifacts||a.visual)&&r.push({testId:a.testId,artifacts:a.artifacts??{},visual:a.visual,outputDir:t});return r}async finalizeStreamingReport(t,r,a,n){if(!this.streamingWriter)return;this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0,visualChecks:0,visualFailures:0,visualDomChanges:0};let s=new Map,l=new Map;for(let u of this.testIndex){let h=`${u.filePath}::${u.titlePath.join(" > ")}`,b=s.get(h);(b===void 0||u.retryIndex>b)&&s.set(h,u.retryIndex);}let i=0;for(let u of this.testIndex){let h=`${u.filePath}::${u.titlePath.join(" > ")}`,b=s.get(h);if(u.isRetry=u.retryIndex<b,u.isRetry)continue;switch(i++,this.summaryCounters.total++,u.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.summaryCounters.visualChecks+=u.visualCount??0,this.summaryCounters.visualFailures+=u.visualFailedCount??0,this.summaryCounters.visualDomChanges+=u.domChangeCount??0;let y=l.get(u.filePath);switch(y||(y={filePath:u.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},l.set(u.filePath,y)),y.total++,u.status){case "passed":y.passed++;break;case "failed":y.failed++;break;case "flaky":y.flaky++;break;case "skipped":y.skipped++;break;case "timedout":y.timedOut++;break}}let d=Array.from(l.values()),o=bo();for(let u of this.streamingTestAgg.values()){o.volApiCalls+=u.apiCalls,o.volAssertions+=u.assertions,o.volNavigations+=u.navigations,o.volNetworkRequests+=u.networkRequests,o.volConsoleLogs+=u.consoleLogs,o.volActionSteps+=u.actionSteps;for(let h in u.methodCounts)o.methodCounts[h]=(o.methodCounts[h]??0)+u.methodCounts[h];o.statusRanges["2xx"]+=u.statusRanges["2xx"],o.statusRanges["3xx"]+=u.statusRanges["3xx"],o.statusRanges["4xx"]+=u.statusRanges["4xx"],o.statusRanges["5xx"]+=u.statusRanges["5xx"],o.statusRanges.error+=u.statusRanges.error,o.passedAssertions+=u.passedAssertions,o.failedAssertions+=u.failedAssertions;for(let h in u.actionCategories)o.actionCategoryCounts[h]=(o.actionCategoryCounts[h]??0)+u.actionCategories[h];for(let h of u.apiUrls){if(o.apiUrlSet.size>=De)break;o.apiUrlSet.add(h);}for(let h of u.navUrls){if(o.navUrlSet.size>=De)break;o.navUrlSet.add(h);}for(let h of u.responseTimes){if(o.responseTimes.length>=rn)break;o.responseTimes.push(h);}}this.summaryCounters.totalApiCalls=o.volApiCalls,this.summaryCounters.totalAssertions=o.volAssertions,this.summaryCounters.totalNavigations=o.volNavigations,this.summaryCounters.totalNetworkRequests=o.volNetworkRequests,this.summaryCounters.totalConsoleLogs=o.volConsoleLogs,this.summaryCounters.totalActionSteps=o.volActionSteps,this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let c={reporterTotal:this.summaryCounters.total,indexTotal:i,playwrightStatus:a.status,isValid:this.summaryCounters.total===i};c.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${c.reporterTotal}, index: ${c.indexTotal}
4308
- `);let p={total:this.summaryCounters.total,passed:this.summaryCounters.passed,failed:this.summaryCounters.failed,flaky:this.summaryCounters.flaky,skipped:this.summaryCounters.skipped,timedout:this.summaryCounters.timedOut,totalApiCalls:this.summaryCounters.totalApiCalls,uniqueApiUrls:o.apiUrlSet.size,apiCallsByMethod:{...o.methodCounts},apiCallsByStatusRange:{"2xx":o.statusRanges["2xx"],"3xx":o.statusRanges["3xx"],"4xx":o.statusRanges["4xx"],"5xx":o.statusRanges["5xx"],error:o.statusRanges.error},apiResponseTime:vo(o.responseTimes),totalAssertions:this.summaryCounters.totalAssertions,passedAssertions:o.passedAssertions,failedAssertions:o.failedAssertions,totalNavigations:this.summaryCounters.totalNavigations,uniqueNavigationUrls:o.navUrlSet.size,totalTimelineSteps:i,totalActionSteps:this.summaryCounters.totalActionSteps,actionStepsByCategory:{...o.actionCategoryCounts},visualChecks:this.summaryCounters.visualChecks,visualFailures:this.summaryCounters.visualFailures,visualDomChanges:this.summaryCounters.visualDomChanges},v={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:t,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:d,enrichedSummary:p,validation:c,writeErrors:this.streamingWriter.getWriteErrors(),cloudUpload:this.cloudReceipt};this.streamingWriter.writeSummary(v);let g={schemaVersion:"2.0",generatedAt:new Date().toISOString(),reportMode:"streaming",summaryFile:"summary.json",indexFile:"index.json",testsDir:"tests",artifactsDir:"artifacts",testCount:this.testIndex.length,totalSizeBytes:this.streamingWriter.computeTotalSize()};this.streamingWriter.writeManifest(g),await gt(this.buildStreamingReport(v,p,t,r),this.config,n),Ct(p,this.config.outputPath,this.config.htmlReportPath,this.config.quiet);let f=this.streamingWriter.getReportDir();process.stderr.write(`[testrelic] Streaming report written to ${f}
4307
+ `),await J(()=>Kr(),kt,"Artifact flush");let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let d=path.dirname(this.config.outputPath);i=la(d,this.runTimestamp);let l=path.join(d,"artifact-manifest.json"),c=JSON.stringify(i),p=l+".tmp";fs$1.writeFileSync(p,c,"utf-8"),fs$1.renameSync(p,l);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await J(()=>this.finalizeStreamingReport(r,s,t,i),wt,"Report finalization");else {let d=this.buildTimeline(),l=new Map;for(let g of this.collectedTests){let f=l.get(g.testId);(!f||g.retry>f.retry)&&l.set(g.testId,g);}let c=Array.from(l.values()),p=ba(c,d.length),v={schemaVersion:ze,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:s,summary:p,ci:U(),metadata:this.config.metadata,timeline:d,shardRunIds:null};if(this.writeReport(v),await J(()=>gt(v,this.config,i),kt,"HTML report write"),Ct(p,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient){let g=this.collectArtifactEntries(),f=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0;let m=await J(()=>Gt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,v,r,s,p,g,f),wt,"Cloud upload");this.cloudReceipt=Wt(this.cloudReceipt,m,this.testRunId);}}}catch{}finally{await this.disposeCloudClient();}}async disposeCloudClient(){let t=this.cloudClient;t&&(this.cloudClient=null,await J(()=>t.dispose(),ga,"Cloud client shutdown"));}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let t=path.dirname(this.config.outputPath),r=[];for(let a of this.collectedTests)(a.artifacts||a.visual)&&r.push({testId:a.testId,artifacts:a.artifacts??{},visual:a.visual,outputDir:t});return r}async finalizeStreamingReport(t,r,a,n){if(!this.streamingWriter)return;this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0,visualChecks:0,visualFailures:0,visualDomChanges:0};let s=new Map,o=new Map;for(let u of this.testIndex){let h=`${u.filePath}::${u.titlePath.join(" > ")}`,b=s.get(h);(b===void 0||u.retryIndex>b)&&s.set(h,u.retryIndex);}let i=0;for(let u of this.testIndex){let h=`${u.filePath}::${u.titlePath.join(" > ")}`,b=s.get(h);if(u.isRetry=u.retryIndex<b,u.isRetry)continue;switch(i++,this.summaryCounters.total++,u.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.summaryCounters.visualChecks+=u.visualCount??0,this.summaryCounters.visualFailures+=u.visualFailedCount??0,this.summaryCounters.visualDomChanges+=u.domChangeCount??0;let y=o.get(u.filePath);switch(y||(y={filePath:u.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},o.set(u.filePath,y)),y.total++,u.status){case "passed":y.passed++;break;case "failed":y.failed++;break;case "flaky":y.flaky++;break;case "skipped":y.skipped++;break;case "timedout":y.timedOut++;break}}let d=Array.from(o.values()),l=yo();for(let u of this.streamingTestAgg.values()){l.volApiCalls+=u.apiCalls,l.volAssertions+=u.assertions,l.volNavigations+=u.navigations,l.volNetworkRequests+=u.networkRequests,l.volConsoleLogs+=u.consoleLogs,l.volActionSteps+=u.actionSteps;for(let h in u.methodCounts)l.methodCounts[h]=(l.methodCounts[h]??0)+u.methodCounts[h];l.statusRanges["2xx"]+=u.statusRanges["2xx"],l.statusRanges["3xx"]+=u.statusRanges["3xx"],l.statusRanges["4xx"]+=u.statusRanges["4xx"],l.statusRanges["5xx"]+=u.statusRanges["5xx"],l.statusRanges.error+=u.statusRanges.error,l.passedAssertions+=u.passedAssertions,l.failedAssertions+=u.failedAssertions;for(let h in u.actionCategories)l.actionCategoryCounts[h]=(l.actionCategoryCounts[h]??0)+u.actionCategories[h];for(let h of u.apiUrls){if(l.apiUrlSet.size>=De)break;l.apiUrlSet.add(h);}for(let h of u.navUrls){if(l.navUrlSet.size>=De)break;l.navUrlSet.add(h);}for(let h of u.responseTimes){if(l.responseTimes.length>=rn)break;l.responseTimes.push(h);}}this.summaryCounters.totalApiCalls=l.volApiCalls,this.summaryCounters.totalAssertions=l.volAssertions,this.summaryCounters.totalNavigations=l.volNavigations,this.summaryCounters.totalNetworkRequests=l.volNetworkRequests,this.summaryCounters.totalConsoleLogs=l.volConsoleLogs,this.summaryCounters.totalActionSteps=l.volActionSteps,this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let c={reporterTotal:this.summaryCounters.total,indexTotal:i,playwrightStatus:a.status,isValid:this.summaryCounters.total===i};c.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${c.reporterTotal}, index: ${c.indexTotal}
4308
+ `);let p={total:this.summaryCounters.total,passed:this.summaryCounters.passed,failed:this.summaryCounters.failed,flaky:this.summaryCounters.flaky,skipped:this.summaryCounters.skipped,timedout:this.summaryCounters.timedOut,totalApiCalls:this.summaryCounters.totalApiCalls,uniqueApiUrls:l.apiUrlSet.size,apiCallsByMethod:{...l.methodCounts},apiCallsByStatusRange:{"2xx":l.statusRanges["2xx"],"3xx":l.statusRanges["3xx"],"4xx":l.statusRanges["4xx"],"5xx":l.statusRanges["5xx"],error:l.statusRanges.error},apiResponseTime:bo(l.responseTimes),totalAssertions:this.summaryCounters.totalAssertions,passedAssertions:l.passedAssertions,failedAssertions:l.failedAssertions,totalNavigations:this.summaryCounters.totalNavigations,uniqueNavigationUrls:l.navUrlSet.size,totalTimelineSteps:i,totalActionSteps:this.summaryCounters.totalActionSteps,actionStepsByCategory:{...l.actionCategoryCounts},visualChecks:this.summaryCounters.visualChecks,visualFailures:this.summaryCounters.visualFailures,visualDomChanges:this.summaryCounters.visualDomChanges},v={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:t,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:d,enrichedSummary:p,validation:c,writeErrors:this.streamingWriter.getWriteErrors(),cloudUpload:this.cloudReceipt};this.streamingWriter.writeSummary(v);let g={schemaVersion:"2.0",generatedAt:new Date().toISOString(),reportMode:"streaming",summaryFile:"summary.json",indexFile:"index.json",testsDir:"tests",artifactsDir:"artifacts",testCount:this.testIndex.length,totalSizeBytes:this.streamingWriter.computeTotalSize()};this.streamingWriter.writeManifest(g),await gt(this.buildStreamingReport(v,p,t,r),this.config,n),Ct(p,this.config.outputPath,this.config.htmlReportPath,this.config.quiet);let f=this.streamingWriter.getReportDir();process.stderr.write(`[testrelic] Streaming report written to ${f}
4309
4309
  [testrelic] ${this.testIndex.length} test detail files on disk
4310
4310
  [testrelic] View report: npx testrelic serve ${f}
4311
4311
  `),this.streamingWriter.getWriteErrors().length>0&&process.stderr.write(`[testrelic] WARNING: ${this.streamingWriter.getWriteErrors().length} write error(s) during streaming
4312
4312
  `);let m=this.streamingWriter;try{if(this.cloudClient){let u=this.buildStreamingReport(v,p,t,r),h=this.collectArtifactEntries(),b=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0;let y=await Gt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,u,t,r,p,h,b);this.cloudReceipt=Wt(this.cloudReceipt,y,this.testRunId);let w={...v,cloudUpload:this.cloudReceipt};try{m.writeSummary(w);}catch{}}}finally{m.dispose();}this.testIndex.length=0,this.collectedTests.length=0,this.pendingArtifactEntries.length=0,this.cloudTestsBuffer.length=0,this.streamingWriter=null,this.cloudClient=null;}buildStreamingReport(t,r,a,n){return {schemaVersion:ze,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:a,totalDuration:n,summary:r,ci:U(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let t=process.memoryUsage(),r=t.heapUsed/1024/1024;if(r<200)return;let a=t.heapUsed/t.heapTotal;a>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
4313
4313
  `),this.switchToStreamingMode()):a>.8&&r>=500&&!this.memoryPressureWarned&&(this.memoryPressureWarned=!0,process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
4314
- `));}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let t=path.dirname(this.config.outputPath);this.streamingWriter=new ie(t);for(let r of this.collectedTests){let a=Be(r.filePath,r.titlePath,r.testId,r.retry),n=r.apiCallsFile&&r.apiCallsCount>0?j(r.apiCallsFile):void 0,s={id:a,navigations:r.navigations??[],apiAssertions:r.apiAssertions??[],actions:r.actions??[],artifacts:r.artifacts,failureDiagnostic:r.failure,hasNetworkFile:r.networkRequestsFile!==null,networkRequestsCount:r.networkRequestsCount,hasConsoleFile:r.consoleLogsFile!==null,consoleLogsCount:r.consoleLogsCount,hasApiCallsFile:r.apiCallsFile!==null,apiCallsCount:r.apiCallsCount,startedAt:r.startedAt};this.streamingWriter.writeTestDetail(a,s,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let l={id:a,title:r.titlePath[r.titlePath.length-1]??r.title,titlePath:r.titlePath,filePath:r.filePath,status:r.status,duration:r.duration,project:r.titlePath[1]??"",retryIndex:r.retry,tags:r.tags,hasNetworkData:r.networkRequestsCount>0,hasConsoleData:r.consoleLogsCount>0,hasArtifacts:r.artifacts!==null,hasActionSteps:(r.actions?.length??0)>0,errorMessage:r.failure?.message?.split(`
4315
- `)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,testType:r.testType,apiCallCount:r.apiCallsCount,...r.apiStatusMix?{apiStatusMix:r.apiStatusMix}:n?{apiStatusMix:mo(n)}:{},assertionsPassed:Le(r.apiAssertions,"passed"),assertionsFailed:Le(r.apiAssertions,"failed"),...(()=>{let i=Xa(r.apiAssertions);return i?{firstFailedAssertion:i}:{}})(),isRetry:!1,retryGroupKey:Oe(r.filePath,r.titlePath,r.testId)};switch(this.testIndex.push(l),this.summaryCounters.total++,r.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.upsertAggContribution(`${r.filePath}::${r.titlePath.join(" > ")}`,Qa(r.retry,n,r.apiAssertions??[],r.navigations??[],r.networkRequestsCount,r.consoleLogsCount,r.actions??null));}this.collectedTests.length=0;}catch{}}buildTimeline(){let t=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls:null,apiAssertions:r.apiAssertions,testId:r.testId,filePath:r.filePath,suiteName:r.suiteName,testType:r.testType,isFlaky:r.isFlaky,retryStatus:r.retryStatus,expectedStatus:r.expectedStatus,actualStatus:r.actualStatus,artifacts:r.artifacts,networkRequests:null,actions:r.actions,consoleLogs:null}));return va(t,{navigationTypes:this.config.navigationTypes})}readJsonlFile(t){if(!t)return null;let r=j(t);return r.length>0?r:null}toTestResult(t,r){let a=null,n=null,s=null;return r?.loadFiles&&(a=this.readJsonlFile(t.networkRequestsFile),n=this.readJsonlFile(t.consoleLogsFile),s=this.readJsonlFile(t.apiCallsFile)),{title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retryCount:t.retryCount,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,retryStatus:t.retryStatus,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,visual:t.visual,networkRequests:a,apiCalls:s,apiAssertions:t.apiAssertions,actions:t.actions??null,consoleLogs:n}}buildCloudTestPayload(t){let r={title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retry:t.retry,retryCount:t.retryCount,retryStatus:t.retryStatus,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,visual:t.visual??[],actions:t.actions??[],navigations:t.navigations??[],steps:t.actions??[],browser:t.browser,os:t.os,source:t.source};if(t.apiAssertions&&t.apiAssertions.length>0&&(r.protocolAssertions=Nt(t.apiAssertions)),t.consoleLogsFile&&(r.consoleLogs=j(t.consoleLogsFile)),t.networkRequestsFile&&(r.networkRequests=j(t.networkRequestsFile)),t.apiCallsFile){let a=j(t.apiCallsFile);r.apiCalls=Lt(a),(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=Dt(a));}return r}writeReport(t){try{let r=JSON.stringify(t),a=this.config.outputPath,n=path.dirname(a);fs$1.mkdirSync(n,{recursive:!0});let s=a+".tmp";fs$1.writeFileSync(s,r,"utf-8"),fs$1.renameSync(s,a);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
4314
+ `));}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let t=path.dirname(this.config.outputPath);this.streamingWriter=new ie(t);for(let r of this.collectedTests){let a=Be(r.filePath,r.titlePath,r.testId,r.retry),n=r.apiCallsFile&&r.apiCallsCount>0?j(r.apiCallsFile):void 0,s={id:a,navigations:r.navigations??[],apiAssertions:r.apiAssertions??[],actions:r.actions??[],artifacts:r.artifacts,failureDiagnostic:r.failure,hasNetworkFile:r.networkRequestsFile!==null,networkRequestsCount:r.networkRequestsCount,hasConsoleFile:r.consoleLogsFile!==null,consoleLogsCount:r.consoleLogsCount,hasApiCallsFile:r.apiCallsFile!==null,apiCallsCount:r.apiCallsCount,startedAt:r.startedAt};this.streamingWriter.writeTestDetail(a,s,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let o={id:a,title:r.titlePath[r.titlePath.length-1]??r.title,titlePath:r.titlePath,filePath:r.filePath,status:r.status,duration:r.duration,project:r.titlePath[1]??"",retryIndex:r.retry,tags:r.tags,hasNetworkData:r.networkRequestsCount>0,hasConsoleData:r.consoleLogsCount>0,hasArtifacts:r.artifacts!==null,hasActionSteps:(r.actions?.length??0)>0,errorMessage:r.failure?.message?.split(`
4315
+ `)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,testType:r.testType,apiCallCount:r.apiCallsCount,...r.apiStatusMix?{apiStatusMix:r.apiStatusMix}:n?{apiStatusMix:vo(n)}:{},assertionsPassed:Le(r.apiAssertions,"passed"),assertionsFailed:Le(r.apiAssertions,"failed"),...(()=>{let i=Xa(r.apiAssertions);return i?{firstFailedAssertion:i}:{}})(),isRetry:!1,retryGroupKey:Oe(r.filePath,r.titlePath,r.testId)};switch(this.testIndex.push(o),this.summaryCounters.total++,r.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.upsertAggContribution(`${r.filePath}::${r.titlePath.join(" > ")}`,Qa(r.retry,n,r.apiAssertions??[],r.navigations??[],r.networkRequestsCount,r.consoleLogsCount,r.actions??null));}this.collectedTests.length=0;}catch{}}buildTimeline(){let t=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls:null,apiAssertions:r.apiAssertions,testId:r.testId,filePath:r.filePath,suiteName:r.suiteName,testType:r.testType,isFlaky:r.isFlaky,retryStatus:r.retryStatus,expectedStatus:r.expectedStatus,actualStatus:r.actualStatus,artifacts:r.artifacts,networkRequests:null,actions:r.actions,consoleLogs:null}));return va(t,{navigationTypes:this.config.navigationTypes})}readJsonlFile(t){if(!t)return null;let r=j(t);return r.length>0?r:null}toTestResult(t,r){let a=null,n=null,s=null;return r?.loadFiles&&(a=this.readJsonlFile(t.networkRequestsFile),n=this.readJsonlFile(t.consoleLogsFile),s=this.readJsonlFile(t.apiCallsFile)),{title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retryCount:t.retryCount,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,retryStatus:t.retryStatus,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,visual:t.visual,networkRequests:a,apiCalls:s,apiAssertions:t.apiAssertions,actions:t.actions??null,consoleLogs:n}}buildCloudTestPayload(t){let r={title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retry:t.retry,retryCount:t.retryCount,retryStatus:t.retryStatus,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,visual:t.visual??[],actions:t.actions??[],navigations:t.navigations??[],steps:t.actions??[],browser:t.browser,os:t.os,source:t.source};if(t.apiAssertions&&t.apiAssertions.length>0&&(r.protocolAssertions=Nt(t.apiAssertions)),t.consoleLogsFile&&(r.consoleLogs=j(t.consoleLogsFile)),t.networkRequestsFile&&(r.networkRequests=j(t.networkRequestsFile)),t.apiCallsFile){let a=j(t.apiCallsFile);r.apiCalls=Lt(a),(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=Dt(a));}return r}writeReport(t){try{let r=JSON.stringify(t),a=this.config.outputPath,n=path.dirname(a);fs$1.mkdirSync(n,{recursive:!0});let s=a+".tmp";fs$1.writeFileSync(s,r,"utf-8"),fs$1.renameSync(s,a);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
4316
4316
  `);}}};module.exports=Ne;//# sourceMappingURL=reporter-entry.cjs.map
4317
4317
  //# sourceMappingURL=reporter-entry.cjs.map