@testrelic/playwright-analytics 2.16.2 → 2.16.3-next.157
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/api-fixture.cjs +6 -5
- package/dist/api-fixture.cjs.map +1 -1
- package/dist/api-fixture.js +6 -5
- package/dist/api-fixture.js.map +1 -1
- package/dist/fixture.cjs +7 -6
- package/dist/fixture.cjs.map +1 -1
- package/dist/fixture.js +7 -6
- package/dist/fixture.js.map +1 -1
- package/dist/index.cjs +57 -52
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +57 -52
- package/dist/index.js.map +1 -1
- package/dist/reporter-entry.cjs +44 -40
- package/dist/reporter-entry.cjs.map +1 -1
- package/dist/reporter-entry.js +44 -40
- package/dist/reporter-entry.js.map +1 -1
- package/dist/visual.cjs +2 -2
- package/dist/visual.cjs.map +1 -1
- package/dist/visual.js +2 -2
- package/dist/visual.js.map +1 -1
- package/package.json +2 -2
package/dist/reporter-entry.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {randomUUID,createHash}from'crypto';import {writeFileSync,renameSync,mkdirSync,unlinkSync,existsSync,readFileSync,appendFileSync,readdirSync,statSync,openSync,readSync,closeSync,createReadStream,rmSync}from'fs';import {join,dirname,resolve,relative,extname,basename}from'path';import {tmpdir,platform}from'os';import {isValidConfig,createError,ErrorCode,ATTACHMENT_NAME,isTestRelicFilePayload,isTestRelicDataPayload,isValidEndpointUrl,isValidCloudConfig,isValidQueueEntry}from'@testrelic/core';import {spawn,execFile,execSync}from'child_process';import {createServer}from'http';import {createInterface}from'readline';import {copyFile}from'fs/promises';import {gzip}from'zlib';import {promisify}from'util';import {Readable}from'stream';var
|
|
2
|
-
`),false}}moveFile(t,r){try{renameSync(t,r);}catch{try{
|
|
3
|
-
`);}}}writeIndex(t){let r=join(this.reportDir,"index.json"),a=r+".tmp",n=JSON.stringify(t);writeFileSync(a,n,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeCompactIndex(t){let r=join(this.reportDir,"index-compact.json"),a=r+".tmp",n=t.map(({titlePath:l,project:i,...d})=>d),s=JSON.stringify(n);writeFileSync(a,s,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeSummary(t){let r=join(this.reportDir,"summary.json"),a=r+".tmp",n=JSON.stringify(t);writeFileSync(a,n,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeManifest(t){let r=join(this.reportDir,"manifest.json"),a=r+".tmp",n=JSON.stringify(t);writeFileSync(a,n,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var or=".testrelic",
|
|
4
|
-
`),n}catch{}let s=dirname(t);if(s===t)break;t=s;}return null}function dr(e){try{let t=readFileSync(e,"utf-8"),r=JSON.parse(t);return typeof r!="object"||r===null||Array.isArray(r)||!cr(r)?null:r}catch{return null}}function cr(e){for(let t of Object.keys(e)){if(
|
|
5
|
-
`);let c=e.queue;if(c&&typeof c=="object"){if(typeof c.maxAge=="string"){let f=ir(c.maxAge);f!==null&&(r.queueMaxAge=f);}typeof c.directory=="string"&&(r.queueDirectory=c.directory);}}if(t){if(typeof t.apiKey=="string"&&t.apiKey.length>0){let d=t.apiKey.startsWith("$")?ur(t.apiKey):t.apiKey;d&&(r.apiKey=d);}if(typeof t.endpoint=="string"&&(r.endpoint=t.endpoint),typeof t.upload=="string"&&(r.uploadStrategy=t.upload),typeof t.timeout=="number"&&(r.timeout=t.timeout),typeof t.uploadBudgetMs=="number"&&(r.uploadBudgetMs=t.uploadBudgetMs),typeof t.projectName=="string"&&(r.projectName=t.projectName),typeof t.queueMaxAge=="string"){let d=ir(t.queueMaxAge);d!==null&&(r.queueMaxAge=d);}typeof t.queueDirectory=="string"&&(r.queueDirectory=t.queueDirectory),typeof t.uploadArtifacts=="boolean"&&(r.uploadArtifacts=t.uploadArtifacts),typeof t.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=t.artifactMaxSizeMb);}let a=process.env.TESTRELIC_API_KEY;a&&a.length>0&&(r.apiKey=a);let n=process.env.TESTRELIC_CLOUD_ENDPOINT;n&&isValidEndpointUrl(n)&&(r.endpoint=n);let s=process.env.TESTRELIC_UPLOAD_STRATEGY;s&&["batch","realtime","both"].includes(s)&&(r.uploadStrategy=s);let l=process.env.TESTRELIC_CLOUD_TIMEOUT;if(l){let d=parseInt(l,10);!isNaN(d)&&d>=1e3&&d<=12e4&&(r.timeout=d);}let i=Object.freeze(r);return isValidCloudConfig(i)?i:sr}var
|
|
1
|
+
import {randomUUID,createHash}from'crypto';import {writeFileSync,renameSync,mkdirSync,copyFileSync,unlinkSync,existsSync,readFileSync,appendFileSync,readdirSync,statSync,openSync,readSync,closeSync,createReadStream,rmSync}from'fs';import {join,dirname,resolve,relative,extname,basename}from'path';import {tmpdir,platform}from'os';import {isValidConfig,createError,ErrorCode,ATTACHMENT_NAME,isTestRelicFilePayload,isTestRelicDataPayload,isValidEndpointUrl,isValidCloudConfig,isValidQueueEntry}from'@testrelic/core';import {spawn,execFile,execSync}from'child_process';import {createServer}from'http';import {createInterface}from'readline';import {copyFile}from'fs/promises';import {gzip}from'zlib';import {promisify}from'util';import {Readable}from'stream';var dn=".testrelic-report";function Be(e,t,r,a){let n=`${e}|${t.join("|")}|${r}|${a}`;return createHash("sha256").update(n).digest("hex").substring(0,12)}function Oe(e,t,r){let a=`${e}|${t.join("|")}|${r}`;return createHash("sha256").update(a).digest("hex").substring(0,12)}var ie=class{constructor(t){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=join(t,dn),this.testsDir=join(this.reportDir,"tests"),mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(t,r,a){try{let n=join(this.testsDir,t);mkdirSync(n,{recursive:!0});let s=join(n,"meta.json"),l=s+".tmp",i=JSON.stringify(r);return writeFileSync(l,i,"utf-8"),renameSync(l,s),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),a?.networkRequestsFile&&this.moveFile(a.networkRequestsFile,join(n,"network.jsonl")),a?.consoleLogsFile&&this.moveFile(a.consoleLogsFile,join(n,"console.jsonl")),a?.apiCallsFile&&this.moveFile(a.apiCallsFile,join(n,"api-calls.jsonl")),!0}catch(n){let s=n instanceof Error?n.message:String(n);return this.writeErrors.push({testId:t,error:s,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${t}: ${s}
|
|
2
|
+
`),false}}moveFile(t,r){try{renameSync(t,r);}catch{try{copyFileSync(t,r);try{unlinkSync(t);}catch{}}catch(a){process.stderr.write(`[testrelic] Failed to move file ${t} \u2192 ${r}: ${a instanceof Error?a.message:String(a)}
|
|
3
|
+
`);}}}writeIndex(t){let r=join(this.reportDir,"index.json"),a=r+".tmp",n=JSON.stringify(t);writeFileSync(a,n,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeCompactIndex(t){let r=join(this.reportDir,"index-compact.json"),a=r+".tmp",n=t.map(({titlePath:l,project:i,...d})=>d),s=JSON.stringify(n);writeFileSync(a,s,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeSummary(t){let r=join(this.reportDir,"summary.json"),a=r+".tmp",n=JSON.stringify(t);writeFileSync(a,n,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeManifest(t){let r=join(this.reportDir,"manifest.json"),a=r+".tmp",n=JSON.stringify(t);writeFileSync(a,n,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var or=".testrelic",hn="testrelic-config.json",mn=".testrelic",vn=5,bn=new Set(["__proto__","constructor","prototype"]),sr=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,uploadBudgetMs:12e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${or}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),yn={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function lr(e){let t=resolve(e);for(let r=0;r<=vn;r++){let a=join(t,or,hn);if(existsSync(a))try{if(statSync(a).isFile())return a}catch{}let n=join(t,mn);if(existsSync(n))try{if(statSync(n).isFile())return process.stderr.write(`[testrelic] Deprecation: config file ".testrelic" has moved to ".testrelic/testrelic-config.json". Please migrate your config file to the new location.
|
|
4
|
+
`),n}catch{}let s=dirname(t);if(s===t)break;t=s;}return null}function dr(e){try{let t=readFileSync(e,"utf-8"),r=JSON.parse(t);return typeof r!="object"||r===null||Array.isArray(r)||!cr(r)?null:r}catch{return null}}function cr(e){for(let t of Object.keys(e)){if(bn.has(t))return false;let r=e[t];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!cr(r))return false}return true}function ur(e){let t=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(e);if(t)return process.env[t[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(e);return r?process.env[r[1]]??null:e}function Ue(e){let t=Object.create(null);for(let r of Object.keys(e)){let a=e[r];typeof a=="string"&&a.startsWith("$")?t[r]=ur(a):typeof a=="object"&&a!==null&&!Array.isArray(a)?t[r]=Ue(a):t[r]=a;}return t}function ir(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let r=parseInt(t[1],10),a=t[2],n=yn[a];return !n||r<=0?null:r*n}function pr(e,t){let r=Object.create(null);if(Object.assign(r,sr),e){let d=e.cloud;d&&typeof d=="object"&&(typeof d.endpoint=="string"&&(r.endpoint=d.endpoint),typeof d.upload=="string"&&(r.uploadStrategy=d.upload),typeof d.timeout=="number"&&(r.timeout=d.timeout),typeof d.uploadBudgetMs=="number"&&(r.uploadBudgetMs=d.uploadBudgetMs),typeof d.apiKey=="string"&&d.apiKey.length>0&&(r.apiKey=d.apiKey));let o=e["testrelic-repo"]??e.project;o&&typeof o=="object"&&typeof o.name=="string"&&(r.projectName=o.name),e.project&&!e["testrelic-repo"]&&process.stderr.write(`[testrelic] Deprecation: "project" key in config is deprecated. Rename it to "testrelic-repo".
|
|
5
|
+
`);let c=e.queue;if(c&&typeof c=="object"){if(typeof c.maxAge=="string"){let f=ir(c.maxAge);f!==null&&(r.queueMaxAge=f);}typeof c.directory=="string"&&(r.queueDirectory=c.directory);}}if(t){if(typeof t.apiKey=="string"&&t.apiKey.length>0){let d=t.apiKey.startsWith("$")?ur(t.apiKey):t.apiKey;d&&(r.apiKey=d);}if(typeof t.endpoint=="string"&&(r.endpoint=t.endpoint),typeof t.upload=="string"&&(r.uploadStrategy=t.upload),typeof t.timeout=="number"&&(r.timeout=t.timeout),typeof t.uploadBudgetMs=="number"&&(r.uploadBudgetMs=t.uploadBudgetMs),typeof t.projectName=="string"&&(r.projectName=t.projectName),typeof t.queueMaxAge=="string"){let d=ir(t.queueMaxAge);d!==null&&(r.queueMaxAge=d);}typeof t.queueDirectory=="string"&&(r.queueDirectory=t.queueDirectory),typeof t.uploadArtifacts=="boolean"&&(r.uploadArtifacts=t.uploadArtifacts),typeof t.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=t.artifactMaxSizeMb);}let a=process.env.TESTRELIC_API_KEY;a&&a.length>0&&(r.apiKey=a);let n=process.env.TESTRELIC_CLOUD_ENDPOINT;n&&isValidEndpointUrl(n)&&(r.endpoint=n);let s=process.env.TESTRELIC_UPLOAD_STRATEGY;s&&["batch","realtime","both"].includes(s)&&(r.uploadStrategy=s);let l=process.env.TESTRELIC_CLOUD_TIMEOUT;if(l){let d=parseInt(l,10);!isNaN(d)&&d>=1e3&&d<=12e4&&(r.timeout=d);}let i=Object.freeze(r);return isValidCloudConfig(i)?i:sr}var Sn=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],Cn=["authorization","cookie","set-cookie","x-api-key"],Tn=["password","secret","token","apiKey","api_key"];function fr(e){let t=Object.create(null);return t.trackApiCalls=e?.trackApiCalls??true,t.captureRequestHeaders=e?.captureRequestHeaders??true,t.captureResponseHeaders=e?.captureResponseHeaders??true,t.captureRequestBody=e?.captureRequestBody??true,t.captureResponseBody=e?.captureResponseBody??true,t.captureAssertions=e?.captureAssertions??true,t.redactHeaders=e?.redactHeaders??[...Cn],t.redactBodyFields=e?.redactBodyFields??[...Tn],t.apiIncludeUrls=e?.apiIncludeUrls??[],t.apiExcludeUrls=e?.apiExcludeUrls??[],Object.freeze(t)}function gr(e){if(e!==void 0&&!isValidConfig(e))throw createError(ErrorCode.CONFIG_INVALID,"Invalid reporter configuration");let t=Object.create(null);t.outputPath=e?.outputPath??"./test-results/analytics-timeline.json",t.includeStackTrace=e?.includeStackTrace??false,t.includeCodeSnippets=e?.includeCodeSnippets??true,t.codeContextLines=e?.codeContextLines??3,t.includeNetworkStats=e?.includeNetworkStats??true,t.captureNavigation=e?.captureNavigation??true,t.navigationTypes=e?.navigationTypes??null,t.redactPatterns=[...Sn,...e?.redactPatterns??[]],t.testRunId=e?.testRunId??null,t.metadata=e?.metadata??null;let r=t.outputPath;t.openReport=e?.openReport??true,t.htmlReportPath=e?.htmlReportPath??r.replace(/\.json$/,".html"),t.includeArtifacts=e?.includeArtifacts??true,t.trackApiCalls=e?.trackApiCalls??true,t.quiet=e?.quiet??false,t.includeActionSteps=e?.includeActionSteps??true,t.captureConsoleLogs=e?.captureConsoleLogs??true;let a=lr(process.cwd()),n=a?dr(a):null,s=n?Ue(n):null,l=pr(s,e?.cloud);return t.cloud=l.apiKey?l:null,t.reportMode=e?.reportMode??"streaming",t.streamingThreshold=e?.streamingThreshold??0,Object.freeze(t)}var ze="1.8.0";function hr(e,t,r){try{let n=readFileSync(e,"utf-8").split(`
|
|
6
6
|
`);if(t<1||t>n.length)return null;let s=Math.max(1,t-r),l=Math.min(n.length,t+r),i=[];for(let d=s;d<=l;d++){let o=d===t?">":" ",c=String(d).padStart(String(l).length," ");i.push(`${o} ${c} | ${n[d-1]}`);}return i.join(`
|
|
7
|
-
`)}catch{return null}}function mr(e){return t=>{let r=t;for(let a of e)if(typeof a=="string"){let n=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(n,"g"),"[REDACTED]");}else {let n=a.flags.includes("g")?a.flags:a.flags+"g",s=new RegExp(a.source,n);r=r.replace(s,"[REDACTED]");}return r}}function
|
|
7
|
+
`)}catch{return null}}function mr(e){return t=>{let r=t;for(let a of e)if(typeof a=="string"){let n=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(n,"g"),"[REDACTED]");}else {let n=a.flags.includes("g")?a.flags:a.flags+"g",s=new RegExp(a.source,n);r=r.replace(s,"[REDACTED]");}return r}}function An(e){return e.GITHUB_ACTIONS!=="true"?null:{provider:"github-actions",buildId:e.GITHUB_RUN_ID??null,commitSha:e.GITHUB_SHA??null,branch:e.GITHUB_REF_NAME??null,runUrl:e.GITHUB_SERVER_URL&&e.GITHUB_REPOSITORY&&e.GITHUB_RUN_ID?`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`:null}}function _n(e){return e.GITLAB_CI!=="true"?null:{provider:"gitlab-ci",buildId:e.CI_PIPELINE_ID??null,commitSha:e.CI_COMMIT_SHA??null,branch:e.CI_COMMIT_BRANCH??e.CI_COMMIT_REF_NAME??null,runUrl:e.CI_PIPELINE_URL??null}}function In(e){if(!e.JENKINS_URL)return null;let t=e.GIT_BRANCH??null;return t?.startsWith("origin/")&&(t=t.slice(7)),{provider:"jenkins",buildId:e.BUILD_ID??null,commitSha:e.GIT_COMMIT??null,branch:t,runUrl:e.BUILD_URL??null}}function Mn(e){return e.CIRCLECI!=="true"?null:{provider:"circleci",buildId:e.CIRCLE_BUILD_NUM??null,commitSha:e.CIRCLE_SHA1??null,branch:e.CIRCLE_BRANCH??null,runUrl:e.CIRCLE_BUILD_URL??null}}function En(e){if(!e.BITBUCKET_PIPELINE_UUID)return null;let t=e.BITBUCKET_WORKSPACE&&e.BITBUCKET_REPO_SLUG&&e.BITBUCKET_PIPELINE_UUID?`https://bitbucket.org/${e.BITBUCKET_WORKSPACE}/${e.BITBUCKET_REPO_SLUG}/pipelines/results/${e.BITBUCKET_PIPELINE_UUID}`:null;return {provider:"bitbucket-pipelines",buildId:e.BITBUCKET_BUILD_NUMBER??null,commitSha:e.BITBUCKET_COMMIT??null,branch:e.BITBUCKET_BRANCH??null,runUrl:t}}var Pn=[An,_n,In,Mn,En];function U(e){let t=process.env;for(let r of Pn){let a=r(t);if(a)return a}return null}var He=`
|
|
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;
|
|
@@ -2888,6 +2888,10 @@ function _updateCard(cls,val){
|
|
|
2888
2888
|
/* Percentages of the capture box: the image may be rendered at any size. */
|
|
2889
2889
|
function domBoxStyle(rect,box){
|
|
2890
2890
|
if(!rect||!box||!box[2]||!box[3])return null;
|
|
2891
|
+
/* A degenerate rect draws a hairline that points at nothing. The platform
|
|
2892
|
+
and Studio drop it; this copy did not, which is exactly the kind of
|
|
2893
|
+
quiet divergence the shared vectors exist to catch. */
|
|
2894
|
+
if(rect[2]<=0||rect[3]<=0)return null;
|
|
2891
2895
|
var left=((rect[0]-box[0])/box[2])*100;
|
|
2892
2896
|
var top=((rect[1]-box[1])/box[3])*100;
|
|
2893
2897
|
var width=(rect[2]/box[2])*100;
|
|
@@ -3999,7 +4003,7 @@ function _updateCard(cls,val){
|
|
|
3999
4003
|
@media (max-width:1100px){
|
|
4000
4004
|
.tband-3,.tband-2{grid-template-columns:1fr}
|
|
4001
4005
|
}
|
|
4002
|
-
`;var
|
|
4006
|
+
`;var Ln=`
|
|
4003
4007
|
(function(){
|
|
4004
4008
|
var data=JSON.parse(document.getElementById('report-data').textContent);
|
|
4005
4009
|
${Ve}
|
|
@@ -4078,7 +4082,7 @@ ${""}
|
|
|
4078
4082
|
</aside>
|
|
4079
4083
|
<script id="report-data" type="application/json">${a}</script>
|
|
4080
4084
|
${n?`<script id="artifact-manifest-data" type="application/json">${n}</script>`:""}
|
|
4081
|
-
<script>${
|
|
4085
|
+
<script>${Ln}</script>
|
|
4082
4086
|
</body>
|
|
4083
4087
|
</html>`}function ot(e,t,r,a){let n=e.replace(/<\//g,"<\\/"),s=t.replace(/<\//g,"<\\/"),l=a?a.replace(/<\//g,"<\\/"):null,i={};try{i=JSON.parse(e);}catch{}let d=`{
|
|
4084
4088
|
"schemaVersion":"2.0",
|
|
@@ -4247,37 +4251,37 @@ ${l?`<script id="artifact-manifest-data" type="application/json">${l}</script>`:
|
|
|
4247
4251
|
<script>${o}</script>
|
|
4248
4252
|
</body>
|
|
4249
4253
|
</html>`}function lt(e){try{let t=process.platform,r,a;t==="darwin"?(r="open",a=[e]):t==="win32"?(r="cmd",a=["/c","start","",e]):(r="xdg-open",a=[e]),execFile(r,a,n=>{n&&process.stderr.write(`[testrelic] Failed to open browser: ${n.message}
|
|
4250
|
-
`);});}catch{}}join(tmpdir(),"testrelic-data");async function br(e,t,r,a){let n=(t-1)*r,s=[],l=0,i=createInterface({input:createReadStream(e,{encoding:"utf-8"}),crlfDelay:1/0});for await(let c of i)if(c.length!==0){if(l>=n&&s.length<r)try{s.push(JSON.parse(c));}catch{}if(l++,s.length>=r&&a!==void 0)break}let d=a??l,o=Math.max(1,Math.ceil(d/r));return {items:s,total:d,page:t,pageSize:r,totalPages:o}}var kr=/^[a-f0-9]{12}$/,ut=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Sr=500;function k(e,t,r){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(r));}function Cr(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type");}function he(e){try{return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):null}catch{return null}}function me(e){let t=0;try{let r=readdirSync(e,{withFileTypes:!0});for(let a of r){let n=join(e,a.name);a.isFile()?t+=statSync(n).size:a.isDirectory()&&(t+=me(n));}}catch{}return t}function Tr(e,t,r,a){let n=he(join(r,"index.json"));k(t,200,{status:"ok",reportMode:"streaming",testCount:n?.length??0,uptime:Math.floor((Date.now()-a)/1e3)});}function Rr(e,t,r){let a=he(join(r,"summary.json"));if(!a){k(t,404,{error:"Summary not found"});return}k(t,200,a);}function Ar(e,t,r){let a=he(join(r,"index.json"));if(!a){k(t,404,{error:"Test index not found"});return}let s=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,l=Math.max(1,parseInt(s.get("page")??"1",10)||1),i=Math.min(Sr,Math.max(1,parseInt(s.get("pageSize")??"100",10)||100)),d=s.get("status")?.split(",").filter(Boolean)??null,o=s.get("file")??null,c=s.get("search")?.toLowerCase()??null,f=s.get("tag")?.split(",").filter(Boolean)??null,v=s.get("sort")??"file",g=s.get("order")==="desc"?-1:1,p=a;d&&d.length>0&&(p=p.filter(y=>d.includes(y.status))),o&&(p=p.filter(y=>y.filePath===o||y.filePath.startsWith(o+"/"))),c&&(p=p.filter(y=>y.title.toLowerCase().includes(c)||y.filePath.toLowerCase().includes(c))),f&&f.length>0&&(p=p.filter(y=>f.some(w=>y.tags.includes(w)))),p=[...p].sort((y,w)=>{let C=0;switch(v){case "duration":C=y.duration-w.duration;break;case "status":C=y.status.localeCompare(w.status);break;case "title":C=y.title.localeCompare(w.title);break;default:C=y.filePath.localeCompare(w.filePath);break}return C*g});let m=p.length,u=Math.max(1,Math.ceil(m/i)),h=(l-1)*i,b=p.slice(h,h+i);k(t,200,{tests:b,pagination:{page:l,pageSize:i,totalItems:m,totalPages:u},filters:{status:d,file:o,search:c,tag:f}});}function _r(e,t,r,a){if(!kr.test(a)){k(t,400,{error:"Invalid test ID format"});return}let n=join(r,"tests",a,"meta.json"),s=join(r,"tests",`${a}.json`),l=existsSync(n)?n:existsSync(s)?s:null;if(!l){k(t,404,{error:`Test not found: ${a}`});return}try{let i=readFileSync(l,"utf-8");t.writeHead(200,{"Content-Type":"application/json"}),t.end(i);}catch(i){k(t,500,{error:i instanceof Error?i.message:String(i)});}}async function Ir(e,t,r,a,n){if(!kr.test(a)){k(t,400,{error:"Invalid test ID format"});return}let l=join(r,"tests",a,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[n]);if(!existsSync(l)){k(t,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let d=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,o=Math.max(1,parseInt(d.get("page")??"1",10)||1),c=Math.min(Sr,Math.max(1,parseInt(d.get("pageSize")??"50",10)||50)),f,v=join(r,"tests",a,"meta.json");if(existsSync(v))try{let p=JSON.parse(readFileSync(v,"utf-8"));switch(n){case "network":f=p.networkRequestsCount;break;case "console":f=p.consoleLogsCount;break;case "api-calls":f=p.apiCallsCount;break}}catch{}let g=await br(l,o,c,f);k(t,200,g);}catch(i){k(t,500,{error:i instanceof Error?i.message:String(i)});}}function Mr(e,t,r){let a=he(join(r,"index.json"));if(!a){k(t,404,{error:"Test index not found"});return}let n=new Map;for(let l of a){if(l.isRetry)continue;let i=n.get(l.filePath);switch(i||(i={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},n.set(l.filePath,i)),i.total++,l.status){case "passed":i.passed++;break;case "failed":i.failed++;break;case "flaky":i.flaky++;break;case "skipped":i.skipped++;break;case "timedout":i.timedOut++;break}}let s=Array.from(n.entries()).map(([l,i])=>({filePath:l,...i})).sort((l,i)=>l.filePath.localeCompare(i.filePath));k(t,200,{files:s});}function Er(e,t,r){if(!existsSync(r)){k(t,200,{runs:[],totalSizeBytes:0});return}try{let a=[],n=0,s=readdirSync(r,{withFileTypes:!0});for(let l of s){if(!l.isDirectory()||!ut.test(l.name))continue;let i=join(r,l.name),d=me(i),o=readdirSync(i,{withFileTypes:!0}).filter(c=>c.isDirectory());a.push({folderName:l.name,totalSizeBytes:d,testCount:o.length}),n+=d;}a.sort((l,i)=>i.folderName.localeCompare(l.folderName)),k(t,200,{runs:a,totalSizeBytes:n});}catch(a){k(t,500,{error:a instanceof Error?a.message:String(a)});}}function Pr(e,t,r){try{let a=0,n=0;if(existsSync(r)){let s=readdirSync(r,{withFileTypes:!0});for(let l of s){if(!l.isDirectory()||!ut.test(l.name))continue;let i=join(r,l.name),d=me(i);rmSync(i,{recursive:!0,force:!0}),n+=d,a++;}}k(t,200,{deletedCount:a,freedBytes:n});}catch(a){k(t,500,{error:a instanceof Error?a.message:String(a)});}}function Lr(e,t,r,a){if(!ut.test(a)){k(t,400,{error:"Invalid folder name"});return}let n=join(r,a);try{if(!statSync(n).isDirectory()){k(t,404,{error:"Not found"});return}}catch{k(t,404,{error:"Not found"});return}try{let s=me(n);rmSync(n,{recursive:!0,force:!0}),k(t,200,{deleted:a,freedBytes:s});}catch(s){k(t,500,{error:s instanceof Error?s.message:String(s)});}}function Dr(e,t,r){k(t,200,{status:"shutting_down"}),r.close();}function pt(e,t,r){if(!existsSync(r)){k(t,404,{error:"File not found"});return}try{let a=statSync(r).size,n=extname(r).toLowerCase(),s=Un[n]??"application/octet-stream",l=On(e.headers.range,a);if(l==="unsatisfiable"){t.writeHead(416,{"Content-Range":`bytes */${a}`,"Accept-Ranges":"bytes"}),t.end();return}if(l){t.writeHead(206,{"Content-Type":s,"Content-Length":l.end-l.start+1,"Content-Range":`bytes ${l.start}-${l.end}/${a}`,"Accept-Ranges":"bytes"}),xr(createReadStream(r,{start:l.start,end:l.end}),t);return}t.writeHead(200,{"Content-Type":s,"Content-Length":a,"Accept-Ranges":"bytes"}),xr(createReadStream(r),t);}catch(a){k(t,500,{error:a instanceof Error?a.message:String(a)});}}function xr(e,t){e.on("error",()=>{e.destroy(),t.destroy();}),t.on("close",()=>{e.destroy();}),e.pipe(t);}function On(e,t){if(!e)return null;let r=/^bytes=(\d*)-(\d*)$/.exec(e.trim());if(!r)return null;let[,a,n]=r;if(a===""&&n==="")return null;let s,l;if(a===""){let i=Number(n);if(i<=0)return "unsatisfiable";s=Math.max(0,t-i),l=t-1;}else s=Number(a),l=n===""?t-1:Math.min(Number(n),t-1);return !Number.isFinite(s)||!Number.isFinite(l)?null:t===0||s>=t||s>l?"unsatisfiable":{start:s,end:l}}var Un={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".json":"application/json",".html":"text/html",".css":"text/css",".js":"text/javascript",".svg":"image/svg+xml"};var $n=9323,Vn=10,jn=1800*1e3;function oe(e,t){return new Promise((r,a)=>{let n=t?.port??$n,s=Date.now(),l,i=0,d=existsSync(join(e,"artifacts"))?join(e,"artifacts"):existsSync(join(e,"..","artifacts"))?join(e,"..","artifacts"):join(e,"artifacts");function o(){clearTimeout(l),l=setTimeout(()=>{f.close();},jn);}let c=t?.htmlPath??null;if(!c){let g=dirname(e);try{let p=readdirSync(g).find(m=>m.endsWith(".html"));p&&(c=join(g,p));}catch{}}let f=createServer((g,p)=>{if(o(),Cr(p),g.method==="OPTIONS"){p.writeHead(204),p.end();return}let m;try{m=new URL(g.url??"/",`http://${g.headers.host??"localhost"}`).pathname;}catch{k(p,400,{error:"Invalid URL"});return}if(g.method==="GET"&&(m==="/"||m==="/index.html")){if(c&&existsSync(c)){pt(g,p,c);return}k(p,404,{error:"HTML report not found"});return}if(g.method==="GET"&&m==="/api/health"){Tr(g,p,e,s);return}if(g.method==="GET"&&m==="/api/summary"){Rr(g,p,e);return}if(g.method==="GET"&&m==="/api/tests"){Ar(g,p,e);return}if(g.method==="GET"&&m==="/api/files"){Mr(g,p,e);return}let u=m.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(g.method==="GET"&&u){Ir(g,p,e,u[1],u[2]);return}let h=m.match(/^\/api\/tests\/([a-f0-9]+)$/);if(g.method==="GET"&&h){_r(g,p,e,h[1]);return}if(g.method==="GET"&&m==="/api/artifacts"){Er(g,p,d);return}if(g.method==="DELETE"&&m==="/api/artifacts"){Pr(g,p,d);return}let b=m.match(/^\/api\/artifacts\/(.+)$/);if(g.method==="DELETE"&&b){Lr(g,p,d,decodeURIComponent(b[1]));return}if(g.method==="GET"&&m.startsWith("/artifacts/")){let y=decodeURIComponent(m.slice(11));if(y.includes("..")||y.includes("\0")){k(p,400,{error:"Invalid path"});return}pt(g,p,join(d,y));return}if(g.method==="POST"&&m==="/api/shutdown"){Dr(g,p,f);return}k(p,404,{error:"Not found"});});function v(g){let p=m=>{m.code==="EADDRINUSE"&&i<Vn?(i++,v(g+1)):a(m);};f.once("error",p),f.listen(g,"127.0.0.1",()=>{f.removeListener("error",p);let m=f.address();if(!m||typeof m=="string"){a(new Error("Failed to get server address"));return}o(),r({port:m.port,dispose:()=>new Promise(u=>{clearTimeout(l),f.close(()=>u());})});});}v(n);})}async function Nr(e){let t=await oe(e);return {port:t.port,dispose:t.dispose}}function Kn(e,t,r){let a=JSON.stringify(e),n=r?JSON.stringify(r):null;return vr(a,t,n)}async function gt(e,t,r){try{let a=null,n=null,s=t.reportMode==="streaming"||t.reportMode==="auto"&&e.timeline.length===0&&e.summary.total>=t.streamingThreshold,l,i=t.htmlReportPath,d=dirname(i);mkdirSync(d,{recursive:!0});let o="",c="[]",f=null;if(s){o=JSON.stringify({...e.summary,testRunId:e.testRunId,startedAt:e.startedAt,completedAt:e.completedAt,totalDuration:e.totalDuration,ci:e.ci,metadata:e.metadata,shardRunIds:e.shardRunIds});let g=dirname(t.outputPath),p=join(g,".testrelic-report");try{let m=join(p,"index-compact.json"),u=join(p,"index.json");existsSync(m)?c=readFileSync(m,"utf-8"):existsSync(u)&&(c=readFileSync(u,"utf-8"));}catch{}f=r?JSON.stringify(r):null,l=ot(o,c,null,f);}else l=Kn(e,null,r);let v=i+".tmp";if(writeFileSync(v,l,"utf-8"),renameSync(v,i),s){if(e.ci===null){let g=dirname(t.outputPath),p=join(g,".testrelic-report"),m=resolve(i);try{if(await Yn(),a=await Xn(p),!a){n=await oe(p,{htmlPath:m}),a=n.port;let u=setInterval(()=>{},6e4),h=()=>{clearInterval(u),n?.dispose();};process.on("SIGINT",h),process.on("SIGTERM",h),setTimeout(h,1800*1e3).unref();}if(a){process.stderr.write(`
|
|
4254
|
+
`);});}catch{}}join(tmpdir(),"testrelic-data");async function br(e,t,r,a){let n=(t-1)*r,s=[],l=0,i=createInterface({input:createReadStream(e,{encoding:"utf-8"}),crlfDelay:1/0});for await(let c of i)if(c.length!==0){if(l>=n&&s.length<r)try{s.push(JSON.parse(c));}catch{}if(l++,s.length>=r&&a!==void 0)break}let d=a??l,o=Math.max(1,Math.ceil(d/r));return {items:s,total:d,page:t,pageSize:r,totalPages:o}}var kr=/^[a-f0-9]{12}$/,ut=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Sr=500;function k(e,t,r){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(r));}function Cr(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type");}function he(e){try{return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):null}catch{return null}}function me(e){let t=0;try{let r=readdirSync(e,{withFileTypes:!0});for(let a of r){let n=join(e,a.name);a.isFile()?t+=statSync(n).size:a.isDirectory()&&(t+=me(n));}}catch{}return t}function Tr(e,t,r,a){let n=he(join(r,"index.json"));k(t,200,{status:"ok",reportMode:"streaming",testCount:n?.length??0,uptime:Math.floor((Date.now()-a)/1e3)});}function Rr(e,t,r){let a=he(join(r,"summary.json"));if(!a){k(t,404,{error:"Summary not found"});return}k(t,200,a);}function Ar(e,t,r){let a=he(join(r,"index.json"));if(!a){k(t,404,{error:"Test index not found"});return}let s=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,l=Math.max(1,parseInt(s.get("page")??"1",10)||1),i=Math.min(Sr,Math.max(1,parseInt(s.get("pageSize")??"100",10)||100)),d=s.get("status")?.split(",").filter(Boolean)??null,o=s.get("file")??null,c=s.get("search")?.toLowerCase()??null,f=s.get("tag")?.split(",").filter(Boolean)??null,v=s.get("sort")??"file",g=s.get("order")==="desc"?-1:1,p=a;d&&d.length>0&&(p=p.filter(y=>d.includes(y.status))),o&&(p=p.filter(y=>y.filePath===o||y.filePath.startsWith(o+"/"))),c&&(p=p.filter(y=>y.title.toLowerCase().includes(c)||y.filePath.toLowerCase().includes(c))),f&&f.length>0&&(p=p.filter(y=>f.some(w=>y.tags.includes(w)))),p=[...p].sort((y,w)=>{let C=0;switch(v){case "duration":C=y.duration-w.duration;break;case "status":C=y.status.localeCompare(w.status);break;case "title":C=y.title.localeCompare(w.title);break;default:C=y.filePath.localeCompare(w.filePath);break}return C*g});let m=p.length,u=Math.max(1,Math.ceil(m/i)),h=(l-1)*i,b=p.slice(h,h+i);k(t,200,{tests:b,pagination:{page:l,pageSize:i,totalItems:m,totalPages:u},filters:{status:d,file:o,search:c,tag:f}});}function _r(e,t,r,a){if(!kr.test(a)){k(t,400,{error:"Invalid test ID format"});return}let n=join(r,"tests",a,"meta.json"),s=join(r,"tests",`${a}.json`),l=existsSync(n)?n:existsSync(s)?s:null;if(!l){k(t,404,{error:`Test not found: ${a}`});return}try{let i=readFileSync(l,"utf-8");t.writeHead(200,{"Content-Type":"application/json"}),t.end(i);}catch(i){k(t,500,{error:i instanceof Error?i.message:String(i)});}}async function Ir(e,t,r,a,n){if(!kr.test(a)){k(t,400,{error:"Invalid test ID format"});return}let l=join(r,"tests",a,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[n]);if(!existsSync(l)){k(t,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let d=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,o=Math.max(1,parseInt(d.get("page")??"1",10)||1),c=Math.min(Sr,Math.max(1,parseInt(d.get("pageSize")??"50",10)||50)),f,v=join(r,"tests",a,"meta.json");if(existsSync(v))try{let p=JSON.parse(readFileSync(v,"utf-8"));switch(n){case "network":f=p.networkRequestsCount;break;case "console":f=p.consoleLogsCount;break;case "api-calls":f=p.apiCallsCount;break}}catch{}let g=await br(l,o,c,f);k(t,200,g);}catch(i){k(t,500,{error:i instanceof Error?i.message:String(i)});}}function Mr(e,t,r){let a=he(join(r,"index.json"));if(!a){k(t,404,{error:"Test index not found"});return}let n=new Map;for(let l of a){if(l.isRetry)continue;let i=n.get(l.filePath);switch(i||(i={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},n.set(l.filePath,i)),i.total++,l.status){case "passed":i.passed++;break;case "failed":i.failed++;break;case "flaky":i.flaky++;break;case "skipped":i.skipped++;break;case "timedout":i.timedOut++;break}}let s=Array.from(n.entries()).map(([l,i])=>({filePath:l,...i})).sort((l,i)=>l.filePath.localeCompare(i.filePath));k(t,200,{files:s});}function Er(e,t,r){if(!existsSync(r)){k(t,200,{runs:[],totalSizeBytes:0});return}try{let a=[],n=0,s=readdirSync(r,{withFileTypes:!0});for(let l of s){if(!l.isDirectory()||!ut.test(l.name))continue;let i=join(r,l.name),d=me(i),o=readdirSync(i,{withFileTypes:!0}).filter(c=>c.isDirectory());a.push({folderName:l.name,totalSizeBytes:d,testCount:o.length}),n+=d;}a.sort((l,i)=>i.folderName.localeCompare(l.folderName)),k(t,200,{runs:a,totalSizeBytes:n});}catch(a){k(t,500,{error:a instanceof Error?a.message:String(a)});}}function Pr(e,t,r){try{let a=0,n=0;if(existsSync(r)){let s=readdirSync(r,{withFileTypes:!0});for(let l of s){if(!l.isDirectory()||!ut.test(l.name))continue;let i=join(r,l.name),d=me(i);rmSync(i,{recursive:!0,force:!0}),n+=d,a++;}}k(t,200,{deletedCount:a,freedBytes:n});}catch(a){k(t,500,{error:a instanceof Error?a.message:String(a)});}}function Lr(e,t,r,a){if(!ut.test(a)){k(t,400,{error:"Invalid folder name"});return}let n=join(r,a);try{if(!statSync(n).isDirectory()){k(t,404,{error:"Not found"});return}}catch{k(t,404,{error:"Not found"});return}try{let s=me(n);rmSync(n,{recursive:!0,force:!0}),k(t,200,{deleted:a,freedBytes:s});}catch(s){k(t,500,{error:s instanceof Error?s.message:String(s)});}}function Dr(e,t,r){k(t,200,{status:"shutting_down"}),r.close();}function pt(e,t,r){if(!existsSync(r)){k(t,404,{error:"File not found"});return}try{let a=statSync(r).size,n=extname(r).toLowerCase(),s=Hn[n]??"application/octet-stream",l=zn(e.headers.range,a);if(l==="unsatisfiable"){t.writeHead(416,{"Content-Range":`bytes */${a}`,"Accept-Ranges":"bytes"}),t.end();return}if(l){t.writeHead(206,{"Content-Type":s,"Content-Length":l.end-l.start+1,"Content-Range":`bytes ${l.start}-${l.end}/${a}`,"Accept-Ranges":"bytes"}),xr(createReadStream(r,{start:l.start,end:l.end}),t);return}t.writeHead(200,{"Content-Type":s,"Content-Length":a,"Accept-Ranges":"bytes"}),xr(createReadStream(r),t);}catch(a){k(t,500,{error:a instanceof Error?a.message:String(a)});}}function xr(e,t){e.on("error",()=>{e.destroy(),t.destroy();}),t.on("close",()=>{e.destroy();}),e.pipe(t);}function zn(e,t){if(!e)return null;let r=/^bytes=(\d*)-(\d*)$/.exec(e.trim());if(!r)return null;let[,a,n]=r;if(a===""&&n==="")return null;let s,l;if(a===""){let i=Number(n);if(i<=0)return "unsatisfiable";s=Math.max(0,t-i),l=t-1;}else s=Number(a),l=n===""?t-1:Math.min(Number(n),t-1);return !Number.isFinite(s)||!Number.isFinite(l)?null:t===0||s>=t||s>l?"unsatisfiable":{start:s,end:l}}var Hn={".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 jn=9323,Gn=10,Wn=1800*1e3;function oe(e,t){return new Promise((r,a)=>{let n=t?.port??jn,s=Date.now(),l,i=0,d=existsSync(join(e,"artifacts"))?join(e,"artifacts"):existsSync(join(e,"..","artifacts"))?join(e,"..","artifacts"):join(e,"artifacts");function o(){clearTimeout(l),l=setTimeout(()=>{f.close();},Wn);}let c=t?.htmlPath??null;if(!c){let g=dirname(e);try{let p=readdirSync(g).find(m=>m.endsWith(".html"));p&&(c=join(g,p));}catch{}}let f=createServer((g,p)=>{if(o(),Cr(p),g.method==="OPTIONS"){p.writeHead(204),p.end();return}let m;try{m=new URL(g.url??"/",`http://${g.headers.host??"localhost"}`).pathname;}catch{k(p,400,{error:"Invalid URL"});return}if(g.method==="GET"&&(m==="/"||m==="/index.html")){if(c&&existsSync(c)){pt(g,p,c);return}k(p,404,{error:"HTML report not found"});return}if(g.method==="GET"&&m==="/api/health"){Tr(g,p,e,s);return}if(g.method==="GET"&&m==="/api/summary"){Rr(g,p,e);return}if(g.method==="GET"&&m==="/api/tests"){Ar(g,p,e);return}if(g.method==="GET"&&m==="/api/files"){Mr(g,p,e);return}let u=m.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(g.method==="GET"&&u){Ir(g,p,e,u[1],u[2]);return}let h=m.match(/^\/api\/tests\/([a-f0-9]+)$/);if(g.method==="GET"&&h){_r(g,p,e,h[1]);return}if(g.method==="GET"&&m==="/api/artifacts"){Er(g,p,d);return}if(g.method==="DELETE"&&m==="/api/artifacts"){Pr(g,p,d);return}let b=m.match(/^\/api\/artifacts\/(.+)$/);if(g.method==="DELETE"&&b){Lr(g,p,d,decodeURIComponent(b[1]));return}if(g.method==="GET"&&m.startsWith("/artifacts/")){let y=decodeURIComponent(m.slice(11));if(y.includes("..")||y.includes("\0")){k(p,400,{error:"Invalid path"});return}pt(g,p,join(d,y));return}if(g.method==="POST"&&m==="/api/shutdown"){Dr(g,p,f);return}k(p,404,{error:"Not found"});});function v(g){let p=m=>{m.code==="EADDRINUSE"&&i<Gn?(i++,v(g+1)):a(m);};f.once("error",p),f.listen(g,"127.0.0.1",()=>{f.removeListener("error",p);let m=f.address();if(!m||typeof m=="string"){a(new Error("Failed to get server address"));return}o(),r({port:m.port,dispose:()=>new Promise(u=>{clearTimeout(l),f.close(()=>u());})});});}v(n);})}async function Nr(e){let t=await oe(e);return {port:t.port,dispose:t.dispose}}function Yn(e,t,r){let a=JSON.stringify(e),n=r?JSON.stringify(r):null;return vr(a,t,n)}async function gt(e,t,r){try{let a=null,n=null,s=t.reportMode==="streaming"||t.reportMode==="auto"&&e.timeline.length===0&&e.summary.total>=t.streamingThreshold,l,i=t.htmlReportPath,d=dirname(i);mkdirSync(d,{recursive:!0});let o="",c="[]",f=null;if(s){o=JSON.stringify({...e.summary,testRunId:e.testRunId,startedAt:e.startedAt,completedAt:e.completedAt,totalDuration:e.totalDuration,ci:e.ci,metadata:e.metadata,shardRunIds:e.shardRunIds});let g=dirname(t.outputPath),p=join(g,".testrelic-report");try{let m=join(p,"index-compact.json"),u=join(p,"index.json");existsSync(m)?c=readFileSync(m,"utf-8"):existsSync(u)&&(c=readFileSync(u,"utf-8"));}catch{}f=r?JSON.stringify(r):null,l=ot(o,c,null,f);}else l=Yn(e,null,r);let v=i+".tmp";if(writeFileSync(v,l,"utf-8"),renameSync(v,i),s){if(e.ci===null){let g=dirname(t.outputPath),p=join(g,".testrelic-report"),m=resolve(i);try{if(await Zn(),a=await Qn(p),!a){n=await oe(p,{htmlPath:m}),a=n.port;let u=setInterval(()=>{},6e4),h=()=>{clearInterval(u),n?.dispose();};process.on("SIGINT",h),process.on("SIGTERM",h),setTimeout(h,1800*1e3).unref();}if(a){process.stderr.write(`
|
|
4251
4255
|
Report server: http://127.0.0.1:${a}
|
|
4252
4256
|
`);try{let u=ot(o,c,a,f),h=i+".tmp";writeFileSync(h,u,"utf-8"),renameSync(h,i);}catch{}}}catch{}}}else if(t.openReport&&e.ci===null&&t.includeArtifacts){let g=dirname(t.outputPath),p=join(g,"artifacts");if(existsSync(p))try{let m=await Nr(p);a=m.port,process.on("exit",()=>{m.dispose();});}catch{}}if(t.openReport&&e.ci===null)if(s&&a)lt(`http://127.0.0.1:${a}`);else {let g=resolve(i);lt(g);}}catch(a){process.stderr.write(`[testrelic] Failed to write HTML report: ${a instanceof Error?a.message:String(a)}
|
|
4253
|
-
`);}}var ye=9323,zr=10;async function Jn(){for(let e=ye;e<ye+zr;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),500),a=await fetch(`http://127.0.0.1:${e}/api/health`,{signal:t.signal});if(clearTimeout(r),a.ok)return e}catch{}return null}async function Yn(){for(let e=ye;e<ye+zr;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),1e3);await fetch(`http://127.0.0.1:${e}/api/shutdown`,{method:"POST",signal:t.signal}),clearTimeout(r);}catch{}await new Promise(e=>setTimeout(e,300));}async function Xn(e){let r=[join(__dirname,"cli.cjs"),join(__dirname,"cli.js"),join(__dirname,"..","dist","cli.cjs"),join(__dirname,"..","dist","cli.js")].find(a=>existsSync(a));if(!r){let a=await oe(e);return process.on("exit",()=>{a?.dispose();}),a.port}return new Promise(a=>{let n=spawn(process.execPath,[r,"serve",e],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),s="",l=false,i=setTimeout(()=>{l||(l=true,n.stderr?.removeAllListeners(),Jn().then(a));},5e3);n.stderr?.on("data",d=>{s+=d.toString();let o=s.match(/127\.0\.0\.1:(\d+)/);o&&!l&&(l=true,clearTimeout(i),n.stderr?.removeAllListeners(),n.unref(),a(Number(o[1])));}),n.on("error",()=>{l||(l=true,clearTimeout(i),a(null));}),n.on("exit",()=>{l||(l=true,clearTimeout(i),a(null));}),n.unref();})}var Hr=Buffer.from([137,80,78,71,13,10,26,10]),Zn=16,Qn=20,xe=24;function qr(e){if(e.length<xe||!e.subarray(0,Hr.length).equals(Hr))return null;let t=e.readUInt32BE(Zn),r=e.readUInt32BE(Qn);return t===0||r===0?null:{width:t,height:r}}var es=/(\d+) pixels \(ratio [\d.]+ of all image pixels\) are different/,$r=/Expected an image (\d+)px by (\d+)px, received (\d+)px by (\d+)px/;function Vr(e){return e?$r.test(e):false}var ts=/^\s*Snapshot:\s*(.+?)\s*$/m;function jr(e){if(!e)return {};let t={},r=es.exec(e);if(r){let s=Number.parseInt(r[1],10);Number.isFinite(s)&&(t.diffPixels=s);}let a=$r.exec(e);if(a){let[,s,l,i,d]=a,o=[s,l,i,d].map(c=>Number.parseInt(c,10));o.every(c=>Number.isFinite(c))&&(t.expectedWidth=o[0],t.expectedHeight=o[1],t.actualWidth=o[2],t.actualHeight=o[3]);}let n=ts.exec(e);return n&&(t.snapshotName=n[1]),t}function Gr(e,t){if(e===void 0||!t)return;let r=t.width*t.height;if(!(r<=0))return e/r}var ls=20,ht=0,mt=[];async function le(e,t){ht>=ls&&await new Promise(r=>mt.push(r)),ht++;try{return await copyFile(e,t),!0}catch{return false}finally{ht--,mt.length>0&&mt.shift()();}}var H=[];async function Kr(){H.length!==0&&(await Promise.allSettled(H),H.length=0);}function Jr(e){let t=new Date,r=s=>String(s).padStart(2,"0"),a=`${t.getFullYear()}-${r(t.getMonth()+1)}-${r(t.getDate())}T${r(t.getHours())}-${r(t.getMinutes())}-${r(t.getSeconds())}`;if(!existsSync(join(e,a)))return a;let n=1;for(;existsSync(join(e,`${a}-${n}`));)n++;return `${a}-${n}`}function vt(e){let t=e.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return t.length>100&&(t=t.substring(0,100).replace(/-+$/,"")),t||"unnamed-test"}var ds=8;function Yr(e,t,r){let a=vt(e),n=r?vt(r).substring(0,ds):"";return n&&(a+=`--${n}`),t>0&&(a+=`--retry-${t}`),a}function Xr(e,t,r,a,n,s){let l=e.find(p=>p.name==="screenshot"&&p.path),i=e.find(p=>p.name==="video"&&p.path),d=e.find(p=>p.name==="trace"&&p.path);if(!l&&!i&&!d)return null;let o=Yr(t,r,s),c=n?["artifacts",n,o]:["artifacts",o],f=join(a,...c),v=c,g={};try{mkdirSync(f,{recursive:!0});}catch{return null}if(l?.path&&existsSync(l.path)){let m=`screenshot${extname(l.path)||".png"}`,u=join(f,m);H.push(le(l.path,u).then(()=>{})),g.screenshot=`${v.join("/")}/${m}`;}if(i?.path&&existsSync(i.path)){let m=`video${extname(i.path)||".webm"}`,u=join(f,m);H.push(le(i.path,u).then(()=>{})),g.video=`${v.join("/")}/${m}`;}if(d?.path&&existsSync(d.path)){let m=`trace${extname(d.path)||".zip"}`,u=join(f,m);H.push(le(d.path,u).then(()=>{})),g.trace=`${v.join("/")}/${m}`;}return !g.screenshot&&!g.video&&!g.trace?null:g}var bt="visual",cs=6;function us(e){let t=createHash("sha256").update(e).digest("hex").substring(0,cs);return `${vt(e)}--${t}`}function Wr(e){let t=null;try{t=openSync(e,"r");let r=Buffer.alloc(xe),a=readSync(t,r,0,xe,0);return qr(r.subarray(0,a))}catch{return null}finally{if(t!==null)try{closeSync(t);}catch{}}}var ps=[{key:"expectedPath",dest:"baseline",field:"baseline"},{key:"actualPath",dest:"actual",field:"actual"},{key:"diffPath",dest:"diff",field:"diff"},{key:"previousPath",dest:"previous",field:"previous"}],fs=[{key:"baselineDomPath",dest:"baseline.dom.json",field:"baselineDom"},{key:"actualDomPath",dest:"actual.dom.json",field:"actualDom"}];function gs(e,t,r,a){let n=us(e.name),s=join(t,n);try{mkdirSync(s,{recursive:!0});}catch{return null}let l={},i=false;for(let g of ps){let p=e[g.key];if(!p||!existsSync(p))continue;let m=extname(p)||".png",u=`${g.dest}${m}`;H.push(le(p,join(s,u)).then(()=>{})),l[g.field]=`${r}/${bt}/${n}/${u}`,i=true;}let d=e.dom;if(d)for(let g of fs){let p=d[g.key];!p||!existsSync(p)||(H.push(le(p,join(s,g.dest)).then(()=>{})),l[g.field]=`${r}/${bt}/${n}/${g.dest}`);}if(!i)return null;let o=e.expectedPath?Wr(e.expectedPath):e.actualPath?Wr(e.actualPath):null,c=Gr(e.diffPixels,o),f=e.committedPath??e.expectedPath,v=f?relative(a,f).replace(/\\/g,"/"):void 0;return {name:e.name,status:e.status,source:e.source,...l,...v?{baselinePath:v}:{},...o?{width:o.width,height:o.height}:{},...e.actualWidth!==void 0?{actualWidth:e.actualWidth}:{},...e.actualHeight!==void 0?{actualHeight:e.actualHeight}:{},...e.diffPixels!==void 0?{diffPixels:e.diffPixels}:{},...c!==void 0?{diffPixelRatio:c}:{},...d?{domChanges:d.changes,domChangeCount:d.total,domRootCauses:d.rootCauses,domTruncated:d.truncated,domCaptureBox:d.captureBox}:{}}}function Zr(e,t,r,a,n,s,l=process.cwd()){if(e.length===0)return null;let i=Yr(t,r,s),d=n?["artifacts",n,i]:["artifacts",i],o=join(a,...d,bt),c=d.join("/");try{mkdirSync(o,{recursive:!0});}catch{return null}let f=[];for(let v of e){let g=gs(v,o,c,l);g&&f.push(g);}return f.length>0?f:null}var Qr="testrelic-visual-dom";var hs="testrelic-visual",ms=/^(.+)-(expected|actual|diff|previous)(\.[A-Za-z0-9]+)$/;function vs(e){let t=new Map;for(let r of e)if(!(r.name!==hs||!r.body))try{let a=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(a))continue;for(let n of a){let s=ys(n);s&&t.set(s.stem,s);}}catch{}return t}var bs=["passed","failed","new","updated"];function ys(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.stem!="string"||!t.stem||typeof t.name!="string"||!t.name||typeof t.status!="string"||!bs.includes(t.status)?null:{stem:t.stem,name:t.name,status:t.status,...typeof t.committedPath=="string"&&t.committedPath?{committedPath:t.committedPath}:{}}}function xs(e){let t=new Map;for(let r of e)if(!(r.name!==Qr||!r.body))try{let a=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(a))continue;for(let n of a){if(typeof n!="object"||n===null)continue;let s=n;typeof s.stem!="string"||!Array.isArray(s.changes)||t.set(s.stem,n);}}catch{}return t}function ws(e){let t=new Map;for(let r of e){if(!r.path)continue;let a=ms.exec(r.name);if(!a)continue;let[,n,s]=a,l=t.get(n)??{};l[s]=r.path,t.set(n,l);}return t}function ks(e){return !!(e.actual&&(e.expected||e.diff))}function Ss(e,t,r){return e.diff||Vr(r)?"failed":t?"updated":"new"}function Cs(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;let r=t.replace(/\.[A-Za-z0-9]+$/,""),a=e.filter(n=>n===r||n.endsWith(`/${r}`));return a.length===1?a[0]:null}function ta(e,t={}){if(e.length===0)return [];let r=vs(e),a=xs(e),n=ws(e);if(n.size===0)return [];let s=t.updatingSnapshots===true,l=[];for(let[i,d]of n){let o=r.get(i);!o&&!ks(d)||l.push({name:o?.name??i,status:o?.status??Ss(d,s,t.failureMessage),source:o?"toMatchVisualBaseline":"toHaveScreenshot",...d.expected?{expectedPath:d.expected}:{},...o?.committedPath?{committedPath:o.committedPath}:{},...d.actual?{actualPath:d.actual}:{},...d.diff?{diffPath:d.diff}:{},...d.previous?{previousPath:d.previous}:{},...a.has(i)?{dom:a.get(i)}:{}});}return Ts(l,n,t.failureMessage)}function Ts(e,t,r){let a=jr(r);if(a.diffPixels===void 0&&a.actualWidth===void 0)return [...e];let n=e.filter(l=>l.status==="failed").map(l=>ea(l,t)),s=Cs(n,a.snapshotName);return s===null?[...e]:e.map(l=>ea(l,t)===s?{...l,...a.diffPixels!==void 0?{diffPixels:a.diffPixels}:{},...a.actualWidth!==void 0?{actualWidth:a.actualWidth}:{},...a.actualHeight!==void 0?{actualHeight:a.actualHeight}:{}}:l)}function ea(e,t){if(t.has(e.name))return e.name;for(let[r,a]of t)if(a.actual===e.actualPath&&a.expected===e.expectedPath&&a.diff===e.diffPath)return r;return e.name}var Rs=new RegExp("[\x1B\x9B][[\\]()#;?]*(?:\\d{1,4}(?:;\\d{0,4})*)?[0-9A-PR-TZcf-nqry=><]","g");function ke(e){return !e||e.indexOf("\x1B")===-1&&e.indexOf("\x9B")===-1?e:e.replace(Rs,"")}function ra(e){return e==null?null:ke(e)}var As=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,_s="1.0",xt="visual";function ia(e){let t=extname(e).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(t)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(t)?"video":t===".zip"&&basename(e,t)==="trace"?"trace":"other"}function Is(e){if(e.endsWith(".dom.json"))return "dom";let t=basename(e,extname(e));return t==="baseline"?"baseline":t==="diff"?"diff":ia(e)}function Ms(e,t,r){let a=[];try{for(let n of readdirSync(e,{withFileTypes:!0})){if(!n.isFile())continue;let s=statSync(join(e,n.name));a.push({name:`${xt}/${r}/${n.name}`,type:Is(n.name),relativePath:`${t}/${xt}/${r}/${n.name}`,sizeBytes:s.size});}}catch{}return a}function oa(e,t,r){let a=[],n=`artifacts/${t}/${r}`;try{let s=readdirSync(e,{withFileTypes:!0});for(let l of s){if(l.isDirectory()&&l.name===xt){let o=join(e,l.name);for(let c of readdirSync(o,{withFileTypes:!0}))c.isDirectory()&&a.push(...Ms(join(o,c.name),n,c.name));continue}if(!l.isFile())continue;let i=join(e,l.name),d=statSync(i);a.push({name:l.name,type:ia(l.name),relativePath:`${n}/${l.name}`,sizeBytes:d.size});}}catch{}return {testName:r,files:a}}function Es(e,t){let r=join(e,t),a=[],n=0;try{let l=readdirSync(r,{withFileTypes:!0});for(let i of l){if(!i.isDirectory())continue;let d=oa(join(r,i.name),t,i.name);a.push(d);for(let o of d.files)n+=o.sizeBytes;}}catch{}let s=t.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return a.sort((l,i)=>l.testName.localeCompare(i.testName)),{folderName:t,timestamp:s,totalSizeBytes:n,testCount:a.length,tests:a,isCurrentRun:false}}function la(e,t){let r=join(e,"artifacts"),a=[],n=[],s=0;try{let i=readdirSync(r,{withFileTypes:!0});for(let d of i)if(d.isDirectory())if(As.test(d.name)){let o=Es(r,d.name);a.push({...o,isCurrentRun:d.name===t});}else {let o=oa(join(r,d.name),d.name,d.name);n.push(o);for(let c of o.files)s+=c.sizeBytes;}}catch{}a.sort((i,d)=>d.timestamp.localeCompare(i.timestamp)),n.length>0&&(n.sort((i,d)=>i.testName.localeCompare(d.testName)),a.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}));let l=a.reduce((i,d)=>i+d.totalSizeBytes,0);return {schemaVersion:_s,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:l,runs:a,serverPort:null}}var Bs=256;function Os(e){let t=resolve(e);for(let r=0;r<Bs;r++){if(existsSync(join(t,".git")))return t;let a=dirname(t);if(a===t)return null;t=a;}return null}function ua(e){try{let t=Os(e);if(!t)return;let r=join(t,".gitignore"),a=relative(t,e).replace(/\\/g,"/"),n=a.endsWith("/")?a:`${a}/`;if(existsSync(r)&&readFileSync(r,"utf-8").split(`
|
|
4257
|
+
`);}}var ye=9323,zr=10;async function Xn(){for(let e=ye;e<ye+zr;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),500),a=await fetch(`http://127.0.0.1:${e}/api/health`,{signal:t.signal});if(clearTimeout(r),a.ok)return e}catch{}return null}async function Zn(){for(let e=ye;e<ye+zr;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),1e3);await fetch(`http://127.0.0.1:${e}/api/shutdown`,{method:"POST",signal:t.signal}),clearTimeout(r);}catch{}await new Promise(e=>setTimeout(e,300));}async function Qn(e){let r=[join(__dirname,"cli.cjs"),join(__dirname,"cli.js"),join(__dirname,"..","dist","cli.cjs"),join(__dirname,"..","dist","cli.js")].find(a=>existsSync(a));if(!r){let a=await oe(e);return process.on("exit",()=>{a?.dispose();}),a.port}return new Promise(a=>{let n=spawn(process.execPath,[r,"serve",e],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),s="",l=false,i=setTimeout(()=>{l||(l=true,n.stderr?.removeAllListeners(),Xn().then(a));},5e3);n.stderr?.on("data",d=>{s+=d.toString();let o=s.match(/127\.0\.0\.1:(\d+)/);o&&!l&&(l=true,clearTimeout(i),n.stderr?.removeAllListeners(),n.unref(),a(Number(o[1])));}),n.on("error",()=>{l||(l=true,clearTimeout(i),a(null));}),n.on("exit",()=>{l||(l=true,clearTimeout(i),a(null));}),n.unref();})}var Hr=Buffer.from([137,80,78,71,13,10,26,10]),es=16,ts=20,xe=24;function qr(e){if(e.length<xe||!e.subarray(0,Hr.length).equals(Hr))return null;let t=e.readUInt32BE(es),r=e.readUInt32BE(ts);return t===0||r===0?null:{width:t,height:r}}var rs=/(\d+) pixels \(ratio [\d.]+ of all image pixels\) are different/,$r=/Expected an image (\d+)px by (\d+)px, received (\d+)px by (\d+)px/;function Vr(e){return e?$r.test(e):false}var as=/^\s*Snapshot:\s*(.+?)\s*$/m;function jr(e){if(!e)return {};let t={},r=rs.exec(e);if(r){let s=Number.parseInt(r[1],10);Number.isFinite(s)&&(t.diffPixels=s);}let a=$r.exec(e);if(a){let[,s,l,i,d]=a,o=[s,l,i,d].map(c=>Number.parseInt(c,10));o.every(c=>Number.isFinite(c))&&(t.expectedWidth=o[0],t.expectedHeight=o[1],t.actualWidth=o[2],t.actualHeight=o[3]);}let n=as.exec(e);return n&&(t.snapshotName=n[1]),t}function Gr(e,t){if(e===void 0||!t)return;let r=t.width*t.height;if(!(r<=0))return e/r}var cs=20,ht=0,mt=[];async function le(e,t){ht>=cs&&await new Promise(r=>mt.push(r)),ht++;try{return await copyFile(e,t),!0}catch{return false}finally{ht--,mt.length>0&&mt.shift()();}}var H=[];async function Jr(){H.length!==0&&(await Promise.allSettled(H),H.length=0);}function Yr(e){let t=new Date,r=s=>String(s).padStart(2,"0"),a=`${t.getFullYear()}-${r(t.getMonth()+1)}-${r(t.getDate())}T${r(t.getHours())}-${r(t.getMinutes())}-${r(t.getSeconds())}`;if(!existsSync(join(e,a)))return a;let n=1;for(;existsSync(join(e,`${a}-${n}`));)n++;return `${a}-${n}`}function vt(e){let t=e.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return t.length>100&&(t=t.substring(0,100).replace(/-+$/,"")),t||"unnamed-test"}var us=8;function Xr(e,t,r){let a=vt(e),n=r?vt(r).substring(0,us):"";return n&&(a+=`--${n}`),t>0&&(a+=`--retry-${t}`),a}function Zr(e,t,r,a,n,s){let l=e.find(p=>p.name==="screenshot"&&p.path),i=e.find(p=>p.name==="video"&&p.path),d=e.find(p=>p.name==="trace"&&p.path);if(!l&&!i&&!d)return null;let o=Xr(t,r,s),c=n?["artifacts",n,o]:["artifacts",o],f=join(a,...c),v=c,g={};try{mkdirSync(f,{recursive:!0});}catch{return null}if(l?.path&&existsSync(l.path)){let m=`screenshot${extname(l.path)||".png"}`,u=join(f,m);H.push(le(l.path,u).then(()=>{})),g.screenshot=`${v.join("/")}/${m}`;}if(i?.path&&existsSync(i.path)){let m=`video${extname(i.path)||".webm"}`,u=join(f,m);H.push(le(i.path,u).then(()=>{})),g.video=`${v.join("/")}/${m}`;}if(d?.path&&existsSync(d.path)){let m=`trace${extname(d.path)||".zip"}`,u=join(f,m);H.push(le(d.path,u).then(()=>{})),g.trace=`${v.join("/")}/${m}`;}return !g.screenshot&&!g.video&&!g.trace?null:g}var bt="visual",ps=6;function fs(e){let t=createHash("sha256").update(e).digest("hex").substring(0,ps);return `${vt(e)}--${t}`}function Wr(e){let t=null;try{t=openSync(e,"r");let r=Buffer.alloc(xe),a=readSync(t,r,0,xe,0);return qr(r.subarray(0,a))}catch{return null}finally{if(t!==null)try{closeSync(t);}catch{}}}var Kr=[{key:"expectedPath",dest:"baseline",field:"baseline"},{key:"actualPath",dest:"actual",field:"actual"},{key:"diffPath",dest:"diff",field:"diff"},{key:"previousPath",dest:"previous",field:"previous"}],gs=[{key:"baselineDomPath",dest:"baseline.dom.json",field:"baselineDom"},{key:"actualDomPath",dest:"actual.dom.json",field:"actualDom"}];function hs(e,t,r,a){let n=fs(e.name),s=join(t,n),l=Kr.some(p=>e[p.key]);if(l||e.dom)try{mkdirSync(s,{recursive:!0});}catch{return null}let i={},d=false;for(let p of Kr){let m=e[p.key];if(!m||!existsSync(m))continue;let u=extname(m)||".png",h=`${p.dest}${u}`;H.push(le(m,join(s,h)).then(()=>{})),i[p.field]=`${r}/${bt}/${n}/${h}`,d=true;}let o=e.dom;if(o)for(let p of gs){let m=o[p.key];!m||!existsSync(m)||(H.push(le(m,join(s,p.dest)).then(()=>{})),i[p.field]=`${r}/${bt}/${n}/${p.dest}`);}if(!d&&l)return null;let c=e.expectedPath?Wr(e.expectedPath):e.actualPath?Wr(e.actualPath):null,f=Gr(e.diffPixels,c),v=e.committedPath??e.expectedPath,g=v?relative(a,v).replace(/\\/g,"/"):void 0;return {name:e.name,status:e.status,source:e.source,...i,...g?{baselinePath:g}:{},...c?{width:c.width,height:c.height}:{},...e.actualWidth!==void 0?{actualWidth:e.actualWidth}:{},...e.actualHeight!==void 0?{actualHeight:e.actualHeight}:{},...e.diffPixels!==void 0?{diffPixels:e.diffPixels}:{},...f!==void 0?{diffPixelRatio:f}:{},...o?{domChanges:o.changes,domChangeCount:o.total,domRootCauses:o.rootCauses,domTruncated:o.truncated,domCaptureBox:o.captureBox}:{}}}function Qr(e,t,r,a,n,s,l=process.cwd()){if(e.length===0)return null;let i=Xr(t,r,s),d=n?["artifacts",n,i]:["artifacts",i],o=join(a,...d,bt),c=d.join("/");try{mkdirSync(o,{recursive:!0});}catch{return null}let f=[];for(let v of e){let g=hs(v,o,c,l);g&&f.push(g);}return f.length>0?f:null}var ea="testrelic-visual-dom";var ms="testrelic-visual",vs=/^(.+)-(expected|actual|diff|previous)(\.[A-Za-z0-9]+)$/;function bs(e){let t=new Map;for(let r of e)if(!(r.name!==ms||!r.body))try{let a=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(a))continue;for(let n of a){let s=xs(n);s&&t.set(s.stem,s);}}catch{}return t}var ys=["passed","failed","new","updated"];function xs(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.stem!="string"||!t.stem||typeof t.name!="string"||!t.name||typeof t.status!="string"||!ys.includes(t.status)?null:{stem:t.stem,name:t.name,status:t.status,...typeof t.committedPath=="string"&&t.committedPath?{committedPath:t.committedPath}:{}}}function ws(e){let t=new Map;for(let r of e)if(!(r.name!==ea||!r.body))try{let a=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(a))continue;for(let n of a){if(typeof n!="object"||n===null)continue;let s=n;typeof s.stem!="string"||!Array.isArray(s.changes)||t.set(s.stem,n);}}catch{}return t}function ks(e){let t=new Map;for(let r of e){if(!r.path)continue;let a=vs.exec(r.name);if(!a)continue;let[,n,s]=a,l=t.get(n)??{};l[s]=r.path,t.set(n,l);}return t}function Ss(e){return !!(e.actual&&(e.expected||e.diff))}function Cs(e,t,r){return e.diff||Vr(r)?"failed":t?"updated":"new"}function Ts(e,t){if(e.length===0)return null;if(e.length===1)return e[0];if(!t)return null;let r=t.replace(/\.[A-Za-z0-9]+$/,""),a=e.filter(n=>n===r||n.endsWith(`/${r}`));return a.length===1?a[0]:null}function aa(e,t={}){if(e.length===0)return [];let r=bs(e),a=ws(e),n=ks(e);if(n.size===0&&r.size===0)return [];let s=t.updatingSnapshots===true,l=[];for(let[i,d]of n){let o=r.get(i);!o&&!Ss(d)||l.push({name:o?.name??i,status:o?.status??Cs(d,s,t.failureMessage),source:o?"toMatchVisualBaseline":"toHaveScreenshot",...d.expected?{expectedPath:d.expected}:{},...o?.committedPath?{committedPath:o.committedPath}:{},...d.actual?{actualPath:d.actual}:{},...d.diff?{diffPath:d.diff}:{},...d.previous?{previousPath:d.previous}:{},...a.has(i)?{dom:a.get(i)}:{}});}for(let[i,d]of r)n.has(i)||l.push({name:d.name,status:d.status,source:"toMatchVisualBaseline",...d.committedPath?{committedPath:d.committedPath}:{},...a.has(i)?{dom:a.get(i)}:{}});return Rs(l,n,t.failureMessage)}function Rs(e,t,r){let a=jr(r);if(a.diffPixels===void 0&&a.actualWidth===void 0)return [...e];let n=e.filter(l=>l.status==="failed"&&ta(l)).map(l=>ra(l,t)),s=Ts(n,a.snapshotName);return s===null?[...e]:e.map(l=>ta(l)&&ra(l,t)===s?{...l,...a.diffPixels!==void 0?{diffPixels:a.diffPixels}:{},...a.actualWidth!==void 0?{actualWidth:a.actualWidth}:{},...a.actualHeight!==void 0?{actualHeight:a.actualHeight}:{}}:l)}function ta(e){return !!(e.expectedPath||e.actualPath||e.diffPath||e.previousPath)}function ra(e,t){if(t.has(e.name))return e.name;for(let[r,a]of t)if(a.actual===e.actualPath&&a.expected===e.expectedPath&&a.diff===e.diffPath)return r;return e.name}var As=new RegExp("[\x1B\x9B][[\\]()#;?]*(?:\\d{1,4}(?:;\\d{0,4})*)?[0-9A-PR-TZcf-nqry=><]","g");function ke(e){return !e||e.indexOf("\x1B")===-1&&e.indexOf("\x9B")===-1?e:e.replace(As,"")}function na(e){return e==null?null:ke(e)}var _s=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Is="1.0",xt="visual";function la(e){let t=extname(e).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(t)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(t)?"video":t===".zip"&&basename(e,t)==="trace"?"trace":"other"}function Ms(e){if(e.endsWith(".dom.json"))return "dom";let t=basename(e,extname(e));return t==="baseline"?"baseline":t==="diff"?"diff":la(e)}function Es(e,t,r){let a=[];try{for(let n of readdirSync(e,{withFileTypes:!0})){if(!n.isFile())continue;let s=statSync(join(e,n.name));a.push({name:`${xt}/${r}/${n.name}`,type:Ms(n.name),relativePath:`${t}/${xt}/${r}/${n.name}`,sizeBytes:s.size});}}catch{}return a}function da(e,t,r){let a=[],n=`artifacts/${t}/${r}`;try{let s=readdirSync(e,{withFileTypes:!0});for(let l of s){if(l.isDirectory()&&l.name===xt){let o=join(e,l.name);for(let c of readdirSync(o,{withFileTypes:!0}))c.isDirectory()&&a.push(...Es(join(o,c.name),n,c.name));continue}if(!l.isFile())continue;let i=join(e,l.name),d=statSync(i);a.push({name:l.name,type:la(l.name),relativePath:`${n}/${l.name}`,sizeBytes:d.size});}}catch{}return {testName:r,files:a}}function Ps(e,t){let r=join(e,t),a=[],n=0;try{let l=readdirSync(r,{withFileTypes:!0});for(let i of l){if(!i.isDirectory())continue;let d=da(join(r,i.name),t,i.name);a.push(d);for(let o of d.files)n+=o.sizeBytes;}}catch{}let s=t.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return a.sort((l,i)=>l.testName.localeCompare(i.testName)),{folderName:t,timestamp:s,totalSizeBytes:n,testCount:a.length,tests:a,isCurrentRun:false}}function ca(e,t){let r=join(e,"artifacts"),a=[],n=[],s=0;try{let i=readdirSync(r,{withFileTypes:!0});for(let d of i)if(d.isDirectory())if(_s.test(d.name)){let o=Ps(r,d.name);a.push({...o,isCurrentRun:d.name===t});}else {let o=da(join(r,d.name),d.name,d.name);n.push(o);for(let c of o.files)s+=c.sizeBytes;}}catch{}a.sort((i,d)=>d.timestamp.localeCompare(i.timestamp)),n.length>0&&(n.sort((i,d)=>i.testName.localeCompare(d.testName)),a.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}));let l=a.reduce((i,d)=>i+d.totalSizeBytes,0);return {schemaVersion:Is,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:l,runs:a,serverPort:null}}var Os=256;function Us(e){let t=resolve(e);for(let r=0;r<Os;r++){if(existsSync(join(t,".git")))return t;let a=dirname(t);if(a===t)return null;t=a;}return null}function fa(e){try{let t=Us(e);if(!t)return;let r=join(t,".gitignore"),a=relative(t,e).replace(/\\/g,"/"),n=a.endsWith("/")?a:`${a}/`;if(existsSync(r)&&readFileSync(r,"utf-8").split(`
|
|
4254
4258
|
`).map(d=>d.trim()).some(d=>d===n||d===a))return;let s=`
|
|
4255
4259
|
# TestRelic test artifacts
|
|
4256
4260
|
${n}
|
|
4257
|
-
`;appendFileSync(r,s,"utf-8");}catch{}}var
|
|
4261
|
+
`;appendFileSync(r,s,"utf-8");}catch{}}var ga=Symbol("testrelic.timeout"),ha=3e4,wt=12e4,kt=6e4,ma=15e3;async function J(e,t,r){let a,n=new Promise(s=>{a=setTimeout(()=>s(ga),t),typeof a?.unref=="function"&&a.unref();});try{let s=await Promise.race([e(),n]);if(s===ga){process.stderr.write(`[testrelic] ${r} timed out after ${Math.round(t/1e3)}s \u2014 continuing without it. Your tests are unaffected.
|
|
4258
4262
|
`);return}return s}catch(s){process.stderr.write(`[testrelic] ${r} failed \u2014 continuing without it. Your tests are unaffected. (${s instanceof Error?s.message:String(s)})
|
|
4259
|
-
`);return}finally{a&&clearTimeout(a);}}function
|
|
4263
|
+
`);return}finally{a&&clearTimeout(a);}}function ya(e,t){let r=[];for(let a of e){let n=zs(a),s=Hs(a),l=qs(a,n,s,t),i=$s(a,n,s);if(l.length===0&&i.length===0){r.push({type:"navigation",url:"about:blank",timestamp:a.startedAt,durationOnUrl:a.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:a.specFile,test:n,tests:[s],_testTitle:a.title});continue}r.push(...l,...i);}return r.sort(Vs),js(r,e),r.map((a,n)=>a.type==="navigation"?{...{index:n,type:"navigation",url:a.url,timestamp:a.timestamp,durationOnUrl:a.durationOnUrl??0,navigationType:a.navigationType,domContentLoadedAt:a.domContentLoadedAt??null,networkIdleAt:a.networkIdleAt??null,networkStats:a.networkStats??null,specFile:a.specFile,test:a.test},tests:a.tests}:{...{index:n,type:"api_call",callId:a.callId,method:a.method,url:a.url,timestamp:a.timestamp,responseTime:a.responseTime??null,request:a.request,response:a.response??null,...a.error?{error:a.error}:{},assertions:a.assertions??[],specFile:a.specFile,test:a.test},tests:a.tests})}function zs(e){return {title:e.title,fullTitle:e.titlePath,status:e.status,duration:e.duration,retries:e.retryCount,retry:e.retry,tags:e.tags,failure:e.failure}}function Hs(e){return {title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,retryStatus:e.retryStatus,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,networkRequests:e.networkRequests,apiCalls:e.apiCalls,apiAssertions:e.apiAssertions,actions:e.actions,consoleLogs:e.consoleLogs}}function qs(e,t,r,a){let n=[];for(let s of e.navigations)a.navigationTypes!==null&&!a.navigationTypes.includes(s.navigationType)||n.push({type:"navigation",url:s.url,timestamp:s.timestamp,durationOnUrl:0,navigationType:s.navigationType,domContentLoadedAt:s.domContentLoadedAt??null,networkIdleAt:s.networkIdleAt??null,networkStats:s.networkStats??null,specFile:e.specFile,test:t,tests:[r],_testTitle:e.title});return n}function $s(e,t,r){if(!e.apiCalls||e.apiCalls.length===0)return [];let a=e.apiAssertions??[];return e.apiCalls.map(n=>{let s=a.filter(i=>i.callId===n.id).map(i=>({type:i.type,expected:i.expected,actual:i.actual,status:i.status,location:i.location,...i.expression!==void 0?{expression:i.expression}:{}})),l=null;return n.responseStatusCode!==null&&n.responseStatusText!==null&&(l={statusCode:n.responseStatusCode,statusText:n.responseStatusText,headers:n.responseHeaders,body:ba(n.responseBody)}),{type:"api_call",callId:n.id,method:n.method,url:n.url,timestamp:n.timestamp,responseTime:n.error?null:n.responseTimeMs,request:{headers:n.requestHeaders,body:ba(n.requestBody)},response:l,...n.error?{error:n.error}:{},assertions:s,specFile:e.specFile,test:t,tests:[r],_testTitle:e.title}})}function Vs(e,t){let r=new Date(e.timestamp).getTime(),a=new Date(t.timestamp).getTime();if(r!==a)return r-a;let n={navigation:0,api_call:1},s=n[e.type],l=n[t.type];return s!==l?s-l:e.type==="api_call"&&t.type==="api_call"&&e.callId&&t.callId?va(e.callId)-va(t.callId):0}function va(e){let t=e.match(/(\d+)$/);return t?parseInt(t[1],10):0}function js(e,t){for(let r=0;r<e.length;r++){let a=e[r];if(a.type!=="navigation")continue;let n=new Date(a.timestamp).getTime(),s=null;for(let l=r+1;l<e.length;l++)if(e[l]._testTitle===a._testTitle){s=new Date(e[l].timestamp).getTime();break}if(s!==null)a.durationOnUrl=Math.max(0,s-n);else {let l=t.find(i=>i.title===a._testTitle);if(l){let i=new Date(l.completedAt).getTime();a.durationOnUrl=Math.max(0,i-n);}}}}function ba(e){if(e==null)return null;try{return JSON.parse(e)}catch{return e}}function Y(e,t){let r=e.length,a=Math.min(Math.ceil(t/100*r)-1,r-1);return e[Math.max(0,a)]}function St(e){try{let t=new URL(e);return t.origin+t.pathname}catch{return e}}function Gs(e){return e==null?"error":e>=200&&e<300?"2xx":e>=300&&e<400?"3xx":e>=400&&e<500?"4xx":e>=500&&e<600?"5xx":"error"}function xa(e,t){let r=0,a=0,n=0,s=0,l=0;for(let x of e)switch(x.status){case "passed":r++;break;case "failed":a++;break;case "flaky":n++;break;case "skipped":s++;break;case "timedout":l++;break}let i=[];for(let x of e)x.apiCalls&&i.push(...x.apiCalls);let d=i.length,o=new Set,c={},f={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},v=[];for(let x of i)o.add(St(x.url)),c[x.method]=(c[x.method]??0)+1,f[Gs(x.responseStatusCode)]+=1,v.push(x.responseTimeMs);let g=null;if(v.length>0){let x=[...v].sort((X,G)=>X-G),S=x.reduce((X,G)=>X+G,0);g={avg:Math.round(S/x.length),min:x[0],max:x[x.length-1],p50:Y(x,50),p95:Y(x,95),p99:Y(x,99)};}let p=0,m=0,u=0;for(let x of e)if(x.apiAssertions)for(let S of x.apiAssertions)p++,S.status==="passed"?m++:u++;let h=0,b=new Set;for(let x of e){h+=x.navigations.length;for(let S of x.navigations)b.add(S.url);}let y=0,w={};function C(x){for(let S of x)y++,w[S.category]=(w[S.category]??0)+1,S.children.length>0&&C(S.children);}for(let x of e)x.actions&&C(x.actions);let P=0,A=0,R=0,L=0;for(let x of e)if(x.visual)for(let S of x.visual)P++,S.status==="failed"?A++:(S.status==="new"||S.status==="updated")&&R++,L+=S.domChangeCount??0;return {total:e.length,passed:r,failed:a,flaky:n,skipped:s,timedout:l,totalApiCalls:d,uniqueApiUrls:o.size,apiCallsByMethod:c,apiCallsByStatusRange:f,apiResponseTime:g,totalAssertions:p,passedAssertions:m,failedAssertions:u,totalNavigations:h,uniqueNavigationUrls:b.size,totalTimelineSteps:t,totalActionSteps:y,actionStepsByCategory:w,visualChecks:P,visualFailures:A,visualNew:R,visualDomChanges:L}}function Ws(e){let t=56-e.length;return t>0?e+" ".repeat(t):e}function E(e){return `\u2502 ${Ws(e)} \u2502
|
|
4260
4264
|
`}function Ct(e,t,r,a){if(a||e.total===0)return;let n=`\u250C${"\u2500".repeat(58)}\u2510
|
|
4261
4265
|
`,s=`\u2514${"\u2500".repeat(58)}\u2518
|
|
4262
4266
|
`,l=E(""),i=n;i+=E("TestRelic AI - Playwright Test Report"),i+=l;let d=[];if(e.passed>0&&d.push(`${e.passed} \u2713`),e.failed>0&&d.push(`${e.failed} \u2717`),e.flaky>0&&d.push(`${e.flaky} \u26A0`),e.skipped>0&&d.push(`${e.skipped} skipped`),e.timedout>0&&d.push(`${e.timedout} timedout`),i+=E(`Tests: ${e.total} total (${d.join(" ")})`),e.totalNavigations>0&&(i+=E(`Navigations: ${e.totalNavigations} visits across ${e.uniqueNavigationUrls} unique URLs`)),e.totalApiCalls>0){i+=E(`API Calls: ${e.totalApiCalls} calls across ${e.uniqueApiUrls} unique endpoints`);let o=Object.entries(e.apiCallsByMethod).filter(([,f])=>f>0).map(([f,v])=>`${f}: ${v}`);o.length>0&&(i+=E(` ${o.join(" ")}`));let c=Object.entries(e.apiCallsByStatusRange).filter(([,f])=>f>0).map(([f,v])=>`${f}: ${v}`);c.length>0&&(i+=E(` ${c.join(" ")}`)),e.apiResponseTime&&(i+=E(` Avg response: ${e.apiResponseTime.avg}ms P95: ${e.apiResponseTime.p95}ms`));}if(e.totalAssertions>0&&(i+=E(`Assertions: ${e.totalAssertions} total (${e.passedAssertions} \u2713 ${e.failedAssertions} \u2717)`)),e.totalActionSteps>0){let o=[],c=e.actionStepsByCategory;c.ui_action&&o.push(`${c.ui_action} UI`),c.assertion&&o.push(`${c.assertion} assertions`),c.custom_step&&o.push(`${c.custom_step} custom`);let f=o.length>0?` (${o.join(" ")})`:"";i+=E(`Actions: ${e.totalActionSteps} steps${f}`);}i+=E(`Report: ${r}`),i+=E(`Data: ${t}`),i+=s,i+=`For more information visit us at https://docs.testrelic.ai
|
|
4263
|
-
`,process.stderr.write(i);}var
|
|
4264
|
-
`)[0]?.trim();return a?$(`git remote get-url ${a}`,e):null}function ce(e){let t=e.trim();return t=t.replace(/^[a-z+]+:\/\//,""),t=t.replace(/^[^@]+@/,""),t=t.replace(/:(?!\d)/,"/"),t=t.replace(/\.git$/,""),t=t.replace(/\/+$/,""),t=t.replace(/^[^@/]+@/,""),t.toLowerCase()}function
|
|
4265
|
-
`),a=JSON.stringify(
|
|
4266
|
-
`),a=JSON.stringify(
|
|
4267
|
-
`),a=JSON.stringify(
|
|
4268
|
-
`),a=JSON.stringify(
|
|
4267
|
+
`,process.stderr.write(i);}var Ks=new Set(["pw:api","expect","test.step"]);function Js(e){return e==="expect"?"assertion":e==="test.step"?"custom_step":"ui_action"}function Tt(e,t,r){if(Ks.has(e.category)){let a=[];for(let s of e.steps)Tt(s,t,a);let n=e.startTime.getTime()-t.getTime();r.push({title:e.title,category:Js(e.category),timestamp:e.startTime.toISOString(),duration:e.duration,videoOffset:n>=0?n/1e3:null,status:e.error?"failed":"passed",error:na(e.error?.message),children:a});}else for(let a of e.steps)Tt(a,t,r);}function wa(e,t){let r=[];for(let a of e)Tt(a,t,r);return r}var Zs=new Set(["localhost","127.0.0.1","0.0.0.0"]);function Sa(e){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&Zs.has(t.hostname)))throw createError(ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${t.protocol}//${t.hostname}`)}var Qs=3e3;async function Rt(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Qs);try{return (await fetch(`${e}/health`,{method:"GET",signal:t.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function Ca(e){return new Promise(t=>setTimeout(t,e))}async function ka(e){try{let r=(await e.json()).error;if(r&&typeof r.message=="string"){let a=r.details;if(Array.isArray(a)&&a.length>0){let n=a.map(s=>`${s.field}: ${s.message}`).join(", ");return `${r.message} (${n})`}return r.message}}catch{}return `HTTP ${e.status}`}async function At(e,t,r){let a=new AbortController,n=setTimeout(()=>a.abort(),r);try{let s=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:a.signal});if(s.ok){let i=await s.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,orgId:i.orgId,orgName:i.orgName,userId:i.userId,userName:i.userName}}if(s.status===429){let i=s.headers.get("Retry-After"),d=i?parseInt(i,10)*1e3:5e3;if(!isNaN(d)&&d>0){await Ca(d);let o=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:a.signal});if(o.ok){let c=await o.json();return {accessToken:c.accessToken,refreshToken:c.refreshToken,expiresIn:c.expiresIn,orgId:c.orgId,orgName:c.orgName,userId:c.userId,userName:c.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return s.status===400?{code:"validation_error",message:await ka(s),statusCode:400}:s.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:s.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await ka(s),statusCode:s.status}}catch(s){return s instanceof DOMException&&s.name==="AbortError"?{code:"timeout",message:"Token exchange timed out.",statusCode:null}:{code:"network_error",message:"Failed to reach cloud for token exchange.",statusCode:null}}finally{clearTimeout(n);}}function _t(e){return "code"in e&&typeof e.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(e.code)}async function Ta(e,t,r){let a=new AbortController,n=setTimeout(()=>a.abort(),r);try{let s=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:a.signal});if(s.status===429){let i=s.headers.get("Retry-After"),d=i?parseInt(i,10)*1e3:5e3;!isNaN(d)&&d>0&&(await Ca(d),s=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:a.signal}));}if(!s.ok)return null;let l=await s.json();return {accessToken:l.accessToken,refreshToken:l.refreshToken,expiresIn:l.expiresIn}}catch{return null}finally{clearTimeout(n);}}async function Ra(e,t,r,a,n,s){let l=new AbortController,i=setTimeout(()=>l.abort(),n);try{let d={gitId:r,displayName:a};s&&(d.branch=s);let o=await fetch(`${e}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(d),signal:l.signal});if(!o.ok)return null;let c=await o.json();return {repoId:c.repoId,displayName:c.displayName}}catch{return null}finally{clearTimeout(i);}}var ni=5e3;function $(e,t){try{return execSync(e,{cwd:t,timeout:ni,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function Aa(e){let t=$("git rev-parse --abbrev-ref HEAD",e),r=$("git rev-parse --short HEAD",e),a=$("git log -1 --pretty=%s",e),n=$("git log -1 --format=%an",e)??$("git config user.name",e),s=si(e),l=s?ce(s):null;return {branch:t,commitSha:r,commitMessage:a,commitAuthor:n,remoteUrl:l}}function si(e){let t=$("git remote get-url origin",e);if(t)return t;let r=$("git remote",e);if(!r)return null;let a=r.split(`
|
|
4268
|
+
`)[0]?.trim();return a?$(`git remote get-url ${a}`,e):null}function ce(e){let t=e.trim();return t=t.replace(/^[a-z+]+:\/\//,""),t=t.replace(/^[^@]+@/,""),t=t.replace(/:(?!\d)/,"/"),t=t.replace(/\.git$/,""),t=t.replace(/\/+$/,""),t=t.replace(/^[^@/]+@/,""),t.toLowerCase()}function _a(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function It(e){try{let t=readFileSync(join(e,"package.json"),"utf-8"),r=JSON.parse(t);return typeof r.name=="string"&&r.name.length>0?r.name:null}catch{return null}}function ue(e){let t=It(e);return t||`local/${basename(e)}`}var ii=new Set(["smoke","regression","nightly","ci"]);function Se(){let e=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(e&&ii.has(e))return e}async function V(e,t,r){let a=new AbortController,n=setTimeout(()=>a.abort(),Math.max(1,r));try{return await fetch(e,{...t,signal:a.signal})}finally{clearTimeout(n);}}function Ia(e,t){let r=t+Math.ceil(Math.max(0,e)/1e3);return Math.min(6e5,Math.max(3e4,r))}var Ce=class{constructor(t=12e4,r=Date.now()){this.deadline=r+Math.max(0,t);}remaining(t=Date.now()){return Math.max(0,this.deadline-t)}expired(t=Date.now()){return this.remaining(t)===0}slice(t,r=Date.now()){return Math.min(t,this.remaining(r))}};var di=1048576,Te=[1e3,3e3,9e3],Re=3,Ea=3e4,ci=90*1048576,ui=new Set(["e2e","mobile","unit"]);function Et(e){if(e&&e.length>0&&e.every(n=>n.testType==="api")){let n=new Map;for(let i of e){let d=i.apiProtocol??"rest";n.set(d,(n.get(d)??0)+1);}let s="rest",l=0;for(let[i,d]of n)d>l&&(l=d,s=i);return {testType:"api",apiProtocol:s,metadata:{testType:"api",primaryProtocol:s}}}let t=new Map;for(let n of e??[])ui.has(n.testType)&&t.set(n.testType,(t.get(n.testType)??0)+1);let r=null,a=0;for(let[n,s]of t)s>a&&(a=s,r=n);return {testType:r??"e2e"}}function Pt(e,t,r,a,n,s){let l=s?.cloudPlatform?s.cloudPlatform:a?.provider&&a.provider!=="unknown"?a.provider:"local",i=Se(),d=Et(n),o=d.testType==="api"?d:null,c=o&&n?n.map(v=>v.apiProtocol?v:{...v,apiProtocol:o.apiProtocol}):n;return {runId:e.testRunId,repoGitId:t,startedAt:e.startedAt,summary:e.summary,timeline:e.timeline,environment:l,...i?{runType:i}:{},...o?{testType:o.testType,apiProtocol:o.apiProtocol,metadata:o.metadata}:{testType:d.testType},...c&&c.length>0?{tests:c}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...e.completedAt?{finishedAt:e.completedAt}:{},...e.totalDuration?{duration:e.totalDuration}:{},...a?.provider?{ciProvider:a.provider}:{},...a?.runUrl?{ciRunUrl:a.runUrl}:{},...s?.cloudPlatform?{cloudPlatform:s.cloudPlatform}:{},...s?.cloudBuildId?{cloudBuildId:s.cloudBuildId}:{},...s?.cloudSessionId?{cloudSessionId:s.cloudSessionId}:{}}}function Mt(e){return typeof e=="string"?Buffer.byteLength(e,"utf-8"):0}function Lt(e){return Array.isArray(e)?e.map(t=>{let r=t.statusCode??t.responseStatusCode??null;return {...t.id!=null?{id:t.id}:{},...t.protocol!=null?{protocol:t.protocol}:{},method:t.method??null,url:t.url??null,statusCode:r,statusText:t.statusText??t.responseStatusText??null,ok:typeof r=="number"?r<400:t.ok??null,durationMs:t.durationMs??t.responseTimeMs??null,bytesIn:typeof t.bytesIn=="number"?t.bytesIn:Mt(t.responseBody),bytesOut:typeof t.bytesOut=="number"?t.bytesOut:Mt(t.requestBody),requestHeaders:t.requestHeaders??null,responseHeaders:t.responseHeaders??null,requestBody:t.requestBody??null,responseBody:t.responseBody??null,requestCookies:t.requestCookies??null,responseCookies:t.responseCookies??null}}):[]}function Dt(e){return Array.isArray(e)?e.map(t=>{let r=t.responseStatusCode??t.statusCode??0,a=t.timestamp??null;return {method:t.method??"GET",url:t.url??"",status:r,statusCode:r,type:"xhr",size:Mt(t.responseBody),duration:t.responseTimeMs??t.durationMs??0,responseTimeMs:t.responseTimeMs??t.durationMs??0,requestHeaders:t.requestHeaders??null,responseHeaders:t.responseHeaders??null,requestBody:t.requestBody??null,responseBody:t.responseBody??null,timestamp:a,startedAt:a}}):[]}function Nt(e){if(!Array.isArray(e))return [];let t=r=>{if(r==null)return String(r);if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}};return e.map(r=>{let a=r.status==="failed"?"failed":"passed",n=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,s=r.kind??r.type??"assertion",l=a==="failed"?`expected ${t(r.expected)}, received ${t(r.actual)}`:r.expected!==void 0?`expected ${t(r.expected)}`:null;return {...r.callId!=null?{callId:r.callId}:{},kind:s,description:n??r.description??`${s} assertion`,status:a,detail:l}})}async function Ae(e){return new Promise(t=>setTimeout(t,e))}function pi(e){let t={};for(let[r,a]of Object.entries(e))a!=null&&(t[r]=a);return t}async function Pa(e,t,r,a=Ea,n){for(let s=0;s<Re;s++){if(n?.expired())return null;let l=n?n.slice(a):a;if(l<=0)return null;try{let i=await V(e,t,l);if(i.ok)return i;if(i.status===401&&r&&s===0){let d=await r();if(d){let o={...t,headers:{...t.headers,Authorization:`Bearer ${d}`}},c=await V(e,o,l);if(c.ok)return c}return null}if(i.status===429&&s<Re-1){let d=i.headers.get("Retry-After"),o=d?parseInt(d,10)*1e3:Te[s];!isNaN(o)&&o>0?await Ae(o):await Ae(Te[s]);continue}if(i.status>=500&&s<Re-1){await Ae(Te[s]);continue}return i}catch{if(s<Re-1){await Ae(Te[s]);continue}return null}}return null}var fi=promisify(gzip);function Ma(e,t){if(!Array.isArray(e.tests))return e;let r=e.tests.map(a=>{let{consoleLogs:n,networkRequests:s,apiCalls:l,...i}=a;return t?i:{...i,...l!==void 0?{apiCalls:l}:{}}});return {...e,tests:r}}var gi=["consoleLogs","networkRequests","apiCalls","actions","navigations","protocolAssertions","visual"];function hi(e){if(!Array.isArray(e.tests))return e;let t=new Set(gi),r=e.tests.map(a=>{let n={};for(let s in a)if(!t.has(s))if(s==="failure"&&a[s]&&typeof a[s]=="object"){let l=a[s];n.failure={message:l.message??null,line:l.line??null};}else n[s]=a[s];return n});return {...e,tests:r}}function mi(e){let t=new Set(["tests","timeline","unifiedTimeline","navigations"]),r={};for(let a in e)t.has(a)||(r[a]=e[a]);return r.tests=[],r}async function Ft(e,t=ci){let r={"Content-Type":"application/json"},a=JSON.stringify(e),n=e,s=Array.isArray(n?.tests)?n.tests.length:0,l=i=>Buffer.byteLength(i,"utf-8")>t;if(s>0&&l(a)){let i=Math.max(1,Math.round(t/1048576));process.stderr.write(`[testrelic] WARNING: batch payload exceeds ${i}MB \u2014 dropping consoleLogs/networkRequests from ${s} test(s) to avoid HTTP 413. Console/network detail will be missing in the cloud.
|
|
4269
|
+
`),a=JSON.stringify(Ma(n,false)),l(a)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${i}MB after dropping logs \u2014 also dropping apiCalls from ${s} test(s). API request/response detail will be missing in the cloud.
|
|
4270
|
+
`),a=JSON.stringify(Ma(n,true))),l(a)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${i}MB \u2014 shedding remaining per-test detail (actions/navigations/assertions) from ${s} test(s). Only test results + summary will reach the cloud.
|
|
4271
|
+
`),a=JSON.stringify(hi(n))),l(a)&&(process.stderr.write(`[testrelic] ERROR: batch still exceeds ${i}MB after shedding all per-test detail \u2014 uploading run summary only (${s} per-test result(s) omitted) to avoid losing the run to HTTP 413.
|
|
4272
|
+
`),a=JSON.stringify(mi(n)));}if(Buffer.byteLength(a,"utf-8")>di){r["Content-Encoding"]="gzip";let i=await fi(Buffer.from(a,"utf-8")),d=i.buffer;return {body:new Uint8Array(d,i.byteOffset,i.byteLength),headers:r}}return {body:a,headers:r}}async function La(e,t,r,a,n,s){let l=`${e}/runs`,{body:i,headers:d}=await Ft(r);d.Authorization=`Bearer ${t}`;let o=await Pa(l,{method:"POST",headers:d,body:i},a,n,s);return o?.ok?{success:true,statusCode:o.status,error:null}:o?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:o?`Upload failed with status ${o.status}`:"Upload failed after retries",statusCode:o?.status??null,payload:r,targetEndpoint:l,method:"POST"}}async function Da(e,t,r,a){let n=`${e}/runs/init`;try{let s=await V(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(pi(r))},a??Ea);return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function Na(e,t,r,a){let n=`${e}/runs/${r}/tests`;fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a)}).catch(()=>{});}async function Fa(e,t,r,a){let n=`${e}/runs/${r}/finalize`;return (await Pa(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a)}))?.ok??false}function Bt(e,t,r,a){let n=`${e}/runs/${r}/finalize`,s=new Date,l={finishedAt:s.toISOString(),duration:s.getTime()-new Date(a).getTime(),summary:{}};fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(l)}).catch(()=>{});}var wi="1.0.0",Ba=10;function Oa(e){return e instanceof Error?e.message:String(e)}function ki(e){return e>=400&&e<500&&e!==408&&e!==429}function pe(e,t,r,a,n,s,l,i){try{mkdirSync(e,{recursive:!0});let d=Date.now(),o=`${d}-${t}-${r}.json`,c=join(e,o),f={version:wi,queuedAt:new Date(d).toISOString(),reason:a,retryCount:0,targetEndpoint:n,method:s,payload:l,headers:i},v=c+".tmp";writeFileSync(v,JSON.stringify(f,null,2),"utf-8"),renameSync(v,c);}catch(d){d.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
|
|
4269
4273
|
`):process.stderr.write(`\u26A0 TestRelic: Unable to queue upload data.
|
|
4270
|
-
`);}}async function
|
|
4271
|
-
`),unlinkSync(i);continue}d=c;}catch(o){process.stderr.write(`\u26A0 TestRelic: Skipping unreadable queue file ${l}: ${
|
|
4272
|
-
`);try{unlinkSync(i);}catch{}continue}try{let{body:o,headers:c}=await Ft(d.payload),f={...d.headers,...c,Authorization:`Bearer ${r}`},v=await fetch(d.targetEndpoint,{method:d.method,headers:f,body:o});if(v.ok)unlinkSync(i);else if(
|
|
4274
|
+
`);}}async function qa(e,t,r){let a;try{a=readdirSync(e).filter(s=>s.endsWith(".json")&&!s.endsWith(".tmp")).sort();}catch{return}if(a.length===0)return;let n=[];for(let s=0;s<a.length;s+=Ba)n.push(a.slice(s,s+Ba));for(let s of n)for(let l of s){let i=join(e,l),d;try{if(!statSync(i).isFile())continue;let c=JSON.parse(readFileSync(i,"utf-8"));if(!isValidQueueEntry(c)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${l}
|
|
4275
|
+
`),unlinkSync(i);continue}d=c;}catch(o){process.stderr.write(`\u26A0 TestRelic: Skipping unreadable queue file ${l}: ${Oa(o)}
|
|
4276
|
+
`);try{unlinkSync(i);}catch{}continue}try{let{body:o,headers:c}=await Ft(d.payload),f={...d.headers,...c,Authorization:`Bearer ${r}`},v=await fetch(d.targetEndpoint,{method:d.method,headers:f,body:o});if(v.ok)unlinkSync(i);else if(ki(v.status)){process.stderr.write(`\u26A0 TestRelic: Queue entry ${l} rejected (HTTP ${v.status}) \u2014 moving aside; it will not be retried.
|
|
4273
4277
|
`);try{renameSync(i,`${i}.failed`);}catch{try{unlinkSync(i);}catch{}}}else {process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 server returned HTTP ${v.status} for ${l}; will retry later.
|
|
4274
|
-
`);return}}catch(o){process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 ${
|
|
4275
|
-
`);return}}}function
|
|
4276
|
-
`);return}try{if(
|
|
4278
|
+
`);return}}catch(o){process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 ${Oa(o)}; will retry later.
|
|
4279
|
+
`);return}}}function $a(e,t){try{let r=readdirSync(e).filter(n=>(n.endsWith(".json")||n.endsWith(".failed"))&&!n.endsWith(".tmp")),a=Date.now();for(let n of r){let s=join(e,n);try{let l=readFileSync(s,"utf-8"),d=JSON.parse(l).queuedAt;if(typeof d=="string"){let o=new Date(d).getTime();a-o>t&&unlinkSync(s);}}catch{try{unlinkSync(s);}catch{}}}}catch{}}var Ii=3e5,Mi=864e5,Ei=6e4,Va=3e4,zt="https://platform.testrelic.ai/settings/api-keys";function ja(e){return new Promise(t=>{let r=setTimeout(t,e);typeof r?.unref=="function"&&r.unref();})}var _e=class{constructor(t){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=t,this.authState={mode:"pending",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null};}async initialize(){if(!this.config||!this.config.apiKey){this.setLocalMode("no_api_key"),process.stderr.write(`\u2139 TestRelic: No API key configured. Running in local mode.
|
|
4280
|
+
`);return}try{if(Sa(this.config.endpoint),this.gitMetadata=Aa(),!await Rt(this.config.endpoint)){this.setLocalMode("cloud_unreachable"),process.stderr.write(`\u26A0 TestRelic: Cloud unreachable. Switching to local mode. Data will be queued for later upload.
|
|
4277
4281
|
`);return}let r=await At(this.config.endpoint,this.config.apiKey,this.config.timeout);if(_t(r)){this.handleAuthError(r.code,r.statusCode);return}let a=r;this.authState={mode:"cloud",accessToken:a.accessToken,refreshToken:a.refreshToken,expiresAt:Date.now()+a.expiresIn*1e3,orgId:a.orgId,orgName:a.orgName,userId:a.userId,userName:a.userName},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${a.orgName} / ${a.userName})
|
|
4278
|
-
`),await this.resolveRepoId(),this.config.queueDirectory&&(
|
|
4279
|
-
`);}}getMode(){return this.authState.mode}isCloudMode(){return this.authState.mode==="cloud"}isLocalMode(){return this.authState.mode==="local"}getAccessToken(){return this.authState.accessToken}getRepoId(){return this.repoId}getGitMetadata(){return this.gitMetadata}getConfig(){return this.config}getFailureReason(){return this.failureReason}getEndpoint(){return this.config?.endpoint??"https://platform.testrelic.ai/api/v1"}async ensureValidToken(){if(!this.isCloudMode()||!this.authState.accessToken)return false;let t=this.authState.expiresAt??0;if(Date.now()+
|
|
4280
|
-
`));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise
|
|
4282
|
+
`),await this.resolveRepoId(),this.config.queueDirectory&&($a(this.config.queueDirectory,this.config.queueMaxAge),this.startBackgroundFlush()),this.startHealthCheck();}catch(t){this.setLocalMode("unexpected_error"),process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. Running in local mode. ${t instanceof Error?t.message:String(t)}
|
|
4283
|
+
`);}}getMode(){return this.authState.mode}isCloudMode(){return this.authState.mode==="cloud"}isLocalMode(){return this.authState.mode==="local"}getAccessToken(){return this.authState.accessToken}getRepoId(){return this.repoId}getGitMetadata(){return this.gitMetadata}getConfig(){return this.config}getFailureReason(){return this.failureReason}getEndpoint(){return this.config?.endpoint??"https://platform.testrelic.ai/api/v1"}async ensureValidToken(){if(!this.isCloudMode()||!this.authState.accessToken)return false;let t=this.authState.expiresAt??0;if(Date.now()+Ii<t)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await Ta(this.config.endpoint,this.authState.refreshToken,this.config.timeout);return r?(this.authState.accessToken=r.accessToken,this.authState.refreshToken=r.refreshToken,this.authState.expiresAt=Date.now()+r.expiresIn*1e3,!0):(this.switchToLocalMode("token_refresh_failed"),!1)}catch{return this.switchToLocalMode("token_refresh_error"),false}}switchToLocalMode(t){this.authState.mode!=="local"&&(this.authState.mode="local",this.failureReason=t,process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${t}).
|
|
4284
|
+
`));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,ja(Va)]);}catch{}this.flushPromise=null;}this.authState={mode:"local",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null},this.repoId=null,this.gitMetadata=null;}setLocalMode(t){this.authState.mode="local",this.failureReason=t;}handleAuthError(t,r){switch(t){case "invalid_key":this.setLocalMode("invalid_api_key"),process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
|
|
4281
4285
|
\u2192 Manage keys: ${zt}
|
|
4282
4286
|
`);break;case "expired_key":this.setLocalMode("expired_api_key"),process.stderr.write(`\u26A0 TestRelic: API key has expired. Running in local mode.
|
|
4283
4287
|
\u2192 Generate a new key: ${zt}
|
|
@@ -4286,16 +4290,16 @@ ${n}
|
|
|
4286
4290
|
`);break;case "rate_limited":this.setLocalMode("rate_limited"),process.stderr.write(`\u26A0 TestRelic: Rate limited during authentication. Running in local mode.
|
|
4287
4291
|
`);break;case "timeout":this.setLocalMode("auth_timeout"),process.stderr.write(`\u26A0 TestRelic: Authentication timed out. Running in local mode.
|
|
4288
4292
|
`);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
|
|
4289
|
-
`);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let t=this.gitMetadata?.remoteUrl?ce(this.gitMetadata.remoteUrl):null,r=t?
|
|
4290
|
-
`);}readRepoCache(t){if(!this.config)return null;let r=join(this.config.queueDirectory,"..","cache","repo.json");try{if(!existsSync(r))return null;let a=readFileSync(r,"utf-8"),n=JSON.parse(a);if(n.gitId!==t||Date.now()-n.resolvedAt>
|
|
4291
|
-
`),this.startBackgroundFlush();}}}catch{}},
|
|
4293
|
+
`);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let t=this.gitMetadata?.remoteUrl?ce(this.gitMetadata.remoteUrl):null,r=t?_a(t):this.config.projectName??ue(process.cwd()),a=t??this.config.projectName??ue(process.cwd()),n=this.readRepoCache(a);if(n){this.repoId=n.repoId;return}try{let s=await Ra(this.config.endpoint,this.authState.accessToken,a,r,this.config.timeout,this.gitMetadata?.branch);s&&(this.repoId=s.repoId,this.writeRepoCache(a,s.repoId,s.displayName));}catch{}!t&&!this.config.projectName&&!It(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
|
|
4294
|
+
`);}readRepoCache(t){if(!this.config)return null;let r=join(this.config.queueDirectory,"..","cache","repo.json");try{if(!existsSync(r))return null;let a=readFileSync(r,"utf-8"),n=JSON.parse(a);if(n.gitId!==t||Date.now()-n.resolvedAt>Mi)return null;let s=this.hashApiKey();return s&&n.apiKeyHash!==s?null:n}catch{return null}}writeRepoCache(t,r,a){if(!this.config)return;let n=join(this.config.queueDirectory,"..","cache"),s=join(n,"repo.json");try{mkdirSync(n,{recursive:!0});let l={repoId:r,gitId:t,displayName:a,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=s+".tmp";writeFileSync(i,JSON.stringify(l,null,2),"utf-8"),renameSync(i,s);}catch{}}hashApiKey(){return this.config?.apiKey?createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let t=this.authState.accessToken,r=this.config.queueDirectory,a=this.config.endpoint;this.flushPromise=Promise.race([qa(r,a,t),ja(Va)]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let t=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await Rt(t))return;if(this.config?.apiKey){let a=await At(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!_t(a)){let n=a;this.authState={mode:"cloud",accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:Date.now()+n.expiresIn*1e3,orgId:n.orgId,orgName:n.orgName,userId:n.userId,userName:n.userName},this.failureReason=null,process.stderr.write(`\u2713 TestRelic: Cloud connectivity restored.
|
|
4295
|
+
`),this.startBackgroundFlush();}}}catch{}},Ei),typeof this.healthCheckTimer?.unref=="function"&&this.healthCheckTimer.unref();}};function Ni(e,t){return t?e?{"2xx":e["2xx"]+t["2xx"],"3xx":e["3xx"]+t["3xx"],"4xx":e["4xx"]+t["4xx"],"5xx":e["5xx"]+t["5xx"],error:e.error+t.error}:{...t}:e}function Ga(e,t,r,a){let n=[],s=[],l=null,i=0,d=null,o=0,c=null,f=0,v=null,g=e.filter(u=>u.name===ATTACHMENT_NAME&&u.body),p=false;if(g.length>0)for(let u of g)try{let h=JSON.parse(u.body.toString());if(isTestRelicFilePayload(h)){n=n.concat(h.navigations),s=s.concat(h.apiAssertions),h.networkRequestsFile&&(l=h.networkRequestsFile,i+=h.networkRequestsCount),h.consoleLogsFile&&(d=h.consoleLogsFile,o+=h.consoleLogsCount),h.apiCallsFile&&(c=h.apiCallsFile,f+=h.apiCallsCount),v=Ni(v,h.apiStatusMix),p=!0;continue}if(isTestRelicDataPayload(h)){n=n.concat(h.navigations),Array.isArray(h.apiAssertions)&&(s=s.concat(h.apiAssertions)),i+=h.networkRequests?.length??0,f+=h.apiCalls?.length??0;let b=h.consoleLogs;Array.isArray(b)&&(o+=b.length),p=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
|
|
4292
4296
|
`);}return p||(n=t.filter(u=>u.type==="lambdatest-navigation"&&u.description).map(u=>{try{return JSON.parse(u.description)}catch{return null}}).filter(u=>u!==null)),n.length===0&&i===0&&f===0&&!a&&!p&&process.stderr.write(`[testrelic] Warning: No data found for test "${r}". Make sure your tests import { test, expect } from '@testrelic/playwright-analytics/fixture' instead of '@playwright/test'. Without the TestRelic fixture, network logs, video sync, and Test Navigation data cannot be captured.
|
|
4293
|
-
`),{navigations:n,apiAssertions:s,networkRequestsFile:l,networkRequestsCount:i,consoleLogsFile:d,consoleLogsCount:o,apiCallsFile:c,apiCallsCount:f,apiStatusMix:v}}function Ie(e=process.env){let t=
|
|
4294
|
-
`),{keyMap:s,visualKeyMap:l,total:o.length,uploaded:m}}async function Gt(e,t,r,a,n,s,l,i,d,o,c){let f={realtimeFinalizeAttempted:false,realtimeFinalized:false,batchAttempted:false,batchAcknowledged:false,artifactsTotal:0,artifactsUploaded:0,failureReason:null},v=new Ce(t?.uploadBudgetMs??12e4),g=p=>{f.failureReason||(f.failureReason=p);};try{if(e.isCloudMode()&&n&&(r==="realtime"||r==="both")){f.realtimeFinalizeAttempted=!0;let u=await e.ensureValidToken(),h=e.getGitMetadata(),b=Et(c),y={finishedAt:l,duration:i,summary:d,...h?.commitMessage?{commitMessage:h.commitMessage}:{},testType:b.testType,...b.testType==="api"?{apiProtocol:b.apiProtocol,metadata:b.metadata}:{}};if(u){let w=await
|
|
4295
|
-
`).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function
|
|
4296
|
-
`).map(s=>s.trim()).filter(Boolean);if(t.length===0)return null;let r=t.filter(s=>!/^Error:\s*expect\(/.test(s));if(r.length===0)return t[0]??null;let a=r[0],n=r[1];return n!==void 0&&/^Received:/.test(n)&&/^Expected:/.test(a)?`${a} \xB7 ${n}`:a}function Jt(e){switch(e){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function
|
|
4297
|
-
`),this.activeReportMode==="streaming"){let i=dirname(this.config.outputPath);this.streamingWriter=new ie(i);let d=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let o={testRunId:this.testRunId??"",startedAt:this.startedAt,completedAt:new Date().toISOString(),totalDuration:Date.now()-new Date(this.startedAt).getTime(),...this.summaryCounters,metadata:null,reportMode:"streaming",files:[],enrichedSummary:null,validation:null,writeErrors:this.streamingWriter.getWriteErrors(),cloudUpload:this.cloudReceipt};this.streamingWriter.writeSummary(o);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let o=this.cloudClient.getAccessToken();o&&Bt(this.cloudClient.getEndpoint(),o,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",d),process.on("SIGINT",d);}if(this.config.includeArtifacts){let i=dirname(this.config.outputPath);this.runTimestamp=
|
|
4298
|
-
`)});if(_.length>0){let T=dirname(this.config.outputPath),B=f[f.length-1]??t.title;R=
|
|
4297
|
+
`),{navigations:n,apiAssertions:s,networkRequestsFile:l,networkRequestsCount:i,consoleLogsFile:d,consoleLogsCount:o,apiCallsFile:c,apiCallsCount:f,apiStatusMix:v}}function Ie(e=process.env){let t=Fi(e.TESTRELIC_CLOUD_PLATFORM);if(t)return {cloudPlatform:t,cloudBuildId:e.TESTRELIC_CLOUD_BUILD_ID||void 0,cloudSessionId:e.TESTRELIC_CLOUD_SESSION_ID||void 0};if(e.BROWSERSTACK_USERNAME||e.BROWSERSTACK_ACCESS_KEY)return {cloudPlatform:"browserstack",cloudBuildId:e.BROWSERSTACK_BUILD_NAME||e.BROWSERSTACK_BUILD_ID||void 0,cloudSessionId:e.BROWSERSTACK_SESSION_ID||void 0};if(e.LT_USERNAME||e.LAMBDATEST_USERNAME||e.LT_ACCESS_KEY||e.LAMBDATEST_ACCESS_KEY)return {cloudPlatform:"lambdatest",cloudBuildId:e.LT_BUILD||e.LAMBDATEST_BUILD||void 0,cloudSessionId:e.LT_SESSION_ID||e.LAMBDATEST_SESSION_ID||void 0};let r=e.PLAYWRIGHT_WS_ENDPOINT;if(r){if(/cdp\.lambdatest\.com/i.test(r))return {cloudPlatform:"lambdatest"};if(/cdp\.browserstack\.com/i.test(r))return {cloudPlatform:"browserstack"}}return {}}function Fi(e){if(!e)return;let t=e.toLowerCase().trim();if(t==="browserstack"||t==="bs")return "browserstack";if(t==="lambdatest"||t==="lt")return "lambdatest"}var Hi=5,Me=[1e3,3e3,9e3],te=3,$t=3e4,qi={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip",".json":"application/json"},Ht=0,qt=[];async function $i(){Ht>=Hi&&await new Promise(e=>qt.push(e)),Ht++;}function Vi(){Ht--,qt.length>0&&qt.shift()();}async function Ee(e){return new Promise(t=>setTimeout(t,e))}function ji(e){let t=e.substring(e.lastIndexOf(".")).toLowerCase();return qi[t]??"application/octet-stream"}function Gi(e){try{return statSync(e).size}catch{return 0}}async function Wi(e,t,r,a,n){let s=`${e}/artifacts/upload-url`,l=JSON.stringify({runId:r.runId,testId:r.testId,fileName:basename(r.filePath),contentType:n,type:r.type,sizeBytes:a});for(let i=0;i<te;i++)try{let d=await V(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:l},$t);if(d.ok)return await d.json();if(d.status>=500&&i<te-1){await Ee(Me[i]);continue}return null}catch{if(i<te-1){await Ee(Me[i]);continue}return null}return null}async function Ki(e,t,r,a){let n=Ia(a,$t);for(let s=0;s<te;s++)try{let l=createReadStream(t),i=Readable.toWeb(l),d=await V(e,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(a)},body:i,duplex:"half"},n);if(d.ok)return !0;if(d.status>=500&&s<te-1){await Ee(Me[s]);continue}return !1}catch{if(s<te-1){await Ee(Me[s]);continue}return false}return false}async function Ji(e,t,r){let a=`${e}/artifacts/confirm`;try{return (await V(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({artifactId:r})},$t)).ok}catch{return false}}async function Yi(e,t,r,a){let n=Gi(r.filePath);if(n===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(n>a*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let s=ji(r.filePath);await $i();try{let l=await Wi(e,t,r,n,s);if(!l)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await Ki(l.uploadUrl,r.filePath,s,n))return {success:!1,storageKey:l.storageKey,artifactId:l.artifactId,error:"presigned_put_failed"};let d=await Ji(e,t,l.artifactId);return {success:d,storageKey:l.storageKey,artifactId:l.artifactId,error:d?null:"confirm_failed"}}finally{Vi();}}async function Wa(e,t,r,a,n){let s=new Map,l=r.map(async i=>{if(n?.expired()){s.set(i.filePath,{success:false,storageKey:null,artifactId:null,error:"upload_budget_exhausted"});return}let d=await Yi(e,t,i,a);s.set(i.filePath,d);});return await Promise.allSettled(l),s}function jt(e){let r=e.getGitMetadata()?.remoteUrl;return r?ce(r):e.getConfig()?.projectName??ue(process.cwd())}async function Ka(e,t,r,a,n){if(!e.isCloudMode()||t!=="realtime"&&t!=="both"||!await e.ensureValidToken())return null;let l=e.getGitMetadata(),i=U(),d=Ie(),o=Se();return (await Da(e.getEndpoint(),e.getAccessToken(),{runId:r,repoGitId:jt(e),branch:l?.branch??null,commit:l?.commitSha??null,commitMessage:l?.commitMessage??null,commitAuthor:l?.commitAuthor??null,startedAt:a,totalTests:null,ciProvider:i?.provider??null,ciRunUrl:i?.runUrl??null,environment:n??d.cloudPlatform??null,cloudPlatform:d.cloudPlatform??null,cloudBuildId:d.cloudBuildId??null,cloudSessionId:d.cloudSessionId??null,...o?{runType:o}:{},testType:"e2e"}))?.runId??null}var Zi=[{field:"baseline",keyField:"baselineKey",type:"baseline"},{field:"actual",keyField:"actualKey",type:"screenshot"},{field:"diff",keyField:"diffKey",type:"diff"},{field:"baselineDom",keyField:"baselineDomKey",type:"dom"},{field:"actualDom",keyField:"actualDomKey",type:"dom"}],Qi=true,eo=50,Vt={keyMap:new Map,visualKeyMap:new Map,total:0,uploaded:0};async function to(e,t,r,a,n){let s=new Map,l=new Map;if(!(t?.uploadArtifacts??Qi)||!await e.ensureValidToken())return Vt;let o=[],c=new Map,f=new Map;for(let u of a){if(u.artifacts.screenshot){let b=join(u.outputDir,u.artifacts.screenshot);o.push({filePath:b,runId:r,testId:u.testId,type:"screenshot"}),c.set(b,{testId:u.testId,field:"screenshot"});}if(u.artifacts.video){let b=join(u.outputDir,u.artifacts.video);o.push({filePath:b,runId:r,testId:u.testId,type:"video"}),c.set(b,{testId:u.testId,field:"video"});}if(u.artifacts.trace){let b=join(u.outputDir,u.artifacts.trace);o.push({filePath:b,runId:r,testId:u.testId,type:"trace"}),c.set(b,{testId:u.testId,field:"trace"});}let h=u.visual??[];for(let b=0;b<h.length;b++){let y=h[b];if(y)for(let w of Zi){let C=y[w.field];if(!C)continue;let P=join(u.outputDir,C);o.push({filePath:P,runId:r,testId:u.testId,type:w.type}),c.set(P,{testId:u.testId,field:"visual",visualIndex:b,visualKey:w.keyField});}}}if(o.length===0)return Vt;let v=t?.artifactMaxSizeMb??eo,g=await Wa(e.getEndpoint(),e.getAccessToken(),o,v,n),p=new Map;for(let[u,h]of g){if(!h.success||!h.storageKey)continue;let b=c.get(u);if(!b)continue;let y=p.get(b.testId)??{};if(b.field==="screenshot"&&(y.screenshotKey=h.storageKey),b.field==="video"&&(y.videoKey=h.storageKey),b.field==="trace"&&(y.traceKey=h.storageKey),b.field==="visual"&&b.visualIndex!==void 0&&b.visualKey){let w=f.get(b.testId)??new Map,C=w.get(b.visualIndex)??{};C[b.visualKey]=h.storageKey,w.set(b.visualIndex,C),f.set(b.testId,w);}p.set(b.testId,y);}for(let u of a){if(u.visual&&u.visual.length>0){let b=f.get(u.testId);l.set(u.testId,u.visual.map((y,w)=>({...y,...b?.get(w)??{}})));}let h=p.get(u.testId);s.set(u.testId,{...u.artifacts,...h?.screenshotKey?{screenshotKey:h.screenshotKey}:{},...h?.videoKey?{videoKey:h.videoKey}:{},...h?.traceKey?{traceKey:h.traceKey}:{}});}let m=Array.from(g.values()).filter(u=>u.success).length;return m>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${m} artifact(s) to cloud storage.
|
|
4298
|
+
`),{keyMap:s,visualKeyMap:l,total:o.length,uploaded:m}}async function Gt(e,t,r,a,n,s,l,i,d,o,c){let f={realtimeFinalizeAttempted:false,realtimeFinalized:false,batchAttempted:false,batchAcknowledged:false,artifactsTotal:0,artifactsUploaded:0,failureReason:null},v=new Ce(t?.uploadBudgetMs??12e4),g=p=>{f.failureReason||(f.failureReason=p);};try{if(e.isCloudMode()&&n&&(r==="realtime"||r==="both")){f.realtimeFinalizeAttempted=!0;let u=await e.ensureValidToken(),h=e.getGitMetadata(),b=Et(c),y={finishedAt:l,duration:i,summary:d,...h?.commitMessage?{commitMessage:h.commitMessage}:{},testType:b.testType,...b.testType==="api"?{apiProtocol:b.apiProtocol,metadata:b.metadata}:{}};if(u){let w=await Fa(e.getEndpoint(),e.getAccessToken(),n,y);if(f.realtimeFinalized=w,!w){g("finalize_failed_after_retries");let C=t?.queueDirectory??".testrelic/queue";pe(C,a,"finalize","finalize_failed_after_retries",`${e.getEndpoint()}/runs/${n}/finalize`,"POST",y,{"Content-Type":"application/json"});}}else {g(e.getFailureReason()??"token_invalid");let w=t?.queueDirectory??".testrelic/queue";pe(w,a,"finalize",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs/${n}/finalize`,"POST",y,{"Content-Type":"application/json"});}}let p=new Map,m=new Map;if(e.isCloudMode()&&o&&o.length>0){let u=await to(e,t,a,o,v);p=u.keyMap,m=u.visualKeyMap,f.artifactsTotal=u.total,f.artifactsUploaded=u.uploaded;}if(e.isCloudMode()&&(!r||r==="batch"||r==="both"))if(f.batchAttempted=!0,await e.ensureValidToken()){let h=e.getGitMetadata(),b=U(),y=jt(e),w=ao(no(s,p),m),C=Pt(w,y,h,b,ro(c,m),Ie()),P=await La(e.getEndpoint(),e.getAccessToken(),C,async()=>await e.ensureValidToken()?e.getAccessToken():null,t?.timeout,v);if(f.batchAcknowledged=P.success,!P.success){let A=P;g(A.reason);let R=t?.queueDirectory??".testrelic/queue";pe(R,a,"batch",A.reason,A.targetEndpoint,A.method,A.payload,{"Content-Type":"application/json"});}}else {g(e.getFailureReason()??"token_invalid");let h=t?.queueDirectory??".testrelic/queue",b=e.getGitMetadata(),y=U(),w=jt(e),C=Pt(s,w,b,y,void 0,Ie());pe(h,a,"batch",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs`,"POST",C,{"Content-Type":"application/json"});}await e.dispose();}catch(p){g(p instanceof Error?p.message:"unexpected_upload_error");try{await e.dispose();}catch{}}return f}function ro(e,t){return !e||t.size===0?e:e.map(r=>{let a=t.get(r.testId);return a?{...r,visual:a}:r})}function ao(e,t){if(t.size===0)return e;let r=e.timeline.map(a=>{let n=a.tests;if(!Array.isArray(n))return a;let s=false,l=n.map(i=>{let d=i.testId;if(!d)return i;let o=t.get(d);return o?(s=true,{...i,visual:o}):i});return s?{...a,tests:l}:a});return {...e,timeline:r}}function no(e,t){if(t.size===0)return e;let r=e.timeline.map(a=>{let n=a.testId;if(!n)return a;let s=t.get(n);return s?{...a,...s.screenshotKey?{screenshotKey:s.screenshotKey}:{},...s.videoKey?{videoKey:s.videoKey}:{}}:a});return {...e,timeline:r}}var so=new Set(["batch","realtime","both"]),fe=Object.freeze({attempted:false,acknowledged:false,runId:null,endpoint:null,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:"cloud reporting was never initialised"});function io(e){switch(e){case "no_api_key":return "cloud mode off \u2014 no API key configured";case "cloud_unreachable":case "network_error":return "cloud endpoint unreachable \u2014 the run stayed local";case "invalid_api_key":return "API key rejected as invalid or revoked \u2014 the run stayed local";case "expired_api_key":return "API key has expired \u2014 the run stayed local";case "validation_error":return "API key format rejected \u2014 the run stayed local";case "rate_limited":return "rate limited during authentication \u2014 the run stayed local";case "auth_timeout":return "authentication timed out \u2014 the run stayed local";case "token_expired_no_refresh":case "token_refresh_failed":case "token_refresh_error":return "access token could not be refreshed \u2014 the run stayed local";case "init_error":return "cloud initialisation timed out \u2014 the run stayed local";case "unexpected_error":return "cloud initialisation failed \u2014 the run stayed local";default:return e?`cloud mode off (${e}) \u2014 the run stayed local`:"cloud mode off \u2014 the run stayed local"}}function Ja(e,t,r){if(!e)return fe;if(!e.isCloudMode())return {...fe,detail:io(e.getFailureReason())};let a=t??"batch";if(!so.has(a))return {...fe,detail:`upload strategy '${a}' is not recognised \u2014 nothing was sent`};let n=e.getEndpoint(),s=a==="realtime"||a==="both";return s&&r?{attempted:true,acknowledged:true,runId:r,endpoint:n,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:null}:{attempted:true,acknowledged:false,runId:null,endpoint:n,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:s?"run init failed \u2014 the platform did not acknowledge this run":`upload runs at the end of the run under the '${a}' strategy \u2014 not sent yet`}}function Wt(e,t,r){if(!e.attempted)return e;if(!t)return {...e,detail:e.acknowledged?"upload timed out before it completed \u2014 the run may be incomplete on the platform":"upload timed out before the platform acknowledged this run",acknowledged:e.acknowledged};let a=e.acknowledged||t.batchAcknowledged,n=e.runId??(t.batchAcknowledged?r:null),s=t.realtimeFinalizeAttempted?t.realtimeFinalized:t.batchAcknowledged,l=null;return a?s||(l="run acknowledged but not closed out \u2014 finalize failed and was queued for retry"):l=t.failureReason?`upload failed (${t.failureReason}) \u2014 queued locally for retry`:"upload failed \u2014 the platform did not acknowledge this run",{attempted:true,acknowledged:a,runId:n,endpoint:e.endpoint,finalized:s,artifactsUploaded:t.artifactsUploaded,artifactsTotal:t.artifactsTotal,detail:l}}function j(e){try{return readFileSync(e,"utf-8").split(`
|
|
4299
|
+
`).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function go(e){if(!e)return null;let t=e.split(`
|
|
4300
|
+
`).map(s=>s.trim()).filter(Boolean);if(t.length===0)return null;let r=t.filter(s=>!/^Error:\s*expect\(/.test(s));if(r.length===0)return t[0]??null;let a=r[0],n=r[1];return n!==void 0&&/^Received:/.test(n)&&/^Expected:/.test(a)?`${a} \xB7 ${n}`:a}function Jt(e){switch(e){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function ho(e,t,r){let a=`${e}::${t}::${r}`;return createHash("sha256").update(a).digest("hex").substring(0,16)}function mo(e){return e.length<=3?"":e[e.length-2]}function vo(e){let t=e.findIndex(r=>r.status==="passed");return t>0?`passed on retry ${t}`:null}function rn(e){return e===null?"error":e>=200&&e<300?"2xx":e>=300&&e<400?"3xx":e>=400&&e<500?"4xx":e>=500&&e<600?"5xx":"error"}function bo(e){let t={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},r=t;for(let a of e){let n=typeof a.responseStatusCode=="number"?a.responseStatusCode:null;r[rn(n)]++;}return t}function Qa(e){if(e){for(let t of e)if(t.status==="failed")return {type:t.type,expected:en(t.expected),actual:en(t.actual),...t.expression?{expression:t.expression}:{}}}}function en(e){if(e===void 0)return "undefined";if(e===null)return "null";let t;if(typeof e=="string")t=e;else try{t=JSON.stringify(e)??String(e);}catch{t=String(e);}return t.length>200?t.slice(0,200)+"\u2026":t}function Le(e,t){if(!e)return 0;let r=0;for(let a of e)a.status===t&&r++;return r}function an(e,t){for(let r of e)t[r.category]=(t[r.category]??0)+1,r.children.length>0&&an(r.children,t);}function yo(e){if(e.length===0)return null;let t=[...e].sort((a,n)=>a-n),r=t.reduce((a,n)=>a+n,0);return {avg:Math.round(r/t.length),min:t[0],max:t[t.length-1],p50:Y(t,50),p95:Y(t,95),p99:Y(t,99)}}var nn=2e5,De=1e5;function tn(e,t,r,a,n,s,l){let i={retryIndex:e,apiCalls:t?.length??0,apiUrls:[],methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,assertions:r.length,navigations:a.length,navUrls:[],networkRequests:n,consoleLogs:s,actionSteps:l?.length??0,actionCategories:{}};if(t){let o=new Set;for(let c of t){let f=typeof c.method=="string"?c.method:"OTHER";i.methodCounts[f]=(i.methodCounts[f]??0)+1;let v=typeof c.url=="string"?c.url:null;v&&o.size<De&&o.add(St(v));let g=typeof c.responseStatusCode=="number"?c.responseStatusCode:typeof c.statusCode=="number"?c.statusCode:null,p=g!==null&&Number.isFinite(g)?g:null;i.statusRanges[rn(p)]++;let m=typeof c.responseTimeMs=="number"?c.responseTimeMs:typeof c.durationMs=="number"?c.durationMs:null;m!==null&&Number.isFinite(m)&&i.responseTimes.length<nn&&i.responseTimes.push(m);}i.apiUrls=Array.from(o);}for(let o of r)o.status==="passed"?i.passedAssertions++:i.failedAssertions++;let d=new Set;for(let o of a)o.url&&d.size<De&&d.add(o.url);return i.navUrls=Array.from(d),l&&an(l,i.actionCategories),i}function xo(){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 wo(e){return process.env.BROWSERSTACK_USERNAME?"BrowserStack":e?{"github-actions":"GitHub Actions","gitlab-ci":"GitLab CI",jenkins:"Jenkins",circleci:"CircleCI","bitbucket-pipelines":"Bitbucket Pipelines"}[e.provider]??"CI":"Local"}function ko(){let e=platform();return e==="win32"?"Windows":e==="darwin"?"macOS":"Linux"}function So(e){let t=e.parent?.project?.()?.use;if(!t)return;let{browserName:r,channel:a}=t;if(a){let s=a.toLowerCase();return s==="chrome"||s==="chrome-stable"?"Chrome":s.startsWith("chrome-beta")?"Chrome Beta":s.startsWith("chrome-dev")?"Chrome Dev":s.startsWith("chrome-canary")?"Chrome Canary":s==="msedge"||s==="msedge-stable"?"Microsoft Edge":s.startsWith("msedge-beta")?"Edge Beta":s.startsWith("msedge-dev")?"Edge Dev":s.startsWith("msedge-canary")?"Edge Canary":a}if(r){let s=r.toLowerCase();return s==="chromium"?"Chromium":s==="firefox"?"Firefox":s==="webkit"?"WebKit":r}let n=t.defaultBrowserType;if(n){let s=n.toLowerCase();return s==="chromium"?"Chromium":s==="firefox"?"Firefox":s==="webkit"?"WebKit":n}}function Co(e,t,r){let a=r.parent?.project?.(),n="unknown";a!==void 0&&(a.use.isMobile===true?n="mobile":n="e2e");let s=["e2e","api","unit","mobile"];for(let d of s)if(e.some(o=>o===`@${d}`||o===d))return d;let l=t.replace(/\\/g,"/"),i=["e2e","api","unit"];for(let d of i)if(l.includes(`/${d}/`))return d;return n}var To="__testrelic_api_config";function Ro(e){return JSON.stringify(e,(t,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var Ne=class{constructor(t){this.rootDir="";this.configDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.navigationsCaptured=false;this.memoryPressureWarned=false;this.testCount=0;this.cloudClient=null;this.cloudRunId=null;this.runTimestamp="";this.updatingSnapshots=false;this.cloudReceipt=fe;this.pendingArtifactEntries=[];this.detectedOs="";this.detectedSource="";this.cloudTestsBuffer=[];this.activeReportMode="embedded";this.streamingWriter=null;this.testIndex=[];this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0,visualChecks:0,visualFailures:0,visualDomChanges:0};this.streamingTestAgg=new Map;this.config=gr(t),this.apiConfig=fr(t);}upsertAggContribution(t,r){let a=this.streamingTestAgg.get(t);(!a||r.retryIndex>a.retryIndex)&&this.streamingTestAgg.set(t,r);}async onBegin(t,r){try{this.rootDir=t.rootDir,this.configDir=t.configFile?dirname(t.configFile):"";let a=t.updateSnapshots;if(this.updatingSnapshots=a==="all"||a==="changed",this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??randomUUID(),this.config.reportMode==="auto"){let i=r.allTests().length;this.activeReportMode=i>=this.config.streamingThreshold?"streaming":"embedded";}else this.activeReportMode=this.config.reportMode;let n=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${n} tests)
|
|
4301
|
+
`),this.activeReportMode==="streaming"){let i=dirname(this.config.outputPath);this.streamingWriter=new ie(i);let d=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let o={testRunId:this.testRunId??"",startedAt:this.startedAt,completedAt:new Date().toISOString(),totalDuration:Date.now()-new Date(this.startedAt).getTime(),...this.summaryCounters,metadata:null,reportMode:"streaming",files:[],enrichedSummary:null,validation:null,writeErrors:this.streamingWriter.getWriteErrors(),cloudUpload:this.cloudReceipt};this.streamingWriter.writeSummary(o);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let o=this.cloudClient.getAccessToken();o&&Bt(this.cloudClient.getEndpoint(),o,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",d),process.on("SIGINT",d);}if(this.config.includeArtifacts){let i=dirname(this.config.outputPath);this.runTimestamp=Yr(join(i,"artifacts"));try{fa(join(i,"artifacts"));}catch{}}let s=U();this.detectedOs=ko(),this.detectedSource=wo(s);let l=await J(async()=>(this.cloudClient=new _e(this.config.cloud),await this.cloudClient.initialize(),Ka(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource)),ha,"Cloud initialization");if(this.cloudRunId=l??null,l===void 0&&this.cloudClient?.switchToLocalMode("init_error"),this.cloudReceipt=Ja(this.cloudClient,this.config.cloud?.uploadStrategy,this.cloudRunId),this.activeReportMode!=="streaming"){let i=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let d=this.cloudClient.getAccessToken();d&&Bt(this.cloudClient.getEndpoint(),d,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",i),process.on("SIGINT",i);}}catch{}}onTestBegin(t,r){try{t.annotations.push({type:To,description:Ro(this.apiConfig)});}catch{}}onTestEnd(t,r){try{let a=r,n=t.outcome(),s;n==="flaky"?s="flaky":n==="skipped"?s="skipped":s=Jt(a.status);let l=a.startTime.toISOString(),i=new Date(a.startTime.getTime()+a.duration).toISOString(),d=t.tags?[...t.tags]:t.annotations.filter(_=>_.type==="tag").map(_=>_.description??""),o=Ga(a.attachments,t.annotations,t.title,s==="skipped");(o.navigations.length>0||o.networkRequestsCount>0||o.apiCallsCount>0)&&(this.fixtureDataReceived=!0),o.navigations.length>0&&(this.navigationsCaptured=!0),!this.config.captureNavigation&&o.navigations.length>0&&(o={...o,navigations:[]});let c=null;if(s==="failed"||s==="flaky"){let T=(s==="flaky"?t.results.find(B=>B.status!=="passed")?.errors??[]:a.errors)[0];if(T){let B=mr(this.config.redactPatterns),ae=T.location?.file??null,I=o.apiAssertions.find(sn=>sn.status==="failed")?.location??null,Z=I!==null&&(ae===null||resolve(ae)!==resolve(t.location.file)),Qt=Z?I.file:ae,Fe=Z?I.line:T.location?.line??null,ne=null;this.config.includeCodeSnippets&&Fe!==null&&Qt&&(ne=hr(Qt,Fe,this.config.codeContextLines),ne&&(ne=B(ne))),c={message:B(ke(T.message??"Unknown error")),line:Fe,code:ne,stack:this.config.includeStackTrace&&T.stack?B(ke(T.stack)):null};}}let f=t.titlePath().filter(Boolean),v=relative(this.rootDir||".",t.location.file).replace(/\\/g,"/"),g=mo(f),p=f.join(" > "),m=v,u=ho(m,g,p),h=Co(d,m,t),b=h!=="mobile"&&o.apiCallsCount>0?"api":h,y=n==="flaky",w=vo(t.results),C=Jt(t.expectedStatus),P=Jt(a.status),A=null;if(this.config.includeArtifacts&&s!=="skipped"&&a.attachments){let _=dirname(this.config.outputPath),T=f[f.length-1]??t.title;A=Zr(a.attachments,T,a.retry,_,this.runTimestamp||void 0,u);}let R=null;if(this.config.includeArtifacts&&s!=="skipped"&&a.attachments)try{let _=aa(a.attachments,{updatingSnapshots:this.updatingSnapshots,failureMessage:a.errors.map(T=>T.message??"").join(`
|
|
4302
|
+
`)});if(_.length>0){let T=dirname(this.config.outputPath),B=f[f.length-1]??t.title;R=Qr(_,B,a.retry,T,this.runTimestamp||void 0,u,this.configDir||this.rootDir||process.cwd());}}catch{}let L=this.config.includeActionSteps&&a.steps?wa(a.steps,a.startTime):null,x=So(t),S={titlePath:f,title:p,status:s,duration:a.duration,startedAt:l,completedAt:i,retryCount:t.results.length-1,retry:a.retry,tags:d,failure:c,specFile:v,navigations:o.navigations,testId:u,filePath:m,suiteName:g,testType:b,isFlaky:y,retryStatus:w,expectedStatus:C,actualStatus:P,artifacts:A,visual:R,apiAssertions:o.apiAssertions,actions:L,networkRequestsFile:o.networkRequestsFile,networkRequestsCount:o.networkRequestsCount,consoleLogsFile:o.consoleLogsFile,consoleLogsCount:o.consoleLogsCount,apiCallsFile:o.apiCallsFile,apiCallsCount:o.apiCallsCount,apiStatusMix:o.apiStatusMix,browser:x,os:this.detectedOs||void 0,source:this.detectedSource||void 0},X=o.consoleLogsFile&&o.consoleLogsCount>0?j(o.consoleLogsFile):void 0,G=o.networkRequestsFile&&o.networkRequestsCount>0?j(o.networkRequestsFile):void 0,re=o.apiCallsFile&&o.apiCallsCount>0?j(o.apiCallsFile):void 0,Yt=re?Lt(re):void 0,Xt=!G&&re?Dt(re):void 0,Zt=o.apiAssertions&&o.apiAssertions.length>0?Nt(o.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:u,title:p,status:s,duration:a.duration,suiteName:g,filePath:m,testType:b,isFlaky:y,startedAt:l,completedAt:i,tags:d,failure:c,retry:a.retry,retryCount:t.results.length-1,retryStatus:w,browser:x,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...L&&L.length>0?{actions:L}:{},...o.navigations&&o.navigations.length>0?{navigations:o.navigations}:{},...X?{consoleLogs:X}:{},...G?{networkRequests:G}:Xt?{networkRequests:Xt}:{},...Yt?{apiCalls:Yt}:{},...Zt?{protocolAssertions:Zt}:{},...R&&R.length>0?{visual:R}:{}});try{let _=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(_==="realtime"||_==="both")){let T=this.cloudClient.getAccessToken();T&&Na(this.cloudClient.getEndpoint(),T,this.cloudRunId,this.buildCloudTestPayload(S));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let _=Be(m,f,t.id??"",a.retry),T=a.retry===t.results.length-1,B={id:_,navigations:o.navigations,apiAssertions:o.apiAssertions,actions:L??[],artifacts:A,visual:R,failureDiagnostic:c,hasNetworkFile:o.networkRequestsFile!==null,networkRequestsCount:o.networkRequestsCount,hasConsoleFile:o.consoleLogsFile!==null,consoleLogsCount:o.consoleLogsCount,hasApiCallsFile:o.apiCallsFile!==null,apiCallsCount:o.apiCallsCount,startedAt:l};this.streamingWriter.writeTestDetail(_,B,{networkRequestsFile:o.networkRequestsFile,consoleLogsFile:o.consoleLogsFile,apiCallsFile:o.apiCallsFile});let ae={id:_,title:f[f.length-1]??t.title,titlePath:f,filePath:m,status:s,...C!=="passed"?{expectedStatus:C}:{},duration:a.duration,project:f[1]??"",retryIndex:a.retry,tags:d,hasNetworkData:o.networkRequestsCount>0,hasConsoleData:o.consoleLogsCount>0,hasArtifacts:A!==null,hasActionSteps:(L?.length??0)>0,visualCount:R?.length??0,visualFailedCount:R?.filter(I=>I.status==="failed").length??0,domChangeCount:R?.reduce((I,Z)=>I+(Z.domChangeCount??0),0)??0,...(()=>{let I=R?.find(Z=>Z.diff);return I?.diff?{visualDiffPath:I.diff}:{}})(),errorMessage:go(c?.message),networkCount:o.networkRequestsCount,consoleCount:o.consoleLogsCount,actionCount:L?.length??0,testType:b,apiCallCount:o.apiCallsCount,...o.apiStatusMix?{apiStatusMix:o.apiStatusMix}:{},assertionsPassed:Le(o.apiAssertions,"passed"),assertionsFailed:Le(o.apiAssertions,"failed"),...(()=>{let I=Qa(o.apiAssertions);return I?{firstFailedAssertion:I}:{}})(),isRetry:!T,retryGroupKey:Oe(m,f,t.id??"")};if(this.testIndex.push(ae),T)switch(this.summaryCounters.total++,s){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.upsertAggContribution(`${m}::${f.join(" > ")}`,tn(a.retry,re,o.apiAssertions,o.navigations,o.networkRequestsCount,o.consoleLogsCount,L)),(A||R)&&this.pendingArtifactEntries.push({testId:u,artifacts:A??{},visual:R,outputDir:dirname(this.config.outputPath)}),S.actions=null,S.apiAssertions=null,S.navigations=[],S.artifacts=null,S.failure=null,S.networkRequestsFile=null,S.consoleLogsFile=null,S.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(S),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(t){try{let r=new Date().toISOString(),a=new Date(this.startedAt).getTime(),s=new Date(r).getTime()-a,l=this.activeReportMode==="streaming"?this.testIndex.some(d=>d.status!=="skipped"):this.collectedTests.some(d=>d.status!=="skipped");!this.fixtureDataReceived&&l&&process.stderr.write(`
|
|
4299
4303
|
\u26A0 TestRelic: No fixture data received from any test.
|
|
4300
4304
|
To enable network logs, video sync, and Test Navigation tracking, import the TestRelic fixture:
|
|
4301
4305
|
import { test, expect } from '@testrelic/playwright-analytics/fixture';
|
|
@@ -4304,14 +4308,14 @@ ${n}
|
|
|
4304
4308
|
|
|
4305
4309
|
`),this.config.captureNavigation?this.fixtureDataReceived&&!this.navigationsCaptured&&l&&process.stderr.write(`[testrelic] Test Navigation: 0 navigation events captured this run. Navigation is recorded automatically on page.goto()/clicks; if you expected a navigation graph, ensure your tests drive page navigations (and use the '@testrelic/playwright-analytics/fixture' import).
|
|
4306
4310
|
`):process.stderr.write(`[testrelic] Test Navigation capture is disabled (captureNavigation: false). Remove the option or set it to true to capture the navigation graph.
|
|
4307
|
-
`),await J(()=>
|
|
4308
|
-
`);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:o.apiUrlSet.size,apiCallsByMethod:{...o.methodCounts},apiCallsByStatusRange:{"2xx":o.statusRanges["2xx"],"3xx":o.statusRanges["3xx"],"4xx":o.statusRanges["4xx"],"5xx":o.statusRanges["5xx"],error:o.statusRanges.error},apiResponseTime:
|
|
4311
|
+
`),await J(()=>Jr(),kt,"Artifact flush");let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let d=dirname(this.config.outputPath);i=ca(d,this.runTimestamp);let o=join(d,"artifact-manifest.json"),c=JSON.stringify(i),f=o+".tmp";writeFileSync(f,c,"utf-8"),renameSync(f,o);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await J(()=>this.finalizeStreamingReport(r,s,t,i),wt,"Report finalization");else {let d=this.buildTimeline(),o=new Map;for(let g of this.collectedTests){let p=o.get(g.testId);(!p||g.retry>p.retry)&&o.set(g.testId,g);}let c=Array.from(o.values()),f=xa(c,d.length),v={schemaVersion:ze,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:s,summary:f,ci:U(),metadata:this.config.metadata,timeline:d,shardRunIds:null};if(this.writeReport(v),await J(()=>gt(v,this.config,i),kt,"HTML report write"),Ct(f,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient){let g=this.collectArtifactEntries(),p=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0;let m=await J(()=>Gt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,v,r,s,f,g,p),wt,"Cloud upload");this.cloudReceipt=Wt(this.cloudReceipt,m,this.testRunId);}}}catch{}finally{await this.disposeCloudClient();}}async disposeCloudClient(){let t=this.cloudClient;t&&(this.cloudClient=null,await J(()=>t.dispose(),ma,"Cloud client shutdown"));}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let t=dirname(this.config.outputPath),r=[];for(let a of this.collectedTests)(a.artifacts||a.visual)&&r.push({testId:a.testId,artifacts:a.artifacts??{},visual:a.visual,outputDir:t});return r}async finalizeStreamingReport(t,r,a,n){if(!this.streamingWriter)return;this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0,visualChecks:0,visualFailures:0,visualDomChanges:0};let s=new Map,l=new Map;for(let u of this.testIndex){let h=`${u.filePath}::${u.titlePath.join(" > ")}`,b=s.get(h);(b===void 0||u.retryIndex>b)&&s.set(h,u.retryIndex);}let i=0;for(let u of this.testIndex){let h=`${u.filePath}::${u.titlePath.join(" > ")}`,b=s.get(h);if(u.isRetry=u.retryIndex<b,u.isRetry)continue;switch(i++,this.summaryCounters.total++,u.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.summaryCounters.visualChecks+=u.visualCount??0,this.summaryCounters.visualFailures+=u.visualFailedCount??0,this.summaryCounters.visualDomChanges+=u.domChangeCount??0;let y=l.get(u.filePath);switch(y||(y={filePath:u.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},l.set(u.filePath,y)),y.total++,u.status){case "passed":y.passed++;break;case "failed":y.failed++;break;case "flaky":y.flaky++;break;case "skipped":y.skipped++;break;case "timedout":y.timedOut++;break}}let d=Array.from(l.values()),o=xo();for(let u of this.streamingTestAgg.values()){o.volApiCalls+=u.apiCalls,o.volAssertions+=u.assertions,o.volNavigations+=u.navigations,o.volNetworkRequests+=u.networkRequests,o.volConsoleLogs+=u.consoleLogs,o.volActionSteps+=u.actionSteps;for(let h in u.methodCounts)o.methodCounts[h]=(o.methodCounts[h]??0)+u.methodCounts[h];o.statusRanges["2xx"]+=u.statusRanges["2xx"],o.statusRanges["3xx"]+=u.statusRanges["3xx"],o.statusRanges["4xx"]+=u.statusRanges["4xx"],o.statusRanges["5xx"]+=u.statusRanges["5xx"],o.statusRanges.error+=u.statusRanges.error,o.passedAssertions+=u.passedAssertions,o.failedAssertions+=u.failedAssertions;for(let h in u.actionCategories)o.actionCategoryCounts[h]=(o.actionCategoryCounts[h]??0)+u.actionCategories[h];for(let h of u.apiUrls){if(o.apiUrlSet.size>=De)break;o.apiUrlSet.add(h);}for(let h of u.navUrls){if(o.navUrlSet.size>=De)break;o.navUrlSet.add(h);}for(let h of u.responseTimes){if(o.responseTimes.length>=nn)break;o.responseTimes.push(h);}}this.summaryCounters.totalApiCalls=o.volApiCalls,this.summaryCounters.totalAssertions=o.volAssertions,this.summaryCounters.totalNavigations=o.volNavigations,this.summaryCounters.totalNetworkRequests=o.volNetworkRequests,this.summaryCounters.totalConsoleLogs=o.volConsoleLogs,this.summaryCounters.totalActionSteps=o.volActionSteps,this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let c={reporterTotal:this.summaryCounters.total,indexTotal:i,playwrightStatus:a.status,isValid:this.summaryCounters.total===i};c.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${c.reporterTotal}, index: ${c.indexTotal}
|
|
4312
|
+
`);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:o.apiUrlSet.size,apiCallsByMethod:{...o.methodCounts},apiCallsByStatusRange:{"2xx":o.statusRanges["2xx"],"3xx":o.statusRanges["3xx"],"4xx":o.statusRanges["4xx"],"5xx":o.statusRanges["5xx"],error:o.statusRanges.error},apiResponseTime:yo(o.responseTimes),totalAssertions:this.summaryCounters.totalAssertions,passedAssertions:o.passedAssertions,failedAssertions:o.failedAssertions,totalNavigations:this.summaryCounters.totalNavigations,uniqueNavigationUrls:o.navUrlSet.size,totalTimelineSteps:i,totalActionSteps:this.summaryCounters.totalActionSteps,actionStepsByCategory:{...o.actionCategoryCounts},visualChecks:this.summaryCounters.visualChecks,visualFailures:this.summaryCounters.visualFailures,visualDomChanges:this.summaryCounters.visualDomChanges},v={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:t,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:d,enrichedSummary:f,validation:c,writeErrors:this.streamingWriter.getWriteErrors(),cloudUpload:this.cloudReceipt};this.streamingWriter.writeSummary(v);let g={schemaVersion:"2.0",generatedAt:new Date().toISOString(),reportMode:"streaming",summaryFile:"summary.json",indexFile:"index.json",testsDir:"tests",artifactsDir:"artifacts",testCount:this.testIndex.length,totalSizeBytes:this.streamingWriter.computeTotalSize()};this.streamingWriter.writeManifest(g),await gt(this.buildStreamingReport(v,f,t,r),this.config,n),Ct(f,this.config.outputPath,this.config.htmlReportPath,this.config.quiet);let p=this.streamingWriter.getReportDir();process.stderr.write(`[testrelic] Streaming report written to ${p}
|
|
4309
4313
|
[testrelic] ${this.testIndex.length} test detail files on disk
|
|
4310
4314
|
[testrelic] View report: npx testrelic serve ${p}
|
|
4311
4315
|
`),this.streamingWriter.getWriteErrors().length>0&&process.stderr.write(`[testrelic] WARNING: ${this.streamingWriter.getWriteErrors().length} write error(s) during streaming
|
|
4312
4316
|
`);let m=this.streamingWriter;try{if(this.cloudClient){let u=this.buildStreamingReport(v,f,t,r),h=this.collectArtifactEntries(),b=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0;let y=await Gt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,u,t,r,f,h,b);this.cloudReceipt=Wt(this.cloudReceipt,y,this.testRunId);let w={...v,cloudUpload:this.cloudReceipt};try{m.writeSummary(w);}catch{}}}finally{m.dispose();}this.testIndex.length=0,this.collectedTests.length=0,this.pendingArtifactEntries.length=0,this.cloudTestsBuffer.length=0,this.streamingWriter=null,this.cloudClient=null;}buildStreamingReport(t,r,a,n){return {schemaVersion:ze,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:a,totalDuration:n,summary:r,ci:U(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let t=process.memoryUsage(),r=t.heapUsed/1024/1024;if(r<200)return;let a=t.heapUsed/t.heapTotal;a>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
|
|
4313
4317
|
`),this.switchToStreamingMode()):a>.8&&r>=500&&!this.memoryPressureWarned&&(this.memoryPressureWarned=!0,process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
|
|
4314
|
-
`));}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let t=dirname(this.config.outputPath);this.streamingWriter=new ie(t);for(let r of this.collectedTests){let a=Be(r.filePath,r.titlePath,r.testId,r.retry),n=r.apiCallsFile&&r.apiCallsCount>0?j(r.apiCallsFile):void 0,s={id:a,navigations:r.navigations??[],apiAssertions:r.apiAssertions??[],actions:r.actions??[],artifacts:r.artifacts,failureDiagnostic:r.failure,hasNetworkFile:r.networkRequestsFile!==null,networkRequestsCount:r.networkRequestsCount,hasConsoleFile:r.consoleLogsFile!==null,consoleLogsCount:r.consoleLogsCount,hasApiCallsFile:r.apiCallsFile!==null,apiCallsCount:r.apiCallsCount,startedAt:r.startedAt};this.streamingWriter.writeTestDetail(a,s,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let l={id:a,title:r.titlePath[r.titlePath.length-1]??r.title,titlePath:r.titlePath,filePath:r.filePath,status:r.status,duration:r.duration,project:r.titlePath[1]??"",retryIndex:r.retry,tags:r.tags,hasNetworkData:r.networkRequestsCount>0,hasConsoleData:r.consoleLogsCount>0,hasArtifacts:r.artifacts!==null,hasActionSteps:(r.actions?.length??0)>0,errorMessage:r.failure?.message?.split(`
|
|
4315
|
-
`)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,testType:r.testType,apiCallCount:r.apiCallsCount,...r.apiStatusMix?{apiStatusMix:r.apiStatusMix}:n?{apiStatusMix:
|
|
4318
|
+
`));}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let t=dirname(this.config.outputPath);this.streamingWriter=new ie(t);for(let r of this.collectedTests){let a=Be(r.filePath,r.titlePath,r.testId,r.retry),n=r.apiCallsFile&&r.apiCallsCount>0?j(r.apiCallsFile):void 0,s={id:a,navigations:r.navigations??[],apiAssertions:r.apiAssertions??[],actions:r.actions??[],artifacts:r.artifacts,failureDiagnostic:r.failure,hasNetworkFile:r.networkRequestsFile!==null,networkRequestsCount:r.networkRequestsCount,hasConsoleFile:r.consoleLogsFile!==null,consoleLogsCount:r.consoleLogsCount,hasApiCallsFile:r.apiCallsFile!==null,apiCallsCount:r.apiCallsCount,startedAt:r.startedAt};this.streamingWriter.writeTestDetail(a,s,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let l={id:a,title:r.titlePath[r.titlePath.length-1]??r.title,titlePath:r.titlePath,filePath:r.filePath,status:r.status,...r.expectedStatus!=="passed"?{expectedStatus:r.expectedStatus}:{},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(`
|
|
4319
|
+
`)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,testType:r.testType,apiCallCount:r.apiCallsCount,...r.apiStatusMix?{apiStatusMix:r.apiStatusMix}:n?{apiStatusMix:bo(n)}:{},assertionsPassed:Le(r.apiAssertions,"passed"),assertionsFailed:Le(r.apiAssertions,"failed"),...(()=>{let i=Qa(r.apiAssertions);return i?{firstFailedAssertion:i}:{}})(),isRetry:!1,retryGroupKey:Oe(r.filePath,r.titlePath,r.testId)};switch(this.testIndex.push(l),this.summaryCounters.total++,r.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.upsertAggContribution(`${r.filePath}::${r.titlePath.join(" > ")}`,tn(r.retry,n,r.apiAssertions??[],r.navigations??[],r.networkRequestsCount,r.consoleLogsCount,r.actions??null));}this.collectedTests.length=0;}catch{}}buildTimeline(){let t=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls:null,apiAssertions:r.apiAssertions,testId:r.testId,filePath:r.filePath,suiteName:r.suiteName,testType:r.testType,isFlaky:r.isFlaky,retryStatus:r.retryStatus,expectedStatus:r.expectedStatus,actualStatus:r.actualStatus,artifacts:r.artifacts,networkRequests:null,actions:r.actions,consoleLogs:null}));return ya(t,{navigationTypes:this.config.navigationTypes})}readJsonlFile(t){if(!t)return null;let r=j(t);return r.length>0?r:null}toTestResult(t,r){let a=null,n=null,s=null;return r?.loadFiles&&(a=this.readJsonlFile(t.networkRequestsFile),n=this.readJsonlFile(t.consoleLogsFile),s=this.readJsonlFile(t.apiCallsFile)),{title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retryCount:t.retryCount,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,retryStatus:t.retryStatus,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,visual:t.visual,networkRequests:a,apiCalls:s,apiAssertions:t.apiAssertions,actions:t.actions??null,consoleLogs:n}}buildCloudTestPayload(t){let r={title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retry:t.retry,retryCount:t.retryCount,retryStatus:t.retryStatus,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,visual:t.visual??[],actions:t.actions??[],navigations:t.navigations??[],steps:t.actions??[],browser:t.browser,os:t.os,source:t.source};if(t.apiAssertions&&t.apiAssertions.length>0&&(r.protocolAssertions=Nt(t.apiAssertions)),t.consoleLogsFile&&(r.consoleLogs=j(t.consoleLogsFile)),t.networkRequestsFile&&(r.networkRequests=j(t.networkRequestsFile)),t.apiCallsFile){let a=j(t.apiCallsFile);r.apiCalls=Lt(a),(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=Dt(a));}return r}writeReport(t){try{let r=JSON.stringify(t),a=this.config.outputPath,n=dirname(a);mkdirSync(n,{recursive:!0});let s=a+".tmp";writeFileSync(s,r,"utf-8"),renameSync(s,a);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
|
|
4316
4320
|
`);}}};export{Ne as default};//# sourceMappingURL=reporter-entry.js.map
|
|
4317
4321
|
//# sourceMappingURL=reporter-entry.js.map
|