@testrelic/playwright-analytics 2.12.0 → 2.12.1-next.107

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,10 +1,10 @@
1
- 'use strict';var crypto=require('crypto'),fs$1=require('fs'),path=require('path'),os=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 ts=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var ns=".testrelic-report";function Te(t,e,r,s){let n=`${t}|${e.join("|")}|${r}|${s}`;return crypto.createHash("sha256").update(n).digest("hex").substring(0,12)}var Y=class{constructor(e){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=path.join(e,ns),this.testsDir=path.join(this.reportDir,"tests"),fs$1.mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(e,r,s){try{let n=path.join(this.testsDir,e);fs$1.mkdirSync(n,{recursive:!0});let a=path.join(n,"meta.json"),o=a+".tmp",i=JSON.stringify(r);return fs$1.writeFileSync(o,i,"utf-8"),fs$1.renameSync(o,a),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),s?.networkRequestsFile&&this.moveFile(s.networkRequestsFile,path.join(n,"network.jsonl")),s?.consoleLogsFile&&this.moveFile(s.consoleLogsFile,path.join(n,"console.jsonl")),s?.apiCallsFile&&this.moveFile(s.apiCallsFile,path.join(n,"api-calls.jsonl")),!0}catch(n){let a=n instanceof Error?n.message:String(n);return this.writeErrors.push({testId:e,error:a,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${e}: ${a}
2
- `),false}}moveFile(e,r){try{fs$1.renameSync(e,r);}catch{try{let{copyFileSync:s}=ts("fs");s(e,r);try{fs$1.unlinkSync(e);}catch{}}catch(s){process.stderr.write(`[testrelic] Failed to move file ${e} \u2192 ${r}: ${s instanceof Error?s.message:String(s)}
3
- `);}}}writeIndex(e){let r=path.join(this.reportDir,"index.json"),s=r+".tmp",n=JSON.stringify(e);fs$1.writeFileSync(s,n,"utf-8"),fs$1.renameSync(s,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeCompactIndex(e){let r=path.join(this.reportDir,"index-compact.json"),s=r+".tmp",n=e.map(({titlePath:o,project:i,...d})=>d),a=JSON.stringify(n);fs$1.writeFileSync(s,a,"utf-8"),fs$1.renameSync(s,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}writeSummary(e){let r=path.join(this.reportDir,"summary.json"),s=r+".tmp",n=JSON.stringify(e);fs$1.writeFileSync(s,n,"utf-8"),fs$1.renameSync(s,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeManifest(e){let r=path.join(this.reportDir,"manifest.json"),s=r+".tmp",n=JSON.stringify(e);fs$1.writeFileSync(s,n,"utf-8"),fs$1.renameSync(s,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var At=".testrelic",cs="testrelic-config.json",us=".testrelic",ps=5,fs=new Set(["__proto__","constructor","prototype"]),Ct=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${At}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),gs={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function _t(t){let e=path.resolve(t);for(let r=0;r<=ps;r++){let s=path.join(e,At,cs);if(fs$1.existsSync(s))try{if(fs$1.statSync(s).isFile())return s}catch{}let n=path.join(e,us);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 a=path.dirname(e);if(a===e)break;e=a;}return null}function It(t){try{let e=fs$1.readFileSync(t,"utf-8"),r=JSON.parse(e);return typeof r!="object"||r===null||Array.isArray(r)||!Mt(r)?null:r}catch{return null}}function Mt(t){for(let e of Object.keys(t)){if(fs.has(e))return false;let r=t[e];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!Mt(r))return false}return true}function Lt(t){let e=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(t);if(e)return process.env[e[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(t);return r?process.env[r[1]]??null:t}function Se(t){let e=Object.create(null);for(let r of Object.keys(t)){let s=t[r];typeof s=="string"&&s.startsWith("$")?e[r]=Lt(s):typeof s=="object"&&s!==null&&!Array.isArray(s)?e[r]=Se(s):e[r]=s;}return e}function Rt(t){let e=/^(\d+)\s*([smhd])$/.exec(t.trim());if(!e)return null;let r=parseInt(e[1],10),s=e[2],n=gs[s];return !n||r<=0?null:r*n}function Et(t,e){let r=Object.create(null);if(Object.assign(r,Ct),t){let d=t.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.apiKey=="string"&&d.apiKey.length>0&&(r.apiKey=d.apiKey));let l=t["testrelic-repo"]??t.project;l&&typeof l=="object"&&typeof l.name=="string"&&(r.projectName=l.name),t.project&&!t["testrelic-repo"]&&process.stderr.write(`[testrelic] Deprecation: "project" key in config is deprecated. Rename it to "testrelic-repo".
5
- `);let u=t.queue;if(u&&typeof u=="object"){if(typeof u.maxAge=="string"){let g=Rt(u.maxAge);g!==null&&(r.queueMaxAge=g);}typeof u.directory=="string"&&(r.queueDirectory=u.directory);}}if(e){if(typeof e.apiKey=="string"&&e.apiKey.length>0){let d=e.apiKey.startsWith("$")?Lt(e.apiKey):e.apiKey;d&&(r.apiKey=d);}if(typeof e.endpoint=="string"&&(r.endpoint=e.endpoint),typeof e.upload=="string"&&(r.uploadStrategy=e.upload),typeof e.timeout=="number"&&(r.timeout=e.timeout),typeof e.projectName=="string"&&(r.projectName=e.projectName),typeof e.queueMaxAge=="string"){let d=Rt(e.queueMaxAge);d!==null&&(r.queueMaxAge=d);}typeof e.queueDirectory=="string"&&(r.queueDirectory=e.queueDirectory),typeof e.uploadArtifacts=="boolean"&&(r.uploadArtifacts=e.uploadArtifacts),typeof e.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=e.artifactMaxSizeMb);}let s=process.env.TESTRELIC_API_KEY;s&&s.length>0&&(r.apiKey=s);let n=process.env.TESTRELIC_CLOUD_ENDPOINT;n&&core.isValidEndpointUrl(n)&&(r.endpoint=n);let a=process.env.TESTRELIC_UPLOAD_STRATEGY;a&&["batch","realtime","both"].includes(a)&&(r.uploadStrategy=a);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:Ct}var ys=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],bs=["authorization","cookie","set-cookie","x-api-key"],xs=["password","secret","token","apiKey","api_key"];function Pt(t){let e=Object.create(null);return e.trackApiCalls=t?.trackApiCalls??true,e.captureRequestHeaders=t?.captureRequestHeaders??true,e.captureResponseHeaders=t?.captureResponseHeaders??true,e.captureRequestBody=t?.captureRequestBody??true,e.captureResponseBody=t?.captureResponseBody??true,e.captureAssertions=t?.captureAssertions??true,e.redactHeaders=t?.redactHeaders??[...bs],e.redactBodyFields=t?.redactBodyFields??[...xs],e.apiIncludeUrls=t?.apiIncludeUrls??[],e.apiExcludeUrls=t?.apiExcludeUrls??[],Object.freeze(e)}function Nt(t){if(t!==void 0&&!core.isValidConfig(t))throw core.createError(core.ErrorCode.CONFIG_INVALID,"Invalid reporter configuration");let e=Object.create(null);e.outputPath=t?.outputPath??"./test-results/analytics-timeline.json",e.includeStackTrace=t?.includeStackTrace??false,e.includeCodeSnippets=t?.includeCodeSnippets??true,e.codeContextLines=t?.codeContextLines??3,e.includeNetworkStats=t?.includeNetworkStats??true,e.captureNavigation=t?.captureNavigation??true,e.navigationTypes=t?.navigationTypes??null,e.redactPatterns=[...ys,...t?.redactPatterns??[]],e.testRunId=t?.testRunId??null,e.metadata=t?.metadata??null;let r=e.outputPath;e.openReport=t?.openReport??true,e.htmlReportPath=t?.htmlReportPath??r.replace(/\.json$/,".html"),e.includeArtifacts=t?.includeArtifacts??true,e.trackApiCalls=t?.trackApiCalls??true,e.quiet=t?.quiet??false,e.includeActionSteps=t?.includeActionSteps??true,e.captureConsoleLogs=t?.captureConsoleLogs??true;let s=_t(process.cwd()),n=s?It(s):null,a=n?Se(n):null,o=Et(a,t?.cloud);return e.cloud=o.apiKey?o:null,e.reportMode=t?.reportMode??"streaming",e.streamingThreshold=t?.streamingThreshold??0,Object.freeze(e)}var Ce="1.3.0";function Ft(t,e,r){try{let n=fs$1.readFileSync(t,"utf-8").split(`
1
+ 'use strict';var crypto=require('crypto'),fs$1=require('fs'),path=require('path'),os=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 ns=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var is=".testrelic-report";function Te(t,e,r,s){let n=`${t}|${e.join("|")}|${r}|${s}`;return crypto.createHash("sha256").update(n).digest("hex").substring(0,12)}function Se(t,e,r){let s=`${t}|${e.join("|")}|${r}`;return crypto.createHash("sha256").update(s).digest("hex").substring(0,12)}var Y=class{constructor(e){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=path.join(e,is),this.testsDir=path.join(this.reportDir,"tests"),fs$1.mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(e,r,s){try{let n=path.join(this.testsDir,e);fs$1.mkdirSync(n,{recursive:!0});let a=path.join(n,"meta.json"),o=a+".tmp",i=JSON.stringify(r);return fs$1.writeFileSync(o,i,"utf-8"),fs$1.renameSync(o,a),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),s?.networkRequestsFile&&this.moveFile(s.networkRequestsFile,path.join(n,"network.jsonl")),s?.consoleLogsFile&&this.moveFile(s.consoleLogsFile,path.join(n,"console.jsonl")),s?.apiCallsFile&&this.moveFile(s.apiCallsFile,path.join(n,"api-calls.jsonl")),!0}catch(n){let a=n instanceof Error?n.message:String(n);return this.writeErrors.push({testId:e,error:a,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${e}: ${a}
2
+ `),false}}moveFile(e,r){try{fs$1.renameSync(e,r);}catch{try{let{copyFileSync:s}=ns("fs");s(e,r);try{fs$1.unlinkSync(e);}catch{}}catch(s){process.stderr.write(`[testrelic] Failed to move file ${e} \u2192 ${r}: ${s instanceof Error?s.message:String(s)}
3
+ `);}}}writeIndex(e){let r=path.join(this.reportDir,"index.json"),s=r+".tmp",n=JSON.stringify(e);fs$1.writeFileSync(s,n,"utf-8"),fs$1.renameSync(s,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeCompactIndex(e){let r=path.join(this.reportDir,"index-compact.json"),s=r+".tmp",n=e.map(({titlePath:o,project:i,...d})=>d),a=JSON.stringify(n);fs$1.writeFileSync(s,a,"utf-8"),fs$1.renameSync(s,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}writeSummary(e){let r=path.join(this.reportDir,"summary.json"),s=r+".tmp",n=JSON.stringify(e);fs$1.writeFileSync(s,n,"utf-8"),fs$1.renameSync(s,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeManifest(e){let r=path.join(this.reportDir,"manifest.json"),s=r+".tmp",n=JSON.stringify(e);fs$1.writeFileSync(s,n,"utf-8"),fs$1.renameSync(s,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var _t=".testrelic",ps="testrelic-config.json",fs=".testrelic",gs=5,hs=new Set(["__proto__","constructor","prototype"]),At=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${_t}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),ms={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function Mt(t){let e=path.resolve(t);for(let r=0;r<=gs;r++){let s=path.join(e,_t,ps);if(fs$1.existsSync(s))try{if(fs$1.statSync(s).isFile())return s}catch{}let n=path.join(e,fs);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 a=path.dirname(e);if(a===e)break;e=a;}return null}function Lt(t){try{let e=fs$1.readFileSync(t,"utf-8"),r=JSON.parse(e);return typeof r!="object"||r===null||Array.isArray(r)||!Et(r)?null:r}catch{return null}}function Et(t){for(let e of Object.keys(t)){if(hs.has(e))return false;let r=t[e];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!Et(r))return false}return true}function Pt(t){let e=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(t);if(e)return process.env[e[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(t);return r?process.env[r[1]]??null:t}function Ce(t){let e=Object.create(null);for(let r of Object.keys(t)){let s=t[r];typeof s=="string"&&s.startsWith("$")?e[r]=Pt(s):typeof s=="object"&&s!==null&&!Array.isArray(s)?e[r]=Ce(s):e[r]=s;}return e}function It(t){let e=/^(\d+)\s*([smhd])$/.exec(t.trim());if(!e)return null;let r=parseInt(e[1],10),s=e[2],n=ms[s];return !n||r<=0?null:r*n}function Nt(t,e){let r=Object.create(null);if(Object.assign(r,At),t){let d=t.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.apiKey=="string"&&d.apiKey.length>0&&(r.apiKey=d.apiKey));let l=t["testrelic-repo"]??t.project;l&&typeof l=="object"&&typeof l.name=="string"&&(r.projectName=l.name),t.project&&!t["testrelic-repo"]&&process.stderr.write(`[testrelic] Deprecation: "project" key in config is deprecated. Rename it to "testrelic-repo".
5
+ `);let u=t.queue;if(u&&typeof u=="object"){if(typeof u.maxAge=="string"){let g=It(u.maxAge);g!==null&&(r.queueMaxAge=g);}typeof u.directory=="string"&&(r.queueDirectory=u.directory);}}if(e){if(typeof e.apiKey=="string"&&e.apiKey.length>0){let d=e.apiKey.startsWith("$")?Pt(e.apiKey):e.apiKey;d&&(r.apiKey=d);}if(typeof e.endpoint=="string"&&(r.endpoint=e.endpoint),typeof e.upload=="string"&&(r.uploadStrategy=e.upload),typeof e.timeout=="number"&&(r.timeout=e.timeout),typeof e.projectName=="string"&&(r.projectName=e.projectName),typeof e.queueMaxAge=="string"){let d=It(e.queueMaxAge);d!==null&&(r.queueMaxAge=d);}typeof e.queueDirectory=="string"&&(r.queueDirectory=e.queueDirectory),typeof e.uploadArtifacts=="boolean"&&(r.uploadArtifacts=e.uploadArtifacts),typeof e.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=e.artifactMaxSizeMb);}let s=process.env.TESTRELIC_API_KEY;s&&s.length>0&&(r.apiKey=s);let n=process.env.TESTRELIC_CLOUD_ENDPOINT;n&&core.isValidEndpointUrl(n)&&(r.endpoint=n);let a=process.env.TESTRELIC_UPLOAD_STRATEGY;a&&["batch","realtime","both"].includes(a)&&(r.uploadStrategy=a);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:At}var xs=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],ws=["authorization","cookie","set-cookie","x-api-key"],ks=["password","secret","token","apiKey","api_key"];function Ft(t){let e=Object.create(null);return e.trackApiCalls=t?.trackApiCalls??true,e.captureRequestHeaders=t?.captureRequestHeaders??true,e.captureResponseHeaders=t?.captureResponseHeaders??true,e.captureRequestBody=t?.captureRequestBody??true,e.captureResponseBody=t?.captureResponseBody??true,e.captureAssertions=t?.captureAssertions??true,e.redactHeaders=t?.redactHeaders??[...ws],e.redactBodyFields=t?.redactBodyFields??[...ks],e.apiIncludeUrls=t?.apiIncludeUrls??[],e.apiExcludeUrls=t?.apiExcludeUrls??[],Object.freeze(e)}function Dt(t){if(t!==void 0&&!core.isValidConfig(t))throw core.createError(core.ErrorCode.CONFIG_INVALID,"Invalid reporter configuration");let e=Object.create(null);e.outputPath=t?.outputPath??"./test-results/analytics-timeline.json",e.includeStackTrace=t?.includeStackTrace??false,e.includeCodeSnippets=t?.includeCodeSnippets??true,e.codeContextLines=t?.codeContextLines??3,e.includeNetworkStats=t?.includeNetworkStats??true,e.captureNavigation=t?.captureNavigation??true,e.navigationTypes=t?.navigationTypes??null,e.redactPatterns=[...xs,...t?.redactPatterns??[]],e.testRunId=t?.testRunId??null,e.metadata=t?.metadata??null;let r=e.outputPath;e.openReport=t?.openReport??true,e.htmlReportPath=t?.htmlReportPath??r.replace(/\.json$/,".html"),e.includeArtifacts=t?.includeArtifacts??true,e.trackApiCalls=t?.trackApiCalls??true,e.quiet=t?.quiet??false,e.includeActionSteps=t?.includeActionSteps??true,e.captureConsoleLogs=t?.captureConsoleLogs??true;let s=Mt(process.cwd()),n=s?Lt(s):null,a=n?Ce(n):null,o=Nt(a,t?.cloud);return e.cloud=o.apiKey?o:null,e.reportMode=t?.reportMode??"streaming",e.streamingThreshold=t?.streamingThreshold??0,Object.freeze(e)}var Re="1.3.0";function Bt(t,e,r){try{let n=fs$1.readFileSync(t,"utf-8").split(`
6
6
  `);if(e<1||e>n.length)return null;let a=Math.max(1,e-r),o=Math.min(n.length,e+r),i=[];for(let d=a;d<=o;d++){let l=d===e?">":" ",u=String(d).padStart(String(o).length," ");i.push(`${l} ${u} | ${n[d-1]}`);}return i.join(`
7
- `)}catch{return null}}function Dt(t){return e=>{let r=e;for(let s of t)if(typeof s=="string"){let n=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(n,"g"),"[REDACTED]");}else {let n=s.flags.includes("g")?s.flags:s.flags+"g",a=new RegExp(s.source,n);r=r.replace(a,"[REDACTED]");}return r}}function ks(t){return t.GITHUB_ACTIONS!=="true"?null:{provider:"github-actions",buildId:t.GITHUB_RUN_ID??null,commitSha:t.GITHUB_SHA??null,branch:t.GITHUB_REF_NAME??null,runUrl:t.GITHUB_SERVER_URL&&t.GITHUB_REPOSITORY&&t.GITHUB_RUN_ID?`${t.GITHUB_SERVER_URL}/${t.GITHUB_REPOSITORY}/actions/runs/${t.GITHUB_RUN_ID}`:null}}function Ts(t){return t.GITLAB_CI!=="true"?null:{provider:"gitlab-ci",buildId:t.CI_PIPELINE_ID??null,commitSha:t.CI_COMMIT_SHA??null,branch:t.CI_COMMIT_BRANCH??t.CI_COMMIT_REF_NAME??null,runUrl:t.CI_PIPELINE_URL??null}}function Ss(t){if(!t.JENKINS_URL)return null;let e=t.GIT_BRANCH??null;return e?.startsWith("origin/")&&(e=e.slice(7)),{provider:"jenkins",buildId:t.BUILD_ID??null,commitSha:t.GIT_COMMIT??null,branch:e,runUrl:t.BUILD_URL??null}}function Cs(t){return t.CIRCLECI!=="true"?null:{provider:"circleci",buildId:t.CIRCLE_BUILD_NUM??null,commitSha:t.CIRCLE_SHA1??null,branch:t.CIRCLE_BRANCH??null,runUrl:t.CIRCLE_BUILD_URL??null}}function Rs(t){if(!t.BITBUCKET_PIPELINE_UUID)return null;let e=t.BITBUCKET_WORKSPACE&&t.BITBUCKET_REPO_SLUG&&t.BITBUCKET_PIPELINE_UUID?`https://bitbucket.org/${t.BITBUCKET_WORKSPACE}/${t.BITBUCKET_REPO_SLUG}/pipelines/results/${t.BITBUCKET_PIPELINE_UUID}`:null;return {provider:"bitbucket-pipelines",buildId:t.BITBUCKET_BUILD_NUMBER??null,commitSha:t.BITBUCKET_COMMIT??null,branch:t.BITBUCKET_BRANCH??null,runUrl:e}}var As=[ks,Ts,Ss,Cs,Rs];function P(t){let e=process.env;for(let r of As){let s=r(e);if(s)return s}return null}var Re=`
7
+ `)}catch{return null}}function Ot(t){return e=>{let r=e;for(let s of t)if(typeof s=="string"){let n=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(n,"g"),"[REDACTED]");}else {let n=s.flags.includes("g")?s.flags:s.flags+"g",a=new RegExp(s.source,n);r=r.replace(a,"[REDACTED]");}return r}}function Ss(t){return t.GITHUB_ACTIONS!=="true"?null:{provider:"github-actions",buildId:t.GITHUB_RUN_ID??null,commitSha:t.GITHUB_SHA??null,branch:t.GITHUB_REF_NAME??null,runUrl:t.GITHUB_SERVER_URL&&t.GITHUB_REPOSITORY&&t.GITHUB_RUN_ID?`${t.GITHUB_SERVER_URL}/${t.GITHUB_REPOSITORY}/actions/runs/${t.GITHUB_RUN_ID}`:null}}function Cs(t){return t.GITLAB_CI!=="true"?null:{provider:"gitlab-ci",buildId:t.CI_PIPELINE_ID??null,commitSha:t.CI_COMMIT_SHA??null,branch:t.CI_COMMIT_BRANCH??t.CI_COMMIT_REF_NAME??null,runUrl:t.CI_PIPELINE_URL??null}}function Rs(t){if(!t.JENKINS_URL)return null;let e=t.GIT_BRANCH??null;return e?.startsWith("origin/")&&(e=e.slice(7)),{provider:"jenkins",buildId:t.BUILD_ID??null,commitSha:t.GIT_COMMIT??null,branch:e,runUrl:t.BUILD_URL??null}}function As(t){return t.CIRCLECI!=="true"?null:{provider:"circleci",buildId:t.CIRCLE_BUILD_NUM??null,commitSha:t.CIRCLE_SHA1??null,branch:t.CIRCLE_BRANCH??null,runUrl:t.CIRCLE_BUILD_URL??null}}function Is(t){if(!t.BITBUCKET_PIPELINE_UUID)return null;let e=t.BITBUCKET_WORKSPACE&&t.BITBUCKET_REPO_SLUG&&t.BITBUCKET_PIPELINE_UUID?`https://bitbucket.org/${t.BITBUCKET_WORKSPACE}/${t.BITBUCKET_REPO_SLUG}/pipelines/results/${t.BITBUCKET_PIPELINE_UUID}`:null;return {provider:"bitbucket-pipelines",buildId:t.BITBUCKET_BUILD_NUMBER??null,commitSha:t.BITBUCKET_COMMIT??null,branch:t.BITBUCKET_BRANCH??null,runUrl:e}}var _s=[Ss,Cs,Rs,As,Is];function P(t){let e=process.env;for(let r of _s){let s=r(e);if(s)return s}return null}var Ae=`
8
8
  /* Theme Variables */
9
9
  :root,[data-theme="dark"]{
10
10
  --bg:#0f1117;--bg-1:#161b22;--bg-2:#1c2128;--bg-3:#21262d;--bg-code:#13111c;
@@ -166,6 +166,12 @@ body{
166
166
  .test-row-arrow{color:var(--fg-2);flex-shrink:0;transition:color .15s}
167
167
  .test-row:hover .test-row-arrow{color:var(--fg-1)}
168
168
 
169
+ .test-row-retries{background:var(--bg-2);border-bottom:1px solid var(--bd-s)}
170
+ .test-row-retry-item{padding-left:42px;border-bottom:1px solid var(--bd-s)}
171
+ .test-row-retry-item:last-child{border-bottom:none}
172
+ .test-row-retry-item .test-row-title{font-size:13px;color:var(--fg-2);font-weight:400}
173
+ .test-row-retry-item .status-indicator{width:8px;height:8px}
174
+
169
175
  .no-tests{text-align:center;padding:48px 20px;color:var(--fg-2);font-size:14px}
170
176
 
171
177
  /* \u2500\u2500 Drawer Overlay \u2500\u2500 */
@@ -561,7 +567,7 @@ body{
561
567
  .detail-error .failure-message{margin-bottom:16px;padding:12px;background:rgba(239,68,68,0.06);border:1px solid rgba(239,68,68,0.15);border-radius:8px;font-size:12px;color:#f87171;text-align:left;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap;word-break:break-word}
562
568
  .detail-error code{font-size:11px;padding:2px 6px;background:var(--bg-2);border-radius:4px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
563
569
  .server-offline-banner{padding:8px 14px;background:rgba(251,191,36,0.08);border:1px solid rgba(251,191,36,0.2);border-radius:6px;font-size:11px;color:#fbbf24;text-align:center;margin-bottom:12px}
564
- `;var Ae=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 196 247" fill="none">
570
+ `;var Ie=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 196 247" fill="none">
565
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)"/>
566
572
  <defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
567
573
  <stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
@@ -569,7 +575,7 @@ body{
569
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)"/>
570
576
  <defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
571
577
  <stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
572
- </linearGradient></defs></svg>`;var Ie=`
578
+ </linearGradient></defs></svg>`;var Me=`
573
579
  /* \u2500\u2500 Utilities \u2500\u2500 */
574
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;')}
575
581
  function stripAnsi(s){return s?s.replace(/\\u001b\\[[0-9;]*m/g,'').replace(/\\x1b\\[[0-9;]*m/g,''):''}
@@ -617,26 +623,61 @@ body{
617
623
  return a.startedAt<b.startedAt?-1:1;
618
624
  });
619
625
 
620
- /* \u2500\u2500 Streaming mode: build tests from compact index \u2500\u2500 */
626
+ /* \u2500\u2500 Streaming mode: build tests from compact index, grouping retries under the final attempt \u2500\u2500 */
621
627
  if(data.reportMode==='streaming'&&data.index&&data.index.length>0){
622
628
  tests=[];testMap={};
629
+ var _retryGroups={};
623
630
  for(var xi=0;xi<data.index.length;xi++){
624
631
  var ix=data.index[xi];
625
- if(ix.isRetry)continue;
632
+ var gk=ix.retryGroupKey||ix.id;
633
+ if(!_retryGroups[gk])_retryGroups[gk]={final:null,attempts:[]};
634
+ if(ix.isRetry){_retryGroups[gk].attempts.push(ix);}
635
+ else{_retryGroups[gk].final=ix;}
636
+ }
637
+ for(var gk2 in _retryGroups){
638
+ if(!_retryGroups.hasOwnProperty(gk2))continue;
639
+ var grp=_retryGroups[gk2];
640
+ // Defensive: if every attempt in a group was marked isRetry (shouldn't happen),
641
+ // fall back to the highest retryIndex so the test still surfaces.
642
+ var final=grp.final;
643
+ if(!final&&grp.attempts.length>0){
644
+ final=grp.attempts.reduce(function(a,b){return b.retryIndex>a.retryIndex?b:a;});
645
+ grp.attempts=grp.attempts.filter(function(a){return a!==final;});
646
+ }
647
+ if(!final)continue;
648
+ var ix2=final;
626
649
  var st={
627
- testId:ix.id,title:ix.title,status:ix.status,duration:ix.duration,
628
- filePath:ix.filePath,tags:ix.tags||[],isFlaky:ix.status==='flaky',
629
- testType:'e2e',retryCount:0,suiteName:'',
650
+ testId:ix2.id,title:ix2.title,status:ix2.status,duration:ix2.duration,
651
+ filePath:ix2.filePath,tags:ix2.tags||[],isFlaky:ix2.status==='flaky',
652
+ testType:'e2e',retryCount:grp.attempts.length,suiteName:'',
630
653
  startedAt:'',completedAt:'',
631
654
  networkRequests:[],steps:[],apiCalls:[],actions:[],consoleLogs:[],
632
655
  artifacts:null,failure:null,retryStatus:null,expectedStatus:null,actualStatus:null,
633
- hasNetworkData:ix.hasNetworkData,hasConsoleData:ix.hasConsoleData,
634
- hasActionSteps:ix.hasActionSteps,hasArtifacts:ix.hasArtifacts,
635
- errorMessage:ix.errorMessage,networkCount:ix.networkCount||0,
636
- consoleCount:ix.consoleCount||0,actionCount:ix.actionCount||0
656
+ hasNetworkData:ix2.hasNetworkData,hasConsoleData:ix2.hasConsoleData,
657
+ hasActionSteps:ix2.hasActionSteps,hasArtifacts:ix2.hasArtifacts,
658
+ errorMessage:ix2.errorMessage,networkCount:ix2.networkCount||0,
659
+ consoleCount:ix2.consoleCount||0,actionCount:ix2.actionCount||0,
660
+ retryAttempts:grp.attempts.slice().sort(function(a,b){return a.retryIndex-b.retryIndex;}).map(function(a){
661
+ return {testId:a.id,retryIndex:a.retryIndex,status:a.status,duration:a.duration,errorMessage:a.errorMessage};
662
+ })
637
663
  };
638
664
  testMap[st.testId]=st;
639
665
  tests.push(st);
666
+ // Register each retry attempt in testMap too (keyed by its own id) so opening
667
+ // its drawer has a title/meta to merge with the fetched detail \u2014 it never
668
+ // appears in the grid itself, only as a nested row under the final attempt.
669
+ for(var ai=0;ai<st.retryAttempts.length;ai++){
670
+ var ra=st.retryAttempts[ai];
671
+ testMap[ra.testId]={
672
+ testId:ra.testId,title:st.title+' (attempt '+(ra.retryIndex+1)+')',status:ra.status,
673
+ duration:ra.duration,filePath:st.filePath,tags:st.tags,isFlaky:false,
674
+ testType:st.testType,retryCount:0,suiteName:'',startedAt:'',completedAt:'',
675
+ networkRequests:[],steps:[],apiCalls:[],actions:[],consoleLogs:[],
676
+ artifacts:null,failure:null,retryStatus:'attempt '+(ra.retryIndex+1)+' of '+(st.retryAttempts.length+1),
677
+ expectedStatus:null,actualStatus:null,errorMessage:ra.errorMessage,
678
+ networkCount:0,consoleCount:0,actionCount:0
679
+ };
680
+ }
640
681
  }
641
682
  tests.sort(function(a,b){
642
683
  if(a.filePath!==b.filePath)return a.filePath<b.filePath?-1:1;
@@ -745,6 +786,19 @@ body{
745
786
  h+='<span class="test-row-dur">'+fmtDur(t.duration)+'</span>';
746
787
  h+='<svg class="test-row-arrow" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 18l6-6-6-6"/></svg>';
747
788
  h+='</div>';
789
+ if(t.retryAttempts&&t.retryAttempts.length>0){
790
+ h+='<div class="test-row-retries">';
791
+ for(var ri=0;ri<t.retryAttempts.length;ri++){
792
+ var ra=t.retryAttempts[ri];
793
+ h+='<div class="test-row test-row-retry-item" data-testid="'+esc(ra.testId)+'">';
794
+ h+='<div class="status-indicator si-'+ra.status+'"></div>';
795
+ h+='<div class="test-row-info"><div class="test-row-title">Attempt '+(ra.retryIndex+1)+' &mdash; '+esc(ra.status)+(ra.errorMessage?': '+esc(ra.errorMessage):'')+'</div></div>';
796
+ h+='<span class="test-row-dur">'+fmtDur(ra.duration)+'</span>';
797
+ h+='<svg class="test-row-arrow" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 18l6-6-6-6"/></svg>';
798
+ h+='</div>';
799
+ }
800
+ h+='</div>';
801
+ }
748
802
  }
749
803
  h+='</div></div>';
750
804
  return h;
@@ -1000,7 +1054,7 @@ body{
1000
1054
  clearTimeout(_searchTimer);
1001
1055
  _searchTimer=setTimeout(function(){searchQuery=q;applyFilters();},150);
1002
1056
  }
1003
- `;var Me=`
1057
+ `;var Le=`
1004
1058
  /* \u2500\u2500 Network Visualization Helpers \u2500\u2500 */
1005
1059
  var RES_COLORS={xhr:'#60a5fa',document:'#818cf8',script:'#fbbf24',stylesheet:'#a78bfa',image:'#34d399',font:'#f472b6',other:'#6b7280'};
1006
1060
  var RES_LABELS={xhr:'XHR',document:'Doc',script:'JS',stylesheet:'CSS',image:'Img',font:'Font',other:'Other'};
@@ -1631,7 +1685,7 @@ body{
1631
1685
  var countEl=ndt.querySelector('.ndt-count');
1632
1686
  if(countEl)countEl.textContent=visible+' / '+rows.length+' requests';
1633
1687
  }
1634
- `;var Le=`
1688
+ `;var Ee=`
1635
1689
  var _filterState={status:{},type:{},specFile:{}};
1636
1690
  var _totalTests=0;
1637
1691
  var _originalSummary=null;
@@ -1802,7 +1856,7 @@ function _updateCard(cls,val){
1802
1856
  var el=document.querySelector('.'+cls+' .s-count');
1803
1857
  if(el)el.textContent=''+val;
1804
1858
  }
1805
- `;var Ee=`
1859
+ `;var Pe=`
1806
1860
  /* \u2500\u2500 Event Delegation \u2500\u2500 */
1807
1861
  document.addEventListener('click',function(e){
1808
1862
  var target=e.target;
@@ -2072,7 +2126,7 @@ function _updateCard(cls,val){
2072
2126
  var d=document.getElementById('filter-drawer');if(d)d.classList.remove('open');
2073
2127
  var b=document.getElementById('filter-drawer-backdrop');if(b)b.classList.remove('open');
2074
2128
  }
2075
- `;var Pe=`
2129
+ `;var Ne=`
2076
2130
  /* \u2500\u2500 Category badge helpers \u2500\u2500 */
2077
2131
  function actionBadgeClass(cat){
2078
2132
  if(cat==='assertion')return 'action-badge-assertion';
@@ -2118,7 +2172,7 @@ function _updateCard(cls,val){
2118
2172
  h+='</div>';
2119
2173
  return h;
2120
2174
  }
2121
- `;var Ne=`
2175
+ `;var Fe=`
2122
2176
  /* \u2500\u2500 Console Log Level Colors & Labels \u2500\u2500 */
2123
2177
  var LOG_COLORS={log:'#9ca3af',warn:'#fbbf24',error:'#f87171',info:'#60a5fa',debug:'#a78bfa',stdout:'#9ca3af',stderr:'#f87171'};
2124
2178
  var LOG_LABELS={log:'LOG',warn:'WARN',error:'ERR',info:'INFO',debug:'DBG',stdout:'OUT',stderr:'ERR'};
@@ -2305,7 +2359,7 @@ function _updateCard(cls,val){
2305
2359
  }
2306
2360
  return h;
2307
2361
  }
2308
- `;var Fe=`
2362
+ `;var De=`
2309
2363
  /* \u2500\u2500 Artifact Utilities \u2500\u2500 */
2310
2364
  function formatBytes(bytes){
2311
2365
  if(bytes===0)return '0 B';
@@ -2314,16 +2368,16 @@ function _updateCard(cls,val){
2314
2368
  if(i>=sizes.length)i=sizes.length-1;
2315
2369
  return parseFloat((bytes/Math.pow(k,i)).toFixed(1))+' '+sizes[i];
2316
2370
  }
2317
- `;var _s=`
2371
+ `;var Ms=`
2318
2372
  (function(){
2319
2373
  var data=JSON.parse(document.getElementById('report-data').textContent);
2320
- ${Ie}
2321
- ${Pe}
2322
- ${Ne}
2323
2374
  ${Me}
2324
- ${Le}
2375
+ ${Ne}
2325
2376
  ${Fe}
2377
+ ${Le}
2326
2378
  ${Ee}
2379
+ ${De}
2380
+ ${Pe}
2327
2381
  applyTheme();
2328
2382
  renderRunMeta();
2329
2383
  renderSummary();
@@ -2331,7 +2385,7 @@ function _updateCard(cls,val){
2331
2385
  renderFilterBar();
2332
2386
  renderTestGrid();
2333
2387
  var _lo=document.getElementById('loading-overlay');if(_lo)_lo.remove();
2334
- })();`;function Bt(t,e,r){let s=t.replace(/<\//g,"<\\/"),n=r?r.replace(/<\//g,"<\\/"):null;return `<!-- TestRelic AI Analytics Report \u2014 self-contained, no external dependencies -->
2388
+ })();`;function qt(t,e,r){let s=t.replace(/<\//g,"<\\/"),n=r?r.replace(/<\//g,"<\\/"):null;return `<!-- TestRelic AI Analytics Report \u2014 self-contained, no external dependencies -->
2335
2389
  <!DOCTYPE html>
2336
2390
  <html lang="en" data-theme="">
2337
2391
  <head>
@@ -2340,8 +2394,8 @@ function _updateCard(cls,val){
2340
2394
  <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: blob: 'self'; media-src blob: 'self'; connect-src 'self' http://127.0.0.1:*;">
2341
2395
  <title>TestRelic AI Analytics Report</title>
2342
2396
  ${""}
2343
- <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Ae).toString("base64")}">
2344
- <style>${Re}</style>
2397
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Ie).toString("base64")}">
2398
+ <style>${Ae}</style>
2345
2399
  <script>(function(){var p=localStorage.getItem('tr-theme')||'system';var t=p==='system'?(window.matchMedia('(prefers-color-scheme:light)').matches?'light':'dark'):p;document.documentElement.setAttribute('data-theme',t);})()</script>
2346
2400
  </head>
2347
2401
  <body>
@@ -2385,9 +2439,9 @@ ${""}
2385
2439
  </aside>
2386
2440
  <script id="report-data" type="application/json">${s}</script>
2387
2441
  ${n?`<script id="artifact-manifest-data" type="application/json">${n}</script>`:""}
2388
- <script>${_s}</script>
2442
+ <script>${Ms}</script>
2389
2443
  </body>
2390
- </html>`}function De(t,e,r,s){let n=t.replace(/<\//g,"<\\/"),a=e.replace(/<\//g,"<\\/"),o=s?s.replace(/<\//g,"<\\/"):null,i={};try{i=JSON.parse(t);}catch{}let d=`{
2444
+ </html>`}function Be(t,e,r,s){let n=t.replace(/<\//g,"<\\/"),a=e.replace(/<\//g,"<\\/"),o=s?s.replace(/<\//g,"<\\/"):null,i={};try{i=JSON.parse(t);}catch{}let d=`{
2391
2445
  "schemaVersion":"2.0",
2392
2446
  "reportMode":"streaming",
2393
2447
  "serverPort":${r??"null"},
@@ -2471,13 +2525,13 @@ ${n?`<script id="artifact-manifest-data" type="application/json">${n}</script>`:
2471
2525
  window.__trServerPort=_serverPort;
2472
2526
  window.__trIsStreaming=true;
2473
2527
 
2474
- ${Ie}
2475
- ${Pe}
2476
- ${Ne}
2477
2528
  ${Me}
2478
- ${Le}
2529
+ ${Ne}
2479
2530
  ${Fe}
2531
+ ${Le}
2480
2532
  ${Ee}
2533
+ ${De}
2534
+ ${Pe}
2481
2535
  applyTheme();
2482
2536
  renderRunMeta();
2483
2537
  renderSummary();
@@ -2496,8 +2550,8 @@ ${n?`<script id="artifact-manifest-data" type="application/json">${n}</script>`:
2496
2550
  <title>TestRelic AI Analytics Report</title>
2497
2551
  ${r?`<meta name="report-server-port" content="${r}">`:""}
2498
2552
  ${r?`<meta name="artifact-server-port" content="${r}">`:""}
2499
- <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Ae).toString("base64")}">
2500
- <style>${Re}</style>
2553
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Ie).toString("base64")}">
2554
+ <style>${Ae}</style>
2501
2555
  <script>(function(){var p=localStorage.getItem('tr-theme')||'system';var t=p==='system'?(window.matchMedia('(prefers-color-scheme:light)').matches?'light':'dark'):p;document.documentElement.setAttribute('data-theme',t);})()</script>
2502
2556
  </head>
2503
2557
  <body>
@@ -2543,55 +2597,55 @@ ${r?`<meta name="artifact-server-port" content="${r}">`:""}
2543
2597
  ${o?`<script id="artifact-manifest-data" type="application/json">${o}</script>`:""}
2544
2598
  <script>${l}</script>
2545
2599
  </body>
2546
- </html>`}function Be(t){try{let e=process.platform,r,s;e==="darwin"?(r="open",s=[t]):e==="win32"?(r="cmd",s=["/c","start","",t]):(r="xdg-open",s=[t]),child_process.execFile(r,s,n=>{n&&process.stderr.write(`[testrelic] Failed to open browser: ${n.message}
2547
- `);});}catch{}}path.join(os.tmpdir(),"testrelic-data");async function Ot(t,e,r,s){let n=(e-1)*r,a=[],o=0,i=readline.createInterface({input:fs$1.createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let u of i)if(u.length!==0){if(o>=n&&a.length<r)try{a.push(JSON.parse(u));}catch{}if(o++,a.length>=r&&s!==void 0)break}let d=s??o,l=Math.max(1,Math.ceil(d/r));return {items:a,total:d,page:e,pageSize:r,totalPages:l}}var Ut=/^[a-f0-9]{12}$/,Oe=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,$t=500;function b(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function zt(t){t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type");}function ie(t){try{return fs$1.existsSync(t)?JSON.parse(fs$1.readFileSync(t,"utf-8")):null}catch{return null}}function oe(t){let e=0;try{let r=fs$1.readdirSync(t,{withFileTypes:!0});for(let s of r){let n=path.join(t,s.name);s.isFile()?e+=fs$1.statSync(n).size:s.isDirectory()&&(e+=oe(n));}}catch{}return e}function jt(t,e,r,s){let n=ie(path.join(r,"index.json"));b(e,200,{status:"ok",reportMode:"streaming",testCount:n?.length??0,uptime:Math.floor((Date.now()-s)/1e3)});}function Vt(t,e,r){let s=ie(path.join(r,"summary.json"));if(!s){b(e,404,{error:"Summary not found"});return}b(e,200,s);}function Gt(t,e,r){let s=ie(path.join(r,"index.json"));if(!s){b(e,404,{error:"Test index not found"});return}let a=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,o=Math.max(1,parseInt(a.get("page")??"1",10)||1),i=Math.min($t,Math.max(1,parseInt(a.get("pageSize")??"100",10)||100)),d=a.get("status")?.split(",").filter(Boolean)??null,l=a.get("file")??null,u=a.get("search")?.toLowerCase()??null,g=a.get("tag")?.split(",").filter(Boolean)??null,m=a.get("sort")??"file",p=a.get("order")==="desc"?-1:1,f=s;d&&d.length>0&&(f=f.filter(x=>d.includes(x.status))),l&&(f=f.filter(x=>x.filePath===l||x.filePath.startsWith(l+"/"))),u&&(f=f.filter(x=>x.title.toLowerCase().includes(u)||x.filePath.toLowerCase().includes(u))),g&&g.length>0&&(f=f.filter(x=>g.some(T=>x.tags.includes(T)))),f=[...f].sort((x,T)=>{let M=0;switch(m){case "duration":M=x.duration-T.duration;break;case "status":M=x.status.localeCompare(T.status);break;case "title":M=x.title.localeCompare(T.title);break;default:M=x.filePath.localeCompare(T.filePath);break}return M*p});let c=f.length,h=Math.max(1,Math.ceil(c/i)),v=(o-1)*i,w=f.slice(v,v+i);b(e,200,{tests:w,pagination:{page:o,pageSize:i,totalItems:c,totalPages:h},filters:{status:d,file:l,search:u,tag:g}});}function Wt(t,e,r,s){if(!Ut.test(s)){b(e,400,{error:"Invalid test ID format"});return}let n=path.join(r,"tests",s,"meta.json"),a=path.join(r,"tests",`${s}.json`),o=fs$1.existsSync(n)?n:fs$1.existsSync(a)?a:null;if(!o){b(e,404,{error:`Test not found: ${s}`});return}try{let i=fs$1.readFileSync(o,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(i);}catch(i){b(e,500,{error:i instanceof Error?i.message:String(i)});}}async function Kt(t,e,r,s,n){if(!Ut.test(s)){b(e,400,{error:"Invalid test ID format"});return}let o=path.join(r,"tests",s,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[n]);if(!fs$1.existsSync(o)){b(e,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let d=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,l=Math.max(1,parseInt(d.get("page")??"1",10)||1),u=Math.min($t,Math.max(1,parseInt(d.get("pageSize")??"50",10)||50)),g,m=path.join(r,"tests",s,"meta.json");if(fs$1.existsSync(m))try{let f=JSON.parse(fs$1.readFileSync(m,"utf-8"));switch(n){case "network":g=f.networkRequestsCount;break;case "console":g=f.consoleLogsCount;break;case "api-calls":g=f.apiCallsCount;break}}catch{}let p=await Ot(o,l,u,g);b(e,200,p);}catch(i){b(e,500,{error:i instanceof Error?i.message:String(i)});}}function Jt(t,e,r){let s=ie(path.join(r,"index.json"));if(!s){b(e,404,{error:"Test index not found"});return}let n=new Map;for(let o of s){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 a=Array.from(n.entries()).map(([o,i])=>({filePath:o,...i})).sort((o,i)=>o.filePath.localeCompare(i.filePath));b(e,200,{files:a});}function Yt(t,e,r){if(!fs$1.existsSync(r)){b(e,200,{runs:[],totalSizeBytes:0});return}try{let s=[],n=0,a=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!Oe.test(o.name))continue;let i=path.join(r,o.name),d=oe(i),l=fs$1.readdirSync(i,{withFileTypes:!0}).filter(u=>u.isDirectory());s.push({folderName:o.name,totalSizeBytes:d,testCount:l.length}),n+=d;}s.sort((o,i)=>i.folderName.localeCompare(o.folderName)),b(e,200,{runs:s,totalSizeBytes:n});}catch(s){b(e,500,{error:s instanceof Error?s.message:String(s)});}}function Zt(t,e,r){try{let s=0,n=0;if(fs$1.existsSync(r)){let a=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!Oe.test(o.name))continue;let i=path.join(r,o.name),d=oe(i);fs$1.rmSync(i,{recursive:!0,force:!0}),n+=d,s++;}}b(e,200,{deletedCount:s,freedBytes:n});}catch(s){b(e,500,{error:s instanceof Error?s.message:String(s)});}}function Qt(t,e,r,s){if(!Oe.test(s)){b(e,400,{error:"Invalid folder name"});return}let n=path.join(r,s);try{if(!fs$1.statSync(n).isDirectory()){b(e,404,{error:"Not found"});return}}catch{b(e,404,{error:"Not found"});return}try{let a=oe(n);fs$1.rmSync(n,{recursive:!0,force:!0}),b(e,200,{deleted:s,freedBytes:a});}catch(a){b(e,500,{error:a instanceof Error?a.message:String(a)});}}function Xt(t,e,r){b(e,200,{status:"shutting_down"}),r.close();}function qe(t,e,r){if(!fs$1.existsSync(r)){b(e,404,{error:"File not found"});return}try{let s=fs$1.readFileSync(r),n=path.extname(r).toLowerCase(),a=Fs[n]??"application/octet-stream";e.writeHead(200,{"Content-Type":a}),e.end(s);}catch(s){b(e,500,{error:s instanceof Error?s.message:String(s)});}}var Fs={".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 qs=9323,Hs=10,Us=1800*1e3;function Z(t,e){return new Promise((r,s)=>{let n=e?.port??qs,a=Date.now(),o,i=0,d=fs$1.existsSync(path.join(t,"artifacts"))?path.join(t,"artifacts"):fs$1.existsSync(path.join(t,"..","artifacts"))?path.join(t,"..","artifacts"):path.join(t,"artifacts");function l(){clearTimeout(o),o=setTimeout(()=>{g.close();},Us);}let u=e?.htmlPath??null;if(!u){let p=path.dirname(t);try{let f=fs$1.readdirSync(p).find(c=>c.endsWith(".html"));f&&(u=path.join(p,f));}catch{}}let g=http.createServer((p,f)=>{if(l(),zt(f),p.method==="OPTIONS"){f.writeHead(204),f.end();return}let c;try{c=new URL(p.url??"/",`http://${p.headers.host??"localhost"}`).pathname;}catch{b(f,400,{error:"Invalid URL"});return}if(p.method==="GET"&&(c==="/"||c==="/index.html")){if(u&&fs$1.existsSync(u)){qe(p,f,u);return}b(f,404,{error:"HTML report not found"});return}if(p.method==="GET"&&c==="/api/health"){jt(p,f,t,a);return}if(p.method==="GET"&&c==="/api/summary"){Vt(p,f,t);return}if(p.method==="GET"&&c==="/api/tests"){Gt(p,f,t);return}if(p.method==="GET"&&c==="/api/files"){Jt(p,f,t);return}let h=c.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(p.method==="GET"&&h){Kt(p,f,t,h[1],h[2]);return}let v=c.match(/^\/api\/tests\/([a-f0-9]+)$/);if(p.method==="GET"&&v){Wt(p,f,t,v[1]);return}if(p.method==="GET"&&c==="/api/artifacts"){Yt(p,f,d);return}if(p.method==="DELETE"&&c==="/api/artifacts"){Zt(p,f,d);return}let w=c.match(/^\/api\/artifacts\/(.+)$/);if(p.method==="DELETE"&&w){Qt(p,f,d,decodeURIComponent(w[1]));return}if(p.method==="GET"&&c.startsWith("/artifacts/")){let x=decodeURIComponent(c.slice(11));if(x.includes("..")||x.includes("\0")){b(f,400,{error:"Invalid path"});return}qe(p,f,path.join(d,x));return}if(p.method==="POST"&&c==="/api/shutdown"){Xt(p,f,g);return}b(f,404,{error:"Not found"});});function m(p){let f=c=>{c.code==="EADDRINUSE"&&i<Hs?(i++,m(p+1)):s(c);};g.once("error",f),g.listen(p,"127.0.0.1",()=>{g.removeListener("error",f);let c=g.address();if(!c||typeof c=="string"){s(new Error("Failed to get server address"));return}l(),r({port:c.port,dispose:()=>new Promise(h=>{clearTimeout(o),g.close(()=>h());})});});}m(n);})}async function er(t){let e=await Z(t);return {port:e.port,dispose:e.dispose}}function js(t,e,r){let s=JSON.stringify(t),n=r?JSON.stringify(r):null;return Bt(s,e,n)}async function Ue(t,e,r){try{let s=null,n=null,a=e.reportMode==="streaming"||e.reportMode==="auto"&&t.timeline.length===0&&t.summary.total>=e.streamingThreshold,o,i=e.htmlReportPath,d=path.dirname(i);fs$1.mkdirSync(d,{recursive:!0});let l="",u="[]",g=null;if(a){l=JSON.stringify({...t.summary,testRunId:t.testRunId,startedAt:t.startedAt,completedAt:t.completedAt,totalDuration:t.totalDuration,ci:t.ci,metadata:t.metadata,shardRunIds:t.shardRunIds});let p=path.dirname(e.outputPath),f=path.join(p,".testrelic-report");try{let c=path.join(f,"index-compact.json"),h=path.join(f,"index.json");fs$1.existsSync(c)?u=fs$1.readFileSync(c,"utf-8"):fs$1.existsSync(h)&&(u=fs$1.readFileSync(h,"utf-8"));}catch{}g=r?JSON.stringify(r):null,o=De(l,u,null,g);}else o=js(t,null,r);let m=i+".tmp";if(fs$1.writeFileSync(m,o,"utf-8"),fs$1.renameSync(m,i),a){if(t.ci===null){let p=path.dirname(e.outputPath),f=path.join(p,".testrelic-report"),c=path.resolve(i);try{if(await Gs(),s=await Ws(f),!s){n=await Z(f,{htmlPath:c}),s=n.port;let h=setInterval(()=>{},6e4),v=()=>{clearInterval(h),n?.dispose();};process.on("SIGINT",v),process.on("SIGTERM",v),setTimeout(v,1800*1e3).unref();}if(s){process.stderr.write(`
2600
+ </html>`}function Oe(t){try{let e=process.platform,r,s;e==="darwin"?(r="open",s=[t]):e==="win32"?(r="cmd",s=["/c","start","",t]):(r="xdg-open",s=[t]),child_process.execFile(r,s,n=>{n&&process.stderr.write(`[testrelic] Failed to open browser: ${n.message}
2601
+ `);});}catch{}}path.join(os.tmpdir(),"testrelic-data");async function Ht(t,e,r,s){let n=(e-1)*r,a=[],o=0,i=readline.createInterface({input:fs$1.createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let u of i)if(u.length!==0){if(o>=n&&a.length<r)try{a.push(JSON.parse(u));}catch{}if(o++,a.length>=r&&s!==void 0)break}let d=s??o,l=Math.max(1,Math.ceil(d/r));return {items:a,total:d,page:e,pageSize:r,totalPages:l}}var zt=/^[a-f0-9]{12}$/,qe=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,jt=500;function b(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function Vt(t){t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type");}function ie(t){try{return fs$1.existsSync(t)?JSON.parse(fs$1.readFileSync(t,"utf-8")):null}catch{return null}}function oe(t){let e=0;try{let r=fs$1.readdirSync(t,{withFileTypes:!0});for(let s of r){let n=path.join(t,s.name);s.isFile()?e+=fs$1.statSync(n).size:s.isDirectory()&&(e+=oe(n));}}catch{}return e}function Gt(t,e,r,s){let n=ie(path.join(r,"index.json"));b(e,200,{status:"ok",reportMode:"streaming",testCount:n?.length??0,uptime:Math.floor((Date.now()-s)/1e3)});}function Wt(t,e,r){let s=ie(path.join(r,"summary.json"));if(!s){b(e,404,{error:"Summary not found"});return}b(e,200,s);}function Kt(t,e,r){let s=ie(path.join(r,"index.json"));if(!s){b(e,404,{error:"Test index not found"});return}let a=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,o=Math.max(1,parseInt(a.get("page")??"1",10)||1),i=Math.min(jt,Math.max(1,parseInt(a.get("pageSize")??"100",10)||100)),d=a.get("status")?.split(",").filter(Boolean)??null,l=a.get("file")??null,u=a.get("search")?.toLowerCase()??null,g=a.get("tag")?.split(",").filter(Boolean)??null,m=a.get("sort")??"file",p=a.get("order")==="desc"?-1:1,f=s;d&&d.length>0&&(f=f.filter(x=>d.includes(x.status))),l&&(f=f.filter(x=>x.filePath===l||x.filePath.startsWith(l+"/"))),u&&(f=f.filter(x=>x.title.toLowerCase().includes(u)||x.filePath.toLowerCase().includes(u))),g&&g.length>0&&(f=f.filter(x=>g.some(T=>x.tags.includes(T)))),f=[...f].sort((x,T)=>{let M=0;switch(m){case "duration":M=x.duration-T.duration;break;case "status":M=x.status.localeCompare(T.status);break;case "title":M=x.title.localeCompare(T.title);break;default:M=x.filePath.localeCompare(T.filePath);break}return M*p});let c=f.length,h=Math.max(1,Math.ceil(c/i)),v=(o-1)*i,w=f.slice(v,v+i);b(e,200,{tests:w,pagination:{page:o,pageSize:i,totalItems:c,totalPages:h},filters:{status:d,file:l,search:u,tag:g}});}function Jt(t,e,r,s){if(!zt.test(s)){b(e,400,{error:"Invalid test ID format"});return}let n=path.join(r,"tests",s,"meta.json"),a=path.join(r,"tests",`${s}.json`),o=fs$1.existsSync(n)?n:fs$1.existsSync(a)?a:null;if(!o){b(e,404,{error:`Test not found: ${s}`});return}try{let i=fs$1.readFileSync(o,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(i);}catch(i){b(e,500,{error:i instanceof Error?i.message:String(i)});}}async function Yt(t,e,r,s,n){if(!zt.test(s)){b(e,400,{error:"Invalid test ID format"});return}let o=path.join(r,"tests",s,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[n]);if(!fs$1.existsSync(o)){b(e,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let d=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,l=Math.max(1,parseInt(d.get("page")??"1",10)||1),u=Math.min(jt,Math.max(1,parseInt(d.get("pageSize")??"50",10)||50)),g,m=path.join(r,"tests",s,"meta.json");if(fs$1.existsSync(m))try{let f=JSON.parse(fs$1.readFileSync(m,"utf-8"));switch(n){case "network":g=f.networkRequestsCount;break;case "console":g=f.consoleLogsCount;break;case "api-calls":g=f.apiCallsCount;break}}catch{}let p=await Ht(o,l,u,g);b(e,200,p);}catch(i){b(e,500,{error:i instanceof Error?i.message:String(i)});}}function Zt(t,e,r){let s=ie(path.join(r,"index.json"));if(!s){b(e,404,{error:"Test index not found"});return}let n=new Map;for(let o of s){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 a=Array.from(n.entries()).map(([o,i])=>({filePath:o,...i})).sort((o,i)=>o.filePath.localeCompare(i.filePath));b(e,200,{files:a});}function Qt(t,e,r){if(!fs$1.existsSync(r)){b(e,200,{runs:[],totalSizeBytes:0});return}try{let s=[],n=0,a=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!qe.test(o.name))continue;let i=path.join(r,o.name),d=oe(i),l=fs$1.readdirSync(i,{withFileTypes:!0}).filter(u=>u.isDirectory());s.push({folderName:o.name,totalSizeBytes:d,testCount:l.length}),n+=d;}s.sort((o,i)=>i.folderName.localeCompare(o.folderName)),b(e,200,{runs:s,totalSizeBytes:n});}catch(s){b(e,500,{error:s instanceof Error?s.message:String(s)});}}function Xt(t,e,r){try{let s=0,n=0;if(fs$1.existsSync(r)){let a=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!qe.test(o.name))continue;let i=path.join(r,o.name),d=oe(i);fs$1.rmSync(i,{recursive:!0,force:!0}),n+=d,s++;}}b(e,200,{deletedCount:s,freedBytes:n});}catch(s){b(e,500,{error:s instanceof Error?s.message:String(s)});}}function er(t,e,r,s){if(!qe.test(s)){b(e,400,{error:"Invalid folder name"});return}let n=path.join(r,s);try{if(!fs$1.statSync(n).isDirectory()){b(e,404,{error:"Not found"});return}}catch{b(e,404,{error:"Not found"});return}try{let a=oe(n);fs$1.rmSync(n,{recursive:!0,force:!0}),b(e,200,{deleted:s,freedBytes:a});}catch(a){b(e,500,{error:a instanceof Error?a.message:String(a)});}}function tr(t,e,r){b(e,200,{status:"shutting_down"}),r.close();}function He(t,e,r){if(!fs$1.existsSync(r)){b(e,404,{error:"File not found"});return}try{let s=fs$1.readFileSync(r),n=path.extname(r).toLowerCase(),a=Bs[n]??"application/octet-stream";e.writeHead(200,{"Content-Type":a}),e.end(s);}catch(s){b(e,500,{error:s instanceof Error?s.message:String(s)});}}var Bs={".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 Us=9323,$s=10,zs=1800*1e3;function Z(t,e){return new Promise((r,s)=>{let n=e?.port??Us,a=Date.now(),o,i=0,d=fs$1.existsSync(path.join(t,"artifacts"))?path.join(t,"artifacts"):fs$1.existsSync(path.join(t,"..","artifacts"))?path.join(t,"..","artifacts"):path.join(t,"artifacts");function l(){clearTimeout(o),o=setTimeout(()=>{g.close();},zs);}let u=e?.htmlPath??null;if(!u){let p=path.dirname(t);try{let f=fs$1.readdirSync(p).find(c=>c.endsWith(".html"));f&&(u=path.join(p,f));}catch{}}let g=http.createServer((p,f)=>{if(l(),Vt(f),p.method==="OPTIONS"){f.writeHead(204),f.end();return}let c;try{c=new URL(p.url??"/",`http://${p.headers.host??"localhost"}`).pathname;}catch{b(f,400,{error:"Invalid URL"});return}if(p.method==="GET"&&(c==="/"||c==="/index.html")){if(u&&fs$1.existsSync(u)){He(p,f,u);return}b(f,404,{error:"HTML report not found"});return}if(p.method==="GET"&&c==="/api/health"){Gt(p,f,t,a);return}if(p.method==="GET"&&c==="/api/summary"){Wt(p,f,t);return}if(p.method==="GET"&&c==="/api/tests"){Kt(p,f,t);return}if(p.method==="GET"&&c==="/api/files"){Zt(p,f,t);return}let h=c.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(p.method==="GET"&&h){Yt(p,f,t,h[1],h[2]);return}let v=c.match(/^\/api\/tests\/([a-f0-9]+)$/);if(p.method==="GET"&&v){Jt(p,f,t,v[1]);return}if(p.method==="GET"&&c==="/api/artifacts"){Qt(p,f,d);return}if(p.method==="DELETE"&&c==="/api/artifacts"){Xt(p,f,d);return}let w=c.match(/^\/api\/artifacts\/(.+)$/);if(p.method==="DELETE"&&w){er(p,f,d,decodeURIComponent(w[1]));return}if(p.method==="GET"&&c.startsWith("/artifacts/")){let x=decodeURIComponent(c.slice(11));if(x.includes("..")||x.includes("\0")){b(f,400,{error:"Invalid path"});return}He(p,f,path.join(d,x));return}if(p.method==="POST"&&c==="/api/shutdown"){tr(p,f,g);return}b(f,404,{error:"Not found"});});function m(p){let f=c=>{c.code==="EADDRINUSE"&&i<$s?(i++,m(p+1)):s(c);};g.once("error",f),g.listen(p,"127.0.0.1",()=>{g.removeListener("error",f);let c=g.address();if(!c||typeof c=="string"){s(new Error("Failed to get server address"));return}l(),r({port:c.port,dispose:()=>new Promise(h=>{clearTimeout(o),g.close(()=>h());})});});}m(n);})}async function rr(t){let e=await Z(t);return {port:e.port,dispose:e.dispose}}function Gs(t,e,r){let s=JSON.stringify(t),n=r?JSON.stringify(r):null;return qt(s,e,n)}async function $e(t,e,r){try{let s=null,n=null,a=e.reportMode==="streaming"||e.reportMode==="auto"&&t.timeline.length===0&&t.summary.total>=e.streamingThreshold,o,i=e.htmlReportPath,d=path.dirname(i);fs$1.mkdirSync(d,{recursive:!0});let l="",u="[]",g=null;if(a){l=JSON.stringify({...t.summary,testRunId:t.testRunId,startedAt:t.startedAt,completedAt:t.completedAt,totalDuration:t.totalDuration,ci:t.ci,metadata:t.metadata,shardRunIds:t.shardRunIds});let p=path.dirname(e.outputPath),f=path.join(p,".testrelic-report");try{let c=path.join(f,"index-compact.json"),h=path.join(f,"index.json");fs$1.existsSync(c)?u=fs$1.readFileSync(c,"utf-8"):fs$1.existsSync(h)&&(u=fs$1.readFileSync(h,"utf-8"));}catch{}g=r?JSON.stringify(r):null,o=Be(l,u,null,g);}else o=Gs(t,null,r);let m=i+".tmp";if(fs$1.writeFileSync(m,o,"utf-8"),fs$1.renameSync(m,i),a){if(t.ci===null){let p=path.dirname(e.outputPath),f=path.join(p,".testrelic-report"),c=path.resolve(i);try{if(await Ks(),s=await Js(f),!s){n=await Z(f,{htmlPath:c}),s=n.port;let h=setInterval(()=>{},6e4),v=()=>{clearInterval(h),n?.dispose();};process.on("SIGINT",v),process.on("SIGTERM",v),setTimeout(v,1800*1e3).unref();}if(s){process.stderr.write(`
2548
2602
  Report server: http://127.0.0.1:${s}
2549
- `);try{let h=De(l,u,s,g),v=i+".tmp";fs$1.writeFileSync(v,h,"utf-8"),fs$1.renameSync(v,i);}catch{}}}catch{}}}else if(e.openReport&&t.ci===null&&e.includeArtifacts){let p=path.dirname(e.outputPath),f=path.join(p,"artifacts");if(fs$1.existsSync(f))try{let c=await er(f);s=c.port,process.on("exit",()=>{c.dispose();});}catch{}}if(e.openReport&&t.ci===null)if(a&&s)Be(`http://127.0.0.1:${s}`);else {let p=path.resolve(i);Be(p);}}catch(s){process.stderr.write(`[testrelic] Failed to write HTML report: ${s instanceof Error?s.message:String(s)}
2550
- `);}}var ce=9323,ar=10;async function Vs(){for(let t=ce;t<ce+ar;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),500),s=await fetch(`http://127.0.0.1:${t}/api/health`,{signal:e.signal});if(clearTimeout(r),s.ok)return t}catch{}return null}async function Gs(){for(let t=ce;t<ce+ar;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),1e3);await fetch(`http://127.0.0.1:${t}/api/shutdown`,{method:"POST",signal:e.signal}),clearTimeout(r);}catch{}await new Promise(t=>setTimeout(t,300));}async function Ws(t){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(s=>fs$1.existsSync(s));if(!r){let s=await Z(t);return process.on("exit",()=>{s?.dispose();}),s.port}return new Promise(s=>{let n=child_process.spawn(process.execPath,[r,"serve",t],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),a="",o=false,i=setTimeout(()=>{o||(o=true,n.stderr?.removeAllListeners(),Vs().then(s));},5e3);n.stderr?.on("data",d=>{a+=d.toString();let l=a.match(/127\.0\.0\.1:(\d+)/);l&&!o&&(o=true,clearTimeout(i),n.stderr?.removeAllListeners(),n.unref(),s(Number(l[1])));}),n.on("error",()=>{o||(o=true,clearTimeout(i),s(null));}),n.on("exit",()=>{o||(o=true,clearTimeout(i),s(null));}),n.unref();})}var Ys=20,$e=0,ze=[];async function or(t,e){$e>=Ys&&await new Promise(r=>ze.push(r)),$e++;try{return await promises.copyFile(t,e),!0}catch{return false}finally{$e--,ze.length>0&&ze.shift()();}}var X=[];async function lr(){X.length!==0&&(await Promise.allSettled(X),X.length=0);}function dr(t){let e=new Date,r=a=>String(a).padStart(2,"0"),s=`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())}T${r(e.getHours())}-${r(e.getMinutes())}-${r(e.getSeconds())}`;if(!fs$1.existsSync(path.join(t,s)))return s;let n=1;for(;fs$1.existsSync(path.join(t,`${s}-${n}`));)n++;return `${s}-${n}`}function Zs(t){let e=t.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return e.length>100&&(e=e.substring(0,100).replace(/-+$/,"")),e||"unnamed-test"}function cr(t,e,r,s,n){let a=t.find(m=>m.name==="screenshot"&&m.path),o=t.find(m=>m.name==="video"&&m.path);if(!a&&!o)return null;let i=Zs(e);r>0&&(i+=`--retry-${r}`);let d=n?["artifacts",n,i]:["artifacts",i],l=path.join(s,...d),u=d,g={};try{fs$1.mkdirSync(l,{recursive:!0});}catch{return null}if(a?.path&&fs$1.existsSync(a.path)){let p=`screenshot${path.extname(a.path)||".png"}`,f=path.join(l,p);X.push(or(a.path,f).then(()=>{})),g.screenshot=`${u.join("/")}/${p}`;}if(o?.path&&fs$1.existsSync(o.path)){let p=`video${path.extname(o.path)||".webm"}`,f=path.join(l,p);X.push(or(o.path,f).then(()=>{})),g.video=`${u.join("/")}/${p}`;}return !g.screenshot&&!g.video?null:g}var en=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,tn="1.0";function rn(t){let e=path.extname(t).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(e)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(e)?"video":"other"}function ur(t,e,r){let s=[];try{let n=fs$1.readdirSync(t,{withFileTypes:!0});for(let a of n){if(!a.isFile())continue;let o=path.join(t,a.name),i=fs$1.statSync(o);s.push({name:a.name,type:rn(a.name),relativePath:`artifacts/${e}/${r}/${a.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:s}}function sn(t,e){let r=path.join(t,e),s=[],n=0;try{let o=fs$1.readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let d=ur(path.join(r,i.name),e,i.name);s.push(d);for(let l of d.files)n+=l.sizeBytes;}}catch{}let a=e.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return s.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:e,timestamp:a,totalSizeBytes:n,testCount:s.length,tests:s,isCurrentRun:false}}function pr(t,e){let r=path.join(t,"artifacts"),s=[],n=[],a=0;try{let i=fs$1.readdirSync(r,{withFileTypes:!0});for(let d of i)if(d.isDirectory())if(en.test(d.name)){let l=sn(r,d.name);s.push({...l,isCurrentRun:d.name===e});}else {let l=ur(path.join(r,d.name),d.name,d.name);n.push(l);for(let u of l.files)a+=u.sizeBytes;}}catch{}s.sort((i,d)=>d.timestamp.localeCompare(i.timestamp)),n.length>0&&(n.sort((i,d)=>i.testName.localeCompare(d.testName)),s.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:a,testCount:n.length,tests:n,isCurrentRun:false}));let o=s.reduce((i,d)=>i+d.totalSizeBytes,0);return {schemaVersion:tn,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:s,serverPort:null}}var cn=256;function un(t){let e=path.resolve(t);for(let r=0;r<cn;r++){if(fs$1.existsSync(path.join(e,".git")))return e;let s=path.dirname(e);if(s===e)return null;e=s;}return null}function hr(t){try{let e=un(t);if(!e)return;let r=path.join(e,".gitignore"),s=path.relative(e,t).replace(/\\/g,"/"),n=s.endsWith("/")?s:`${s}/`;if(fs$1.existsSync(r)&&fs$1.readFileSync(r,"utf-8").split(`
2603
+ `);try{let h=Be(l,u,s,g),v=i+".tmp";fs$1.writeFileSync(v,h,"utf-8"),fs$1.renameSync(v,i);}catch{}}}catch{}}}else if(e.openReport&&t.ci===null&&e.includeArtifacts){let p=path.dirname(e.outputPath),f=path.join(p,"artifacts");if(fs$1.existsSync(f))try{let c=await rr(f);s=c.port,process.on("exit",()=>{c.dispose();});}catch{}}if(e.openReport&&t.ci===null)if(a&&s)Oe(`http://127.0.0.1:${s}`);else {let p=path.resolve(i);Oe(p);}}catch(s){process.stderr.write(`[testrelic] Failed to write HTML report: ${s instanceof Error?s.message:String(s)}
2604
+ `);}}var ce=9323,or=10;async function Ws(){for(let t=ce;t<ce+or;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),500),s=await fetch(`http://127.0.0.1:${t}/api/health`,{signal:e.signal});if(clearTimeout(r),s.ok)return t}catch{}return null}async function Ks(){for(let t=ce;t<ce+or;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),1e3);await fetch(`http://127.0.0.1:${t}/api/shutdown`,{method:"POST",signal:e.signal}),clearTimeout(r);}catch{}await new Promise(t=>setTimeout(t,300));}async function Js(t){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(s=>fs$1.existsSync(s));if(!r){let s=await Z(t);return process.on("exit",()=>{s?.dispose();}),s.port}return new Promise(s=>{let n=child_process.spawn(process.execPath,[r,"serve",t],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),a="",o=false,i=setTimeout(()=>{o||(o=true,n.stderr?.removeAllListeners(),Ws().then(s));},5e3);n.stderr?.on("data",d=>{a+=d.toString();let l=a.match(/127\.0\.0\.1:(\d+)/);l&&!o&&(o=true,clearTimeout(i),n.stderr?.removeAllListeners(),n.unref(),s(Number(l[1])));}),n.on("error",()=>{o||(o=true,clearTimeout(i),s(null));}),n.on("exit",()=>{o||(o=true,clearTimeout(i),s(null));}),n.unref();})}var Qs=20,ze=0,je=[];async function dr(t,e){ze>=Qs&&await new Promise(r=>je.push(r)),ze++;try{return await promises.copyFile(t,e),!0}catch{return false}finally{ze--,je.length>0&&je.shift()();}}var X=[];async function ur(){X.length!==0&&(await Promise.allSettled(X),X.length=0);}function pr(t){let e=new Date,r=a=>String(a).padStart(2,"0"),s=`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())}T${r(e.getHours())}-${r(e.getMinutes())}-${r(e.getSeconds())}`;if(!fs$1.existsSync(path.join(t,s)))return s;let n=1;for(;fs$1.existsSync(path.join(t,`${s}-${n}`));)n++;return `${s}-${n}`}function cr(t){let e=t.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return e.length>100&&(e=e.substring(0,100).replace(/-+$/,"")),e||"unnamed-test"}var Xs=8;function en(t,e,r){let s=cr(t),n=r?cr(r).substring(0,Xs):"";return n&&(s+=`--${n}`),e>0&&(s+=`--retry-${e}`),s}function fr(t,e,r,s,n,a){let o=t.find(p=>p.name==="screenshot"&&p.path),i=t.find(p=>p.name==="video"&&p.path);if(!o&&!i)return null;let d=en(e,r,a),l=n?["artifacts",n,d]:["artifacts",d],u=path.join(s,...l),g=l,m={};try{fs$1.mkdirSync(u,{recursive:!0});}catch{return null}if(o?.path&&fs$1.existsSync(o.path)){let f=`screenshot${path.extname(o.path)||".png"}`,c=path.join(u,f);X.push(dr(o.path,c).then(()=>{})),m.screenshot=`${g.join("/")}/${f}`;}if(i?.path&&fs$1.existsSync(i.path)){let f=`video${path.extname(i.path)||".webm"}`,c=path.join(u,f);X.push(dr(i.path,c).then(()=>{})),m.video=`${g.join("/")}/${f}`;}return !m.screenshot&&!m.video?null:m}var sn=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,nn="1.0";function an(t){let e=path.extname(t).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(e)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(e)?"video":"other"}function gr(t,e,r){let s=[];try{let n=fs$1.readdirSync(t,{withFileTypes:!0});for(let a of n){if(!a.isFile())continue;let o=path.join(t,a.name),i=fs$1.statSync(o);s.push({name:a.name,type:an(a.name),relativePath:`artifacts/${e}/${r}/${a.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:s}}function on(t,e){let r=path.join(t,e),s=[],n=0;try{let o=fs$1.readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let d=gr(path.join(r,i.name),e,i.name);s.push(d);for(let l of d.files)n+=l.sizeBytes;}}catch{}let a=e.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return s.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:e,timestamp:a,totalSizeBytes:n,testCount:s.length,tests:s,isCurrentRun:false}}function hr(t,e){let r=path.join(t,"artifacts"),s=[],n=[],a=0;try{let i=fs$1.readdirSync(r,{withFileTypes:!0});for(let d of i)if(d.isDirectory())if(sn.test(d.name)){let l=on(r,d.name);s.push({...l,isCurrentRun:d.name===e});}else {let l=gr(path.join(r,d.name),d.name,d.name);n.push(l);for(let u of l.files)a+=u.sizeBytes;}}catch{}s.sort((i,d)=>d.timestamp.localeCompare(i.timestamp)),n.length>0&&(n.sort((i,d)=>i.testName.localeCompare(d.testName)),s.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:a,testCount:n.length,tests:n,isCurrentRun:false}));let o=s.reduce((i,d)=>i+d.totalSizeBytes,0);return {schemaVersion:nn,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:s,serverPort:null}}var fn=256;function gn(t){let e=path.resolve(t);for(let r=0;r<fn;r++){if(fs$1.existsSync(path.join(e,".git")))return e;let s=path.dirname(e);if(s===e)return null;e=s;}return null}function yr(t){try{let e=gn(t);if(!e)return;let r=path.join(e,".gitignore"),s=path.relative(e,t).replace(/\\/g,"/"),n=s.endsWith("/")?s:`${s}/`;if(fs$1.existsSync(r)&&fs$1.readFileSync(r,"utf-8").split(`
2551
2605
  `).map(d=>d.trim()).some(d=>d===n||d===s))return;let a=`
2552
2606
  # TestRelic test artifacts
2553
2607
  ${n}
2554
- `;fs$1.appendFileSync(r,a,"utf-8");}catch{}}var mr=Symbol("testrelic.timeout"),vr=3e4,Ve=12e4,Ge=6e4,yr=15e3;async function H(t,e,r){let s,n=new Promise(a=>{s=setTimeout(()=>a(mr),e),typeof s?.unref=="function"&&s.unref();});try{let a=await Promise.race([t(),n]);if(a===mr){process.stderr.write(`[testrelic] ${r} timed out after ${Math.round(e/1e3)}s \u2014 continuing without it. Your tests are unaffected.
2608
+ `;fs$1.appendFileSync(r,a,"utf-8");}catch{}}var br=Symbol("testrelic.timeout"),xr=3e4,Ge=12e4,We=6e4,wr=15e3;async function H(t,e,r){let s,n=new Promise(a=>{s=setTimeout(()=>a(br),e),typeof s?.unref=="function"&&s.unref();});try{let a=await Promise.race([t(),n]);if(a===br){process.stderr.write(`[testrelic] ${r} timed out after ${Math.round(e/1e3)}s \u2014 continuing without it. Your tests are unaffected.
2555
2609
  `);return}return a}catch(a){process.stderr.write(`[testrelic] ${r} failed \u2014 continuing without it. Your tests are unaffected. (${a instanceof Error?a.message:String(a)})
2556
- `);return}finally{s&&clearTimeout(s);}}function wr(t,e){let r=[];for(let s of t){let n=pn(s),a=fn(s),o=gn(s,n,a,e),i=hn(s,n,a);if(o.length===0&&i.length===0){r.push({type:"navigation",url:"about:blank",timestamp:s.startedAt,durationOnUrl:s.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:s.specFile,test:n,tests:[a],_testTitle:s.title});continue}r.push(...o,...i);}return r.sort(mn),vn(r,t),r.map((s,n)=>s.type==="navigation"?{...{index:n,type:"navigation",url:s.url,timestamp:s.timestamp,durationOnUrl:s.durationOnUrl??0,navigationType:s.navigationType,domContentLoadedAt:s.domContentLoadedAt??null,networkIdleAt:s.networkIdleAt??null,networkStats:s.networkStats??null,specFile:s.specFile,test:s.test},tests:s.tests}:{...{index:n,type:"api_call",callId:s.callId,method:s.method,url:s.url,timestamp:s.timestamp,responseTime:s.responseTime??null,request:s.request,response:s.response??null,...s.error?{error:s.error}:{},assertions:s.assertions??[],specFile:s.specFile,test:s.test},tests:s.tests})}function pn(t){return {title:t.title,fullTitle:t.titlePath,status:t.status,duration:t.duration,retries:t.retryCount,retry:t.retry,tags:t.tags,failure:t.failure}}function fn(t){return {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,networkRequests:t.networkRequests,apiCalls:t.apiCalls,apiAssertions:t.apiAssertions,actions:t.actions,consoleLogs:t.consoleLogs}}function gn(t,e,r,s){let n=[];for(let a of t.navigations)s.navigationTypes!==null&&!s.navigationTypes.includes(a.navigationType)||n.push({type:"navigation",url:a.url,timestamp:a.timestamp,durationOnUrl:0,navigationType:a.navigationType,domContentLoadedAt:a.domContentLoadedAt??null,networkIdleAt:a.networkIdleAt??null,networkStats:a.networkStats??null,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title});return n}function hn(t,e,r){if(!t.apiCalls||t.apiCalls.length===0)return [];let s=t.apiAssertions??[];return t.apiCalls.map(n=>{let a=s.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:xr(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:xr(n.requestBody)},response:o,...n.error?{error:n.error}:{},assertions:a,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title}})}function mn(t,e){let r=new Date(t.timestamp).getTime(),s=new Date(e.timestamp).getTime();if(r!==s)return r-s;let n={navigation:0,api_call:1},a=n[t.type],o=n[e.type];return a!==o?a-o:t.type==="api_call"&&e.type==="api_call"&&t.callId&&e.callId?br(t.callId)-br(e.callId):0}function br(t){let e=t.match(/(\d+)$/);return e?parseInt(e[1],10):0}function vn(t,e){for(let r=0;r<t.length;r++){let s=t[r];if(s.type!=="navigation")continue;let n=new Date(s.timestamp).getTime(),a=null;for(let o=r+1;o<t.length;o++)if(t[o]._testTitle===s._testTitle){a=new Date(t[o].timestamp).getTime();break}if(a!==null)s.durationOnUrl=Math.max(0,a-n);else {let o=e.find(i=>i.title===s._testTitle);if(o){let i=new Date(o.completedAt).getTime();s.durationOnUrl=Math.max(0,i-n);}}}}function xr(t){if(t==null)return null;try{return JSON.parse(t)}catch{return t}}function U(t,e){let r=t.length,s=Math.min(Math.ceil(e/100*r)-1,r-1);return t[Math.max(0,s)]}function We(t){try{let e=new URL(t);return e.origin+e.pathname}catch{return t}}function yn(t){return t==null?"error":t>=200&&t<300?"2xx":t>=300&&t<400?"3xx":t>=400&&t<500?"4xx":t>=500&&t<600?"5xx":"error"}function kr(t,e){let r=0,s=0,n=0,a=0,o=0;for(let y of t)switch(y.status){case "passed":r++;break;case "failed":s++;break;case "flaky":n++;break;case "skipped":a++;break;case "timedout":o++;break}let i=[];for(let y of t)y.apiCalls&&i.push(...y.apiCalls);let d=i.length,l=new Set,u={},g={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},m=[];for(let y of i)l.add(We(y.url)),u[y.method]=(u[y.method]??0)+1,g[yn(y.responseStatusCode)]+=1,m.push(y.responseTimeMs);let p=null;if(m.length>0){let y=[...m].sort((R,$)=>R-$),k=y.reduce((R,$)=>R+$,0);p={avg:Math.round(k/y.length),min:y[0],max:y[y.length-1],p50:U(y,50),p95:U(y,95),p99:U(y,99)};}let f=0,c=0,h=0;for(let y of t)if(y.apiAssertions)for(let k of y.apiAssertions)f++,k.status==="passed"?c++:h++;let v=0,w=new Set;for(let y of t){v+=y.navigations.length;for(let k of y.navigations)w.add(k.url);}let x=0,T={};function M(y){for(let k of y)x++,T[k.category]=(T[k.category]??0)+1,k.children.length>0&&M(k.children);}for(let y of t)y.actions&&M(y.actions);return {total:t.length,passed:r,failed:s,flaky:n,skipped:a,timedout:o,totalApiCalls:d,uniqueApiUrls:l.size,apiCallsByMethod:u,apiCallsByStatusRange:g,apiResponseTime:p,totalAssertions:f,passedAssertions:c,failedAssertions:h,totalNavigations:v,uniqueNavigationUrls:w.size,totalTimelineSteps:e,totalActionSteps:x,actionStepsByCategory:T}}function bn(t){let e=56-t.length;return e>0?t+" ".repeat(e):t}function _(t){return `\u2502 ${bn(t)} \u2502
2557
- `}function Ke(t,e,r,s){if(s||t.total===0)return;let n=`\u250C${"\u2500".repeat(58)}\u2510
2610
+ `);return}finally{s&&clearTimeout(s);}}function Sr(t,e){let r=[];for(let s of t){let n=hn(s),a=mn(s),o=vn(s,n,a,e),i=yn(s,n,a);if(o.length===0&&i.length===0){r.push({type:"navigation",url:"about:blank",timestamp:s.startedAt,durationOnUrl:s.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:s.specFile,test:n,tests:[a],_testTitle:s.title});continue}r.push(...o,...i);}return r.sort(bn),xn(r,t),r.map((s,n)=>s.type==="navigation"?{...{index:n,type:"navigation",url:s.url,timestamp:s.timestamp,durationOnUrl:s.durationOnUrl??0,navigationType:s.navigationType,domContentLoadedAt:s.domContentLoadedAt??null,networkIdleAt:s.networkIdleAt??null,networkStats:s.networkStats??null,specFile:s.specFile,test:s.test},tests:s.tests}:{...{index:n,type:"api_call",callId:s.callId,method:s.method,url:s.url,timestamp:s.timestamp,responseTime:s.responseTime??null,request:s.request,response:s.response??null,...s.error?{error:s.error}:{},assertions:s.assertions??[],specFile:s.specFile,test:s.test},tests:s.tests})}function hn(t){return {title:t.title,fullTitle:t.titlePath,status:t.status,duration:t.duration,retries:t.retryCount,retry:t.retry,tags:t.tags,failure:t.failure}}function mn(t){return {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,networkRequests:t.networkRequests,apiCalls:t.apiCalls,apiAssertions:t.apiAssertions,actions:t.actions,consoleLogs:t.consoleLogs}}function vn(t,e,r,s){let n=[];for(let a of t.navigations)s.navigationTypes!==null&&!s.navigationTypes.includes(a.navigationType)||n.push({type:"navigation",url:a.url,timestamp:a.timestamp,durationOnUrl:0,navigationType:a.navigationType,domContentLoadedAt:a.domContentLoadedAt??null,networkIdleAt:a.networkIdleAt??null,networkStats:a.networkStats??null,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title});return n}function yn(t,e,r){if(!t.apiCalls||t.apiCalls.length===0)return [];let s=t.apiAssertions??[];return t.apiCalls.map(n=>{let a=s.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:Tr(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:Tr(n.requestBody)},response:o,...n.error?{error:n.error}:{},assertions:a,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title}})}function bn(t,e){let r=new Date(t.timestamp).getTime(),s=new Date(e.timestamp).getTime();if(r!==s)return r-s;let n={navigation:0,api_call:1},a=n[t.type],o=n[e.type];return a!==o?a-o:t.type==="api_call"&&e.type==="api_call"&&t.callId&&e.callId?kr(t.callId)-kr(e.callId):0}function kr(t){let e=t.match(/(\d+)$/);return e?parseInt(e[1],10):0}function xn(t,e){for(let r=0;r<t.length;r++){let s=t[r];if(s.type!=="navigation")continue;let n=new Date(s.timestamp).getTime(),a=null;for(let o=r+1;o<t.length;o++)if(t[o]._testTitle===s._testTitle){a=new Date(t[o].timestamp).getTime();break}if(a!==null)s.durationOnUrl=Math.max(0,a-n);else {let o=e.find(i=>i.title===s._testTitle);if(o){let i=new Date(o.completedAt).getTime();s.durationOnUrl=Math.max(0,i-n);}}}}function Tr(t){if(t==null)return null;try{return JSON.parse(t)}catch{return t}}function U(t,e){let r=t.length,s=Math.min(Math.ceil(e/100*r)-1,r-1);return t[Math.max(0,s)]}function Ke(t){try{let e=new URL(t);return e.origin+e.pathname}catch{return t}}function wn(t){return t==null?"error":t>=200&&t<300?"2xx":t>=300&&t<400?"3xx":t>=400&&t<500?"4xx":t>=500&&t<600?"5xx":"error"}function Cr(t,e){let r=0,s=0,n=0,a=0,o=0;for(let y of t)switch(y.status){case "passed":r++;break;case "failed":s++;break;case "flaky":n++;break;case "skipped":a++;break;case "timedout":o++;break}let i=[];for(let y of t)y.apiCalls&&i.push(...y.apiCalls);let d=i.length,l=new Set,u={},g={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},m=[];for(let y of i)l.add(Ke(y.url)),u[y.method]=(u[y.method]??0)+1,g[wn(y.responseStatusCode)]+=1,m.push(y.responseTimeMs);let p=null;if(m.length>0){let y=[...m].sort((R,$)=>R-$),k=y.reduce((R,$)=>R+$,0);p={avg:Math.round(k/y.length),min:y[0],max:y[y.length-1],p50:U(y,50),p95:U(y,95),p99:U(y,99)};}let f=0,c=0,h=0;for(let y of t)if(y.apiAssertions)for(let k of y.apiAssertions)f++,k.status==="passed"?c++:h++;let v=0,w=new Set;for(let y of t){v+=y.navigations.length;for(let k of y.navigations)w.add(k.url);}let x=0,T={};function M(y){for(let k of y)x++,T[k.category]=(T[k.category]??0)+1,k.children.length>0&&M(k.children);}for(let y of t)y.actions&&M(y.actions);return {total:t.length,passed:r,failed:s,flaky:n,skipped:a,timedout:o,totalApiCalls:d,uniqueApiUrls:l.size,apiCallsByMethod:u,apiCallsByStatusRange:g,apiResponseTime:p,totalAssertions:f,passedAssertions:c,failedAssertions:h,totalNavigations:v,uniqueNavigationUrls:w.size,totalTimelineSteps:e,totalActionSteps:x,actionStepsByCategory:T}}function kn(t){let e=56-t.length;return e>0?t+" ".repeat(e):t}function I(t){return `\u2502 ${kn(t)} \u2502
2611
+ `}function Je(t,e,r,s){if(s||t.total===0)return;let n=`\u250C${"\u2500".repeat(58)}\u2510
2558
2612
  `,a=`\u2514${"\u2500".repeat(58)}\u2518
2559
- `,o=_(""),i=n;i+=_("TestRelic AI - Playwright Test Report"),i+=o;let d=[];if(t.passed>0&&d.push(`${t.passed} \u2713`),t.failed>0&&d.push(`${t.failed} \u2717`),t.flaky>0&&d.push(`${t.flaky} \u26A0`),t.skipped>0&&d.push(`${t.skipped} skipped`),t.timedout>0&&d.push(`${t.timedout} timedout`),i+=_(`Tests: ${t.total} total (${d.join(" ")})`),t.totalNavigations>0&&(i+=_(`Navigations: ${t.totalNavigations} visits across ${t.uniqueNavigationUrls} unique URLs`)),t.totalApiCalls>0){i+=_(`API Calls: ${t.totalApiCalls} calls across ${t.uniqueApiUrls} unique endpoints`);let l=Object.entries(t.apiCallsByMethod).filter(([,g])=>g>0).map(([g,m])=>`${g}: ${m}`);l.length>0&&(i+=_(` ${l.join(" ")}`));let u=Object.entries(t.apiCallsByStatusRange).filter(([,g])=>g>0).map(([g,m])=>`${g}: ${m}`);u.length>0&&(i+=_(` ${u.join(" ")}`)),t.apiResponseTime&&(i+=_(` Avg response: ${t.apiResponseTime.avg}ms P95: ${t.apiResponseTime.p95}ms`));}if(t.totalAssertions>0&&(i+=_(`Assertions: ${t.totalAssertions} total (${t.passedAssertions} \u2713 ${t.failedAssertions} \u2717)`)),t.totalActionSteps>0){let l=[],u=t.actionStepsByCategory;u.ui_action&&l.push(`${u.ui_action} UI`),u.assertion&&l.push(`${u.assertion} assertions`),u.custom_step&&l.push(`${u.custom_step} custom`);let g=l.length>0?` (${l.join(" ")})`:"";i+=_(`Actions: ${t.totalActionSteps} steps${g}`);}i+=_(`Report: ${r}`),i+=_(`Data: ${e}`),i+=a,i+=`For more information visit us at https://docs.testrelic.ai
2560
- `,process.stderr.write(i);}var xn=new Set(["pw:api","expect","test.step"]);function wn(t){return t==="expect"?"assertion":t==="test.step"?"custom_step":"ui_action"}function Je(t,e,r){if(xn.has(t.category)){let s=[];for(let a of t.steps)Je(a,e,s);let n=t.startTime.getTime()-e.getTime();r.push({title:t.title,category:wn(t.category),timestamp:t.startTime.toISOString(),duration:t.duration,videoOffset:n>=0?n/1e3:null,status:t.error?"failed":"passed",error:t.error?.message??null,children:s});}else for(let s of t.steps)Je(s,e,r);}function Tr(t,e){let r=[];for(let s of t)Je(s,e,r);return r}var Sn=new Set(["localhost","127.0.0.1","0.0.0.0"]);function Cr(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Sn.has(e.hostname)))throw core.createError(core.ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${e.protocol}//${e.hostname}`)}var Cn=3e3;async function Ye(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Cn);try{return (await fetch(`${t}/health`,{method:"GET",signal:e.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function Rr(t){return new Promise(e=>setTimeout(e,t))}async function Sr(t){try{let r=(await t.json()).error;if(r&&typeof r.message=="string"){let s=r.details;if(Array.isArray(s)&&s.length>0){let n=s.map(a=>`${a.field}: ${a.message}`).join(", ");return `${r.message} (${n})`}return r.message}}catch{}return `HTTP ${t.status}`}async function Ze(t,e,r){let s=new AbortController,n=setTimeout(()=>s.abort(),r);try{let a=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:s.signal});if(a.ok){let i=await a.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,orgId:i.orgId,orgName:i.orgName,userId:i.userId,userName:i.userName}}if(a.status===429){let i=a.headers.get("Retry-After"),d=i?parseInt(i,10)*1e3:5e3;if(!isNaN(d)&&d>0){await Rr(d);let l=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:s.signal});if(l.ok){let u=await l.json();return {accessToken:u.accessToken,refreshToken:u.refreshToken,expiresIn:u.expiresIn,orgId:u.orgId,orgName:u.orgName,userId:u.userId,userName:u.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return a.status===400?{code:"validation_error",message:await Sr(a),statusCode:400}:a.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:a.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await Sr(a),statusCode:a.status}}catch(a){return a instanceof DOMException&&a.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 Qe(t){return "code"in t&&typeof t.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(t.code)}async function Ar(t,e,r){let s=new AbortController,n=setTimeout(()=>s.abort(),r);try{let a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:s.signal});if(a.status===429){let i=a.headers.get("Retry-After"),d=i?parseInt(i,10)*1e3:5e3;!isNaN(d)&&d>0&&(await Rr(d),a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:s.signal}));}if(!a.ok)return null;let o=await a.json();return {accessToken:o.accessToken,refreshToken:o.refreshToken,expiresIn:o.expiresIn}}catch{return null}finally{clearTimeout(n);}}async function _r(t,e,r,s,n,a){let o=new AbortController,i=setTimeout(()=>o.abort(),n);try{let d={gitId:r,displayName:s};a&&(d.branch=a);let l=await fetch(`${t}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(d),signal:o.signal});if(!l.ok)return null;let u=await l.json();return {repoId:u.repoId,displayName:u.displayName}}catch{return null}finally{clearTimeout(i);}}var Mn=5e3;function F(t,e){try{return child_process.execSync(t,{cwd:e,timeout:Mn,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function Ir(t){let e=F("git rev-parse --abbrev-ref HEAD",t),r=F("git rev-parse --short HEAD",t),s=F("git log -1 --pretty=%s",t),n=F("git log -1 --format=%an",t)??F("git config user.name",t),a=Ln(t),o=a?te(a):null;return {branch:e,commitSha:r,commitMessage:s,commitAuthor:n,remoteUrl:o}}function Ln(t){let e=F("git remote get-url origin",t);if(e)return e;let r=F("git remote",t);if(!r)return null;let s=r.split(`
2561
- `)[0]?.trim();return s?F(`git remote get-url ${s}`,t):null}function te(t){let e=t.trim();return e=e.replace(/^[a-z+]+:\/\//,""),e=e.replace(/^[^@]+@/,""),e=e.replace(/:(?!\d)/,"/"),e=e.replace(/\.git$/,""),e=e.replace(/\/+$/,""),e=e.replace(/^[^@/]+@/,""),e.toLowerCase()}function Mr(t){let e=t.split("/").filter(Boolean);return e[e.length-1]??t}function Xe(t){try{let e=fs$1.readFileSync(path.join(t,"package.json"),"utf-8"),r=JSON.parse(e);return typeof r.name=="string"&&r.name.length>0?r.name:null}catch{return null}}function re(t){let e=Xe(t);return e||`local/${path.basename(t)}`}var En=new Set(["smoke","regression","nightly","ci"]);function pe(){let t=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(t&&En.has(t))return t}var Fn=1048576,fe=[1e3,3e3,9e3],ge=3,Dn=90*1048576,Bn=new Set(["e2e","mobile","unit"]);function tt(t){if(t&&t.length>0&&t.every(n=>n.testType==="api")){let n=new Map;for(let i of t){let d=i.apiProtocol??"rest";n.set(d,(n.get(d)??0)+1);}let a="rest",o=0;for(let[i,d]of n)d>o&&(o=d,a=i);return {testType:"api",apiProtocol:a,metadata:{testType:"api",primaryProtocol:a}}}let e=new Map;for(let n of t??[])Bn.has(n.testType)&&e.set(n.testType,(e.get(n.testType)??0)+1);let r=null,s=0;for(let[n,a]of e)a>s&&(s=a,r=n);return {testType:r??"e2e"}}function rt(t,e,r,s,n,a){let o=a?.cloudPlatform?a.cloudPlatform:s?.provider&&s.provider!=="unknown"?s.provider:"local",i=pe(),d=tt(n),l=d.testType==="api"?d:null,u=l&&n?n.map(m=>m.apiProtocol?m:{...m,apiProtocol:l.apiProtocol}):n;return {runId:t.testRunId,repoGitId:e,startedAt:t.startedAt,summary:t.summary,timeline:t.timeline,environment:o,...i?{runType:i}:{},...l?{testType:l.testType,apiProtocol:l.apiProtocol,metadata:l.metadata}:{testType:d.testType},...u&&u.length>0?{tests:u}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...s?.provider?{ciProvider:s.provider}:{},...s?.runUrl?{ciRunUrl:s.runUrl}:{},...a?.cloudPlatform?{cloudPlatform:a.cloudPlatform}:{},...a?.cloudBuildId?{cloudBuildId:a.cloudBuildId}:{},...a?.cloudSessionId?{cloudSessionId:a.cloudSessionId}:{}}}function et(t){return typeof t=="string"?Buffer.byteLength(t,"utf-8"):0}function st(t){return Array.isArray(t)?t.map(e=>{let r=e.statusCode??e.responseStatusCode??null;return {...e.id!=null?{id:e.id}:{},...e.protocol!=null?{protocol:e.protocol}:{},method:e.method??null,url:e.url??null,statusCode:r,statusText:e.statusText??e.responseStatusText??null,ok:typeof r=="number"?r<400:e.ok??null,durationMs:e.durationMs??e.responseTimeMs??null,bytesIn:typeof e.bytesIn=="number"?e.bytesIn:et(e.responseBody),bytesOut:typeof e.bytesOut=="number"?e.bytesOut:et(e.requestBody),requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null,requestCookies:e.requestCookies??null,responseCookies:e.responseCookies??null}}):[]}function nt(t){return Array.isArray(t)?t.map(e=>{let r=e.responseStatusCode??e.statusCode??0,s=e.timestamp??null;return {method:e.method??"GET",url:e.url??"",status:r,statusCode:r,type:"xhr",size:et(e.responseBody),duration:e.responseTimeMs??e.durationMs??0,responseTimeMs:e.responseTimeMs??e.durationMs??0,requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null,timestamp:s,startedAt:s}}):[]}function at(t){if(!Array.isArray(t))return [];let e=r=>{if(r==null)return String(r);if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}};return t.map(r=>{let s=r.status==="failed"?"failed":"passed",n=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,a=r.kind??r.type??"assertion",o=s==="failed"?`expected ${e(r.expected)}, received ${e(r.actual)}`:r.expected!==void 0?`expected ${e(r.expected)}`:null;return {...r.callId!=null?{callId:r.callId}:{},kind:a,description:n??r.description??`${a} assertion`,status:s,detail:o}})}async function he(t){return new Promise(e=>setTimeout(e,t))}function On(t){let e={};for(let[r,s]of Object.entries(t))s!=null&&(e[r]=s);return e}async function Er(t,e,r){for(let s=0;s<ge;s++)try{let n=await fetch(t,e);if(n.ok)return n;if(n.status===401&&r&&s===0){let a=await r();if(a){let o={...e,headers:{...e.headers,Authorization:`Bearer ${a}`}},i=await fetch(t,o);if(i.ok)return i}return null}if(n.status===429&&s<ge-1){let a=n.headers.get("Retry-After"),o=a?parseInt(a,10)*1e3:fe[s];!isNaN(o)&&o>0?await he(o):await he(fe[s]);continue}if(n.status>=500&&s<ge-1){await he(fe[s]);continue}return n}catch{if(s<ge-1){await he(fe[s]);continue}return null}return null}var qn=util.promisify(zlib.gzip);function Lr(t,e){if(!Array.isArray(t.tests))return t;let r=t.tests.map(s=>{let{consoleLogs:n,networkRequests:a,apiCalls:o,...i}=s;return e?i:{...i,...o!==void 0?{apiCalls:o}:{}}});return {...t,tests:r}}var Hn=["consoleLogs","networkRequests","apiCalls","actions","navigations","protocolAssertions"];function Un(t){if(!Array.isArray(t.tests))return t;let e=new Set(Hn),r=t.tests.map(s=>{let n={};for(let a in s)if(!e.has(a))if(a==="failure"&&s[a]&&typeof s[a]=="object"){let o=s[a];n.failure={message:o.message??null,line:o.line??null};}else n[a]=s[a];return n});return {...t,tests:r}}function $n(t){let e=new Set(["tests","timeline","unifiedTimeline","navigations"]),r={};for(let s in t)e.has(s)||(r[s]=t[s]);return r.tests=[],r}async function it(t,e=Dn){let r={"Content-Type":"application/json"},s=JSON.stringify(t),n=t,a=Array.isArray(n?.tests)?n.tests.length:0,o=i=>Buffer.byteLength(i,"utf-8")>e;if(a>0&&o(s)){let i=Math.max(1,Math.round(e/1048576));process.stderr.write(`[testrelic] WARNING: batch payload exceeds ${i}MB \u2014 dropping consoleLogs/networkRequests from ${a} test(s) to avoid HTTP 413. Console/network detail will be missing in the cloud.
2562
- `),s=JSON.stringify(Lr(n,false)),o(s)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${i}MB after dropping logs \u2014 also dropping apiCalls from ${a} test(s). API request/response detail will be missing in the cloud.
2563
- `),s=JSON.stringify(Lr(n,true))),o(s)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${i}MB \u2014 shedding remaining per-test detail (actions/navigations/assertions) from ${a} test(s). Only test results + summary will reach the cloud.
2564
- `),s=JSON.stringify(Un(n))),o(s)&&(process.stderr.write(`[testrelic] ERROR: batch still exceeds ${i}MB after shedding all per-test detail \u2014 uploading run summary only (${a} per-test result(s) omitted) to avoid losing the run to HTTP 413.
2565
- `),s=JSON.stringify($n(n)));}return Buffer.byteLength(s,"utf-8")>Fn?(r["Content-Encoding"]="gzip",{body:await qn(Buffer.from(s,"utf-8")),headers:r}):{body:s,headers:r}}async function Pr(t,e,r,s){let n=`${t}/runs`,{body:a,headers:o}=await it(r);o.Authorization=`Bearer ${e}`;let i=await Er(n,{method:"POST",headers:o,body:a},s);return i?.ok?{success:true,statusCode:i.status,error:null}:i?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:i?`Upload failed with status ${i.status}`:"Upload failed after retries",statusCode:i?.status??null,payload:r,targetEndpoint:n,method:"POST"}}async function Nr(t,e,r){let s=`${t}/runs/init`;try{let n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(On(r))});return n.ok?{runId:(await n.json()).runId}:null}catch{return null}}function Fr(t,e,r,s){let n=`${t}/runs/${r}/tests`;fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(s)}).catch(()=>{});}async function Dr(t,e,r,s){let n=`${t}/runs/${r}/finalize`;return (await Er(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(s)}))?.ok??false}function ot(t,e,r,s){let n=`${t}/runs/${r}/finalize`,a=new Date,o={finishedAt:a.toISOString(),duration:a.getTime()-new Date(s).getTime(),summary:{}};fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}).catch(()=>{});}var Wn="1.0.0",Br=10;function Or(t){return t instanceof Error?t.message:String(t)}function Kn(t){return t>=400&&t<500&&t!==408&&t!==429}function se(t,e,r,s,n,a,o,i){try{fs$1.mkdirSync(t,{recursive:!0});let d=Date.now(),l=`${d}-${e}-${r}.json`,u=path.join(t,l),g={version:Wn,queuedAt:new Date(d).toISOString(),reason:s,retryCount:0,targetEndpoint:n,method:a,payload:o,headers:i},m=u+".tmp";fs$1.writeFileSync(m,JSON.stringify(g,null,2),"utf-8"),fs$1.renameSync(m,u);}catch(d){d.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
2613
+ `,o=I(""),i=n;i+=I("TestRelic AI - Playwright Test Report"),i+=o;let d=[];if(t.passed>0&&d.push(`${t.passed} \u2713`),t.failed>0&&d.push(`${t.failed} \u2717`),t.flaky>0&&d.push(`${t.flaky} \u26A0`),t.skipped>0&&d.push(`${t.skipped} skipped`),t.timedout>0&&d.push(`${t.timedout} timedout`),i+=I(`Tests: ${t.total} total (${d.join(" ")})`),t.totalNavigations>0&&(i+=I(`Navigations: ${t.totalNavigations} visits across ${t.uniqueNavigationUrls} unique URLs`)),t.totalApiCalls>0){i+=I(`API Calls: ${t.totalApiCalls} calls across ${t.uniqueApiUrls} unique endpoints`);let l=Object.entries(t.apiCallsByMethod).filter(([,g])=>g>0).map(([g,m])=>`${g}: ${m}`);l.length>0&&(i+=I(` ${l.join(" ")}`));let u=Object.entries(t.apiCallsByStatusRange).filter(([,g])=>g>0).map(([g,m])=>`${g}: ${m}`);u.length>0&&(i+=I(` ${u.join(" ")}`)),t.apiResponseTime&&(i+=I(` Avg response: ${t.apiResponseTime.avg}ms P95: ${t.apiResponseTime.p95}ms`));}if(t.totalAssertions>0&&(i+=I(`Assertions: ${t.totalAssertions} total (${t.passedAssertions} \u2713 ${t.failedAssertions} \u2717)`)),t.totalActionSteps>0){let l=[],u=t.actionStepsByCategory;u.ui_action&&l.push(`${u.ui_action} UI`),u.assertion&&l.push(`${u.assertion} assertions`),u.custom_step&&l.push(`${u.custom_step} custom`);let g=l.length>0?` (${l.join(" ")})`:"";i+=I(`Actions: ${t.totalActionSteps} steps${g}`);}i+=I(`Report: ${r}`),i+=I(`Data: ${e}`),i+=a,i+=`For more information visit us at https://docs.testrelic.ai
2614
+ `,process.stderr.write(i);}var Tn=new Set(["pw:api","expect","test.step"]);function Sn(t){return t==="expect"?"assertion":t==="test.step"?"custom_step":"ui_action"}function Ye(t,e,r){if(Tn.has(t.category)){let s=[];for(let a of t.steps)Ye(a,e,s);let n=t.startTime.getTime()-e.getTime();r.push({title:t.title,category:Sn(t.category),timestamp:t.startTime.toISOString(),duration:t.duration,videoOffset:n>=0?n/1e3:null,status:t.error?"failed":"passed",error:t.error?.message??null,children:s});}else for(let s of t.steps)Ye(s,e,r);}function Rr(t,e){let r=[];for(let s of t)Ye(s,e,r);return r}var An=new Set(["localhost","127.0.0.1","0.0.0.0"]);function Ir(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&An.has(e.hostname)))throw core.createError(core.ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${e.protocol}//${e.hostname}`)}var In=3e3;async function Ze(t){let e=new AbortController,r=setTimeout(()=>e.abort(),In);try{return (await fetch(`${t}/health`,{method:"GET",signal:e.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function _r(t){return new Promise(e=>setTimeout(e,t))}async function Ar(t){try{let r=(await t.json()).error;if(r&&typeof r.message=="string"){let s=r.details;if(Array.isArray(s)&&s.length>0){let n=s.map(a=>`${a.field}: ${a.message}`).join(", ");return `${r.message} (${n})`}return r.message}}catch{}return `HTTP ${t.status}`}async function Qe(t,e,r){let s=new AbortController,n=setTimeout(()=>s.abort(),r);try{let a=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:s.signal});if(a.ok){let i=await a.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,orgId:i.orgId,orgName:i.orgName,userId:i.userId,userName:i.userName}}if(a.status===429){let i=a.headers.get("Retry-After"),d=i?parseInt(i,10)*1e3:5e3;if(!isNaN(d)&&d>0){await _r(d);let l=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:s.signal});if(l.ok){let u=await l.json();return {accessToken:u.accessToken,refreshToken:u.refreshToken,expiresIn:u.expiresIn,orgId:u.orgId,orgName:u.orgName,userId:u.userId,userName:u.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return a.status===400?{code:"validation_error",message:await Ar(a),statusCode:400}:a.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:a.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await Ar(a),statusCode:a.status}}catch(a){return a instanceof DOMException&&a.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 Xe(t){return "code"in t&&typeof t.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(t.code)}async function Mr(t,e,r){let s=new AbortController,n=setTimeout(()=>s.abort(),r);try{let a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:s.signal});if(a.status===429){let i=a.headers.get("Retry-After"),d=i?parseInt(i,10)*1e3:5e3;!isNaN(d)&&d>0&&(await _r(d),a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:s.signal}));}if(!a.ok)return null;let o=await a.json();return {accessToken:o.accessToken,refreshToken:o.refreshToken,expiresIn:o.expiresIn}}catch{return null}finally{clearTimeout(n);}}async function Lr(t,e,r,s,n,a){let o=new AbortController,i=setTimeout(()=>o.abort(),n);try{let d={gitId:r,displayName:s};a&&(d.branch=a);let l=await fetch(`${t}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(d),signal:o.signal});if(!l.ok)return null;let u=await l.json();return {repoId:u.repoId,displayName:u.displayName}}catch{return null}finally{clearTimeout(i);}}var Pn=5e3;function F(t,e){try{return child_process.execSync(t,{cwd:e,timeout:Pn,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function Er(t){let e=F("git rev-parse --abbrev-ref HEAD",t),r=F("git rev-parse --short HEAD",t),s=F("git log -1 --pretty=%s",t),n=F("git log -1 --format=%an",t)??F("git config user.name",t),a=Nn(t),o=a?te(a):null;return {branch:e,commitSha:r,commitMessage:s,commitAuthor:n,remoteUrl:o}}function Nn(t){let e=F("git remote get-url origin",t);if(e)return e;let r=F("git remote",t);if(!r)return null;let s=r.split(`
2615
+ `)[0]?.trim();return s?F(`git remote get-url ${s}`,t):null}function te(t){let e=t.trim();return e=e.replace(/^[a-z+]+:\/\//,""),e=e.replace(/^[^@]+@/,""),e=e.replace(/:(?!\d)/,"/"),e=e.replace(/\.git$/,""),e=e.replace(/\/+$/,""),e=e.replace(/^[^@/]+@/,""),e.toLowerCase()}function Pr(t){let e=t.split("/").filter(Boolean);return e[e.length-1]??t}function et(t){try{let e=fs$1.readFileSync(path.join(t,"package.json"),"utf-8"),r=JSON.parse(e);return typeof r.name=="string"&&r.name.length>0?r.name:null}catch{return null}}function re(t){let e=et(t);return e||`local/${path.basename(t)}`}var Fn=new Set(["smoke","regression","nightly","ci"]);function pe(){let t=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(t&&Fn.has(t))return t}var On=1048576,fe=[1e3,3e3,9e3],ge=3,qn=90*1048576,Hn=new Set(["e2e","mobile","unit"]);function rt(t){if(t&&t.length>0&&t.every(n=>n.testType==="api")){let n=new Map;for(let i of t){let d=i.apiProtocol??"rest";n.set(d,(n.get(d)??0)+1);}let a="rest",o=0;for(let[i,d]of n)d>o&&(o=d,a=i);return {testType:"api",apiProtocol:a,metadata:{testType:"api",primaryProtocol:a}}}let e=new Map;for(let n of t??[])Hn.has(n.testType)&&e.set(n.testType,(e.get(n.testType)??0)+1);let r=null,s=0;for(let[n,a]of e)a>s&&(s=a,r=n);return {testType:r??"e2e"}}function st(t,e,r,s,n,a){let o=a?.cloudPlatform?a.cloudPlatform:s?.provider&&s.provider!=="unknown"?s.provider:"local",i=pe(),d=rt(n),l=d.testType==="api"?d:null,u=l&&n?n.map(m=>m.apiProtocol?m:{...m,apiProtocol:l.apiProtocol}):n;return {runId:t.testRunId,repoGitId:e,startedAt:t.startedAt,summary:t.summary,timeline:t.timeline,environment:o,...i?{runType:i}:{},...l?{testType:l.testType,apiProtocol:l.apiProtocol,metadata:l.metadata}:{testType:d.testType},...u&&u.length>0?{tests:u}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...s?.provider?{ciProvider:s.provider}:{},...s?.runUrl?{ciRunUrl:s.runUrl}:{},...a?.cloudPlatform?{cloudPlatform:a.cloudPlatform}:{},...a?.cloudBuildId?{cloudBuildId:a.cloudBuildId}:{},...a?.cloudSessionId?{cloudSessionId:a.cloudSessionId}:{}}}function tt(t){return typeof t=="string"?Buffer.byteLength(t,"utf-8"):0}function nt(t){return Array.isArray(t)?t.map(e=>{let r=e.statusCode??e.responseStatusCode??null;return {...e.id!=null?{id:e.id}:{},...e.protocol!=null?{protocol:e.protocol}:{},method:e.method??null,url:e.url??null,statusCode:r,statusText:e.statusText??e.responseStatusText??null,ok:typeof r=="number"?r<400:e.ok??null,durationMs:e.durationMs??e.responseTimeMs??null,bytesIn:typeof e.bytesIn=="number"?e.bytesIn:tt(e.responseBody),bytesOut:typeof e.bytesOut=="number"?e.bytesOut:tt(e.requestBody),requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null,requestCookies:e.requestCookies??null,responseCookies:e.responseCookies??null}}):[]}function at(t){return Array.isArray(t)?t.map(e=>{let r=e.responseStatusCode??e.statusCode??0,s=e.timestamp??null;return {method:e.method??"GET",url:e.url??"",status:r,statusCode:r,type:"xhr",size:tt(e.responseBody),duration:e.responseTimeMs??e.durationMs??0,responseTimeMs:e.responseTimeMs??e.durationMs??0,requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null,timestamp:s,startedAt:s}}):[]}function it(t){if(!Array.isArray(t))return [];let e=r=>{if(r==null)return String(r);if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}};return t.map(r=>{let s=r.status==="failed"?"failed":"passed",n=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,a=r.kind??r.type??"assertion",o=s==="failed"?`expected ${e(r.expected)}, received ${e(r.actual)}`:r.expected!==void 0?`expected ${e(r.expected)}`:null;return {...r.callId!=null?{callId:r.callId}:{},kind:a,description:n??r.description??`${a} assertion`,status:s,detail:o}})}async function he(t){return new Promise(e=>setTimeout(e,t))}function Un(t){let e={};for(let[r,s]of Object.entries(t))s!=null&&(e[r]=s);return e}async function Fr(t,e,r){for(let s=0;s<ge;s++)try{let n=await fetch(t,e);if(n.ok)return n;if(n.status===401&&r&&s===0){let a=await r();if(a){let o={...e,headers:{...e.headers,Authorization:`Bearer ${a}`}},i=await fetch(t,o);if(i.ok)return i}return null}if(n.status===429&&s<ge-1){let a=n.headers.get("Retry-After"),o=a?parseInt(a,10)*1e3:fe[s];!isNaN(o)&&o>0?await he(o):await he(fe[s]);continue}if(n.status>=500&&s<ge-1){await he(fe[s]);continue}return n}catch{if(s<ge-1){await he(fe[s]);continue}return null}return null}var $n=util.promisify(zlib.gzip);function Nr(t,e){if(!Array.isArray(t.tests))return t;let r=t.tests.map(s=>{let{consoleLogs:n,networkRequests:a,apiCalls:o,...i}=s;return e?i:{...i,...o!==void 0?{apiCalls:o}:{}}});return {...t,tests:r}}var zn=["consoleLogs","networkRequests","apiCalls","actions","navigations","protocolAssertions"];function jn(t){if(!Array.isArray(t.tests))return t;let e=new Set(zn),r=t.tests.map(s=>{let n={};for(let a in s)if(!e.has(a))if(a==="failure"&&s[a]&&typeof s[a]=="object"){let o=s[a];n.failure={message:o.message??null,line:o.line??null};}else n[a]=s[a];return n});return {...t,tests:r}}function Vn(t){let e=new Set(["tests","timeline","unifiedTimeline","navigations"]),r={};for(let s in t)e.has(s)||(r[s]=t[s]);return r.tests=[],r}async function ot(t,e=qn){let r={"Content-Type":"application/json"},s=JSON.stringify(t),n=t,a=Array.isArray(n?.tests)?n.tests.length:0,o=i=>Buffer.byteLength(i,"utf-8")>e;if(a>0&&o(s)){let i=Math.max(1,Math.round(e/1048576));process.stderr.write(`[testrelic] WARNING: batch payload exceeds ${i}MB \u2014 dropping consoleLogs/networkRequests from ${a} test(s) to avoid HTTP 413. Console/network detail will be missing in the cloud.
2616
+ `),s=JSON.stringify(Nr(n,false)),o(s)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${i}MB after dropping logs \u2014 also dropping apiCalls from ${a} test(s). API request/response detail will be missing in the cloud.
2617
+ `),s=JSON.stringify(Nr(n,true))),o(s)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${i}MB \u2014 shedding remaining per-test detail (actions/navigations/assertions) from ${a} test(s). Only test results + summary will reach the cloud.
2618
+ `),s=JSON.stringify(jn(n))),o(s)&&(process.stderr.write(`[testrelic] ERROR: batch still exceeds ${i}MB after shedding all per-test detail \u2014 uploading run summary only (${a} per-test result(s) omitted) to avoid losing the run to HTTP 413.
2619
+ `),s=JSON.stringify(Vn(n)));}return Buffer.byteLength(s,"utf-8")>On?(r["Content-Encoding"]="gzip",{body:await $n(Buffer.from(s,"utf-8")),headers:r}):{body:s,headers:r}}async function Dr(t,e,r,s){let n=`${t}/runs`,{body:a,headers:o}=await ot(r);o.Authorization=`Bearer ${e}`;let i=await Fr(n,{method:"POST",headers:o,body:a},s);return i?.ok?{success:true,statusCode:i.status,error:null}:i?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:i?`Upload failed with status ${i.status}`:"Upload failed after retries",statusCode:i?.status??null,payload:r,targetEndpoint:n,method:"POST"}}async function Br(t,e,r){let s=`${t}/runs/init`;try{let n=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(Un(r))});return n.ok?{runId:(await n.json()).runId}:null}catch{return null}}function Or(t,e,r,s){let n=`${t}/runs/${r}/tests`;fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(s)}).catch(()=>{});}async function qr(t,e,r,s){let n=`${t}/runs/${r}/finalize`;return (await Fr(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(s)}))?.ok??false}function lt(t,e,r,s){let n=`${t}/runs/${r}/finalize`,a=new Date,o={finishedAt:a.toISOString(),duration:a.getTime()-new Date(s).getTime(),summary:{}};fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}).catch(()=>{});}var Yn="1.0.0",Hr=10;function Ur(t){return t instanceof Error?t.message:String(t)}function Zn(t){return t>=400&&t<500&&t!==408&&t!==429}function se(t,e,r,s,n,a,o,i){try{fs$1.mkdirSync(t,{recursive:!0});let d=Date.now(),l=`${d}-${e}-${r}.json`,u=path.join(t,l),g={version:Yn,queuedAt:new Date(d).toISOString(),reason:s,retryCount:0,targetEndpoint:n,method:a,payload:o,headers:i},m=u+".tmp";fs$1.writeFileSync(m,JSON.stringify(g,null,2),"utf-8"),fs$1.renameSync(m,u);}catch(d){d.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
2566
2620
  `):process.stderr.write(`\u26A0 TestRelic: Unable to queue upload data.
2567
- `);}}async function $r(t,e,r){let s;try{s=fs$1.readdirSync(t).filter(a=>a.endsWith(".json")&&!a.endsWith(".tmp")).sort();}catch{return}if(s.length===0)return;let n=[];for(let a=0;a<s.length;a+=Br)n.push(s.slice(a,a+Br));for(let a of n)for(let o of a){let i=path.join(t,o),d;try{if(!fs$1.statSync(i).isFile())continue;let u=JSON.parse(fs$1.readFileSync(i,"utf-8"));if(!core.isValidQueueEntry(u)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${o}
2568
- `),fs$1.unlinkSync(i);continue}d=u;}catch(l){process.stderr.write(`\u26A0 TestRelic: Skipping unreadable queue file ${o}: ${Or(l)}
2569
- `);try{fs$1.unlinkSync(i);}catch{}continue}try{let{body:l,headers:u}=await it(d.payload),g={...d.headers,...u,Authorization:`Bearer ${r}`},m=await fetch(d.targetEndpoint,{method:d.method,headers:g,body:l});if(m.ok)fs$1.unlinkSync(i);else if(Kn(m.status)){process.stderr.write(`\u26A0 TestRelic: Queue entry ${o} rejected (HTTP ${m.status}) \u2014 moving aside; it will not be retried.
2621
+ `);}}async function Vr(t,e,r){let s;try{s=fs$1.readdirSync(t).filter(a=>a.endsWith(".json")&&!a.endsWith(".tmp")).sort();}catch{return}if(s.length===0)return;let n=[];for(let a=0;a<s.length;a+=Hr)n.push(s.slice(a,a+Hr));for(let a of n)for(let o of a){let i=path.join(t,o),d;try{if(!fs$1.statSync(i).isFile())continue;let u=JSON.parse(fs$1.readFileSync(i,"utf-8"));if(!core.isValidQueueEntry(u)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${o}
2622
+ `),fs$1.unlinkSync(i);continue}d=u;}catch(l){process.stderr.write(`\u26A0 TestRelic: Skipping unreadable queue file ${o}: ${Ur(l)}
2623
+ `);try{fs$1.unlinkSync(i);}catch{}continue}try{let{body:l,headers:u}=await ot(d.payload),g={...d.headers,...u,Authorization:`Bearer ${r}`},m=await fetch(d.targetEndpoint,{method:d.method,headers:g,body:l});if(m.ok)fs$1.unlinkSync(i);else if(Zn(m.status)){process.stderr.write(`\u26A0 TestRelic: Queue entry ${o} rejected (HTTP ${m.status}) \u2014 moving aside; it will not be retried.
2570
2624
  `);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 ${m.status} for ${o}; will retry later.
2571
- `);return}}catch(l){process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 ${Or(l)}; will retry later.
2572
- `);return}}}function zr(t,e){try{let r=fs$1.readdirSync(t).filter(n=>(n.endsWith(".json")||n.endsWith(".failed"))&&!n.endsWith(".tmp")),s=Date.now();for(let n of r){let a=path.join(t,n);try{let o=fs$1.readFileSync(a,"utf-8"),d=JSON.parse(o).queuedAt;if(typeof d=="string"){let l=new Date(d).getTime();s-l>e&&fs$1.unlinkSync(a);}}catch{try{fs$1.unlinkSync(a);}catch{}}}}catch{}}var ta=3e5,ra=864e5,sa=6e4,jr=3e4,ct="https://platform.testrelic.ai/settings/api-keys";function Vr(t){return new Promise(e=>{let r=setTimeout(e,t);typeof r?.unref=="function"&&r.unref();})}var me=class{constructor(e){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=e,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.
2573
- `);return}try{if(Cr(this.config.endpoint),this.gitMetadata=Ir(),!await Ye(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.
2574
- `);return}let r=await Ze(this.config.endpoint,this.config.apiKey,this.config.timeout);if(Qe(r)){this.handleAuthError(r.code,r.statusCode);return}let s=r;this.authState={mode:"cloud",accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:Date.now()+s.expiresIn*1e3,orgId:s.orgId,orgName:s.orgName,userId:s.userId,userName:s.userName},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${s.orgName} / ${s.userName})
2575
- `),await this.resolveRepoId(),this.config.queueDirectory&&(zr(this.config.queueDirectory,this.config.queueMaxAge),this.startBackgroundFlush()),this.startHealthCheck();}catch(e){this.setLocalMode("unexpected_error"),process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. Running in local mode. ${e instanceof Error?e.message:String(e)}
2576
- `);}}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 e=this.authState.expiresAt??0;if(Date.now()+ta<e)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await Ar(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(e){this.authState.mode!=="local"&&(this.authState.mode="local",this.failureReason=e,process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${e}).
2577
- `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,Vr(jr)]);}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(e){this.authState.mode="local",this.failureReason=e;}handleAuthError(e,r){switch(e){case "invalid_key":this.setLocalMode("invalid_api_key"),process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
2578
- \u2192 Manage keys: ${ct}
2625
+ `);return}}catch(l){process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 ${Ur(l)}; will retry later.
2626
+ `);return}}}function Gr(t,e){try{let r=fs$1.readdirSync(t).filter(n=>(n.endsWith(".json")||n.endsWith(".failed"))&&!n.endsWith(".tmp")),s=Date.now();for(let n of r){let a=path.join(t,n);try{let o=fs$1.readFileSync(a,"utf-8"),d=JSON.parse(o).queuedAt;if(typeof d=="string"){let l=new Date(d).getTime();s-l>e&&fs$1.unlinkSync(a);}}catch{try{fs$1.unlinkSync(a);}catch{}}}}catch{}}var na=3e5,aa=864e5,ia=6e4,Wr=3e4,ut="https://platform.testrelic.ai/settings/api-keys";function Kr(t){return new Promise(e=>{let r=setTimeout(e,t);typeof r?.unref=="function"&&r.unref();})}var me=class{constructor(e){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=e,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.
2627
+ `);return}try{if(Ir(this.config.endpoint),this.gitMetadata=Er(),!await Ze(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.
2628
+ `);return}let r=await Qe(this.config.endpoint,this.config.apiKey,this.config.timeout);if(Xe(r)){this.handleAuthError(r.code,r.statusCode);return}let s=r;this.authState={mode:"cloud",accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:Date.now()+s.expiresIn*1e3,orgId:s.orgId,orgName:s.orgName,userId:s.userId,userName:s.userName},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${s.orgName} / ${s.userName})
2629
+ `),await this.resolveRepoId(),this.config.queueDirectory&&(Gr(this.config.queueDirectory,this.config.queueMaxAge),this.startBackgroundFlush()),this.startHealthCheck();}catch(e){this.setLocalMode("unexpected_error"),process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. Running in local mode. ${e instanceof Error?e.message:String(e)}
2630
+ `);}}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 e=this.authState.expiresAt??0;if(Date.now()+na<e)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await Mr(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(e){this.authState.mode!=="local"&&(this.authState.mode="local",this.failureReason=e,process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${e}).
2631
+ `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,Kr(Wr)]);}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(e){this.authState.mode="local",this.failureReason=e;}handleAuthError(e,r){switch(e){case "invalid_key":this.setLocalMode("invalid_api_key"),process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
2632
+ \u2192 Manage keys: ${ut}
2579
2633
  `);break;case "expired_key":this.setLocalMode("expired_api_key"),process.stderr.write(`\u26A0 TestRelic: API key has expired. Running in local mode.
2580
- \u2192 Generate a new key: ${ct}
2634
+ \u2192 Generate a new key: ${ut}
2581
2635
  `);break;case "validation_error":this.setLocalMode("validation_error"),process.stderr.write(`\u26A0 TestRelic: API key format invalid. Running in local mode.
2582
- \u2192 Manage keys: ${ct}
2636
+ \u2192 Manage keys: ${ut}
2583
2637
  `);break;case "rate_limited":this.setLocalMode("rate_limited"),process.stderr.write(`\u26A0 TestRelic: Rate limited during authentication. Running in local mode.
2584
2638
  `);break;case "timeout":this.setLocalMode("auth_timeout"),process.stderr.write(`\u26A0 TestRelic: Authentication timed out. Running in local mode.
2585
2639
  `);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
2586
- `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?te(this.gitMetadata.remoteUrl):null,r=e?Mr(e):this.config.projectName??re(process.cwd()),s=e??this.config.projectName??re(process.cwd()),n=this.readRepoCache(s);if(n){this.repoId=n.repoId;return}try{let a=await _r(this.config.endpoint,this.authState.accessToken,s,r,this.config.timeout,this.gitMetadata?.branch);a&&(this.repoId=a.repoId,this.writeRepoCache(s,a.repoId,a.displayName));}catch{}!e&&!this.config.projectName&&!Xe(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
2587
- `);}readRepoCache(e){if(!this.config)return null;let r=path.join(this.config.queueDirectory,"..","cache","repo.json");try{if(!fs$1.existsSync(r))return null;let s=fs$1.readFileSync(r,"utf-8"),n=JSON.parse(s);if(n.gitId!==e||Date.now()-n.resolvedAt>ra)return null;let a=this.hashApiKey();return a&&n.apiKeyHash!==a?null:n}catch{return null}}writeRepoCache(e,r,s){if(!this.config)return;let n=path.join(this.config.queueDirectory,"..","cache"),a=path.join(n,"repo.json");try{fs$1.mkdirSync(n,{recursive:!0});let o={repoId:r,gitId:e,displayName:s,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=a+".tmp";fs$1.writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),fs$1.renameSync(i,a);}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 e=this.authState.accessToken,r=this.config.queueDirectory,s=this.config.endpoint;this.flushPromise=Promise.race([$r(r,s,e),Vr(jr)]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let e=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await Ye(e))return;if(this.config?.apiKey){let s=await Ze(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!Qe(s)){let n=s;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.
2588
- `),this.startBackgroundFlush();}}}catch{}},sa),typeof this.healthCheckTimer?.unref=="function"&&this.healthCheckTimer.unref();}};function Gr(t,e,r,s){let n=[],a=[],o=null,i=0,d=null,l=0,u=null,g=0,m=t.filter(c=>c.name===core.ATTACHMENT_NAME&&c.body),p=false;if(m.length>0)for(let c of m)try{let h=JSON.parse(c.body.toString());if(core.isTestRelicFilePayload(h)){n=n.concat(h.navigations),a=a.concat(h.apiAssertions),h.networkRequestsFile&&(o=h.networkRequestsFile,i+=h.networkRequestsCount),h.consoleLogsFile&&(d=h.consoleLogsFile,l+=h.consoleLogsCount),h.apiCallsFile&&(u=h.apiCallsFile,g+=h.apiCallsCount),p=!0;continue}if(core.isTestRelicDataPayload(h)){n=n.concat(h.navigations),Array.isArray(h.apiAssertions)&&(a=a.concat(h.apiAssertions)),i+=h.networkRequests?.length??0,g+=h.apiCalls?.length??0;let v=h.consoleLogs;Array.isArray(v)&&(l+=v.length),p=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
2640
+ `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?te(this.gitMetadata.remoteUrl):null,r=e?Pr(e):this.config.projectName??re(process.cwd()),s=e??this.config.projectName??re(process.cwd()),n=this.readRepoCache(s);if(n){this.repoId=n.repoId;return}try{let a=await Lr(this.config.endpoint,this.authState.accessToken,s,r,this.config.timeout,this.gitMetadata?.branch);a&&(this.repoId=a.repoId,this.writeRepoCache(s,a.repoId,a.displayName));}catch{}!e&&!this.config.projectName&&!et(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
2641
+ `);}readRepoCache(e){if(!this.config)return null;let r=path.join(this.config.queueDirectory,"..","cache","repo.json");try{if(!fs$1.existsSync(r))return null;let s=fs$1.readFileSync(r,"utf-8"),n=JSON.parse(s);if(n.gitId!==e||Date.now()-n.resolvedAt>aa)return null;let a=this.hashApiKey();return a&&n.apiKeyHash!==a?null:n}catch{return null}}writeRepoCache(e,r,s){if(!this.config)return;let n=path.join(this.config.queueDirectory,"..","cache"),a=path.join(n,"repo.json");try{fs$1.mkdirSync(n,{recursive:!0});let o={repoId:r,gitId:e,displayName:s,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=a+".tmp";fs$1.writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),fs$1.renameSync(i,a);}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 e=this.authState.accessToken,r=this.config.queueDirectory,s=this.config.endpoint;this.flushPromise=Promise.race([Vr(r,s,e),Kr(Wr)]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let e=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await Ze(e))return;if(this.config?.apiKey){let s=await Qe(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!Xe(s)){let n=s;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.
2642
+ `),this.startBackgroundFlush();}}}catch{}},ia),typeof this.healthCheckTimer?.unref=="function"&&this.healthCheckTimer.unref();}};function Jr(t,e,r,s){let n=[],a=[],o=null,i=0,d=null,l=0,u=null,g=0,m=t.filter(c=>c.name===core.ATTACHMENT_NAME&&c.body),p=false;if(m.length>0)for(let c of m)try{let h=JSON.parse(c.body.toString());if(core.isTestRelicFilePayload(h)){n=n.concat(h.navigations),a=a.concat(h.apiAssertions),h.networkRequestsFile&&(o=h.networkRequestsFile,i+=h.networkRequestsCount),h.consoleLogsFile&&(d=h.consoleLogsFile,l+=h.consoleLogsCount),h.apiCallsFile&&(u=h.apiCallsFile,g+=h.apiCallsCount),p=!0;continue}if(core.isTestRelicDataPayload(h)){n=n.concat(h.navigations),Array.isArray(h.apiAssertions)&&(a=a.concat(h.apiAssertions)),i+=h.networkRequests?.length??0,g+=h.apiCalls?.length??0;let v=h.consoleLogs;Array.isArray(v)&&(l+=v.length),p=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
2589
2643
  `);}return p||(n=e.filter(c=>c.type==="lambdatest-navigation"&&c.description).map(c=>{try{return JSON.parse(c.description)}catch{return null}}).filter(c=>c!==null)),n.length===0&&i===0&&g===0&&!s&&!p&&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.
2590
- `),{navigations:n,apiAssertions:a,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:d,consoleLogsCount:l,apiCallsFile:u,apiCallsCount:g}}function ve(t=process.env){let e=oa(t.TESTRELIC_CLOUD_PLATFORM);if(e)return {cloudPlatform:e,cloudBuildId:t.TESTRELIC_CLOUD_BUILD_ID||void 0,cloudSessionId:t.TESTRELIC_CLOUD_SESSION_ID||void 0};if(t.BROWSERSTACK_USERNAME||t.BROWSERSTACK_ACCESS_KEY)return {cloudPlatform:"browserstack",cloudBuildId:t.BROWSERSTACK_BUILD_NAME||t.BROWSERSTACK_BUILD_ID||void 0,cloudSessionId:t.BROWSERSTACK_SESSION_ID||void 0};if(t.LT_USERNAME||t.LAMBDATEST_USERNAME||t.LT_ACCESS_KEY||t.LAMBDATEST_ACCESS_KEY)return {cloudPlatform:"lambdatest",cloudBuildId:t.LT_BUILD||t.LAMBDATEST_BUILD||void 0,cloudSessionId:t.LT_SESSION_ID||t.LAMBDATEST_SESSION_ID||void 0};let r=t.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 oa(t){if(!t)return;let e=t.toLowerCase().trim();if(e==="browserstack"||e==="bs")return "browserstack";if(e==="lambdatest"||e==="lt")return "lambdatest"}var pa=5,ye=[1e3,3e3,9e3],V=3,fa={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip"},ut=0,pt=[];async function ga(){ut>=pa&&await new Promise(t=>pt.push(t)),ut++;}function ha(){ut--,pt.length>0&&pt.shift()();}async function be(t){return new Promise(e=>setTimeout(e,t))}function ma(t){let e=t.substring(t.lastIndexOf(".")).toLowerCase();return fa[e]??"application/octet-stream"}function va(t){try{return fs$1.statSync(t).size}catch{return 0}}async function ya(t,e,r,s,n){let a=`${t}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:path.basename(r.filePath),contentType:n,type:r.type,sizeBytes:s});for(let i=0;i<V;i++)try{let d=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:o});if(d.ok)return await d.json();if(d.status>=500&&i<V-1){await be(ye[i]);continue}return null}catch{if(i<V-1){await be(ye[i]);continue}return null}return null}async function ba(t,e,r,s){for(let n=0;n<V;n++)try{let a=fs$1.createReadStream(e),o=stream.Readable.toWeb(a),i=await fetch(t,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(s)},body:o,duplex:"half"});if(i.ok)return !0;if(i.status>=500&&n<V-1){await be(ye[n]);continue}return !1}catch{if(n<V-1){await be(ye[n]);continue}return false}return false}async function xa(t,e,r){let s=`${t}/artifacts/confirm`;try{return (await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({artifactId:r})})).ok}catch{return false}}async function wa(t,e,r,s){let n=va(r.filePath);if(n===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(n>s*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let a=ma(r.filePath);await ga();try{let o=await ya(t,e,r,n,a);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await ba(o.uploadUrl,r.filePath,a,n))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let d=await xa(t,e,o.artifactId);return {success:d,storageKey:o.storageKey,artifactId:o.artifactId,error:d?null:"confirm_failed"}}finally{ha();}}async function Wr(t,e,r,s){let n=new Map,a=r.map(async o=>{let i=await wa(t,e,o,s);n.set(o.filePath,i);});return await Promise.allSettled(a),n}function ft(t){let r=t.getGitMetadata()?.remoteUrl;return r?te(r):t.getConfig()?.projectName??re(process.cwd())}async function Jr(t,e,r,s,n){if(!t.isCloudMode()||e!=="realtime"&&e!=="both"||!await t.ensureValidToken())return null;let o=t.getGitMetadata(),i=P(),d=ve(),l=pe();return (await Nr(t.getEndpoint(),t.getAccessToken(),{runId:r,repoGitId:ft(t),branch:o?.branch??null,commit:o?.commitSha??null,commitMessage:o?.commitMessage??null,commitAuthor:o?.commitAuthor??null,startedAt:s,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 ka=true,Ta=50;async function Sa(t,e,r,s){let n=new Map;if(!(e?.uploadArtifacts??ka)||!await t.ensureValidToken())return n;let i=[],d=new Map;for(let p of s){if(p.artifacts.screenshot){let f=path.join(p.outputDir,p.artifacts.screenshot);i.push({filePath:f,runId:r,testId:p.testId,type:"screenshot"}),d.set(f,{testId:p.testId,field:"screenshot"});}if(p.artifacts.video){let f=path.join(p.outputDir,p.artifacts.video);i.push({filePath:f,runId:r,testId:p.testId,type:"video"}),d.set(f,{testId:p.testId,field:"video"});}}if(i.length===0)return n;let l=e?.artifactMaxSizeMb??Ta,u=await Wr(t.getEndpoint(),t.getAccessToken(),i,l),g=new Map;for(let[p,f]of u){if(!f.success||!f.storageKey)continue;let c=d.get(p);if(!c)continue;let h=g.get(c.testId)??{};c.field==="screenshot"&&(h.screenshotKey=f.storageKey),c.field==="video"&&(h.videoKey=f.storageKey),g.set(c.testId,h);}for(let p of s){let f=g.get(p.testId);n.set(p.testId,{...p.artifacts,...f?.screenshotKey?{screenshotKey:f.screenshotKey}:{},...f?.videoKey?{videoKey:f.videoKey}:{}});}let m=Array.from(u.values()).filter(p=>p.success).length;return m>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${m} artifact(s) to cloud storage.
2591
- `),n}async function gt(t,e,r,s,n,a,o,i,d,l,u){try{if(t.isCloudMode()&&n&&(r==="realtime"||r==="both")){let m=await t.ensureValidToken(),p=t.getGitMetadata(),f=tt(u),c={finishedAt:o,duration:i,summary:d,...p?.commitMessage?{commitMessage:p.commitMessage}:{},testType:f.testType,...f.testType==="api"?{apiProtocol:f.apiProtocol,metadata:f.metadata}:{}};if(m){if(!await Dr(t.getEndpoint(),t.getAccessToken(),n,c)){let v=e?.queueDirectory??".testrelic/queue";se(v,s,"finalize","finalize_failed_after_retries",`${t.getEndpoint()}/runs/${n}/finalize`,"POST",c,{"Content-Type":"application/json"});}}else {let h=e?.queueDirectory??".testrelic/queue";se(h,s,"finalize",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs/${n}/finalize`,"POST",c,{"Content-Type":"application/json"});}}let g=new Map;if(t.isCloudMode()&&l&&l.length>0&&(g=await Sa(t,e,s,l)),t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await t.ensureValidToken()){let p=t.getGitMetadata(),f=P(),c=ft(t),h=Ca(a,g),v=rt(h,c,p,f,u,ve()),w=await Pr(t.getEndpoint(),t.getAccessToken(),v,async()=>await t.ensureValidToken()?t.getAccessToken():null);if(!w.success){let x=w,T=e?.queueDirectory??".testrelic/queue";se(T,s,"batch",x.reason,x.targetEndpoint,x.method,x.payload,{"Content-Type":"application/json"});}}else {let p=e?.queueDirectory??".testrelic/queue",f=t.getGitMetadata(),c=P(),h=ft(t),v=rt(a,h,f,c,void 0,ve());se(p,s,"batch",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs`,"POST",v,{"Content-Type":"application/json"});}await t.dispose();}catch{try{await t.dispose();}catch{}}}function Ca(t,e){if(e.size===0)return t;let r=t.timeline.map(s=>{let n=s.testId;if(!n)return s;let a=e.get(n);return a?{...s,...a.screenshotKey?{screenshotKey:a.screenshotKey}:{},...a.videoKey?{videoKey:a.videoKey}:{}}:s});return {...t,timeline:r}}function B(t){try{return fs$1.readFileSync(t,"utf-8").split(`
2592
- `).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function mt(t){switch(t){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function Ea(t,e,r){let s=`${t}::${e}::${r}`;return crypto.createHash("sha256").update(s).digest("hex").substring(0,16)}function Pa(t){return t.length<=3?"":t[t.length-2]}function Na(t){let e=t.findIndex(r=>r.status==="passed");return e>0?`passed on retry ${e}`:null}function Fa(t){return t===null?"error":t>=200&&t<300?"2xx":t>=300&&t<400?"3xx":t>=400&&t<500?"4xx":t>=500&&t<600?"5xx":"error"}function Xr(t,e){for(let r of t)e[r.category]=(e[r.category]??0)+1,r.children.length>0&&Xr(r.children,e);}function Da(t){if(t.length===0)return null;let e=[...t].sort((s,n)=>s-n),r=e.reduce((s,n)=>s+n,0);return {avg:Math.round(r/e.length),min:e[0],max:e[e.length-1],p50:U(e,50),p95:U(e,95),p99:U(e,99)}}var es=2e5,xe=1e5;function Qr(t,e,r,s,n,a,o){let i={retryIndex:t,apiCalls:e?.length??0,apiUrls:[],methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,assertions:r.length,navigations:s.length,navUrls:[],networkRequests:n,consoleLogs:a,actionSteps:o?.length??0,actionCategories:{}};if(e){let l=new Set;for(let u of e){let g=typeof u.method=="string"?u.method:"OTHER";i.methodCounts[g]=(i.methodCounts[g]??0)+1;let m=typeof u.url=="string"?u.url:null;m&&l.size<xe&&l.add(We(m));let p=typeof u.responseStatusCode=="number"?u.responseStatusCode:typeof u.statusCode=="number"?u.statusCode:null,f=p!==null&&Number.isFinite(p)?p:null;i.statusRanges[Fa(f)]++;let c=typeof u.responseTimeMs=="number"?u.responseTimeMs:typeof u.durationMs=="number"?u.durationMs:null;c!==null&&Number.isFinite(c)&&i.responseTimes.length<es&&i.responseTimes.push(c);}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 s)l.url&&d.size<xe&&d.add(l.url);return i.navUrls=Array.from(d),o&&Xr(o,i.actionCategories),i}function Ba(){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 Oa(t){return process.env.BROWSERSTACK_USERNAME?"BrowserStack":t?{"github-actions":"GitHub Actions","gitlab-ci":"GitLab CI",jenkins:"Jenkins",circleci:"CircleCI","bitbucket-pipelines":"Bitbucket Pipelines"}[t.provider]??"CI":"Local"}function qa(){let t=os.platform();return t==="win32"?"Windows":t==="darwin"?"macOS":"Linux"}function Ha(t){let e=t.parent?.project?.()?.use;if(!e)return;let{browserName:r,channel:s}=e;if(s){let a=s.toLowerCase();return a==="chrome"||a==="chrome-stable"?"Chrome":a.startsWith("chrome-beta")?"Chrome Beta":a.startsWith("chrome-dev")?"Chrome Dev":a.startsWith("chrome-canary")?"Chrome Canary":a==="msedge"||a==="msedge-stable"?"Microsoft Edge":a.startsWith("msedge-beta")?"Edge Beta":a.startsWith("msedge-dev")?"Edge Dev":a.startsWith("msedge-canary")?"Edge Canary":s}if(r){let a=r.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":r}let n=e.defaultBrowserType;if(n){let a=n.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":n}}function Ua(t,e,r){let s=r.parent?.project?.(),n="unknown";s!==void 0&&(s.use.isMobile===true?n="mobile":n="e2e");let a=["e2e","api","unit","mobile"];for(let d of a)if(t.some(l=>l===`@${d}`||l===d))return d;let o=e.replace(/\\/g,"/"),i=["e2e","api","unit"];for(let d of i)if(o.includes(`/${d}/`))return d;return n}var $a="__testrelic_api_config";function za(t){return JSON.stringify(t,(e,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var we=class{constructor(e){this.rootDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.navigationsCaptured=false;this.testCount=0;this.cloudClient=null;this.cloudRunId=null;this.runTimestamp="";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};this.streamingTestAgg=new Map;this.config=Nt(e),this.apiConfig=Pt(e);}upsertAggContribution(e,r){let s=this.streamingTestAgg.get(e);(!s||r.retryIndex>s.retryIndex)&&this.streamingTestAgg.set(e,r);}async onBegin(e,r){try{if(this.rootDir=e.rootDir,this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??crypto.randomUUID(),this.config.reportMode==="auto"){let o=r.allTests().length;this.activeReportMode=o>=this.config.streamingThreshold?"streaming":"embedded";}else this.activeReportMode=this.config.reportMode;let s=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${s} tests)
2593
- `),this.activeReportMode==="streaming"){let o=path.dirname(this.config.outputPath);this.streamingWriter=new Y(o);let i=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let d={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()};this.streamingWriter.writeSummary(d);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let d=this.cloudClient.getAccessToken();d&&ot(this.cloudClient.getEndpoint(),d,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",i),process.on("SIGINT",i);}if(this.config.includeArtifacts){let o=path.dirname(this.config.outputPath);this.runTimestamp=dr(path.join(o,"artifacts"));try{hr(path.join(o,"artifacts"));}catch{}}let n=P();this.detectedOs=qa(),this.detectedSource=Oa(n);let a=await H(async()=>(this.cloudClient=new me(this.config.cloud),await this.cloudClient.initialize(),Jr(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource)),vr,"Cloud initialization");if(this.cloudRunId=a??null,a===void 0&&this.cloudClient?.switchToLocalMode("init_error"),this.activeReportMode!=="streaming"){let o=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let i=this.cloudClient.getAccessToken();i&&ot(this.cloudClient.getEndpoint(),i,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",o),process.on("SIGINT",o);}}catch{}}onTestBegin(e,r){try{e.annotations.push({type:$a,description:za(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let s=r,n=e.outcome(),a;n==="flaky"?a="flaky":n==="skipped"?a="skipped":a=mt(s.status);let o=s.startTime.toISOString(),i=new Date(s.startTime.getTime()+s.duration).toISOString(),d=e.tags?[...e.tags]:e.annotations.filter(C=>C.type==="tag").map(C=>C.description??""),l=Gr(s.attachments,e.annotations,e.title,a==="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 u=null;if(a==="failed"||a==="flaky"){let S=(a==="flaky"?e.results.find(O=>O.status!=="passed")?.errors??[]:s.errors)[0];if(S){let O=Dt(this.config.redactPatterns),W=S.location?.line??null,K=null;this.config.includeCodeSnippets&&W!==null&&S.location?.file&&(K=Ft(S.location.file,W,this.config.codeContextLines),K&&(K=O(K))),u={message:O(S.message??"Unknown error"),line:W,code:K,stack:this.config.includeStackTrace&&S.stack?O(S.stack):null};}}let g=e.titlePath().filter(Boolean),m=path.relative(this.rootDir||".",e.location.file),p=Pa(g),f=g.join(" > "),c=m,h=Ea(c,p,f),v=Ua(d,c,e),w=v!=="mobile"&&l.apiCallsCount>0?"api":v,x=n==="flaky",T=Na(e.results),M=mt(e.expectedStatus),y=mt(s.status),k=null;if(this.config.includeArtifacts&&a!=="skipped"&&s.attachments){let C=path.dirname(this.config.outputPath),S=g[g.length-1]??e.title;k=cr(s.attachments,S,s.retry,C,this.runTimestamp||void 0);}let R=this.config.includeActionSteps&&s.steps?Tr(s.steps,s.startTime):null,$=Ha(e),L={titlePath:g,title:f,status:a,duration:s.duration,startedAt:o,completedAt:i,retryCount:e.results.length-1,retry:s.retry,tags:d,failure:u,specFile:m,navigations:l.navigations,testId:h,filePath:c,suiteName:p,testType:w,isFlaky:x,retryStatus:T,expectedStatus:M,actualStatus:y,artifacts:k,apiAssertions:l.apiAssertions,actions:R,networkRequestsFile:l.networkRequestsFile,networkRequestsCount:l.networkRequestsCount,consoleLogsFile:l.consoleLogsFile,consoleLogsCount:l.consoleLogsCount,apiCallsFile:l.apiCallsFile,apiCallsCount:l.apiCallsCount,browser:$,os:this.detectedOs||void 0,source:this.detectedSource||void 0},vt=l.consoleLogsFile&&l.consoleLogsCount>0?B(l.consoleLogsFile):void 0,ke=l.networkRequestsFile&&l.networkRequestsCount>0?B(l.networkRequestsFile):void 0,G=l.apiCallsFile&&l.apiCallsCount>0?B(l.apiCallsFile):void 0,yt=G?st(G):void 0,bt=!ke&&G?nt(G):void 0,xt=l.apiAssertions&&l.apiAssertions.length>0?at(l.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:h,title:f,status:a,duration:s.duration,suiteName:p,filePath:c,testType:w,isFlaky:x,startedAt:o,completedAt:i,tags:d,failure:u,retry:s.retry,retryCount:e.results.length-1,retryStatus:T,browser:$,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...R&&R.length>0?{actions:R}:{},...l.navigations&&l.navigations.length>0?{navigations:l.navigations}:{},...vt?{consoleLogs:vt}:{},...ke?{networkRequests:ke}:bt?{networkRequests:bt}:{},...yt?{apiCalls:yt}:{},...xt?{protocolAssertions:xt}:{}});try{let C=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(C==="realtime"||C==="both")){let S=this.cloudClient.getAccessToken();S&&Fr(this.cloudClient.getEndpoint(),S,this.cloudRunId,this.buildCloudTestPayload(L));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let C=Te(c,g,e.id??"",s.retry),S=s.retry===e.results.length-1,O={id:C,navigations:l.navigations,apiAssertions:l.apiAssertions,actions:R??[],artifacts:k,failureDiagnostic:u,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(C,O,{networkRequestsFile:l.networkRequestsFile,consoleLogsFile:l.consoleLogsFile,apiCallsFile:l.apiCallsFile});let W={id:C,title:g[g.length-1]??e.title,titlePath:g,filePath:c,status:a,duration:s.duration,project:g[1]??"",retryIndex:s.retry,tags:d,hasNetworkData:l.networkRequestsCount>0,hasConsoleData:l.consoleLogsCount>0,hasArtifacts:k!==null,hasActionSteps:(R?.length??0)>0,errorMessage:u?.message?.split(`
2594
- `)[0]??null,networkCount:l.networkRequestsCount,consoleCount:l.consoleLogsCount,actionCount:R?.length??0,isRetry:!S};if(this.testIndex.push(W),S)switch(this.summaryCounters.total++,a){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(`${c}::${g.join(" > ")}`,Qr(s.retry,G,l.apiAssertions,l.navigations,l.networkRequestsCount,l.consoleLogsCount,R)),k&&this.pendingArtifactEntries.push({testId:h,artifacts:k,outputDir:path.dirname(this.config.outputPath)}),L.actions=null,L.apiAssertions=null,L.navigations=[],L.artifacts=null,L.failure=null,L.networkRequestsFile=null,L.consoleLogsFile=null,L.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(L),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(e){try{let r=new Date().toISOString(),s=new Date(this.startedAt).getTime(),a=new Date(r).getTime()-s,o=this.activeReportMode==="streaming"?this.testIndex.some(d=>d.status!=="skipped"):this.collectedTests.some(d=>d.status!=="skipped");!this.fixtureDataReceived&&o&&process.stderr.write(`
2644
+ `),{navigations:n,apiAssertions:a,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:d,consoleLogsCount:l,apiCallsFile:u,apiCallsCount:g}}function ve(t=process.env){let e=ca(t.TESTRELIC_CLOUD_PLATFORM);if(e)return {cloudPlatform:e,cloudBuildId:t.TESTRELIC_CLOUD_BUILD_ID||void 0,cloudSessionId:t.TESTRELIC_CLOUD_SESSION_ID||void 0};if(t.BROWSERSTACK_USERNAME||t.BROWSERSTACK_ACCESS_KEY)return {cloudPlatform:"browserstack",cloudBuildId:t.BROWSERSTACK_BUILD_NAME||t.BROWSERSTACK_BUILD_ID||void 0,cloudSessionId:t.BROWSERSTACK_SESSION_ID||void 0};if(t.LT_USERNAME||t.LAMBDATEST_USERNAME||t.LT_ACCESS_KEY||t.LAMBDATEST_ACCESS_KEY)return {cloudPlatform:"lambdatest",cloudBuildId:t.LT_BUILD||t.LAMBDATEST_BUILD||void 0,cloudSessionId:t.LT_SESSION_ID||t.LAMBDATEST_SESSION_ID||void 0};let r=t.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 ca(t){if(!t)return;let e=t.toLowerCase().trim();if(e==="browserstack"||e==="bs")return "browserstack";if(e==="lambdatest"||e==="lt")return "lambdatest"}var ha=5,ye=[1e3,3e3,9e3],V=3,ma={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip"},pt=0,ft=[];async function va(){pt>=ha&&await new Promise(t=>ft.push(t)),pt++;}function ya(){pt--,ft.length>0&&ft.shift()();}async function be(t){return new Promise(e=>setTimeout(e,t))}function ba(t){let e=t.substring(t.lastIndexOf(".")).toLowerCase();return ma[e]??"application/octet-stream"}function xa(t){try{return fs$1.statSync(t).size}catch{return 0}}async function wa(t,e,r,s,n){let a=`${t}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:path.basename(r.filePath),contentType:n,type:r.type,sizeBytes:s});for(let i=0;i<V;i++)try{let d=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:o});if(d.ok)return await d.json();if(d.status>=500&&i<V-1){await be(ye[i]);continue}return null}catch{if(i<V-1){await be(ye[i]);continue}return null}return null}async function ka(t,e,r,s){for(let n=0;n<V;n++)try{let a=fs$1.createReadStream(e),o=stream.Readable.toWeb(a),i=await fetch(t,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(s)},body:o,duplex:"half"});if(i.ok)return !0;if(i.status>=500&&n<V-1){await be(ye[n]);continue}return !1}catch{if(n<V-1){await be(ye[n]);continue}return false}return false}async function Ta(t,e,r){let s=`${t}/artifacts/confirm`;try{return (await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({artifactId:r})})).ok}catch{return false}}async function Sa(t,e,r,s){let n=xa(r.filePath);if(n===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(n>s*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let a=ba(r.filePath);await va();try{let o=await wa(t,e,r,n,a);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await ka(o.uploadUrl,r.filePath,a,n))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let d=await Ta(t,e,o.artifactId);return {success:d,storageKey:o.storageKey,artifactId:o.artifactId,error:d?null:"confirm_failed"}}finally{ya();}}async function Yr(t,e,r,s){let n=new Map,a=r.map(async o=>{let i=await Sa(t,e,o,s);n.set(o.filePath,i);});return await Promise.allSettled(a),n}function gt(t){let r=t.getGitMetadata()?.remoteUrl;return r?te(r):t.getConfig()?.projectName??re(process.cwd())}async function Qr(t,e,r,s,n){if(!t.isCloudMode()||e!=="realtime"&&e!=="both"||!await t.ensureValidToken())return null;let o=t.getGitMetadata(),i=P(),d=ve(),l=pe();return (await Br(t.getEndpoint(),t.getAccessToken(),{runId:r,repoGitId:gt(t),branch:o?.branch??null,commit:o?.commitSha??null,commitMessage:o?.commitMessage??null,commitAuthor:o?.commitAuthor??null,startedAt:s,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 Ca=true,Ra=50;async function Aa(t,e,r,s){let n=new Map;if(!(e?.uploadArtifacts??Ca)||!await t.ensureValidToken())return n;let i=[],d=new Map;for(let p of s){if(p.artifacts.screenshot){let f=path.join(p.outputDir,p.artifacts.screenshot);i.push({filePath:f,runId:r,testId:p.testId,type:"screenshot"}),d.set(f,{testId:p.testId,field:"screenshot"});}if(p.artifacts.video){let f=path.join(p.outputDir,p.artifacts.video);i.push({filePath:f,runId:r,testId:p.testId,type:"video"}),d.set(f,{testId:p.testId,field:"video"});}}if(i.length===0)return n;let l=e?.artifactMaxSizeMb??Ra,u=await Yr(t.getEndpoint(),t.getAccessToken(),i,l),g=new Map;for(let[p,f]of u){if(!f.success||!f.storageKey)continue;let c=d.get(p);if(!c)continue;let h=g.get(c.testId)??{};c.field==="screenshot"&&(h.screenshotKey=f.storageKey),c.field==="video"&&(h.videoKey=f.storageKey),g.set(c.testId,h);}for(let p of s){let f=g.get(p.testId);n.set(p.testId,{...p.artifacts,...f?.screenshotKey?{screenshotKey:f.screenshotKey}:{},...f?.videoKey?{videoKey:f.videoKey}:{}});}let m=Array.from(u.values()).filter(p=>p.success).length;return m>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${m} artifact(s) to cloud storage.
2645
+ `),n}async function ht(t,e,r,s,n,a,o,i,d,l,u){try{if(t.isCloudMode()&&n&&(r==="realtime"||r==="both")){let m=await t.ensureValidToken(),p=t.getGitMetadata(),f=rt(u),c={finishedAt:o,duration:i,summary:d,...p?.commitMessage?{commitMessage:p.commitMessage}:{},testType:f.testType,...f.testType==="api"?{apiProtocol:f.apiProtocol,metadata:f.metadata}:{}};if(m){if(!await qr(t.getEndpoint(),t.getAccessToken(),n,c)){let v=e?.queueDirectory??".testrelic/queue";se(v,s,"finalize","finalize_failed_after_retries",`${t.getEndpoint()}/runs/${n}/finalize`,"POST",c,{"Content-Type":"application/json"});}}else {let h=e?.queueDirectory??".testrelic/queue";se(h,s,"finalize",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs/${n}/finalize`,"POST",c,{"Content-Type":"application/json"});}}let g=new Map;if(t.isCloudMode()&&l&&l.length>0&&(g=await Aa(t,e,s,l)),t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await t.ensureValidToken()){let p=t.getGitMetadata(),f=P(),c=gt(t),h=Ia(a,g),v=st(h,c,p,f,u,ve()),w=await Dr(t.getEndpoint(),t.getAccessToken(),v,async()=>await t.ensureValidToken()?t.getAccessToken():null);if(!w.success){let x=w,T=e?.queueDirectory??".testrelic/queue";se(T,s,"batch",x.reason,x.targetEndpoint,x.method,x.payload,{"Content-Type":"application/json"});}}else {let p=e?.queueDirectory??".testrelic/queue",f=t.getGitMetadata(),c=P(),h=gt(t),v=st(a,h,f,c,void 0,ve());se(p,s,"batch",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs`,"POST",v,{"Content-Type":"application/json"});}await t.dispose();}catch{try{await t.dispose();}catch{}}}function Ia(t,e){if(e.size===0)return t;let r=t.timeline.map(s=>{let n=s.testId;if(!n)return s;let a=e.get(n);return a?{...s,...a.screenshotKey?{screenshotKey:a.screenshotKey}:{},...a.videoKey?{videoKey:a.videoKey}:{}}:s});return {...t,timeline:r}}function B(t){try{return fs$1.readFileSync(t,"utf-8").split(`
2646
+ `).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function vt(t){switch(t){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function Fa(t,e,r){let s=`${t}::${e}::${r}`;return crypto.createHash("sha256").update(s).digest("hex").substring(0,16)}function Da(t){return t.length<=3?"":t[t.length-2]}function Ba(t){let e=t.findIndex(r=>r.status==="passed");return e>0?`passed on retry ${e}`:null}function Oa(t){return t===null?"error":t>=200&&t<300?"2xx":t>=300&&t<400?"3xx":t>=400&&t<500?"4xx":t>=500&&t<600?"5xx":"error"}function rs(t,e){for(let r of t)e[r.category]=(e[r.category]??0)+1,r.children.length>0&&rs(r.children,e);}function qa(t){if(t.length===0)return null;let e=[...t].sort((s,n)=>s-n),r=e.reduce((s,n)=>s+n,0);return {avg:Math.round(r/e.length),min:e[0],max:e[e.length-1],p50:U(e,50),p95:U(e,95),p99:U(e,99)}}var ss=2e5,xe=1e5;function ts(t,e,r,s,n,a,o){let i={retryIndex:t,apiCalls:e?.length??0,apiUrls:[],methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,assertions:r.length,navigations:s.length,navUrls:[],networkRequests:n,consoleLogs:a,actionSteps:o?.length??0,actionCategories:{}};if(e){let l=new Set;for(let u of e){let g=typeof u.method=="string"?u.method:"OTHER";i.methodCounts[g]=(i.methodCounts[g]??0)+1;let m=typeof u.url=="string"?u.url:null;m&&l.size<xe&&l.add(Ke(m));let p=typeof u.responseStatusCode=="number"?u.responseStatusCode:typeof u.statusCode=="number"?u.statusCode:null,f=p!==null&&Number.isFinite(p)?p:null;i.statusRanges[Oa(f)]++;let c=typeof u.responseTimeMs=="number"?u.responseTimeMs:typeof u.durationMs=="number"?u.durationMs:null;c!==null&&Number.isFinite(c)&&i.responseTimes.length<ss&&i.responseTimes.push(c);}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 s)l.url&&d.size<xe&&d.add(l.url);return i.navUrls=Array.from(d),o&&rs(o,i.actionCategories),i}function Ha(){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 Ua(t){return process.env.BROWSERSTACK_USERNAME?"BrowserStack":t?{"github-actions":"GitHub Actions","gitlab-ci":"GitLab CI",jenkins:"Jenkins",circleci:"CircleCI","bitbucket-pipelines":"Bitbucket Pipelines"}[t.provider]??"CI":"Local"}function $a(){let t=os.platform();return t==="win32"?"Windows":t==="darwin"?"macOS":"Linux"}function za(t){let e=t.parent?.project?.()?.use;if(!e)return;let{browserName:r,channel:s}=e;if(s){let a=s.toLowerCase();return a==="chrome"||a==="chrome-stable"?"Chrome":a.startsWith("chrome-beta")?"Chrome Beta":a.startsWith("chrome-dev")?"Chrome Dev":a.startsWith("chrome-canary")?"Chrome Canary":a==="msedge"||a==="msedge-stable"?"Microsoft Edge":a.startsWith("msedge-beta")?"Edge Beta":a.startsWith("msedge-dev")?"Edge Dev":a.startsWith("msedge-canary")?"Edge Canary":s}if(r){let a=r.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":r}let n=e.defaultBrowserType;if(n){let a=n.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":n}}function ja(t,e,r){let s=r.parent?.project?.(),n="unknown";s!==void 0&&(s.use.isMobile===true?n="mobile":n="e2e");let a=["e2e","api","unit","mobile"];for(let d of a)if(t.some(l=>l===`@${d}`||l===d))return d;let o=e.replace(/\\/g,"/"),i=["e2e","api","unit"];for(let d of i)if(o.includes(`/${d}/`))return d;return n}var Va="__testrelic_api_config";function Ga(t){return JSON.stringify(t,(e,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var we=class{constructor(e){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.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};this.streamingTestAgg=new Map;this.config=Dt(e),this.apiConfig=Ft(e);}upsertAggContribution(e,r){let s=this.streamingTestAgg.get(e);(!s||r.retryIndex>s.retryIndex)&&this.streamingTestAgg.set(e,r);}async onBegin(e,r){try{if(this.rootDir=e.rootDir,this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??crypto.randomUUID(),this.config.reportMode==="auto"){let o=r.allTests().length;this.activeReportMode=o>=this.config.streamingThreshold?"streaming":"embedded";}else this.activeReportMode=this.config.reportMode;let s=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${s} tests)
2647
+ `),this.activeReportMode==="streaming"){let o=path.dirname(this.config.outputPath);this.streamingWriter=new Y(o);let i=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let d={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()};this.streamingWriter.writeSummary(d);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let d=this.cloudClient.getAccessToken();d&&lt(this.cloudClient.getEndpoint(),d,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",i),process.on("SIGINT",i);}if(this.config.includeArtifacts){let o=path.dirname(this.config.outputPath);this.runTimestamp=pr(path.join(o,"artifacts"));try{yr(path.join(o,"artifacts"));}catch{}}let n=P();this.detectedOs=$a(),this.detectedSource=Ua(n);let a=await H(async()=>(this.cloudClient=new me(this.config.cloud),await this.cloudClient.initialize(),Qr(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource)),xr,"Cloud initialization");if(this.cloudRunId=a??null,a===void 0&&this.cloudClient?.switchToLocalMode("init_error"),this.activeReportMode!=="streaming"){let o=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let i=this.cloudClient.getAccessToken();i&&lt(this.cloudClient.getEndpoint(),i,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",o),process.on("SIGINT",o);}}catch{}}onTestBegin(e,r){try{e.annotations.push({type:Va,description:Ga(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let s=r,n=e.outcome(),a;n==="flaky"?a="flaky":n==="skipped"?a="skipped":a=vt(s.status);let o=s.startTime.toISOString(),i=new Date(s.startTime.getTime()+s.duration).toISOString(),d=e.tags?[...e.tags]:e.annotations.filter(C=>C.type==="tag").map(C=>C.description??""),l=Jr(s.attachments,e.annotations,e.title,a==="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 u=null;if(a==="failed"||a==="flaky"){let S=(a==="flaky"?e.results.find(O=>O.status!=="passed")?.errors??[]:s.errors)[0];if(S){let O=Ot(this.config.redactPatterns),W=S.location?.line??null,K=null;this.config.includeCodeSnippets&&W!==null&&S.location?.file&&(K=Bt(S.location.file,W,this.config.codeContextLines),K&&(K=O(K))),u={message:O(S.message??"Unknown error"),line:W,code:K,stack:this.config.includeStackTrace&&S.stack?O(S.stack):null};}}let g=e.titlePath().filter(Boolean),m=path.relative(this.rootDir||".",e.location.file),p=Da(g),f=g.join(" > "),c=m,h=Fa(c,p,f),v=ja(d,c,e),w=v!=="mobile"&&l.apiCallsCount>0?"api":v,x=n==="flaky",T=Ba(e.results),M=vt(e.expectedStatus),y=vt(s.status),k=null;if(this.config.includeArtifacts&&a!=="skipped"&&s.attachments){let C=path.dirname(this.config.outputPath),S=g[g.length-1]??e.title;k=fr(s.attachments,S,s.retry,C,this.runTimestamp||void 0,h);}let R=this.config.includeActionSteps&&s.steps?Rr(s.steps,s.startTime):null,$=za(e),L={titlePath:g,title:f,status:a,duration:s.duration,startedAt:o,completedAt:i,retryCount:e.results.length-1,retry:s.retry,tags:d,failure:u,specFile:m,navigations:l.navigations,testId:h,filePath:c,suiteName:p,testType:w,isFlaky:x,retryStatus:T,expectedStatus:M,actualStatus:y,artifacts:k,apiAssertions:l.apiAssertions,actions:R,networkRequestsFile:l.networkRequestsFile,networkRequestsCount:l.networkRequestsCount,consoleLogsFile:l.consoleLogsFile,consoleLogsCount:l.consoleLogsCount,apiCallsFile:l.apiCallsFile,apiCallsCount:l.apiCallsCount,browser:$,os:this.detectedOs||void 0,source:this.detectedSource||void 0},yt=l.consoleLogsFile&&l.consoleLogsCount>0?B(l.consoleLogsFile):void 0,ke=l.networkRequestsFile&&l.networkRequestsCount>0?B(l.networkRequestsFile):void 0,G=l.apiCallsFile&&l.apiCallsCount>0?B(l.apiCallsFile):void 0,bt=G?nt(G):void 0,xt=!ke&&G?at(G):void 0,wt=l.apiAssertions&&l.apiAssertions.length>0?it(l.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:h,title:f,status:a,duration:s.duration,suiteName:p,filePath:c,testType:w,isFlaky:x,startedAt:o,completedAt:i,tags:d,failure:u,retry:s.retry,retryCount:e.results.length-1,retryStatus:T,browser:$,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...R&&R.length>0?{actions:R}:{},...l.navigations&&l.navigations.length>0?{navigations:l.navigations}:{},...yt?{consoleLogs:yt}:{},...ke?{networkRequests:ke}:xt?{networkRequests:xt}:{},...bt?{apiCalls:bt}:{},...wt?{protocolAssertions:wt}:{}});try{let C=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(C==="realtime"||C==="both")){let S=this.cloudClient.getAccessToken();S&&Or(this.cloudClient.getEndpoint(),S,this.cloudRunId,this.buildCloudTestPayload(L));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let C=Te(c,g,e.id??"",s.retry),S=s.retry===e.results.length-1,O={id:C,navigations:l.navigations,apiAssertions:l.apiAssertions,actions:R??[],artifacts:k,failureDiagnostic:u,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(C,O,{networkRequestsFile:l.networkRequestsFile,consoleLogsFile:l.consoleLogsFile,apiCallsFile:l.apiCallsFile});let W={id:C,title:g[g.length-1]??e.title,titlePath:g,filePath:c,status:a,duration:s.duration,project:g[1]??"",retryIndex:s.retry,tags:d,hasNetworkData:l.networkRequestsCount>0,hasConsoleData:l.consoleLogsCount>0,hasArtifacts:k!==null,hasActionSteps:(R?.length??0)>0,errorMessage:u?.message?.split(`
2648
+ `)[0]??null,networkCount:l.networkRequestsCount,consoleCount:l.consoleLogsCount,actionCount:R?.length??0,isRetry:!S,retryGroupKey:Se(c,g,e.id??"")};if(this.testIndex.push(W),S)switch(this.summaryCounters.total++,a){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(`${c}::${g.join(" > ")}`,ts(s.retry,G,l.apiAssertions,l.navigations,l.networkRequestsCount,l.consoleLogsCount,R)),k&&this.pendingArtifactEntries.push({testId:h,artifacts:k,outputDir:path.dirname(this.config.outputPath)}),L.actions=null,L.apiAssertions=null,L.navigations=[],L.artifacts=null,L.failure=null,L.networkRequestsFile=null,L.consoleLogsFile=null,L.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(L),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(e){try{let r=new Date().toISOString(),s=new Date(this.startedAt).getTime(),a=new Date(r).getTime()-s,o=this.activeReportMode==="streaming"?this.testIndex.some(d=>d.status!=="skipped"):this.collectedTests.some(d=>d.status!=="skipped");!this.fixtureDataReceived&&o&&process.stderr.write(`
2595
2649
  \u26A0 TestRelic: No fixture data received from any test.
2596
2650
  To enable network logs, video sync, and Test Navigation tracking, import the TestRelic fixture:
2597
2651
  import { test, expect } from '@testrelic/playwright-analytics/fixture';
@@ -2600,14 +2654,14 @@ ${n}
2600
2654
 
2601
2655
  `),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).
2602
2656
  `):process.stderr.write(`[testrelic] Test Navigation capture is disabled (captureNavigation: false). Remove the option or set it to true to capture the navigation graph.
2603
- `),await H(()=>lr(),Ge,"Artifact flush");let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let d=path.dirname(this.config.outputPath);i=pr(d,this.runTimestamp);let l=path.join(d,"artifact-manifest.json"),u=JSON.stringify(i),g=l+".tmp";fs$1.writeFileSync(g,u,"utf-8"),fs$1.renameSync(g,l);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await H(()=>this.finalizeStreamingReport(r,a,e,i),Ve,"Report finalization");else {let d=this.buildTimeline(),l=new Map;for(let p of this.collectedTests){let f=l.get(p.testId);(!f||p.retry>f.retry)&&l.set(p.testId,p);}let u=Array.from(l.values()),g=kr(u,d.length),m={schemaVersion:Ce,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:a,summary:g,ci:P(),metadata:this.config.metadata,timeline:d,shardRunIds:null};if(this.writeReport(m),await H(()=>Ue(m,this.config,i),Ge,"HTML report write"),Ke(g,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient){let p=this.collectArtifactEntries(),f=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await H(()=>gt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,m,r,a,g,p,f),Ve,"Cloud upload");}}}catch{}finally{await this.disposeCloudClient();}}async disposeCloudClient(){let e=this.cloudClient;e&&(this.cloudClient=null,await H(()=>e.dispose(),yr,"Cloud client shutdown"));}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let e=path.dirname(this.config.outputPath),r=[];for(let s of this.collectedTests)s.artifacts&&r.push({testId:s.testId,artifacts:s.artifacts,outputDir:e});return r}async finalizeStreamingReport(e,r,s,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};let a=new Map,o=new Map;for(let c of this.testIndex){let h=`${c.filePath}::${c.titlePath.join(" > ")}`,v=a.get(h);(v===void 0||c.retryIndex>v)&&a.set(h,c.retryIndex);}let i=0;for(let c of this.testIndex){let h=`${c.filePath}::${c.titlePath.join(" > ")}`,v=a.get(h);if(c.isRetry=c.retryIndex<v,c.isRetry)continue;switch(i++,this.summaryCounters.total++,c.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}let w=o.get(c.filePath);switch(w||(w={filePath:c.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},o.set(c.filePath,w)),w.total++,c.status){case "passed":w.passed++;break;case "failed":w.failed++;break;case "flaky":w.flaky++;break;case "skipped":w.skipped++;break;case "timedout":w.timedOut++;break}}let d=Array.from(o.values()),l=Ba();for(let c of this.streamingTestAgg.values()){l.volApiCalls+=c.apiCalls,l.volAssertions+=c.assertions,l.volNavigations+=c.navigations,l.volNetworkRequests+=c.networkRequests,l.volConsoleLogs+=c.consoleLogs,l.volActionSteps+=c.actionSteps;for(let h in c.methodCounts)l.methodCounts[h]=(l.methodCounts[h]??0)+c.methodCounts[h];l.statusRanges["2xx"]+=c.statusRanges["2xx"],l.statusRanges["3xx"]+=c.statusRanges["3xx"],l.statusRanges["4xx"]+=c.statusRanges["4xx"],l.statusRanges["5xx"]+=c.statusRanges["5xx"],l.statusRanges.error+=c.statusRanges.error,l.passedAssertions+=c.passedAssertions,l.failedAssertions+=c.failedAssertions;for(let h in c.actionCategories)l.actionCategoryCounts[h]=(l.actionCategoryCounts[h]??0)+c.actionCategories[h];for(let h of c.apiUrls){if(l.apiUrlSet.size>=xe)break;l.apiUrlSet.add(h);}for(let h of c.navUrls){if(l.navUrlSet.size>=xe)break;l.navUrlSet.add(h);}for(let h of c.responseTimes){if(l.responseTimes.length>=es)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 u={reporterTotal:this.summaryCounters.total,indexTotal:i,playwrightStatus:s.status,isValid:this.summaryCounters.total===i};u.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${u.reporterTotal}, index: ${u.indexTotal}
2604
- `);let g={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:Da(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}},m={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:e,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:d,enrichedSummary:g,validation:u,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(m);let p={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(p),await Ue(this.buildStreamingReport(m,g,e,r),this.config,n),Ke(g,this.config.outputPath,this.config.htmlReportPath,this.config.quiet);let f=this.streamingWriter.getReportDir();if(process.stderr.write(`[testrelic] Streaming report written to ${f}
2657
+ `),await H(()=>ur(),We,"Artifact flush");let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let d=path.dirname(this.config.outputPath);i=hr(d,this.runTimestamp);let l=path.join(d,"artifact-manifest.json"),u=JSON.stringify(i),g=l+".tmp";fs$1.writeFileSync(g,u,"utf-8"),fs$1.renameSync(g,l);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await H(()=>this.finalizeStreamingReport(r,a,e,i),Ge,"Report finalization");else {let d=this.buildTimeline(),l=new Map;for(let p of this.collectedTests){let f=l.get(p.testId);(!f||p.retry>f.retry)&&l.set(p.testId,p);}let u=Array.from(l.values()),g=Cr(u,d.length),m={schemaVersion:Re,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:a,summary:g,ci:P(),metadata:this.config.metadata,timeline:d,shardRunIds:null};if(this.writeReport(m),await H(()=>$e(m,this.config,i),We,"HTML report write"),Je(g,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient){let p=this.collectArtifactEntries(),f=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await H(()=>ht(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,m,r,a,g,p,f),Ge,"Cloud upload");}}}catch{}finally{await this.disposeCloudClient();}}async disposeCloudClient(){let e=this.cloudClient;e&&(this.cloudClient=null,await H(()=>e.dispose(),wr,"Cloud client shutdown"));}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let e=path.dirname(this.config.outputPath),r=[];for(let s of this.collectedTests)s.artifacts&&r.push({testId:s.testId,artifacts:s.artifacts,outputDir:e});return r}async finalizeStreamingReport(e,r,s,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};let a=new Map,o=new Map;for(let c of this.testIndex){let h=`${c.filePath}::${c.titlePath.join(" > ")}`,v=a.get(h);(v===void 0||c.retryIndex>v)&&a.set(h,c.retryIndex);}let i=0;for(let c of this.testIndex){let h=`${c.filePath}::${c.titlePath.join(" > ")}`,v=a.get(h);if(c.isRetry=c.retryIndex<v,c.isRetry)continue;switch(i++,this.summaryCounters.total++,c.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}let w=o.get(c.filePath);switch(w||(w={filePath:c.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},o.set(c.filePath,w)),w.total++,c.status){case "passed":w.passed++;break;case "failed":w.failed++;break;case "flaky":w.flaky++;break;case "skipped":w.skipped++;break;case "timedout":w.timedOut++;break}}let d=Array.from(o.values()),l=Ha();for(let c of this.streamingTestAgg.values()){l.volApiCalls+=c.apiCalls,l.volAssertions+=c.assertions,l.volNavigations+=c.navigations,l.volNetworkRequests+=c.networkRequests,l.volConsoleLogs+=c.consoleLogs,l.volActionSteps+=c.actionSteps;for(let h in c.methodCounts)l.methodCounts[h]=(l.methodCounts[h]??0)+c.methodCounts[h];l.statusRanges["2xx"]+=c.statusRanges["2xx"],l.statusRanges["3xx"]+=c.statusRanges["3xx"],l.statusRanges["4xx"]+=c.statusRanges["4xx"],l.statusRanges["5xx"]+=c.statusRanges["5xx"],l.statusRanges.error+=c.statusRanges.error,l.passedAssertions+=c.passedAssertions,l.failedAssertions+=c.failedAssertions;for(let h in c.actionCategories)l.actionCategoryCounts[h]=(l.actionCategoryCounts[h]??0)+c.actionCategories[h];for(let h of c.apiUrls){if(l.apiUrlSet.size>=xe)break;l.apiUrlSet.add(h);}for(let h of c.navUrls){if(l.navUrlSet.size>=xe)break;l.navUrlSet.add(h);}for(let h of c.responseTimes){if(l.responseTimes.length>=ss)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 u={reporterTotal:this.summaryCounters.total,indexTotal:i,playwrightStatus:s.status,isValid:this.summaryCounters.total===i};u.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${u.reporterTotal}, index: ${u.indexTotal}
2658
+ `);let g={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:qa(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}},m={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:e,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:d,enrichedSummary:g,validation:u,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(m);let p={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(p),await $e(this.buildStreamingReport(m,g,e,r),this.config,n),Je(g,this.config.outputPath,this.config.htmlReportPath,this.config.quiet);let f=this.streamingWriter.getReportDir();if(process.stderr.write(`[testrelic] Streaming report written to ${f}
2605
2659
  [testrelic] ${this.testIndex.length} test detail files on disk
2606
2660
  [testrelic] View report: npx testrelic serve ${f}
2607
2661
  `),this.streamingWriter.getWriteErrors().length>0&&process.stderr.write(`[testrelic] WARNING: ${this.streamingWriter.getWriteErrors().length} write error(s) during streaming
2608
- `),this.streamingWriter.dispose(),this.cloudClient){let c=this.buildStreamingReport(m,g,e,r),h=this.collectArtifactEntries(),v=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await gt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,c,e,r,g,h,v);}this.testIndex.length=0,this.collectedTests.length=0,this.pendingArtifactEntries.length=0,this.cloudTestsBuffer.length=0,this.streamingWriter=null,this.cloudClient=null;}buildStreamingReport(e,r,s,n){return {schemaVersion:Ce,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:s,totalDuration:n,summary:r,ci:P(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let e=process.memoryUsage(),r=e.heapUsed/1024/1024;if(r<200)return;let s=e.heapUsed/e.heapTotal;s>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
2609
- `),this.switchToStreamingMode()):s>.8&&process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
2610
- `);}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let e=path.dirname(this.config.outputPath);this.streamingWriter=new Y(e);for(let r of this.collectedTests){let s=Te(r.filePath,r.titlePath,r.testId,r.retry),n=r.apiCallsFile&&r.apiCallsCount>0?B(r.apiCallsFile):void 0,a={id:s,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(s,a,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let o={id:s,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(`
2611
- `)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,isRetry:!1};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(" > ")}`,Qr(r.retry,n,r.apiAssertions??[],r.navigations??[],r.networkRequestsCount,r.consoleLogsCount,r.actions??null));}this.collectedTests.length=0;}catch{}}buildTimeline(){let e=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 wr(e,{navigationTypes:this.config.navigationTypes})}readJsonlFile(e){if(!e)return null;let r=B(e);return r.length>0?r:null}toTestResult(e,r){let s=null,n=null,a=null;return r?.loadFiles&&(s=this.readJsonlFile(e.networkRequestsFile),n=this.readJsonlFile(e.consoleLogsFile),a=this.readJsonlFile(e.apiCallsFile)),{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:s,apiCalls:a,apiAssertions:e.apiAssertions,actions:e.actions??null,consoleLogs:n}}buildCloudTestPayload(e){let r={title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retry:e.retry,retryCount:e.retryCount,retryStatus:e.retryStatus,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,actions:e.actions??[],navigations:e.navigations??[],steps:e.actions??[],browser:e.browser,os:e.os,source:e.source};if(e.apiAssertions&&e.apiAssertions.length>0&&(r.protocolAssertions=at(e.apiAssertions)),e.consoleLogsFile&&(r.consoleLogs=B(e.consoleLogsFile)),e.networkRequestsFile&&(r.networkRequests=B(e.networkRequestsFile)),e.apiCallsFile){let s=B(e.apiCallsFile);r.apiCalls=st(s),(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=nt(s));}return r}writeReport(e){try{let r=JSON.stringify(e),s=this.config.outputPath,n=path.dirname(s);fs$1.mkdirSync(n,{recursive:!0});let a=s+".tmp";fs$1.writeFileSync(a,r,"utf-8"),fs$1.renameSync(a,s);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
2662
+ `),this.streamingWriter.dispose(),this.cloudClient){let c=this.buildStreamingReport(m,g,e,r),h=this.collectArtifactEntries(),v=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await ht(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,c,e,r,g,h,v);}this.testIndex.length=0,this.collectedTests.length=0,this.pendingArtifactEntries.length=0,this.cloudTestsBuffer.length=0,this.streamingWriter=null,this.cloudClient=null;}buildStreamingReport(e,r,s,n){return {schemaVersion:Re,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:s,totalDuration:n,summary:r,ci:P(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let e=process.memoryUsage(),r=e.heapUsed/1024/1024;if(r<200)return;let s=e.heapUsed/e.heapTotal;s>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
2663
+ `),this.switchToStreamingMode()):s>.8&&r>=500&&!this.memoryPressureWarned&&(this.memoryPressureWarned=!0,process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
2664
+ `));}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let e=path.dirname(this.config.outputPath);this.streamingWriter=new Y(e);for(let r of this.collectedTests){let s=Te(r.filePath,r.titlePath,r.testId,r.retry),n=r.apiCallsFile&&r.apiCallsCount>0?B(r.apiCallsFile):void 0,a={id:s,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(s,a,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let o={id:s,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(`
2665
+ `)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,isRetry:!1,retryGroupKey:Se(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(" > ")}`,ts(r.retry,n,r.apiAssertions??[],r.navigations??[],r.networkRequestsCount,r.consoleLogsCount,r.actions??null));}this.collectedTests.length=0;}catch{}}buildTimeline(){let e=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 Sr(e,{navigationTypes:this.config.navigationTypes})}readJsonlFile(e){if(!e)return null;let r=B(e);return r.length>0?r:null}toTestResult(e,r){let s=null,n=null,a=null;return r?.loadFiles&&(s=this.readJsonlFile(e.networkRequestsFile),n=this.readJsonlFile(e.consoleLogsFile),a=this.readJsonlFile(e.apiCallsFile)),{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:s,apiCalls:a,apiAssertions:e.apiAssertions,actions:e.actions??null,consoleLogs:n}}buildCloudTestPayload(e){let r={title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retry:e.retry,retryCount:e.retryCount,retryStatus:e.retryStatus,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,actions:e.actions??[],navigations:e.navigations??[],steps:e.actions??[],browser:e.browser,os:e.os,source:e.source};if(e.apiAssertions&&e.apiAssertions.length>0&&(r.protocolAssertions=it(e.apiAssertions)),e.consoleLogsFile&&(r.consoleLogs=B(e.consoleLogsFile)),e.networkRequestsFile&&(r.networkRequests=B(e.networkRequestsFile)),e.apiCallsFile){let s=B(e.apiCallsFile);r.apiCalls=nt(s),(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=at(s));}return r}writeReport(e){try{let r=JSON.stringify(e),s=this.config.outputPath,n=path.dirname(s);fs$1.mkdirSync(n,{recursive:!0});let a=s+".tmp";fs$1.writeFileSync(a,r,"utf-8"),fs$1.renameSync(a,s);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
2612
2666
  `);}}};module.exports=we;//# sourceMappingURL=reporter-entry.cjs.map
2613
2667
  //# sourceMappingURL=reporter-entry.cjs.map