@testrelic/playwright-analytics 2.12.0-next.84 → 2.12.1-next.104

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,10 +1,10 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var crypto=require('crypto'),fs=require('fs'),path=require('path'),os$1=require('os'),core=require('@testrelic/core'),child_process=require('child_process'),http=require('http'),readline=require('readline'),promises=require('fs/promises'),zlib=require('zlib'),util=require('util'),stream=require('stream'),test=require('@playwright/test'),perf_hooks=require('perf_hooks'),url=require('url');var Dn=(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 qn=".testrelic-report";function Pe(t,e,r,n){let s=`${t}|${e.join("|")}|${r}|${n}`;return crypto.createHash("sha256").update(s).digest("hex").substring(0,12)}var te=class{constructor(e){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=path.join(e,qn),this.testsDir=path.join(this.reportDir,"tests"),fs.mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(e,r,n){try{let s=path.join(this.testsDir,e);fs.mkdirSync(s,{recursive:!0});let a=path.join(s,"meta.json"),o=a+".tmp",i=JSON.stringify(r);return fs.writeFileSync(o,i,"utf-8"),fs.renameSync(o,a),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),n?.networkRequestsFile&&this.moveFile(n.networkRequestsFile,path.join(s,"network.jsonl")),n?.consoleLogsFile&&this.moveFile(n.consoleLogsFile,path.join(s,"console.jsonl")),n?.apiCallsFile&&this.moveFile(n.apiCallsFile,path.join(s,"api-calls.jsonl")),!0}catch(s){let a=s instanceof Error?s.message:String(s);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.renameSync(e,r);}catch{try{let{copyFileSync:n}=Dn("fs");n(e,r);try{fs.unlinkSync(e);}catch{}}catch(n){process.stderr.write(`[testrelic] Failed to move file ${e} \u2192 ${r}: ${n instanceof Error?n.message:String(n)}
3
- `);}}}writeIndex(e){let r=path.join(this.reportDir,"index.json"),n=r+".tmp",s=JSON.stringify(e);fs.writeFileSync(n,s,"utf-8"),fs.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeCompactIndex(e){let r=path.join(this.reportDir,"index-compact.json"),n=r+".tmp",s=e.map(({titlePath:o,project:i,...d})=>d),a=JSON.stringify(s);fs.writeFileSync(n,a,"utf-8"),fs.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}writeSummary(e){let r=path.join(this.reportDir,"summary.json"),n=r+".tmp",s=JSON.stringify(e);fs.writeFileSync(n,s,"utf-8"),fs.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeManifest(e){let r=path.join(this.reportDir,"manifest.json"),n=r+".tmp",s=JSON.stringify(e);fs.writeFileSync(n,s,"utf-8"),fs.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var zt=".testrelic",Wn="testrelic-config.json",Vn=".testrelic",Gn=5,Jn=new Set(["__proto__","constructor","prototype"]),Ut=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${zt}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),Kn={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function jt(t){let e=path.resolve(t);for(let r=0;r<=Gn;r++){let n=path.join(e,zt,Wn);if(fs.existsSync(n))try{if(fs.statSync(n).isFile())return n}catch{}let s=path.join(e,Vn);if(fs.existsSync(s))try{if(fs.statSync(s).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
- `),s}catch{}let a=path.dirname(e);if(a===e)break;e=a;}return null}function Wt(t){try{let e=fs.readFileSync(t,"utf-8"),r=JSON.parse(e);return typeof r!="object"||r===null||Array.isArray(r)||!Vt(r)?null:r}catch{return null}}function Vt(t){for(let e of Object.keys(t)){if(Jn.has(e))return false;let r=t[e];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!Vt(r))return false}return true}function Gt(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 Ne(t){let e=Object.create(null);for(let r of Object.keys(t)){let n=t[r];typeof n=="string"&&n.startsWith("$")?e[r]=Gt(n):typeof n=="object"&&n!==null&&!Array.isArray(n)?e[r]=Ne(n):e[r]=n;}return e}function $t(t){let e=/^(\d+)\s*([smhd])$/.exec(t.trim());if(!e)return null;let r=parseInt(e[1],10),n=e[2],s=Kn[n];return !s||r<=0?null:r*s}function Jt(t,e){let r=Object.create(null);if(Object.assign(r,Ut),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 c=t.queue;if(c&&typeof c=="object"){if(typeof c.maxAge=="string"){let f=$t(c.maxAge);f!==null&&(r.queueMaxAge=f);}typeof c.directory=="string"&&(r.queueDirectory=c.directory);}}if(e){if(typeof e.apiKey=="string"&&e.apiKey.length>0){let d=e.apiKey.startsWith("$")?Gt(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=$t(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 n=process.env.TESTRELIC_API_KEY;n&&n.length>0&&(r.apiKey=n);let s=process.env.TESTRELIC_CLOUD_ENDPOINT;s&&core.isValidEndpointUrl(s)&&(r.endpoint=s);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:Ut}var Xn=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],es=["authorization","cookie","set-cookie","x-api-key"],ts=["password","secret","token","apiKey","api_key"];function Kt(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??[...es],e.redactBodyFields=t?.redactBodyFields??[...ts],e.apiIncludeUrls=t?.apiIncludeUrls??[],e.apiExcludeUrls=t?.apiExcludeUrls??[],Object.freeze(e)}function Yt(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=[...Xn,...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 n=jt(process.cwd()),s=n?Wt(n):null,a=s?Ne(s):null,o=Jt(a,t?.cloud);return e.cloud=o.apiKey?o:null,e.reportMode=t?.reportMode??"streaming",e.streamingThreshold=t?.streamingThreshold??0,Object.freeze(e)}var de="1.3.0";function Zt(t,e,r){try{let s=fs.readFileSync(t,"utf-8").split(`
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var crypto=require('crypto'),fs=require('fs'),path=require('path'),os$1=require('os'),core=require('@testrelic/core'),child_process=require('child_process'),http=require('http'),readline=require('readline'),promises=require('fs/promises'),zlib=require('zlib'),util=require('util'),stream=require('stream'),test=require('@playwright/test'),perf_hooks=require('perf_hooks'),url=require('url');var On=(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 Hn=".testrelic-report";function Ee(t,e,r,n){let s=`${t}|${e.join("|")}|${r}|${n}`;return crypto.createHash("sha256").update(s).digest("hex").substring(0,12)}function Ne(t,e,r){let n=`${t}|${e.join("|")}|${r}`;return crypto.createHash("sha256").update(n).digest("hex").substring(0,12)}var te=class{constructor(e){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=path.join(e,Hn),this.testsDir=path.join(this.reportDir,"tests"),fs.mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(e,r,n){try{let s=path.join(this.testsDir,e);fs.mkdirSync(s,{recursive:!0});let a=path.join(s,"meta.json"),o=a+".tmp",i=JSON.stringify(r);return fs.writeFileSync(o,i,"utf-8"),fs.renameSync(o,a),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),n?.networkRequestsFile&&this.moveFile(n.networkRequestsFile,path.join(s,"network.jsonl")),n?.consoleLogsFile&&this.moveFile(n.consoleLogsFile,path.join(s,"console.jsonl")),n?.apiCallsFile&&this.moveFile(n.apiCallsFile,path.join(s,"api-calls.jsonl")),!0}catch(s){let a=s instanceof Error?s.message:String(s);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.renameSync(e,r);}catch{try{let{copyFileSync:n}=On("fs");n(e,r);try{fs.unlinkSync(e);}catch{}}catch(n){process.stderr.write(`[testrelic] Failed to move file ${e} \u2192 ${r}: ${n instanceof Error?n.message:String(n)}
3
+ `);}}}writeIndex(e){let r=path.join(this.reportDir,"index.json"),n=r+".tmp",s=JSON.stringify(e);fs.writeFileSync(n,s,"utf-8"),fs.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeCompactIndex(e){let r=path.join(this.reportDir,"index-compact.json"),n=r+".tmp",s=e.map(({titlePath:o,project:i,...d})=>d),a=JSON.stringify(s);fs.writeFileSync(n,a,"utf-8"),fs.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}writeSummary(e){let r=path.join(this.reportDir,"summary.json"),n=r+".tmp",s=JSON.stringify(e);fs.writeFileSync(n,s,"utf-8"),fs.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeManifest(e){let r=path.join(this.reportDir,"manifest.json"),n=r+".tmp",s=JSON.stringify(e);fs.writeFileSync(n,s,"utf-8"),fs.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var Wt=".testrelic",Gn="testrelic-config.json",Vn=".testrelic",Kn=5,Jn=new Set(["__proto__","constructor","prototype"]),zt=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${Wt}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),Yn={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function Gt(t){let e=path.resolve(t);for(let r=0;r<=Kn;r++){let n=path.join(e,Wt,Gn);if(fs.existsSync(n))try{if(fs.statSync(n).isFile())return n}catch{}let s=path.join(e,Vn);if(fs.existsSync(s))try{if(fs.statSync(s).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
+ `),s}catch{}let a=path.dirname(e);if(a===e)break;e=a;}return null}function Vt(t){try{let e=fs.readFileSync(t,"utf-8"),r=JSON.parse(e);return typeof r!="object"||r===null||Array.isArray(r)||!Kt(r)?null:r}catch{return null}}function Kt(t){for(let e of Object.keys(t)){if(Jn.has(e))return false;let r=t[e];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!Kt(r))return false}return true}function Jt(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 Fe(t){let e=Object.create(null);for(let r of Object.keys(t)){let n=t[r];typeof n=="string"&&n.startsWith("$")?e[r]=Jt(n):typeof n=="object"&&n!==null&&!Array.isArray(n)?e[r]=Fe(n):e[r]=n;}return e}function jt(t){let e=/^(\d+)\s*([smhd])$/.exec(t.trim());if(!e)return null;let r=parseInt(e[1],10),n=e[2],s=Yn[n];return !s||r<=0?null:r*s}function Yt(t,e){let r=Object.create(null);if(Object.assign(r,zt),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 c=t.queue;if(c&&typeof c=="object"){if(typeof c.maxAge=="string"){let f=jt(c.maxAge);f!==null&&(r.queueMaxAge=f);}typeof c.directory=="string"&&(r.queueDirectory=c.directory);}}if(e){if(typeof e.apiKey=="string"&&e.apiKey.length>0){let d=e.apiKey.startsWith("$")?Jt(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=jt(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 n=process.env.TESTRELIC_API_KEY;n&&n.length>0&&(r.apiKey=n);let s=process.env.TESTRELIC_CLOUD_ENDPOINT;s&&core.isValidEndpointUrl(s)&&(r.endpoint=s);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:zt}var es=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],ts=["authorization","cookie","set-cookie","x-api-key"],rs=["password","secret","token","apiKey","api_key"];function Zt(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??[...ts],e.redactBodyFields=t?.redactBodyFields??[...rs],e.apiIncludeUrls=t?.apiIncludeUrls??[],e.apiExcludeUrls=t?.apiExcludeUrls??[],Object.freeze(e)}function Qt(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=[...es,...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 n=Gt(process.cwd()),s=n?Vt(n):null,a=s?Fe(s):null,o=Yt(a,t?.cloud);return e.cloud=o.apiKey?o:null,e.reportMode=t?.reportMode??"streaming",e.streamingThreshold=t?.streamingThreshold??0,Object.freeze(e)}var de="1.3.0";function Xt(t,e,r){try{let s=fs.readFileSync(t,"utf-8").split(`
6
6
  `);if(e<1||e>s.length)return null;let a=Math.max(1,e-r),o=Math.min(s.length,e+r),i=[];for(let d=a;d<=o;d++){let l=d===e?">":" ",c=String(d).padStart(String(o).length," ");i.push(`${l} ${c} | ${s[d-1]}`);}return i.join(`
7
- `)}catch{return null}}function Qt(t){return e=>{let r=e;for(let n of t)if(typeof n=="string"){let s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(s,"g"),"[REDACTED]");}else {let s=n.flags.includes("g")?n.flags:n.flags+"g",a=new RegExp(n.source,s);r=r.replace(a,"[REDACTED]");}return r}}function ns(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 ss(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 as(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 is(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 os(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 ls=[ns,ss,as,is,os];function F(t){let e=process.env;for(let r of ls){let n=r(e);if(n)return n}return null}var Fe=`
7
+ `)}catch{return null}}function er(t){return e=>{let r=e;for(let n of t)if(typeof n=="string"){let s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(s,"g"),"[REDACTED]");}else {let s=n.flags.includes("g")?n.flags:n.flags+"g",a=new RegExp(n.source,s);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 as(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 is(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 os(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 ls(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 ds=[ss,as,is,os,ls];function F(t){let e=process.env;for(let r of ds){let n=r(e);if(n)return n}return null}var De=`
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,15 +567,15 @@ 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 De=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 196 247" fill="none">
570
+ `;var Be=`<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"/>
568
- </linearGradient></defs></svg>`,Be=`<svg width="32" height="40" viewBox="0 0 196 247" fill="none" xmlns="http://www.w3.org/2000/svg">
574
+ </linearGradient></defs></svg>`,Oe=`<svg width="32" height="40" viewBox="0 0 196 247" fill="none" xmlns="http://www.w3.org/2000/svg">
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 Oe=`
578
+ </linearGradient></defs></svg>`;var qe=`
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 qe=`
1057
+ `;var He=`
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 He=`
1688
+ `;var Ue=`
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 Ue=`
1859
+ `;var $e=`
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 $e=`
2129
+ `;var ze=`
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 ze=`
2175
+ `;var je=`
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 je=`
2362
+ `;var We=`
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 ds=`
2371
+ `;var cs=`
2318
2372
  (function(){
2319
2373
  var data=JSON.parse(document.getElementById('report-data').textContent);
2320
- ${Oe}
2321
- ${$e}
2322
- ${ze}
2323
2374
  ${qe}
2324
- ${He}
2375
+ ${ze}
2325
2376
  ${je}
2377
+ ${He}
2326
2378
  ${Ue}
2379
+ ${We}
2380
+ ${$e}
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 Xt(t,e,r){let n=t.replace(/<\//g,"<\\/"),s=r?r.replace(/<\//g,"<\\/"):null;return `<!-- TestRelic AI Analytics Report \u2014 self-contained, no external dependencies -->
2388
+ })();`;function tr(t,e,r){let n=t.replace(/<\//g,"<\\/"),s=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,15 +2394,15 @@ 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(De).toString("base64")}">
2344
- <style>${Fe}</style>
2397
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Be).toString("base64")}">
2398
+ <style>${De}</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>
2348
2402
  <div class="wrap">
2349
2403
  <div class="top-bar">
2350
2404
  <div class="brand">
2351
- ${Be}
2405
+ ${Oe}
2352
2406
  <div class="brand-text">
2353
2407
  <span class="brand-title">TestRelic AI</span>
2354
2408
  <span class="brand-sub">Analytics Report</span>
@@ -2385,9 +2439,9 @@ ${""}
2385
2439
  </aside>
2386
2440
  <script id="report-data" type="application/json">${n}</script>
2387
2441
  ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:""}
2388
- <script>${ds}</script>
2442
+ <script>${cs}</script>
2389
2443
  </body>
2390
- </html>`}function We(t,e,r,n){let s=t.replace(/<\//g,"<\\/"),a=e.replace(/<\//g,"<\\/"),o=n?n.replace(/<\//g,"<\\/"):null,i={};try{i=JSON.parse(t);}catch{}let d=`{
2444
+ </html>`}function Ge(t,e,r,n){let s=t.replace(/<\//g,"<\\/"),a=e.replace(/<\//g,"<\\/"),o=n?n.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 @@ ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:
2471
2525
  window.__trServerPort=_serverPort;
2472
2526
  window.__trIsStreaming=true;
2473
2527
 
2474
- ${Oe}
2475
- ${$e}
2476
- ${ze}
2477
2528
  ${qe}
2478
- ${He}
2529
+ ${ze}
2479
2530
  ${je}
2531
+ ${He}
2480
2532
  ${Ue}
2533
+ ${We}
2534
+ ${$e}
2481
2535
  applyTheme();
2482
2536
  renderRunMeta();
2483
2537
  renderSummary();
@@ -2496,15 +2550,15 @@ ${s?`<script id="artifact-manifest-data" type="application/json">${s}</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(De).toString("base64")}">
2500
- <style>${Fe}</style>
2553
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Be).toString("base64")}">
2554
+ <style>${De}</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>
2504
2558
  <div class="wrap">
2505
2559
  <div class="top-bar">
2506
2560
  <div class="brand">
2507
- ${Be}
2561
+ ${Oe}
2508
2562
  <div class="brand-text">
2509
2563
  <span class="brand-title">TestRelic AI</span>
2510
2564
  <span class="brand-sub">Analytics Report</span>
@@ -2544,55 +2598,55 @@ ${o?`<script id="artifact-manifest-data" type="application/json">${o}</script>`:
2544
2598
  <script>${l}</script>
2545
2599
  </body>
2546
2600
  </html>`}function Ve(t){try{let e=process.platform,r,n;e==="darwin"?(r="open",n=[t]):e==="win32"?(r="cmd",n=["/c","start","",t]):(r="xdg-open",n=[t]),child_process.execFile(r,n,s=>{s&&process.stderr.write(`[testrelic] Failed to open browser: ${s.message}
2547
- `);});}catch{}}var er=path.join(os$1.tmpdir(),"testrelic-data"),P=class{constructor(e){this.count=0;this.closed=false;fs.mkdirSync(er,{recursive:true}),this.filePath=path.join(er,`${e}-${crypto.randomUUID().substring(0,8)}.jsonl`),this.fd=fs.openSync(this.filePath,"w");}append(e){if(this.closed)return;let r=JSON.stringify(e)+`
2548
- `;fs.writeSync(this.fd,r),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{fs.closeSync(this.fd);}catch{}}}cleanup(){try{fs.unlinkSync(this.filePath);}catch{}}};async function rr(t,e,r,n){let s=(e-1)*r,a=[],o=0,i=readline.createInterface({input:fs.createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let c of i)if(c.length!==0){if(o>=s&&a.length<r)try{a.push(JSON.parse(c));}catch{}if(o++,a.length>=r&&n!==void 0)break}let d=n??o,l=Math.max(1,Math.ceil(d/r));return {items:a,total:d,page:e,pageSize:r,totalPages:l}}var ar=/^[a-f0-9]{12}$/,Ge=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,ir=500;function x(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function or(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 pe(t){try{return fs.existsSync(t)?JSON.parse(fs.readFileSync(t,"utf-8")):null}catch{return null}}function fe(t){let e=0;try{let r=fs.readdirSync(t,{withFileTypes:!0});for(let n of r){let s=path.join(t,n.name);n.isFile()?e+=fs.statSync(s).size:n.isDirectory()&&(e+=fe(s));}}catch{}return e}function lr(t,e,r,n){let s=pe(path.join(r,"index.json"));x(e,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-n)/1e3)});}function dr(t,e,r){let n=pe(path.join(r,"summary.json"));if(!n){x(e,404,{error:"Summary not found"});return}x(e,200,n);}function cr(t,e,r){let n=pe(path.join(r,"index.json"));if(!n){x(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(ir,Math.max(1,parseInt(a.get("pageSize")??"100",10)||100)),d=a.get("status")?.split(",").filter(Boolean)??null,l=a.get("file")??null,c=a.get("search")?.toLowerCase()??null,f=a.get("tag")?.split(",").filter(Boolean)??null,g=a.get("sort")??"file",u=a.get("order")==="desc"?-1:1,h=n;d&&d.length>0&&(h=h.filter(v=>d.includes(v.status))),l&&(h=h.filter(v=>v.filePath===l||v.filePath.startsWith(l+"/"))),c&&(h=h.filter(v=>v.title.toLowerCase().includes(c)||v.filePath.toLowerCase().includes(c))),f&&f.length>0&&(h=h.filter(v=>f.some(k=>v.tags.includes(k)))),h=[...h].sort((v,k)=>{let C=0;switch(g){case "duration":C=v.duration-k.duration;break;case "status":C=v.status.localeCompare(k.status);break;case "title":C=v.title.localeCompare(k.title);break;default:C=v.filePath.localeCompare(k.filePath);break}return C*u});let p=h.length,m=Math.max(1,Math.ceil(p/i)),y=(o-1)*i,w=h.slice(y,y+i);x(e,200,{tests:w,pagination:{page:o,pageSize:i,totalItems:p,totalPages:m},filters:{status:d,file:l,search:c,tag:f}});}function ur(t,e,r,n){if(!ar.test(n)){x(e,400,{error:"Invalid test ID format"});return}let s=path.join(r,"tests",n,"meta.json"),a=path.join(r,"tests",`${n}.json`),o=fs.existsSync(s)?s:fs.existsSync(a)?a:null;if(!o){x(e,404,{error:`Test not found: ${n}`});return}try{let i=fs.readFileSync(o,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(i);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}async function pr(t,e,r,n,s){if(!ar.test(n)){x(e,400,{error:"Invalid test ID format"});return}let o=path.join(r,"tests",n,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!fs.existsSync(o)){x(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),c=Math.min(ir,Math.max(1,parseInt(d.get("pageSize")??"50",10)||50)),f,g=path.join(r,"tests",n,"meta.json");if(fs.existsSync(g))try{let h=JSON.parse(fs.readFileSync(g,"utf-8"));switch(s){case "network":f=h.networkRequestsCount;break;case "console":f=h.consoleLogsCount;break;case "api-calls":f=h.apiCallsCount;break}}catch{}let u=await rr(o,l,c,f);x(e,200,u);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}function fr(t,e,r){let n=pe(path.join(r,"index.json"));if(!n){x(e,404,{error:"Test index not found"});return}let s=new Map;for(let o of n){if(o.isRetry)continue;let i=s.get(o.filePath);switch(i||(i={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},s.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(s.entries()).map(([o,i])=>({filePath:o,...i})).sort((o,i)=>o.filePath.localeCompare(i.filePath));x(e,200,{files:a});}function gr(t,e,r){if(!fs.existsSync(r)){x(e,200,{runs:[],totalSizeBytes:0});return}try{let n=[],s=0,a=fs.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!Ge.test(o.name))continue;let i=path.join(r,o.name),d=fe(i),l=fs.readdirSync(i,{withFileTypes:!0}).filter(c=>c.isDirectory());n.push({folderName:o.name,totalSizeBytes:d,testCount:l.length}),s+=d;}n.sort((o,i)=>i.folderName.localeCompare(o.folderName)),x(e,200,{runs:n,totalSizeBytes:s});}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}function hr(t,e,r){try{let n=0,s=0;if(fs.existsSync(r)){let a=fs.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!Ge.test(o.name))continue;let i=path.join(r,o.name),d=fe(i);fs.rmSync(i,{recursive:!0,force:!0}),s+=d,n++;}}x(e,200,{deletedCount:n,freedBytes:s});}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}function mr(t,e,r,n){if(!Ge.test(n)){x(e,400,{error:"Invalid folder name"});return}let s=path.join(r,n);try{if(!fs.statSync(s).isDirectory()){x(e,404,{error:"Not found"});return}}catch{x(e,404,{error:"Not found"});return}try{let a=fe(s);fs.rmSync(s,{recursive:!0,force:!0}),x(e,200,{deleted:n,freedBytes:a});}catch(a){x(e,500,{error:a instanceof Error?a.message:String(a)});}}function yr(t,e,r){x(e,200,{status:"shutting_down"}),r.close();}function Je(t,e,r){if(!fs.existsSync(r)){x(e,404,{error:"File not found"});return}try{let n=fs.readFileSync(r),s=path.extname(r).toLowerCase(),a=xs[s]??"application/octet-stream";e.writeHead(200,{"Content-Type":a}),e.end(n);}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}var xs={".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 Ss=9323,Rs=10,As=1800*1e3;function re(t,e){return new Promise((r,n)=>{let s=e?.port??Ss,a=Date.now(),o,i=0,d=fs.existsSync(path.join(t,"artifacts"))?path.join(t,"artifacts"):fs.existsSync(path.join(t,"..","artifacts"))?path.join(t,"..","artifacts"):path.join(t,"artifacts");function l(){clearTimeout(o),o=setTimeout(()=>{f.close();},As);}let c=e?.htmlPath??null;if(!c){let u=path.dirname(t);try{let h=fs.readdirSync(u).find(p=>p.endsWith(".html"));h&&(c=path.join(u,h));}catch{}}let f=http.createServer((u,h)=>{if(l(),or(h),u.method==="OPTIONS"){h.writeHead(204),h.end();return}let p;try{p=new URL(u.url??"/",`http://${u.headers.host??"localhost"}`).pathname;}catch{x(h,400,{error:"Invalid URL"});return}if(u.method==="GET"&&(p==="/"||p==="/index.html")){if(c&&fs.existsSync(c)){Je(u,h,c);return}x(h,404,{error:"HTML report not found"});return}if(u.method==="GET"&&p==="/api/health"){lr(u,h,t,a);return}if(u.method==="GET"&&p==="/api/summary"){dr(u,h,t);return}if(u.method==="GET"&&p==="/api/tests"){cr(u,h,t);return}if(u.method==="GET"&&p==="/api/files"){fr(u,h,t);return}let m=p.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(u.method==="GET"&&m){pr(u,h,t,m[1],m[2]);return}let y=p.match(/^\/api\/tests\/([a-f0-9]+)$/);if(u.method==="GET"&&y){ur(u,h,t,y[1]);return}if(u.method==="GET"&&p==="/api/artifacts"){gr(u,h,d);return}if(u.method==="DELETE"&&p==="/api/artifacts"){hr(u,h,d);return}let w=p.match(/^\/api\/artifacts\/(.+)$/);if(u.method==="DELETE"&&w){mr(u,h,d,decodeURIComponent(w[1]));return}if(u.method==="GET"&&p.startsWith("/artifacts/")){let v=decodeURIComponent(p.slice(11));if(v.includes("..")||v.includes("\0")){x(h,400,{error:"Invalid path"});return}Je(u,h,path.join(d,v));return}if(u.method==="POST"&&p==="/api/shutdown"){yr(u,h,f);return}x(h,404,{error:"Not found"});});function g(u){let h=p=>{p.code==="EADDRINUSE"&&i<Rs?(i++,g(u+1)):n(p);};f.once("error",h),f.listen(u,"127.0.0.1",()=>{f.removeListener("error",h);let p=f.address();if(!p||typeof p=="string"){n(new Error("Failed to get server address"));return}l(),r({port:p.port,dispose:()=>new Promise(m=>{clearTimeout(o),f.close(()=>m());})});});}g(s);})}async function vr(t){let e=await re(t);return {port:e.port,dispose:e.dispose}}function Ls(t,e,r){let n=JSON.stringify(t),s=r?JSON.stringify(r):null;return Xt(n,e,s)}async function Ye(t,e,r){try{let n=null,s=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.mkdirSync(d,{recursive:!0});let l="",c="[]",f=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 u=path.dirname(e.outputPath),h=path.join(u,".testrelic-report");try{let p=path.join(h,"index-compact.json"),m=path.join(h,"index.json");fs.existsSync(p)?c=fs.readFileSync(p,"utf-8"):fs.existsSync(m)&&(c=fs.readFileSync(m,"utf-8"));}catch{}f=r?JSON.stringify(r):null,o=We(l,c,null,f);}else o=Ls(t,null,r);let g=i+".tmp";if(fs.writeFileSync(g,o,"utf-8"),fs.renameSync(g,i),a){if(t.ci===null){let u=path.dirname(e.outputPath),h=path.join(u,".testrelic-report"),p=path.resolve(i);try{if(await Es(),n=await Ps(h),!n){s=await re(h,{htmlPath:p}),n=s.port;let m=setInterval(()=>{},6e4),y=()=>{clearInterval(m),s?.dispose();};process.on("SIGINT",y),process.on("SIGTERM",y),setTimeout(y,1800*1e3).unref();}if(n){process.stderr.write(`
2601
+ `);});}catch{}}var rr=path.join(os$1.tmpdir(),"testrelic-data"),E=class{constructor(e){this.count=0;this.closed=false;fs.mkdirSync(rr,{recursive:true}),this.filePath=path.join(rr,`${e}-${crypto.randomUUID().substring(0,8)}.jsonl`),this.fd=fs.openSync(this.filePath,"w");}append(e){if(this.closed)return;let r=JSON.stringify(e)+`
2602
+ `;fs.writeSync(this.fd,r),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{fs.closeSync(this.fd);}catch{}}}cleanup(){try{fs.unlinkSync(this.filePath);}catch{}}};async function sr(t,e,r,n){let s=(e-1)*r,a=[],o=0,i=readline.createInterface({input:fs.createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let c of i)if(c.length!==0){if(o>=s&&a.length<r)try{a.push(JSON.parse(c));}catch{}if(o++,a.length>=r&&n!==void 0)break}let d=n??o,l=Math.max(1,Math.ceil(d/r));return {items:a,total:d,page:e,pageSize:r,totalPages:l}}var or=/^[a-f0-9]{12}$/,Ke=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,lr=500;function x(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function dr(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 pe(t){try{return fs.existsSync(t)?JSON.parse(fs.readFileSync(t,"utf-8")):null}catch{return null}}function fe(t){let e=0;try{let r=fs.readdirSync(t,{withFileTypes:!0});for(let n of r){let s=path.join(t,n.name);n.isFile()?e+=fs.statSync(s).size:n.isDirectory()&&(e+=fe(s));}}catch{}return e}function cr(t,e,r,n){let s=pe(path.join(r,"index.json"));x(e,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-n)/1e3)});}function ur(t,e,r){let n=pe(path.join(r,"summary.json"));if(!n){x(e,404,{error:"Summary not found"});return}x(e,200,n);}function pr(t,e,r){let n=pe(path.join(r,"index.json"));if(!n){x(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(lr,Math.max(1,parseInt(a.get("pageSize")??"100",10)||100)),d=a.get("status")?.split(",").filter(Boolean)??null,l=a.get("file")??null,c=a.get("search")?.toLowerCase()??null,f=a.get("tag")?.split(",").filter(Boolean)??null,g=a.get("sort")??"file",u=a.get("order")==="desc"?-1:1,h=n;d&&d.length>0&&(h=h.filter(v=>d.includes(v.status))),l&&(h=h.filter(v=>v.filePath===l||v.filePath.startsWith(l+"/"))),c&&(h=h.filter(v=>v.title.toLowerCase().includes(c)||v.filePath.toLowerCase().includes(c))),f&&f.length>0&&(h=h.filter(v=>f.some(k=>v.tags.includes(k)))),h=[...h].sort((v,k)=>{let C=0;switch(g){case "duration":C=v.duration-k.duration;break;case "status":C=v.status.localeCompare(k.status);break;case "title":C=v.title.localeCompare(k.title);break;default:C=v.filePath.localeCompare(k.filePath);break}return C*u});let p=h.length,m=Math.max(1,Math.ceil(p/i)),y=(o-1)*i,w=h.slice(y,y+i);x(e,200,{tests:w,pagination:{page:o,pageSize:i,totalItems:p,totalPages:m},filters:{status:d,file:l,search:c,tag:f}});}function fr(t,e,r,n){if(!or.test(n)){x(e,400,{error:"Invalid test ID format"});return}let s=path.join(r,"tests",n,"meta.json"),a=path.join(r,"tests",`${n}.json`),o=fs.existsSync(s)?s:fs.existsSync(a)?a:null;if(!o){x(e,404,{error:`Test not found: ${n}`});return}try{let i=fs.readFileSync(o,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(i);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}async function gr(t,e,r,n,s){if(!or.test(n)){x(e,400,{error:"Invalid test ID format"});return}let o=path.join(r,"tests",n,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!fs.existsSync(o)){x(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),c=Math.min(lr,Math.max(1,parseInt(d.get("pageSize")??"50",10)||50)),f,g=path.join(r,"tests",n,"meta.json");if(fs.existsSync(g))try{let h=JSON.parse(fs.readFileSync(g,"utf-8"));switch(s){case "network":f=h.networkRequestsCount;break;case "console":f=h.consoleLogsCount;break;case "api-calls":f=h.apiCallsCount;break}}catch{}let u=await sr(o,l,c,f);x(e,200,u);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}function hr(t,e,r){let n=pe(path.join(r,"index.json"));if(!n){x(e,404,{error:"Test index not found"});return}let s=new Map;for(let o of n){if(o.isRetry)continue;let i=s.get(o.filePath);switch(i||(i={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},s.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(s.entries()).map(([o,i])=>({filePath:o,...i})).sort((o,i)=>o.filePath.localeCompare(i.filePath));x(e,200,{files:a});}function mr(t,e,r){if(!fs.existsSync(r)){x(e,200,{runs:[],totalSizeBytes:0});return}try{let n=[],s=0,a=fs.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!Ke.test(o.name))continue;let i=path.join(r,o.name),d=fe(i),l=fs.readdirSync(i,{withFileTypes:!0}).filter(c=>c.isDirectory());n.push({folderName:o.name,totalSizeBytes:d,testCount:l.length}),s+=d;}n.sort((o,i)=>i.folderName.localeCompare(o.folderName)),x(e,200,{runs:n,totalSizeBytes:s});}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}function yr(t,e,r){try{let n=0,s=0;if(fs.existsSync(r)){let a=fs.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!Ke.test(o.name))continue;let i=path.join(r,o.name),d=fe(i);fs.rmSync(i,{recursive:!0,force:!0}),s+=d,n++;}}x(e,200,{deletedCount:n,freedBytes:s});}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}function vr(t,e,r,n){if(!Ke.test(n)){x(e,400,{error:"Invalid folder name"});return}let s=path.join(r,n);try{if(!fs.statSync(s).isDirectory()){x(e,404,{error:"Not found"});return}}catch{x(e,404,{error:"Not found"});return}try{let a=fe(s);fs.rmSync(s,{recursive:!0,force:!0}),x(e,200,{deleted:n,freedBytes:a});}catch(a){x(e,500,{error:a instanceof Error?a.message:String(a)});}}function br(t,e,r){x(e,200,{status:"shutting_down"}),r.close();}function Je(t,e,r){if(!fs.existsSync(r)){x(e,404,{error:"File not found"});return}try{let n=fs.readFileSync(r),s=path.extname(r).toLowerCase(),a=ks[s]??"application/octet-stream";e.writeHead(200,{"Content-Type":a}),e.end(n);}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}var ks={".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 Rs=9323,As=10,_s=1800*1e3;function re(t,e){return new Promise((r,n)=>{let s=e?.port??Rs,a=Date.now(),o,i=0,d=fs.existsSync(path.join(t,"artifacts"))?path.join(t,"artifacts"):fs.existsSync(path.join(t,"..","artifacts"))?path.join(t,"..","artifacts"):path.join(t,"artifacts");function l(){clearTimeout(o),o=setTimeout(()=>{f.close();},_s);}let c=e?.htmlPath??null;if(!c){let u=path.dirname(t);try{let h=fs.readdirSync(u).find(p=>p.endsWith(".html"));h&&(c=path.join(u,h));}catch{}}let f=http.createServer((u,h)=>{if(l(),dr(h),u.method==="OPTIONS"){h.writeHead(204),h.end();return}let p;try{p=new URL(u.url??"/",`http://${u.headers.host??"localhost"}`).pathname;}catch{x(h,400,{error:"Invalid URL"});return}if(u.method==="GET"&&(p==="/"||p==="/index.html")){if(c&&fs.existsSync(c)){Je(u,h,c);return}x(h,404,{error:"HTML report not found"});return}if(u.method==="GET"&&p==="/api/health"){cr(u,h,t,a);return}if(u.method==="GET"&&p==="/api/summary"){ur(u,h,t);return}if(u.method==="GET"&&p==="/api/tests"){pr(u,h,t);return}if(u.method==="GET"&&p==="/api/files"){hr(u,h,t);return}let m=p.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(u.method==="GET"&&m){gr(u,h,t,m[1],m[2]);return}let y=p.match(/^\/api\/tests\/([a-f0-9]+)$/);if(u.method==="GET"&&y){fr(u,h,t,y[1]);return}if(u.method==="GET"&&p==="/api/artifacts"){mr(u,h,d);return}if(u.method==="DELETE"&&p==="/api/artifacts"){yr(u,h,d);return}let w=p.match(/^\/api\/artifacts\/(.+)$/);if(u.method==="DELETE"&&w){vr(u,h,d,decodeURIComponent(w[1]));return}if(u.method==="GET"&&p.startsWith("/artifacts/")){let v=decodeURIComponent(p.slice(11));if(v.includes("..")||v.includes("\0")){x(h,400,{error:"Invalid path"});return}Je(u,h,path.join(d,v));return}if(u.method==="POST"&&p==="/api/shutdown"){br(u,h,f);return}x(h,404,{error:"Not found"});});function g(u){let h=p=>{p.code==="EADDRINUSE"&&i<As?(i++,g(u+1)):n(p);};f.once("error",h),f.listen(u,"127.0.0.1",()=>{f.removeListener("error",h);let p=f.address();if(!p||typeof p=="string"){n(new Error("Failed to get server address"));return}l(),r({port:p.port,dispose:()=>new Promise(m=>{clearTimeout(o),f.close(()=>m());})});});}g(s);})}async function wr(t){let e=await re(t);return {port:e.port,dispose:e.dispose}}function Ms(t,e,r){let n=JSON.stringify(t),s=r?JSON.stringify(r):null;return tr(n,e,s)}async function Ze(t,e,r){try{let n=null,s=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.mkdirSync(d,{recursive:!0});let l="",c="[]",f=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 u=path.dirname(e.outputPath),h=path.join(u,".testrelic-report");try{let p=path.join(h,"index-compact.json"),m=path.join(h,"index.json");fs.existsSync(p)?c=fs.readFileSync(p,"utf-8"):fs.existsSync(m)&&(c=fs.readFileSync(m,"utf-8"));}catch{}f=r?JSON.stringify(r):null,o=Ge(l,c,null,f);}else o=Ms(t,null,r);let g=i+".tmp";if(fs.writeFileSync(g,o,"utf-8"),fs.renameSync(g,i),a){if(t.ci===null){let u=path.dirname(e.outputPath),h=path.join(u,".testrelic-report"),p=path.resolve(i);try{if(await Es(),n=await Ns(h),!n){s=await re(h,{htmlPath:p}),n=s.port;let m=setInterval(()=>{},6e4),y=()=>{clearInterval(m),s?.dispose();};process.on("SIGINT",y),process.on("SIGTERM",y),setTimeout(y,1800*1e3).unref();}if(n){process.stderr.write(`
2549
2603
  Report server: http://127.0.0.1:${n}
2550
- `);try{let m=We(l,c,n,f),y=i+".tmp";fs.writeFileSync(y,m,"utf-8"),fs.renameSync(y,i);}catch{}}}catch{}}}else if(e.openReport&&t.ci===null&&e.includeArtifacts){let u=path.dirname(e.outputPath),h=path.join(u,"artifacts");if(fs.existsSync(h))try{let p=await vr(h);n=p.port,process.on("exit",()=>{p.dispose();});}catch{}}if(e.openReport&&t.ci===null)if(a&&n)Ve(`http://127.0.0.1:${n}`);else {let u=path.resolve(i);Ve(u);}}catch(n){process.stderr.write(`[testrelic] Failed to write HTML report: ${n instanceof Error?n.message:String(n)}
2551
- `);}}var me=9323,Tr=10;async function Ms(){for(let t=me;t<me+Tr;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${t}/api/health`,{signal:e.signal});if(clearTimeout(r),n.ok)return t}catch{}return null}async function Es(){for(let t=me;t<me+Tr;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 Ps(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(n=>fs.existsSync(n));if(!r){let n=await re(t);return process.on("exit",()=>{n?.dispose();}),n.port}return new Promise(n=>{let s=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,s.stderr?.removeAllListeners(),Ms().then(n));},5e3);s.stderr?.on("data",d=>{a+=d.toString();let l=a.match(/127\.0\.0\.1:(\d+)/);l&&!o&&(o=true,clearTimeout(i),s.stderr?.removeAllListeners(),s.unref(),n(Number(l[1])));}),s.on("error",()=>{o||(o=true,clearTimeout(i),n(null));}),s.on("exit",()=>{o||(o=true,clearTimeout(i),n(null));}),s.unref();})}var Ds=20,Ze=0,Qe=[];async function Sr(t,e){Ze>=Ds&&await new Promise(r=>Qe.push(r)),Ze++;try{return await promises.copyFile(t,e),!0}catch{return false}finally{Ze--,Qe.length>0&&Qe.shift()();}}var se=[];async function Ar(){se.length!==0&&(await Promise.allSettled(se),se.length=0);}function _r(t){let e=new Date,r=a=>String(a).padStart(2,"0"),n=`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())}T${r(e.getHours())}-${r(e.getMinutes())}-${r(e.getSeconds())}`;if(!fs.existsSync(path.join(t,n)))return n;let s=1;for(;fs.existsSync(path.join(t,`${n}-${s}`));)s++;return `${n}-${s}`}function Rr(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 Bs=8;function Os(t,e,r){let n=Rr(t),s=r?Rr(r).substring(0,Bs):"";return s&&(n+=`--${s}`),e>0&&(n+=`--retry-${e}`),n}function Ir(t,e,r,n,s,a){let o=t.find(u=>u.name==="screenshot"&&u.path),i=t.find(u=>u.name==="video"&&u.path);if(!o&&!i)return null;let d=Os(e,r,a),l=s?["artifacts",s,d]:["artifacts",d],c=path.join(n,...l),f=l,g={};try{fs.mkdirSync(c,{recursive:!0});}catch{return null}if(o?.path&&fs.existsSync(o.path)){let h=`screenshot${path.extname(o.path)||".png"}`,p=path.join(c,h);se.push(Sr(o.path,p).then(()=>{})),g.screenshot=`${f.join("/")}/${h}`;}if(i?.path&&fs.existsSync(i.path)){let h=`video${path.extname(i.path)||".webm"}`,p=path.join(c,h);se.push(Sr(i.path,p).then(()=>{})),g.video=`${f.join("/")}/${h}`;}return !g.screenshot&&!g.video?null:g}var Us=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,$s="1.0";function zs(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 Lr(t,e,r){let n=[];try{let s=fs.readdirSync(t,{withFileTypes:!0});for(let a of s){if(!a.isFile())continue;let o=path.join(t,a.name),i=fs.statSync(o);n.push({name:a.name,type:zs(a.name),relativePath:`artifacts/${e}/${r}/${a.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:n}}function js(t,e){let r=path.join(t,e),n=[],s=0;try{let o=fs.readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let d=Lr(path.join(r,i.name),e,i.name);n.push(d);for(let l of d.files)s+=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 n.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:e,timestamp:a,totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}}function Mr(t,e){let r=path.join(t,"artifacts"),n=[],s=[],a=0;try{let i=fs.readdirSync(r,{withFileTypes:!0});for(let d of i)if(d.isDirectory())if(Us.test(d.name)){let l=js(r,d.name);n.push({...l,isCurrentRun:d.name===e});}else {let l=Lr(path.join(r,d.name),d.name,d.name);s.push(l);for(let c of l.files)a+=c.sizeBytes;}}catch{}n.sort((i,d)=>d.timestamp.localeCompare(i.timestamp)),s.length>0&&(s.sort((i,d)=>i.testName.localeCompare(d.testName)),n.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:a,testCount:s.length,tests:s,isCurrentRun:false}));let o=n.reduce((i,d)=>i+d.totalSizeBytes,0);return {schemaVersion:$s,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:n,serverPort:null}}var Ys=256;function Zs(t){let e=path.resolve(t);for(let r=0;r<Ys;r++){if(fs.existsSync(path.join(e,".git")))return e;let n=path.dirname(e);if(n===e)return null;e=n;}return null}function Nr(t){try{let e=Zs(t);if(!e)return;let r=path.join(e,".gitignore"),n=path.relative(e,t).replace(/\\/g,"/"),s=n.endsWith("/")?n:`${n}/`;if(fs.existsSync(r)&&fs.readFileSync(r,"utf-8").split(`
2604
+ `);try{let m=Ge(l,c,n,f),y=i+".tmp";fs.writeFileSync(y,m,"utf-8"),fs.renameSync(y,i);}catch{}}}catch{}}}else if(e.openReport&&t.ci===null&&e.includeArtifacts){let u=path.dirname(e.outputPath),h=path.join(u,"artifacts");if(fs.existsSync(h))try{let p=await wr(h);n=p.port,process.on("exit",()=>{p.dispose();});}catch{}}if(e.openReport&&t.ci===null)if(a&&n)Ve(`http://127.0.0.1:${n}`);else {let u=path.resolve(i);Ve(u);}}catch(n){process.stderr.write(`[testrelic] Failed to write HTML report: ${n instanceof Error?n.message:String(n)}
2605
+ `);}}var me=9323,Sr=10;async function Ps(){for(let t=me;t<me+Sr;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${t}/api/health`,{signal:e.signal});if(clearTimeout(r),n.ok)return t}catch{}return null}async function Es(){for(let t=me;t<me+Sr;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 Ns(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(n=>fs.existsSync(n));if(!r){let n=await re(t);return process.on("exit",()=>{n?.dispose();}),n.port}return new Promise(n=>{let s=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,s.stderr?.removeAllListeners(),Ps().then(n));},5e3);s.stderr?.on("data",d=>{a+=d.toString();let l=a.match(/127\.0\.0\.1:(\d+)/);l&&!o&&(o=true,clearTimeout(i),s.stderr?.removeAllListeners(),s.unref(),n(Number(l[1])));}),s.on("error",()=>{o||(o=true,clearTimeout(i),n(null));}),s.on("exit",()=>{o||(o=true,clearTimeout(i),n(null));}),s.unref();})}var Bs=20,Qe=0,Xe=[];async function Ar(t,e){Qe>=Bs&&await new Promise(r=>Xe.push(r)),Qe++;try{return await promises.copyFile(t,e),!0}catch{return false}finally{Qe--,Xe.length>0&&Xe.shift()();}}var se=[];async function Ir(){se.length!==0&&(await Promise.allSettled(se),se.length=0);}function Lr(t){let e=new Date,r=a=>String(a).padStart(2,"0"),n=`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())}T${r(e.getHours())}-${r(e.getMinutes())}-${r(e.getSeconds())}`;if(!fs.existsSync(path.join(t,n)))return n;let s=1;for(;fs.existsSync(path.join(t,`${n}-${s}`));)s++;return `${n}-${s}`}function _r(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 Os=8;function qs(t,e,r){let n=_r(t),s=r?_r(r).substring(0,Os):"";return s&&(n+=`--${s}`),e>0&&(n+=`--retry-${e}`),n}function Mr(t,e,r,n,s,a){let o=t.find(u=>u.name==="screenshot"&&u.path),i=t.find(u=>u.name==="video"&&u.path);if(!o&&!i)return null;let d=qs(e,r,a),l=s?["artifacts",s,d]:["artifacts",d],c=path.join(n,...l),f=l,g={};try{fs.mkdirSync(c,{recursive:!0});}catch{return null}if(o?.path&&fs.existsSync(o.path)){let h=`screenshot${path.extname(o.path)||".png"}`,p=path.join(c,h);se.push(Ar(o.path,p).then(()=>{})),g.screenshot=`${f.join("/")}/${h}`;}if(i?.path&&fs.existsSync(i.path)){let h=`video${path.extname(i.path)||".webm"}`,p=path.join(c,h);se.push(Ar(i.path,p).then(()=>{})),g.video=`${f.join("/")}/${h}`;}return !g.screenshot&&!g.video?null:g}var $s=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,zs="1.0";function js(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 Pr(t,e,r){let n=[];try{let s=fs.readdirSync(t,{withFileTypes:!0});for(let a of s){if(!a.isFile())continue;let o=path.join(t,a.name),i=fs.statSync(o);n.push({name:a.name,type:js(a.name),relativePath:`artifacts/${e}/${r}/${a.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:n}}function Ws(t,e){let r=path.join(t,e),n=[],s=0;try{let o=fs.readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let d=Pr(path.join(r,i.name),e,i.name);n.push(d);for(let l of d.files)s+=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 n.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:e,timestamp:a,totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}}function Er(t,e){let r=path.join(t,"artifacts"),n=[],s=[],a=0;try{let i=fs.readdirSync(r,{withFileTypes:!0});for(let d of i)if(d.isDirectory())if($s.test(d.name)){let l=Ws(r,d.name);n.push({...l,isCurrentRun:d.name===e});}else {let l=Pr(path.join(r,d.name),d.name,d.name);s.push(l);for(let c of l.files)a+=c.sizeBytes;}}catch{}n.sort((i,d)=>d.timestamp.localeCompare(i.timestamp)),s.length>0&&(s.sort((i,d)=>i.testName.localeCompare(d.testName)),n.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:a,testCount:s.length,tests:s,isCurrentRun:false}));let o=n.reduce((i,d)=>i+d.totalSizeBytes,0);return {schemaVersion:zs,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:n,serverPort:null}}var Zs=256;function Qs(t){let e=path.resolve(t);for(let r=0;r<Zs;r++){if(fs.existsSync(path.join(e,".git")))return e;let n=path.dirname(e);if(n===e)return null;e=n;}return null}function Dr(t){try{let e=Qs(t);if(!e)return;let r=path.join(e,".gitignore"),n=path.relative(e,t).replace(/\\/g,"/"),s=n.endsWith("/")?n:`${n}/`;if(fs.existsSync(r)&&fs.readFileSync(r,"utf-8").split(`
2552
2606
  `).map(d=>d.trim()).some(d=>d===s||d===n))return;let a=`
2553
2607
  # TestRelic test artifacts
2554
2608
  ${s}
2555
- `;fs.appendFileSync(r,a,"utf-8");}catch{}}var Fr=Symbol("testrelic.timeout"),Dr=3e4,et=12e4,tt=6e4,Br=15e3;async function $(t,e,r){let n,s=new Promise(a=>{n=setTimeout(()=>a(Fr),e),typeof n?.unref=="function"&&n.unref();});try{let a=await Promise.race([t(),s]);if(a===Fr){process.stderr.write(`[testrelic] ${r} timed out after ${Math.round(e/1e3)}s \u2014 continuing without it. Your tests are unaffected.
2609
+ `;fs.appendFileSync(r,a,"utf-8");}catch{}}var Br=Symbol("testrelic.timeout"),Or=3e4,tt=12e4,rt=6e4,qr=15e3;async function $(t,e,r){let n,s=new Promise(a=>{n=setTimeout(()=>a(Br),e),typeof n?.unref=="function"&&n.unref();});try{let a=await Promise.race([t(),s]);if(a===Br){process.stderr.write(`[testrelic] ${r} timed out after ${Math.round(e/1e3)}s \u2014 continuing without it. Your tests are unaffected.
2556
2610
  `);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)})
2557
- `);return}finally{n&&clearTimeout(n);}}function Hr(t,e){let r=[];for(let n of t){let s=Qs(n),a=Xs(n),o=ea(n,s,a,e),i=ta(n,s,a);if(o.length===0&&i.length===0){r.push({type:"navigation",url:"about:blank",timestamp:n.startedAt,durationOnUrl:n.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:n.specFile,test:s,tests:[a],_testTitle:n.title});continue}r.push(...o,...i);}return r.sort(ra),na(r,t),r.map((n,s)=>n.type==="navigation"?{...{index:s,type:"navigation",url:n.url,timestamp:n.timestamp,durationOnUrl:n.durationOnUrl??0,navigationType:n.navigationType,domContentLoadedAt:n.domContentLoadedAt??null,networkIdleAt:n.networkIdleAt??null,networkStats:n.networkStats??null,specFile:n.specFile,test:n.test},tests:n.tests}:{...{index:s,type:"api_call",callId:n.callId,method:n.method,url:n.url,timestamp:n.timestamp,responseTime:n.responseTime??null,request:n.request,response:n.response??null,...n.error?{error:n.error}:{},assertions:n.assertions??[],specFile:n.specFile,test:n.test},tests:n.tests})}function Qs(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 Xs(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 ea(t,e,r,n){let s=[];for(let a of t.navigations)n.navigationTypes!==null&&!n.navigationTypes.includes(a.navigationType)||s.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 s}function ta(t,e,r){if(!t.apiCalls||t.apiCalls.length===0)return [];let n=t.apiAssertions??[];return t.apiCalls.map(s=>{let a=n.filter(i=>i.callId===s.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 s.responseStatusCode!==null&&s.responseStatusText!==null&&(o={statusCode:s.responseStatusCode,statusText:s.responseStatusText,headers:s.responseHeaders,body:qr(s.responseBody)}),{type:"api_call",callId:s.id,method:s.method,url:s.url,timestamp:s.timestamp,responseTime:s.error?null:s.responseTimeMs,request:{headers:s.requestHeaders,body:qr(s.requestBody)},response:o,...s.error?{error:s.error}:{},assertions:a,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title}})}function ra(t,e){let r=new Date(t.timestamp).getTime(),n=new Date(e.timestamp).getTime();if(r!==n)return r-n;let s={navigation:0,api_call:1},a=s[t.type],o=s[e.type];return a!==o?a-o:t.type==="api_call"&&e.type==="api_call"&&t.callId&&e.callId?Or(t.callId)-Or(e.callId):0}function Or(t){let e=t.match(/(\d+)$/);return e?parseInt(e[1],10):0}function na(t,e){for(let r=0;r<t.length;r++){let n=t[r];if(n.type!=="navigation")continue;let s=new Date(n.timestamp).getTime(),a=null;for(let o=r+1;o<t.length;o++)if(t[o]._testTitle===n._testTitle){a=new Date(t[o].timestamp).getTime();break}if(a!==null)n.durationOnUrl=Math.max(0,a-s);else {let o=e.find(i=>i.title===n._testTitle);if(o){let i=new Date(o.completedAt).getTime();n.durationOnUrl=Math.max(0,i-s);}}}}function qr(t){if(t==null)return null;try{return JSON.parse(t)}catch{return t}}function z(t,e){let r=t.length,n=Math.min(Math.ceil(e/100*r)-1,r-1);return t[Math.max(0,n)]}function rt(t){try{let e=new URL(t);return e.origin+e.pathname}catch{return t}}function sa(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 Ur(t,e){let r=0,n=0,s=0,a=0,o=0;for(let b of t)switch(b.status){case "passed":r++;break;case "failed":n++;break;case "flaky":s++;break;case "skipped":a++;break;case "timedout":o++;break}let i=[];for(let b of t)b.apiCalls&&i.push(...b.apiCalls);let d=i.length,l=new Set,c={},f={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},g=[];for(let b of i)l.add(rt(b.url)),c[b.method]=(c[b.method]??0)+1,f[sa(b.responseStatusCode)]+=1,g.push(b.responseTimeMs);let u=null;if(g.length>0){let b=[...g].sort((S,M)=>S-M),T=b.reduce((S,M)=>S+M,0);u={avg:Math.round(T/b.length),min:b[0],max:b[b.length-1],p50:z(b,50),p95:z(b,95),p99:z(b,99)};}let h=0,p=0,m=0;for(let b of t)if(b.apiAssertions)for(let T of b.apiAssertions)h++,T.status==="passed"?p++:m++;let y=0,w=new Set;for(let b of t){y+=b.navigations.length;for(let T of b.navigations)w.add(T.url);}let v=0,k={};function C(b){for(let T of b)v++,k[T.category]=(k[T.category]??0)+1,T.children.length>0&&C(T.children);}for(let b of t)b.actions&&C(b.actions);return {total:t.length,passed:r,failed:n,flaky:s,skipped:a,timedout:o,totalApiCalls:d,uniqueApiUrls:l.size,apiCallsByMethod:c,apiCallsByStatusRange:f,apiResponseTime:u,totalAssertions:h,passedAssertions:p,failedAssertions:m,totalNavigations:y,uniqueNavigationUrls:w.size,totalTimelineSteps:e,totalActionSteps:v,actionStepsByCategory:k}}function aa(t){let e=56-t.length;return e>0?t+" ".repeat(e):t}function I(t){return `\u2502 ${aa(t)} \u2502
2558
- `}function nt(t,e,r,n){if(n||t.total===0)return;let s=`\u250C${"\u2500".repeat(58)}\u2510
2611
+ `);return}finally{n&&clearTimeout(n);}}function $r(t,e){let r=[];for(let n of t){let s=Xs(n),a=ea(n),o=ta(n,s,a,e),i=ra(n,s,a);if(o.length===0&&i.length===0){r.push({type:"navigation",url:"about:blank",timestamp:n.startedAt,durationOnUrl:n.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:n.specFile,test:s,tests:[a],_testTitle:n.title});continue}r.push(...o,...i);}return r.sort(na),sa(r,t),r.map((n,s)=>n.type==="navigation"?{...{index:s,type:"navigation",url:n.url,timestamp:n.timestamp,durationOnUrl:n.durationOnUrl??0,navigationType:n.navigationType,domContentLoadedAt:n.domContentLoadedAt??null,networkIdleAt:n.networkIdleAt??null,networkStats:n.networkStats??null,specFile:n.specFile,test:n.test},tests:n.tests}:{...{index:s,type:"api_call",callId:n.callId,method:n.method,url:n.url,timestamp:n.timestamp,responseTime:n.responseTime??null,request:n.request,response:n.response??null,...n.error?{error:n.error}:{},assertions:n.assertions??[],specFile:n.specFile,test:n.test},tests:n.tests})}function Xs(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 ea(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 ta(t,e,r,n){let s=[];for(let a of t.navigations)n.navigationTypes!==null&&!n.navigationTypes.includes(a.navigationType)||s.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 s}function ra(t,e,r){if(!t.apiCalls||t.apiCalls.length===0)return [];let n=t.apiAssertions??[];return t.apiCalls.map(s=>{let a=n.filter(i=>i.callId===s.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 s.responseStatusCode!==null&&s.responseStatusText!==null&&(o={statusCode:s.responseStatusCode,statusText:s.responseStatusText,headers:s.responseHeaders,body:Ur(s.responseBody)}),{type:"api_call",callId:s.id,method:s.method,url:s.url,timestamp:s.timestamp,responseTime:s.error?null:s.responseTimeMs,request:{headers:s.requestHeaders,body:Ur(s.requestBody)},response:o,...s.error?{error:s.error}:{},assertions:a,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title}})}function na(t,e){let r=new Date(t.timestamp).getTime(),n=new Date(e.timestamp).getTime();if(r!==n)return r-n;let s={navigation:0,api_call:1},a=s[t.type],o=s[e.type];return a!==o?a-o:t.type==="api_call"&&e.type==="api_call"&&t.callId&&e.callId?Hr(t.callId)-Hr(e.callId):0}function Hr(t){let e=t.match(/(\d+)$/);return e?parseInt(e[1],10):0}function sa(t,e){for(let r=0;r<t.length;r++){let n=t[r];if(n.type!=="navigation")continue;let s=new Date(n.timestamp).getTime(),a=null;for(let o=r+1;o<t.length;o++)if(t[o]._testTitle===n._testTitle){a=new Date(t[o].timestamp).getTime();break}if(a!==null)n.durationOnUrl=Math.max(0,a-s);else {let o=e.find(i=>i.title===n._testTitle);if(o){let i=new Date(o.completedAt).getTime();n.durationOnUrl=Math.max(0,i-s);}}}}function Ur(t){if(t==null)return null;try{return JSON.parse(t)}catch{return t}}function z(t,e){let r=t.length,n=Math.min(Math.ceil(e/100*r)-1,r-1);return t[Math.max(0,n)]}function nt(t){try{let e=new URL(t);return e.origin+e.pathname}catch{return t}}function aa(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 zr(t,e){let r=0,n=0,s=0,a=0,o=0;for(let b of t)switch(b.status){case "passed":r++;break;case "failed":n++;break;case "flaky":s++;break;case "skipped":a++;break;case "timedout":o++;break}let i=[];for(let b of t)b.apiCalls&&i.push(...b.apiCalls);let d=i.length,l=new Set,c={},f={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},g=[];for(let b of i)l.add(nt(b.url)),c[b.method]=(c[b.method]??0)+1,f[aa(b.responseStatusCode)]+=1,g.push(b.responseTimeMs);let u=null;if(g.length>0){let b=[...g].sort((S,M)=>S-M),T=b.reduce((S,M)=>S+M,0);u={avg:Math.round(T/b.length),min:b[0],max:b[b.length-1],p50:z(b,50),p95:z(b,95),p99:z(b,99)};}let h=0,p=0,m=0;for(let b of t)if(b.apiAssertions)for(let T of b.apiAssertions)h++,T.status==="passed"?p++:m++;let y=0,w=new Set;for(let b of t){y+=b.navigations.length;for(let T of b.navigations)w.add(T.url);}let v=0,k={};function C(b){for(let T of b)v++,k[T.category]=(k[T.category]??0)+1,T.children.length>0&&C(T.children);}for(let b of t)b.actions&&C(b.actions);return {total:t.length,passed:r,failed:n,flaky:s,skipped:a,timedout:o,totalApiCalls:d,uniqueApiUrls:l.size,apiCallsByMethod:c,apiCallsByStatusRange:f,apiResponseTime:u,totalAssertions:h,passedAssertions:p,failedAssertions:m,totalNavigations:y,uniqueNavigationUrls:w.size,totalTimelineSteps:e,totalActionSteps:v,actionStepsByCategory:k}}function ia(t){let e=56-t.length;return e>0?t+" ".repeat(e):t}function I(t){return `\u2502 ${ia(t)} \u2502
2612
+ `}function st(t,e,r,n){if(n||t.total===0)return;let s=`\u250C${"\u2500".repeat(58)}\u2510
2559
2613
  `,a=`\u2514${"\u2500".repeat(58)}\u2518
2560
2614
  `,o=I(""),i=s;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(([,f])=>f>0).map(([f,g])=>`${f}: ${g}`);l.length>0&&(i+=I(` ${l.join(" ")}`));let c=Object.entries(t.apiCallsByStatusRange).filter(([,f])=>f>0).map(([f,g])=>`${f}: ${g}`);c.length>0&&(i+=I(` ${c.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=[],c=t.actionStepsByCategory;c.ui_action&&l.push(`${c.ui_action} UI`),c.assertion&&l.push(`${c.assertion} assertions`),c.custom_step&&l.push(`${c.custom_step} custom`);let f=l.length>0?` (${l.join(" ")})`:"";i+=I(`Actions: ${t.totalActionSteps} steps${f}`);}i+=I(`Report: ${r}`),i+=I(`Data: ${e}`),i+=a,i+=`For more information visit us at https://docs.testrelic.ai
2561
- `,process.stderr.write(i);}var ia=new Set(["pw:api","expect","test.step"]);function oa(t){return t==="expect"?"assertion":t==="test.step"?"custom_step":"ui_action"}function st(t,e,r){if(ia.has(t.category)){let n=[];for(let a of t.steps)st(a,e,n);let s=t.startTime.getTime()-e.getTime();r.push({title:t.title,category:oa(t.category),timestamp:t.startTime.toISOString(),duration:t.duration,videoOffset:s>=0?s/1e3:null,status:t.error?"failed":"passed",error:t.error?.message??null,children:n});}else for(let n of t.steps)st(n,e,r);}function $r(t,e){let r=[];for(let n of t)st(n,e,r);return r}var ca=new Set(["localhost","127.0.0.1","0.0.0.0"]);function jr(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&ca.has(e.hostname)))throw core.createError(core.ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${e.protocol}//${e.hostname}`)}var ua=3e3;async function at(t){let e=new AbortController,r=setTimeout(()=>e.abort(),ua);try{return (await fetch(`${t}/health`,{method:"GET",signal:e.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function Wr(t){return new Promise(e=>setTimeout(e,t))}async function zr(t){try{let r=(await t.json()).error;if(r&&typeof r.message=="string"){let n=r.details;if(Array.isArray(n)&&n.length>0){let s=n.map(a=>`${a.field}: ${a.message}`).join(", ");return `${r.message} (${s})`}return r.message}}catch{}return `HTTP ${t.status}`}async function it(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:n.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 Wr(d);let l=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:n.signal});if(l.ok){let c=await l.json();return {accessToken:c.accessToken,refreshToken:c.refreshToken,expiresIn:c.expiresIn,orgId:c.orgId,orgName:c.orgName,userId:c.userId,userName:c.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return a.status===400?{code:"validation_error",message:await zr(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 zr(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(s);}}function ot(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 Vr(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:n.signal});if(a.status===429){let i=a.headers.get("Retry-After"),d=i?parseInt(i,10)*1e3:5e3;!isNaN(d)&&d>0&&(await Wr(d),a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:n.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(s);}}async function Gr(t,e,r,n,s,a){let o=new AbortController,i=setTimeout(()=>o.abort(),s);try{let d={gitId:r,displayName:n};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 c=await l.json();return {repoId:c.repoId,displayName:c.displayName}}catch{return null}finally{clearTimeout(i);}}var ma=5e3;function B(t,e){try{return child_process.execSync(t,{cwd:e,timeout:ma,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function Jr(t){let e=B("git rev-parse --abbrev-ref HEAD",t),r=B("git rev-parse --short HEAD",t),n=B("git log -1 --pretty=%s",t),s=B("git log -1 --format=%an",t)??B("git config user.name",t),a=ya(t),o=a?ie(a):null;return {branch:e,commitSha:r,commitMessage:n,commitAuthor:s,remoteUrl:o}}function ya(t){let e=B("git remote get-url origin",t);if(e)return e;let r=B("git remote",t);if(!r)return null;let n=r.split(`
2562
- `)[0]?.trim();return n?B(`git remote get-url ${n}`,t):null}function ie(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 Kr(t){let e=t.split("/").filter(Boolean);return e[e.length-1]??t}function lt(t){try{let e=fs.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 oe(t){let e=lt(t);return e||`local/${path.basename(t)}`}var va=new Set(["smoke","regression","nightly","ci"]);function ve(){let t=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(t&&va.has(t))return t}var xa=1048576,be=[1e3,3e3,9e3],we=3,ka=90*1048576,Ta=new Set(["e2e","mobile","unit"]);function ct(t){if(t&&t.length>0&&t.every(s=>s.testType==="api")){let s=new Map;for(let i of t){let d=i.apiProtocol??"rest";s.set(d,(s.get(d)??0)+1);}let a="rest",o=0;for(let[i,d]of s)d>o&&(o=d,a=i);return {testType:"api",apiProtocol:a,metadata:{testType:"api",primaryProtocol:a}}}let e=new Map;for(let s of t??[])Ta.has(s.testType)&&e.set(s.testType,(e.get(s.testType)??0)+1);let r=null,n=0;for(let[s,a]of e)a>n&&(n=a,r=s);return {testType:r??"e2e"}}function ut(t,e,r,n,s,a){let o=a?.cloudPlatform?a.cloudPlatform:n?.provider&&n.provider!=="unknown"?n.provider:"local",i=ve(),d=ct(s),l=d.testType==="api"?d:null,c=l&&s?s.map(g=>g.apiProtocol?g:{...g,apiProtocol:l.apiProtocol}):s;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},...c&&c.length>0?{tests:c}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...n?.provider?{ciProvider:n.provider}:{},...n?.runUrl?{ciRunUrl:n.runUrl}:{},...a?.cloudPlatform?{cloudPlatform:a.cloudPlatform}:{},...a?.cloudBuildId?{cloudBuildId:a.cloudBuildId}:{},...a?.cloudSessionId?{cloudSessionId:a.cloudSessionId}:{}}}function dt(t){return typeof t=="string"?Buffer.byteLength(t,"utf-8"):0}function pt(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:dt(e.responseBody),bytesOut:typeof e.bytesOut=="number"?e.bytesOut:dt(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 ft(t){return Array.isArray(t)?t.map(e=>{let r=e.responseStatusCode??e.statusCode??0,n=e.timestamp??null;return {method:e.method??"GET",url:e.url??"",status:r,statusCode:r,type:"xhr",size:dt(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:n,startedAt:n}}):[]}function gt(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 n=r.status==="failed"?"failed":"passed",s=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,a=r.kind??r.type??"assertion",o=n==="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:s??r.description??`${a} assertion`,status:n,detail:o}})}async function xe(t){return new Promise(e=>setTimeout(e,t))}function Ca(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}async function Zr(t,e,r){for(let n=0;n<we;n++)try{let s=await fetch(t,e);if(s.ok)return s;if(s.status===401&&r&&n===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(s.status===429&&n<we-1){let a=s.headers.get("Retry-After"),o=a?parseInt(a,10)*1e3:be[n];!isNaN(o)&&o>0?await xe(o):await xe(be[n]);continue}if(s.status>=500&&n<we-1){await xe(be[n]);continue}return s}catch{if(n<we-1){await xe(be[n]);continue}return null}return null}var Sa=util.promisify(zlib.gzip);function Yr(t,e){if(!Array.isArray(t.tests))return t;let r=t.tests.map(n=>{let{consoleLogs:s,networkRequests:a,apiCalls:o,...i}=n;return e?i:{...i,...o!==void 0?{apiCalls:o}:{}}});return {...t,tests:r}}var Ra=["consoleLogs","networkRequests","apiCalls","actions","navigations","protocolAssertions"];function Aa(t){if(!Array.isArray(t.tests))return t;let e=new Set(Ra),r=t.tests.map(n=>{let s={};for(let a in n)if(!e.has(a))if(a==="failure"&&n[a]&&typeof n[a]=="object"){let o=n[a];s.failure={message:o.message??null,line:o.line??null};}else s[a]=n[a];return s});return {...t,tests:r}}function _a(t){let e=new Set(["tests","timeline","unifiedTimeline","navigations"]),r={};for(let n in t)e.has(n)||(r[n]=t[n]);return r.tests=[],r}async function ht(t,e=ka){let r={"Content-Type":"application/json"},n=JSON.stringify(t),s=t,a=Array.isArray(s?.tests)?s.tests.length:0,o=i=>Buffer.byteLength(i,"utf-8")>e;if(a>0&&o(n)){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.
2563
- `),n=JSON.stringify(Yr(s,false)),o(n)&&(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.
2564
- `),n=JSON.stringify(Yr(s,true))),o(n)&&(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.
2565
- `),n=JSON.stringify(Aa(s))),o(n)&&(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.
2566
- `),n=JSON.stringify(_a(s)));}return Buffer.byteLength(n,"utf-8")>xa?(r["Content-Encoding"]="gzip",{body:await Sa(Buffer.from(n,"utf-8")),headers:r}):{body:n,headers:r}}async function Qr(t,e,r,n){let s=`${t}/runs`,{body:a,headers:o}=await ht(r);o.Authorization=`Bearer ${e}`;let i=await Zr(s,{method:"POST",headers:o,body:a},n);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:s,method:"POST"}}async function Xr(t,e,r){let n=`${t}/runs/init`;try{let s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(Ca(r))});return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function en(t,e,r,n){let s=`${t}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}).catch(()=>{});}async function tn(t,e,r,n){let s=`${t}/runs/${r}/finalize`;return (await Zr(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}))?.ok??false}function mt(t,e,r,n){let s=`${t}/runs/${r}/finalize`,a=new Date,o={finishedAt:a.toISOString(),duration:a.getTime()-new Date(n).getTime(),summary:{}};fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}).catch(()=>{});}var Pa="1.0.0",rn=10;function nn(t){return t instanceof Error?t.message:String(t)}function Na(t){return t>=400&&t<500&&t!==408&&t!==429}function le(t,e,r,n,s,a,o,i){try{fs.mkdirSync(t,{recursive:!0});let d=Date.now(),l=`${d}-${e}-${r}.json`,c=path.join(t,l),f={version:Pa,queuedAt:new Date(d).toISOString(),reason:n,retryCount:0,targetEndpoint:s,method:a,payload:o,headers:i},g=c+".tmp";fs.writeFileSync(g,JSON.stringify(f,null,2),"utf-8"),fs.renameSync(g,c);}catch(d){d.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
2615
+ `,process.stderr.write(i);}var oa=new Set(["pw:api","expect","test.step"]);function la(t){return t==="expect"?"assertion":t==="test.step"?"custom_step":"ui_action"}function at(t,e,r){if(oa.has(t.category)){let n=[];for(let a of t.steps)at(a,e,n);let s=t.startTime.getTime()-e.getTime();r.push({title:t.title,category:la(t.category),timestamp:t.startTime.toISOString(),duration:t.duration,videoOffset:s>=0?s/1e3:null,status:t.error?"failed":"passed",error:t.error?.message??null,children:n});}else for(let n of t.steps)at(n,e,r);}function jr(t,e){let r=[];for(let n of t)at(n,e,r);return r}var ua=new Set(["localhost","127.0.0.1","0.0.0.0"]);function Gr(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&ua.has(e.hostname)))throw core.createError(core.ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${e.protocol}//${e.hostname}`)}var pa=3e3;async function it(t){let e=new AbortController,r=setTimeout(()=>e.abort(),pa);try{return (await fetch(`${t}/health`,{method:"GET",signal:e.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function Vr(t){return new Promise(e=>setTimeout(e,t))}async function Wr(t){try{let r=(await t.json()).error;if(r&&typeof r.message=="string"){let n=r.details;if(Array.isArray(n)&&n.length>0){let s=n.map(a=>`${a.field}: ${a.message}`).join(", ");return `${r.message} (${s})`}return r.message}}catch{}return `HTTP ${t.status}`}async function ot(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:n.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 Vr(d);let l=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:n.signal});if(l.ok){let c=await l.json();return {accessToken:c.accessToken,refreshToken:c.refreshToken,expiresIn:c.expiresIn,orgId:c.orgId,orgName:c.orgName,userId:c.userId,userName:c.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return a.status===400?{code:"validation_error",message:await Wr(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 Wr(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(s);}}function lt(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 Kr(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:n.signal});if(a.status===429){let i=a.headers.get("Retry-After"),d=i?parseInt(i,10)*1e3:5e3;!isNaN(d)&&d>0&&(await Vr(d),a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:n.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(s);}}async function Jr(t,e,r,n,s,a){let o=new AbortController,i=setTimeout(()=>o.abort(),s);try{let d={gitId:r,displayName:n};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 c=await l.json();return {repoId:c.repoId,displayName:c.displayName}}catch{return null}finally{clearTimeout(i);}}var ya=5e3;function B(t,e){try{return child_process.execSync(t,{cwd:e,timeout:ya,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function Yr(t){let e=B("git rev-parse --abbrev-ref HEAD",t),r=B("git rev-parse --short HEAD",t),n=B("git log -1 --pretty=%s",t),s=B("git log -1 --format=%an",t)??B("git config user.name",t),a=va(t),o=a?ie(a):null;return {branch:e,commitSha:r,commitMessage:n,commitAuthor:s,remoteUrl:o}}function va(t){let e=B("git remote get-url origin",t);if(e)return e;let r=B("git remote",t);if(!r)return null;let n=r.split(`
2616
+ `)[0]?.trim();return n?B(`git remote get-url ${n}`,t):null}function ie(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 Zr(t){let e=t.split("/").filter(Boolean);return e[e.length-1]??t}function dt(t){try{let e=fs.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 oe(t){let e=dt(t);return e||`local/${path.basename(t)}`}var ba=new Set(["smoke","regression","nightly","ci"]);function ve(){let t=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(t&&ba.has(t))return t}var ka=1048576,be=[1e3,3e3,9e3],we=3,Ta=90*1048576,Ca=new Set(["e2e","mobile","unit"]);function ut(t){if(t&&t.length>0&&t.every(s=>s.testType==="api")){let s=new Map;for(let i of t){let d=i.apiProtocol??"rest";s.set(d,(s.get(d)??0)+1);}let a="rest",o=0;for(let[i,d]of s)d>o&&(o=d,a=i);return {testType:"api",apiProtocol:a,metadata:{testType:"api",primaryProtocol:a}}}let e=new Map;for(let s of t??[])Ca.has(s.testType)&&e.set(s.testType,(e.get(s.testType)??0)+1);let r=null,n=0;for(let[s,a]of e)a>n&&(n=a,r=s);return {testType:r??"e2e"}}function pt(t,e,r,n,s,a){let o=a?.cloudPlatform?a.cloudPlatform:n?.provider&&n.provider!=="unknown"?n.provider:"local",i=ve(),d=ut(s),l=d.testType==="api"?d:null,c=l&&s?s.map(g=>g.apiProtocol?g:{...g,apiProtocol:l.apiProtocol}):s;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},...c&&c.length>0?{tests:c}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...n?.provider?{ciProvider:n.provider}:{},...n?.runUrl?{ciRunUrl:n.runUrl}:{},...a?.cloudPlatform?{cloudPlatform:a.cloudPlatform}:{},...a?.cloudBuildId?{cloudBuildId:a.cloudBuildId}:{},...a?.cloudSessionId?{cloudSessionId:a.cloudSessionId}:{}}}function ct(t){return typeof t=="string"?Buffer.byteLength(t,"utf-8"):0}function ft(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:ct(e.responseBody),bytesOut:typeof e.bytesOut=="number"?e.bytesOut:ct(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 gt(t){return Array.isArray(t)?t.map(e=>{let r=e.responseStatusCode??e.statusCode??0,n=e.timestamp??null;return {method:e.method??"GET",url:e.url??"",status:r,statusCode:r,type:"xhr",size:ct(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:n,startedAt:n}}):[]}function ht(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 n=r.status==="failed"?"failed":"passed",s=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,a=r.kind??r.type??"assertion",o=n==="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:s??r.description??`${a} assertion`,status:n,detail:o}})}async function xe(t){return new Promise(e=>setTimeout(e,t))}function Sa(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}async function Xr(t,e,r){for(let n=0;n<we;n++)try{let s=await fetch(t,e);if(s.ok)return s;if(s.status===401&&r&&n===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(s.status===429&&n<we-1){let a=s.headers.get("Retry-After"),o=a?parseInt(a,10)*1e3:be[n];!isNaN(o)&&o>0?await xe(o):await xe(be[n]);continue}if(s.status>=500&&n<we-1){await xe(be[n]);continue}return s}catch{if(n<we-1){await xe(be[n]);continue}return null}return null}var Ra=util.promisify(zlib.gzip);function Qr(t,e){if(!Array.isArray(t.tests))return t;let r=t.tests.map(n=>{let{consoleLogs:s,networkRequests:a,apiCalls:o,...i}=n;return e?i:{...i,...o!==void 0?{apiCalls:o}:{}}});return {...t,tests:r}}var Aa=["consoleLogs","networkRequests","apiCalls","actions","navigations","protocolAssertions"];function _a(t){if(!Array.isArray(t.tests))return t;let e=new Set(Aa),r=t.tests.map(n=>{let s={};for(let a in n)if(!e.has(a))if(a==="failure"&&n[a]&&typeof n[a]=="object"){let o=n[a];s.failure={message:o.message??null,line:o.line??null};}else s[a]=n[a];return s});return {...t,tests:r}}function Ia(t){let e=new Set(["tests","timeline","unifiedTimeline","navigations"]),r={};for(let n in t)e.has(n)||(r[n]=t[n]);return r.tests=[],r}async function mt(t,e=Ta){let r={"Content-Type":"application/json"},n=JSON.stringify(t),s=t,a=Array.isArray(s?.tests)?s.tests.length:0,o=i=>Buffer.byteLength(i,"utf-8")>e;if(a>0&&o(n)){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.
2617
+ `),n=JSON.stringify(Qr(s,false)),o(n)&&(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.
2618
+ `),n=JSON.stringify(Qr(s,true))),o(n)&&(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.
2619
+ `),n=JSON.stringify(_a(s))),o(n)&&(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.
2620
+ `),n=JSON.stringify(Ia(s)));}return Buffer.byteLength(n,"utf-8")>ka?(r["Content-Encoding"]="gzip",{body:await Ra(Buffer.from(n,"utf-8")),headers:r}):{body:n,headers:r}}async function en(t,e,r,n){let s=`${t}/runs`,{body:a,headers:o}=await mt(r);o.Authorization=`Bearer ${e}`;let i=await Xr(s,{method:"POST",headers:o,body:a},n);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:s,method:"POST"}}async function tn(t,e,r){let n=`${t}/runs/init`;try{let s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(Sa(r))});return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function rn(t,e,r,n){let s=`${t}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}).catch(()=>{});}async function nn(t,e,r,n){let s=`${t}/runs/${r}/finalize`;return (await Xr(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}))?.ok??false}function yt(t,e,r,n){let s=`${t}/runs/${r}/finalize`,a=new Date,o={finishedAt:a.toISOString(),duration:a.getTime()-new Date(n).getTime(),summary:{}};fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}).catch(()=>{});}var Na="1.0.0",sn=10;function an(t){return t instanceof Error?t.message:String(t)}function Fa(t){return t>=400&&t<500&&t!==408&&t!==429}function le(t,e,r,n,s,a,o,i){try{fs.mkdirSync(t,{recursive:!0});let d=Date.now(),l=`${d}-${e}-${r}.json`,c=path.join(t,l),f={version:Na,queuedAt:new Date(d).toISOString(),reason:n,retryCount:0,targetEndpoint:s,method:a,payload:o,headers:i},g=c+".tmp";fs.writeFileSync(g,JSON.stringify(f,null,2),"utf-8"),fs.renameSync(g,c);}catch(d){d.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
2567
2621
  `):process.stderr.write(`\u26A0 TestRelic: Unable to queue upload data.
2568
- `);}}async function ln(t,e,r){let n;try{n=fs.readdirSync(t).filter(a=>a.endsWith(".json")&&!a.endsWith(".tmp")).sort();}catch{return}if(n.length===0)return;let s=[];for(let a=0;a<n.length;a+=rn)s.push(n.slice(a,a+rn));for(let a of s)for(let o of a){let i=path.join(t,o),d;try{if(!fs.statSync(i).isFile())continue;let c=JSON.parse(fs.readFileSync(i,"utf-8"));if(!core.isValidQueueEntry(c)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${o}
2569
- `),fs.unlinkSync(i);continue}d=c;}catch(l){process.stderr.write(`\u26A0 TestRelic: Skipping unreadable queue file ${o}: ${nn(l)}
2570
- `);try{fs.unlinkSync(i);}catch{}continue}try{let{body:l,headers:c}=await ht(d.payload),f={...d.headers,...c,Authorization:`Bearer ${r}`},g=await fetch(d.targetEndpoint,{method:d.method,headers:f,body:l});if(g.ok)fs.unlinkSync(i);else if(Na(g.status)){process.stderr.write(`\u26A0 TestRelic: Queue entry ${o} rejected (HTTP ${g.status}) \u2014 moving aside; it will not be retried.
2622
+ `);}}async function cn(t,e,r){let n;try{n=fs.readdirSync(t).filter(a=>a.endsWith(".json")&&!a.endsWith(".tmp")).sort();}catch{return}if(n.length===0)return;let s=[];for(let a=0;a<n.length;a+=sn)s.push(n.slice(a,a+sn));for(let a of s)for(let o of a){let i=path.join(t,o),d;try{if(!fs.statSync(i).isFile())continue;let c=JSON.parse(fs.readFileSync(i,"utf-8"));if(!core.isValidQueueEntry(c)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${o}
2623
+ `),fs.unlinkSync(i);continue}d=c;}catch(l){process.stderr.write(`\u26A0 TestRelic: Skipping unreadable queue file ${o}: ${an(l)}
2624
+ `);try{fs.unlinkSync(i);}catch{}continue}try{let{body:l,headers:c}=await mt(d.payload),f={...d.headers,...c,Authorization:`Bearer ${r}`},g=await fetch(d.targetEndpoint,{method:d.method,headers:f,body:l});if(g.ok)fs.unlinkSync(i);else if(Fa(g.status)){process.stderr.write(`\u26A0 TestRelic: Queue entry ${o} rejected (HTTP ${g.status}) \u2014 moving aside; it will not be retried.
2571
2625
  `);try{fs.renameSync(i,`${i}.failed`);}catch{try{fs.unlinkSync(i);}catch{}}}else {process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 server returned HTTP ${g.status} for ${o}; will retry later.
2572
- `);return}}catch(l){process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 ${nn(l)}; will retry later.
2573
- `);return}}}function dn(t,e){try{let r=fs.readdirSync(t).filter(s=>(s.endsWith(".json")||s.endsWith(".failed"))&&!s.endsWith(".tmp")),n=Date.now();for(let s of r){let a=path.join(t,s);try{let o=fs.readFileSync(a,"utf-8"),d=JSON.parse(o).queuedAt;if(typeof d=="string"){let l=new Date(d).getTime();n-l>e&&fs.unlinkSync(a);}}catch{try{fs.unlinkSync(a);}catch{}}}}catch{}}var Ua=3e5,$a=864e5,za=6e4,cn=3e4,bt="https://platform.testrelic.ai/settings/api-keys";function un(t){return new Promise(e=>{let r=setTimeout(e,t);typeof r?.unref=="function"&&r.unref();})}var ke=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.
2574
- `);return}try{if(jr(this.config.endpoint),this.gitMetadata=Jr(),!await at(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.
2575
- `);return}let r=await it(this.config.endpoint,this.config.apiKey,this.config.timeout);if(ot(r)){this.handleAuthError(r.code,r.statusCode);return}let n=r;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},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${n.orgName} / ${n.userName})
2576
- `),await this.resolveRepoId(),this.config.queueDirectory&&(dn(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)}
2577
- `);}}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()+Ua<e)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await Vr(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}).
2578
- `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,un(cn)]);}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.
2579
- \u2192 Manage keys: ${bt}
2626
+ `);return}}catch(l){process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 ${an(l)}; will retry later.
2627
+ `);return}}}function un(t,e){try{let r=fs.readdirSync(t).filter(s=>(s.endsWith(".json")||s.endsWith(".failed"))&&!s.endsWith(".tmp")),n=Date.now();for(let s of r){let a=path.join(t,s);try{let o=fs.readFileSync(a,"utf-8"),d=JSON.parse(o).queuedAt;if(typeof d=="string"){let l=new Date(d).getTime();n-l>e&&fs.unlinkSync(a);}}catch{try{fs.unlinkSync(a);}catch{}}}}catch{}}var $a=3e5,za=864e5,ja=6e4,pn=3e4,wt="https://platform.testrelic.ai/settings/api-keys";function fn(t){return new Promise(e=>{let r=setTimeout(e,t);typeof r?.unref=="function"&&r.unref();})}var ke=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.
2628
+ `);return}try{if(Gr(this.config.endpoint),this.gitMetadata=Yr(),!await it(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.
2629
+ `);return}let r=await ot(this.config.endpoint,this.config.apiKey,this.config.timeout);if(lt(r)){this.handleAuthError(r.code,r.statusCode);return}let n=r;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},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${n.orgName} / ${n.userName})
2630
+ `),await this.resolveRepoId(),this.config.queueDirectory&&(un(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)}
2631
+ `);}}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()+$a<e)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await Kr(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}).
2632
+ `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,fn(pn)]);}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.
2633
+ \u2192 Manage keys: ${wt}
2580
2634
  `);break;case "expired_key":this.setLocalMode("expired_api_key"),process.stderr.write(`\u26A0 TestRelic: API key has expired. Running in local mode.
2581
- \u2192 Generate a new key: ${bt}
2635
+ \u2192 Generate a new key: ${wt}
2582
2636
  `);break;case "validation_error":this.setLocalMode("validation_error"),process.stderr.write(`\u26A0 TestRelic: API key format invalid. Running in local mode.
2583
- \u2192 Manage keys: ${bt}
2637
+ \u2192 Manage keys: ${wt}
2584
2638
  `);break;case "rate_limited":this.setLocalMode("rate_limited"),process.stderr.write(`\u26A0 TestRelic: Rate limited during authentication. Running in local mode.
2585
2639
  `);break;case "timeout":this.setLocalMode("auth_timeout"),process.stderr.write(`\u26A0 TestRelic: Authentication timed out. Running in local mode.
2586
2640
  `);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
2587
- `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?ie(this.gitMetadata.remoteUrl):null,r=e?Kr(e):this.config.projectName??oe(process.cwd()),n=e??this.config.projectName??oe(process.cwd()),s=this.readRepoCache(n);if(s){this.repoId=s.repoId;return}try{let a=await Gr(this.config.endpoint,this.authState.accessToken,n,r,this.config.timeout,this.gitMetadata?.branch);a&&(this.repoId=a.repoId,this.writeRepoCache(n,a.repoId,a.displayName));}catch{}!e&&!this.config.projectName&&!lt(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
2588
- `);}readRepoCache(e){if(!this.config)return null;let r=path.join(this.config.queueDirectory,"..","cache","repo.json");try{if(!fs.existsSync(r))return null;let n=fs.readFileSync(r,"utf-8"),s=JSON.parse(n);if(s.gitId!==e||Date.now()-s.resolvedAt>$a)return null;let a=this.hashApiKey();return a&&s.apiKeyHash!==a?null:s}catch{return null}}writeRepoCache(e,r,n){if(!this.config)return;let s=path.join(this.config.queueDirectory,"..","cache"),a=path.join(s,"repo.json");try{fs.mkdirSync(s,{recursive:!0});let o={repoId:r,gitId:e,displayName:n,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=a+".tmp";fs.writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),fs.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,n=this.config.endpoint;this.flushPromise=Promise.race([ln(r,n,e),un(cn)]).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 at(e))return;if(this.config?.apiKey){let n=await it(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!ot(n)){let s=n;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},this.failureReason=null,process.stderr.write(`\u2713 TestRelic: Cloud connectivity restored.
2589
- `),this.startBackgroundFlush();}}}catch{}},za),typeof this.healthCheckTimer?.unref=="function"&&this.healthCheckTimer.unref();}};function pn(t,e,r,n){let s=[],a=[],o=null,i=0,d=null,l=0,c=null,f=0,g=t.filter(p=>p.name===core.ATTACHMENT_NAME&&p.body),u=false;if(g.length>0)for(let p of g)try{let m=JSON.parse(p.body.toString());if(core.isTestRelicFilePayload(m)){s=s.concat(m.navigations),a=a.concat(m.apiAssertions),m.networkRequestsFile&&(o=m.networkRequestsFile,i+=m.networkRequestsCount),m.consoleLogsFile&&(d=m.consoleLogsFile,l+=m.consoleLogsCount),m.apiCallsFile&&(c=m.apiCallsFile,f+=m.apiCallsCount),u=!0;continue}if(core.isTestRelicDataPayload(m)){s=s.concat(m.navigations),Array.isArray(m.apiAssertions)&&(a=a.concat(m.apiAssertions)),i+=m.networkRequests?.length??0,f+=m.apiCalls?.length??0;let y=m.consoleLogs;Array.isArray(y)&&(l+=y.length),u=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
2641
+ `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?ie(this.gitMetadata.remoteUrl):null,r=e?Zr(e):this.config.projectName??oe(process.cwd()),n=e??this.config.projectName??oe(process.cwd()),s=this.readRepoCache(n);if(s){this.repoId=s.repoId;return}try{let a=await Jr(this.config.endpoint,this.authState.accessToken,n,r,this.config.timeout,this.gitMetadata?.branch);a&&(this.repoId=a.repoId,this.writeRepoCache(n,a.repoId,a.displayName));}catch{}!e&&!this.config.projectName&&!dt(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
2642
+ `);}readRepoCache(e){if(!this.config)return null;let r=path.join(this.config.queueDirectory,"..","cache","repo.json");try{if(!fs.existsSync(r))return null;let n=fs.readFileSync(r,"utf-8"),s=JSON.parse(n);if(s.gitId!==e||Date.now()-s.resolvedAt>za)return null;let a=this.hashApiKey();return a&&s.apiKeyHash!==a?null:s}catch{return null}}writeRepoCache(e,r,n){if(!this.config)return;let s=path.join(this.config.queueDirectory,"..","cache"),a=path.join(s,"repo.json");try{fs.mkdirSync(s,{recursive:!0});let o={repoId:r,gitId:e,displayName:n,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=a+".tmp";fs.writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),fs.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,n=this.config.endpoint;this.flushPromise=Promise.race([cn(r,n,e),fn(pn)]).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 it(e))return;if(this.config?.apiKey){let n=await ot(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!lt(n)){let s=n;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},this.failureReason=null,process.stderr.write(`\u2713 TestRelic: Cloud connectivity restored.
2643
+ `),this.startBackgroundFlush();}}}catch{}},ja),typeof this.healthCheckTimer?.unref=="function"&&this.healthCheckTimer.unref();}};function gn(t,e,r,n){let s=[],a=[],o=null,i=0,d=null,l=0,c=null,f=0,g=t.filter(p=>p.name===core.ATTACHMENT_NAME&&p.body),u=false;if(g.length>0)for(let p of g)try{let m=JSON.parse(p.body.toString());if(core.isTestRelicFilePayload(m)){s=s.concat(m.navigations),a=a.concat(m.apiAssertions),m.networkRequestsFile&&(o=m.networkRequestsFile,i+=m.networkRequestsCount),m.consoleLogsFile&&(d=m.consoleLogsFile,l+=m.consoleLogsCount),m.apiCallsFile&&(c=m.apiCallsFile,f+=m.apiCallsCount),u=!0;continue}if(core.isTestRelicDataPayload(m)){s=s.concat(m.navigations),Array.isArray(m.apiAssertions)&&(a=a.concat(m.apiAssertions)),i+=m.networkRequests?.length??0,f+=m.apiCalls?.length??0;let y=m.consoleLogs;Array.isArray(y)&&(l+=y.length),u=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
2590
2644
  `);}return u||(s=e.filter(p=>p.type==="lambdatest-navigation"&&p.description).map(p=>{try{return JSON.parse(p.description)}catch{return null}}).filter(p=>p!==null)),s.length===0&&i===0&&f===0&&!n&&!u&&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.
2591
- `),{navigations:s,apiAssertions:a,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:d,consoleLogsCount:l,apiCallsFile:c,apiCallsCount:f}}function Te(t=process.env){let e=Ga(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 Ga(t){if(!t)return;let e=t.toLowerCase().trim();if(e==="browserstack"||e==="bs")return "browserstack";if(e==="lambdatest"||e==="lt")return "lambdatest"}var Qa=5,Ce=[1e3,3e3,9e3],G=3,Xa={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip"},wt=0,xt=[];async function ei(){wt>=Qa&&await new Promise(t=>xt.push(t)),wt++;}function ti(){wt--,xt.length>0&&xt.shift()();}async function Se(t){return new Promise(e=>setTimeout(e,t))}function ri(t){let e=t.substring(t.lastIndexOf(".")).toLowerCase();return Xa[e]??"application/octet-stream"}function ni(t){try{return fs.statSync(t).size}catch{return 0}}async function si(t,e,r,n,s){let a=`${t}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:path.basename(r.filePath),contentType:s,type:r.type,sizeBytes:n});for(let i=0;i<G;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<G-1){await Se(Ce[i]);continue}return null}catch{if(i<G-1){await Se(Ce[i]);continue}return null}return null}async function ai(t,e,r,n){for(let s=0;s<G;s++)try{let a=fs.createReadStream(e),o=stream.Readable.toWeb(a),i=await fetch(t,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(n)},body:o,duplex:"half"});if(i.ok)return !0;if(i.status>=500&&s<G-1){await Se(Ce[s]);continue}return !1}catch{if(s<G-1){await Se(Ce[s]);continue}return false}return false}async function ii(t,e,r){let n=`${t}/artifacts/confirm`;try{return (await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({artifactId:r})})).ok}catch{return false}}async function oi(t,e,r,n){let s=ni(r.filePath);if(s===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(s>n*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let a=ri(r.filePath);await ei();try{let o=await si(t,e,r,s,a);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await ai(o.uploadUrl,r.filePath,a,s))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let d=await ii(t,e,o.artifactId);return {success:d,storageKey:o.storageKey,artifactId:o.artifactId,error:d?null:"confirm_failed"}}finally{ti();}}async function fn(t,e,r,n){let s=new Map,a=r.map(async o=>{let i=await oi(t,e,o,n);s.set(o.filePath,i);});return await Promise.allSettled(a),s}function kt(t){let r=t.getGitMetadata()?.remoteUrl;return r?ie(r):t.getConfig()?.projectName??oe(process.cwd())}async function hn(t,e,r,n,s){if(!t.isCloudMode()||e!=="realtime"&&e!=="both"||!await t.ensureValidToken())return null;let o=t.getGitMetadata(),i=F(),d=Te(),l=ve();return (await Xr(t.getEndpoint(),t.getAccessToken(),{runId:r,repoGitId:kt(t),branch:o?.branch??null,commit:o?.commitSha??null,commitMessage:o?.commitMessage??null,commitAuthor:o?.commitAuthor??null,startedAt:n,totalTests:null,ciProvider:i?.provider??null,ciRunUrl:i?.runUrl??null,environment:s??d.cloudPlatform??null,cloudPlatform:d.cloudPlatform??null,cloudBuildId:d.cloudBuildId??null,cloudSessionId:d.cloudSessionId??null,...l?{runType:l}:{},testType:"e2e"}))?.runId??null}var li=true,di=50;async function ci(t,e,r,n){let s=new Map;if(!(e?.uploadArtifacts??li)||!await t.ensureValidToken())return s;let i=[],d=new Map;for(let u of n){if(u.artifacts.screenshot){let h=path.join(u.outputDir,u.artifacts.screenshot);i.push({filePath:h,runId:r,testId:u.testId,type:"screenshot"}),d.set(h,{testId:u.testId,field:"screenshot"});}if(u.artifacts.video){let h=path.join(u.outputDir,u.artifacts.video);i.push({filePath:h,runId:r,testId:u.testId,type:"video"}),d.set(h,{testId:u.testId,field:"video"});}}if(i.length===0)return s;let l=e?.artifactMaxSizeMb??di,c=await fn(t.getEndpoint(),t.getAccessToken(),i,l),f=new Map;for(let[u,h]of c){if(!h.success||!h.storageKey)continue;let p=d.get(u);if(!p)continue;let m=f.get(p.testId)??{};p.field==="screenshot"&&(m.screenshotKey=h.storageKey),p.field==="video"&&(m.videoKey=h.storageKey),f.set(p.testId,m);}for(let u of n){let h=f.get(u.testId);s.set(u.testId,{...u.artifacts,...h?.screenshotKey?{screenshotKey:h.screenshotKey}:{},...h?.videoKey?{videoKey:h.videoKey}:{}});}let g=Array.from(c.values()).filter(u=>u.success).length;return g>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${g} artifact(s) to cloud storage.
2592
- `),s}async function Tt(t,e,r,n,s,a,o,i,d,l,c){try{if(t.isCloudMode()&&s&&(r==="realtime"||r==="both")){let g=await t.ensureValidToken(),u=t.getGitMetadata(),h=ct(c),p={finishedAt:o,duration:i,summary:d,...u?.commitMessage?{commitMessage:u.commitMessage}:{},testType:h.testType,...h.testType==="api"?{apiProtocol:h.apiProtocol,metadata:h.metadata}:{}};if(g){if(!await tn(t.getEndpoint(),t.getAccessToken(),s,p)){let y=e?.queueDirectory??".testrelic/queue";le(y,n,"finalize","finalize_failed_after_retries",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",p,{"Content-Type":"application/json"});}}else {let m=e?.queueDirectory??".testrelic/queue";le(m,n,"finalize",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",p,{"Content-Type":"application/json"});}}let f=new Map;if(t.isCloudMode()&&l&&l.length>0&&(f=await ci(t,e,n,l)),t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await t.ensureValidToken()){let u=t.getGitMetadata(),h=F(),p=kt(t),m=ui(a,f),y=ut(m,p,u,h,c,Te()),w=await Qr(t.getEndpoint(),t.getAccessToken(),y,async()=>await t.ensureValidToken()?t.getAccessToken():null);if(!w.success){let v=w,k=e?.queueDirectory??".testrelic/queue";le(k,n,"batch",v.reason,v.targetEndpoint,v.method,v.payload,{"Content-Type":"application/json"});}}else {let u=e?.queueDirectory??".testrelic/queue",h=t.getGitMetadata(),p=F(),m=kt(t),y=ut(a,m,h,p,void 0,Te());le(u,n,"batch",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs`,"POST",y,{"Content-Type":"application/json"});}await t.dispose();}catch{try{await t.dispose();}catch{}}}function ui(t,e){if(e.size===0)return t;let r=t.timeline.map(n=>{let s=n.testId;if(!s)return n;let a=e.get(s);return a?{...n,...a.screenshotKey?{screenshotKey:a.screenshotKey}:{},...a.videoKey?{videoKey:a.videoKey}:{}}:n});return {...t,timeline:r}}function q(t){try{return fs.readFileSync(t,"utf-8").split(`
2593
- `).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function St(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 vi(t,e,r){let n=`${t}::${e}::${r}`;return crypto.createHash("sha256").update(n).digest("hex").substring(0,16)}function bi(t){return t.length<=3?"":t[t.length-2]}function wi(t){let e=t.findIndex(r=>r.status==="passed");return e>0?`passed on retry ${e}`:null}function xi(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 bn(t,e){for(let r of t)e[r.category]=(e[r.category]??0)+1,r.children.length>0&&bn(r.children,e);}function ki(t){if(t.length===0)return null;let e=[...t].sort((n,s)=>n-s),r=e.reduce((n,s)=>n+s,0);return {avg:Math.round(r/e.length),min:e[0],max:e[e.length-1],p50:z(e,50),p95:z(e,95),p99:z(e,99)}}var wn=2e5,Re=1e5;function vn(t,e,r,n,s,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:n.length,navUrls:[],networkRequests:s,consoleLogs:a,actionSteps:o?.length??0,actionCategories:{}};if(e){let l=new Set;for(let c of e){let f=typeof c.method=="string"?c.method:"OTHER";i.methodCounts[f]=(i.methodCounts[f]??0)+1;let g=typeof c.url=="string"?c.url:null;g&&l.size<Re&&l.add(rt(g));let u=typeof c.responseStatusCode=="number"?c.responseStatusCode:typeof c.statusCode=="number"?c.statusCode:null,h=u!==null&&Number.isFinite(u)?u:null;i.statusRanges[xi(h)]++;let p=typeof c.responseTimeMs=="number"?c.responseTimeMs:typeof c.durationMs=="number"?c.durationMs:null;p!==null&&Number.isFinite(p)&&i.responseTimes.length<wn&&i.responseTimes.push(p);}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 n)l.url&&d.size<Re&&d.add(l.url);return i.navUrls=Array.from(d),o&&bn(o,i.actionCategories),i}function Ti(){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 Ci(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 Si(){let t=os$1.platform();return t==="win32"?"Windows":t==="darwin"?"macOS":"Linux"}function Ri(t){let e=t.parent?.project?.()?.use;if(!e)return;let{browserName:r,channel:n}=e;if(n){let a=n.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":n}if(r){let a=r.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":r}let s=e.defaultBrowserType;if(s){let a=s.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":s}}function Ai(t,e,r){let n=r.parent?.project?.(),s="unknown";n!==void 0&&(n.use.isMobile===true?s="mobile":s="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 s}var _i="__testrelic_api_config";function Ii(t){return JSON.stringify(t,(e,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var Ae=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=Yt(e),this.apiConfig=Kt(e);}upsertAggContribution(e,r){let n=this.streamingTestAgg.get(e);(!n||r.retryIndex>n.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 n=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${n} tests)
2594
- `),this.activeReportMode==="streaming"){let o=path.dirname(this.config.outputPath);this.streamingWriter=new te(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&&mt(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=_r(path.join(o,"artifacts"));try{Nr(path.join(o,"artifacts"));}catch{}}let s=F();this.detectedOs=Si(),this.detectedSource=Ci(s);let a=await $(async()=>(this.cloudClient=new ke(this.config.cloud),await this.cloudClient.initialize(),hn(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource)),Dr,"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&&mt(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:_i,description:Ii(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let n=r,s=e.outcome(),a;s==="flaky"?a="flaky":s==="skipped"?a="skipped":a=St(n.status);let o=n.startTime.toISOString(),i=new Date(n.startTime.getTime()+n.duration).toISOString(),d=e.tags?[...e.tags]:e.annotations.filter(A=>A.type==="tag").map(A=>A.description??""),l=pn(n.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 c=null;if(a==="failed"||a==="flaky"){let R=(a==="flaky"?e.results.find(H=>H.status!=="passed")?.errors??[]:n.errors)[0];if(R){let H=Qt(this.config.redactPatterns),Q=R.location?.line??null,X=null;this.config.includeCodeSnippets&&Q!==null&&R.location?.file&&(X=Zt(R.location.file,Q,this.config.codeContextLines),X&&(X=H(X))),c={message:H(R.message??"Unknown error"),line:Q,code:X,stack:this.config.includeStackTrace&&R.stack?H(R.stack):null};}}let f=e.titlePath().filter(Boolean),g=path.relative(this.rootDir||".",e.location.file),u=bi(f),h=f.join(" > "),p=g,m=vi(p,u,h),y=Ai(d,p,e),w=y!=="mobile"&&l.apiCallsCount>0?"api":y,v=s==="flaky",k=wi(e.results),C=St(e.expectedStatus),b=St(n.status),T=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments){let A=path.dirname(this.config.outputPath),R=f[f.length-1]??e.title;T=Ir(n.attachments,R,n.retry,A,this.runTimestamp||void 0,m);}let S=this.config.includeActionSteps&&n.steps?$r(n.steps,n.startTime):null,M=Ri(e),E={titlePath:f,title:h,status:a,duration:n.duration,startedAt:o,completedAt:i,retryCount:e.results.length-1,retry:n.retry,tags:d,failure:c,specFile:g,navigations:l.navigations,testId:m,filePath:p,suiteName:u,testType:w,isFlaky:v,retryStatus:k,expectedStatus:C,actualStatus:b,artifacts:T,apiAssertions:l.apiAssertions,actions:S,networkRequestsFile:l.networkRequestsFile,networkRequestsCount:l.networkRequestsCount,consoleLogsFile:l.consoleLogsFile,consoleLogsCount:l.consoleLogsCount,apiCallsFile:l.apiCallsFile,apiCallsCount:l.apiCallsCount,browser:M,os:this.detectedOs||void 0,source:this.detectedSource||void 0},Pt=l.consoleLogsFile&&l.consoleLogsCount>0?q(l.consoleLogsFile):void 0,Ee=l.networkRequestsFile&&l.networkRequestsCount>0?q(l.networkRequestsFile):void 0,Z=l.apiCallsFile&&l.apiCallsCount>0?q(l.apiCallsFile):void 0,Nt=Z?pt(Z):void 0,Ft=!Ee&&Z?ft(Z):void 0,Dt=l.apiAssertions&&l.apiAssertions.length>0?gt(l.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:m,title:h,status:a,duration:n.duration,suiteName:u,filePath:p,testType:w,isFlaky:v,startedAt:o,completedAt:i,tags:d,failure:c,retry:n.retry,retryCount:e.results.length-1,retryStatus:k,browser:M,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...S&&S.length>0?{actions:S}:{},...l.navigations&&l.navigations.length>0?{navigations:l.navigations}:{},...Pt?{consoleLogs:Pt}:{},...Ee?{networkRequests:Ee}:Ft?{networkRequests:Ft}:{},...Nt?{apiCalls:Nt}:{},...Dt?{protocolAssertions:Dt}:{}});try{let A=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(A==="realtime"||A==="both")){let R=this.cloudClient.getAccessToken();R&&en(this.cloudClient.getEndpoint(),R,this.cloudRunId,this.buildCloudTestPayload(E));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let A=Pe(p,f,e.id??"",n.retry),R=n.retry===e.results.length-1,H={id:A,navigations:l.navigations,apiAssertions:l.apiAssertions,actions:S??[],artifacts:T,failureDiagnostic:c,hasNetworkFile:l.networkRequestsFile!==null,networkRequestsCount:l.networkRequestsCount,hasConsoleFile:l.consoleLogsFile!==null,consoleLogsCount:l.consoleLogsCount,hasApiCallsFile:l.apiCallsFile!==null,apiCallsCount:l.apiCallsCount,startedAt:o};this.streamingWriter.writeTestDetail(A,H,{networkRequestsFile:l.networkRequestsFile,consoleLogsFile:l.consoleLogsFile,apiCallsFile:l.apiCallsFile});let Q={id:A,title:f[f.length-1]??e.title,titlePath:f,filePath:p,status:a,duration:n.duration,project:f[1]??"",retryIndex:n.retry,tags:d,hasNetworkData:l.networkRequestsCount>0,hasConsoleData:l.consoleLogsCount>0,hasArtifacts:T!==null,hasActionSteps:(S?.length??0)>0,errorMessage:c?.message?.split(`
2595
- `)[0]??null,networkCount:l.networkRequestsCount,consoleCount:l.consoleLogsCount,actionCount:S?.length??0,isRetry:!R};if(this.testIndex.push(Q),R)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(`${p}::${f.join(" > ")}`,vn(n.retry,Z,l.apiAssertions,l.navigations,l.networkRequestsCount,l.consoleLogsCount,S)),T&&this.pendingArtifactEntries.push({testId:m,artifacts:T,outputDir:path.dirname(this.config.outputPath)}),E.actions=null,E.apiAssertions=null,E.navigations=[],E.artifacts=null,E.failure=null,E.networkRequestsFile=null,E.consoleLogsFile=null,E.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(E),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(e){try{let r=new Date().toISOString(),n=new Date(this.startedAt).getTime(),a=new Date(r).getTime()-n,o=this.activeReportMode==="streaming"?this.testIndex.some(d=>d.status!=="skipped"):this.collectedTests.some(d=>d.status!=="skipped");!this.fixtureDataReceived&&o&&process.stderr.write(`
2645
+ `),{navigations:s,apiAssertions:a,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:d,consoleLogsCount:l,apiCallsFile:c,apiCallsCount:f}}function Te(t=process.env){let e=Ka(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 Ka(t){if(!t)return;let e=t.toLowerCase().trim();if(e==="browserstack"||e==="bs")return "browserstack";if(e==="lambdatest"||e==="lt")return "lambdatest"}var Xa=5,Ce=[1e3,3e3,9e3],V=3,ei={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip"},xt=0,kt=[];async function ti(){xt>=Xa&&await new Promise(t=>kt.push(t)),xt++;}function ri(){xt--,kt.length>0&&kt.shift()();}async function Se(t){return new Promise(e=>setTimeout(e,t))}function ni(t){let e=t.substring(t.lastIndexOf(".")).toLowerCase();return ei[e]??"application/octet-stream"}function si(t){try{return fs.statSync(t).size}catch{return 0}}async function ai(t,e,r,n,s){let a=`${t}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:path.basename(r.filePath),contentType:s,type:r.type,sizeBytes:n});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 Se(Ce[i]);continue}return null}catch{if(i<V-1){await Se(Ce[i]);continue}return null}return null}async function ii(t,e,r,n){for(let s=0;s<V;s++)try{let a=fs.createReadStream(e),o=stream.Readable.toWeb(a),i=await fetch(t,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(n)},body:o,duplex:"half"});if(i.ok)return !0;if(i.status>=500&&s<V-1){await Se(Ce[s]);continue}return !1}catch{if(s<V-1){await Se(Ce[s]);continue}return false}return false}async function oi(t,e,r){let n=`${t}/artifacts/confirm`;try{return (await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({artifactId:r})})).ok}catch{return false}}async function li(t,e,r,n){let s=si(r.filePath);if(s===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(s>n*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let a=ni(r.filePath);await ti();try{let o=await ai(t,e,r,s,a);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await ii(o.uploadUrl,r.filePath,a,s))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let d=await oi(t,e,o.artifactId);return {success:d,storageKey:o.storageKey,artifactId:o.artifactId,error:d?null:"confirm_failed"}}finally{ri();}}async function hn(t,e,r,n){let s=new Map,a=r.map(async o=>{let i=await li(t,e,o,n);s.set(o.filePath,i);});return await Promise.allSettled(a),s}function Tt(t){let r=t.getGitMetadata()?.remoteUrl;return r?ie(r):t.getConfig()?.projectName??oe(process.cwd())}async function yn(t,e,r,n,s){if(!t.isCloudMode()||e!=="realtime"&&e!=="both"||!await t.ensureValidToken())return null;let o=t.getGitMetadata(),i=F(),d=Te(),l=ve();return (await tn(t.getEndpoint(),t.getAccessToken(),{runId:r,repoGitId:Tt(t),branch:o?.branch??null,commit:o?.commitSha??null,commitMessage:o?.commitMessage??null,commitAuthor:o?.commitAuthor??null,startedAt:n,totalTests:null,ciProvider:i?.provider??null,ciRunUrl:i?.runUrl??null,environment:s??d.cloudPlatform??null,cloudPlatform:d.cloudPlatform??null,cloudBuildId:d.cloudBuildId??null,cloudSessionId:d.cloudSessionId??null,...l?{runType:l}:{},testType:"e2e"}))?.runId??null}var di=true,ci=50;async function ui(t,e,r,n){let s=new Map;if(!(e?.uploadArtifacts??di)||!await t.ensureValidToken())return s;let i=[],d=new Map;for(let u of n){if(u.artifacts.screenshot){let h=path.join(u.outputDir,u.artifacts.screenshot);i.push({filePath:h,runId:r,testId:u.testId,type:"screenshot"}),d.set(h,{testId:u.testId,field:"screenshot"});}if(u.artifacts.video){let h=path.join(u.outputDir,u.artifacts.video);i.push({filePath:h,runId:r,testId:u.testId,type:"video"}),d.set(h,{testId:u.testId,field:"video"});}}if(i.length===0)return s;let l=e?.artifactMaxSizeMb??ci,c=await hn(t.getEndpoint(),t.getAccessToken(),i,l),f=new Map;for(let[u,h]of c){if(!h.success||!h.storageKey)continue;let p=d.get(u);if(!p)continue;let m=f.get(p.testId)??{};p.field==="screenshot"&&(m.screenshotKey=h.storageKey),p.field==="video"&&(m.videoKey=h.storageKey),f.set(p.testId,m);}for(let u of n){let h=f.get(u.testId);s.set(u.testId,{...u.artifacts,...h?.screenshotKey?{screenshotKey:h.screenshotKey}:{},...h?.videoKey?{videoKey:h.videoKey}:{}});}let g=Array.from(c.values()).filter(u=>u.success).length;return g>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${g} artifact(s) to cloud storage.
2646
+ `),s}async function Ct(t,e,r,n,s,a,o,i,d,l,c){try{if(t.isCloudMode()&&s&&(r==="realtime"||r==="both")){let g=await t.ensureValidToken(),u=t.getGitMetadata(),h=ut(c),p={finishedAt:o,duration:i,summary:d,...u?.commitMessage?{commitMessage:u.commitMessage}:{},testType:h.testType,...h.testType==="api"?{apiProtocol:h.apiProtocol,metadata:h.metadata}:{}};if(g){if(!await nn(t.getEndpoint(),t.getAccessToken(),s,p)){let y=e?.queueDirectory??".testrelic/queue";le(y,n,"finalize","finalize_failed_after_retries",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",p,{"Content-Type":"application/json"});}}else {let m=e?.queueDirectory??".testrelic/queue";le(m,n,"finalize",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",p,{"Content-Type":"application/json"});}}let f=new Map;if(t.isCloudMode()&&l&&l.length>0&&(f=await ui(t,e,n,l)),t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await t.ensureValidToken()){let u=t.getGitMetadata(),h=F(),p=Tt(t),m=pi(a,f),y=pt(m,p,u,h,c,Te()),w=await en(t.getEndpoint(),t.getAccessToken(),y,async()=>await t.ensureValidToken()?t.getAccessToken():null);if(!w.success){let v=w,k=e?.queueDirectory??".testrelic/queue";le(k,n,"batch",v.reason,v.targetEndpoint,v.method,v.payload,{"Content-Type":"application/json"});}}else {let u=e?.queueDirectory??".testrelic/queue",h=t.getGitMetadata(),p=F(),m=Tt(t),y=pt(a,m,h,p,void 0,Te());le(u,n,"batch",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs`,"POST",y,{"Content-Type":"application/json"});}await t.dispose();}catch{try{await t.dispose();}catch{}}}function pi(t,e){if(e.size===0)return t;let r=t.timeline.map(n=>{let s=n.testId;if(!s)return n;let a=e.get(s);return a?{...n,...a.screenshotKey?{screenshotKey:a.screenshotKey}:{},...a.videoKey?{videoKey:a.videoKey}:{}}:n});return {...t,timeline:r}}function q(t){try{return fs.readFileSync(t,"utf-8").split(`
2647
+ `).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function Rt(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 bi(t,e,r){let n=`${t}::${e}::${r}`;return crypto.createHash("sha256").update(n).digest("hex").substring(0,16)}function wi(t){return t.length<=3?"":t[t.length-2]}function xi(t){let e=t.findIndex(r=>r.status==="passed");return e>0?`passed on retry ${e}`:null}function ki(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 xn(t,e){for(let r of t)e[r.category]=(e[r.category]??0)+1,r.children.length>0&&xn(r.children,e);}function Ti(t){if(t.length===0)return null;let e=[...t].sort((n,s)=>n-s),r=e.reduce((n,s)=>n+s,0);return {avg:Math.round(r/e.length),min:e[0],max:e[e.length-1],p50:z(e,50),p95:z(e,95),p99:z(e,99)}}var kn=2e5,Re=1e5;function wn(t,e,r,n,s,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:n.length,navUrls:[],networkRequests:s,consoleLogs:a,actionSteps:o?.length??0,actionCategories:{}};if(e){let l=new Set;for(let c of e){let f=typeof c.method=="string"?c.method:"OTHER";i.methodCounts[f]=(i.methodCounts[f]??0)+1;let g=typeof c.url=="string"?c.url:null;g&&l.size<Re&&l.add(nt(g));let u=typeof c.responseStatusCode=="number"?c.responseStatusCode:typeof c.statusCode=="number"?c.statusCode:null,h=u!==null&&Number.isFinite(u)?u:null;i.statusRanges[ki(h)]++;let p=typeof c.responseTimeMs=="number"?c.responseTimeMs:typeof c.durationMs=="number"?c.durationMs:null;p!==null&&Number.isFinite(p)&&i.responseTimes.length<kn&&i.responseTimes.push(p);}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 n)l.url&&d.size<Re&&d.add(l.url);return i.navUrls=Array.from(d),o&&xn(o,i.actionCategories),i}function Ci(){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 Si(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 Ri(){let t=os$1.platform();return t==="win32"?"Windows":t==="darwin"?"macOS":"Linux"}function Ai(t){let e=t.parent?.project?.()?.use;if(!e)return;let{browserName:r,channel:n}=e;if(n){let a=n.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":n}if(r){let a=r.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":r}let s=e.defaultBrowserType;if(s){let a=s.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":s}}function _i(t,e,r){let n=r.parent?.project?.(),s="unknown";n!==void 0&&(n.use.isMobile===true?s="mobile":s="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 s}var Ii="__testrelic_api_config";function Li(t){return JSON.stringify(t,(e,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var Ae=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=Qt(e),this.apiConfig=Zt(e);}upsertAggContribution(e,r){let n=this.streamingTestAgg.get(e);(!n||r.retryIndex>n.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 n=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${n} tests)
2648
+ `),this.activeReportMode==="streaming"){let o=path.dirname(this.config.outputPath);this.streamingWriter=new te(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&&yt(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=Lr(path.join(o,"artifacts"));try{Dr(path.join(o,"artifacts"));}catch{}}let s=F();this.detectedOs=Ri(),this.detectedSource=Si(s);let a=await $(async()=>(this.cloudClient=new ke(this.config.cloud),await this.cloudClient.initialize(),yn(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource)),Or,"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&&yt(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:Ii,description:Li(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let n=r,s=e.outcome(),a;s==="flaky"?a="flaky":s==="skipped"?a="skipped":a=Rt(n.status);let o=n.startTime.toISOString(),i=new Date(n.startTime.getTime()+n.duration).toISOString(),d=e.tags?[...e.tags]:e.annotations.filter(A=>A.type==="tag").map(A=>A.description??""),l=gn(n.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 c=null;if(a==="failed"||a==="flaky"){let R=(a==="flaky"?e.results.find(H=>H.status!=="passed")?.errors??[]:n.errors)[0];if(R){let H=er(this.config.redactPatterns),Q=R.location?.line??null,X=null;this.config.includeCodeSnippets&&Q!==null&&R.location?.file&&(X=Xt(R.location.file,Q,this.config.codeContextLines),X&&(X=H(X))),c={message:H(R.message??"Unknown error"),line:Q,code:X,stack:this.config.includeStackTrace&&R.stack?H(R.stack):null};}}let f=e.titlePath().filter(Boolean),g=path.relative(this.rootDir||".",e.location.file),u=wi(f),h=f.join(" > "),p=g,m=bi(p,u,h),y=_i(d,p,e),w=y!=="mobile"&&l.apiCallsCount>0?"api":y,v=s==="flaky",k=xi(e.results),C=Rt(e.expectedStatus),b=Rt(n.status),T=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments){let A=path.dirname(this.config.outputPath),R=f[f.length-1]??e.title;T=Mr(n.attachments,R,n.retry,A,this.runTimestamp||void 0,m);}let S=this.config.includeActionSteps&&n.steps?jr(n.steps,n.startTime):null,M=Ai(e),P={titlePath:f,title:h,status:a,duration:n.duration,startedAt:o,completedAt:i,retryCount:e.results.length-1,retry:n.retry,tags:d,failure:c,specFile:g,navigations:l.navigations,testId:m,filePath:p,suiteName:u,testType:w,isFlaky:v,retryStatus:k,expectedStatus:C,actualStatus:b,artifacts:T,apiAssertions:l.apiAssertions,actions:S,networkRequestsFile:l.networkRequestsFile,networkRequestsCount:l.networkRequestsCount,consoleLogsFile:l.consoleLogsFile,consoleLogsCount:l.consoleLogsCount,apiCallsFile:l.apiCallsFile,apiCallsCount:l.apiCallsCount,browser:M,os:this.detectedOs||void 0,source:this.detectedSource||void 0},Nt=l.consoleLogsFile&&l.consoleLogsCount>0?q(l.consoleLogsFile):void 0,Pe=l.networkRequestsFile&&l.networkRequestsCount>0?q(l.networkRequestsFile):void 0,Z=l.apiCallsFile&&l.apiCallsCount>0?q(l.apiCallsFile):void 0,Ft=Z?ft(Z):void 0,Dt=!Pe&&Z?gt(Z):void 0,Bt=l.apiAssertions&&l.apiAssertions.length>0?ht(l.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:m,title:h,status:a,duration:n.duration,suiteName:u,filePath:p,testType:w,isFlaky:v,startedAt:o,completedAt:i,tags:d,failure:c,retry:n.retry,retryCount:e.results.length-1,retryStatus:k,browser:M,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...S&&S.length>0?{actions:S}:{},...l.navigations&&l.navigations.length>0?{navigations:l.navigations}:{},...Nt?{consoleLogs:Nt}:{},...Pe?{networkRequests:Pe}:Dt?{networkRequests:Dt}:{},...Ft?{apiCalls:Ft}:{},...Bt?{protocolAssertions:Bt}:{}});try{let A=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(A==="realtime"||A==="both")){let R=this.cloudClient.getAccessToken();R&&rn(this.cloudClient.getEndpoint(),R,this.cloudRunId,this.buildCloudTestPayload(P));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let A=Ee(p,f,e.id??"",n.retry),R=n.retry===e.results.length-1,H={id:A,navigations:l.navigations,apiAssertions:l.apiAssertions,actions:S??[],artifacts:T,failureDiagnostic:c,hasNetworkFile:l.networkRequestsFile!==null,networkRequestsCount:l.networkRequestsCount,hasConsoleFile:l.consoleLogsFile!==null,consoleLogsCount:l.consoleLogsCount,hasApiCallsFile:l.apiCallsFile!==null,apiCallsCount:l.apiCallsCount,startedAt:o};this.streamingWriter.writeTestDetail(A,H,{networkRequestsFile:l.networkRequestsFile,consoleLogsFile:l.consoleLogsFile,apiCallsFile:l.apiCallsFile});let Q={id:A,title:f[f.length-1]??e.title,titlePath:f,filePath:p,status:a,duration:n.duration,project:f[1]??"",retryIndex:n.retry,tags:d,hasNetworkData:l.networkRequestsCount>0,hasConsoleData:l.consoleLogsCount>0,hasArtifacts:T!==null,hasActionSteps:(S?.length??0)>0,errorMessage:c?.message?.split(`
2649
+ `)[0]??null,networkCount:l.networkRequestsCount,consoleCount:l.consoleLogsCount,actionCount:S?.length??0,isRetry:!R,retryGroupKey:Ne(p,f,e.id??"")};if(this.testIndex.push(Q),R)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(`${p}::${f.join(" > ")}`,wn(n.retry,Z,l.apiAssertions,l.navigations,l.networkRequestsCount,l.consoleLogsCount,S)),T&&this.pendingArtifactEntries.push({testId:m,artifacts:T,outputDir:path.dirname(this.config.outputPath)}),P.actions=null,P.apiAssertions=null,P.navigations=[],P.artifacts=null,P.failure=null,P.networkRequestsFile=null,P.consoleLogsFile=null,P.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(P),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(e){try{let r=new Date().toISOString(),n=new Date(this.startedAt).getTime(),a=new Date(r).getTime()-n,o=this.activeReportMode==="streaming"?this.testIndex.some(d=>d.status!=="skipped"):this.collectedTests.some(d=>d.status!=="skipped");!this.fixtureDataReceived&&o&&process.stderr.write(`
2596
2650
  \u26A0 TestRelic: No fixture data received from any test.
2597
2651
  To enable network logs, video sync, and Test Navigation tracking, import the TestRelic fixture:
2598
2652
  import { test, expect } from '@testrelic/playwright-analytics/fixture';
@@ -2601,17 +2655,17 @@ ${s}
2601
2655
 
2602
2656
  `),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).
2603
2657
  `):process.stderr.write(`[testrelic] Test Navigation capture is disabled (captureNavigation: false). Remove the option or set it to true to capture the navigation graph.
2604
- `),await $(()=>Ar(),tt,"Artifact flush");let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let d=path.dirname(this.config.outputPath);i=Mr(d,this.runTimestamp);let l=path.join(d,"artifact-manifest.json"),c=JSON.stringify(i),f=l+".tmp";fs.writeFileSync(f,c,"utf-8"),fs.renameSync(f,l);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await $(()=>this.finalizeStreamingReport(r,a,e,i),et,"Report finalization");else {let d=this.buildTimeline(),l=new Map;for(let u of this.collectedTests){let h=l.get(u.testId);(!h||u.retry>h.retry)&&l.set(u.testId,u);}let c=Array.from(l.values()),f=Ur(c,d.length),g={schemaVersion:de,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:a,summary:f,ci:F(),metadata:this.config.metadata,timeline:d,shardRunIds:null};if(this.writeReport(g),await $(()=>Ye(g,this.config,i),tt,"HTML report write"),nt(f,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient){let u=this.collectArtifactEntries(),h=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await $(()=>Tt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,g,r,a,f,u,h),et,"Cloud upload");}}}catch{}finally{await this.disposeCloudClient();}}async disposeCloudClient(){let e=this.cloudClient;e&&(this.cloudClient=null,await $(()=>e.dispose(),Br,"Cloud client shutdown"));}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let e=path.dirname(this.config.outputPath),r=[];for(let n of this.collectedTests)n.artifacts&&r.push({testId:n.testId,artifacts:n.artifacts,outputDir:e});return r}async finalizeStreamingReport(e,r,n,s){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 p of this.testIndex){let m=`${p.filePath}::${p.titlePath.join(" > ")}`,y=a.get(m);(y===void 0||p.retryIndex>y)&&a.set(m,p.retryIndex);}let i=0;for(let p of this.testIndex){let m=`${p.filePath}::${p.titlePath.join(" > ")}`,y=a.get(m);if(p.isRetry=p.retryIndex<y,p.isRetry)continue;switch(i++,this.summaryCounters.total++,p.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(p.filePath);switch(w||(w={filePath:p.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},o.set(p.filePath,w)),w.total++,p.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=Ti();for(let p of this.streamingTestAgg.values()){l.volApiCalls+=p.apiCalls,l.volAssertions+=p.assertions,l.volNavigations+=p.navigations,l.volNetworkRequests+=p.networkRequests,l.volConsoleLogs+=p.consoleLogs,l.volActionSteps+=p.actionSteps;for(let m in p.methodCounts)l.methodCounts[m]=(l.methodCounts[m]??0)+p.methodCounts[m];l.statusRanges["2xx"]+=p.statusRanges["2xx"],l.statusRanges["3xx"]+=p.statusRanges["3xx"],l.statusRanges["4xx"]+=p.statusRanges["4xx"],l.statusRanges["5xx"]+=p.statusRanges["5xx"],l.statusRanges.error+=p.statusRanges.error,l.passedAssertions+=p.passedAssertions,l.failedAssertions+=p.failedAssertions;for(let m in p.actionCategories)l.actionCategoryCounts[m]=(l.actionCategoryCounts[m]??0)+p.actionCategories[m];for(let m of p.apiUrls){if(l.apiUrlSet.size>=Re)break;l.apiUrlSet.add(m);}for(let m of p.navUrls){if(l.navUrlSet.size>=Re)break;l.navUrlSet.add(m);}for(let m of p.responseTimes){if(l.responseTimes.length>=wn)break;l.responseTimes.push(m);}}this.summaryCounters.totalApiCalls=l.volApiCalls,this.summaryCounters.totalAssertions=l.volAssertions,this.summaryCounters.totalNavigations=l.volNavigations,this.summaryCounters.totalNetworkRequests=l.volNetworkRequests,this.summaryCounters.totalConsoleLogs=l.volConsoleLogs,this.summaryCounters.totalActionSteps=l.volActionSteps,this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let c={reporterTotal:this.summaryCounters.total,indexTotal:i,playwrightStatus:n.status,isValid:this.summaryCounters.total===i};c.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${c.reporterTotal}, index: ${c.indexTotal}
2605
- `);let f={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:ki(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}},g={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:e,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:d,enrichedSummary:f,validation:c,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(g);let u={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(u),await Ye(this.buildStreamingReport(g,f,e,r),this.config,s),nt(f,this.config.outputPath,this.config.htmlReportPath,this.config.quiet);let h=this.streamingWriter.getReportDir();if(process.stderr.write(`[testrelic] Streaming report written to ${h}
2658
+ `),await $(()=>Ir(),rt,"Artifact flush");let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let d=path.dirname(this.config.outputPath);i=Er(d,this.runTimestamp);let l=path.join(d,"artifact-manifest.json"),c=JSON.stringify(i),f=l+".tmp";fs.writeFileSync(f,c,"utf-8"),fs.renameSync(f,l);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await $(()=>this.finalizeStreamingReport(r,a,e,i),tt,"Report finalization");else {let d=this.buildTimeline(),l=new Map;for(let u of this.collectedTests){let h=l.get(u.testId);(!h||u.retry>h.retry)&&l.set(u.testId,u);}let c=Array.from(l.values()),f=zr(c,d.length),g={schemaVersion:de,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:a,summary:f,ci:F(),metadata:this.config.metadata,timeline:d,shardRunIds:null};if(this.writeReport(g),await $(()=>Ze(g,this.config,i),rt,"HTML report write"),st(f,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient){let u=this.collectArtifactEntries(),h=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await $(()=>Ct(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,g,r,a,f,u,h),tt,"Cloud upload");}}}catch{}finally{await this.disposeCloudClient();}}async disposeCloudClient(){let e=this.cloudClient;e&&(this.cloudClient=null,await $(()=>e.dispose(),qr,"Cloud client shutdown"));}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let e=path.dirname(this.config.outputPath),r=[];for(let n of this.collectedTests)n.artifacts&&r.push({testId:n.testId,artifacts:n.artifacts,outputDir:e});return r}async finalizeStreamingReport(e,r,n,s){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 p of this.testIndex){let m=`${p.filePath}::${p.titlePath.join(" > ")}`,y=a.get(m);(y===void 0||p.retryIndex>y)&&a.set(m,p.retryIndex);}let i=0;for(let p of this.testIndex){let m=`${p.filePath}::${p.titlePath.join(" > ")}`,y=a.get(m);if(p.isRetry=p.retryIndex<y,p.isRetry)continue;switch(i++,this.summaryCounters.total++,p.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(p.filePath);switch(w||(w={filePath:p.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},o.set(p.filePath,w)),w.total++,p.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=Ci();for(let p of this.streamingTestAgg.values()){l.volApiCalls+=p.apiCalls,l.volAssertions+=p.assertions,l.volNavigations+=p.navigations,l.volNetworkRequests+=p.networkRequests,l.volConsoleLogs+=p.consoleLogs,l.volActionSteps+=p.actionSteps;for(let m in p.methodCounts)l.methodCounts[m]=(l.methodCounts[m]??0)+p.methodCounts[m];l.statusRanges["2xx"]+=p.statusRanges["2xx"],l.statusRanges["3xx"]+=p.statusRanges["3xx"],l.statusRanges["4xx"]+=p.statusRanges["4xx"],l.statusRanges["5xx"]+=p.statusRanges["5xx"],l.statusRanges.error+=p.statusRanges.error,l.passedAssertions+=p.passedAssertions,l.failedAssertions+=p.failedAssertions;for(let m in p.actionCategories)l.actionCategoryCounts[m]=(l.actionCategoryCounts[m]??0)+p.actionCategories[m];for(let m of p.apiUrls){if(l.apiUrlSet.size>=Re)break;l.apiUrlSet.add(m);}for(let m of p.navUrls){if(l.navUrlSet.size>=Re)break;l.navUrlSet.add(m);}for(let m of p.responseTimes){if(l.responseTimes.length>=kn)break;l.responseTimes.push(m);}}this.summaryCounters.totalApiCalls=l.volApiCalls,this.summaryCounters.totalAssertions=l.volAssertions,this.summaryCounters.totalNavigations=l.volNavigations,this.summaryCounters.totalNetworkRequests=l.volNetworkRequests,this.summaryCounters.totalConsoleLogs=l.volConsoleLogs,this.summaryCounters.totalActionSteps=l.volActionSteps,this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let c={reporterTotal:this.summaryCounters.total,indexTotal:i,playwrightStatus:n.status,isValid:this.summaryCounters.total===i};c.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${c.reporterTotal}, index: ${c.indexTotal}
2659
+ `);let f={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:Ti(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}},g={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:e,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:d,enrichedSummary:f,validation:c,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(g);let u={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(u),await Ze(this.buildStreamingReport(g,f,e,r),this.config,s),st(f,this.config.outputPath,this.config.htmlReportPath,this.config.quiet);let h=this.streamingWriter.getReportDir();if(process.stderr.write(`[testrelic] Streaming report written to ${h}
2606
2660
  [testrelic] ${this.testIndex.length} test detail files on disk
2607
2661
  [testrelic] View report: npx testrelic serve ${h}
2608
2662
  `),this.streamingWriter.getWriteErrors().length>0&&process.stderr.write(`[testrelic] WARNING: ${this.streamingWriter.getWriteErrors().length} write error(s) during streaming
2609
- `),this.streamingWriter.dispose(),this.cloudClient){let p=this.buildStreamingReport(g,f,e,r),m=this.collectArtifactEntries(),y=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await Tt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,p,e,r,f,m,y);}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,n,s){return {schemaVersion:de,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:n,totalDuration:s,summary:r,ci:F(),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 n=e.heapUsed/e.heapTotal;n>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
2610
- `),this.switchToStreamingMode()):n>.8&&process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
2611
- `);}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let e=path.dirname(this.config.outputPath);this.streamingWriter=new te(e);for(let r of this.collectedTests){let n=Pe(r.filePath,r.titlePath,r.testId,r.retry),s=r.apiCallsFile&&r.apiCallsCount>0?q(r.apiCallsFile):void 0,a={id:n,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(n,a,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let o={id:n,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(`
2612
- `)[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(" > ")}`,vn(r.retry,s,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 Hr(e,{navigationTypes:this.config.navigationTypes})}readJsonlFile(e){if(!e)return null;let r=q(e);return r.length>0?r:null}toTestResult(e,r){let n=null,s=null,a=null;return r?.loadFiles&&(n=this.readJsonlFile(e.networkRequestsFile),s=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:n,apiCalls:a,apiAssertions:e.apiAssertions,actions:e.actions??null,consoleLogs:s}}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=gt(e.apiAssertions)),e.consoleLogsFile&&(r.consoleLogs=q(e.consoleLogsFile)),e.networkRequestsFile&&(r.networkRequests=q(e.networkRequestsFile)),e.apiCallsFile){let n=q(e.apiCallsFile);r.apiCalls=pt(n),(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=ft(n));}return r}writeReport(e){try{let r=JSON.stringify(e),n=this.config.outputPath,s=path.dirname(n);fs.mkdirSync(s,{recursive:!0});let a=n+".tmp";fs.writeFileSync(a,r,"utf-8"),fs.renameSync(a,n);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
2613
- `);}}};var Ni=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Fi(t){let e=t.toLowerCase();return Ni.some(r=>e.includes(r))}var _e=class t{constructor(e,r){this.page=e;this.records=[];this.listeners=[];this.navCounters=[];this.pendingRequests=new Map;this.networkWriter=null;this.consoleWriter=null;this.pendingBodyReads=[];this.requestIdCounter=0;this.networkRequestCount=0;this.consoleLogCount=0;this.includeNetworkStats=r?.includeNetworkStats??true,this.origGoto=e.goto.bind(e),this.origGoBack=e.goBack.bind(e),this.origGoForward=e.goForward.bind(e),this.origReload=e.reload.bind(e);try{this.includeNetworkStats&&(this.networkWriter=new P("network")),this.consoleWriter=new P("console");}catch{}this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async finalizeCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[,e]of this.pendingRequests)this.networkWriter&&(this.networkWriter.append({url:e.url,method:e.method,resourceType:e.resourceType,statusCode:0,responseTimeMs:Date.now()-e.startTimeMs,startedAt:e.startedAt,requestHeaders:e.headers,requestBody:e.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:e.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.networkRequestCount++);this.pendingRequests.clear(),this.networkWriter?.close(),this.consoleWriter?.close();}static mapConsoleType(e){switch(e){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getFileData(){this.assembleNetworkStats();let e=this.records.map(r=>({url:r.url,navigationType:r.navigationType,timestamp:r.timestamp,domContentLoadedAt:r.domContentLoadedAt,networkIdleAt:r.networkIdleAt,networkStats:r.networkStats}));return this.includeNetworkStats?await this.finalizeCapturedRequests():this.consoleWriter?.close(),{navigations:e,networkRequestsFile:this.networkWriter?.getCount()?this.networkWriter.getPath():null,networkRequestsCount:this.networkWriter?.getCount()??0,consoleLogsFile:this.consoleWriter?.getCount()?this.consoleWriter.getPath():null,consoleLogsCount:this.consoleWriter?.getCount()??0}}async flushLegacyAnnotations(e){}dispose(){this.page.goto=this.origGoto,this.page.goBack=this.origGoBack,this.page.goForward=this.origGoForward,this.page.reload=this.origReload;for(let{event:e,handler:r}of this.listeners)this.page.off(e,r);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}getRecords(){return this.assembleNetworkStats(),this.records}interceptMethods(){let e=this,r=this.page;r.goto=async function(n,s){return e.recordNavigation(n,"goto"),e.origGoto(n,s)},r.goBack=async function(n){let s=await e.origGoBack(n);return e.recordNavigation(r.url(),"back"),s},r.goForward=async function(n){let s=await e.origGoForward(n);return e.recordNavigation(r.url(),"forward"),s},r.reload=async function(n){return e.recordNavigation(r.url(),"refresh"),e.origReload(n)};}attachListeners(){let e=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",e),this.listeners.push({event:"domcontentloaded",handler:e});let r=s=>{try{let a=s;if(typeof a.parentFrame=="function"&&a.parentFrame()!==null)return;let o=a.url(),i=this.records[this.records.length-1];if(i&&Date.now()-new Date(i.timestamp).getTime()<50&&i.url===o)return;this.recordNavigation(o,"navigation");}catch{}};this.page.on("framenavigated",r),this.listeners.push({event:"framenavigated",handler:r});let n=s=>{try{let a=s,o=a.type(),i=a.text();if(o==="debug"&&i.startsWith("__testrelic_nav:")){try{let d=JSON.parse(i.slice(16));d.type&&d.url&&this.recordNavigation(d.url,d.type);}catch{}return}{let d=null;try{let c=a.location();c&&c.url&&(d=`${c.url}:${c.lineNumber}:${c.columnNumber}`);}catch{}let l=t.mapConsoleType(o);this.consoleWriter&&(this.consoleWriter.append({level:l,text:i,timestamp:new Date().toISOString(),location:d}),this.consoleLogCount++);}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=i=>{let d=this.records.length-1,l=this.counterForNav(d);l&&l.totalRequests++;try{let c=i,f=String(this.requestIdCounter++),g=c.postData()??null,u={url:c.url(),method:c.method(),resourceType:this.mapResourceType(c.resourceType()),headers:c.headers(),postData:g,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now(),navIndex:d};this.pendingRequests.set(f,u),i.__testrelic_id=f;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let a=i=>{try{let d=i,l=d.request().__testrelic_id,c=l?this.pendingRequests.get(l):void 0,f=this.counterForNav(c?c.navIndex:this.records.length-1);if(f){let w=d.status();w>=400&&(f.failedRequests++,f.failedRequestUrls.push(w+" "+d.url()));let v=d.headers()["content-length"];v&&(f.totalBytes+=parseInt(v,10)||0);let k=d.request().resourceType(),C=this.mapResourceType(k);f.byType[C]++;}if(!l||!c)return;this.pendingRequests.delete(l);let g=Date.now()-c.startTimeMs,u=d.headers(),h=u["content-type"]??null,p=parseInt(u["content-length"]??"0",10)||0,m=h?!Fi(h):!1,y=(async()=>{let w=null;if(!m)try{w=(await d.body()).toString("utf-8");}catch{}let v={url:c.url,method:c.method,resourceType:c.resourceType,statusCode:d.status(),responseTimeMs:g,startedAt:c.startedAt,requestHeaders:c.headers,requestBody:c.postData,responseBody:w,responseHeaders:u,contentType:h,responseSize:p,requestBodyTruncated:c.postDataTruncated,responseBodyTruncated:!1,isBinary:m,error:null};this.networkWriter&&(this.networkWriter.append(v),this.networkRequestCount++);})();this.pendingBodyReads.push(y);}catch{}};this.page.on("response",a),this.listeners.push({event:"response",handler:a});let o=i=>{let d=i.__testrelic_id,l=d?this.pendingRequests.get(d):void 0,c=this.counterForNav(l?l.navIndex:this.records.length-1);if(c){c.failedRequests++;try{let f=i;c.failedRequestUrls.push("ERR "+f.url());}catch{}}try{let f=i;if(!d||!l)return;this.pendingRequests.delete(d);let g={url:l.url,method:l.method,resourceType:l.resourceType,statusCode:0,responseTimeMs:Date.now()-l.startTimeMs,startedAt:l.startedAt,requestHeaders:l.headers,requestBody:l.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:l.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:f.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(g),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",o),this.listeners.push({event:"requestfailed",handler:o});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let e=history.pushState.bind(history),r=history.replaceState.bind(history);history.pushState=function(...n){e(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){r(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(e,r){this.records.push({url:e,navigationType:r,timestamp:new Date().toISOString()}),this.includeNetworkStats&&this.navCounters.push(this.createNetworkCounter());}createNetworkCounter(){return {totalRequests:0,failedRequests:0,failedRequestUrls:[],totalBytes:0,byType:{xhr:0,document:0,script:0,stylesheet:0,image:0,font:0,other:0}}}counterForNav(e){return e>=0?this.navCounters[e]:void 0}assembleNetworkStats(){if(this.includeNetworkStats)for(let e=0;e<this.records.length;e++){let r=this.navCounters[e];r&&(this.records[e].networkStats={totalRequests:r.totalRequests,failedRequests:r.failedRequests,failedRequestUrls:[...r.failedRequestUrls],totalBytes:r.totalBytes,byType:{...r.byType}});}}mapResourceType(e){switch(e){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};var At=Symbol.for("__testrelic_call_id"),Oi="__testrelic_api_assertions",j=new WeakMap,J=class{constructor(){this.assertions=[];this.currentCallId=null;}recordAssertion(e){this.assertions.push(e);}getAssertions(){return this.assertions}setCurrentCallId(e){this.currentCallId=e;}getCurrentCallId(){return this.currentCallId}getData(){return [...this.assertions]}flushLegacyAnnotations(e){this.assertions.length!==0&&e.annotations.push({type:Oi,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}},xn=new Map;function qi(t){let e=xn.get(t);if(e)return e;try{let r=t.startsWith("file://")?url.fileURLToPath(t):t,s=fs.readFileSync(r,"utf-8").split(`
2614
- `);return xn.set(t,s),s}catch{return null}}function Hi(){let e=new Error().stack;if(!e)return null;let r=e.split(`
2615
- `);for(let n of r){if(n.includes("/assertion-tracker.")||n.includes("/api-request-tracker.")||n.includes("node:internal")||n.includes(" at new Error")||n.includes(" at captureAssertionLocation")||n.includes(" at expectWrapper")||n.includes(" at wrappedMatcher"))continue;let s=n.match(/at\s+(?:.*?\s+\()?(.+?):(\d+):(\d+)\)?$/);if(s)return {file:s[1],line:parseInt(s[2],10),column:parseInt(s[3],10)}}return null}function Ui(t,e){if(!t)return "custom";let r=t.toLowerCase();return r.includes(".status()")&&!r.includes(".statustext()")?r.includes(".ok()")?"statusOk":"status":r.includes(".ok()")?"statusOk":r.includes(".headers()")||r.includes(".headersarray()")?"header":r.includes("tomatchobject")||r.includes("toequal")?"bodyMatch":r.includes("tocontain")||r.includes("tostringcontaining")?"bodyContains":r.includes(".json()")||r.includes(".text()")?"bodyField":"custom"}function $i(t,e,r){let n=function(a,...o){let i=t(),d=e();if(!i||!d)return r(a,...o);let l=null;if(a!=null&&typeof a=="object"){let u=a[At];typeof u=="string"&&(l=u);}if(!l&&a!==null&&a!==void 0&&typeof a=="object"&&(l=j.get(a)??null),l||(l=d.getCallIdForValue(a)),l||(l=i.getCurrentCallId()),!l)return r(a,...o);let c=Hi(),f;if(c){let u=qi(c.file);u&&c.line>0&&c.line<=u.length&&(f=u[c.line-1].trim());}let g=r(a,...o);return l?Sn(g,{tracker:i,callId:l,received:a,location:c??{file:"unknown",line:0},expression:f}):g};for(let s of Object.keys(r))n[s]=r[s];return n}var Tn=null,Cn=null;function K(t,e){Tn=t,Cn=e;}function Ie(t){return $i(()=>Tn,()=>Cn,t)}function Sn(t,e){return new Proxy(t,{get(r,n,s){let a=Reflect.get(r,n,s);return typeof a!="function"||typeof n=="symbol"?a:n==="not"?Sn(a,e):function(...i){let d=i[0],l="passed",c=e.received,f=null;try{let g=a.apply(this??r,i);return g&&typeof g=="object"&&typeof g.then=="function"?g.then(()=>{Rt(e,n,d,c,"passed");},u=>{throw Rt(e,n,d,c,"failed"),u}):g}catch(g){if(l="failed",f=g,g instanceof Error&&g.message){let u=g.message.match(/Received:\s*(.+)/);u&&(c=u[1]);}throw g}finally{(f!==null||l==="passed")&&Rt(e,n,d,c,l);}}}})}function Rt(t,e,r,n,s){let a=Ui(t.expression,t.received),o={callId:t.callId,type:a,expected:kn(r),actual:kn(n),status:s,location:t.location,expression:t.expression};t.tracker.recordAssertion(o);}function kn(t){if(t==null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;try{return JSON.stringify(t),t}catch{return String(t)}}var Rn="[REDACTED]";function It(t,e){if(t===null||e.length===0)return t;let r=new Set(e.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(t))Object.hasOwn(t,s)&&(n[s]=r.has(s.toLowerCase())?Rn:t[s]);return n}function Le(t,e){if(t===null||e.length===0)return t;let r;try{r=JSON.parse(t);}catch{return t}if(typeof r!="object"||r===null)return t;let n=new Set(e.map(a=>a.toLowerCase())),s=_t(r,n);return JSON.stringify(s)}function _t(t,e){if(Array.isArray(t))return t.map(r=>_t(r,e));if(typeof t=="object"&&t!==null){let r={};for(let n of Object.keys(t)){if(!Object.hasOwn(t,n))continue;let s=t[n];e.has(n.toLowerCase())?r[n]=Rn:r[n]=_t(s,e);}return r}return t}var zi=new Set(["access_token","api_key","token","sig"]);function Lt(t){if(!t)return t;let e;try{e=new URL(t);}catch{return t}let r=false;for(let n of [...e.searchParams.keys()])zi.has(n.toLowerCase())&&(e.searchParams.delete(n),r=true);return r?e.toString():t}function _n(t,e,r){if(r.length>0){for(let n of r)if(An(t,n))return false}if(e.length>0){for(let n of e)if(An(t,n))return true;return false}return true}function An(t,e){try{return e instanceof RegExp?e.test(t):ji(e).test(t)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(e)}`),false}}function ji(t){let e="",r=0;for(;r<t.length;){let n=t[r];n==="*"&&t[r+1]==="*"?(e+=".*",r+=2,t[r]==="/"&&r++):n==="*"?(e+="[^/]*",r++):n==="?"?(e+="[^/]",r++):".+^${}()|[]\\".includes(n)?(e+="\\"+n,r++):(e+=n,r++);}return new RegExp(e)}var Wi=["get","post","put","patch","delete","head","fetch"],Vi=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Gi(t){let e=t.toLowerCase();return Vi.some(r=>e.includes(r))}function Ji(t){if(!t)return null;if(t.data!==void 0&&t.data!==null){let e=t.data;return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString("base64"):JSON.stringify(e)}if(t.form!==void 0&&t.form!==null)return JSON.stringify(t.form);if(t.multipart!==void 0&&t.multipart!==null){let e=t.multipart,r={};for(let[n,s]of Object.entries(e))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?r[n]=String(s):s&&typeof s=="object"&&"name"in s?r[n]=`[file: ${s.name}]`:r[n]="[binary]";return JSON.stringify(r)}return null}function In(t){return t?"\u2022\u2022\u2022\u2022":""}function Ki(t){if(!t)return [];let e;for(let[n,s]of Object.entries(t))if(n.toLowerCase()==="cookie"){e=s;break}if(!e)return [];let r=[];for(let n of e.split(";")){let s=n.trim();if(!s)continue;let a=s.indexOf("="),o=a===-1?s:s.slice(0,a).trim(),i=a===-1?"":s.slice(a+1).trim();o&&r.push({name:o,value:In(i)});}return r}function Yi(t){let e=[];for(let r of t)for(let n of r.split(/,(?=\s*[A-Za-z0-9_.\-]+=)/)){let s=n.trim();if(!s)continue;let a=s.split(";"),o=a[0].indexOf("=");if(o===-1)continue;let i=a[0].slice(0,o).trim(),d=a[0].slice(o+1).trim(),l=a.slice(1).map(c=>c.trim()).filter(Boolean).join(" \xB7 ")||void 0;i&&e.push({name:i,value:In(d),attributes:l});}return e}var Me=class Me{constructor(e,r,n){this.originals=new Map;this.apiCallWriter=null;this.callCounter=0;this.apiCallCount=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=e,this.assertionTracker=r??null,this.apiConfig=n??Me.DEFAULT_API_CONFIG;try{this.apiCallWriter=new P("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(e){return e!=null&&typeof e=="object"?j.get(e)??null:this.primitiveCallIds.get(e)??null}intercept(){for(let r of Wi){let n=this.context[r].bind(this.context);this.originals.set(r,n),this.context[r]=this.createWrapper(r,n);}let e=this.context.dispose.bind(this.context);this.originals.set("dispose",e),this.context.dispose=async r=>(this.disposed=true,e(r));}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0}}flushLegacyAnnotations(e){}dispose(){for(let[e,r]of this.originals)this.context[e]=r;this.originals.clear(),this.apiCallWriter?.close(),this.callCounter=0,this.apiCallCount=0,this._lastCallId=null,this.primitiveCallIds.clear();}get isDisposed(){return this.disposed}getCapturedCallCount(){return this.apiCallCount}tagResponseMethods(e,r){let n=this,s=e.headers.bind(e);e.headers=function(){let u=s();return j.set(u,r),u};let a=e.headersArray.bind(e);e.headersArray=function(){let u=a();return j.set(u,r),u};let o=e.json.bind(e);e.json=async function(){let u=await o();return u!=null&&typeof u=="object"&&j.set(u,r),u};let i=e.status.bind(e);e.status=function(){let u=i();return n.primitiveCallIds.set(u,r),u};let d=e.statusText.bind(e);e.statusText=function(){let u=d();return n.primitiveCallIds.set(u,r),u};let l=e.ok.bind(e);e.ok=function(){let u=l();return n.primitiveCallIds.set(u,r),u};let c=e.text.bind(e);e.text=async function(){let u=await c();return n.primitiveCallIds.set(u,r),u};let f=e.body.bind(e);e.body=async function(){let u=await f();return j.set(u,r),u};}createWrapper(e,r){let n=this;return async function(a,o){if(!_n(a,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return r(a,o);let i=`api-call-${n.callCounter++}`,d=new Date().toISOString(),l=e==="fetch"?(o?.method??"GET").toUpperCase():e.toUpperCase(),c=Ji(o),f=perf_hooks.performance.now();n._lastCallId=i,n.assertionTracker&&n.assertionTracker.setCurrentCallId(i);let g;try{g=await r(a,o);}catch(u){let h=perf_hooks.performance.now();try{let p=n.apiConfig.captureRequestBody?Le(c,n.apiConfig.redactBodyFields):null,m={id:i,timestamp:d,method:l,url:Lt(a),requestHeaders:null,requestBody:p,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((h-f)*100)/100,isBinary:!1,error:u instanceof Error?u.message:String(u)};n.apiCallWriter&&(n.apiCallWriter.append(m),n.apiCallCount++);}catch{}throw u}try{let u=perf_hooks.performance.now(),h=g.headers(),p=h["content-type"]??null,m=p?!Gi(p):!1,y=null;n.apiConfig.captureRequestHeaders&&o?.headers&&(y=o.headers);let w=null;n.apiConfig.captureResponseHeaders&&(w=h);let v=n.apiConfig.captureRequestBody?c:null,k=null;if(n.apiConfig.captureResponseBody)try{m?k=(await g.body()).toString("base64"):k=await g.text();}catch{}let C=[],b=[];try{if(n.apiConfig.captureRequestHeaders&&(C=Ki(o?.headers)),n.apiConfig.captureResponseHeaders){let S=g.headersArray().filter(M=>M.name.toLowerCase()==="set-cookie").map(M=>M.value);b=Yi(S);}}catch{}y=It(y,n.apiConfig.redactHeaders),w=It(w,n.apiConfig.redactHeaders),v=Le(v,n.apiConfig.redactBodyFields),k=Le(k,n.apiConfig.redactBodyFields);let T={id:i,timestamp:d,method:l,url:Lt(g.url()),requestHeaders:y,requestBody:v,responseStatusCode:g.status(),responseStatusText:g.statusText(),responseHeaders:w,responseBody:k,requestCookies:C.length?C:null,responseCookies:b.length?b:null,responseTimeMs:Math.round((u-f)*100)/100,isBinary:m,error:null};n.apiCallWriter&&(n.apiCallWriter.append(T),n.apiCallCount++);}catch{}try{g[At]=i,n.tagResponseMethods(g,i);}catch{}return g}}};Me.DEFAULT_API_CONFIG=Object.freeze({trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]});var Y=Me;Ie(test.expect);var Xi="__testrelic_api_config",eo="__testrelic_config_trackApiCalls";function Et(t){let e=t.annotations.find(n=>n.type===Xi&&n.description!==void 0);if(e)try{return JSON.parse(e.description,to)}catch{}let r=t.annotations.find(n=>n.type===eo&&n.description!==void 0);return r?{trackApiCalls:r.description!=="false",captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}:{trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}}function to(t,e){if(typeof e=="object"&&e!==null&&e.__regexp===true&&typeof e.source=="string"){let{source:r,flags:n}=e;return new RegExp(r,n)}return e}var Pn={page:async({page:t},e,r)=>{let n=new _e(t);try{await n.init();}catch{}await e(t);try{let{navigations:s,networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:d}=await n.getFileData(),l={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:d,apiCallsFile:null,apiCallsCount:0};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(l)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:t},e,r)=>{let n=Et(r);if(!n.trackApiCalls){await e(t);return}let s=new J,a=new Y(t,s,n);a.intercept(),K(s,a);try{await e(t);}finally{K(null,null);}try{let{apiCallsFile:o,apiCallsCount:i}=a.getFileData(),d=n.captureAssertions?s.getData():[],l={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:d,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:o,apiCallsCount:i};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(l)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};test.test.extend(Pn);Ie(test.expect);var io={request:async({request:t},e,r)=>{let n=Et(r);if(!n.trackApiCalls){await e(t);return}let s=new J,a=new Y(t,s,n);a.intercept(),K(s,a);let o=null;try{o=new P("api-console");}catch{}let i=0,d=process.stdout.write,l=process.stderr.write;process.stdout.write=function(c,...f){try{let g=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!g.startsWith("[testrelic]")&&!g.startsWith("\u2139 TestRelic")&&!g.startsWith("\u2713 TestRelic")&&!g.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stdout",text:g.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return d.apply(process.stdout,[c,...f])},process.stderr.write=function(c,...f){try{let g=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!g.startsWith("[testrelic]")&&!g.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stderr",text:g.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return l.apply(process.stderr,[c,...f])};try{await e(t);}finally{process.stdout.write=d,process.stderr.write=l,K(null,null);}try{o?.close();let{apiCallsFile:c,apiCallsCount:f}=a.getFileData(),g=n.captureAssertions?s.getData():[],u={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:g,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:i>0?o?.getPath()??null:null,consoleLogsCount:i,apiCallsFile:c,apiCallsCount:f};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(u)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};var Nn="@testrelic/playwright-analytics";function lo(t){return Array.isArray(t)?t.some(e=>Array.isArray(e)&&typeof e[0]=="string"&&e[0]===Nn):false}function co(t,e){let n={video:"on",screenshot:"on",trace:"on",...t.use??{}},s;Array.isArray(t.reporter)?s=t.reporter:typeof t.reporter=="string"?s=[[t.reporter]]:s=[["list"]];let a=lo(s)?s:[...s,[Nn,e??{}]];return test.defineConfig({...t,use:n,reporter:a})}var Fn=false;function Rc(t,e,r="manual_record"){if(!t||!t.annotations){Fn||(Fn=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
2616
- `));return}let n={url:e,navigationType:r,timestamp:new Date().toISOString()};t.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}Object.defineProperty(exports,"ATTACHMENT_CONTENT_TYPE",{enumerable:true,get:function(){return core.ATTACHMENT_CONTENT_TYPE}});Object.defineProperty(exports,"ATTACHMENT_NAME",{enumerable:true,get:function(){return core.ATTACHMENT_NAME}});Object.defineProperty(exports,"PAYLOAD_VERSION",{enumerable:true,get:function(){return core.PAYLOAD_VERSION}});Object.defineProperty(exports,"isTestRelicDataPayload",{enumerable:true,get:function(){return core.isTestRelicDataPayload}});exports.SCHEMA_VERSION=de;exports.default=Ae;exports.defineConfig=co;exports.recordNavigation=Rc;exports.testRelicApiFixture=io;exports.testRelicFixture=Pn;//# sourceMappingURL=index.cjs.map
2663
+ `),this.streamingWriter.dispose(),this.cloudClient){let p=this.buildStreamingReport(g,f,e,r),m=this.collectArtifactEntries(),y=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await Ct(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,p,e,r,f,m,y);}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,n,s){return {schemaVersion:de,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:n,totalDuration:s,summary:r,ci:F(),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 n=e.heapUsed/e.heapTotal;n>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
2664
+ `),this.switchToStreamingMode()):n>.8&&r>=500&&!this.memoryPressureWarned&&(this.memoryPressureWarned=!0,process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
2665
+ `));}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let e=path.dirname(this.config.outputPath);this.streamingWriter=new te(e);for(let r of this.collectedTests){let n=Ee(r.filePath,r.titlePath,r.testId,r.retry),s=r.apiCallsFile&&r.apiCallsCount>0?q(r.apiCallsFile):void 0,a={id:n,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(n,a,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let o={id:n,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(`
2666
+ `)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,isRetry:!1,retryGroupKey:Ne(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(" > ")}`,wn(r.retry,s,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 $r(e,{navigationTypes:this.config.navigationTypes})}readJsonlFile(e){if(!e)return null;let r=q(e);return r.length>0?r:null}toTestResult(e,r){let n=null,s=null,a=null;return r?.loadFiles&&(n=this.readJsonlFile(e.networkRequestsFile),s=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:n,apiCalls:a,apiAssertions:e.apiAssertions,actions:e.actions??null,consoleLogs:s}}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=ht(e.apiAssertions)),e.consoleLogsFile&&(r.consoleLogs=q(e.consoleLogsFile)),e.networkRequestsFile&&(r.networkRequests=q(e.networkRequestsFile)),e.apiCallsFile){let n=q(e.apiCallsFile);r.apiCalls=ft(n),(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=gt(n));}return r}writeReport(e){try{let r=JSON.stringify(e),n=this.config.outputPath,s=path.dirname(n);fs.mkdirSync(s,{recursive:!0});let a=n+".tmp";fs.writeFileSync(a,r,"utf-8"),fs.renameSync(a,n);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
2667
+ `);}}};var Fi=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Di(t){let e=t.toLowerCase();return Fi.some(r=>e.includes(r))}var _e=class t{constructor(e,r){this.page=e;this.records=[];this.listeners=[];this.navCounters=[];this.pendingRequests=new Map;this.networkWriter=null;this.consoleWriter=null;this.pendingBodyReads=[];this.requestIdCounter=0;this.networkRequestCount=0;this.consoleLogCount=0;this.includeNetworkStats=r?.includeNetworkStats??true,this.origGoto=e.goto.bind(e),this.origGoBack=e.goBack.bind(e),this.origGoForward=e.goForward.bind(e),this.origReload=e.reload.bind(e);try{this.includeNetworkStats&&(this.networkWriter=new E("network")),this.consoleWriter=new E("console");}catch{}this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async finalizeCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[,e]of this.pendingRequests)this.networkWriter&&(this.networkWriter.append({url:e.url,method:e.method,resourceType:e.resourceType,statusCode:0,responseTimeMs:Date.now()-e.startTimeMs,startedAt:e.startedAt,requestHeaders:e.headers,requestBody:e.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:e.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.networkRequestCount++);this.pendingRequests.clear(),this.networkWriter?.close(),this.consoleWriter?.close();}static mapConsoleType(e){switch(e){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getFileData(){this.assembleNetworkStats();let e=this.records.map(r=>({url:r.url,navigationType:r.navigationType,timestamp:r.timestamp,domContentLoadedAt:r.domContentLoadedAt,networkIdleAt:r.networkIdleAt,networkStats:r.networkStats}));return this.includeNetworkStats?await this.finalizeCapturedRequests():this.consoleWriter?.close(),{navigations:e,networkRequestsFile:this.networkWriter?.getCount()?this.networkWriter.getPath():null,networkRequestsCount:this.networkWriter?.getCount()??0,consoleLogsFile:this.consoleWriter?.getCount()?this.consoleWriter.getPath():null,consoleLogsCount:this.consoleWriter?.getCount()??0}}async flushLegacyAnnotations(e){}dispose(){this.page.goto=this.origGoto,this.page.goBack=this.origGoBack,this.page.goForward=this.origGoForward,this.page.reload=this.origReload;for(let{event:e,handler:r}of this.listeners)this.page.off(e,r);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}getRecords(){return this.assembleNetworkStats(),this.records}interceptMethods(){let e=this,r=this.page;r.goto=async function(n,s){return e.recordNavigation(n,"goto"),e.origGoto(n,s)},r.goBack=async function(n){let s=await e.origGoBack(n);return e.recordNavigation(r.url(),"back"),s},r.goForward=async function(n){let s=await e.origGoForward(n);return e.recordNavigation(r.url(),"forward"),s},r.reload=async function(n){return e.recordNavigation(r.url(),"refresh"),e.origReload(n)};}attachListeners(){let e=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",e),this.listeners.push({event:"domcontentloaded",handler:e});let r=s=>{try{let a=s;if(typeof a.parentFrame=="function"&&a.parentFrame()!==null)return;let o=a.url(),i=this.records[this.records.length-1];if(i&&Date.now()-new Date(i.timestamp).getTime()<50&&i.url===o)return;this.recordNavigation(o,"navigation");}catch{}};this.page.on("framenavigated",r),this.listeners.push({event:"framenavigated",handler:r});let n=s=>{try{let a=s,o=a.type(),i=a.text();if(o==="debug"&&i.startsWith("__testrelic_nav:")){try{let d=JSON.parse(i.slice(16));d.type&&d.url&&this.recordNavigation(d.url,d.type);}catch{}return}{let d=null;try{let c=a.location();c&&c.url&&(d=`${c.url}:${c.lineNumber}:${c.columnNumber}`);}catch{}let l=t.mapConsoleType(o);this.consoleWriter&&(this.consoleWriter.append({level:l,text:i,timestamp:new Date().toISOString(),location:d}),this.consoleLogCount++);}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=i=>{let d=this.records.length-1,l=this.counterForNav(d);l&&l.totalRequests++;try{let c=i,f=String(this.requestIdCounter++),g=c.postData()??null,u={url:c.url(),method:c.method(),resourceType:this.mapResourceType(c.resourceType()),headers:c.headers(),postData:g,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now(),navIndex:d};this.pendingRequests.set(f,u),i.__testrelic_id=f;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let a=i=>{try{let d=i,l=d.request().__testrelic_id,c=l?this.pendingRequests.get(l):void 0,f=this.counterForNav(c?c.navIndex:this.records.length-1);if(f){let w=d.status();w>=400&&(f.failedRequests++,f.failedRequestUrls.push(w+" "+d.url()));let v=d.headers()["content-length"];v&&(f.totalBytes+=parseInt(v,10)||0);let k=d.request().resourceType(),C=this.mapResourceType(k);f.byType[C]++;}if(!l||!c)return;this.pendingRequests.delete(l);let g=Date.now()-c.startTimeMs,u=d.headers(),h=u["content-type"]??null,p=parseInt(u["content-length"]??"0",10)||0,m=h?!Di(h):!1,y=(async()=>{let w=null;if(!m)try{w=(await d.body()).toString("utf-8");}catch{}let v={url:c.url,method:c.method,resourceType:c.resourceType,statusCode:d.status(),responseTimeMs:g,startedAt:c.startedAt,requestHeaders:c.headers,requestBody:c.postData,responseBody:w,responseHeaders:u,contentType:h,responseSize:p,requestBodyTruncated:c.postDataTruncated,responseBodyTruncated:!1,isBinary:m,error:null};this.networkWriter&&(this.networkWriter.append(v),this.networkRequestCount++);})();this.pendingBodyReads.push(y);}catch{}};this.page.on("response",a),this.listeners.push({event:"response",handler:a});let o=i=>{let d=i.__testrelic_id,l=d?this.pendingRequests.get(d):void 0,c=this.counterForNav(l?l.navIndex:this.records.length-1);if(c){c.failedRequests++;try{let f=i;c.failedRequestUrls.push("ERR "+f.url());}catch{}}try{let f=i;if(!d||!l)return;this.pendingRequests.delete(d);let g={url:l.url,method:l.method,resourceType:l.resourceType,statusCode:0,responseTimeMs:Date.now()-l.startTimeMs,startedAt:l.startedAt,requestHeaders:l.headers,requestBody:l.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:l.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:f.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(g),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",o),this.listeners.push({event:"requestfailed",handler:o});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let e=history.pushState.bind(history),r=history.replaceState.bind(history);history.pushState=function(...n){e(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){r(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(e,r){this.records.push({url:e,navigationType:r,timestamp:new Date().toISOString()}),this.includeNetworkStats&&this.navCounters.push(this.createNetworkCounter());}createNetworkCounter(){return {totalRequests:0,failedRequests:0,failedRequestUrls:[],totalBytes:0,byType:{xhr:0,document:0,script:0,stylesheet:0,image:0,font:0,other:0}}}counterForNav(e){return e>=0?this.navCounters[e]:void 0}assembleNetworkStats(){if(this.includeNetworkStats)for(let e=0;e<this.records.length;e++){let r=this.navCounters[e];r&&(this.records[e].networkStats={totalRequests:r.totalRequests,failedRequests:r.failedRequests,failedRequestUrls:[...r.failedRequestUrls],totalBytes:r.totalBytes,byType:{...r.byType}});}}mapResourceType(e){switch(e){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};var _t=Symbol.for("__testrelic_call_id"),qi="__testrelic_api_assertions",j=new WeakMap,K=class{constructor(){this.assertions=[];this.currentCallId=null;}recordAssertion(e){this.assertions.push(e);}getAssertions(){return this.assertions}setCurrentCallId(e){this.currentCallId=e;}getCurrentCallId(){return this.currentCallId}getData(){return [...this.assertions]}flushLegacyAnnotations(e){this.assertions.length!==0&&e.annotations.push({type:qi,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}},Tn=new Map;function Hi(t){let e=Tn.get(t);if(e)return e;try{let r=t.startsWith("file://")?url.fileURLToPath(t):t,s=fs.readFileSync(r,"utf-8").split(`
2668
+ `);return Tn.set(t,s),s}catch{return null}}function Ui(){let e=new Error().stack;if(!e)return null;let r=e.split(`
2669
+ `);for(let n of r){if(n.includes("/assertion-tracker.")||n.includes("/api-request-tracker.")||n.includes("node:internal")||n.includes(" at new Error")||n.includes(" at captureAssertionLocation")||n.includes(" at expectWrapper")||n.includes(" at wrappedMatcher"))continue;let s=n.match(/at\s+(?:.*?\s+\()?(.+?):(\d+):(\d+)\)?$/);if(s)return {file:s[1],line:parseInt(s[2],10),column:parseInt(s[3],10)}}return null}function $i(t,e){if(!t)return "custom";let r=t.toLowerCase();return r.includes(".status()")&&!r.includes(".statustext()")?r.includes(".ok()")?"statusOk":"status":r.includes(".ok()")?"statusOk":r.includes(".headers()")||r.includes(".headersarray()")?"header":r.includes("tomatchobject")||r.includes("toequal")?"bodyMatch":r.includes("tocontain")||r.includes("tostringcontaining")?"bodyContains":r.includes(".json()")||r.includes(".text()")?"bodyField":"custom"}function zi(t,e,r){let n=function(a,...o){let i=t(),d=e();if(!i||!d)return r(a,...o);let l=null;if(a!=null&&typeof a=="object"){let u=a[_t];typeof u=="string"&&(l=u);}if(!l&&a!==null&&a!==void 0&&typeof a=="object"&&(l=j.get(a)??null),l||(l=d.getCallIdForValue(a)),l||(l=i.getCurrentCallId()),!l)return r(a,...o);let c=Ui(),f;if(c){let u=Hi(c.file);u&&c.line>0&&c.line<=u.length&&(f=u[c.line-1].trim());}let g=r(a,...o);return l?An(g,{tracker:i,callId:l,received:a,location:c??{file:"unknown",line:0},expression:f}):g};for(let s of Object.keys(r))n[s]=r[s];return n}var Sn=null,Rn=null;function J(t,e){Sn=t,Rn=e;}function Ie(t){return zi(()=>Sn,()=>Rn,t)}function An(t,e){return new Proxy(t,{get(r,n,s){let a=Reflect.get(r,n,s);return typeof a!="function"||typeof n=="symbol"?a:n==="not"?An(a,e):function(...i){let d=i[0],l="passed",c=e.received,f=null;try{let g=a.apply(this??r,i);return g&&typeof g=="object"&&typeof g.then=="function"?g.then(()=>{At(e,n,d,c,"passed");},u=>{throw At(e,n,d,c,"failed"),u}):g}catch(g){if(l="failed",f=g,g instanceof Error&&g.message){let u=g.message.match(/Received:\s*(.+)/);u&&(c=u[1]);}throw g}finally{(f!==null||l==="passed")&&At(e,n,d,c,l);}}}})}function At(t,e,r,n,s){let a=$i(t.expression,t.received),o={callId:t.callId,type:a,expected:Cn(r),actual:Cn(n),status:s,location:t.location,expression:t.expression};t.tracker.recordAssertion(o);}function Cn(t){if(t==null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;try{return JSON.stringify(t),t}catch{return String(t)}}var _n="[REDACTED]";function Lt(t,e){if(t===null||e.length===0)return t;let r=new Set(e.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(t))Object.hasOwn(t,s)&&(n[s]=r.has(s.toLowerCase())?_n:t[s]);return n}function Le(t,e){if(t===null||e.length===0)return t;let r;try{r=JSON.parse(t);}catch{return t}if(typeof r!="object"||r===null)return t;let n=new Set(e.map(a=>a.toLowerCase())),s=It(r,n);return JSON.stringify(s)}function It(t,e){if(Array.isArray(t))return t.map(r=>It(r,e));if(typeof t=="object"&&t!==null){let r={};for(let n of Object.keys(t)){if(!Object.hasOwn(t,n))continue;let s=t[n];e.has(n.toLowerCase())?r[n]=_n:r[n]=It(s,e);}return r}return t}var ji=new Set(["access_token","api_key","token","sig"]);function Mt(t){if(!t)return t;let e;try{e=new URL(t);}catch{return t}let r=false;for(let n of [...e.searchParams.keys()])ji.has(n.toLowerCase())&&(e.searchParams.delete(n),r=true);return r?e.toString():t}function Ln(t,e,r){if(r.length>0){for(let n of r)if(In(t,n))return false}if(e.length>0){for(let n of e)if(In(t,n))return true;return false}return true}function In(t,e){try{return e instanceof RegExp?e.test(t):Wi(e).test(t)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(e)}`),false}}function Wi(t){let e="",r=0;for(;r<t.length;){let n=t[r];n==="*"&&t[r+1]==="*"?(e+=".*",r+=2,t[r]==="/"&&r++):n==="*"?(e+="[^/]*",r++):n==="?"?(e+="[^/]",r++):".+^${}()|[]\\".includes(n)?(e+="\\"+n,r++):(e+=n,r++);}return new RegExp(e)}var Gi=["get","post","put","patch","delete","head","fetch"],Vi=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Ki(t){let e=t.toLowerCase();return Vi.some(r=>e.includes(r))}function Ji(t){if(!t)return null;if(t.data!==void 0&&t.data!==null){let e=t.data;return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString("base64"):JSON.stringify(e)}if(t.form!==void 0&&t.form!==null)return JSON.stringify(t.form);if(t.multipart!==void 0&&t.multipart!==null){let e=t.multipart,r={};for(let[n,s]of Object.entries(e))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?r[n]=String(s):s&&typeof s=="object"&&"name"in s?r[n]=`[file: ${s.name}]`:r[n]="[binary]";return JSON.stringify(r)}return null}function Mn(t){return t?"\u2022\u2022\u2022\u2022":""}function Yi(t){if(!t)return [];let e;for(let[n,s]of Object.entries(t))if(n.toLowerCase()==="cookie"){e=s;break}if(!e)return [];let r=[];for(let n of e.split(";")){let s=n.trim();if(!s)continue;let a=s.indexOf("="),o=a===-1?s:s.slice(0,a).trim(),i=a===-1?"":s.slice(a+1).trim();o&&r.push({name:o,value:Mn(i)});}return r}function Zi(t){let e=[];for(let r of t)for(let n of r.split(/,(?=\s*[A-Za-z0-9_.\-]+=)/)){let s=n.trim();if(!s)continue;let a=s.split(";"),o=a[0].indexOf("=");if(o===-1)continue;let i=a[0].slice(0,o).trim(),d=a[0].slice(o+1).trim(),l=a.slice(1).map(c=>c.trim()).filter(Boolean).join(" \xB7 ")||void 0;i&&e.push({name:i,value:Mn(d),attributes:l});}return e}var Me=class Me{constructor(e,r,n){this.originals=new Map;this.apiCallWriter=null;this.callCounter=0;this.apiCallCount=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=e,this.assertionTracker=r??null,this.apiConfig=n??Me.DEFAULT_API_CONFIG;try{this.apiCallWriter=new E("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(e){return e!=null&&typeof e=="object"?j.get(e)??null:this.primitiveCallIds.get(e)??null}intercept(){for(let r of Gi){let n=this.context[r].bind(this.context);this.originals.set(r,n),this.context[r]=this.createWrapper(r,n);}let e=this.context.dispose.bind(this.context);this.originals.set("dispose",e),this.context.dispose=async r=>(this.disposed=true,e(r));}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0}}flushLegacyAnnotations(e){}dispose(){for(let[e,r]of this.originals)this.context[e]=r;this.originals.clear(),this.apiCallWriter?.close(),this.callCounter=0,this.apiCallCount=0,this._lastCallId=null,this.primitiveCallIds.clear();}get isDisposed(){return this.disposed}getCapturedCallCount(){return this.apiCallCount}tagResponseMethods(e,r){let n=this,s=e.headers.bind(e);e.headers=function(){let u=s();return j.set(u,r),u};let a=e.headersArray.bind(e);e.headersArray=function(){let u=a();return j.set(u,r),u};let o=e.json.bind(e);e.json=async function(){let u=await o();return u!=null&&typeof u=="object"&&j.set(u,r),u};let i=e.status.bind(e);e.status=function(){let u=i();return n.primitiveCallIds.set(u,r),u};let d=e.statusText.bind(e);e.statusText=function(){let u=d();return n.primitiveCallIds.set(u,r),u};let l=e.ok.bind(e);e.ok=function(){let u=l();return n.primitiveCallIds.set(u,r),u};let c=e.text.bind(e);e.text=async function(){let u=await c();return n.primitiveCallIds.set(u,r),u};let f=e.body.bind(e);e.body=async function(){let u=await f();return j.set(u,r),u};}createWrapper(e,r){let n=this;return async function(a,o){if(!Ln(a,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return r(a,o);let i=`api-call-${n.callCounter++}`,d=new Date().toISOString(),l=e==="fetch"?(o?.method??"GET").toUpperCase():e.toUpperCase(),c=Ji(o),f=perf_hooks.performance.now();n._lastCallId=i,n.assertionTracker&&n.assertionTracker.setCurrentCallId(i);let g;try{g=await r(a,o);}catch(u){let h=perf_hooks.performance.now();try{let p=n.apiConfig.captureRequestBody?Le(c,n.apiConfig.redactBodyFields):null,m={id:i,timestamp:d,method:l,url:Mt(a),requestHeaders:null,requestBody:p,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((h-f)*100)/100,isBinary:!1,error:u instanceof Error?u.message:String(u)};n.apiCallWriter&&(n.apiCallWriter.append(m),n.apiCallCount++);}catch{}throw u}try{let u=perf_hooks.performance.now(),h=g.headers(),p=h["content-type"]??null,m=p?!Ki(p):!1,y=null;n.apiConfig.captureRequestHeaders&&o?.headers&&(y=o.headers);let w=null;n.apiConfig.captureResponseHeaders&&(w=h);let v=n.apiConfig.captureRequestBody?c:null,k=null;if(n.apiConfig.captureResponseBody)try{m?k=(await g.body()).toString("base64"):k=await g.text();}catch{}let C=[],b=[];try{if(n.apiConfig.captureRequestHeaders&&(C=Yi(o?.headers)),n.apiConfig.captureResponseHeaders){let S=g.headersArray().filter(M=>M.name.toLowerCase()==="set-cookie").map(M=>M.value);b=Zi(S);}}catch{}y=Lt(y,n.apiConfig.redactHeaders),w=Lt(w,n.apiConfig.redactHeaders),v=Le(v,n.apiConfig.redactBodyFields),k=Le(k,n.apiConfig.redactBodyFields);let T={id:i,timestamp:d,method:l,url:Mt(g.url()),requestHeaders:y,requestBody:v,responseStatusCode:g.status(),responseStatusText:g.statusText(),responseHeaders:w,responseBody:k,requestCookies:C.length?C:null,responseCookies:b.length?b:null,responseTimeMs:Math.round((u-f)*100)/100,isBinary:m,error:null};n.apiCallWriter&&(n.apiCallWriter.append(T),n.apiCallCount++);}catch{}try{g[_t]=i,n.tagResponseMethods(g,i);}catch{}return g}}};Me.DEFAULT_API_CONFIG=Object.freeze({trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]});var Y=Me;Ie(test.expect);var eo="__testrelic_api_config",to="__testrelic_config_trackApiCalls";function Et(t){let e=t.annotations.find(n=>n.type===eo&&n.description!==void 0);if(e)try{return JSON.parse(e.description,ro)}catch{}let r=t.annotations.find(n=>n.type===to&&n.description!==void 0);return r?{trackApiCalls:r.description!=="false",captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}:{trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}}function ro(t,e){if(typeof e=="object"&&e!==null&&e.__regexp===true&&typeof e.source=="string"){let{source:r,flags:n}=e;return new RegExp(r,n)}return e}var Fn={page:async({page:t},e,r)=>{let n=new _e(t);try{await n.init();}catch{}await e(t);try{let{navigations:s,networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:d}=await n.getFileData(),l={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:d,apiCallsFile:null,apiCallsCount:0};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(l)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:t},e,r)=>{let n=Et(r);if(!n.trackApiCalls){await e(t);return}let s=new K,a=new Y(t,s,n);a.intercept(),J(s,a);try{await e(t);}finally{J(null,null);}try{let{apiCallsFile:o,apiCallsCount:i}=a.getFileData(),d=n.captureAssertions?s.getData():[],l={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:d,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:o,apiCallsCount:i};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(l)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};test.test.extend(Fn);Ie(test.expect);var oo={request:async({request:t},e,r)=>{let n=Et(r);if(!n.trackApiCalls){await e(t);return}let s=new K,a=new Y(t,s,n);a.intercept(),J(s,a);let o=null;try{o=new E("api-console");}catch{}let i=0,d=process.stdout.write,l=process.stderr.write;process.stdout.write=function(c,...f){try{let g=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!g.startsWith("[testrelic]")&&!g.startsWith("\u2139 TestRelic")&&!g.startsWith("\u2713 TestRelic")&&!g.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stdout",text:g.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return d.apply(process.stdout,[c,...f])},process.stderr.write=function(c,...f){try{let g=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!g.startsWith("[testrelic]")&&!g.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stderr",text:g.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return l.apply(process.stderr,[c,...f])};try{await e(t);}finally{process.stdout.write=d,process.stderr.write=l,J(null,null);}try{o?.close();let{apiCallsFile:c,apiCallsCount:f}=a.getFileData(),g=n.captureAssertions?s.getData():[],u={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:g,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:i>0?o?.getPath()??null:null,consoleLogsCount:i,apiCallsFile:c,apiCallsCount:f};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(u)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};var Dn="@testrelic/playwright-analytics";function co(t){return Array.isArray(t)?t.some(e=>Array.isArray(e)&&typeof e[0]=="string"&&e[0]===Dn):false}function uo(t,e){let n={video:"on",screenshot:"on",trace:"on",...t.use??{}},s;Array.isArray(t.reporter)?s=t.reporter:typeof t.reporter=="string"?s=[[t.reporter]]:s=[["list"]];let a=co(s)?s:[...s,[Dn,e??{}]];return test.defineConfig({...t,use:n,reporter:a})}var Bn=false;function Ac(t,e,r="manual_record"){if(!t||!t.annotations){Bn||(Bn=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
2670
+ `));return}let n={url:e,navigationType:r,timestamp:new Date().toISOString()};t.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}Object.defineProperty(exports,"ATTACHMENT_CONTENT_TYPE",{enumerable:true,get:function(){return core.ATTACHMENT_CONTENT_TYPE}});Object.defineProperty(exports,"ATTACHMENT_NAME",{enumerable:true,get:function(){return core.ATTACHMENT_NAME}});Object.defineProperty(exports,"PAYLOAD_VERSION",{enumerable:true,get:function(){return core.PAYLOAD_VERSION}});Object.defineProperty(exports,"isTestRelicDataPayload",{enumerable:true,get:function(){return core.isTestRelicDataPayload}});exports.SCHEMA_VERSION=de;exports.default=Ae;exports.defineConfig=uo;exports.recordNavigation=Ac;exports.testRelicApiFixture=oo;exports.testRelicFixture=Fn;//# sourceMappingURL=index.cjs.map
2617
2671
  //# sourceMappingURL=index.cjs.map