@testrelic/playwright-analytics 2.9.0-next.71 → 2.9.0-next.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
- 'use strict';var crypto=require('crypto'),fs$1=require('fs'),path=require('path'),os=require('os'),core=require('@testrelic/core'),child_process=require('child_process'),http=require('http'),readline=require('readline'),promises=require('fs/promises'),zlib=require('zlib'),stream=require('stream');var qr=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var zr=".testrelic-report";function xe(t,e,r,a){let n=`${t}|${e.join("|")}|${r}|${a}`;return crypto.createHash("sha256").update(n).digest("hex").substring(0,12)}var G=class{constructor(e){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=path.join(e,zr),this.testsDir=path.join(this.reportDir,"tests"),fs$1.mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(e,r,a){try{let n=path.join(this.testsDir,e);fs$1.mkdirSync(n,{recursive:!0});let s=path.join(n,"meta.json"),o=s+".tmp",i=JSON.stringify(r);return fs$1.writeFileSync(o,i,"utf-8"),fs$1.renameSync(o,s),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),a?.networkRequestsFile&&this.moveFile(a.networkRequestsFile,path.join(n,"network.jsonl")),a?.consoleLogsFile&&this.moveFile(a.consoleLogsFile,path.join(n,"console.jsonl")),a?.apiCallsFile&&this.moveFile(a.apiCallsFile,path.join(n,"api-calls.jsonl")),!0}catch(n){let s=n instanceof Error?n.message:String(n);return this.writeErrors.push({testId:e,error:s,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${e}: ${s}
2
- `),false}}moveFile(e,r){try{fs$1.renameSync(e,r);}catch{try{let{copyFileSync:a}=qr("fs");a(e,r);try{fs$1.unlinkSync(e);}catch{}}catch(a){process.stderr.write(`[testrelic] Failed to move file ${e} \u2192 ${r}: ${a instanceof Error?a.message:String(a)}
3
- `);}}}writeIndex(e){let r=path.join(this.reportDir,"index.json"),a=r+".tmp",n=JSON.stringify(e);fs$1.writeFileSync(a,n,"utf-8"),fs$1.renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeCompactIndex(e){let r=path.join(this.reportDir,"index-compact.json"),a=r+".tmp",n=e.map(({titlePath:o,project:i,...l})=>l),s=JSON.stringify(n);fs$1.writeFileSync(a,s,"utf-8"),fs$1.renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeSummary(e){let r=path.join(this.reportDir,"summary.json"),a=r+".tmp",n=JSON.stringify(e);fs$1.writeFileSync(a,n,"utf-8"),fs$1.renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeManifest(e){let r=path.join(this.reportDir,"manifest.json"),a=r+".tmp",n=JSON.stringify(e);fs$1.writeFileSync(a,n,"utf-8"),fs$1.renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var kt=".testrelic",Kr="testrelic-config.json",Jr=".testrelic",Yr=5,Zr=new Set(["__proto__","constructor","prototype"]),xt=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${kt}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),Qr={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function Tt(t){let e=path.resolve(t);for(let r=0;r<=Yr;r++){let a=path.join(e,kt,Kr);if(fs$1.existsSync(a))try{if(fs$1.statSync(a).isFile())return a}catch{}let n=path.join(e,Jr);if(fs$1.existsSync(n))try{if(fs$1.statSync(n).isFile())return process.stderr.write(`[testrelic] Deprecation: config file ".testrelic" has moved to ".testrelic/testrelic-config.json". Please migrate your config file to the new location.
4
- `),n}catch{}let s=path.dirname(e);if(s===e)break;e=s;}return null}function St(t){try{let e=fs$1.readFileSync(t,"utf-8"),r=JSON.parse(e);return typeof r!="object"||r===null||Array.isArray(r)||!Ct(r)?null:r}catch{return null}}function Ct(t){for(let e of Object.keys(t)){if(Zr.has(e))return false;let r=t[e];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!Ct(r))return false}return true}function Rt(t){let e=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(t);if(e)return process.env[e[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(t);return r?process.env[r[1]]??null:t}function we(t){let e=Object.create(null);for(let r of Object.keys(t)){let a=t[r];typeof a=="string"&&a.startsWith("$")?e[r]=Rt(a):typeof a=="object"&&a!==null&&!Array.isArray(a)?e[r]=we(a):e[r]=a;}return e}function wt(t){let e=/^(\d+)\s*([smhd])$/.exec(t.trim());if(!e)return null;let r=parseInt(e[1],10),a=e[2],n=Qr[a];return !n||r<=0?null:r*n}function At(t,e){let r=Object.create(null);if(Object.assign(r,xt),t){let l=t.cloud;l&&typeof l=="object"&&(typeof l.endpoint=="string"&&(r.endpoint=l.endpoint),typeof l.upload=="string"&&(r.uploadStrategy=l.upload),typeof l.timeout=="number"&&(r.timeout=l.timeout),typeof l.apiKey=="string"&&l.apiKey.length>0&&(r.apiKey=l.apiKey));let d=t["testrelic-repo"]??t.project;d&&typeof d=="object"&&typeof d.name=="string"&&(r.projectName=d.name),t.project&&!t["testrelic-repo"]&&process.stderr.write(`[testrelic] Deprecation: "project" key in config is deprecated. Rename it to "testrelic-repo".
5
- `);let p=t.queue;if(p&&typeof p=="object"){if(typeof p.maxAge=="string"){let f=wt(p.maxAge);f!==null&&(r.queueMaxAge=f);}typeof p.directory=="string"&&(r.queueDirectory=p.directory);}}if(e){if(typeof e.apiKey=="string"&&e.apiKey.length>0){let l=e.apiKey.startsWith("$")?Rt(e.apiKey):e.apiKey;l&&(r.apiKey=l);}if(typeof e.endpoint=="string"&&(r.endpoint=e.endpoint),typeof e.upload=="string"&&(r.uploadStrategy=e.upload),typeof e.timeout=="number"&&(r.timeout=e.timeout),typeof e.projectName=="string"&&(r.projectName=e.projectName),typeof e.queueMaxAge=="string"){let l=wt(e.queueMaxAge);l!==null&&(r.queueMaxAge=l);}typeof e.queueDirectory=="string"&&(r.queueDirectory=e.queueDirectory),typeof e.uploadArtifacts=="boolean"&&(r.uploadArtifacts=e.uploadArtifacts),typeof e.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=e.artifactMaxSizeMb);}let a=process.env.TESTRELIC_API_KEY;a&&a.length>0&&(r.apiKey=a);let n=process.env.TESTRELIC_CLOUD_ENDPOINT;n&&core.isValidEndpointUrl(n)&&(r.endpoint=n);let s=process.env.TESTRELIC_UPLOAD_STRATEGY;s&&["batch","realtime","both"].includes(s)&&(r.uploadStrategy=s);let o=process.env.TESTRELIC_CLOUD_TIMEOUT;if(o){let l=parseInt(o,10);!isNaN(l)&&l>=1e3&&l<=12e4&&(r.timeout=l);}let i=Object.freeze(r);return core.isValidCloudConfig(i)?i:xt}var ra=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],aa=["authorization","cookie","set-cookie","x-api-key"],na=["password","secret","token","apiKey","api_key"];function It(t){let e=Object.create(null);return e.trackApiCalls=t?.trackApiCalls??true,e.captureRequestHeaders=t?.captureRequestHeaders??true,e.captureResponseHeaders=t?.captureResponseHeaders??true,e.captureRequestBody=t?.captureRequestBody??true,e.captureResponseBody=t?.captureResponseBody??true,e.captureAssertions=t?.captureAssertions??true,e.redactHeaders=t?.redactHeaders??[...aa],e.redactBodyFields=t?.redactBodyFields??[...na],e.apiIncludeUrls=t?.apiIncludeUrls??[],e.apiExcludeUrls=t?.apiExcludeUrls??[],Object.freeze(e)}function _t(t){if(t!==void 0&&!core.isValidConfig(t))throw core.createError(core.ErrorCode.CONFIG_INVALID,"Invalid reporter configuration");let e=Object.create(null);e.outputPath=t?.outputPath??"./test-results/analytics-timeline.json",e.includeStackTrace=t?.includeStackTrace??false,e.includeCodeSnippets=t?.includeCodeSnippets??true,e.codeContextLines=t?.codeContextLines??3,e.includeNetworkStats=t?.includeNetworkStats??true,e.captureNavigation=t?.captureNavigation??true,e.navigationTypes=t?.navigationTypes??null,e.redactPatterns=[...ra,...t?.redactPatterns??[]],e.testRunId=t?.testRunId??null,e.metadata=t?.metadata??null;let r=e.outputPath;e.openReport=t?.openReport??true,e.htmlReportPath=t?.htmlReportPath??r.replace(/\.json$/,".html"),e.includeArtifacts=t?.includeArtifacts??true,e.trackApiCalls=t?.trackApiCalls??true,e.quiet=t?.quiet??false,e.includeActionSteps=t?.includeActionSteps??true,e.captureConsoleLogs=t?.captureConsoleLogs??true;let a=Tt(process.cwd()),n=a?St(a):null,s=n?we(n):null,o=At(s,t?.cloud);return e.cloud=o.apiKey?o:null,e.reportMode=t?.reportMode??"streaming",e.streamingThreshold=t?.streamingThreshold??0,Object.freeze(e)}var ke="1.3.0";function Lt(t,e,r){try{let n=fs$1.readFileSync(t,"utf-8").split(`
6
- `);if(e<1||e>n.length)return null;let s=Math.max(1,e-r),o=Math.min(n.length,e+r),i=[];for(let l=s;l<=o;l++){let d=l===e?">":" ",p=String(l).padStart(String(o).length," ");i.push(`${d} ${p} | ${n[l-1]}`);}return i.join(`
7
- `)}catch{return null}}function Mt(t){return e=>{let r=e;for(let a of t)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 ia(t){return t.GITHUB_ACTIONS!=="true"?null:{provider:"github-actions",buildId:t.GITHUB_RUN_ID??null,commitSha:t.GITHUB_SHA??null,branch:t.GITHUB_REF_NAME??null,runUrl:t.GITHUB_SERVER_URL&&t.GITHUB_REPOSITORY&&t.GITHUB_RUN_ID?`${t.GITHUB_SERVER_URL}/${t.GITHUB_REPOSITORY}/actions/runs/${t.GITHUB_RUN_ID}`:null}}function oa(t){return t.GITLAB_CI!=="true"?null:{provider:"gitlab-ci",buildId:t.CI_PIPELINE_ID??null,commitSha:t.CI_COMMIT_SHA??null,branch:t.CI_COMMIT_BRANCH??t.CI_COMMIT_REF_NAME??null,runUrl:t.CI_PIPELINE_URL??null}}function la(t){if(!t.JENKINS_URL)return null;let e=t.GIT_BRANCH??null;return e?.startsWith("origin/")&&(e=e.slice(7)),{provider:"jenkins",buildId:t.BUILD_ID??null,commitSha:t.GIT_COMMIT??null,branch:e,runUrl:t.BUILD_URL??null}}function da(t){return t.CIRCLECI!=="true"?null:{provider:"circleci",buildId:t.CIRCLE_BUILD_NUM??null,commitSha:t.CIRCLE_SHA1??null,branch:t.CIRCLE_BRANCH??null,runUrl:t.CIRCLE_BUILD_URL??null}}function ca(t){if(!t.BITBUCKET_PIPELINE_UUID)return null;let e=t.BITBUCKET_WORKSPACE&&t.BITBUCKET_REPO_SLUG&&t.BITBUCKET_PIPELINE_UUID?`https://bitbucket.org/${t.BITBUCKET_WORKSPACE}/${t.BITBUCKET_REPO_SLUG}/pipelines/results/${t.BITBUCKET_PIPELINE_UUID}`:null;return {provider:"bitbucket-pipelines",buildId:t.BITBUCKET_BUILD_NUMBER??null,commitSha:t.BITBUCKET_COMMIT??null,branch:t.BITBUCKET_BRANCH??null,runUrl:e}}var ua=[ia,oa,la,da,ca];function P(t){let e=process.env;for(let r of ua){let a=r(e);if(a)return a}return null}var Te=`
1
+ 'use strict';var crypto=require('crypto'),fs$1=require('fs'),path=require('path'),os$1=require('os'),core=require('@testrelic/core'),child_process=require('child_process'),http=require('http'),readline=require('readline'),promises=require('fs/promises'),zlib=require('zlib'),util=require('util'),stream=require('stream');var Kr=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Zr=".testrelic-report";function we(t,e,r,s){let a=`${t}|${e.join("|")}|${r}|${s}`;return crypto.createHash("sha256").update(a).digest("hex").substring(0,12)}var K=class{constructor(e){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=path.join(e,Zr),this.testsDir=path.join(this.reportDir,"tests"),fs$1.mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(e,r,s){try{let a=path.join(this.testsDir,e);fs$1.mkdirSync(a,{recursive:!0});let n=path.join(a,"meta.json"),o=n+".tmp",i=JSON.stringify(r);return fs$1.writeFileSync(o,i,"utf-8"),fs$1.renameSync(o,n),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),s?.networkRequestsFile&&this.moveFile(s.networkRequestsFile,path.join(a,"network.jsonl")),s?.consoleLogsFile&&this.moveFile(s.consoleLogsFile,path.join(a,"console.jsonl")),s?.apiCallsFile&&this.moveFile(s.apiCallsFile,path.join(a,"api-calls.jsonl")),!0}catch(a){let n=a instanceof Error?a.message:String(a);return this.writeErrors.push({testId:e,error:n,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${e}: ${n}
2
+ `),false}}moveFile(e,r){try{fs$1.renameSync(e,r);}catch{try{let{copyFileSync:s}=Kr("fs");s(e,r);try{fs$1.unlinkSync(e);}catch{}}catch(s){process.stderr.write(`[testrelic] Failed to move file ${e} \u2192 ${r}: ${s instanceof Error?s.message:String(s)}
3
+ `);}}}writeIndex(e){let r=path.join(this.reportDir,"index.json"),s=r+".tmp",a=JSON.stringify(e);fs$1.writeFileSync(s,a,"utf-8"),fs$1.renameSync(s,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}writeCompactIndex(e){let r=path.join(this.reportDir,"index-compact.json"),s=r+".tmp",a=e.map(({titlePath:o,project:i,...l})=>l),n=JSON.stringify(a);fs$1.writeFileSync(s,n,"utf-8"),fs$1.renameSync(s,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeSummary(e){let r=path.join(this.reportDir,"summary.json"),s=r+".tmp",a=JSON.stringify(e);fs$1.writeFileSync(s,a,"utf-8"),fs$1.renameSync(s,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}writeManifest(e){let r=path.join(this.reportDir,"manifest.json"),s=r+".tmp",a=JSON.stringify(e);fs$1.writeFileSync(s,a,"utf-8"),fs$1.renameSync(s,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var It=".testrelic",ss="testrelic-config.json",as=".testrelic",ns=5,is=new Set(["__proto__","constructor","prototype"]),Rt=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${It}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),os={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function _t(t){let e=path.resolve(t);for(let r=0;r<=ns;r++){let s=path.join(e,It,ss);if(fs$1.existsSync(s))try{if(fs$1.statSync(s).isFile())return s}catch{}let a=path.join(e,as);if(fs$1.existsSync(a))try{if(fs$1.statSync(a).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
+ `),a}catch{}let n=path.dirname(e);if(n===e)break;e=n;}return null}function Mt(t){try{let e=fs$1.readFileSync(t,"utf-8"),r=JSON.parse(e);return typeof r!="object"||r===null||Array.isArray(r)||!Lt(r)?null:r}catch{return null}}function Lt(t){for(let e of Object.keys(t)){if(is.has(e))return false;let r=t[e];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!Lt(r))return false}return true}function Et(t){let e=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(t);if(e)return process.env[e[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(t);return r?process.env[r[1]]??null:t}function ke(t){let e=Object.create(null);for(let r of Object.keys(t)){let s=t[r];typeof s=="string"&&s.startsWith("$")?e[r]=Et(s):typeof s=="object"&&s!==null&&!Array.isArray(s)?e[r]=ke(s):e[r]=s;}return e}function At(t){let e=/^(\d+)\s*([smhd])$/.exec(t.trim());if(!e)return null;let r=parseInt(e[1],10),s=e[2],a=os[s];return !a||r<=0?null:r*a}function Pt(t,e){let r=Object.create(null);if(Object.assign(r,Rt),t){let l=t.cloud;l&&typeof l=="object"&&(typeof l.endpoint=="string"&&(r.endpoint=l.endpoint),typeof l.upload=="string"&&(r.uploadStrategy=l.upload),typeof l.timeout=="number"&&(r.timeout=l.timeout),typeof l.apiKey=="string"&&l.apiKey.length>0&&(r.apiKey=l.apiKey));let d=t["testrelic-repo"]??t.project;d&&typeof d=="object"&&typeof d.name=="string"&&(r.projectName=d.name),t.project&&!t["testrelic-repo"]&&process.stderr.write(`[testrelic] Deprecation: "project" key in config is deprecated. Rename it to "testrelic-repo".
5
+ `);let p=t.queue;if(p&&typeof p=="object"){if(typeof p.maxAge=="string"){let f=At(p.maxAge);f!==null&&(r.queueMaxAge=f);}typeof p.directory=="string"&&(r.queueDirectory=p.directory);}}if(e){if(typeof e.apiKey=="string"&&e.apiKey.length>0){let l=e.apiKey.startsWith("$")?Et(e.apiKey):e.apiKey;l&&(r.apiKey=l);}if(typeof e.endpoint=="string"&&(r.endpoint=e.endpoint),typeof e.upload=="string"&&(r.uploadStrategy=e.upload),typeof e.timeout=="number"&&(r.timeout=e.timeout),typeof e.projectName=="string"&&(r.projectName=e.projectName),typeof e.queueMaxAge=="string"){let l=At(e.queueMaxAge);l!==null&&(r.queueMaxAge=l);}typeof e.queueDirectory=="string"&&(r.queueDirectory=e.queueDirectory),typeof e.uploadArtifacts=="boolean"&&(r.uploadArtifacts=e.uploadArtifacts),typeof e.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=e.artifactMaxSizeMb);}let s=process.env.TESTRELIC_API_KEY;s&&s.length>0&&(r.apiKey=s);let a=process.env.TESTRELIC_CLOUD_ENDPOINT;a&&core.isValidEndpointUrl(a)&&(r.endpoint=a);let n=process.env.TESTRELIC_UPLOAD_STRATEGY;n&&["batch","realtime","both"].includes(n)&&(r.uploadStrategy=n);let o=process.env.TESTRELIC_CLOUD_TIMEOUT;if(o){let l=parseInt(o,10);!isNaN(l)&&l>=1e3&&l<=12e4&&(r.timeout=l);}let i=Object.freeze(r);return core.isValidCloudConfig(i)?i:Rt}var us=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],ps=["authorization","cookie","set-cookie","x-api-key"],fs=["password","secret","token","apiKey","api_key"];function Nt(t){let e=Object.create(null);return e.trackApiCalls=t?.trackApiCalls??true,e.captureRequestHeaders=t?.captureRequestHeaders??true,e.captureResponseHeaders=t?.captureResponseHeaders??true,e.captureRequestBody=t?.captureRequestBody??true,e.captureResponseBody=t?.captureResponseBody??true,e.captureAssertions=t?.captureAssertions??true,e.redactHeaders=t?.redactHeaders??[...ps],e.redactBodyFields=t?.redactBodyFields??[...fs],e.apiIncludeUrls=t?.apiIncludeUrls??[],e.apiExcludeUrls=t?.apiExcludeUrls??[],Object.freeze(e)}function Ft(t){if(t!==void 0&&!core.isValidConfig(t))throw core.createError(core.ErrorCode.CONFIG_INVALID,"Invalid reporter configuration");let e=Object.create(null);e.outputPath=t?.outputPath??"./test-results/analytics-timeline.json",e.includeStackTrace=t?.includeStackTrace??false,e.includeCodeSnippets=t?.includeCodeSnippets??true,e.codeContextLines=t?.codeContextLines??3,e.includeNetworkStats=t?.includeNetworkStats??true,e.captureNavigation=t?.captureNavigation??true,e.navigationTypes=t?.navigationTypes??null,e.redactPatterns=[...us,...t?.redactPatterns??[]],e.testRunId=t?.testRunId??null,e.metadata=t?.metadata??null;let r=e.outputPath;e.openReport=t?.openReport??true,e.htmlReportPath=t?.htmlReportPath??r.replace(/\.json$/,".html"),e.includeArtifacts=t?.includeArtifacts??true,e.trackApiCalls=t?.trackApiCalls??true,e.quiet=t?.quiet??false,e.includeActionSteps=t?.includeActionSteps??true,e.captureConsoleLogs=t?.captureConsoleLogs??true;let s=_t(process.cwd()),a=s?Mt(s):null,n=a?ke(a):null,o=Pt(n,t?.cloud);return e.cloud=o.apiKey?o:null,e.reportMode=t?.reportMode??"streaming",e.streamingThreshold=t?.streamingThreshold??0,Object.freeze(e)}var Te="1.3.0";function Dt(t,e,r){try{let a=fs$1.readFileSync(t,"utf-8").split(`
6
+ `);if(e<1||e>a.length)return null;let n=Math.max(1,e-r),o=Math.min(a.length,e+r),i=[];for(let l=n;l<=o;l++){let d=l===e?">":" ",p=String(l).padStart(String(o).length," ");i.push(`${d} ${p} | ${a[l-1]}`);}return i.join(`
7
+ `)}catch{return null}}function Bt(t){return e=>{let r=e;for(let s of t)if(typeof s=="string"){let a=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(a,"g"),"[REDACTED]");}else {let a=s.flags.includes("g")?s.flags:s.flags+"g",n=new RegExp(s.source,a);r=r.replace(n,"[REDACTED]");}return r}}function hs(t){return t.GITHUB_ACTIONS!=="true"?null:{provider:"github-actions",buildId:t.GITHUB_RUN_ID??null,commitSha:t.GITHUB_SHA??null,branch:t.GITHUB_REF_NAME??null,runUrl:t.GITHUB_SERVER_URL&&t.GITHUB_REPOSITORY&&t.GITHUB_RUN_ID?`${t.GITHUB_SERVER_URL}/${t.GITHUB_REPOSITORY}/actions/runs/${t.GITHUB_RUN_ID}`:null}}function ms(t){return t.GITLAB_CI!=="true"?null:{provider:"gitlab-ci",buildId:t.CI_PIPELINE_ID??null,commitSha:t.CI_COMMIT_SHA??null,branch:t.CI_COMMIT_BRANCH??t.CI_COMMIT_REF_NAME??null,runUrl:t.CI_PIPELINE_URL??null}}function vs(t){if(!t.JENKINS_URL)return null;let e=t.GIT_BRANCH??null;return e?.startsWith("origin/")&&(e=e.slice(7)),{provider:"jenkins",buildId:t.BUILD_ID??null,commitSha:t.GIT_COMMIT??null,branch:e,runUrl:t.BUILD_URL??null}}function ys(t){return t.CIRCLECI!=="true"?null:{provider:"circleci",buildId:t.CIRCLE_BUILD_NUM??null,commitSha:t.CIRCLE_SHA1??null,branch:t.CIRCLE_BRANCH??null,runUrl:t.CIRCLE_BUILD_URL??null}}function bs(t){if(!t.BITBUCKET_PIPELINE_UUID)return null;let e=t.BITBUCKET_WORKSPACE&&t.BITBUCKET_REPO_SLUG&&t.BITBUCKET_PIPELINE_UUID?`https://bitbucket.org/${t.BITBUCKET_WORKSPACE}/${t.BITBUCKET_REPO_SLUG}/pipelines/results/${t.BITBUCKET_PIPELINE_UUID}`:null;return {provider:"bitbucket-pipelines",buildId:t.BITBUCKET_BUILD_NUMBER??null,commitSha:t.BITBUCKET_COMMIT??null,branch:t.BITBUCKET_BRANCH??null,runUrl:e}}var xs=[hs,ms,vs,ys,bs];function N(t){let e=process.env;for(let r of xs){let s=r(e);if(s)return s}return null}var Se=`
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;
@@ -561,15 +561,15 @@ body{
561
561
  .detail-error .failure-message{margin-bottom:16px;padding:12px;background:rgba(239,68,68,0.06);border:1px solid rgba(239,68,68,0.15);border-radius:8px;font-size:12px;color:#f87171;text-align:left;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap;word-break:break-word}
562
562
  .detail-error code{font-size:11px;padding:2px 6px;background:var(--bg-2);border-radius:4px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
563
563
  .server-offline-banner{padding:8px 14px;background:rgba(251,191,36,0.08);border:1px solid rgba(251,191,36,0.2);border-radius:6px;font-size:11px;color:#fbbf24;text-align:center;margin-bottom:12px}
564
- `;var Se=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 196 247" fill="none">
564
+ `;var Ce=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 196 247" fill="none">
565
565
  <path fill-rule="evenodd" clip-rule="evenodd" d="M4.75 1.08009C2.034 2.66209 -0.130999 7.63009 0.610001 10.5821C0.969001 12.0121 3.021 15.2131 5.17 17.6971C14.375 28.3321 18 39.7791 18 58.2101V71.0001H12.434C1.16501 71.0001 0 73.4641 0 97.3051C0 106.858 0.298003 128.922 0.662003 146.337L1.323 178H33.606C65.786 178 65.897 178.007 68.544 180.284C72.228 183.453 72.244 189.21 68.579 192.877L65.957 195.5L33.479 195.801L1 196.103V204.551V213H24.577H48.154L51.077 215.923C55.007 219.853 55.007 224.147 51.077 228.077L48.154 231H26.469H4.783L5.41901 233.534C5.76901 234.927 7.143 238.527 8.472 241.534L10.89 247H40.945H71L71.006 241.75C71.017 230.748 76.027 221.606 84.697 216.767C97.854 209.424 114.086 213.895 121.323 226.857C123.659 231.041 124.418 233.833 124.789 239.607L125.263 247H155.187H185.11L187.528 241.534C188.857 238.527 190.231 234.927 190.581 233.534L191.217 231H169.531H147.846L144.923 228.077C142.928 226.082 142 224.152 142 222C142 219.848 142.928 217.918 144.923 215.923L147.846 213H171.423H195V204.551V196.103L162.521 195.801L130.043 195.5L127.421 192.877C123.991 189.445 123.835 183.869 127.074 180.421L129.349 178H162.013H194.677L195.338 146.337C195.702 128.922 196 106.858 196 97.3051C196 73.4641 194.835 71.0001 183.566 71.0001H178V58.2101C178 39.6501 181.397 28.7731 190.538 18.0651C195.631 12.0971 196.572 9.00809 194.511 5.02109C192.672 1.46509 190.197 9.12233e-05 186.028 9.12233e-05C179.761 9.12233e-05 168.713 14.8831 163.388 30.5001C160.975 37.5771 160.608 40.3751 160.213 54.7501L159.765 71.0001H150.732H141.7L142.286 53.2501C142.904 34.5511 144.727 24.3761 148.938 16.1211C151.823 10.4671 151.628 5.90109 148.364 2.63609C145 -0.726907 140.105 -0.887909 136.596 2.25009C133.481 5.03609 128.686 17.0811 126.507 27.5921C125.569 32.1191 124.617 43.0901 124.28 53.2501L123.69 71.0001H115.345H107V38.4231V5.84609L104.077 2.92309C102.082 0.928088 100.152 9.12233e-05 98 9.12233e-05C95.848 9.12233e-05 93.918 0.928088 91.923 2.92309L89 5.84609V38.4231V71.0001H80.655H72.31L71.72 53.2501C71.383 43.0901 70.431 32.1191 69.493 27.5921C67.314 17.0811 62.519 5.03609 59.404 2.25009C55.998 -0.795909 51.059 -0.710905 47.646 2.45209C44.221 5.62609 44.191 9.92109 47.539 17.4911C51.71 26.9241 53.007 34.4791 53.676 53.2501L54.31 71.0001H45.272H36.235L35.787 54.7501C35.392 40.3751 35.025 37.5771 32.612 30.5001C27.194 14.6091 16.228 -0.02891 9.787 0.03009C7.979 0.04709 5.712 0.519093 4.75 1.08009ZM42.687 108.974C33.431 112.591 20.036 125.024 18.408 131.512C17.476 135.223 20.677 140.453 28.253 147.599C37.495 156.319 44.191 159.471 53.5 159.485C59.317 159.494 61.645 158.953 67.274 156.289C77.634 151.385 88.987 139.161 88.996 132.9C89.004 127.304 76.787 114.707 66.745 109.956C59.16 106.368 50.285 106.006 42.687 108.974ZM129.255 109.904C119.151 114.768 106.996 127.33 107.004 132.9C107.013 139.108 118.562 151.475 128.939 156.389C134.338 158.945 136.744 159.496 142.521 159.498C152.526 159.501 160.369 155.502 169.771 145.605C180.444 134.368 180.278 130.975 168.486 119.388C160.043 111.094 152.727 107.595 143 107.201C136.364 106.933 134.78 107.244 129.255 109.904ZM48.5 125.922C46.3 126.969 43.152 128.945 41.505 130.314L38.511 132.802L40.504 135.005C41.601 136.216 44.434 138.342 46.8 139.728C52.577 143.114 57.36 142.466 64.009 137.395L68.978 133.606L66.756 131.24C60.944 125.054 54.357 123.135 48.5 125.922ZM138.386 125.063C136.674 125.571 133.375 127.677 131.057 129.743L126.841 133.5L131.901 137.343C138.65 142.468 143.407 143.124 149.2 139.728C151.566 138.342 154.351 136.269 155.389 135.122C157.684 132.587 156.742 131.097 150.58 127.511C145.438 124.519 142.329 123.895 138.386 125.063ZM91.923 162.923C89.043 165.804 89 166.008 89 176.973C89 184.805 89.435 188.941 90.47 190.941C92.356 194.589 96.918 196.273 101.03 194.84C105.82 193.17 107 189.638 107 176.973C107 166.008 106.957 165.804 104.077 162.923C102.082 160.928 100.152 160 98 160C95.848 160 93.918 160.928 91.923 162.923ZM94.5 232.155C91.026 234.055 90 236.229 90 241.691V247H98H106V242.082C106 235.732 105.37 234.242 101.928 232.463C98.591 230.737 97.197 230.679 94.5 232.155Z" fill="url(#paint0_linear_55_11)"/>
566
566
  <defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
567
567
  <stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
568
- </linearGradient></defs></svg>`,Ce=`<svg width="32" height="40" viewBox="0 0 196 247" fill="none" xmlns="http://www.w3.org/2000/svg">
568
+ </linearGradient></defs></svg>`,Re=`<svg width="32" height="40" viewBox="0 0 196 247" fill="none" xmlns="http://www.w3.org/2000/svg">
569
569
  <path fill-rule="evenodd" clip-rule="evenodd" d="M4.75 1.08009C2.034 2.66209 -0.130999 7.63009 0.610001 10.5821C0.969001 12.0121 3.021 15.2131 5.17 17.6971C14.375 28.3321 18 39.7791 18 58.2101V71.0001H12.434C1.16501 71.0001 0 73.4641 0 97.3051C0 106.858 0.298003 128.922 0.662003 146.337L1.323 178H33.606C65.786 178 65.897 178.007 68.544 180.284C72.228 183.453 72.244 189.21 68.579 192.877L65.957 195.5L33.479 195.801L1 196.103V204.551V213H24.577H48.154L51.077 215.923C55.007 219.853 55.007 224.147 51.077 228.077L48.154 231H26.469H4.783L5.41901 233.534C5.76901 234.927 7.143 238.527 8.472 241.534L10.89 247H40.945H71L71.006 241.75C71.017 230.748 76.027 221.606 84.697 216.767C97.854 209.424 114.086 213.895 121.323 226.857C123.659 231.041 124.418 233.833 124.789 239.607L125.263 247H155.187H185.11L187.528 241.534C188.857 238.527 190.231 234.927 190.581 233.534L191.217 231H169.531H147.846L144.923 228.077C142.928 226.082 142 224.152 142 222C142 219.848 142.928 217.918 144.923 215.923L147.846 213H171.423H195V204.551V196.103L162.521 195.801L130.043 195.5L127.421 192.877C123.991 189.445 123.835 183.869 127.074 180.421L129.349 178H162.013H194.677L195.338 146.337C195.702 128.922 196 106.858 196 97.3051C196 73.4641 194.835 71.0001 183.566 71.0001H178V58.2101C178 39.6501 181.397 28.7731 190.538 18.0651C195.631 12.0971 196.572 9.00809 194.511 5.02109C192.672 1.46509 190.197 9.12233e-05 186.028 9.12233e-05C179.761 9.12233e-05 168.713 14.8831 163.388 30.5001C160.975 37.5771 160.608 40.3751 160.213 54.7501L159.765 71.0001H150.732H141.7L142.286 53.2501C142.904 34.5511 144.727 24.3761 148.938 16.1211C151.823 10.4671 151.628 5.90109 148.364 2.63609C145 -0.726907 140.105 -0.887909 136.596 2.25009C133.481 5.03609 128.686 17.0811 126.507 27.5921C125.569 32.1191 124.617 43.0901 124.28 53.2501L123.69 71.0001H115.345H107V38.4231V5.84609L104.077 2.92309C102.082 0.928088 100.152 9.12233e-05 98 9.12233e-05C95.848 9.12233e-05 93.918 0.928088 91.923 2.92309L89 5.84609V38.4231V71.0001H80.655H72.31L71.72 53.2501C71.383 43.0901 70.431 32.1191 69.493 27.5921C67.314 17.0811 62.519 5.03609 59.404 2.25009C55.998 -0.795909 51.059 -0.710905 47.646 2.45209C44.221 5.62609 44.191 9.92109 47.539 17.4911C51.71 26.9241 53.007 34.4791 53.676 53.2501L54.31 71.0001H45.272H36.235L35.787 54.7501C35.392 40.3751 35.025 37.5771 32.612 30.5001C27.194 14.6091 16.228 -0.02891 9.787 0.03009C7.979 0.04709 5.712 0.519093 4.75 1.08009ZM42.687 108.974C33.431 112.591 20.036 125.024 18.408 131.512C17.476 135.223 20.677 140.453 28.253 147.599C37.495 156.319 44.191 159.471 53.5 159.485C59.317 159.494 61.645 158.953 67.274 156.289C77.634 151.385 88.987 139.161 88.996 132.9C89.004 127.304 76.787 114.707 66.745 109.956C59.16 106.368 50.285 106.006 42.687 108.974ZM129.255 109.904C119.151 114.768 106.996 127.33 107.004 132.9C107.013 139.108 118.562 151.475 128.939 156.389C134.338 158.945 136.744 159.496 142.521 159.498C152.526 159.501 160.369 155.502 169.771 145.605C180.444 134.368 180.278 130.975 168.486 119.388C160.043 111.094 152.727 107.595 143 107.201C136.364 106.933 134.78 107.244 129.255 109.904ZM48.5 125.922C46.3 126.969 43.152 128.945 41.505 130.314L38.511 132.802L40.504 135.005C41.601 136.216 44.434 138.342 46.8 139.728C52.577 143.114 57.36 142.466 64.009 137.395L68.978 133.606L66.756 131.24C60.944 125.054 54.357 123.135 48.5 125.922ZM138.386 125.063C136.674 125.571 133.375 127.677 131.057 129.743L126.841 133.5L131.901 137.343C138.65 142.468 143.407 143.124 149.2 139.728C151.566 138.342 154.351 136.269 155.389 135.122C157.684 132.587 156.742 131.097 150.58 127.511C145.438 124.519 142.329 123.895 138.386 125.063ZM91.923 162.923C89.043 165.804 89 166.008 89 176.973C89 184.805 89.435 188.941 90.47 190.941C92.356 194.589 96.918 196.273 101.03 194.84C105.82 193.17 107 189.638 107 176.973C107 166.008 106.957 165.804 104.077 162.923C102.082 160.928 100.152 160 98 160C95.848 160 93.918 160.928 91.923 162.923ZM94.5 232.155C91.026 234.055 90 236.229 90 241.691V247H98H106V242.082C106 235.732 105.37 234.242 101.928 232.463C98.591 230.737 97.197 230.679 94.5 232.155Z" fill="url(#paint0_linear_55_11)"/>
570
570
  <defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
571
571
  <stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
572
- </linearGradient></defs></svg>`;var Re=`
572
+ </linearGradient></defs></svg>`;var Ae=`
573
573
  /* \u2500\u2500 Utilities \u2500\u2500 */
574
574
  function esc(s){if(!s)return '';return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;')}
575
575
  function stripAnsi(s){return s?s.replace(/\\u001b\\[[0-9;]*m/g,'').replace(/\\x1b\\[[0-9;]*m/g,''):''}
@@ -1000,7 +1000,7 @@ body{
1000
1000
  clearTimeout(_searchTimer);
1001
1001
  _searchTimer=setTimeout(function(){searchQuery=q;applyFilters();},150);
1002
1002
  }
1003
- `;var Ae=`
1003
+ `;var Ie=`
1004
1004
  /* \u2500\u2500 Network Visualization Helpers \u2500\u2500 */
1005
1005
  var RES_COLORS={xhr:'#60a5fa',document:'#818cf8',script:'#fbbf24',stylesheet:'#a78bfa',image:'#34d399',font:'#f472b6',other:'#6b7280'};
1006
1006
  var RES_LABELS={xhr:'XHR',document:'Doc',script:'JS',stylesheet:'CSS',image:'Img',font:'Font',other:'Other'};
@@ -1631,7 +1631,7 @@ body{
1631
1631
  var countEl=ndt.querySelector('.ndt-count');
1632
1632
  if(countEl)countEl.textContent=visible+' / '+rows.length+' requests';
1633
1633
  }
1634
- `;var Ie=`
1634
+ `;var _e=`
1635
1635
  var _filterState={status:{},type:{},specFile:{}};
1636
1636
  var _totalTests=0;
1637
1637
  var _originalSummary=null;
@@ -1802,7 +1802,7 @@ function _updateCard(cls,val){
1802
1802
  var el=document.querySelector('.'+cls+' .s-count');
1803
1803
  if(el)el.textContent=''+val;
1804
1804
  }
1805
- `;var _e=`
1805
+ `;var Me=`
1806
1806
  /* \u2500\u2500 Event Delegation \u2500\u2500 */
1807
1807
  document.addEventListener('click',function(e){
1808
1808
  var target=e.target;
@@ -2118,7 +2118,7 @@ function _updateCard(cls,val){
2118
2118
  h+='</div>';
2119
2119
  return h;
2120
2120
  }
2121
- `;var Me=`
2121
+ `;var Ee=`
2122
2122
  /* \u2500\u2500 Console Log Level Colors & Labels \u2500\u2500 */
2123
2123
  var LOG_COLORS={log:'#9ca3af',warn:'#fbbf24',error:'#f87171',info:'#60a5fa',debug:'#a78bfa',stdout:'#9ca3af',stderr:'#f87171'};
2124
2124
  var LOG_LABELS={log:'LOG',warn:'WARN',error:'ERR',info:'INFO',debug:'DBG',stdout:'OUT',stderr:'ERR'};
@@ -2305,7 +2305,7 @@ function _updateCard(cls,val){
2305
2305
  }
2306
2306
  return h;
2307
2307
  }
2308
- `;var Ee=`
2308
+ `;var Pe=`
2309
2309
  /* \u2500\u2500 Artifact Utilities \u2500\u2500 */
2310
2310
  function formatBytes(bytes){
2311
2311
  if(bytes===0)return '0 B';
@@ -2314,16 +2314,16 @@ function _updateCard(cls,val){
2314
2314
  if(i>=sizes.length)i=sizes.length-1;
2315
2315
  return parseFloat((bytes/Math.pow(k,i)).toFixed(1))+' '+sizes[i];
2316
2316
  }
2317
- `;var pa=`
2317
+ `;var ws=`
2318
2318
  (function(){
2319
2319
  var data=JSON.parse(document.getElementById('report-data').textContent);
2320
- ${Re}
2321
- ${Le}
2322
- ${Me}
2323
2320
  ${Ae}
2324
- ${Ie}
2321
+ ${Le}
2325
2322
  ${Ee}
2323
+ ${Ie}
2326
2324
  ${_e}
2325
+ ${Pe}
2326
+ ${Me}
2327
2327
  applyTheme();
2328
2328
  renderRunMeta();
2329
2329
  renderSummary();
@@ -2331,7 +2331,7 @@ function _updateCard(cls,val){
2331
2331
  renderFilterBar();
2332
2332
  renderTestGrid();
2333
2333
  var _lo=document.getElementById('loading-overlay');if(_lo)_lo.remove();
2334
- })();`;function Et(t,e,r){let a=t.replace(/<\//g,"<\\/"),n=r?r.replace(/<\//g,"<\\/"):null;return `<!-- TestRelic AI Analytics Report \u2014 self-contained, no external dependencies -->
2334
+ })();`;function Ot(t,e,r){let s=t.replace(/<\//g,"<\\/"),a=r?r.replace(/<\//g,"<\\/"):null;return `<!-- TestRelic AI Analytics Report \u2014 self-contained, no external dependencies -->
2335
2335
  <!DOCTYPE html>
2336
2336
  <html lang="en" data-theme="">
2337
2337
  <head>
@@ -2340,15 +2340,15 @@ function _updateCard(cls,val){
2340
2340
  <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: blob: 'self'; media-src blob: 'self'; connect-src 'self' http://127.0.0.1:*;">
2341
2341
  <title>TestRelic AI Analytics Report</title>
2342
2342
  ${""}
2343
- <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Se).toString("base64")}">
2344
- <style>${Te}</style>
2343
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Ce).toString("base64")}">
2344
+ <style>${Se}</style>
2345
2345
  <script>(function(){var p=localStorage.getItem('tr-theme')||'system';var t=p==='system'?(window.matchMedia('(prefers-color-scheme:light)').matches?'light':'dark'):p;document.documentElement.setAttribute('data-theme',t);})()</script>
2346
2346
  </head>
2347
2347
  <body>
2348
2348
  <div class="wrap">
2349
2349
  <div class="top-bar">
2350
2350
  <div class="brand">
2351
- ${Ce}
2351
+ ${Re}
2352
2352
  <div class="brand-text">
2353
2353
  <span class="brand-title">TestRelic AI</span>
2354
2354
  <span class="brand-sub">Analytics Report</span>
@@ -2383,16 +2383,16 @@ ${""}
2383
2383
  </div>
2384
2384
  <div class="filter-drawer-body" id="filter-drawer-body"></div>
2385
2385
  </aside>
2386
- <script id="report-data" type="application/json">${a}</script>
2387
- ${n?`<script id="artifact-manifest-data" type="application/json">${n}</script>`:""}
2388
- <script>${pa}</script>
2386
+ <script id="report-data" type="application/json">${s}</script>
2387
+ ${a?`<script id="artifact-manifest-data" type="application/json">${a}</script>`:""}
2388
+ <script>${ws}</script>
2389
2389
  </body>
2390
- </html>`}function Pe(t,e,r,a){let n=t.replace(/<\//g,"<\\/"),s=e.replace(/<\//g,"<\\/"),o=a?a.replace(/<\//g,"<\\/"):null,i={};try{i=JSON.parse(t);}catch{}let l=`{
2390
+ </html>`}function Ne(t,e,r,s){let a=t.replace(/<\//g,"<\\/"),n=e.replace(/<\//g,"<\\/"),o=s?s.replace(/<\//g,"<\\/"):null,i={};try{i=JSON.parse(t);}catch{}let l=`{
2391
2391
  "schemaVersion":"2.0",
2392
2392
  "reportMode":"streaming",
2393
2393
  "serverPort":${r??"null"},
2394
- "summary":${n},
2395
- "index":${s},
2394
+ "summary":${a},
2395
+ "index":${n},
2396
2396
  "timeline":[],
2397
2397
  "testRunId":${JSON.stringify(String(i.testRunId??""))},
2398
2398
  "startedAt":${JSON.stringify(String(i.startedAt??""))},
@@ -2471,13 +2471,13 @@ ${n?`<script id="artifact-manifest-data" type="application/json">${n}</script>`:
2471
2471
  window.__trServerPort=_serverPort;
2472
2472
  window.__trIsStreaming=true;
2473
2473
 
2474
- ${Re}
2475
- ${Le}
2476
- ${Me}
2477
2474
  ${Ae}
2478
- ${Ie}
2475
+ ${Le}
2479
2476
  ${Ee}
2477
+ ${Ie}
2480
2478
  ${_e}
2479
+ ${Pe}
2480
+ ${Me}
2481
2481
  applyTheme();
2482
2482
  renderRunMeta();
2483
2483
  renderSummary();
@@ -2496,15 +2496,15 @@ ${n?`<script id="artifact-manifest-data" type="application/json">${n}</script>`:
2496
2496
  <title>TestRelic AI Analytics Report</title>
2497
2497
  ${r?`<meta name="report-server-port" content="${r}">`:""}
2498
2498
  ${r?`<meta name="artifact-server-port" content="${r}">`:""}
2499
- <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Se).toString("base64")}">
2500
- <style>${Te}</style>
2499
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Ce).toString("base64")}">
2500
+ <style>${Se}</style>
2501
2501
  <script>(function(){var p=localStorage.getItem('tr-theme')||'system';var t=p==='system'?(window.matchMedia('(prefers-color-scheme:light)').matches?'light':'dark'):p;document.documentElement.setAttribute('data-theme',t);})()</script>
2502
2502
  </head>
2503
2503
  <body>
2504
2504
  <div class="wrap">
2505
2505
  <div class="top-bar">
2506
2506
  <div class="brand">
2507
- ${Ce}
2507
+ ${Re}
2508
2508
  <div class="brand-text">
2509
2509
  <span class="brand-title">TestRelic AI</span>
2510
2510
  <span class="brand-sub">Analytics Report</span>
@@ -2543,45 +2543,47 @@ ${r?`<meta name="artifact-server-port" content="${r}">`:""}
2543
2543
  ${o?`<script id="artifact-manifest-data" type="application/json">${o}</script>`:""}
2544
2544
  <script>${d}</script>
2545
2545
  </body>
2546
- </html>`}function Ne(t){try{let e=process.platform,r;e==="darwin"?r=`open "${t}"`:e==="win32"?r=`start "" "${t}"`:r=`xdg-open "${t}"`,child_process.exec(r,a=>{a&&process.stderr.write(`[testrelic] Failed to open browser: ${a.message}
2547
- `);});}catch{}}path.join(os.tmpdir(),"testrelic-data");async function Pt(t,e,r,a){let n=(e-1)*r,s=[],o=0,i=readline.createInterface({input:fs$1.createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let p of i)if(p.length!==0){if(o>=n&&s.length<r)try{s.push(JSON.parse(p));}catch{}if(o++,s.length>=r&&a!==void 0)break}let l=a??o,d=Math.max(1,Math.ceil(l/r));return {items:s,total:l,page:e,pageSize:r,totalPages:d}}var Dt=/^[a-f0-9]{12}$/,Fe=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Bt=500;function w(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function Ot(t){t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type");}function ae(t){try{return fs$1.existsSync(t)?JSON.parse(fs$1.readFileSync(t,"utf-8")):null}catch{return null}}function ne(t){let e=0;try{let r=fs$1.readdirSync(t,{withFileTypes:!0});for(let a of r){let n=path.join(t,a.name);a.isFile()?e+=fs$1.statSync(n).size:a.isDirectory()&&(e+=ne(n));}}catch{}return e}function qt(t,e,r,a){let n=ae(path.join(r,"index.json"));w(e,200,{status:"ok",reportMode:"streaming",testCount:n?.length??0,uptime:Math.floor((Date.now()-a)/1e3)});}function Ht(t,e,r){let a=ae(path.join(r,"summary.json"));if(!a){w(e,404,{error:"Summary not found"});return}w(e,200,a);}function Ut(t,e,r){let a=ae(path.join(r,"index.json"));if(!a){w(e,404,{error:"Test index not found"});return}let s=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,o=Math.max(1,parseInt(s.get("page")??"1",10)||1),i=Math.min(Bt,Math.max(1,parseInt(s.get("pageSize")??"100",10)||100)),l=s.get("status")?.split(",").filter(Boolean)??null,d=s.get("file")??null,p=s.get("search")?.toLowerCase()??null,f=s.get("tag")?.split(",").filter(Boolean)??null,h=s.get("sort")??"file",c=s.get("order")==="desc"?-1:1,u=a;l&&l.length>0&&(u=u.filter(y=>l.includes(y.status))),d&&(u=u.filter(y=>y.filePath===d||y.filePath.startsWith(d+"/"))),p&&(u=u.filter(y=>y.title.toLowerCase().includes(p)||y.filePath.toLowerCase().includes(p))),f&&f.length>0&&(u=u.filter(y=>f.some(x=>y.tags.includes(x)))),u=[...u].sort((y,x)=>{let T=0;switch(h){case "duration":T=y.duration-x.duration;break;case "status":T=y.status.localeCompare(x.status);break;case "title":T=y.title.localeCompare(x.title);break;default:T=y.filePath.localeCompare(x.filePath);break}return T*c});let g=u.length,m=Math.max(1,Math.ceil(g/i)),b=(o-1)*i,S=u.slice(b,b+i);w(e,200,{tests:S,pagination:{page:o,pageSize:i,totalItems:g,totalPages:m},filters:{status:l,file:d,search:p,tag:f}});}function zt(t,e,r,a){if(!Dt.test(a)){w(e,400,{error:"Invalid test ID format"});return}let n=path.join(r,"tests",a,"meta.json"),s=path.join(r,"tests",`${a}.json`),o=fs$1.existsSync(n)?n:fs$1.existsSync(s)?s:null;if(!o){w(e,404,{error:`Test not found: ${a}`});return}try{let i=fs$1.readFileSync(o,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(i);}catch(i){w(e,500,{error:i instanceof Error?i.message:String(i)});}}async function $t(t,e,r,a,n){if(!Dt.test(a)){w(e,400,{error:"Invalid test ID format"});return}let o=path.join(r,"tests",a,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[n]);if(!fs$1.existsSync(o)){w(e,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let l=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,d=Math.max(1,parseInt(l.get("page")??"1",10)||1),p=Math.min(Bt,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),f,h=path.join(r,"tests",a,"meta.json");if(fs$1.existsSync(h))try{let u=JSON.parse(fs$1.readFileSync(h,"utf-8"));switch(n){case "network":f=u.networkRequestsCount;break;case "console":f=u.consoleLogsCount;break;case "api-calls":f=u.apiCallsCount;break}}catch{}let c=await Pt(o,d,p,f);w(e,200,c);}catch(i){w(e,500,{error:i instanceof Error?i.message:String(i)});}}function jt(t,e,r){let a=ae(path.join(r,"index.json"));if(!a){w(e,404,{error:"Test index not found"});return}let n=new Map;for(let o of a){if(o.isRetry)continue;let i=n.get(o.filePath);switch(i||(i={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},n.set(o.filePath,i)),i.total++,o.status){case "passed":i.passed++;break;case "failed":i.failed++;break;case "flaky":i.flaky++;break;case "skipped":i.skipped++;break;case "timedout":i.timedOut++;break}}let s=Array.from(n.entries()).map(([o,i])=>({filePath:o,...i})).sort((o,i)=>o.filePath.localeCompare(i.filePath));w(e,200,{files:s});}function Vt(t,e,r){if(!fs$1.existsSync(r)){w(e,200,{runs:[],totalSizeBytes:0});return}try{let a=[],n=0,s=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of s){if(!o.isDirectory()||!Fe.test(o.name))continue;let i=path.join(r,o.name),l=ne(i),d=fs$1.readdirSync(i,{withFileTypes:!0}).filter(p=>p.isDirectory());a.push({folderName:o.name,totalSizeBytes:l,testCount:d.length}),n+=l;}a.sort((o,i)=>i.folderName.localeCompare(o.folderName)),w(e,200,{runs:a,totalSizeBytes:n});}catch(a){w(e,500,{error:a instanceof Error?a.message:String(a)});}}function Gt(t,e,r){try{let a=0,n=0;if(fs$1.existsSync(r)){let s=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of s){if(!o.isDirectory()||!Fe.test(o.name))continue;let i=path.join(r,o.name),l=ne(i);fs$1.rmSync(i,{recursive:!0,force:!0}),n+=l,a++;}}w(e,200,{deletedCount:a,freedBytes:n});}catch(a){w(e,500,{error:a instanceof Error?a.message:String(a)});}}function Wt(t,e,r,a){if(!Fe.test(a)){w(e,400,{error:"Invalid folder name"});return}let n=path.join(r,a);try{if(!fs$1.statSync(n).isDirectory()){w(e,404,{error:"Not found"});return}}catch{w(e,404,{error:"Not found"});return}try{let s=ne(n);fs$1.rmSync(n,{recursive:!0,force:!0}),w(e,200,{deleted:a,freedBytes:s});}catch(s){w(e,500,{error:s instanceof Error?s.message:String(s)});}}function Kt(t,e,r){w(e,200,{status:"shutting_down"}),r.close();}function De(t,e,r){if(!fs$1.existsSync(r)){w(e,404,{error:"File not found"});return}try{let a=fs$1.readFileSync(r),n=path.extname(r).toLowerCase(),s=ba[n]??"application/octet-stream";e.writeHead(200,{"Content-Type":s}),e.end(a);}catch(a){w(e,500,{error:a instanceof Error?a.message:String(a)});}}var ba={".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 Ta=9323,Sa=10,Ca=1800*1e3;function W(t,e){return new Promise((r,a)=>{let n=e?.port??Ta,s=Date.now(),o,i=0,l=fs$1.existsSync(path.join(t,"artifacts"))?path.join(t,"artifacts"):fs$1.existsSync(path.join(t,"..","artifacts"))?path.join(t,"..","artifacts"):path.join(t,"artifacts");function d(){clearTimeout(o),o=setTimeout(()=>{f.close();},Ca);}let p=e?.htmlPath??null;if(!p){let c=path.dirname(t);try{let u=fs$1.readdirSync(c).find(g=>g.endsWith(".html"));u&&(p=path.join(c,u));}catch{}}let f=http.createServer((c,u)=>{if(d(),Ot(u),c.method==="OPTIONS"){u.writeHead(204),u.end();return}let g;try{g=new URL(c.url??"/",`http://${c.headers.host??"localhost"}`).pathname;}catch{w(u,400,{error:"Invalid URL"});return}if(c.method==="GET"&&(g==="/"||g==="/index.html")){if(p&&fs$1.existsSync(p)){De(c,u,p);return}w(u,404,{error:"HTML report not found"});return}if(c.method==="GET"&&g==="/api/health"){qt(c,u,t,s);return}if(c.method==="GET"&&g==="/api/summary"){Ht(c,u,t);return}if(c.method==="GET"&&g==="/api/tests"){Ut(c,u,t);return}if(c.method==="GET"&&g==="/api/files"){jt(c,u,t);return}let m=g.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(c.method==="GET"&&m){$t(c,u,t,m[1],m[2]);return}let b=g.match(/^\/api\/tests\/([a-f0-9]+)$/);if(c.method==="GET"&&b){zt(c,u,t,b[1]);return}if(c.method==="GET"&&g==="/api/artifacts"){Vt(c,u,l);return}if(c.method==="DELETE"&&g==="/api/artifacts"){Gt(c,u,l);return}let S=g.match(/^\/api\/artifacts\/(.+)$/);if(c.method==="DELETE"&&S){Wt(c,u,l,decodeURIComponent(S[1]));return}if(c.method==="GET"&&g.startsWith("/artifacts/")){let y=decodeURIComponent(g.slice(11));if(y.includes("..")||y.includes("\0")){w(u,400,{error:"Invalid path"});return}De(c,u,path.join(l,y));return}if(c.method==="POST"&&g==="/api/shutdown"){Kt(c,u,f);return}w(u,404,{error:"Not found"});});function h(c){let u=g=>{g.code==="EADDRINUSE"&&i<Sa?(i++,h(c+1)):a(g);};f.once("error",u),f.listen(c,"127.0.0.1",()=>{f.removeListener("error",u);let g=f.address();if(!g||typeof g=="string"){a(new Error("Failed to get server address"));return}d(),r({port:g.port,dispose:()=>new Promise(m=>{clearTimeout(o),f.close(()=>m());})});});}h(n);})}async function Jt(t){let e=await W(t);return {port:e.port,dispose:e.dispose}}function Ia(t,e,r){let a=JSON.stringify(t),n=r?JSON.stringify(r):null;return Et(a,e,n)}async function Oe(t,e,r){try{let a=null,n=null,s=e.reportMode==="streaming"||e.reportMode==="auto"&&t.timeline.length===0&&t.summary.total>=e.streamingThreshold,o,i=e.htmlReportPath,l=path.dirname(i);fs$1.mkdirSync(l,{recursive:!0});let d="",p="[]",f=null;if(s){d=JSON.stringify({...t.summary,testRunId:t.testRunId,startedAt:t.startedAt,completedAt:t.completedAt,totalDuration:t.totalDuration,ci:t.ci,metadata:t.metadata,shardRunIds:t.shardRunIds});let c=path.dirname(e.outputPath),u=path.join(c,".testrelic-report");try{let g=path.join(u,"index-compact.json"),m=path.join(u,"index.json");fs$1.existsSync(g)?p=fs$1.readFileSync(g,"utf-8"):fs$1.existsSync(m)&&(p=fs$1.readFileSync(m,"utf-8"));}catch{}f=r?JSON.stringify(r):null,o=Pe(d,p,null,f);}else o=Ia(t,null,r);let h=i+".tmp";if(fs$1.writeFileSync(h,o,"utf-8"),fs$1.renameSync(h,i),s){if(t.ci===null){let c=path.dirname(e.outputPath),u=path.join(c,".testrelic-report"),g=path.resolve(i);try{if(await La(),a=await Ma(u),!a){n=await W(u,{htmlPath:g}),a=n.port;let m=setInterval(()=>{},6e4),b=()=>{clearInterval(m),n?.dispose();};process.on("SIGINT",b),process.on("SIGTERM",b),setTimeout(b,1800*1e3).unref();}if(a){process.stderr.write(`
2548
- Report server: http://127.0.0.1:${a}
2549
- `);try{let m=Pe(d,p,a,f),b=i+".tmp";fs$1.writeFileSync(b,m,"utf-8"),fs$1.renameSync(b,i);}catch{}}}catch{}}}else if(e.openReport&&t.ci===null&&e.includeArtifacts){let c=path.dirname(e.outputPath),u=path.join(c,"artifacts");if(fs$1.existsSync(u))try{let g=await Jt(u);a=g.port,process.on("exit",()=>{g.dispose();});}catch{}}if(e.openReport&&t.ci===null)if(s&&a)Ne(`http://127.0.0.1:${a}`);else {let c=path.resolve(i);Ne(c);}}catch(a){process.stderr.write(`[testrelic] Failed to write HTML report: ${a instanceof Error?a.message:String(a)}
2550
- `);}}var oe=9323,er=10;async function _a(){for(let t=oe;t<oe+er;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),500),a=await fetch(`http://127.0.0.1:${t}/api/health`,{signal:e.signal});if(clearTimeout(r),a.ok)return t}catch{}return null}async function La(){for(let t=oe;t<oe+er;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),1e3);await fetch(`http://127.0.0.1:${t}/api/shutdown`,{method:"POST",signal:e.signal}),clearTimeout(r);}catch{}await new Promise(t=>setTimeout(t,300));}async function Ma(t){let r=[path.join(__dirname,"cli.cjs"),path.join(__dirname,"cli.js"),path.join(__dirname,"..","dist","cli.cjs"),path.join(__dirname,"..","dist","cli.js")].find(a=>fs$1.existsSync(a));if(!r){let a=await W(t);return process.on("exit",()=>{a?.dispose();}),a.port}return new Promise(a=>{let n=child_process.spawn(process.execPath,[r,"serve",t],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),s="",o=false,i=setTimeout(()=>{o||(o=true,n.stderr?.removeAllListeners(),_a().then(a));},5e3);n.stderr?.on("data",l=>{s+=l.toString();let d=s.match(/127\.0\.0\.1:(\d+)/);d&&!o&&(o=true,clearTimeout(i),n.stderr?.removeAllListeners(),n.unref(),a(Number(d[1])));}),n.on("error",()=>{o||(o=true,clearTimeout(i),a(null));}),n.on("exit",()=>{o||(o=true,clearTimeout(i),a(null));}),n.unref();})}var Na=20,qe=0,He=[];async function rr(t,e){qe>=Na&&await new Promise(r=>He.push(r)),qe++;try{return await promises.copyFile(t,e),!0}catch{return false}finally{qe--,He.length>0&&He.shift()();}}var J=[];async function ar(){J.length!==0&&(await Promise.allSettled(J),J.length=0);}function nr(t){let e=new Date,r=s=>String(s).padStart(2,"0"),a=`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())}T${r(e.getHours())}-${r(e.getMinutes())}-${r(e.getSeconds())}`;if(!fs$1.existsSync(path.join(t,a)))return a;let n=1;for(;fs$1.existsSync(path.join(t,`${a}-${n}`));)n++;return `${a}-${n}`}function Fa(t){let e=t.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return e.length>100&&(e=e.substring(0,100).replace(/-+$/,"")),e||"unnamed-test"}function sr(t,e,r,a,n){let s=t.find(h=>h.name==="screenshot"&&h.path),o=t.find(h=>h.name==="video"&&h.path);if(!s&&!o)return null;let i=Fa(e);r>0&&(i+=`--retry-${r}`);let l=n?["artifacts",n,i]:["artifacts",i],d=path.join(a,...l),p=l,f={};try{fs$1.mkdirSync(d,{recursive:!0});}catch{return null}if(s?.path&&fs$1.existsSync(s.path)){let c=`screenshot${path.extname(s.path)||".png"}`,u=path.join(d,c);J.push(rr(s.path,u).then(()=>{})),f.screenshot=`${p.join("/")}/${c}`;}if(o?.path&&fs$1.existsSync(o.path)){let c=`video${path.extname(o.path)||".webm"}`,u=path.join(d,c);J.push(rr(o.path,u).then(()=>{})),f.video=`${p.join("/")}/${c}`;}return !f.screenshot&&!f.video?null:f}var Oa=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,qa="1.0";function Ha(t){let e=path.extname(t).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(e)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(e)?"video":"other"}function ir(t,e,r){let a=[];try{let n=fs$1.readdirSync(t,{withFileTypes:!0});for(let s of n){if(!s.isFile())continue;let o=path.join(t,s.name),i=fs$1.statSync(o);a.push({name:s.name,type:Ha(s.name),relativePath:`artifacts/${e}/${r}/${s.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:a}}function Ua(t,e){let r=path.join(t,e),a=[],n=0;try{let o=fs$1.readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let l=ir(path.join(r,i.name),e,i.name);a.push(l);for(let d of l.files)n+=d.sizeBytes;}}catch{}let s=e.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return a.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:e,timestamp:s,totalSizeBytes:n,testCount:a.length,tests:a,isCurrentRun:false}}function or(t,e){let r=path.join(t,"artifacts"),a=[],n=[],s=0;try{let i=fs$1.readdirSync(r,{withFileTypes:!0});for(let l of i)if(l.isDirectory())if(Oa.test(l.name)){let d=Ua(r,l.name);a.push({...d,isCurrentRun:l.name===e});}else {let d=ir(path.join(r,l.name),l.name,l.name);n.push(d);for(let p of d.files)s+=p.sizeBytes;}}catch{}a.sort((i,l)=>l.timestamp.localeCompare(i.timestamp)),n.length>0&&(n.sort((i,l)=>i.testName.localeCompare(l.testName)),a.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}));let o=a.reduce((i,l)=>i+l.totalSizeBytes,0);return {schemaVersion:qa,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:a,serverPort:null}}function Ga(t){let e=t,{root:r}=path.parse(e);for(;e!==r;){if(fs$1.existsSync(path.join(e,".git")))return e;e=path.join(e,"..");}return null}function dr(t){try{let e=Ga(t);if(!e)return;let r=path.join(e,".gitignore"),a=path.relative(e,t).replace(/\\/g,"/"),n=a.endsWith("/")?a:`${a}/`;if(fs$1.existsSync(r)&&fs$1.readFileSync(r,"utf-8").split(`
2551
- `).map(l=>l.trim()).some(l=>l===n||l===a))return;let s=`
2546
+ </html>`}function Fe(t){try{let e=process.platform,r;e==="darwin"?r=`open "${t}"`:e==="win32"?r=`start "" "${t}"`:r=`xdg-open "${t}"`,child_process.exec(r,s=>{s&&process.stderr.write(`[testrelic] Failed to open browser: ${s.message}
2547
+ `);});}catch{}}path.join(os$1.tmpdir(),"testrelic-data");async function qt(t,e,r,s){let a=(e-1)*r,n=[],o=0,i=readline.createInterface({input:fs$1.createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let p of i)if(p.length!==0){if(o>=a&&n.length<r)try{n.push(JSON.parse(p));}catch{}if(o++,n.length>=r&&s!==void 0)break}let l=s??o,d=Math.max(1,Math.ceil(l/r));return {items:n,total:l,page:e,pageSize:r,totalPages:d}}var zt=/^[a-f0-9]{12}$/,De=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,$t=500;function x(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function jt(t){t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type");}function ae(t){try{return fs$1.existsSync(t)?JSON.parse(fs$1.readFileSync(t,"utf-8")):null}catch{return null}}function ne(t){let e=0;try{let r=fs$1.readdirSync(t,{withFileTypes:!0});for(let s of r){let a=path.join(t,s.name);s.isFile()?e+=fs$1.statSync(a).size:s.isDirectory()&&(e+=ne(a));}}catch{}return e}function Vt(t,e,r,s){let a=ae(path.join(r,"index.json"));x(e,200,{status:"ok",reportMode:"streaming",testCount:a?.length??0,uptime:Math.floor((Date.now()-s)/1e3)});}function Gt(t,e,r){let s=ae(path.join(r,"summary.json"));if(!s){x(e,404,{error:"Summary not found"});return}x(e,200,s);}function Wt(t,e,r){let s=ae(path.join(r,"index.json"));if(!s){x(e,404,{error:"Test index not found"});return}let n=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,o=Math.max(1,parseInt(n.get("page")??"1",10)||1),i=Math.min($t,Math.max(1,parseInt(n.get("pageSize")??"100",10)||100)),l=n.get("status")?.split(",").filter(Boolean)??null,d=n.get("file")??null,p=n.get("search")?.toLowerCase()??null,f=n.get("tag")?.split(",").filter(Boolean)??null,m=n.get("sort")??"file",c=n.get("order")==="desc"?-1:1,u=s;l&&l.length>0&&(u=u.filter(y=>l.includes(y.status))),d&&(u=u.filter(y=>y.filePath===d||y.filePath.startsWith(d+"/"))),p&&(u=u.filter(y=>y.title.toLowerCase().includes(p)||y.filePath.toLowerCase().includes(p))),f&&f.length>0&&(u=u.filter(y=>f.some(b=>y.tags.includes(b)))),u=[...u].sort((y,b)=>{let S=0;switch(m){case "duration":S=y.duration-b.duration;break;case "status":S=y.status.localeCompare(b.status);break;case "title":S=y.title.localeCompare(b.title);break;default:S=y.filePath.localeCompare(b.filePath);break}return S*c});let g=u.length,h=Math.max(1,Math.ceil(g/i)),w=(o-1)*i,C=u.slice(w,w+i);x(e,200,{tests:C,pagination:{page:o,pageSize:i,totalItems:g,totalPages:h},filters:{status:l,file:d,search:p,tag:f}});}function Kt(t,e,r,s){if(!zt.test(s)){x(e,400,{error:"Invalid test ID format"});return}let a=path.join(r,"tests",s,"meta.json"),n=path.join(r,"tests",`${s}.json`),o=fs$1.existsSync(a)?a:fs$1.existsSync(n)?n:null;if(!o){x(e,404,{error:`Test not found: ${s}`});return}try{let i=fs$1.readFileSync(o,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(i);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}async function Jt(t,e,r,s,a){if(!zt.test(s)){x(e,400,{error:"Invalid test ID format"});return}let o=path.join(r,"tests",s,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[a]);if(!fs$1.existsSync(o)){x(e,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let l=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,d=Math.max(1,parseInt(l.get("page")??"1",10)||1),p=Math.min($t,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),f,m=path.join(r,"tests",s,"meta.json");if(fs$1.existsSync(m))try{let u=JSON.parse(fs$1.readFileSync(m,"utf-8"));switch(a){case "network":f=u.networkRequestsCount;break;case "console":f=u.consoleLogsCount;break;case "api-calls":f=u.apiCallsCount;break}}catch{}let c=await qt(o,d,p,f);x(e,200,c);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}function Yt(t,e,r){let s=ae(path.join(r,"index.json"));if(!s){x(e,404,{error:"Test index not found"});return}let a=new Map;for(let o of s){if(o.isRetry)continue;let i=a.get(o.filePath);switch(i||(i={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},a.set(o.filePath,i)),i.total++,o.status){case "passed":i.passed++;break;case "failed":i.failed++;break;case "flaky":i.flaky++;break;case "skipped":i.skipped++;break;case "timedout":i.timedOut++;break}}let n=Array.from(a.entries()).map(([o,i])=>({filePath:o,...i})).sort((o,i)=>o.filePath.localeCompare(i.filePath));x(e,200,{files:n});}function Zt(t,e,r){if(!fs$1.existsSync(r)){x(e,200,{runs:[],totalSizeBytes:0});return}try{let s=[],a=0,n=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of n){if(!o.isDirectory()||!De.test(o.name))continue;let i=path.join(r,o.name),l=ne(i),d=fs$1.readdirSync(i,{withFileTypes:!0}).filter(p=>p.isDirectory());s.push({folderName:o.name,totalSizeBytes:l,testCount:d.length}),a+=l;}s.sort((o,i)=>i.folderName.localeCompare(o.folderName)),x(e,200,{runs:s,totalSizeBytes:a});}catch(s){x(e,500,{error:s instanceof Error?s.message:String(s)});}}function Qt(t,e,r){try{let s=0,a=0;if(fs$1.existsSync(r)){let n=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of n){if(!o.isDirectory()||!De.test(o.name))continue;let i=path.join(r,o.name),l=ne(i);fs$1.rmSync(i,{recursive:!0,force:!0}),a+=l,s++;}}x(e,200,{deletedCount:s,freedBytes:a});}catch(s){x(e,500,{error:s instanceof Error?s.message:String(s)});}}function Xt(t,e,r,s){if(!De.test(s)){x(e,400,{error:"Invalid folder name"});return}let a=path.join(r,s);try{if(!fs$1.statSync(a).isDirectory()){x(e,404,{error:"Not found"});return}}catch{x(e,404,{error:"Not found"});return}try{let n=ne(a);fs$1.rmSync(a,{recursive:!0,force:!0}),x(e,200,{deleted:s,freedBytes:n});}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}function er(t,e,r){x(e,200,{status:"shutting_down"}),r.close();}function Be(t,e,r){if(!fs$1.existsSync(r)){x(e,404,{error:"File not found"});return}try{let s=fs$1.readFileSync(r),a=path.extname(r).toLowerCase(),n=Is[a]??"application/octet-stream";e.writeHead(200,{"Content-Type":n}),e.end(s);}catch(s){x(e,500,{error:s instanceof Error?s.message:String(s)});}}var Is={".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 Es=9323,Ps=10,Ns=1800*1e3;function J(t,e){return new Promise((r,s)=>{let a=e?.port??Es,n=Date.now(),o,i=0,l=fs$1.existsSync(path.join(t,"artifacts"))?path.join(t,"artifacts"):fs$1.existsSync(path.join(t,"..","artifacts"))?path.join(t,"..","artifacts"):path.join(t,"artifacts");function d(){clearTimeout(o),o=setTimeout(()=>{f.close();},Ns);}let p=e?.htmlPath??null;if(!p){let c=path.dirname(t);try{let u=fs$1.readdirSync(c).find(g=>g.endsWith(".html"));u&&(p=path.join(c,u));}catch{}}let f=http.createServer((c,u)=>{if(d(),jt(u),c.method==="OPTIONS"){u.writeHead(204),u.end();return}let g;try{g=new URL(c.url??"/",`http://${c.headers.host??"localhost"}`).pathname;}catch{x(u,400,{error:"Invalid URL"});return}if(c.method==="GET"&&(g==="/"||g==="/index.html")){if(p&&fs$1.existsSync(p)){Be(c,u,p);return}x(u,404,{error:"HTML report not found"});return}if(c.method==="GET"&&g==="/api/health"){Vt(c,u,t,n);return}if(c.method==="GET"&&g==="/api/summary"){Gt(c,u,t);return}if(c.method==="GET"&&g==="/api/tests"){Wt(c,u,t);return}if(c.method==="GET"&&g==="/api/files"){Yt(c,u,t);return}let h=g.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(c.method==="GET"&&h){Jt(c,u,t,h[1],h[2]);return}let w=g.match(/^\/api\/tests\/([a-f0-9]+)$/);if(c.method==="GET"&&w){Kt(c,u,t,w[1]);return}if(c.method==="GET"&&g==="/api/artifacts"){Zt(c,u,l);return}if(c.method==="DELETE"&&g==="/api/artifacts"){Qt(c,u,l);return}let C=g.match(/^\/api\/artifacts\/(.+)$/);if(c.method==="DELETE"&&C){Xt(c,u,l,decodeURIComponent(C[1]));return}if(c.method==="GET"&&g.startsWith("/artifacts/")){let y=decodeURIComponent(g.slice(11));if(y.includes("..")||y.includes("\0")){x(u,400,{error:"Invalid path"});return}Be(c,u,path.join(l,y));return}if(c.method==="POST"&&g==="/api/shutdown"){er(c,u,f);return}x(u,404,{error:"Not found"});});function m(c){let u=g=>{g.code==="EADDRINUSE"&&i<Ps?(i++,m(c+1)):s(g);};f.once("error",u),f.listen(c,"127.0.0.1",()=>{f.removeListener("error",u);let g=f.address();if(!g||typeof g=="string"){s(new Error("Failed to get server address"));return}d(),r({port:g.port,dispose:()=>new Promise(h=>{clearTimeout(o),f.close(()=>h());})});});}m(a);})}async function tr(t){let e=await J(t);return {port:e.port,dispose:e.dispose}}function Bs(t,e,r){let s=JSON.stringify(t),a=r?JSON.stringify(r):null;return Ot(s,e,a)}async function qe(t,e,r){try{let s=null,a=null,n=e.reportMode==="streaming"||e.reportMode==="auto"&&t.timeline.length===0&&t.summary.total>=e.streamingThreshold,o,i=e.htmlReportPath,l=path.dirname(i);fs$1.mkdirSync(l,{recursive:!0});let d="",p="[]",f=null;if(n){d=JSON.stringify({...t.summary,testRunId:t.testRunId,startedAt:t.startedAt,completedAt:t.completedAt,totalDuration:t.totalDuration,ci:t.ci,metadata:t.metadata,shardRunIds:t.shardRunIds});let c=path.dirname(e.outputPath),u=path.join(c,".testrelic-report");try{let g=path.join(u,"index-compact.json"),h=path.join(u,"index.json");fs$1.existsSync(g)?p=fs$1.readFileSync(g,"utf-8"):fs$1.existsSync(h)&&(p=fs$1.readFileSync(h,"utf-8"));}catch{}f=r?JSON.stringify(r):null,o=Ne(d,p,null,f);}else o=Bs(t,null,r);let m=i+".tmp";if(fs$1.writeFileSync(m,o,"utf-8"),fs$1.renameSync(m,i),n){if(t.ci===null){let c=path.dirname(e.outputPath),u=path.join(c,".testrelic-report"),g=path.resolve(i);try{if(await qs(),s=await Hs(u),!s){a=await J(u,{htmlPath:g}),s=a.port;let h=setInterval(()=>{},6e4),w=()=>{clearInterval(h),a?.dispose();};process.on("SIGINT",w),process.on("SIGTERM",w),setTimeout(w,1800*1e3).unref();}if(s){process.stderr.write(`
2548
+ Report server: http://127.0.0.1:${s}
2549
+ `);try{let h=Ne(d,p,s,f),w=i+".tmp";fs$1.writeFileSync(w,h,"utf-8"),fs$1.renameSync(w,i);}catch{}}}catch{}}}else if(e.openReport&&t.ci===null&&e.includeArtifacts){let c=path.dirname(e.outputPath),u=path.join(c,"artifacts");if(fs$1.existsSync(u))try{let g=await tr(u);s=g.port,process.on("exit",()=>{g.dispose();});}catch{}}if(e.openReport&&t.ci===null)if(n&&s)Fe(`http://127.0.0.1:${s}`);else {let c=path.resolve(i);Fe(c);}}catch(s){process.stderr.write(`[testrelic] Failed to write HTML report: ${s instanceof Error?s.message:String(s)}
2550
+ `);}}var le=9323,ir=10;async function Os(){for(let t=le;t<le+ir;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),500),s=await fetch(`http://127.0.0.1:${t}/api/health`,{signal:e.signal});if(clearTimeout(r),s.ok)return t}catch{}return null}async function qs(){for(let t=le;t<le+ir;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),1e3);await fetch(`http://127.0.0.1:${t}/api/shutdown`,{method:"POST",signal:e.signal}),clearTimeout(r);}catch{}await new Promise(t=>setTimeout(t,300));}async function Hs(t){let r=[path.join(__dirname,"cli.cjs"),path.join(__dirname,"cli.js"),path.join(__dirname,"..","dist","cli.cjs"),path.join(__dirname,"..","dist","cli.js")].find(s=>fs$1.existsSync(s));if(!r){let s=await J(t);return process.on("exit",()=>{s?.dispose();}),s.port}return new Promise(s=>{let a=child_process.spawn(process.execPath,[r,"serve",t],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),n="",o=false,i=setTimeout(()=>{o||(o=true,a.stderr?.removeAllListeners(),Os().then(s));},5e3);a.stderr?.on("data",l=>{n+=l.toString();let d=n.match(/127\.0\.0\.1:(\d+)/);d&&!o&&(o=true,clearTimeout(i),a.stderr?.removeAllListeners(),a.unref(),s(Number(d[1])));}),a.on("error",()=>{o||(o=true,clearTimeout(i),s(null));}),a.on("exit",()=>{o||(o=true,clearTimeout(i),s(null));}),a.unref();})}var $s=20,He=0,Ue=[];async function lr(t,e){He>=$s&&await new Promise(r=>Ue.push(r)),He++;try{return await promises.copyFile(t,e),!0}catch{return false}finally{He--,Ue.length>0&&Ue.shift()();}}var Z=[];async function dr(){Z.length!==0&&(await Promise.allSettled(Z),Z.length=0);}function cr(t){let e=new Date,r=n=>String(n).padStart(2,"0"),s=`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())}T${r(e.getHours())}-${r(e.getMinutes())}-${r(e.getSeconds())}`;if(!fs$1.existsSync(path.join(t,s)))return s;let a=1;for(;fs$1.existsSync(path.join(t,`${s}-${a}`));)a++;return `${s}-${a}`}function js(t){let e=t.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return e.length>100&&(e=e.substring(0,100).replace(/-+$/,"")),e||"unnamed-test"}function ur(t,e,r,s,a){let n=t.find(m=>m.name==="screenshot"&&m.path),o=t.find(m=>m.name==="video"&&m.path);if(!n&&!o)return null;let i=js(e);r>0&&(i+=`--retry-${r}`);let l=a?["artifacts",a,i]:["artifacts",i],d=path.join(s,...l),p=l,f={};try{fs$1.mkdirSync(d,{recursive:!0});}catch{return null}if(n?.path&&fs$1.existsSync(n.path)){let c=`screenshot${path.extname(n.path)||".png"}`,u=path.join(d,c);Z.push(lr(n.path,u).then(()=>{})),f.screenshot=`${p.join("/")}/${c}`;}if(o?.path&&fs$1.existsSync(o.path)){let c=`video${path.extname(o.path)||".webm"}`,u=path.join(d,c);Z.push(lr(o.path,u).then(()=>{})),f.video=`${p.join("/")}/${c}`;}return !f.screenshot&&!f.video?null:f}var Ws=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Ks="1.0";function Js(t){let e=path.extname(t).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(e)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(e)?"video":"other"}function pr(t,e,r){let s=[];try{let a=fs$1.readdirSync(t,{withFileTypes:!0});for(let n of a){if(!n.isFile())continue;let o=path.join(t,n.name),i=fs$1.statSync(o);s.push({name:n.name,type:Js(n.name),relativePath:`artifacts/${e}/${r}/${n.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:s}}function Ys(t,e){let r=path.join(t,e),s=[],a=0;try{let o=fs$1.readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let l=pr(path.join(r,i.name),e,i.name);s.push(l);for(let d of l.files)a+=d.sizeBytes;}}catch{}let n=e.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return s.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:e,timestamp:n,totalSizeBytes:a,testCount:s.length,tests:s,isCurrentRun:false}}function fr(t,e){let r=path.join(t,"artifacts"),s=[],a=[],n=0;try{let i=fs$1.readdirSync(r,{withFileTypes:!0});for(let l of i)if(l.isDirectory())if(Ws.test(l.name)){let d=Ys(r,l.name);s.push({...d,isCurrentRun:l.name===e});}else {let d=pr(path.join(r,l.name),l.name,l.name);a.push(d);for(let p of d.files)n+=p.sizeBytes;}}catch{}s.sort((i,l)=>l.timestamp.localeCompare(i.timestamp)),a.length>0&&(a.sort((i,l)=>i.testName.localeCompare(l.testName)),s.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:n,testCount:a.length,tests:a,isCurrentRun:false}));let o=s.reduce((i,l)=>i+l.totalSizeBytes,0);return {schemaVersion:Ks,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:s,serverPort:null}}function ta(t){let e=t,{root:r}=path.parse(e);for(;e!==r;){if(fs$1.existsSync(path.join(e,".git")))return e;e=path.join(e,"..");}return null}function hr(t){try{let e=ta(t);if(!e)return;let r=path.join(e,".gitignore"),s=path.relative(e,t).replace(/\\/g,"/"),a=s.endsWith("/")?s:`${s}/`;if(fs$1.existsSync(r)&&fs$1.readFileSync(r,"utf-8").split(`
2551
+ `).map(l=>l.trim()).some(l=>l===a||l===s))return;let n=`
2552
2552
  # TestRelic test artifacts
2553
- ${n}
2554
- `;fs$1.appendFileSync(r,s,"utf-8");}catch{}}function pr(t,e){let r=[];for(let a of t){let n=Wa(a),s=Ka(a),o=Ja(a,n,s,e),i=Ya(a,n,s);if(o.length===0&&i.length===0){r.push({type:"navigation",url:"about:blank",timestamp:a.startedAt,durationOnUrl:a.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:a.specFile,test:n,tests:[s],_testTitle:a.title});continue}r.push(...o,...i);}return r.sort(Za),Qa(r,t),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 Wa(t){return {title:t.title,fullTitle:t.titlePath,status:t.status,duration:t.duration,retries:t.retryCount,retry:t.retry,tags:t.tags,failure:t.failure}}function Ka(t){return {title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retryCount:t.retryCount,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,retryStatus:t.retryStatus,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,networkRequests:t.networkRequests,apiCalls:t.apiCalls,apiAssertions:t.apiAssertions,actions:t.actions,consoleLogs:t.consoleLogs}}function Ja(t,e,r,a){let n=[];for(let s of t.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:t.specFile,test:e,tests:[r],_testTitle:t.title});return n}function Ya(t,e,r){if(!t.apiCalls||t.apiCalls.length===0)return [];let a=t.apiAssertions??[];return t.apiCalls.map(n=>{let s=a.filter(i=>i.callId===n.id).map(i=>({type:i.type,expected:i.expected,actual:i.actual,status:i.status,location:i.location,...i.expression!==void 0?{expression:i.expression}:{}})),o=null;return n.responseStatusCode!==null&&n.responseStatusText!==null&&(o={statusCode:n.responseStatusCode,statusText:n.responseStatusText,headers:n.responseHeaders,body:ur(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:ur(n.requestBody)},response:o,...n.error?{error:n.error}:{},assertions:s,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title}})}function Za(t,e){let r=new Date(t.timestamp).getTime(),a=new Date(e.timestamp).getTime();if(r!==a)return r-a;let n={navigation:0,api_call:1},s=n[t.type],o=n[e.type];return s!==o?s-o:t.type==="api_call"&&e.type==="api_call"&&t.callId&&e.callId?cr(t.callId)-cr(e.callId):0}function cr(t){let e=t.match(/(\d+)$/);return e?parseInt(e[1],10):0}function Qa(t,e){for(let r=0;r<t.length;r++){let a=t[r];if(a.type!=="navigation")continue;let n=new Date(a.timestamp).getTime(),s=null;for(let o=r+1;o<t.length;o++)if(t[o]._testTitle===a._testTitle){s=new Date(t[o].timestamp).getTime();break}if(s!==null)a.durationOnUrl=Math.max(0,s-n);else {let o=e.find(i=>i.title===a._testTitle);if(o){let i=new Date(o.completedAt).getTime();a.durationOnUrl=Math.max(0,i-n);}}}}function ur(t){if(t==null)return null;try{return JSON.parse(t)}catch{return t}}function $e(t,e){let r=t.length,a=Math.min(Math.ceil(e/100*r)-1,r-1);return t[Math.max(0,a)]}function Xa(t){try{let e=new URL(t);return e.origin+e.pathname}catch{return t}}function en(t){return t==null?"error":t>=200&&t<300?"2xx":t>=300&&t<400?"3xx":t>=400&&t<500?"4xx":t>=500&&t<600?"5xx":"error"}function fr(t,e){let r=0,a=0,n=0,s=0,o=0;for(let v of t)switch(v.status){case "passed":r++;break;case "failed":a++;break;case "flaky":n++;break;case "skipped":s++;break;case "timedout":o++;break}let i=[];for(let v of t)v.apiCalls&&i.push(...v.apiCalls);let l=i.length,d=new Set,p={},f={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},h=[];for(let v of i)d.add(Xa(v.url)),p[v.method]=(p[v.method]??0)+1,f[en(v.responseStatusCode)]+=1,h.push(v.responseTimeMs);let c=null;if(h.length>0){let v=[...h].sort((A,H)=>A-H),k=v.reduce((A,H)=>A+H,0);c={avg:Math.round(k/v.length),min:v[0],max:v[v.length-1],p50:$e(v,50),p95:$e(v,95),p99:$e(v,99)};}let u=0,g=0,m=0;for(let v of t)if(v.apiAssertions)for(let k of v.apiAssertions)u++,k.status==="passed"?g++:m++;let b=0,S=new Set;for(let v of t){b+=v.navigations.length;for(let k of v.navigations)S.add(k.url);}let y=0,x={};function T(v){for(let k of v)y++,x[k.category]=(x[k.category]??0)+1,k.children.length>0&&T(k.children);}for(let v of t)v.actions&&T(v.actions);return {total:t.length,passed:r,failed:a,flaky:n,skipped:s,timedout:o,totalApiCalls:l,uniqueApiUrls:d.size,apiCallsByMethod:p,apiCallsByStatusRange:f,apiResponseTime:c,totalAssertions:u,passedAssertions:g,failedAssertions:m,totalNavigations:b,uniqueNavigationUrls:S.size,totalTimelineSteps:e,totalActionSteps:y,actionStepsByCategory:x}}function tn(t){let e=56-t.length;return e>0?t+" ".repeat(e):t}function _(t){return `\u2502 ${tn(t)} \u2502
2555
- `}function je(t,e,r,a){if(a||t.total===0)return;let n=`\u250C${"\u2500".repeat(58)}\u2510
2556
- `,s=`\u2514${"\u2500".repeat(58)}\u2518
2557
- `,o=_(""),i=n;i+=_("TestRelic AI - Playwright Test Report"),i+=o;let l=[];if(t.passed>0&&l.push(`${t.passed} \u2713`),t.failed>0&&l.push(`${t.failed} \u2717`),t.flaky>0&&l.push(`${t.flaky} \u26A0`),t.skipped>0&&l.push(`${t.skipped} skipped`),t.timedout>0&&l.push(`${t.timedout} timedout`),i+=_(`Tests: ${t.total} total (${l.join(" ")})`),t.totalNavigations>0&&(i+=_(`Navigations: ${t.totalNavigations} visits across ${t.uniqueNavigationUrls} unique URLs`)),t.totalApiCalls>0){i+=_(`API Calls: ${t.totalApiCalls} calls across ${t.uniqueApiUrls} unique endpoints`);let d=Object.entries(t.apiCallsByMethod).filter(([,f])=>f>0).map(([f,h])=>`${f}: ${h}`);d.length>0&&(i+=_(` ${d.join(" ")}`));let p=Object.entries(t.apiCallsByStatusRange).filter(([,f])=>f>0).map(([f,h])=>`${f}: ${h}`);p.length>0&&(i+=_(` ${p.join(" ")}`)),t.apiResponseTime&&(i+=_(` Avg response: ${t.apiResponseTime.avg}ms P95: ${t.apiResponseTime.p95}ms`));}if(t.totalAssertions>0&&(i+=_(`Assertions: ${t.totalAssertions} total (${t.passedAssertions} \u2713 ${t.failedAssertions} \u2717)`)),t.totalActionSteps>0){let d=[],p=t.actionStepsByCategory;p.ui_action&&d.push(`${p.ui_action} UI`),p.assertion&&d.push(`${p.assertion} assertions`),p.custom_step&&d.push(`${p.custom_step} custom`);let f=d.length>0?` (${d.join(" ")})`:"";i+=_(`Actions: ${t.totalActionSteps} steps${f}`);}i+=_(`Report: ${r}`),i+=_(`Data: ${e}`),i+=s,i+=`For more information visit us at https://docs.testrelic.ai
2558
- `,process.stderr.write(i);}var rn=new Set(["pw:api","expect","test.step"]);function an(t){return t==="expect"?"assertion":t==="test.step"?"custom_step":"ui_action"}function Ve(t,e,r){if(rn.has(t.category)){let a=[];for(let s of t.steps)Ve(s,e,a);let n=t.startTime.getTime()-e.getTime();r.push({title:t.title,category:an(t.category),timestamp:t.startTime.toISOString(),duration:t.duration,videoOffset:n>=0?n/1e3:null,status:t.error?"failed":"passed",error:t.error?.message??null,children:a});}else for(let a of t.steps)Ve(a,e,r);}function gr(t,e){let r=[];for(let a of t)Ve(a,e,r);return r}var on=new Set(["localhost","127.0.0.1","0.0.0.0"]);function mr(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&on.has(e.hostname)))throw core.createError(core.ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${e.protocol}//${e.hostname}`)}var ln=3e3;async function Ge(t){let e=new AbortController,r=setTimeout(()=>e.abort(),ln);try{return (await fetch(`${t}/health`,{method:"GET",signal:e.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function vr(t){return new Promise(e=>setTimeout(e,t))}async function hr(t){try{let r=(await t.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 ${t.status}`}async function We(t,e,r){let a=new AbortController,n=setTimeout(()=>a.abort(),r);try{let s=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),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"),l=i?parseInt(i,10)*1e3:5e3;if(!isNaN(l)&&l>0){await vr(l);let d=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:a.signal});if(d.ok){let p=await d.json();return {accessToken:p.accessToken,refreshToken:p.refreshToken,expiresIn:p.expiresIn,orgId:p.orgId,orgName:p.orgName,userId:p.userId,userName:p.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return s.status===400?{code:"validation_error",message:await hr(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 hr(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 Ke(t){return "code"in t&&typeof t.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(t.code)}async function yr(t,e,r){let a=new AbortController,n=setTimeout(()=>a.abort(),r);try{let s=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:a.signal});if(s.status===429){let i=s.headers.get("Retry-After"),l=i?parseInt(i,10)*1e3:5e3;!isNaN(l)&&l>0&&(await vr(l),s=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:a.signal}));}if(!s.ok)return null;let o=await s.json();return {accessToken:o.accessToken,refreshToken:o.refreshToken,expiresIn:o.expiresIn}}catch{return null}finally{clearTimeout(n);}}async function br(t,e,r,a,n,s){let o=new AbortController,i=setTimeout(()=>o.abort(),n);try{let l={gitId:r,displayName:a};s&&(l.branch=s);let d=await fetch(`${t}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(l),signal:o.signal});if(!d.ok)return null;let p=await d.json();return {repoId:p.repoId,displayName:p.displayName}}catch{return null}finally{clearTimeout(i);}}var fn=5e3;function F(t,e){try{return child_process.execSync(t,{cwd:e,timeout:fn,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function xr(t){let e=F("git rev-parse --abbrev-ref HEAD",t),r=F("git rev-parse --short HEAD",t),a=F("git log -1 --pretty=%s",t),n=F("git log -1 --format=%an",t)??F("git config user.name",t),s=gn(t),o=s?Z(s):null;return {branch:e,commitSha:r,commitMessage:a,commitAuthor:n,remoteUrl:o}}function gn(t){let e=F("git remote get-url origin",t);if(e)return e;let r=F("git remote",t);if(!r)return null;let a=r.split(`
2559
- `)[0]?.trim();return a?F(`git remote get-url ${a}`,t):null}function Z(t){let e=t.trim();return e=e.replace(/^[a-z+]+:\/\//,""),e=e.replace(/^[^@]+@/,""),e=e.replace(/:(?!\d)/,"/"),e=e.replace(/\.git$/,""),e=e.replace(/\/+$/,""),e=e.replace(/^[^@/]+@/,""),e.toLowerCase()}function wr(t){let e=t.split("/").filter(Boolean);return e[e.length-1]??t}function Je(t){try{let e=fs$1.readFileSync(path.join(t,"package.json"),"utf-8"),r=JSON.parse(e);return typeof r.name=="string"&&r.name.length>0?r.name:null}catch{return null}}function Q(t){let e=Je(t);return e||`local/${path.basename(t)}`}var wn=1048576,kn="1.0.0",kr=10;function X(t,e,r,a,n,s,o,i){try{fs$1.mkdirSync(t,{recursive:!0});let l=Date.now(),d=`${l}-${e}-${r}.json`,p=path.join(t,d),f={version:kn,queuedAt:new Date(l).toISOString(),reason:a,retryCount:0,targetEndpoint:n,method:s,payload:o,headers:i},h=p+".tmp";fs$1.writeFileSync(h,JSON.stringify(f,null,2),"utf-8"),fs$1.renameSync(h,p);}catch(l){l.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
2553
+ ${a}
2554
+ `;fs$1.appendFileSync(r,n,"utf-8");}catch{}}function yr(t,e){let r=[];for(let s of t){let a=ra(s),n=sa(s),o=aa(s,a,n,e),i=na(s,a,n);if(o.length===0&&i.length===0){r.push({type:"navigation",url:"about:blank",timestamp:s.startedAt,durationOnUrl:s.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:s.specFile,test:a,tests:[n],_testTitle:s.title});continue}r.push(...o,...i);}return r.sort(ia),oa(r,t),r.map((s,a)=>s.type==="navigation"?{...{index:a,type:"navigation",url:s.url,timestamp:s.timestamp,durationOnUrl:s.durationOnUrl??0,navigationType:s.navigationType,domContentLoadedAt:s.domContentLoadedAt??null,networkIdleAt:s.networkIdleAt??null,networkStats:s.networkStats??null,specFile:s.specFile,test:s.test},tests:s.tests}:{...{index:a,type:"api_call",callId:s.callId,method:s.method,url:s.url,timestamp:s.timestamp,responseTime:s.responseTime??null,request:s.request,response:s.response??null,...s.error?{error:s.error}:{},assertions:s.assertions??[],specFile:s.specFile,test:s.test},tests:s.tests})}function ra(t){return {title:t.title,fullTitle:t.titlePath,status:t.status,duration:t.duration,retries:t.retryCount,retry:t.retry,tags:t.tags,failure:t.failure}}function sa(t){return {title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retryCount:t.retryCount,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,retryStatus:t.retryStatus,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,networkRequests:t.networkRequests,apiCalls:t.apiCalls,apiAssertions:t.apiAssertions,actions:t.actions,consoleLogs:t.consoleLogs}}function aa(t,e,r,s){let a=[];for(let n of t.navigations)s.navigationTypes!==null&&!s.navigationTypes.includes(n.navigationType)||a.push({type:"navigation",url:n.url,timestamp:n.timestamp,durationOnUrl:0,navigationType:n.navigationType,domContentLoadedAt:n.domContentLoadedAt??null,networkIdleAt:n.networkIdleAt??null,networkStats:n.networkStats??null,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title});return a}function na(t,e,r){if(!t.apiCalls||t.apiCalls.length===0)return [];let s=t.apiAssertions??[];return t.apiCalls.map(a=>{let n=s.filter(i=>i.callId===a.id).map(i=>({type:i.type,expected:i.expected,actual:i.actual,status:i.status,location:i.location,...i.expression!==void 0?{expression:i.expression}:{}})),o=null;return a.responseStatusCode!==null&&a.responseStatusText!==null&&(o={statusCode:a.responseStatusCode,statusText:a.responseStatusText,headers:a.responseHeaders,body:vr(a.responseBody)}),{type:"api_call",callId:a.id,method:a.method,url:a.url,timestamp:a.timestamp,responseTime:a.error?null:a.responseTimeMs,request:{headers:a.requestHeaders,body:vr(a.requestBody)},response:o,...a.error?{error:a.error}:{},assertions:n,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title}})}function ia(t,e){let r=new Date(t.timestamp).getTime(),s=new Date(e.timestamp).getTime();if(r!==s)return r-s;let a={navigation:0,api_call:1},n=a[t.type],o=a[e.type];return n!==o?n-o:t.type==="api_call"&&e.type==="api_call"&&t.callId&&e.callId?mr(t.callId)-mr(e.callId):0}function mr(t){let e=t.match(/(\d+)$/);return e?parseInt(e[1],10):0}function oa(t,e){for(let r=0;r<t.length;r++){let s=t[r];if(s.type!=="navigation")continue;let a=new Date(s.timestamp).getTime(),n=null;for(let o=r+1;o<t.length;o++)if(t[o]._testTitle===s._testTitle){n=new Date(t[o].timestamp).getTime();break}if(n!==null)s.durationOnUrl=Math.max(0,n-a);else {let o=e.find(i=>i.title===s._testTitle);if(o){let i=new Date(o.completedAt).getTime();s.durationOnUrl=Math.max(0,i-a);}}}}function vr(t){if(t==null)return null;try{return JSON.parse(t)}catch{return t}}function H(t,e){let r=t.length,s=Math.min(Math.ceil(e/100*r)-1,r-1);return t[Math.max(0,s)]}function je(t){try{let e=new URL(t);return e.origin+e.pathname}catch{return t}}function la(t){return t==null?"error":t>=200&&t<300?"2xx":t>=300&&t<400?"3xx":t>=400&&t<500?"4xx":t>=500&&t<600?"5xx":"error"}function br(t,e){let r=0,s=0,a=0,n=0,o=0;for(let v of t)switch(v.status){case "passed":r++;break;case "failed":s++;break;case "flaky":a++;break;case "skipped":n++;break;case "timedout":o++;break}let i=[];for(let v of t)v.apiCalls&&i.push(...v.apiCalls);let l=i.length,d=new Set,p={},f={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},m=[];for(let v of i)d.add(je(v.url)),p[v.method]=(p[v.method]??0)+1,f[la(v.responseStatusCode)]+=1,m.push(v.responseTimeMs);let c=null;if(m.length>0){let v=[...m].sort((A,z)=>A-z),k=v.reduce((A,z)=>A+z,0);c={avg:Math.round(k/v.length),min:v[0],max:v[v.length-1],p50:H(v,50),p95:H(v,95),p99:H(v,99)};}let u=0,g=0,h=0;for(let v of t)if(v.apiAssertions)for(let k of v.apiAssertions)u++,k.status==="passed"?g++:h++;let w=0,C=new Set;for(let v of t){w+=v.navigations.length;for(let k of v.navigations)C.add(k.url);}let y=0,b={};function S(v){for(let k of v)y++,b[k.category]=(b[k.category]??0)+1,k.children.length>0&&S(k.children);}for(let v of t)v.actions&&S(v.actions);return {total:t.length,passed:r,failed:s,flaky:a,skipped:n,timedout:o,totalApiCalls:l,uniqueApiUrls:d.size,apiCallsByMethod:p,apiCallsByStatusRange:f,apiResponseTime:c,totalAssertions:u,passedAssertions:g,failedAssertions:h,totalNavigations:w,uniqueNavigationUrls:C.size,totalTimelineSteps:e,totalActionSteps:y,actionStepsByCategory:b}}function da(t){let e=56-t.length;return e>0?t+" ".repeat(e):t}function M(t){return `\u2502 ${da(t)} \u2502
2555
+ `}function Ve(t,e,r,s){if(s||t.total===0)return;let a=`\u250C${"\u2500".repeat(58)}\u2510
2556
+ `,n=`\u2514${"\u2500".repeat(58)}\u2518
2557
+ `,o=M(""),i=a;i+=M("TestRelic AI - Playwright Test Report"),i+=o;let l=[];if(t.passed>0&&l.push(`${t.passed} \u2713`),t.failed>0&&l.push(`${t.failed} \u2717`),t.flaky>0&&l.push(`${t.flaky} \u26A0`),t.skipped>0&&l.push(`${t.skipped} skipped`),t.timedout>0&&l.push(`${t.timedout} timedout`),i+=M(`Tests: ${t.total} total (${l.join(" ")})`),t.totalNavigations>0&&(i+=M(`Navigations: ${t.totalNavigations} visits across ${t.uniqueNavigationUrls} unique URLs`)),t.totalApiCalls>0){i+=M(`API Calls: ${t.totalApiCalls} calls across ${t.uniqueApiUrls} unique endpoints`);let d=Object.entries(t.apiCallsByMethod).filter(([,f])=>f>0).map(([f,m])=>`${f}: ${m}`);d.length>0&&(i+=M(` ${d.join(" ")}`));let p=Object.entries(t.apiCallsByStatusRange).filter(([,f])=>f>0).map(([f,m])=>`${f}: ${m}`);p.length>0&&(i+=M(` ${p.join(" ")}`)),t.apiResponseTime&&(i+=M(` Avg response: ${t.apiResponseTime.avg}ms P95: ${t.apiResponseTime.p95}ms`));}if(t.totalAssertions>0&&(i+=M(`Assertions: ${t.totalAssertions} total (${t.passedAssertions} \u2713 ${t.failedAssertions} \u2717)`)),t.totalActionSteps>0){let d=[],p=t.actionStepsByCategory;p.ui_action&&d.push(`${p.ui_action} UI`),p.assertion&&d.push(`${p.assertion} assertions`),p.custom_step&&d.push(`${p.custom_step} custom`);let f=d.length>0?` (${d.join(" ")})`:"";i+=M(`Actions: ${t.totalActionSteps} steps${f}`);}i+=M(`Report: ${r}`),i+=M(`Data: ${e}`),i+=n,i+=`For more information visit us at https://docs.testrelic.ai
2558
+ `,process.stderr.write(i);}var ca=new Set(["pw:api","expect","test.step"]);function ua(t){return t==="expect"?"assertion":t==="test.step"?"custom_step":"ui_action"}function Ge(t,e,r){if(ca.has(t.category)){let s=[];for(let n of t.steps)Ge(n,e,s);let a=t.startTime.getTime()-e.getTime();r.push({title:t.title,category:ua(t.category),timestamp:t.startTime.toISOString(),duration:t.duration,videoOffset:a>=0?a/1e3:null,status:t.error?"failed":"passed",error:t.error?.message??null,children:s});}else for(let s of t.steps)Ge(s,e,r);}function xr(t,e){let r=[];for(let s of t)Ge(s,e,r);return r}var ga=new Set(["localhost","127.0.0.1","0.0.0.0"]);function kr(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&ga.has(e.hostname)))throw core.createError(core.ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${e.protocol}//${e.hostname}`)}var ha=3e3;async function We(t){let e=new AbortController,r=setTimeout(()=>e.abort(),ha);try{return (await fetch(`${t}/health`,{method:"GET",signal:e.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function Tr(t){return new Promise(e=>setTimeout(e,t))}async function wr(t){try{let r=(await t.json()).error;if(r&&typeof r.message=="string"){let s=r.details;if(Array.isArray(s)&&s.length>0){let a=s.map(n=>`${n.field}: ${n.message}`).join(", ");return `${r.message} (${a})`}return r.message}}catch{}return `HTTP ${t.status}`}async function Ke(t,e,r){let s=new AbortController,a=setTimeout(()=>s.abort(),r);try{let n=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:s.signal});if(n.ok){let i=await n.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,orgId:i.orgId,orgName:i.orgName,userId:i.userId,userName:i.userName}}if(n.status===429){let i=n.headers.get("Retry-After"),l=i?parseInt(i,10)*1e3:5e3;if(!isNaN(l)&&l>0){await Tr(l);let d=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:s.signal});if(d.ok){let p=await d.json();return {accessToken:p.accessToken,refreshToken:p.refreshToken,expiresIn:p.expiresIn,orgId:p.orgId,orgName:p.orgName,userId:p.userId,userName:p.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return n.status===400?{code:"validation_error",message:await wr(n),statusCode:400}:n.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:n.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await wr(n),statusCode:n.status}}catch(n){return n instanceof DOMException&&n.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(a);}}function Je(t){return "code"in t&&typeof t.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(t.code)}async function Sr(t,e,r){let s=new AbortController,a=setTimeout(()=>s.abort(),r);try{let n=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:s.signal});if(n.status===429){let i=n.headers.get("Retry-After"),l=i?parseInt(i,10)*1e3:5e3;!isNaN(l)&&l>0&&(await Tr(l),n=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:s.signal}));}if(!n.ok)return null;let o=await n.json();return {accessToken:o.accessToken,refreshToken:o.refreshToken,expiresIn:o.expiresIn}}catch{return null}finally{clearTimeout(a);}}async function Cr(t,e,r,s,a,n){let o=new AbortController,i=setTimeout(()=>o.abort(),a);try{let l={gitId:r,displayName:s};n&&(l.branch=n);let d=await fetch(`${t}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(l),signal:o.signal});if(!d.ok)return null;let p=await d.json();return {repoId:p.repoId,displayName:p.displayName}}catch{return null}finally{clearTimeout(i);}}var xa=5e3;function D(t,e){try{return child_process.execSync(t,{cwd:e,timeout:xa,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function Rr(t){let e=D("git rev-parse --abbrev-ref HEAD",t),r=D("git rev-parse --short HEAD",t),s=D("git log -1 --pretty=%s",t),a=D("git log -1 --format=%an",t)??D("git config user.name",t),n=wa(t),o=n?X(n):null;return {branch:e,commitSha:r,commitMessage:s,commitAuthor:a,remoteUrl:o}}function wa(t){let e=D("git remote get-url origin",t);if(e)return e;let r=D("git remote",t);if(!r)return null;let s=r.split(`
2559
+ `)[0]?.trim();return s?D(`git remote get-url ${s}`,t):null}function X(t){let e=t.trim();return e=e.replace(/^[a-z+]+:\/\//,""),e=e.replace(/^[^@]+@/,""),e=e.replace(/:(?!\d)/,"/"),e=e.replace(/\.git$/,""),e=e.replace(/\/+$/,""),e=e.replace(/^[^@/]+@/,""),e.toLowerCase()}function Ar(t){let e=t.split("/").filter(Boolean);return e[e.length-1]??t}function Ye(t){try{let e=fs$1.readFileSync(path.join(t,"package.json"),"utf-8"),r=JSON.parse(e);return typeof r.name=="string"&&r.name.length>0?r.name:null}catch{return null}}function ee(t){let e=Ye(t);return e||`local/${path.basename(t)}`}var ka=new Set(["smoke","regression","nightly","ci"]);function ce(){let t=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(t&&ka.has(t))return t}var Ca=1048576,ue=[1e3,3e3,9e3],pe=3,Ze=90*1048576,Ra=new Set(["e2e","mobile","unit"]);function Xe(t){if(t&&t.length>0&&t.every(a=>a.testType==="api")){let a=new Map;for(let i of t){let l=i.apiProtocol??"rest";a.set(l,(a.get(l)??0)+1);}let n="rest",o=0;for(let[i,l]of a)l>o&&(o=l,n=i);return {testType:"api",apiProtocol:n,metadata:{testType:"api",primaryProtocol:n}}}let e=new Map;for(let a of t??[])Ra.has(a.testType)&&e.set(a.testType,(e.get(a.testType)??0)+1);let r=null,s=0;for(let[a,n]of e)n>s&&(s=n,r=a);return {testType:r??"e2e"}}function et(t,e,r,s,a,n){let o=n?.cloudPlatform?n.cloudPlatform:s?.provider&&s.provider!=="unknown"?s.provider:"local",i=ce(),l=Xe(a),d=l.testType==="api"?l:null,p=d&&a?a.map(m=>m.apiProtocol?m:{...m,apiProtocol:d.apiProtocol}):a;return {runId:t.testRunId,repoGitId:e,startedAt:t.startedAt,summary:t.summary,timeline:t.timeline,environment:o,...i?{runType:i}:{},...d?{testType:d.testType,apiProtocol:d.apiProtocol,metadata:d.metadata}:{testType:l.testType},...p&&p.length>0?{tests:p}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...s?.provider?{ciProvider:s.provider}:{},...s?.runUrl?{ciRunUrl:s.runUrl}:{},...n?.cloudPlatform?{cloudPlatform:n.cloudPlatform}:{},...n?.cloudBuildId?{cloudBuildId:n.cloudBuildId}:{},...n?.cloudSessionId?{cloudSessionId:n.cloudSessionId}:{}}}function Qe(t){return typeof t=="string"?Buffer.byteLength(t,"utf-8"):0}function tt(t){return Array.isArray(t)?t.map(e=>{let r=e.statusCode??e.responseStatusCode??null;return {...e.id!=null?{id:e.id}:{},...e.protocol!=null?{protocol:e.protocol}:{},method:e.method??null,url:e.url??null,statusCode:r,statusText:e.statusText??e.responseStatusText??null,ok:typeof r=="number"?r<400:e.ok??null,durationMs:e.durationMs??e.responseTimeMs??null,bytesIn:typeof e.bytesIn=="number"?e.bytesIn:Qe(e.responseBody),bytesOut:typeof e.bytesOut=="number"?e.bytesOut:Qe(e.requestBody),requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null,requestCookies:e.requestCookies??null,responseCookies:e.responseCookies??null}}):[]}function rt(t){return Array.isArray(t)?t.map(e=>{let r=e.responseStatusCode??e.statusCode??0,s=e.timestamp??null;return {method:e.method??"GET",url:e.url??"",status:r,statusCode:r,type:"xhr",size:Qe(e.responseBody),duration:e.responseTimeMs??e.durationMs??0,responseTimeMs:e.responseTimeMs??e.durationMs??0,requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null,timestamp:s,startedAt:s}}):[]}function st(t){if(!Array.isArray(t))return [];let e=r=>{if(r==null)return String(r);if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}};return t.map(r=>{let s=r.status==="failed"?"failed":"passed",a=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,n=r.kind??r.type??"assertion",o=s==="failed"?`expected ${e(r.expected)}, received ${e(r.actual)}`:r.expected!==void 0?`expected ${e(r.expected)}`:null;return {...r.callId!=null?{callId:r.callId}:{},kind:n,description:a??r.description??`${n} assertion`,status:s,detail:o}})}async function fe(t){return new Promise(e=>setTimeout(e,t))}function Aa(t){let e={};for(let[r,s]of Object.entries(t))s!=null&&(e[r]=s);return e}async function _r(t,e,r){for(let s=0;s<pe;s++)try{let a=await fetch(t,e);if(a.ok)return a;if(a.status===401&&r&&s===0){let n=await r();if(n){let o={...e,headers:{...e.headers,Authorization:`Bearer ${n}`}},i=await fetch(t,o);if(i.ok)return i}return null}if(a.status===429&&s<pe-1){let n=a.headers.get("Retry-After"),o=n?parseInt(n,10)*1e3:ue[s];!isNaN(o)&&o>0?await fe(o):await fe(ue[s]);continue}if(a.status>=500&&s<pe-1){await fe(ue[s]);continue}return a}catch{if(s<pe-1){await fe(ue[s]);continue}return null}return null}var Ia=util.promisify(zlib.gzip);function Ir(t,e){if(!Array.isArray(t.tests))return t;let r=t.tests.map(s=>{let{consoleLogs:a,networkRequests:n,apiCalls:o,...i}=s;return e?i:{...i,...o!==void 0?{apiCalls:o}:{}}});return {...t,tests:r}}async function at(t){let e={"Content-Type":"application/json"},r=JSON.stringify(t),s=t,a=Array.isArray(s?.tests)?s.tests.length:0;if(a>0&&Buffer.byteLength(r,"utf-8")>Ze){let n=Math.round(Ze/1048576);process.stderr.write(`[testrelic] WARNING: batch payload exceeds ${n}MB \u2014 dropping consoleLogs/networkRequests from ${a} test(s) to avoid HTTP 413. Console/network detail will be missing in the cloud.
2560
+ `),r=JSON.stringify(Ir(s,false)),Buffer.byteLength(r,"utf-8")>Ze&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${n}MB after dropping logs \u2014 also dropping apiCalls from ${a} test(s). API request/response detail will be missing in the cloud.
2561
+ `),r=JSON.stringify(Ir(s,true)));}return Buffer.byteLength(r,"utf-8")>Ca?(e["Content-Encoding"]="gzip",{body:await Ia(Buffer.from(r,"utf-8")),headers:e}):{body:r,headers:e}}async function Mr(t,e,r,s){let a=`${t}/runs`,{body:n,headers:o}=await at(r);o.Authorization=`Bearer ${e}`;let i=await _r(a,{method:"POST",headers:o,body:n},s);return i?.ok?{success:true,statusCode:i.status,error:null}:i?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:i?`Upload failed with status ${i.status}`:"Upload failed after retries",statusCode:i?.status??null,payload:r,targetEndpoint:a,method:"POST"}}async function Lr(t,e,r){let s=`${t}/runs/init`;try{let a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(Aa(r))});return a.ok?{runId:(await a.json()).runId}:null}catch{return null}}function Er(t,e,r,s){let a=`${t}/runs/${r}/tests`;fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(s)}).catch(()=>{});}async function Pr(t,e,r,s){let a=`${t}/runs/${r}/finalize`;return (await _r(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(s)}))?.ok??false}function nt(t,e,r,s){let a=`${t}/runs/${r}/finalize`,n=new Date,o={finishedAt:n.toISOString(),duration:n.getTime()-new Date(s).getTime(),summary:{}};fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}).catch(()=>{});}var Na="1.0.0",Nr=10;function te(t,e,r,s,a,n,o,i){try{fs$1.mkdirSync(t,{recursive:!0});let l=Date.now(),d=`${l}-${e}-${r}.json`,p=path.join(t,d),f={version:Na,queuedAt:new Date(l).toISOString(),reason:s,retryCount:0,targetEndpoint:a,method:n,payload:o,headers:i},m=p+".tmp";fs$1.writeFileSync(m,JSON.stringify(f,null,2),"utf-8"),fs$1.renameSync(m,p);}catch(l){l.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
2560
2562
  `):process.stderr.write(`\u26A0 TestRelic: Unable to queue upload data.
2561
- `);}}async function Cr(t,e,r){let a;try{a=fs$1.readdirSync(t).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+=kr)n.push(a.slice(s,s+kr));for(let s of n)for(let o of s){let i=path.join(t,o);try{if(!fs$1.statSync(i).isFile())continue;let d=fs$1.readFileSync(i,"utf-8"),p=JSON.parse(d);if(!core.isValidQueueEntry(p)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${o}
2562
- `),fs$1.unlinkSync(i);continue}let f=p,h=JSON.stringify(f.payload),c={...f.headers,Authorization:`Bearer ${r}`},u=h;if(Buffer.byteLength(h,"utf-8")>wn&&(u=zlib.gzipSync(Buffer.from(h,"utf-8")),c["Content-Encoding"]="gzip"),(await fetch(f.targetEndpoint,{method:f.method,headers:c,body:u})).ok)fs$1.unlinkSync(i);else return}catch{return}}}function Rr(t,e){try{let r=fs$1.readdirSync(t).filter(n=>n.endsWith(".json")&&!n.endsWith(".tmp")),a=Date.now();for(let n of r){let s=path.join(t,n);try{let o=fs$1.readFileSync(s,"utf-8"),l=JSON.parse(o).queuedAt;if(typeof l=="string"){let d=new Date(l).getTime();a-d>e&&fs$1.unlinkSync(s);}}catch{try{fs$1.unlinkSync(s);}catch{}}}}catch{}}var _n=3e5,Ln=864e5,Mn=6e4,Ar=3e4,Qe="https://platform.testrelic.ai/settings/api-keys",ce=class{constructor(e){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=e,this.authState={mode:"pending",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null};}async initialize(){if(!this.config||!this.config.apiKey){this.setLocalMode("no_api_key"),process.stderr.write(`\u2139 TestRelic: No API key configured. Running in local mode.
2563
- `);return}try{if(mr(this.config.endpoint),this.gitMetadata=xr(),!await Ge(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.
2564
- `);return}let r=await We(this.config.endpoint,this.config.apiKey,this.config.timeout);if(Ke(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})
2565
- `),await this.resolveRepoId(),this.config.queueDirectory&&(Rr(this.config.queueDirectory,this.config.queueMaxAge),this.startBackgroundFlush()),this.startHealthCheck();}catch(e){this.setLocalMode("unexpected_error"),process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. Running in local mode. ${e instanceof Error?e.message:String(e)}
2566
- `);}}getMode(){return this.authState.mode}isCloudMode(){return this.authState.mode==="cloud"}isLocalMode(){return this.authState.mode==="local"}getAccessToken(){return this.authState.accessToken}getRepoId(){return this.repoId}getGitMetadata(){return this.gitMetadata}getConfig(){return this.config}getFailureReason(){return this.failureReason}getEndpoint(){return this.config?.endpoint??"https://platform.testrelic.ai/api/v1"}async ensureValidToken(){if(!this.isCloudMode()||!this.authState.accessToken)return false;let e=this.authState.expiresAt??0;if(Date.now()+_n<e)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await yr(this.config.endpoint,this.authState.refreshToken,this.config.timeout);return r?(this.authState.accessToken=r.accessToken,this.authState.refreshToken=r.refreshToken,this.authState.expiresAt=Date.now()+r.expiresIn*1e3,!0):(this.switchToLocalMode("token_refresh_failed"),!1)}catch{return this.switchToLocalMode("token_refresh_error"),false}}switchToLocalMode(e){this.authState.mode!=="local"&&(this.authState.mode="local",this.failureReason=e,process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${e}).
2567
- `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,new Promise(e=>setTimeout(e,Ar))]);}catch{}this.flushPromise=null;}this.authState={mode:"local",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null},this.repoId=null,this.gitMetadata=null;}setLocalMode(e){this.authState.mode="local",this.failureReason=e;}handleAuthError(e,r){switch(e){case "invalid_key":this.setLocalMode("invalid_api_key"),process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
2568
- \u2192 Manage keys: ${Qe}
2563
+ `);}}async function Br(t,e,r){let s;try{s=fs$1.readdirSync(t).filter(n=>n.endsWith(".json")&&!n.endsWith(".tmp")).sort();}catch{return}if(s.length===0)return;let a=[];for(let n=0;n<s.length;n+=Nr)a.push(s.slice(n,n+Nr));for(let n of a)for(let o of n){let i=path.join(t,o);try{if(!fs$1.statSync(i).isFile())continue;let d=fs$1.readFileSync(i,"utf-8"),p=JSON.parse(d);if(!core.isValidQueueEntry(p)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${o}
2564
+ `),fs$1.unlinkSync(i);continue}let f=p,{body:m,headers:c}=await at(f.payload),u={...f.headers,...c,Authorization:`Bearer ${r}`};if((await fetch(f.targetEndpoint,{method:f.method,headers:u,body:m})).ok)fs$1.unlinkSync(i);else return}catch{return}}}function Or(t,e){try{let r=fs$1.readdirSync(t).filter(a=>a.endsWith(".json")&&!a.endsWith(".tmp")),s=Date.now();for(let a of r){let n=path.join(t,a);try{let o=fs$1.readFileSync(n,"utf-8"),l=JSON.parse(o).queuedAt;if(typeof l=="string"){let d=new Date(l).getTime();s-d>e&&fs$1.unlinkSync(n);}}catch{try{fs$1.unlinkSync(n);}catch{}}}}catch{}}var Ua=3e5,za=864e5,$a=6e4,qr=3e4,lt="https://platform.testrelic.ai/settings/api-keys",he=class{constructor(e){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=e,this.authState={mode:"pending",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null};}async initialize(){if(!this.config||!this.config.apiKey){this.setLocalMode("no_api_key"),process.stderr.write(`\u2139 TestRelic: No API key configured. Running in local mode.
2565
+ `);return}try{if(kr(this.config.endpoint),this.gitMetadata=Rr(),!await We(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.
2566
+ `);return}let r=await Ke(this.config.endpoint,this.config.apiKey,this.config.timeout);if(Je(r)){this.handleAuthError(r.code,r.statusCode);return}let s=r;this.authState={mode:"cloud",accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:Date.now()+s.expiresIn*1e3,orgId:s.orgId,orgName:s.orgName,userId:s.userId,userName:s.userName},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${s.orgName} / ${s.userName})
2567
+ `),await this.resolveRepoId(),this.config.queueDirectory&&(Or(this.config.queueDirectory,this.config.queueMaxAge),this.startBackgroundFlush()),this.startHealthCheck();}catch(e){this.setLocalMode("unexpected_error"),process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. Running in local mode. ${e instanceof Error?e.message:String(e)}
2568
+ `);}}getMode(){return this.authState.mode}isCloudMode(){return this.authState.mode==="cloud"}isLocalMode(){return this.authState.mode==="local"}getAccessToken(){return this.authState.accessToken}getRepoId(){return this.repoId}getGitMetadata(){return this.gitMetadata}getConfig(){return this.config}getFailureReason(){return this.failureReason}getEndpoint(){return this.config?.endpoint??"https://platform.testrelic.ai/api/v1"}async ensureValidToken(){if(!this.isCloudMode()||!this.authState.accessToken)return false;let e=this.authState.expiresAt??0;if(Date.now()+Ua<e)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await Sr(this.config.endpoint,this.authState.refreshToken,this.config.timeout);return r?(this.authState.accessToken=r.accessToken,this.authState.refreshToken=r.refreshToken,this.authState.expiresAt=Date.now()+r.expiresIn*1e3,!0):(this.switchToLocalMode("token_refresh_failed"),!1)}catch{return this.switchToLocalMode("token_refresh_error"),false}}switchToLocalMode(e){this.authState.mode!=="local"&&(this.authState.mode="local",this.failureReason=e,process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${e}).
2569
+ `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,new Promise(e=>setTimeout(e,qr))]);}catch{}this.flushPromise=null;}this.authState={mode:"local",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null},this.repoId=null,this.gitMetadata=null;}setLocalMode(e){this.authState.mode="local",this.failureReason=e;}handleAuthError(e,r){switch(e){case "invalid_key":this.setLocalMode("invalid_api_key"),process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
2570
+ \u2192 Manage keys: ${lt}
2569
2571
  `);break;case "expired_key":this.setLocalMode("expired_api_key"),process.stderr.write(`\u26A0 TestRelic: API key has expired. Running in local mode.
2570
- \u2192 Generate a new key: ${Qe}
2572
+ \u2192 Generate a new key: ${lt}
2571
2573
  `);break;case "validation_error":this.setLocalMode("validation_error"),process.stderr.write(`\u26A0 TestRelic: API key format invalid. Running in local mode.
2572
- \u2192 Manage keys: ${Qe}
2574
+ \u2192 Manage keys: ${lt}
2573
2575
  `);break;case "rate_limited":this.setLocalMode("rate_limited"),process.stderr.write(`\u26A0 TestRelic: Rate limited during authentication. Running in local mode.
2574
2576
  `);break;case "timeout":this.setLocalMode("auth_timeout"),process.stderr.write(`\u26A0 TestRelic: Authentication timed out. Running in local mode.
2575
2577
  `);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
2576
- `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?Z(this.gitMetadata.remoteUrl):null,r=e?wr(e):this.config.projectName??Q(process.cwd()),a=e??this.config.projectName??Q(process.cwd()),n=this.readRepoCache(a);if(n){this.repoId=n.repoId;return}try{let s=await br(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{}!e&&!this.config.projectName&&!Je(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
2577
- `);}readRepoCache(e){if(!this.config)return null;let r=path.join(this.config.queueDirectory,"..","cache","repo.json");try{if(!fs$1.existsSync(r))return null;let a=fs$1.readFileSync(r,"utf-8"),n=JSON.parse(a);if(n.gitId!==e||Date.now()-n.resolvedAt>Ln)return null;let s=this.hashApiKey();return s&&n.apiKeyHash!==s?null:n}catch{return null}}writeRepoCache(e,r,a){if(!this.config)return;let n=path.join(this.config.queueDirectory,"..","cache"),s=path.join(n,"repo.json");try{fs$1.mkdirSync(n,{recursive:!0});let o={repoId:r,gitId:e,displayName:a,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=s+".tmp";fs$1.writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),fs$1.renameSync(i,s);}catch{}}hashApiKey(){return this.config?.apiKey?crypto.createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let e=this.authState.accessToken,r=this.config.queueDirectory,a=this.config.endpoint;this.flushPromise=Promise.race([Cr(r,a,e),new Promise(n=>setTimeout(n,Ar))]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let e=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await Ge(e))return;if(this.config?.apiKey){let a=await We(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!Ke(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.
2578
- `),this.startBackgroundFlush();}}}catch{}},Mn);}};var En=new Set(["smoke","regression","nightly","ci"]);function ue(){let t=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(t&&En.has(t))return t}var Nn=1048576,pe=[1e3,3e3,9e3],fe=3,Fn=40*1048576,Dn=new Set(["e2e","mobile","unit"]);function et(t){if(t&&t.length>0&&t.every(n=>n.testType==="api")){let n=new Map;for(let i of t){let l=i.apiProtocol??"rest";n.set(l,(n.get(l)??0)+1);}let s="rest",o=0;for(let[i,l]of n)l>o&&(o=l,s=i);return {testType:"api",apiProtocol:s,metadata:{testType:"api",primaryProtocol:s}}}let e=new Map;for(let n of t??[])Dn.has(n.testType)&&e.set(n.testType,(e.get(n.testType)??0)+1);let r=null,a=0;for(let[n,s]of e)s>a&&(a=s,r=n);return {testType:r??"e2e"}}function tt(t,e,r,a,n,s){let o=s?.cloudPlatform?s.cloudPlatform:a?.provider&&a.provider!=="unknown"?a.provider:"local",i=ue(),l=et(n),d=l.testType==="api"?l:null,p=d&&n?n.map(h=>h.apiProtocol?h:{...h,apiProtocol:d.apiProtocol}):n,f={runId:t.testRunId,repoGitId:e,startedAt:t.startedAt,summary:t.summary,timeline:t.timeline,environment:o,...i?{runType:i}:{},...d?{testType:d.testType,apiProtocol:d.apiProtocol,metadata:d.metadata}:{testType:l.testType},...p&&p.length>0?{tests:p}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...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}:{}};if(f.tests&&f.tests.length>0){let h=JSON.stringify(f);if(Buffer.byteLength(h,"utf-8")>Fn){let c=f.tests.map(({consoleLogs:u,networkRequests:g,apiCalls:m,...b})=>b);return {...f,tests:c}}}return f}function Xe(t){return typeof t=="string"?Buffer.byteLength(t,"utf-8"):0}function rt(t){return Array.isArray(t)?t.map(e=>{let r=e.statusCode??e.responseStatusCode??null;return {...e.id!=null?{id:e.id}:{},...e.protocol!=null?{protocol:e.protocol}:{},method:e.method??null,url:e.url??null,statusCode:r,statusText:e.statusText??e.responseStatusText??null,ok:typeof r=="number"?r<400:e.ok??null,durationMs:e.durationMs??e.responseTimeMs??null,bytesIn:typeof e.bytesIn=="number"?e.bytesIn:Xe(e.responseBody),bytesOut:typeof e.bytesOut=="number"?e.bytesOut:Xe(e.requestBody),requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null,requestCookies:e.requestCookies??null,responseCookies:e.responseCookies??null}}):[]}function at(t){return Array.isArray(t)?t.map(e=>{let r=e.responseStatusCode??e.statusCode??0,a=e.timestamp??null;return {method:e.method??"GET",url:e.url??"",status:r,statusCode:r,type:"xhr",size:Xe(e.responseBody),duration:e.responseTimeMs??e.durationMs??0,responseTimeMs:e.responseTimeMs??e.durationMs??0,requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null,timestamp:a,startedAt:a}}):[]}function nt(t){if(!Array.isArray(t))return [];let e=r=>{if(r==null)return String(r);if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}};return t.map(r=>{let a=r.status==="failed"?"failed":"passed",n=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,s=r.kind??r.type??"assertion",o=a==="failed"?`expected ${e(r.expected)}, received ${e(r.actual)}`:r.expected!==void 0?`expected ${e(r.expected)}`:null;return {...r.callId!=null?{callId:r.callId}:{},kind:s,description:n??r.description??`${s} assertion`,status:a,detail:o}})}async function ge(t){return new Promise(e=>setTimeout(e,t))}function Bn(t){let e={};for(let[r,a]of Object.entries(t))a!=null&&(e[r]=a);return e}async function Ir(t,e,r){for(let a=0;a<fe;a++)try{let n=await fetch(t,e);if(n.ok)return n;if(n.status===401&&r&&a===0){let s=await r();if(s){let o={...e,headers:{...e.headers,Authorization:`Bearer ${s}`}},i=await fetch(t,o);if(i.ok)return i}return null}if(n.status===429&&a<fe-1){let s=n.headers.get("Retry-After"),o=s?parseInt(s,10)*1e3:pe[a];!isNaN(o)&&o>0?await ge(o):await ge(pe[a]);continue}if(n.status>=500&&a<fe-1){await ge(pe[a]);continue}return n}catch{if(a<fe-1){await ge(pe[a]);continue}return null}return null}function On(t){let e=JSON.stringify(t),r={"Content-Type":"application/json"};if(Buffer.byteLength(e,"utf-8")>Nn){let a=zlib.gzipSync(Buffer.from(e,"utf-8"));return r["Content-Encoding"]="gzip",{body:a,headers:r}}return {body:e,headers:r}}async function _r(t,e,r,a){let n=`${t}/runs`,{body:s,headers:o}=On(r);o.Authorization=`Bearer ${e}`;let i=await Ir(n,{method:"POST",headers:o,body:s},a);return i?.ok?{success:true,statusCode:i.status,error:null}:i?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:i?`Upload failed with status ${i.status}`:"Upload failed after retries",statusCode:i?.status??null,payload:r,targetEndpoint:n,method:"POST"}}async function Lr(t,e,r){let a=`${t}/runs/init`;try{let n=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(Bn(r))});return n.ok?{runId:(await n.json()).runId}:null}catch{return null}}function Mr(t,e,r,a){let n=`${t}/runs/${r}/tests`;fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(a)}).catch(()=>{});}async function Er(t,e,r,a){let n=`${t}/runs/${r}/finalize`;return (await Ir(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(a)}))?.ok??false}function st(t,e,r,a){let n=`${t}/runs/${r}/finalize`,s=new Date,o={finishedAt:s.toISOString(),duration:s.getTime()-new Date(a).getTime(),summary:{}};fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}).catch(()=>{});}function Pr(t,e,r,a){let n=[],s=[],o=null,i=0,l=null,d=0,p=null,f=0,h=t.filter(g=>g.name===core.ATTACHMENT_NAME&&g.body),c=false;if(h.length>0)for(let g of h)try{let m=JSON.parse(g.body.toString());if(core.isTestRelicFilePayload(m)){n=n.concat(m.navigations),s=s.concat(m.apiAssertions),m.networkRequestsFile&&(o=m.networkRequestsFile,i+=m.networkRequestsCount),m.consoleLogsFile&&(l=m.consoleLogsFile,d+=m.consoleLogsCount),m.apiCallsFile&&(p=m.apiCallsFile,f+=m.apiCallsCount),c=!0;continue}if(core.isTestRelicDataPayload(m)){n=n.concat(m.navigations),Array.isArray(m.apiAssertions)&&(s=s.concat(m.apiAssertions)),i+=m.networkRequests?.length??0,f+=m.apiCalls?.length??0;let b=m.consoleLogs;Array.isArray(b)&&(d+=b.length),c=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
2579
- `);}return c||(n=e.filter(g=>g.type==="lambdatest-navigation"&&g.description).map(g=>{try{return JSON.parse(g.description)}catch{return null}}).filter(g=>g!==null)),n.length===0&&i===0&&f===0&&!a&&!c&&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.
2580
- `),{navigations:n,apiAssertions:s,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:l,consoleLogsCount:d,apiCallsFile:p,apiCallsCount:f}}function he(t=process.env){let e=zn(t.TESTRELIC_CLOUD_PLATFORM);if(e)return {cloudPlatform:e,cloudBuildId:t.TESTRELIC_CLOUD_BUILD_ID||void 0,cloudSessionId:t.TESTRELIC_CLOUD_SESSION_ID||void 0};if(t.BROWSERSTACK_USERNAME||t.BROWSERSTACK_ACCESS_KEY)return {cloudPlatform:"browserstack",cloudBuildId:t.BROWSERSTACK_BUILD_NAME||t.BROWSERSTACK_BUILD_ID||void 0,cloudSessionId:t.BROWSERSTACK_SESSION_ID||void 0};if(t.LT_USERNAME||t.LAMBDATEST_USERNAME||t.LT_ACCESS_KEY||t.LAMBDATEST_ACCESS_KEY)return {cloudPlatform:"lambdatest",cloudBuildId:t.LT_BUILD||t.LAMBDATEST_BUILD||void 0,cloudSessionId:t.LT_SESSION_ID||t.LAMBDATEST_SESSION_ID||void 0};let r=t.PLAYWRIGHT_WS_ENDPOINT;if(r){if(/cdp\.lambdatest\.com/i.test(r))return {cloudPlatform:"lambdatest"};if(/cdp\.browserstack\.com/i.test(r))return {cloudPlatform:"browserstack"}}return {}}function zn(t){if(!t)return;let e=t.toLowerCase().trim();if(e==="browserstack"||e==="bs")return "browserstack";if(e==="lambdatest"||e==="lt")return "lambdatest"}var Wn=5,me=[1e3,3e3,9e3],z=3,Kn={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip"},it=0,ot=[];async function Jn(){it>=Wn&&await new Promise(t=>ot.push(t)),it++;}function Yn(){it--,ot.length>0&&ot.shift()();}async function ve(t){return new Promise(e=>setTimeout(e,t))}function Zn(t){let e=t.substring(t.lastIndexOf(".")).toLowerCase();return Kn[e]??"application/octet-stream"}function Qn(t){try{return fs$1.statSync(t).size}catch{return 0}}async function Xn(t,e,r,a,n){let s=`${t}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:path.basename(r.filePath),contentType:n,type:r.type,sizeBytes:a});for(let i=0;i<z;i++)try{let l=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:o});if(l.ok)return await l.json();if(l.status>=500&&i<z-1){await ve(me[i]);continue}return null}catch{if(i<z-1){await ve(me[i]);continue}return null}return null}async function es(t,e,r,a){for(let n=0;n<z;n++)try{let s=fs$1.createReadStream(e),o=stream.Readable.toWeb(s),i=await fetch(t,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(a)},body:o,duplex:"half"});if(i.ok)return !0;if(i.status>=500&&n<z-1){await ve(me[n]);continue}return !1}catch{if(n<z-1){await ve(me[n]);continue}return false}return false}async function ts(t,e,r){let a=`${t}/artifacts/confirm`;try{return (await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({artifactId:r})})).ok}catch{return false}}async function rs(t,e,r,a){let n=Qn(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=Zn(r.filePath);await Jn();try{let o=await Xn(t,e,r,n,s);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await es(o.uploadUrl,r.filePath,s,n))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let l=await ts(t,e,o.artifactId);return {success:l,storageKey:o.storageKey,artifactId:o.artifactId,error:l?null:"confirm_failed"}}finally{Yn();}}async function Nr(t,e,r,a){let n=new Map,s=r.map(async o=>{let i=await rs(t,e,o,a);n.set(o.filePath,i);});return await Promise.allSettled(s),n}function lt(t){let r=t.getGitMetadata()?.remoteUrl;return r?Z(r):t.getConfig()?.projectName??Q(process.cwd())}async function Dr(t,e,r,a,n){if(!t.isCloudMode()||e!=="realtime"&&e!=="both"||!await t.ensureValidToken())return null;let o=t.getGitMetadata(),i=P(),l=he(),d=ue();return (await Lr(t.getEndpoint(),t.getAccessToken(),{runId:r,repoGitId:lt(t),branch:o?.branch??null,commit:o?.commitSha??null,commitMessage:o?.commitMessage??null,commitAuthor:o?.commitAuthor??null,startedAt:a,totalTests:null,ciProvider:i?.provider??null,ciRunUrl:i?.runUrl??null,environment:n??l.cloudPlatform??null,cloudPlatform:l.cloudPlatform??null,cloudBuildId:l.cloudBuildId??null,cloudSessionId:l.cloudSessionId??null,...d?{runType:d}:{},testType:"e2e"}))?.runId??null}var as=true,ns=50;async function ss(t,e,r,a){let n=new Map;if(!(e?.uploadArtifacts??as)||!await t.ensureValidToken())return n;let i=[],l=new Map;for(let c of a){if(c.artifacts.screenshot){let u=path.join(c.outputDir,c.artifacts.screenshot);i.push({filePath:u,runId:r,testId:c.testId,type:"screenshot"}),l.set(u,{testId:c.testId,field:"screenshot"});}if(c.artifacts.video){let u=path.join(c.outputDir,c.artifacts.video);i.push({filePath:u,runId:r,testId:c.testId,type:"video"}),l.set(u,{testId:c.testId,field:"video"});}}if(i.length===0)return n;let d=e?.artifactMaxSizeMb??ns,p=await Nr(t.getEndpoint(),t.getAccessToken(),i,d),f=new Map;for(let[c,u]of p){if(!u.success||!u.storageKey)continue;let g=l.get(c);if(!g)continue;let m=f.get(g.testId)??{};g.field==="screenshot"&&(m.screenshotKey=u.storageKey),g.field==="video"&&(m.videoKey=u.storageKey),f.set(g.testId,m);}for(let c of a){let u=f.get(c.testId);n.set(c.testId,{...c.artifacts,...u?.screenshotKey?{screenshotKey:u.screenshotKey}:{},...u?.videoKey?{videoKey:u.videoKey}:{}});}let h=Array.from(p.values()).filter(c=>c.success).length;return h>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${h} artifact(s) to cloud storage.
2581
- `),n}async function dt(t,e,r,a,n,s,o,i,l,d,p){try{if(t.isCloudMode()&&n&&(r==="realtime"||r==="both")){let h=await t.ensureValidToken(),c=t.getGitMetadata(),u=et(p),g={finishedAt:o,duration:i,summary:l,...c?.commitMessage?{commitMessage:c.commitMessage}:{},testType:u.testType,...u.testType==="api"?{apiProtocol:u.apiProtocol,metadata:u.metadata}:{}};if(h){if(!await Er(t.getEndpoint(),t.getAccessToken(),n,g)){let b=e?.queueDirectory??".testrelic/queue";X(b,a,"finalize","finalize_failed_after_retries",`${t.getEndpoint()}/runs/${n}/finalize`,"POST",g,{"Content-Type":"application/json"});}}else {let m=e?.queueDirectory??".testrelic/queue";X(m,a,"finalize",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs/${n}/finalize`,"POST",g,{"Content-Type":"application/json"});}}let f=new Map;if(t.isCloudMode()&&d&&d.length>0&&(f=await ss(t,e,a,d)),t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await t.ensureValidToken()){let c=t.getGitMetadata(),u=P(),g=lt(t),m=is(s,f),b=tt(m,g,c,u,p,he()),S=await _r(t.getEndpoint(),t.getAccessToken(),b,async()=>await t.ensureValidToken()?t.getAccessToken():null);if(!S.success){let y=S,x=e?.queueDirectory??".testrelic/queue";X(x,a,"batch",y.reason,y.targetEndpoint,y.method,y.payload,{"Content-Type":"application/json"});}}else {let c=e?.queueDirectory??".testrelic/queue",u=t.getGitMetadata(),g=P(),m=lt(t),b=tt(s,m,u,g,void 0,he());X(c,a,"batch",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs`,"POST",b,{"Content-Type":"application/json"});}await t.dispose();}catch{try{await t.dispose();}catch{}}}function is(t,e){if(e.size===0)return t;let r=t.timeline.map(a=>{let n=a.testId;if(!n)return a;let s=e.get(n);return s?{...a,...s.screenshotKey?{screenshotKey:s.screenshotKey}:{},...s.videoKey?{videoKey:s.videoKey}:{}}:a});return {...t,timeline:r}}function q(t){try{return fs$1.readFileSync(t,"utf-8").split(`
2582
- `).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function ut(t){switch(t){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function fs(t,e,r){let a=`${t}::${e}::${r}`;return crypto.createHash("sha256").update(a).digest("hex").substring(0,16)}function gs(t){return t.length<=3?"":t[t.length-2]}function hs(t){let e=t.findIndex(r=>r.status==="passed");return e>0?`passed on retry ${e}`:null}function ms(t){return process.env.BROWSERSTACK_USERNAME?"BrowserStack":t?{"github-actions":"GitHub Actions","gitlab-ci":"GitLab CI",jenkins:"Jenkins",circleci:"CircleCI","bitbucket-pipelines":"Bitbucket Pipelines"}[t.provider]??"CI":"Local"}function vs(){let t=os.platform();return t==="win32"?"Windows":t==="darwin"?"macOS":"Linux"}function ys(t){let e=t.parent?.project?.()?.use;if(!e)return;let{browserName:r,channel:a}=e;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=e.defaultBrowserType;if(n){let s=n.toLowerCase();return s==="chromium"?"Chromium":s==="firefox"?"Firefox":s==="webkit"?"WebKit":n}}function bs(t,e,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 l of s)if(t.some(d=>d===`@${l}`||d===l))return l;let o=e.replace(/\\/g,"/"),i=["e2e","api","unit"];for(let l of i)if(o.includes(`/${l}/`))return l;return n}var xs="__testrelic_api_config";function ws(t){return JSON.stringify(t,(e,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var ye=class{constructor(e){this.rootDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.navigationsCaptured=false;this.testCount=0;this.cloudClient=null;this.cloudRunId=null;this.runTimestamp="";this.pendingArtifactEntries=[];this.detectedOs="";this.detectedSource="";this.cloudTestsBuffer=[];this.activeReportMode="embedded";this.streamingWriter=null;this.testIndex=[];this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0};this.config=_t(e),this.apiConfig=It(e);}async onBegin(e,r){try{if(this.rootDir=e.rootDir,this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??crypto.randomUUID(),this.config.reportMode==="auto"){let s=r.allTests().length;this.activeReportMode=s>=this.config.streamingThreshold?"streaming":"embedded";}else this.activeReportMode=this.config.reportMode;let a=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${a} tests)
2583
- `),this.activeReportMode==="streaming"){let s=path.dirname(this.config.outputPath);this.streamingWriter=new G(s);let o=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let i={testRunId:this.testRunId??"",startedAt:this.startedAt,completedAt:new Date().toISOString(),totalDuration:Date.now()-new Date(this.startedAt).getTime(),...this.summaryCounters,metadata:null,reportMode:"streaming",files:[],enrichedSummary:null,validation:null,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(i);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let i=this.cloudClient.getAccessToken();i&&st(this.cloudClient.getEndpoint(),i,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",o),process.on("SIGINT",o);}if(this.config.includeArtifacts){let s=path.dirname(this.config.outputPath);this.runTimestamp=nr(path.join(s,"artifacts"));try{dr(path.join(s,"artifacts"));}catch{}}let n=P();this.detectedOs=vs(),this.detectedSource=ms(n);try{this.cloudClient=new ce(this.config.cloud),await this.cloudClient.initialize(),this.cloudRunId=await Dr(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource);}catch{this.cloudClient?.switchToLocalMode("init_error");}if(this.activeReportMode!=="streaming"){let s=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let o=this.cloudClient.getAccessToken();o&&st(this.cloudClient.getEndpoint(),o,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",s),process.on("SIGINT",s);}}catch{}}onTestBegin(e,r){try{e.annotations.push({type:xs,description:ws(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let a=r,n=e.outcome(),s;n==="flaky"?s="flaky":n==="skipped"?s="skipped":s=ut(a.status);let o=a.startTime.toISOString(),i=new Date(a.startTime.getTime()+a.duration).toISOString(),l=e.tags?[...e.tags]:e.annotations.filter(R=>R.type==="tag").map(R=>R.description??""),d=Pr(a.attachments,e.annotations,e.title,s==="skipped");(d.navigations.length>0||d.networkRequestsCount>0||d.apiCallsCount>0)&&(this.fixtureDataReceived=!0),d.navigations.length>0&&(this.navigationsCaptured=!0),!this.config.captureNavigation&&d.navigations.length>0&&(d={...d,navigations:[]});let p=null;if(s==="failed"||s==="flaky"){let C=(s==="flaky"?e.results.find(B=>B.status!=="passed")?.errors??[]:a.errors)[0];if(C){let B=Mt(this.config.redactPatterns),$=C.location?.line??null,j=null;this.config.includeCodeSnippets&&$!==null&&C.location?.file&&(j=Lt(C.location.file,$,this.config.codeContextLines),j&&(j=B(j))),p={message:B(C.message??"Unknown error"),line:$,code:j,stack:this.config.includeStackTrace&&C.stack?B(C.stack):null};}}let f=e.titlePath().filter(Boolean),h=path.relative(this.rootDir||".",e.location.file),c=gs(f),u=f.join(" > "),g=h,m=fs(g,c,u),b=bs(l,g,e),S=b!=="mobile"&&d.apiCallsCount>0?"api":b,y=n==="flaky",x=hs(e.results),T=ut(e.expectedStatus),v=ut(a.status),k=null;if(this.config.includeArtifacts&&s!=="skipped"&&a.attachments){let R=path.dirname(this.config.outputPath),C=f[f.length-1]??e.title;k=sr(a.attachments,C,a.retry,R,this.runTimestamp||void 0);}let A=this.config.includeActionSteps&&a.steps?gr(a.steps,a.startTime):null,H=ys(e),M={titlePath:f,title:u,status:s,duration:a.duration,startedAt:o,completedAt:i,retryCount:e.results.length-1,retry:a.retry,tags:l,failure:p,specFile:h,navigations:d.navigations,testId:m,filePath:g,suiteName:c,testType:S,isFlaky:y,retryStatus:x,expectedStatus:T,actualStatus:v,artifacts:k,apiAssertions:d.apiAssertions,actions:A,networkRequestsFile:d.networkRequestsFile,networkRequestsCount:d.networkRequestsCount,consoleLogsFile:d.consoleLogsFile,consoleLogsCount:d.consoleLogsCount,apiCallsFile:d.apiCallsFile,apiCallsCount:d.apiCallsCount,browser:H,os:this.detectedOs||void 0,source:this.detectedSource||void 0},pt=d.consoleLogsFile&&d.consoleLogsCount>0?q(d.consoleLogsFile):void 0,be=d.networkRequestsFile&&d.networkRequestsCount>0?q(d.networkRequestsFile):void 0,ee=d.apiCallsFile&&d.apiCallsCount>0?q(d.apiCallsFile):void 0,ft=ee?rt(ee):void 0,gt=!be&&ee?at(ee):void 0,ht=d.apiAssertions&&d.apiAssertions.length>0?nt(d.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:m,title:u,status:s,duration:a.duration,suiteName:c,filePath:g,testType:S,isFlaky:y,startedAt:o,completedAt:i,tags:l,failure:p,retry:a.retry,retryCount:e.results.length-1,retryStatus:x,browser:H,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...A&&A.length>0?{actions:A}:{},...d.navigations&&d.navigations.length>0?{navigations:d.navigations}:{},...pt?{consoleLogs:pt}:{},...be?{networkRequests:be}:gt?{networkRequests:gt}:{},...ft?{apiCalls:ft}:{},...ht?{protocolAssertions:ht}:{}});try{let R=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(R==="realtime"||R==="both")){let C=this.cloudClient.getAccessToken();C&&Mr(this.cloudClient.getEndpoint(),C,this.cloudRunId,this.buildCloudTestPayload(M));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let R=xe(g,f,e.id??"",a.retry),C=a.retry===e.results.length-1,B={id:R,navigations:d.navigations,apiAssertions:d.apiAssertions,actions:A??[],artifacts:k,failureDiagnostic:p,hasNetworkFile:d.networkRequestsFile!==null,networkRequestsCount:d.networkRequestsCount,hasConsoleFile:d.consoleLogsFile!==null,consoleLogsCount:d.consoleLogsCount,hasApiCallsFile:d.apiCallsFile!==null,apiCallsCount:d.apiCallsCount,startedAt:o};this.streamingWriter.writeTestDetail(R,B,{networkRequestsFile:d.networkRequestsFile,consoleLogsFile:d.consoleLogsFile,apiCallsFile:d.apiCallsFile});let $={id:R,title:f[f.length-1]??e.title,titlePath:f,filePath:g,status:s,duration:a.duration,project:f[1]??"",retryIndex:a.retry,tags:l,hasNetworkData:d.networkRequestsCount>0,hasConsoleData:d.consoleLogsCount>0,hasArtifacts:k!==null,hasActionSteps:(A?.length??0)>0,errorMessage:p?.message?.split(`
2584
- `)[0]??null,networkCount:d.networkRequestsCount,consoleCount:d.consoleLogsCount,actionCount:A?.length??0,isRetry:!C};if(this.testIndex.push($),C)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.summaryCounters.totalApiCalls+=d.apiCallsCount,this.summaryCounters.totalAssertions+=d.apiAssertions.length,this.summaryCounters.totalNavigations+=d.navigations.length,this.summaryCounters.totalNetworkRequests+=d.networkRequestsCount,this.summaryCounters.totalConsoleLogs+=d.consoleLogsCount,this.summaryCounters.totalActionSteps+=A?.length??0,k&&this.pendingArtifactEntries.push({testId:m,artifacts:k,outputDir:path.dirname(this.config.outputPath)}),M.actions=null,M.apiAssertions=null,M.navigations=[],M.artifacts=null,M.failure=null,M.networkRequestsFile=null,M.consoleLogsFile=null,M.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(M),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(e){try{let r=new Date().toISOString(),a=new Date(this.startedAt).getTime(),s=new Date(r).getTime()-a,o=this.activeReportMode==="streaming"?this.testIndex.some(l=>l.status!=="skipped"):this.collectedTests.some(l=>l.status!=="skipped");!this.fixtureDataReceived&&o&&process.stderr.write(`
2578
+ `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?X(this.gitMetadata.remoteUrl):null,r=e?Ar(e):this.config.projectName??ee(process.cwd()),s=e??this.config.projectName??ee(process.cwd()),a=this.readRepoCache(s);if(a){this.repoId=a.repoId;return}try{let n=await Cr(this.config.endpoint,this.authState.accessToken,s,r,this.config.timeout,this.gitMetadata?.branch);n&&(this.repoId=n.repoId,this.writeRepoCache(s,n.repoId,n.displayName));}catch{}!e&&!this.config.projectName&&!Ye(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
2579
+ `);}readRepoCache(e){if(!this.config)return null;let r=path.join(this.config.queueDirectory,"..","cache","repo.json");try{if(!fs$1.existsSync(r))return null;let s=fs$1.readFileSync(r,"utf-8"),a=JSON.parse(s);if(a.gitId!==e||Date.now()-a.resolvedAt>za)return null;let n=this.hashApiKey();return n&&a.apiKeyHash!==n?null:a}catch{return null}}writeRepoCache(e,r,s){if(!this.config)return;let a=path.join(this.config.queueDirectory,"..","cache"),n=path.join(a,"repo.json");try{fs$1.mkdirSync(a,{recursive:!0});let o={repoId:r,gitId:e,displayName:s,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=n+".tmp";fs$1.writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),fs$1.renameSync(i,n);}catch{}}hashApiKey(){return this.config?.apiKey?crypto.createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let e=this.authState.accessToken,r=this.config.queueDirectory,s=this.config.endpoint;this.flushPromise=Promise.race([Br(r,s,e),new Promise(a=>setTimeout(a,qr))]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let e=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await We(e))return;if(this.config?.apiKey){let s=await Ke(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!Je(s)){let a=s;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},this.failureReason=null,process.stderr.write(`\u2713 TestRelic: Cloud connectivity restored.
2580
+ `),this.startBackgroundFlush();}}}catch{}},$a);}};function Hr(t,e,r,s){let a=[],n=[],o=null,i=0,l=null,d=0,p=null,f=0,m=t.filter(g=>g.name===core.ATTACHMENT_NAME&&g.body),c=false;if(m.length>0)for(let g of m)try{let h=JSON.parse(g.body.toString());if(core.isTestRelicFilePayload(h)){a=a.concat(h.navigations),n=n.concat(h.apiAssertions),h.networkRequestsFile&&(o=h.networkRequestsFile,i+=h.networkRequestsCount),h.consoleLogsFile&&(l=h.consoleLogsFile,d+=h.consoleLogsCount),h.apiCallsFile&&(p=h.apiCallsFile,f+=h.apiCallsCount),c=!0;continue}if(core.isTestRelicDataPayload(h)){a=a.concat(h.navigations),Array.isArray(h.apiAssertions)&&(n=n.concat(h.apiAssertions)),i+=h.networkRequests?.length??0,f+=h.apiCalls?.length??0;let w=h.consoleLogs;Array.isArray(w)&&(d+=w.length),c=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
2581
+ `);}return c||(a=e.filter(g=>g.type==="lambdatest-navigation"&&g.description).map(g=>{try{return JSON.parse(g.description)}catch{return null}}).filter(g=>g!==null)),a.length===0&&i===0&&f===0&&!s&&!c&&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.
2582
+ `),{navigations:a,apiAssertions:n,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:l,consoleLogsCount:d,apiCallsFile:p,apiCallsCount:f}}function me(t=process.env){let e=Wa(t.TESTRELIC_CLOUD_PLATFORM);if(e)return {cloudPlatform:e,cloudBuildId:t.TESTRELIC_CLOUD_BUILD_ID||void 0,cloudSessionId:t.TESTRELIC_CLOUD_SESSION_ID||void 0};if(t.BROWSERSTACK_USERNAME||t.BROWSERSTACK_ACCESS_KEY)return {cloudPlatform:"browserstack",cloudBuildId:t.BROWSERSTACK_BUILD_NAME||t.BROWSERSTACK_BUILD_ID||void 0,cloudSessionId:t.BROWSERSTACK_SESSION_ID||void 0};if(t.LT_USERNAME||t.LAMBDATEST_USERNAME||t.LT_ACCESS_KEY||t.LAMBDATEST_ACCESS_KEY)return {cloudPlatform:"lambdatest",cloudBuildId:t.LT_BUILD||t.LAMBDATEST_BUILD||void 0,cloudSessionId:t.LT_SESSION_ID||t.LAMBDATEST_SESSION_ID||void 0};let r=t.PLAYWRIGHT_WS_ENDPOINT;if(r){if(/cdp\.lambdatest\.com/i.test(r))return {cloudPlatform:"lambdatest"};if(/cdp\.browserstack\.com/i.test(r))return {cloudPlatform:"browserstack"}}return {}}function Wa(t){if(!t)return;let e=t.toLowerCase().trim();if(e==="browserstack"||e==="bs")return "browserstack";if(e==="lambdatest"||e==="lt")return "lambdatest"}var Qa=5,ve=[1e3,3e3,9e3],V=3,Xa={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip"},dt=0,ct=[];async function en(){dt>=Qa&&await new Promise(t=>ct.push(t)),dt++;}function tn(){dt--,ct.length>0&&ct.shift()();}async function ye(t){return new Promise(e=>setTimeout(e,t))}function rn(t){let e=t.substring(t.lastIndexOf(".")).toLowerCase();return Xa[e]??"application/octet-stream"}function sn(t){try{return fs$1.statSync(t).size}catch{return 0}}async function an(t,e,r,s,a){let n=`${t}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:path.basename(r.filePath),contentType:a,type:r.type,sizeBytes:s});for(let i=0;i<V;i++)try{let l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:o});if(l.ok)return await l.json();if(l.status>=500&&i<V-1){await ye(ve[i]);continue}return null}catch{if(i<V-1){await ye(ve[i]);continue}return null}return null}async function nn(t,e,r,s){for(let a=0;a<V;a++)try{let n=fs$1.createReadStream(e),o=stream.Readable.toWeb(n),i=await fetch(t,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(s)},body:o,duplex:"half"});if(i.ok)return !0;if(i.status>=500&&a<V-1){await ye(ve[a]);continue}return !1}catch{if(a<V-1){await ye(ve[a]);continue}return false}return false}async function on(t,e,r){let s=`${t}/artifacts/confirm`;try{return (await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({artifactId:r})})).ok}catch{return false}}async function ln(t,e,r,s){let a=sn(r.filePath);if(a===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(a>s*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let n=rn(r.filePath);await en();try{let o=await an(t,e,r,a,n);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await nn(o.uploadUrl,r.filePath,n,a))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let l=await on(t,e,o.artifactId);return {success:l,storageKey:o.storageKey,artifactId:o.artifactId,error:l?null:"confirm_failed"}}finally{tn();}}async function Ur(t,e,r,s){let a=new Map,n=r.map(async o=>{let i=await ln(t,e,o,s);a.set(o.filePath,i);});return await Promise.allSettled(n),a}function ut(t){let r=t.getGitMetadata()?.remoteUrl;return r?X(r):t.getConfig()?.projectName??ee(process.cwd())}async function $r(t,e,r,s,a){if(!t.isCloudMode()||e!=="realtime"&&e!=="both"||!await t.ensureValidToken())return null;let o=t.getGitMetadata(),i=N(),l=me(),d=ce();return (await Lr(t.getEndpoint(),t.getAccessToken(),{runId:r,repoGitId:ut(t),branch:o?.branch??null,commit:o?.commitSha??null,commitMessage:o?.commitMessage??null,commitAuthor:o?.commitAuthor??null,startedAt:s,totalTests:null,ciProvider:i?.provider??null,ciRunUrl:i?.runUrl??null,environment:a??l.cloudPlatform??null,cloudPlatform:l.cloudPlatform??null,cloudBuildId:l.cloudBuildId??null,cloudSessionId:l.cloudSessionId??null,...d?{runType:d}:{},testType:"e2e"}))?.runId??null}var dn=true,cn=50;async function un(t,e,r,s){let a=new Map;if(!(e?.uploadArtifacts??dn)||!await t.ensureValidToken())return a;let i=[],l=new Map;for(let c of s){if(c.artifacts.screenshot){let u=path.join(c.outputDir,c.artifacts.screenshot);i.push({filePath:u,runId:r,testId:c.testId,type:"screenshot"}),l.set(u,{testId:c.testId,field:"screenshot"});}if(c.artifacts.video){let u=path.join(c.outputDir,c.artifacts.video);i.push({filePath:u,runId:r,testId:c.testId,type:"video"}),l.set(u,{testId:c.testId,field:"video"});}}if(i.length===0)return a;let d=e?.artifactMaxSizeMb??cn,p=await Ur(t.getEndpoint(),t.getAccessToken(),i,d),f=new Map;for(let[c,u]of p){if(!u.success||!u.storageKey)continue;let g=l.get(c);if(!g)continue;let h=f.get(g.testId)??{};g.field==="screenshot"&&(h.screenshotKey=u.storageKey),g.field==="video"&&(h.videoKey=u.storageKey),f.set(g.testId,h);}for(let c of s){let u=f.get(c.testId);a.set(c.testId,{...c.artifacts,...u?.screenshotKey?{screenshotKey:u.screenshotKey}:{},...u?.videoKey?{videoKey:u.videoKey}:{}});}let m=Array.from(p.values()).filter(c=>c.success).length;return m>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${m} artifact(s) to cloud storage.
2583
+ `),a}async function pt(t,e,r,s,a,n,o,i,l,d,p){try{if(t.isCloudMode()&&a&&(r==="realtime"||r==="both")){let m=await t.ensureValidToken(),c=t.getGitMetadata(),u=Xe(p),g={finishedAt:o,duration:i,summary:l,...c?.commitMessage?{commitMessage:c.commitMessage}:{},testType:u.testType,...u.testType==="api"?{apiProtocol:u.apiProtocol,metadata:u.metadata}:{}};if(m){if(!await Pr(t.getEndpoint(),t.getAccessToken(),a,g)){let w=e?.queueDirectory??".testrelic/queue";te(w,s,"finalize","finalize_failed_after_retries",`${t.getEndpoint()}/runs/${a}/finalize`,"POST",g,{"Content-Type":"application/json"});}}else {let h=e?.queueDirectory??".testrelic/queue";te(h,s,"finalize",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs/${a}/finalize`,"POST",g,{"Content-Type":"application/json"});}}let f=new Map;if(t.isCloudMode()&&d&&d.length>0&&(f=await un(t,e,s,d)),t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await t.ensureValidToken()){let c=t.getGitMetadata(),u=N(),g=ut(t),h=pn(n,f),w=et(h,g,c,u,p,me()),C=await Mr(t.getEndpoint(),t.getAccessToken(),w,async()=>await t.ensureValidToken()?t.getAccessToken():null);if(!C.success){let y=C,b=e?.queueDirectory??".testrelic/queue";te(b,s,"batch",y.reason,y.targetEndpoint,y.method,y.payload,{"Content-Type":"application/json"});}}else {let c=e?.queueDirectory??".testrelic/queue",u=t.getGitMetadata(),g=N(),h=ut(t),w=et(n,h,u,g,void 0,me());te(c,s,"batch",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs`,"POST",w,{"Content-Type":"application/json"});}await t.dispose();}catch{try{await t.dispose();}catch{}}}function pn(t,e){if(e.size===0)return t;let r=t.timeline.map(s=>{let a=s.testId;if(!a)return s;let n=e.get(a);return n?{...s,...n.screenshotKey?{screenshotKey:n.screenshotKey}:{},...n.videoKey?{videoKey:n.videoKey}:{}}:s});return {...t,timeline:r}}function U(t){try{return fs$1.readFileSync(t,"utf-8").split(`
2584
+ `).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function gt(t){switch(t){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function bn(t,e,r){let s=`${t}::${e}::${r}`;return crypto.createHash("sha256").update(s).digest("hex").substring(0,16)}function xn(t){return t.length<=3?"":t[t.length-2]}function wn(t){let e=t.findIndex(r=>r.status==="passed");return e>0?`passed on retry ${e}`:null}function kn(t){return t===null?"error":t>=200&&t<300?"2xx":t>=300&&t<400?"3xx":t>=400&&t<500?"4xx":t>=500&&t<600?"5xx":"error"}function Gr(t,e){for(let r of t)e[r.category]=(e[r.category]??0)+1,r.children.length>0&&Gr(r.children,e);}function Tn(t){if(t.length===0)return null;let e=[...t].sort((s,a)=>s-a),r=e.reduce((s,a)=>s+a,0);return {avg:Math.round(r/e.length),min:e[0],max:e[e.length-1],p50:H(e,50),p95:H(e,95),p99:H(e,99)}}function Sn(t){return process.env.BROWSERSTACK_USERNAME?"BrowserStack":t?{"github-actions":"GitHub Actions","gitlab-ci":"GitLab CI",jenkins:"Jenkins",circleci:"CircleCI","bitbucket-pipelines":"Bitbucket Pipelines"}[t.provider]??"CI":"Local"}function Cn(){let t=os$1.platform();return t==="win32"?"Windows":t==="darwin"?"macOS":"Linux"}function Rn(t){let e=t.parent?.project?.()?.use;if(!e)return;let{browserName:r,channel:s}=e;if(s){let n=s.toLowerCase();return n==="chrome"||n==="chrome-stable"?"Chrome":n.startsWith("chrome-beta")?"Chrome Beta":n.startsWith("chrome-dev")?"Chrome Dev":n.startsWith("chrome-canary")?"Chrome Canary":n==="msedge"||n==="msedge-stable"?"Microsoft Edge":n.startsWith("msedge-beta")?"Edge Beta":n.startsWith("msedge-dev")?"Edge Dev":n.startsWith("msedge-canary")?"Edge Canary":s}if(r){let n=r.toLowerCase();return n==="chromium"?"Chromium":n==="firefox"?"Firefox":n==="webkit"?"WebKit":r}let a=e.defaultBrowserType;if(a){let n=a.toLowerCase();return n==="chromium"?"Chromium":n==="firefox"?"Firefox":n==="webkit"?"WebKit":a}}function An(t,e,r){let s=r.parent?.project?.(),a="unknown";s!==void 0&&(s.use.isMobile===true?a="mobile":a="e2e");let n=["e2e","api","unit","mobile"];for(let l of n)if(t.some(d=>d===`@${l}`||d===l))return l;let o=e.replace(/\\/g,"/"),i=["e2e","api","unit"];for(let l of i)if(o.includes(`/${l}/`))return l;return a}var In="__testrelic_api_config";function _n(t){return JSON.stringify(t,(e,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var be=class{constructor(e){this.rootDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.navigationsCaptured=false;this.testCount=0;this.cloudClient=null;this.cloudRunId=null;this.runTimestamp="";this.pendingArtifactEntries=[];this.detectedOs="";this.detectedSource="";this.cloudTestsBuffer=[];this.activeReportMode="embedded";this.streamingWriter=null;this.testIndex=[];this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0};this.streamingAgg={apiUrlSet:new Set,methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,navUrlSet:new Set,actionCategoryCounts:{}};this.config=Ft(e),this.apiConfig=Nt(e);}async onBegin(e,r){try{if(this.rootDir=e.rootDir,this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??crypto.randomUUID(),this.config.reportMode==="auto"){let n=r.allTests().length;this.activeReportMode=n>=this.config.streamingThreshold?"streaming":"embedded";}else this.activeReportMode=this.config.reportMode;let s=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${s} tests)
2585
+ `),this.activeReportMode==="streaming"){let n=path.dirname(this.config.outputPath);this.streamingWriter=new K(n);let o=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let i={testRunId:this.testRunId??"",startedAt:this.startedAt,completedAt:new Date().toISOString(),totalDuration:Date.now()-new Date(this.startedAt).getTime(),...this.summaryCounters,metadata:null,reportMode:"streaming",files:[],enrichedSummary:null,validation:null,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(i);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let i=this.cloudClient.getAccessToken();i&&nt(this.cloudClient.getEndpoint(),i,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",o),process.on("SIGINT",o);}if(this.config.includeArtifacts){let n=path.dirname(this.config.outputPath);this.runTimestamp=cr(path.join(n,"artifacts"));try{hr(path.join(n,"artifacts"));}catch{}}let a=N();this.detectedOs=Cn(),this.detectedSource=Sn(a);try{this.cloudClient=new he(this.config.cloud),await this.cloudClient.initialize(),this.cloudRunId=await $r(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource);}catch{this.cloudClient?.switchToLocalMode("init_error");}if(this.activeReportMode!=="streaming"){let n=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let o=this.cloudClient.getAccessToken();o&&nt(this.cloudClient.getEndpoint(),o,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",n),process.on("SIGINT",n);}}catch{}}onTestBegin(e,r){try{e.annotations.push({type:In,description:_n(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let s=r,a=e.outcome(),n;a==="flaky"?n="flaky":a==="skipped"?n="skipped":n=gt(s.status);let o=s.startTime.toISOString(),i=new Date(s.startTime.getTime()+s.duration).toISOString(),l=e.tags?[...e.tags]:e.annotations.filter(I=>I.type==="tag").map(I=>I.description??""),d=Hr(s.attachments,e.annotations,e.title,n==="skipped");(d.navigations.length>0||d.networkRequestsCount>0||d.apiCallsCount>0)&&(this.fixtureDataReceived=!0),d.navigations.length>0&&(this.navigationsCaptured=!0),!this.config.captureNavigation&&d.navigations.length>0&&(d={...d,navigations:[]});let p=null;if(n==="failed"||n==="flaky"){let R=(n==="flaky"?e.results.find(O=>O.status!=="passed")?.errors??[]:s.errors)[0];if(R){let O=Bt(this.config.redactPatterns),G=R.location?.line??null,T=null;this.config.includeCodeSnippets&&G!==null&&R.location?.file&&(T=Dt(R.location.file,G,this.config.codeContextLines),T&&(T=O(T))),p={message:O(R.message??"Unknown error"),line:G,code:T,stack:this.config.includeStackTrace&&R.stack?O(R.stack):null};}}let f=e.titlePath().filter(Boolean),m=path.relative(this.rootDir||".",e.location.file),c=xn(f),u=f.join(" > "),g=m,h=bn(g,c,u),w=An(l,g,e),C=w!=="mobile"&&d.apiCallsCount>0?"api":w,y=a==="flaky",b=wn(e.results),S=gt(e.expectedStatus),v=gt(s.status),k=null;if(this.config.includeArtifacts&&n!=="skipped"&&s.attachments){let I=path.dirname(this.config.outputPath),R=f[f.length-1]??e.title;k=ur(s.attachments,R,s.retry,I,this.runTimestamp||void 0);}let A=this.config.includeActionSteps&&s.steps?xr(s.steps,s.startTime):null,z=Rn(e),E={titlePath:f,title:u,status:n,duration:s.duration,startedAt:o,completedAt:i,retryCount:e.results.length-1,retry:s.retry,tags:l,failure:p,specFile:m,navigations:d.navigations,testId:h,filePath:g,suiteName:c,testType:C,isFlaky:y,retryStatus:b,expectedStatus:S,actualStatus:v,artifacts:k,apiAssertions:d.apiAssertions,actions:A,networkRequestsFile:d.networkRequestsFile,networkRequestsCount:d.networkRequestsCount,consoleLogsFile:d.consoleLogsFile,consoleLogsCount:d.consoleLogsCount,apiCallsFile:d.apiCallsFile,apiCallsCount:d.apiCallsCount,browser:z,os:this.detectedOs||void 0,source:this.detectedSource||void 0},ht=d.consoleLogsFile&&d.consoleLogsCount>0?U(d.consoleLogsFile):void 0,xe=d.networkRequestsFile&&d.networkRequestsCount>0?U(d.networkRequestsFile):void 0,$=d.apiCallsFile&&d.apiCallsCount>0?U(d.apiCallsFile):void 0,mt=$?tt($):void 0,vt=!xe&&$?rt($):void 0,yt=d.apiAssertions&&d.apiAssertions.length>0?st(d.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:h,title:u,status:n,duration:s.duration,suiteName:c,filePath:g,testType:C,isFlaky:y,startedAt:o,completedAt:i,tags:l,failure:p,retry:s.retry,retryCount:e.results.length-1,retryStatus:b,browser:z,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...A&&A.length>0?{actions:A}:{},...d.navigations&&d.navigations.length>0?{navigations:d.navigations}:{},...ht?{consoleLogs:ht}:{},...xe?{networkRequests:xe}:vt?{networkRequests:vt}:{},...mt?{apiCalls:mt}:{},...yt?{protocolAssertions:yt}:{}});try{let I=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(I==="realtime"||I==="both")){let R=this.cloudClient.getAccessToken();R&&Er(this.cloudClient.getEndpoint(),R,this.cloudRunId,this.buildCloudTestPayload(E));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let I=we(g,f,e.id??"",s.retry),R=s.retry===e.results.length-1,O={id:I,navigations:d.navigations,apiAssertions:d.apiAssertions,actions:A??[],artifacts:k,failureDiagnostic:p,hasNetworkFile:d.networkRequestsFile!==null,networkRequestsCount:d.networkRequestsCount,hasConsoleFile:d.consoleLogsFile!==null,consoleLogsCount:d.consoleLogsCount,hasApiCallsFile:d.apiCallsFile!==null,apiCallsCount:d.apiCallsCount,startedAt:o};this.streamingWriter.writeTestDetail(I,O,{networkRequestsFile:d.networkRequestsFile,consoleLogsFile:d.consoleLogsFile,apiCallsFile:d.apiCallsFile});let G={id:I,title:f[f.length-1]??e.title,titlePath:f,filePath:g,status:n,duration:s.duration,project:f[1]??"",retryIndex:s.retry,tags:l,hasNetworkData:d.networkRequestsCount>0,hasConsoleData:d.consoleLogsCount>0,hasArtifacts:k!==null,hasActionSteps:(A?.length??0)>0,errorMessage:p?.message?.split(`
2586
+ `)[0]??null,networkCount:d.networkRequestsCount,consoleCount:d.consoleLogsCount,actionCount:A?.length??0,isRetry:!R};if(this.testIndex.push(G),R)switch(this.summaryCounters.total++,n){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}if(this.summaryCounters.totalApiCalls+=d.apiCallsCount,this.summaryCounters.totalAssertions+=d.apiAssertions.length,this.summaryCounters.totalNavigations+=d.navigations.length,this.summaryCounters.totalNetworkRequests+=d.networkRequestsCount,this.summaryCounters.totalConsoleLogs+=d.consoleLogsCount,this.summaryCounters.totalActionSteps+=A?.length??0,$)for(let T of $){let bt=typeof T.method=="string"?T.method:"OTHER";this.streamingAgg.methodCounts[bt]=(this.streamingAgg.methodCounts[bt]??0)+1;let xt=typeof T.url=="string"?T.url:null;xt&&this.streamingAgg.apiUrlSet.add(je(xt));let Wr=typeof T.responseStatusCode=="number"?T.responseStatusCode:typeof T.statusCode=="number"?T.statusCode:null;this.streamingAgg.statusRanges[kn(Wr)]++;let wt=typeof T.responseTimeMs=="number"?T.responseTimeMs:typeof T.durationMs=="number"?T.durationMs:null;wt!==null&&this.streamingAgg.responseTimes.push(wt);}for(let T of d.apiAssertions)T.status==="passed"?this.streamingAgg.passedAssertions++:this.streamingAgg.failedAssertions++;for(let T of d.navigations)T.url&&this.streamingAgg.navUrlSet.add(T.url);A&&Gr(A,this.streamingAgg.actionCategoryCounts),k&&this.pendingArtifactEntries.push({testId:h,artifacts:k,outputDir:path.dirname(this.config.outputPath)}),E.actions=null,E.apiAssertions=null,E.navigations=[],E.artifacts=null,E.failure=null,E.networkRequestsFile=null,E.consoleLogsFile=null,E.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(E),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(e){try{let r=new Date().toISOString(),s=new Date(this.startedAt).getTime(),n=new Date(r).getTime()-s,o=this.activeReportMode==="streaming"?this.testIndex.some(l=>l.status!=="skipped"):this.collectedTests.some(l=>l.status!=="skipped");!this.fixtureDataReceived&&o&&process.stderr.write(`
2585
2587
  \u26A0 TestRelic: No fixture data received from any test.
2586
2588
  To enable network logs, video sync, and Test Navigation tracking, import the TestRelic fixture:
2587
2589
  import { test, expect } from '@testrelic/playwright-analytics/fixture';
@@ -2590,14 +2592,14 @@ ${n}
2590
2592
 
2591
2593
  `),this.config.captureNavigation?this.fixtureDataReceived&&!this.navigationsCaptured&&o&&process.stderr.write(`[testrelic] Test Navigation: 0 navigation events captured this run. Navigation is recorded automatically on page.goto()/clicks; if you expected a navigation graph, ensure your tests drive page navigations (and use the '@testrelic/playwright-analytics/fixture' import).
2592
2594
  `):process.stderr.write(`[testrelic] Test Navigation capture is disabled (captureNavigation: false). Remove the option or set it to true to capture the navigation graph.
2593
- `),await ar();let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let l=path.dirname(this.config.outputPath);i=or(l,this.runTimestamp);let d=path.join(l,"artifact-manifest.json"),p=JSON.stringify(i),f=d+".tmp";fs$1.writeFileSync(f,p,"utf-8"),fs$1.renameSync(f,d);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await this.finalizeStreamingReport(r,s,e,i);else {let l=this.buildTimeline(),d=new Map;for(let c of this.collectedTests){let u=d.get(c.testId);(!u||c.retry>u.retry)&&d.set(c.testId,c);}let p=Array.from(d.values()),f=fr(p,l.length),h={schemaVersion:ke,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:s,summary:f,ci:P(),metadata:this.config.metadata,timeline:l,shardRunIds:null};if(this.writeReport(h),await Oe(h,this.config,i),je(f,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient){let c=this.collectArtifactEntries(),u=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await dt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,h,r,s,f,c,u);}}}catch{}}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let e=path.dirname(this.config.outputPath),r=[];for(let a of this.collectedTests)a.artifacts&&r.push({testId:a.testId,artifacts:a.artifacts,outputDir:e});return r}async finalizeStreamingReport(e,r,a,n){if(!this.streamingWriter)return;let{totalApiCalls:s,totalAssertions:o,totalNavigations:i,totalNetworkRequests:l,totalConsoleLogs:d,totalActionSteps:p}=this.summaryCounters;this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:s,totalAssertions:o,totalNavigations:i,totalNetworkRequests:l,totalConsoleLogs:d,totalActionSteps:p};let f=new Map,h=new Map;for(let x of this.testIndex){let T=`${x.filePath}::${x.titlePath.join(" > ")}`,v=f.get(T);(v===void 0||x.retryIndex>v)&&f.set(T,x.retryIndex);}let c=0;for(let x of this.testIndex){let T=`${x.filePath}::${x.titlePath.join(" > ")}`,v=f.get(T);if(x.isRetry=x.retryIndex<v,x.isRetry)continue;switch(c++,this.summaryCounters.total++,x.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}let k=h.get(x.filePath);switch(k||(k={filePath:x.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},h.set(x.filePath,k)),k.total++,x.status){case "passed":k.passed++;break;case "failed":k.failed++;break;case "flaky":k.flaky++;break;case "skipped":k.skipped++;break;case "timedout":k.timedOut++;break}}let u=Array.from(h.values());this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let g={reporterTotal:this.summaryCounters.total,indexTotal:c,playwrightStatus:a.status,isValid:this.summaryCounters.total===c};g.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${g.reporterTotal}, index: ${g.indexTotal}
2594
- `);let m={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:0,apiCallsByMethod:{},apiCallsByStatusRange:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},apiResponseTime:null,totalAssertions:this.summaryCounters.totalAssertions,passedAssertions:0,failedAssertions:0,totalNavigations:this.summaryCounters.totalNavigations,uniqueNavigationUrls:0,totalTimelineSteps:this.testIndex.length,totalActionSteps:this.summaryCounters.totalActionSteps,actionStepsByCategory:{}},b={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:e,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:u,enrichedSummary:m,validation:g,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(b);let S={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(S),await Oe(this.buildStreamingReport(b,m,e,r),this.config,n),je(m,this.config.outputPath,this.config.htmlReportPath,this.config.quiet);let y=this.streamingWriter.getReportDir();if(process.stderr.write(`[testrelic] Streaming report written to ${y}
2595
+ `),await dr();let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let l=path.dirname(this.config.outputPath);i=fr(l,this.runTimestamp);let d=path.join(l,"artifact-manifest.json"),p=JSON.stringify(i),f=d+".tmp";fs$1.writeFileSync(f,p,"utf-8"),fs$1.renameSync(f,d);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await this.finalizeStreamingReport(r,n,e,i);else {let l=this.buildTimeline(),d=new Map;for(let c of this.collectedTests){let u=d.get(c.testId);(!u||c.retry>u.retry)&&d.set(c.testId,c);}let p=Array.from(d.values()),f=br(p,l.length),m={schemaVersion:Te,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:n,summary:f,ci:N(),metadata:this.config.metadata,timeline:l,shardRunIds:null};if(this.writeReport(m),await qe(m,this.config,i),Ve(f,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient){let c=this.collectArtifactEntries(),u=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await pt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,m,r,n,f,c,u);}}}catch{}}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let e=path.dirname(this.config.outputPath),r=[];for(let s of this.collectedTests)s.artifacts&&r.push({testId:s.testId,artifacts:s.artifacts,outputDir:e});return r}async finalizeStreamingReport(e,r,s,a){if(!this.streamingWriter)return;let{totalApiCalls:n,totalAssertions:o,totalNavigations:i,totalNetworkRequests:l,totalConsoleLogs:d,totalActionSteps:p}=this.summaryCounters;this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:n,totalAssertions:o,totalNavigations:i,totalNetworkRequests:l,totalConsoleLogs:d,totalActionSteps:p};let f=new Map,m=new Map;for(let b of this.testIndex){let S=`${b.filePath}::${b.titlePath.join(" > ")}`,v=f.get(S);(v===void 0||b.retryIndex>v)&&f.set(S,b.retryIndex);}let c=0;for(let b of this.testIndex){let S=`${b.filePath}::${b.titlePath.join(" > ")}`,v=f.get(S);if(b.isRetry=b.retryIndex<v,b.isRetry)continue;switch(c++,this.summaryCounters.total++,b.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}let k=m.get(b.filePath);switch(k||(k={filePath:b.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},m.set(b.filePath,k)),k.total++,b.status){case "passed":k.passed++;break;case "failed":k.failed++;break;case "flaky":k.flaky++;break;case "skipped":k.skipped++;break;case "timedout":k.timedOut++;break}}let u=Array.from(m.values());this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let g={reporterTotal:this.summaryCounters.total,indexTotal:c,playwrightStatus:s.status,isValid:this.summaryCounters.total===c};g.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${g.reporterTotal}, index: ${g.indexTotal}
2596
+ `);let h={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:this.streamingAgg.apiUrlSet.size,apiCallsByMethod:{...this.streamingAgg.methodCounts},apiCallsByStatusRange:{"2xx":this.streamingAgg.statusRanges["2xx"],"3xx":this.streamingAgg.statusRanges["3xx"],"4xx":this.streamingAgg.statusRanges["4xx"],"5xx":this.streamingAgg.statusRanges["5xx"],error:this.streamingAgg.statusRanges.error},apiResponseTime:Tn(this.streamingAgg.responseTimes),totalAssertions:this.summaryCounters.totalAssertions,passedAssertions:this.streamingAgg.passedAssertions,failedAssertions:this.streamingAgg.failedAssertions,totalNavigations:this.summaryCounters.totalNavigations,uniqueNavigationUrls:this.streamingAgg.navUrlSet.size,totalTimelineSteps:this.testIndex.length,totalActionSteps:this.summaryCounters.totalActionSteps,actionStepsByCategory:{...this.streamingAgg.actionCategoryCounts}},w={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:e,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:u,enrichedSummary:h,validation:g,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(w);let C={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(C),await qe(this.buildStreamingReport(w,h,e,r),this.config,a),Ve(h,this.config.outputPath,this.config.htmlReportPath,this.config.quiet);let y=this.streamingWriter.getReportDir();if(process.stderr.write(`[testrelic] Streaming report written to ${y}
2595
2597
  [testrelic] ${this.testIndex.length} test detail files on disk
2596
2598
  [testrelic] View report: npx testrelic serve ${y}
2597
2599
  `),this.streamingWriter.getWriteErrors().length>0&&process.stderr.write(`[testrelic] WARNING: ${this.streamingWriter.getWriteErrors().length} write error(s) during streaming
2598
- `),this.streamingWriter.dispose(),this.cloudClient){let x=this.buildStreamingReport(b,m,e,r),T=this.collectArtifactEntries(),v=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await dt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,x,e,r,m,T,v);}this.testIndex.length=0,this.collectedTests.length=0,this.pendingArtifactEntries.length=0,this.cloudTestsBuffer.length=0,this.streamingWriter=null,this.cloudClient=null;}buildStreamingReport(e,r,a,n){return {schemaVersion:ke,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:a,totalDuration:n,summary:r,ci:P(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let e=process.memoryUsage(),r=e.heapUsed/1024/1024;if(r<200)return;let a=e.heapUsed/e.heapTotal;a>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
2599
- `),this.switchToStreamingMode()):a>.8&&process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
2600
- `);}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let e=path.dirname(this.config.outputPath);this.streamingWriter=new G(e);for(let r of this.collectedTests){let a=xe(r.filePath,r.titlePath,r.testId,r.retry),n={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,n,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let s={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(`
2601
- `)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,isRetry:!1};switch(this.testIndex.push(s),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.summaryCounters.totalApiCalls+=r.apiCallsCount,this.summaryCounters.totalAssertions+=r.apiAssertions?.length??0,this.summaryCounters.totalNavigations+=r.navigations?.length??0,this.summaryCounters.totalNetworkRequests+=r.networkRequestsCount,this.summaryCounters.totalConsoleLogs+=r.consoleLogsCount,this.summaryCounters.totalActionSteps+=r.actions?.length??0;}this.collectedTests.length=0;}catch{}}buildTimeline(){let e=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls:null,apiAssertions:r.apiAssertions,testId:r.testId,filePath:r.filePath,suiteName:r.suiteName,testType:r.testType,isFlaky:r.isFlaky,retryStatus:r.retryStatus,expectedStatus:r.expectedStatus,actualStatus:r.actualStatus,artifacts:r.artifacts,networkRequests:null,actions:r.actions,consoleLogs:null}));return pr(e,{navigationTypes:this.config.navigationTypes})}readJsonlFile(e){if(!e)return null;let r=q(e);return r.length>0?r:null}toTestResult(e,r){let a=null,n=null,s=null;return r?.loadFiles&&(a=this.readJsonlFile(e.networkRequestsFile),n=this.readJsonlFile(e.consoleLogsFile),s=this.readJsonlFile(e.apiCallsFile)),{title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,retryStatus:e.retryStatus,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,networkRequests:a,apiCalls:s,apiAssertions:e.apiAssertions,actions:e.actions??null,consoleLogs:n}}buildCloudTestPayload(e){let r={title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retry:e.retry,retryCount:e.retryCount,retryStatus:e.retryStatus,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,actions:e.actions??[],navigations:e.navigations??[],steps:e.actions??[],browser:e.browser,os:e.os,source:e.source};if(e.apiAssertions&&e.apiAssertions.length>0&&(r.protocolAssertions=nt(e.apiAssertions)),e.consoleLogsFile&&(r.consoleLogs=q(e.consoleLogsFile)),e.networkRequestsFile&&(r.networkRequests=q(e.networkRequestsFile)),e.apiCallsFile){let a=q(e.apiCallsFile);r.apiCalls=rt(a),(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=at(a));}return r}writeReport(e){try{let r=JSON.stringify(e),a=this.config.outputPath,n=path.dirname(a);fs$1.mkdirSync(n,{recursive:!0});let s=a+".tmp";fs$1.writeFileSync(s,r,"utf-8"),fs$1.renameSync(s,a);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
2602
- `);}}};module.exports=ye;//# sourceMappingURL=reporter-entry.cjs.map
2600
+ `),this.streamingWriter.dispose(),this.cloudClient){let b=this.buildStreamingReport(w,h,e,r),S=this.collectArtifactEntries(),v=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await pt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,b,e,r,h,S,v);}this.testIndex.length=0,this.collectedTests.length=0,this.pendingArtifactEntries.length=0,this.cloudTestsBuffer.length=0,this.streamingWriter=null,this.cloudClient=null;}buildStreamingReport(e,r,s,a){return {schemaVersion:Te,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:s,totalDuration:a,summary:r,ci:N(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let e=process.memoryUsage(),r=e.heapUsed/1024/1024;if(r<200)return;let s=e.heapUsed/e.heapTotal;s>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
2601
+ `),this.switchToStreamingMode()):s>.8&&process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
2602
+ `);}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let e=path.dirname(this.config.outputPath);this.streamingWriter=new K(e);for(let r of this.collectedTests){let s=we(r.filePath,r.titlePath,r.testId,r.retry),a={id:s,navigations:r.navigations??[],apiAssertions:r.apiAssertions??[],actions:r.actions??[],artifacts:r.artifacts,failureDiagnostic:r.failure,hasNetworkFile:r.networkRequestsFile!==null,networkRequestsCount:r.networkRequestsCount,hasConsoleFile:r.consoleLogsFile!==null,consoleLogsCount:r.consoleLogsCount,hasApiCallsFile:r.apiCallsFile!==null,apiCallsCount:r.apiCallsCount,startedAt:r.startedAt};this.streamingWriter.writeTestDetail(s,a,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let n={id:s,title:r.titlePath[r.titlePath.length-1]??r.title,titlePath:r.titlePath,filePath:r.filePath,status:r.status,duration:r.duration,project:r.titlePath[1]??"",retryIndex:r.retry,tags:r.tags,hasNetworkData:r.networkRequestsCount>0,hasConsoleData:r.consoleLogsCount>0,hasArtifacts:r.artifacts!==null,hasActionSteps:(r.actions?.length??0)>0,errorMessage:r.failure?.message?.split(`
2603
+ `)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,isRetry:!1};switch(this.testIndex.push(n),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.summaryCounters.totalApiCalls+=r.apiCallsCount,this.summaryCounters.totalAssertions+=r.apiAssertions?.length??0,this.summaryCounters.totalNavigations+=r.navigations?.length??0,this.summaryCounters.totalNetworkRequests+=r.networkRequestsCount,this.summaryCounters.totalConsoleLogs+=r.consoleLogsCount,this.summaryCounters.totalActionSteps+=r.actions?.length??0;}this.collectedTests.length=0;}catch{}}buildTimeline(){let e=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls:null,apiAssertions:r.apiAssertions,testId:r.testId,filePath:r.filePath,suiteName:r.suiteName,testType:r.testType,isFlaky:r.isFlaky,retryStatus:r.retryStatus,expectedStatus:r.expectedStatus,actualStatus:r.actualStatus,artifacts:r.artifacts,networkRequests:null,actions:r.actions,consoleLogs:null}));return yr(e,{navigationTypes:this.config.navigationTypes})}readJsonlFile(e){if(!e)return null;let r=U(e);return r.length>0?r:null}toTestResult(e,r){let s=null,a=null,n=null;return r?.loadFiles&&(s=this.readJsonlFile(e.networkRequestsFile),a=this.readJsonlFile(e.consoleLogsFile),n=this.readJsonlFile(e.apiCallsFile)),{title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,retryStatus:e.retryStatus,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,networkRequests:s,apiCalls:n,apiAssertions:e.apiAssertions,actions:e.actions??null,consoleLogs:a}}buildCloudTestPayload(e){let r={title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retry:e.retry,retryCount:e.retryCount,retryStatus:e.retryStatus,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,actions:e.actions??[],navigations:e.navigations??[],steps:e.actions??[],browser:e.browser,os:e.os,source:e.source};if(e.apiAssertions&&e.apiAssertions.length>0&&(r.protocolAssertions=st(e.apiAssertions)),e.consoleLogsFile&&(r.consoleLogs=U(e.consoleLogsFile)),e.networkRequestsFile&&(r.networkRequests=U(e.networkRequestsFile)),e.apiCallsFile){let s=U(e.apiCallsFile);r.apiCalls=tt(s),(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=rt(s));}return r}writeReport(e){try{let r=JSON.stringify(e),s=this.config.outputPath,a=path.dirname(s);fs$1.mkdirSync(a,{recursive:!0});let n=s+".tmp";fs$1.writeFileSync(n,r,"utf-8"),fs$1.renameSync(n,s);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
2604
+ `);}}};module.exports=be;//# sourceMappingURL=reporter-entry.cjs.map
2603
2605
  //# sourceMappingURL=reporter-entry.cjs.map