@testrelic/playwright-analytics 2.8.0 → 2.9.0-next.66

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
- import {randomUUID,createHash}from'crypto';import {writeFileSync,renameSync,mkdirSync,unlinkSync,existsSync,readFileSync,appendFileSync,readdirSync,statSync,rmSync,createReadStream}from'fs';import {join,dirname,relative,extname,resolve,parse,basename}from'path';import {tmpdir,platform}from'os';import {isValidConfig,createError,ErrorCode,ATTACHMENT_NAME,isTestRelicFilePayload,isTestRelicDataPayload,isValidEndpointUrl,isValidCloudConfig,isValidQueueEntry}from'@testrelic/core';import {spawn,exec,execSync}from'child_process';import {createServer}from'http';import {createInterface}from'readline';import {copyFile}from'fs/promises';import {gzipSync}from'zlib';import {Readable}from'stream';var Mr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Fr=".testrelic-report";function ye(e,t,r,a){let s=`${e}|${t.join("|")}|${r}|${a}`;return createHash("sha256").update(s).digest("hex").substring(0,12)}var G=class{constructor(t){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=join(t,Fr),this.testsDir=join(this.reportDir,"tests"),mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(t,r,a){try{let s=join(this.testsDir,t);mkdirSync(s,{recursive:!0});let n=join(s,"meta.json"),o=n+".tmp",i=JSON.stringify(r);return writeFileSync(o,i,"utf-8"),renameSync(o,n),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),a?.networkRequestsFile&&this.moveFile(a.networkRequestsFile,join(s,"network.jsonl")),a?.consoleLogsFile&&this.moveFile(a.consoleLogsFile,join(s,"console.jsonl")),a?.apiCallsFile&&this.moveFile(a.apiCallsFile,join(s,"api-calls.jsonl")),!0}catch(s){let n=s instanceof Error?s.message:String(s);return this.writeErrors.push({testId:t,error:n,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${t}: ${n}
2
- `),false}}moveFile(t,r){try{renameSync(t,r);}catch{try{let{copyFileSync:a}=Mr("fs");a(t,r);try{unlinkSync(t);}catch{}}catch(a){process.stderr.write(`[testrelic] Failed to move file ${t} \u2192 ${r}: ${a instanceof Error?a.message:String(a)}
3
- `);}}}writeIndex(t){let r=join(this.reportDir,"index.json"),a=r+".tmp",s=JSON.stringify(t);writeFileSync(a,s,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeCompactIndex(t){let r=join(this.reportDir,"index-compact.json"),a=r+".tmp",s=t.map(({titlePath:o,project:i,...l})=>l),n=JSON.stringify(s);writeFileSync(a,n,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeSummary(t){let r=join(this.reportDir,"summary.json"),a=r+".tmp",s=JSON.stringify(t);writeFileSync(a,s,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeManifest(t){let r=join(this.reportDir,"manifest.json"),a=r+".tmp",s=JSON.stringify(t);writeFileSync(a,s,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var gt=".testrelic",Hr="testrelic-config.json",Ur=".testrelic",zr=5,$r=new Set(["__proto__","constructor","prototype"]),ut=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${gt}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),jr={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function ht(e){let t=resolve(e);for(let r=0;r<=zr;r++){let a=join(t,gt,Hr);if(existsSync(a))try{if(statSync(a).isFile())return a}catch{}let s=join(t,Ur);if(existsSync(s))try{if(statSync(s).isFile())return process.stderr.write(`[testrelic] Deprecation: config file ".testrelic" has moved to ".testrelic/testrelic-config.json". Please migrate your config file to the new location.
4
- `),s}catch{}let n=dirname(t);if(n===t)break;t=n;}return null}function mt(e){try{let t=readFileSync(e,"utf-8"),r=JSON.parse(t);return typeof r!="object"||r===null||Array.isArray(r)||!vt(r)?null:r}catch{return null}}function vt(e){for(let t of Object.keys(e)){if($r.has(t))return false;let r=e[t];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!vt(r))return false}return true}function yt(e){let t=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(e);if(t)return process.env[t[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(e);return r?process.env[r[1]]??null:e}function be(e){let t=Object.create(null);for(let r of Object.keys(e)){let a=e[r];typeof a=="string"&&a.startsWith("$")?t[r]=yt(a):typeof a=="object"&&a!==null&&!Array.isArray(a)?t[r]=be(a):t[r]=a;}return t}function ft(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let r=parseInt(t[1],10),a=t[2],s=jr[a];return !s||r<=0?null:r*s}function bt(e,t){let r=Object.create(null);if(Object.assign(r,ut),e){let l=e.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=e["testrelic-repo"]??e.project;d&&typeof d=="object"&&typeof d.name=="string"&&(r.projectName=d.name),e.project&&!e["testrelic-repo"]&&process.stderr.write(`[testrelic] Deprecation: "project" key in config is deprecated. Rename it to "testrelic-repo".
5
- `);let u=e.queue;if(u&&typeof u=="object"){if(typeof u.maxAge=="string"){let f=ft(u.maxAge);f!==null&&(r.queueMaxAge=f);}typeof u.directory=="string"&&(r.queueDirectory=u.directory);}}if(t){if(typeof t.apiKey=="string"&&t.apiKey.length>0){let l=t.apiKey.startsWith("$")?yt(t.apiKey):t.apiKey;l&&(r.apiKey=l);}if(typeof t.endpoint=="string"&&(r.endpoint=t.endpoint),typeof t.upload=="string"&&(r.uploadStrategy=t.upload),typeof t.timeout=="number"&&(r.timeout=t.timeout),typeof t.projectName=="string"&&(r.projectName=t.projectName),typeof t.queueMaxAge=="string"){let l=ft(t.queueMaxAge);l!==null&&(r.queueMaxAge=l);}typeof t.queueDirectory=="string"&&(r.queueDirectory=t.queueDirectory),typeof t.uploadArtifacts=="boolean"&&(r.uploadArtifacts=t.uploadArtifacts),typeof t.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=t.artifactMaxSizeMb);}let a=process.env.TESTRELIC_API_KEY;a&&a.length>0&&(r.apiKey=a);let s=process.env.TESTRELIC_CLOUD_ENDPOINT;s&&isValidEndpointUrl(s)&&(r.endpoint=s);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 isValidCloudConfig(i)?i:ut}var Kr=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],Jr=["authorization","cookie","set-cookie","x-api-key"],Yr=["password","secret","token","apiKey","api_key"];function xt(e){let t=Object.create(null);return t.trackApiCalls=e?.trackApiCalls??true,t.captureRequestHeaders=e?.captureRequestHeaders??true,t.captureResponseHeaders=e?.captureResponseHeaders??true,t.captureRequestBody=e?.captureRequestBody??true,t.captureResponseBody=e?.captureResponseBody??true,t.captureAssertions=e?.captureAssertions??true,t.redactHeaders=e?.redactHeaders??[...Jr],t.redactBodyFields=e?.redactBodyFields??[...Yr],t.apiIncludeUrls=e?.apiIncludeUrls??[],t.apiExcludeUrls=e?.apiExcludeUrls??[],Object.freeze(t)}function wt(e){if(e!==void 0&&!isValidConfig(e))throw createError(ErrorCode.CONFIG_INVALID,"Invalid reporter configuration");let t=Object.create(null);t.outputPath=e?.outputPath??"./test-results/analytics-timeline.json",t.includeStackTrace=e?.includeStackTrace??false,t.includeCodeSnippets=e?.includeCodeSnippets??true,t.codeContextLines=e?.codeContextLines??3,t.includeNetworkStats=e?.includeNetworkStats??true,t.navigationTypes=e?.navigationTypes??null,t.redactPatterns=[...Kr,...e?.redactPatterns??[]],t.testRunId=e?.testRunId??null,t.metadata=e?.metadata??null;let r=t.outputPath;t.openReport=e?.openReport??true,t.htmlReportPath=e?.htmlReportPath??r.replace(/\.json$/,".html"),t.includeArtifacts=e?.includeArtifacts??true,t.trackApiCalls=e?.trackApiCalls??true,t.quiet=e?.quiet??false,t.includeActionSteps=e?.includeActionSteps??true,t.captureConsoleLogs=e?.captureConsoleLogs??true;let a=ht(process.cwd()),s=a?mt(a):null,n=s?be(s):null,o=bt(n,e?.cloud);return t.cloud=o.apiKey?o:null,t.reportMode=e?.reportMode??"streaming",t.streamingThreshold=e?.streamingThreshold??0,Object.freeze(t)}var xe="1.3.0";function kt(e,t,r){try{let s=readFileSync(e,"utf-8").split(`
6
- `);if(t<1||t>s.length)return null;let n=Math.max(1,t-r),o=Math.min(s.length,t+r),i=[];for(let l=n;l<=o;l++){let d=l===t?">":" ",u=String(l).padStart(String(o).length," ");i.push(`${d} ${u} | ${s[l-1]}`);}return i.join(`
7
- `)}catch{return null}}function Tt(e){return t=>{let r=t;for(let a of e)if(typeof a=="string"){let s=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(s,"g"),"[REDACTED]");}else {let s=a.flags.includes("g")?a.flags:a.flags+"g",n=new RegExp(a.source,s);r=r.replace(n,"[REDACTED]");}return r}}function Qr(e){return e.GITHUB_ACTIONS!=="true"?null:{provider:"github-actions",buildId:e.GITHUB_RUN_ID??null,commitSha:e.GITHUB_SHA??null,branch:e.GITHUB_REF_NAME??null,runUrl:e.GITHUB_SERVER_URL&&e.GITHUB_REPOSITORY&&e.GITHUB_RUN_ID?`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`:null}}function Xr(e){return e.GITLAB_CI!=="true"?null:{provider:"gitlab-ci",buildId:e.CI_PIPELINE_ID??null,commitSha:e.CI_COMMIT_SHA??null,branch:e.CI_COMMIT_BRANCH??e.CI_COMMIT_REF_NAME??null,runUrl:e.CI_PIPELINE_URL??null}}function ea(e){if(!e.JENKINS_URL)return null;let t=e.GIT_BRANCH??null;return t?.startsWith("origin/")&&(t=t.slice(7)),{provider:"jenkins",buildId:e.BUILD_ID??null,commitSha:e.GIT_COMMIT??null,branch:t,runUrl:e.BUILD_URL??null}}function ta(e){return e.CIRCLECI!=="true"?null:{provider:"circleci",buildId:e.CIRCLE_BUILD_NUM??null,commitSha:e.CIRCLE_SHA1??null,branch:e.CIRCLE_BRANCH??null,runUrl:e.CIRCLE_BUILD_URL??null}}function ra(e){if(!e.BITBUCKET_PIPELINE_UUID)return null;let t=e.BITBUCKET_WORKSPACE&&e.BITBUCKET_REPO_SLUG&&e.BITBUCKET_PIPELINE_UUID?`https://bitbucket.org/${e.BITBUCKET_WORKSPACE}/${e.BITBUCKET_REPO_SLUG}/pipelines/results/${e.BITBUCKET_PIPELINE_UUID}`:null;return {provider:"bitbucket-pipelines",buildId:e.BITBUCKET_BUILD_NUMBER??null,commitSha:e.BITBUCKET_COMMIT??null,branch:e.BITBUCKET_BRANCH??null,runUrl:t}}var aa=[Qr,Xr,ea,ta,ra];function P(e){let t=process.env;for(let r of aa){let a=r(t);if(a)return a}return null}var we=`
1
+ import {randomUUID,createHash}from'crypto';import {writeFileSync,renameSync,mkdirSync,unlinkSync,existsSync,readFileSync,appendFileSync,readdirSync,statSync,rmSync,createReadStream}from'fs';import {join,dirname,relative,extname,resolve,parse,basename}from'path';import {tmpdir,platform}from'os';import {isValidConfig,createError,ErrorCode,ATTACHMENT_NAME,isTestRelicFilePayload,isTestRelicDataPayload,isValidEndpointUrl,isValidCloudConfig,isValidQueueEntry}from'@testrelic/core';import {spawn,exec,execSync}from'child_process';import {createServer}from'http';import {createInterface}from'readline';import {copyFile}from'fs/promises';import {gzipSync}from'zlib';import {Readable}from'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 s=`${t}|${e.join("|")}|${r}|${a}`;return createHash("sha256").update(s).digest("hex").substring(0,12)}var G=class{constructor(e){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=join(e,zr),this.testsDir=join(this.reportDir,"tests"),mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(e,r,a){try{let s=join(this.testsDir,e);mkdirSync(s,{recursive:!0});let n=join(s,"meta.json"),o=n+".tmp",i=JSON.stringify(r);return writeFileSync(o,i,"utf-8"),renameSync(o,n),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),a?.networkRequestsFile&&this.moveFile(a.networkRequestsFile,join(s,"network.jsonl")),a?.consoleLogsFile&&this.moveFile(a.consoleLogsFile,join(s,"console.jsonl")),a?.apiCallsFile&&this.moveFile(a.apiCallsFile,join(s,"api-calls.jsonl")),!0}catch(s){let n=s instanceof Error?s.message:String(s);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{renameSync(e,r);}catch{try{let{copyFileSync:a}=qr("fs");a(e,r);try{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=join(this.reportDir,"index.json"),a=r+".tmp",s=JSON.stringify(e);writeFileSync(a,s,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeCompactIndex(e){let r=join(this.reportDir,"index-compact.json"),a=r+".tmp",s=e.map(({titlePath:o,project:i,...l})=>l),n=JSON.stringify(s);writeFileSync(a,n,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeSummary(e){let r=join(this.reportDir,"summary.json"),a=r+".tmp",s=JSON.stringify(e);writeFileSync(a,s,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeManifest(e){let r=join(this.reportDir,"manifest.json"),a=r+".tmp",s=JSON.stringify(e);writeFileSync(a,s,"utf-8"),renameSync(a,r),this.totalBytesWritten+=Buffer.byteLength(s,"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=resolve(t);for(let r=0;r<=Yr;r++){let a=join(e,kt,Kr);if(existsSync(a))try{if(statSync(a).isFile())return a}catch{}let s=join(e,Jr);if(existsSync(s))try{if(statSync(s).isFile())return process.stderr.write(`[testrelic] Deprecation: config file ".testrelic" has moved to ".testrelic/testrelic-config.json". Please migrate your config file to the new location.
4
+ `),s}catch{}let n=dirname(e);if(n===e)break;e=n;}return null}function St(t){try{let e=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],s=Qr[a];return !s||r<=0?null:r*s}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 s=process.env.TESTRELIC_CLOUD_ENDPOINT;s&&isValidEndpointUrl(s)&&(r.endpoint=s);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 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"],sa=["password","secret","token","apiKey","api_key"];function _t(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??[...sa],e.apiIncludeUrls=t?.apiIncludeUrls??[],e.apiExcludeUrls=t?.apiExcludeUrls??[],Object.freeze(e)}function It(t){if(t!==void 0&&!isValidConfig(t))throw createError(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.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()),s=a?St(a):null,n=s?we(s):null,o=At(n,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 s=readFileSync(t,"utf-8").split(`
6
+ `);if(e<1||e>s.length)return null;let n=Math.max(1,e-r),o=Math.min(s.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} | ${s[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 s=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(s,"g"),"[REDACTED]");}else {let s=a.flags.includes("g")?a.flags:a.flags+"g",n=new RegExp(a.source,s);r=r.replace(n,"[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=`
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 ke=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 196 247" fill="none">
564
+ `;var Se=`<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>`,Te=`<svg width="32" height="40" viewBox="0 0 196 247" fill="none" xmlns="http://www.w3.org/2000/svg">
568
+ </linearGradient></defs></svg>`,Ce=`<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 Se=`
572
+ </linearGradient></defs></svg>`;var Re=`
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 Ce=`
1003
+ `;var Ae=`
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 Re=`
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 Ae=`
1805
+ `;var Ie=`
1806
1806
  /* \u2500\u2500 Event Delegation \u2500\u2500 */
1807
1807
  document.addEventListener('click',function(e){
1808
1808
  var target=e.target;
@@ -2072,7 +2072,7 @@ function _updateCard(cls,val){
2072
2072
  var d=document.getElementById('filter-drawer');if(d)d.classList.remove('open');
2073
2073
  var b=document.getElementById('filter-drawer-backdrop');if(b)b.classList.remove('open');
2074
2074
  }
2075
- `;var _e=`
2075
+ `;var Le=`
2076
2076
  /* \u2500\u2500 Category badge helpers \u2500\u2500 */
2077
2077
  function actionBadgeClass(cat){
2078
2078
  if(cat==='assertion')return 'action-badge-assertion';
@@ -2118,7 +2118,7 @@ function _updateCard(cls,val){
2118
2118
  h+='</div>';
2119
2119
  return h;
2120
2120
  }
2121
- `;var Ie=`
2121
+ `;var Me=`
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 Le=`
2308
+ `;var Ee=`
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 sa=`
2317
+ `;var pa=`
2318
2318
  (function(){
2319
2319
  var data=JSON.parse(document.getElementById('report-data').textContent);
2320
- ${Se}
2321
- ${_e}
2322
- ${Ie}
2323
- ${Ce}
2324
2320
  ${Re}
2325
2321
  ${Le}
2322
+ ${Me}
2326
2323
  ${Ae}
2324
+ ${_e}
2325
+ ${Ee}
2326
+ ${Ie}
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 St(e,t,r){let a=e.replace(/<\//g,"<\\/"),s=r?r.replace(/<\//g,"<\\/"):null;return `<!-- TestRelic AI Analytics Report \u2014 self-contained, no external dependencies -->
2334
+ })();`;function Et(t,e,r){let a=t.replace(/<\//g,"<\\/"),s=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(ke).toString("base64")}">
2344
- <style>${we}</style>
2343
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Se).toString("base64")}">
2344
+ <style>${Te}</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
- ${Te}
2351
+ ${Ce}
2352
2352
  <div class="brand-text">
2353
2353
  <span class="brand-title">TestRelic AI</span>
2354
2354
  <span class="brand-sub">Analytics Report</span>
@@ -2385,9 +2385,9 @@ ${""}
2385
2385
  </aside>
2386
2386
  <script id="report-data" type="application/json">${a}</script>
2387
2387
  ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:""}
2388
- <script>${sa}</script>
2388
+ <script>${pa}</script>
2389
2389
  </body>
2390
- </html>`}function Me(e,t,r,a){let s=e.replace(/<\//g,"<\\/"),n=t.replace(/<\//g,"<\\/"),o=a?a.replace(/<\//g,"<\\/"):null,i={};try{i=JSON.parse(e);}catch{}let l=`{
2390
+ </html>`}function Pe(t,e,r,a){let s=t.replace(/<\//g,"<\\/"),n=e.replace(/<\//g,"<\\/"),o=a?a.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"},
@@ -2471,13 +2471,13 @@ ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:
2471
2471
  window.__trServerPort=_serverPort;
2472
2472
  window.__trIsStreaming=true;
2473
2473
 
2474
- ${Se}
2475
- ${_e}
2476
- ${Ie}
2477
- ${Ce}
2478
2474
  ${Re}
2479
2475
  ${Le}
2476
+ ${Me}
2480
2477
  ${Ae}
2478
+ ${_e}
2479
+ ${Ee}
2480
+ ${Ie}
2481
2481
  applyTheme();
2482
2482
  renderRunMeta();
2483
2483
  renderSummary();
@@ -2496,15 +2496,15 @@ ${s?`<script id="artifact-manifest-data" type="application/json">${s}</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(ke).toString("base64")}">
2500
- <style>${we}</style>
2499
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Se).toString("base64")}">
2500
+ <style>${Te}</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
- ${Te}
2507
+ ${Ce}
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,59 +2543,59 @@ ${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 Ee(e){try{let t=process.platform,r;t==="darwin"?r=`open "${e}"`:t==="win32"?r=`start "" "${e}"`:r=`xdg-open "${e}"`,exec(r,a=>{a&&process.stderr.write(`[testrelic] Failed to open browser: ${a.message}
2547
- `);});}catch{}}join(tmpdir(),"testrelic-data");async function Ct(e,t,r,a){let s=(t-1)*r,n=[],o=0,i=createInterface({input:createReadStream(e,{encoding:"utf-8"}),crlfDelay:1/0});for await(let u of i)if(u.length!==0){if(o>=s&&n.length<r)try{n.push(JSON.parse(u));}catch{}if(o++,n.length>=r&&a!==void 0)break}let l=a??o,d=Math.max(1,Math.ceil(l/r));return {items:n,total:l,page:t,pageSize:r,totalPages:d}}var _t=/^[a-f0-9]{12}$/,Pe=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,It=500;function x(e,t,r){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(r));}function Lt(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type");}function re(e){try{return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):null}catch{return null}}function ae(e){let t=0;try{let r=readdirSync(e,{withFileTypes:!0});for(let a of r){let s=join(e,a.name);a.isFile()?t+=statSync(s).size:a.isDirectory()&&(t+=ae(s));}}catch{}return t}function Mt(e,t,r,a){let s=re(join(r,"index.json"));x(t,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-a)/1e3)});}function Et(e,t,r){let a=re(join(r,"summary.json"));if(!a){x(t,404,{error:"Summary not found"});return}x(t,200,a);}function Pt(e,t,r){let a=re(join(r,"index.json"));if(!a){x(t,404,{error:"Test index not found"});return}let n=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,o=Math.max(1,parseInt(n.get("page")??"1",10)||1),i=Math.min(It,Math.max(1,parseInt(n.get("pageSize")??"100",10)||100)),l=n.get("status")?.split(",").filter(Boolean)??null,d=n.get("file")??null,u=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,p=a;l&&l.length>0&&(p=p.filter(y=>l.includes(y.status))),d&&(p=p.filter(y=>y.filePath===d||y.filePath.startsWith(d+"/"))),u&&(p=p.filter(y=>y.title.toLowerCase().includes(u)||y.filePath.toLowerCase().includes(u))),f&&f.length>0&&(p=p.filter(y=>f.some(b=>y.tags.includes(b)))),p=[...p].sort((y,b)=>{let T=0;switch(m){case "duration":T=y.duration-b.duration;break;case "status":T=y.status.localeCompare(b.status);break;case "title":T=y.title.localeCompare(b.title);break;default:T=y.filePath.localeCompare(b.filePath);break}return T*c});let g=p.length,h=Math.max(1,Math.ceil(g/i)),w=(o-1)*i,S=p.slice(w,w+i);x(t,200,{tests:S,pagination:{page:o,pageSize:i,totalItems:g,totalPages:h},filters:{status:l,file:d,search:u,tag:f}});}function Ft(e,t,r,a){if(!_t.test(a)){x(t,400,{error:"Invalid test ID format"});return}let s=join(r,"tests",a,"meta.json"),n=join(r,"tests",`${a}.json`),o=existsSync(s)?s:existsSync(n)?n:null;if(!o){x(t,404,{error:`Test not found: ${a}`});return}try{let i=readFileSync(o,"utf-8");t.writeHead(200,{"Content-Type":"application/json"}),t.end(i);}catch(i){x(t,500,{error:i instanceof Error?i.message:String(i)});}}async function Dt(e,t,r,a,s){if(!_t.test(a)){x(t,400,{error:"Invalid test ID format"});return}let o=join(r,"tests",a,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!existsSync(o)){x(t,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let l=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,d=Math.max(1,parseInt(l.get("page")??"1",10)||1),u=Math.min(It,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),f,m=join(r,"tests",a,"meta.json");if(existsSync(m))try{let p=JSON.parse(readFileSync(m,"utf-8"));switch(s){case "network":f=p.networkRequestsCount;break;case "console":f=p.consoleLogsCount;break;case "api-calls":f=p.apiCallsCount;break}}catch{}let c=await Ct(o,d,u,f);x(t,200,c);}catch(i){x(t,500,{error:i instanceof Error?i.message:String(i)});}}function Nt(e,t,r){let a=re(join(r,"index.json"));if(!a){x(t,404,{error:"Test index not found"});return}let s=new Map;for(let o of a){if(o.isRetry)continue;let i=s.get(o.filePath);switch(i||(i={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},s.set(o.filePath,i)),i.total++,o.status){case "passed":i.passed++;break;case "failed":i.failed++;break;case "flaky":i.flaky++;break;case "skipped":i.skipped++;break;case "timedout":i.timedOut++;break}}let n=Array.from(s.entries()).map(([o,i])=>({filePath:o,...i})).sort((o,i)=>o.filePath.localeCompare(i.filePath));x(t,200,{files:n});}function Bt(e,t,r){if(!existsSync(r)){x(t,200,{runs:[],totalSizeBytes:0});return}try{let a=[],s=0,n=readdirSync(r,{withFileTypes:!0});for(let o of n){if(!o.isDirectory()||!Pe.test(o.name))continue;let i=join(r,o.name),l=ae(i),d=readdirSync(i,{withFileTypes:!0}).filter(u=>u.isDirectory());a.push({folderName:o.name,totalSizeBytes:l,testCount:d.length}),s+=l;}a.sort((o,i)=>i.folderName.localeCompare(o.folderName)),x(t,200,{runs:a,totalSizeBytes:s});}catch(a){x(t,500,{error:a instanceof Error?a.message:String(a)});}}function Ot(e,t,r){try{let a=0,s=0;if(existsSync(r)){let n=readdirSync(r,{withFileTypes:!0});for(let o of n){if(!o.isDirectory()||!Pe.test(o.name))continue;let i=join(r,o.name),l=ae(i);rmSync(i,{recursive:!0,force:!0}),s+=l,a++;}}x(t,200,{deletedCount:a,freedBytes:s});}catch(a){x(t,500,{error:a instanceof Error?a.message:String(a)});}}function qt(e,t,r,a){if(!Pe.test(a)){x(t,400,{error:"Invalid folder name"});return}let s=join(r,a);try{if(!statSync(s).isDirectory()){x(t,404,{error:"Not found"});return}}catch{x(t,404,{error:"Not found"});return}try{let n=ae(s);rmSync(s,{recursive:!0,force:!0}),x(t,200,{deleted:a,freedBytes:n});}catch(n){x(t,500,{error:n instanceof Error?n.message:String(n)});}}function Ht(e,t,r){x(t,200,{status:"shutting_down"}),r.close();}function Fe(e,t,r){if(!existsSync(r)){x(t,404,{error:"File not found"});return}try{let a=readFileSync(r),s=extname(r).toLowerCase(),n=pa[s]??"application/octet-stream";t.writeHead(200,{"Content-Type":n}),t.end(a);}catch(a){x(t,500,{error:a instanceof Error?a.message:String(a)});}}var pa={".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 ha=9323,ma=10,va=1800*1e3;function W(e,t){return new Promise((r,a)=>{let s=t?.port??ha,n=Date.now(),o,i=0,l=existsSync(join(e,"artifacts"))?join(e,"artifacts"):existsSync(join(e,"..","artifacts"))?join(e,"..","artifacts"):join(e,"artifacts");function d(){clearTimeout(o),o=setTimeout(()=>{f.close();},va);}let u=t?.htmlPath??null;if(!u){let c=dirname(e);try{let p=readdirSync(c).find(g=>g.endsWith(".html"));p&&(u=join(c,p));}catch{}}let f=createServer((c,p)=>{if(d(),Lt(p),c.method==="OPTIONS"){p.writeHead(204),p.end();return}let g;try{g=new URL(c.url??"/",`http://${c.headers.host??"localhost"}`).pathname;}catch{x(p,400,{error:"Invalid URL"});return}if(c.method==="GET"&&(g==="/"||g==="/index.html")){if(u&&existsSync(u)){Fe(c,p,u);return}x(p,404,{error:"HTML report not found"});return}if(c.method==="GET"&&g==="/api/health"){Mt(c,p,e,n);return}if(c.method==="GET"&&g==="/api/summary"){Et(c,p,e);return}if(c.method==="GET"&&g==="/api/tests"){Pt(c,p,e);return}if(c.method==="GET"&&g==="/api/files"){Nt(c,p,e);return}let h=g.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(c.method==="GET"&&h){Dt(c,p,e,h[1],h[2]);return}let w=g.match(/^\/api\/tests\/([a-f0-9]+)$/);if(c.method==="GET"&&w){Ft(c,p,e,w[1]);return}if(c.method==="GET"&&g==="/api/artifacts"){Bt(c,p,l);return}if(c.method==="DELETE"&&g==="/api/artifacts"){Ot(c,p,l);return}let S=g.match(/^\/api\/artifacts\/(.+)$/);if(c.method==="DELETE"&&S){qt(c,p,l,decodeURIComponent(S[1]));return}if(c.method==="GET"&&g.startsWith("/artifacts/")){let y=decodeURIComponent(g.slice(11));if(y.includes("..")||y.includes("\0")){x(p,400,{error:"Invalid path"});return}Fe(c,p,join(l,y));return}if(c.method==="POST"&&g==="/api/shutdown"){Ht(c,p,f);return}x(p,404,{error:"Not found"});});function m(c){let p=g=>{g.code==="EADDRINUSE"&&i<ma?(i++,m(c+1)):a(g);};f.once("error",p),f.listen(c,"127.0.0.1",()=>{f.removeListener("error",p);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(h=>{clearTimeout(o),f.close(()=>h());})});});}m(s);})}async function Ut(e){let t=await W(e);return {port:t.port,dispose:t.dispose}}function xa(e,t,r){let a=JSON.stringify(e),s=r?JSON.stringify(r):null;return St(a,t,s)}async function Ne(e,t,r){try{let a=null,s=null,n=t.reportMode==="streaming"||t.reportMode==="auto"&&e.timeline.length===0&&e.summary.total>=t.streamingThreshold,o,i=t.htmlReportPath,l=dirname(i);mkdirSync(l,{recursive:!0});let d="",u="[]",f=null;if(n){d=JSON.stringify(e.summary);let c=dirname(t.outputPath),p=join(c,".testrelic-report");try{let g=join(p,"index-compact.json"),h=join(p,"index.json");existsSync(g)?u=readFileSync(g,"utf-8"):existsSync(h)&&(u=readFileSync(h,"utf-8"));}catch{}f=r?JSON.stringify(r):null,o=Me(d,u,null,f);}else o=xa(e,null,r);let m=i+".tmp";if(writeFileSync(m,o,"utf-8"),renameSync(m,i),n){if(e.ci===null){let c=dirname(t.outputPath),p=join(c,".testrelic-report"),g=resolve(i);try{if(await ka(),a=await Ta(p),!a){s=await W(p,{htmlPath:g}),a=s.port;let h=setInterval(()=>{},6e4),w=()=>{clearInterval(h),s?.dispose();};process.on("SIGINT",w),process.on("SIGTERM",w),setTimeout(w,1800*1e3).unref();}if(a){process.stderr.write(`
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}"`,exec(r,a=>{a&&process.stderr.write(`[testrelic] Failed to open browser: ${a.message}
2547
+ `);});}catch{}}join(tmpdir(),"testrelic-data");async function Pt(t,e,r,a){let s=(e-1)*r,n=[],o=0,i=createInterface({input:createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let p of i)if(p.length!==0){if(o>=s&&n.length<r)try{n.push(JSON.parse(p));}catch{}if(o++,n.length>=r&&a!==void 0)break}let l=a??o,d=Math.max(1,Math.ceil(l/r));return {items:n,total:l,page:e,pageSize:r,totalPages:d}}var Dt=/^[a-f0-9]{12}$/,Ne=/^\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 existsSync(t)?JSON.parse(readFileSync(t,"utf-8")):null}catch{return null}}function se(t){let e=0;try{let r=readdirSync(t,{withFileTypes:!0});for(let a of r){let s=join(t,a.name);a.isFile()?e+=statSync(s).size:a.isDirectory()&&(e+=se(s));}}catch{}return e}function qt(t,e,r,a){let s=ae(join(r,"index.json"));w(e,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-a)/1e3)});}function Ht(t,e,r){let a=ae(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(join(r,"index.json"));if(!a){w(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(Bt,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,h=n.get("sort")??"file",c=n.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 s=join(r,"tests",a,"meta.json"),n=join(r,"tests",`${a}.json`),o=existsSync(s)?s:existsSync(n)?n:null;if(!o){w(e,404,{error:`Test not found: ${a}`});return}try{let i=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,s){if(!Dt.test(a)){w(e,400,{error:"Invalid test ID format"});return}let o=join(r,"tests",a,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!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=join(r,"tests",a,"meta.json");if(existsSync(h))try{let u=JSON.parse(readFileSync(h,"utf-8"));switch(s){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(join(r,"index.json"));if(!a){w(e,404,{error:"Test index not found"});return}let s=new Map;for(let o of a){if(o.isRetry)continue;let i=s.get(o.filePath);switch(i||(i={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},s.set(o.filePath,i)),i.total++,o.status){case "passed":i.passed++;break;case "failed":i.failed++;break;case "flaky":i.flaky++;break;case "skipped":i.skipped++;break;case "timedout":i.timedOut++;break}}let n=Array.from(s.entries()).map(([o,i])=>({filePath:o,...i})).sort((o,i)=>o.filePath.localeCompare(i.filePath));w(e,200,{files:n});}function Vt(t,e,r){if(!existsSync(r)){w(e,200,{runs:[],totalSizeBytes:0});return}try{let a=[],s=0,n=readdirSync(r,{withFileTypes:!0});for(let o of n){if(!o.isDirectory()||!Ne.test(o.name))continue;let i=join(r,o.name),l=se(i),d=readdirSync(i,{withFileTypes:!0}).filter(p=>p.isDirectory());a.push({folderName:o.name,totalSizeBytes:l,testCount:d.length}),s+=l;}a.sort((o,i)=>i.folderName.localeCompare(o.folderName)),w(e,200,{runs:a,totalSizeBytes:s});}catch(a){w(e,500,{error:a instanceof Error?a.message:String(a)});}}function Gt(t,e,r){try{let a=0,s=0;if(existsSync(r)){let n=readdirSync(r,{withFileTypes:!0});for(let o of n){if(!o.isDirectory()||!Ne.test(o.name))continue;let i=join(r,o.name),l=se(i);rmSync(i,{recursive:!0,force:!0}),s+=l,a++;}}w(e,200,{deletedCount:a,freedBytes:s});}catch(a){w(e,500,{error:a instanceof Error?a.message:String(a)});}}function Wt(t,e,r,a){if(!Ne.test(a)){w(e,400,{error:"Invalid folder name"});return}let s=join(r,a);try{if(!statSync(s).isDirectory()){w(e,404,{error:"Not found"});return}}catch{w(e,404,{error:"Not found"});return}try{let n=se(s);rmSync(s,{recursive:!0,force:!0}),w(e,200,{deleted:a,freedBytes:n});}catch(n){w(e,500,{error:n instanceof Error?n.message:String(n)});}}function Kt(t,e,r){w(e,200,{status:"shutting_down"}),r.close();}function De(t,e,r){if(!existsSync(r)){w(e,404,{error:"File not found"});return}try{let a=readFileSync(r),s=extname(r).toLowerCase(),n=ba[s]??"application/octet-stream";e.writeHead(200,{"Content-Type":n}),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 s=e?.port??Ta,n=Date.now(),o,i=0,l=existsSync(join(t,"artifacts"))?join(t,"artifacts"):existsSync(join(t,"..","artifacts"))?join(t,"..","artifacts"):join(t,"artifacts");function d(){clearTimeout(o),o=setTimeout(()=>{f.close();},Ca);}let p=e?.htmlPath??null;if(!p){let c=dirname(t);try{let u=readdirSync(c).find(g=>g.endsWith(".html"));u&&(p=join(c,u));}catch{}}let f=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&&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,n);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,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(s);})}async function Jt(t){let e=await W(t);return {port:e.port,dispose:e.dispose}}function _a(t,e,r){let a=JSON.stringify(t),s=r?JSON.stringify(r):null;return Et(a,e,s)}async function Oe(t,e,r){try{let a=null,s=null,n=e.reportMode==="streaming"||e.reportMode==="auto"&&t.timeline.length===0&&t.summary.total>=e.streamingThreshold,o,i=e.htmlReportPath,l=dirname(i);mkdirSync(l,{recursive:!0});let d="",p="[]",f=null;if(n){d=JSON.stringify(t.summary);let c=dirname(e.outputPath),u=join(c,".testrelic-report");try{let g=join(u,"index-compact.json"),m=join(u,"index.json");existsSync(g)?p=readFileSync(g,"utf-8"):existsSync(m)&&(p=readFileSync(m,"utf-8"));}catch{}f=r?JSON.stringify(r):null,o=Pe(d,p,null,f);}else o=_a(t,null,r);let h=i+".tmp";if(writeFileSync(h,o,"utf-8"),renameSync(h,i),n){if(t.ci===null){let c=dirname(e.outputPath),u=join(c,".testrelic-report"),g=resolve(i);try{if(await La(),a=await Ma(u),!a){s=await W(u,{htmlPath:g}),a=s.port;let m=setInterval(()=>{},6e4),b=()=>{clearInterval(m),s?.dispose();};process.on("SIGINT",b),process.on("SIGTERM",b),setTimeout(b,1800*1e3).unref();}if(a){process.stderr.write(`
2548
2548
  Report server: http://127.0.0.1:${a}
2549
- `);try{let h=Me(d,u,a,f),w=i+".tmp";writeFileSync(w,h,"utf-8"),renameSync(w,i);}catch{}}}catch{}}}else if(t.openReport&&e.ci===null&&t.includeArtifacts){let c=dirname(t.outputPath),p=join(c,"artifacts");if(existsSync(p))try{let g=await Ut(p);a=g.port,process.on("exit",()=>{g.dispose();});}catch{}}if(t.openReport&&e.ci===null)if(n&&a)Ee(`http://127.0.0.1:${a}`);else {let c=resolve(i);Ee(c);}}catch(a){process.stderr.write(`[testrelic] Failed to write HTML report: ${a instanceof Error?a.message:String(a)}
2550
- `);}}var ie=9323,Gt=10;async function wa(){for(let e=ie;e<ie+Gt;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),500),a=await fetch(`http://127.0.0.1:${e}/api/health`,{signal:t.signal});if(clearTimeout(r),a.ok)return e}catch{}return null}async function ka(){for(let e=ie;e<ie+Gt;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),1e3);await fetch(`http://127.0.0.1:${e}/api/shutdown`,{method:"POST",signal:t.signal}),clearTimeout(r);}catch{}await new Promise(e=>setTimeout(e,300));}async function Ta(e){let r=[join(__dirname,"cli.cjs"),join(__dirname,"cli.js"),join(__dirname,"..","dist","cli.cjs"),join(__dirname,"..","dist","cli.js")].find(a=>existsSync(a));if(!r){let a=await W(e);return process.on("exit",()=>{a?.dispose();}),a.port}return new Promise(a=>{let s=spawn(process.execPath,[r,"serve",e],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),n="",o=false,i=setTimeout(()=>{o||(o=true,s.stderr?.removeAllListeners(),wa().then(a));},5e3);s.stderr?.on("data",l=>{n+=l.toString();let d=n.match(/127\.0\.0\.1:(\d+)/);d&&!o&&(o=true,clearTimeout(i),s.stderr?.removeAllListeners(),s.unref(),a(Number(d[1])));}),s.on("error",()=>{o||(o=true,clearTimeout(i),a(null));}),s.on("exit",()=>{o||(o=true,clearTimeout(i),a(null));}),s.unref();})}var Ra=20,Be=0,Oe=[];async function Kt(e,t){Be>=Ra&&await new Promise(r=>Oe.push(r)),Be++;try{return await copyFile(e,t),!0}catch{return false}finally{Be--,Oe.length>0&&Oe.shift()();}}var J=[];async function Jt(){J.length!==0&&(await Promise.allSettled(J),J.length=0);}function Yt(e){let t=new Date,r=n=>String(n).padStart(2,"0"),a=`${t.getFullYear()}-${r(t.getMonth()+1)}-${r(t.getDate())}T${r(t.getHours())}-${r(t.getMinutes())}-${r(t.getSeconds())}`;if(!existsSync(join(e,a)))return a;let s=1;for(;existsSync(join(e,`${a}-${s}`));)s++;return `${a}-${s}`}function Aa(e){let t=e.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return t.length>100&&(t=t.substring(0,100).replace(/-+$/,"")),t||"unnamed-test"}function Zt(e,t,r,a,s){let n=e.find(m=>m.name==="screenshot"&&m.path),o=e.find(m=>m.name==="video"&&m.path);if(!n&&!o)return null;let i=Aa(t);r>0&&(i+=`--retry-${r}`);let l=s?["artifacts",s,i]:["artifacts",i],d=join(a,...l),u=l,f={};try{mkdirSync(d,{recursive:!0});}catch{return null}if(n?.path&&existsSync(n.path)){let c=`screenshot${extname(n.path)||".png"}`,p=join(d,c);J.push(Kt(n.path,p).then(()=>{})),f.screenshot=`${u.join("/")}/${c}`;}if(o?.path&&existsSync(o.path)){let c=`video${extname(o.path)||".webm"}`,p=join(d,c);J.push(Kt(o.path,p).then(()=>{})),f.video=`${u.join("/")}/${c}`;}return !f.screenshot&&!f.video?null:f}var La=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Ma="1.0";function Ea(e){let t=extname(e).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(t)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(t)?"video":"other"}function Qt(e,t,r){let a=[];try{let s=readdirSync(e,{withFileTypes:!0});for(let n of s){if(!n.isFile())continue;let o=join(e,n.name),i=statSync(o);a.push({name:n.name,type:Ea(n.name),relativePath:`artifacts/${t}/${r}/${n.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:a}}function Pa(e,t){let r=join(e,t),a=[],s=0;try{let o=readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let l=Qt(join(r,i.name),t,i.name);a.push(l);for(let d of l.files)s+=d.sizeBytes;}}catch{}let n=t.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return a.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:t,timestamp:n,totalSizeBytes:s,testCount:a.length,tests:a,isCurrentRun:false}}function Xt(e,t){let r=join(e,"artifacts"),a=[],s=[],n=0;try{let i=readdirSync(r,{withFileTypes:!0});for(let l of i)if(l.isDirectory())if(La.test(l.name)){let d=Pa(r,l.name);a.push({...d,isCurrentRun:l.name===t});}else {let d=Qt(join(r,l.name),l.name,l.name);s.push(d);for(let u of d.files)n+=u.sizeBytes;}}catch{}a.sort((i,l)=>l.timestamp.localeCompare(i.timestamp)),s.length>0&&(s.sort((i,l)=>i.testName.localeCompare(l.testName)),a.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:n,testCount:s.length,tests:s,isCurrentRun:false}));let o=a.reduce((i,l)=>i+l.totalSizeBytes,0);return {schemaVersion:Ma,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:a,serverPort:null}}function Oa(e){let t=e,{root:r}=parse(t);for(;t!==r;){if(existsSync(join(t,".git")))return t;t=join(t,"..");}return null}function tr(e){try{let t=Oa(e);if(!t)return;let r=join(t,".gitignore"),a=relative(t,e).replace(/\\/g,"/"),s=a.endsWith("/")?a:`${a}/`;if(existsSync(r)&&readFileSync(r,"utf-8").split(`
2549
+ `);try{let m=Pe(d,p,a,f),b=i+".tmp";writeFileSync(b,m,"utf-8"),renameSync(b,i);}catch{}}}catch{}}}else if(e.openReport&&t.ci===null&&e.includeArtifacts){let c=dirname(e.outputPath),u=join(c,"artifacts");if(existsSync(u))try{let g=await Jt(u);a=g.port,process.on("exit",()=>{g.dispose();});}catch{}}if(e.openReport&&t.ci===null)if(n&&a)Fe(`http://127.0.0.1:${a}`);else {let c=resolve(i);Fe(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 Ia(){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=[join(__dirname,"cli.cjs"),join(__dirname,"cli.js"),join(__dirname,"..","dist","cli.cjs"),join(__dirname,"..","dist","cli.js")].find(a=>existsSync(a));if(!r){let a=await W(t);return process.on("exit",()=>{a?.dispose();}),a.port}return new Promise(a=>{let s=spawn(process.execPath,[r,"serve",t],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),n="",o=false,i=setTimeout(()=>{o||(o=true,s.stderr?.removeAllListeners(),Ia().then(a));},5e3);s.stderr?.on("data",l=>{n+=l.toString();let d=n.match(/127\.0\.0\.1:(\d+)/);d&&!o&&(o=true,clearTimeout(i),s.stderr?.removeAllListeners(),s.unref(),a(Number(d[1])));}),s.on("error",()=>{o||(o=true,clearTimeout(i),a(null));}),s.on("exit",()=>{o||(o=true,clearTimeout(i),a(null));}),s.unref();})}var Fa=20,qe=0,He=[];async function rr(t,e){qe>=Fa&&await new Promise(r=>He.push(r)),qe++;try{return await 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 sr(t){let e=new Date,r=n=>String(n).padStart(2,"0"),a=`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())}T${r(e.getHours())}-${r(e.getMinutes())}-${r(e.getSeconds())}`;if(!existsSync(join(t,a)))return a;let s=1;for(;existsSync(join(t,`${a}-${s}`));)s++;return `${a}-${s}`}function Na(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 nr(t,e,r,a,s){let n=t.find(h=>h.name==="screenshot"&&h.path),o=t.find(h=>h.name==="video"&&h.path);if(!n&&!o)return null;let i=Na(e);r>0&&(i+=`--retry-${r}`);let l=s?["artifacts",s,i]:["artifacts",i],d=join(a,...l),p=l,f={};try{mkdirSync(d,{recursive:!0});}catch{return null}if(n?.path&&existsSync(n.path)){let c=`screenshot${extname(n.path)||".png"}`,u=join(d,c);J.push(rr(n.path,u).then(()=>{})),f.screenshot=`${p.join("/")}/${c}`;}if(o?.path&&existsSync(o.path)){let c=`video${extname(o.path)||".webm"}`,u=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=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 s=readdirSync(t,{withFileTypes:!0});for(let n of s){if(!n.isFile())continue;let o=join(t,n.name),i=statSync(o);a.push({name:n.name,type:Ha(n.name),relativePath:`artifacts/${e}/${r}/${n.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:a}}function Ua(t,e){let r=join(t,e),a=[],s=0;try{let o=readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let l=ir(join(r,i.name),e,i.name);a.push(l);for(let d of l.files)s+=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 a.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:e,timestamp:n,totalSizeBytes:s,testCount:a.length,tests:a,isCurrentRun:false}}function or(t,e){let r=join(t,"artifacts"),a=[],s=[],n=0;try{let i=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(join(r,l.name),l.name,l.name);s.push(d);for(let p of d.files)n+=p.sizeBytes;}}catch{}a.sort((i,l)=>l.timestamp.localeCompare(i.timestamp)),s.length>0&&(s.sort((i,l)=>i.testName.localeCompare(l.testName)),a.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:n,testCount:s.length,tests:s,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}=parse(e);for(;e!==r;){if(existsSync(join(e,".git")))return e;e=join(e,"..");}return null}function dr(t){try{let e=Ga(t);if(!e)return;let r=join(e,".gitignore"),a=relative(e,t).replace(/\\/g,"/"),s=a.endsWith("/")?a:`${a}/`;if(existsSync(r)&&readFileSync(r,"utf-8").split(`
2551
2551
  `).map(l=>l.trim()).some(l=>l===s||l===a))return;let n=`
2552
2552
  # TestRelic test artifacts
2553
2553
  ${s}
2554
- `;appendFileSync(r,n,"utf-8");}catch{}}function sr(e,t){let r=[];for(let a of e){let s=qa(a),n=Ha(a),o=Ua(a,s,n,t),i=za(a,s,n);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:s,tests:[n],_testTitle:a.title});continue}r.push(...o,...i);}return r.sort($a),ja(r,e),r.map((a,s)=>a.type==="navigation"?{...{index:s,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:s,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 qa(e){return {title:e.title,fullTitle:e.titlePath,status:e.status,duration:e.duration,retries:e.retryCount,retry:e.retry,tags:e.tags,failure:e.failure}}function Ha(e){return {title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,retryStatus:e.retryStatus,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,networkRequests:e.networkRequests,apiCalls:e.apiCalls,apiAssertions:e.apiAssertions,actions:e.actions,consoleLogs:e.consoleLogs}}function Ua(e,t,r,a){let s=[];for(let n of e.navigations)a.navigationTypes!==null&&!a.navigationTypes.includes(n.navigationType)||s.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:e.specFile,test:t,tests:[r],_testTitle:e.title});return s}function za(e,t,r){if(!e.apiCalls||e.apiCalls.length===0)return [];let a=e.apiAssertions??[];return e.apiCalls.map(s=>{let n=a.filter(i=>i.callId===s.id).map(i=>({type:i.type,expected:i.expected,actual:i.actual,status:i.status,location:i.location,...i.expression!==void 0?{expression:i.expression}:{}})),o=null;return s.responseStatusCode!==null&&s.responseStatusText!==null&&(o={statusCode:s.responseStatusCode,statusText:s.responseStatusText,headers:s.responseHeaders,body:ar(s.responseBody)}),{type:"api_call",callId:s.id,method:s.method,url:s.url,timestamp:s.timestamp,responseTime:s.error?null:s.responseTimeMs,request:{headers:s.requestHeaders,body:ar(s.requestBody)},response:o,...s.error?{error:s.error}:{},assertions:n,specFile:e.specFile,test:t,tests:[r],_testTitle:e.title}})}function $a(e,t){let r=new Date(e.timestamp).getTime(),a=new Date(t.timestamp).getTime();if(r!==a)return r-a;let s={navigation:0,api_call:1},n=s[e.type],o=s[t.type];return n!==o?n-o:e.type==="api_call"&&t.type==="api_call"&&e.callId&&t.callId?rr(e.callId)-rr(t.callId):0}function rr(e){let t=e.match(/(\d+)$/);return t?parseInt(t[1],10):0}function ja(e,t){for(let r=0;r<e.length;r++){let a=e[r];if(a.type!=="navigation")continue;let s=new Date(a.timestamp).getTime(),n=null;for(let o=r+1;o<e.length;o++)if(e[o]._testTitle===a._testTitle){n=new Date(e[o].timestamp).getTime();break}if(n!==null)a.durationOnUrl=Math.max(0,n-s);else {let o=t.find(i=>i.title===a._testTitle);if(o){let i=new Date(o.completedAt).getTime();a.durationOnUrl=Math.max(0,i-s);}}}}function ar(e){if(e==null)return null;try{return JSON.parse(e)}catch{return e}}function Ue(e,t){let r=e.length,a=Math.min(Math.ceil(t/100*r)-1,r-1);return e[Math.max(0,a)]}function Va(e){try{let t=new URL(e);return t.origin+t.pathname}catch{return e}}function Ga(e){return e==null?"error":e>=200&&e<300?"2xx":e>=300&&e<400?"3xx":e>=400&&e<500?"4xx":e>=500&&e<600?"5xx":"error"}function nr(e,t){let r=0,a=0,s=0,n=0,o=0;for(let v of e)switch(v.status){case "passed":r++;break;case "failed":a++;break;case "flaky":s++;break;case "skipped":n++;break;case "timedout":o++;break}let i=[];for(let v of e)v.apiCalls&&i.push(...v.apiCalls);let l=i.length,d=new Set,u={},f={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},m=[];for(let v of i)d.add(Va(v.url)),u[v.method]=(u[v.method]??0)+1,f[Ga(v.responseStatusCode)]+=1,m.push(v.responseTimeMs);let c=null;if(m.length>0){let v=[...m].sort((A,q)=>A-q),k=v.reduce((A,q)=>A+q,0);c={avg:Math.round(k/v.length),min:v[0],max:v[v.length-1],p50:Ue(v,50),p95:Ue(v,95),p99:Ue(v,99)};}let p=0,g=0,h=0;for(let v of e)if(v.apiAssertions)for(let k of v.apiAssertions)p++,k.status==="passed"?g++:h++;let w=0,S=new Set;for(let v of e){w+=v.navigations.length;for(let k of v.navigations)S.add(k.url);}let y=0,b={};function T(v){for(let k of v)y++,b[k.category]=(b[k.category]??0)+1,k.children.length>0&&T(k.children);}for(let v of e)v.actions&&T(v.actions);return {total:e.length,passed:r,failed:a,flaky:s,skipped:n,timedout:o,totalApiCalls:l,uniqueApiUrls:d.size,apiCallsByMethod:u,apiCallsByStatusRange:f,apiResponseTime:c,totalAssertions:p,passedAssertions:g,failedAssertions:h,totalNavigations:w,uniqueNavigationUrls:S.size,totalTimelineSteps:t,totalActionSteps:y,actionStepsByCategory:b}}function Wa(e){let t=56-e.length;return t>0?e+" ".repeat(t):e}function I(e){return `\u2502 ${Wa(e)} \u2502
2555
- `}function ze(e,t,r,a){if(a||e.total===0)return;let s=`\u250C${"\u2500".repeat(58)}\u2510
2554
+ `;appendFileSync(r,n,"utf-8");}catch{}}function pr(t,e){let r=[];for(let a of t){let s=Wa(a),n=Ka(a),o=Ja(a,s,n,e),i=Ya(a,s,n);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:s,tests:[n],_testTitle:a.title});continue}r.push(...o,...i);}return r.sort(Za),Qa(r,t),r.map((a,s)=>a.type==="navigation"?{...{index:s,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:s,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 s=[];for(let n of t.navigations)a.navigationTypes!==null&&!a.navigationTypes.includes(n.navigationType)||s.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 s}function Ya(t,e,r){if(!t.apiCalls||t.apiCalls.length===0)return [];let a=t.apiAssertions??[];return t.apiCalls.map(s=>{let n=a.filter(i=>i.callId===s.id).map(i=>({type:i.type,expected:i.expected,actual:i.actual,status:i.status,location:i.location,...i.expression!==void 0?{expression:i.expression}:{}})),o=null;return s.responseStatusCode!==null&&s.responseStatusText!==null&&(o={statusCode:s.responseStatusCode,statusText:s.responseStatusText,headers:s.responseHeaders,body:ur(s.responseBody)}),{type:"api_call",callId:s.id,method:s.method,url:s.url,timestamp:s.timestamp,responseTime:s.error?null:s.responseTimeMs,request:{headers:s.requestHeaders,body:ur(s.requestBody)},response:o,...s.error?{error:s.error}:{},assertions:n,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 s={navigation:0,api_call:1},n=s[t.type],o=s[e.type];return n!==o?n-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 s=new Date(a.timestamp).getTime(),n=null;for(let o=r+1;o<t.length;o++)if(t[o]._testTitle===a._testTitle){n=new Date(t[o].timestamp).getTime();break}if(n!==null)a.durationOnUrl=Math.max(0,n-s);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-s);}}}}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 es(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,s=0,n=0,o=0;for(let v of t)switch(v.status){case "passed":r++;break;case "failed":a++;break;case "flaky":s++;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},h=[];for(let v of i)d.add(Xa(v.url)),p[v.method]=(p[v.method]??0)+1,f[es(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:s,skipped:n,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 ts(t){let e=56-t.length;return e>0?t+" ".repeat(e):t}function I(t){return `\u2502 ${ts(t)} \u2502
2555
+ `}function je(t,e,r,a){if(a||t.total===0)return;let s=`\u250C${"\u2500".repeat(58)}\u2510
2556
2556
  `,n=`\u2514${"\u2500".repeat(58)}\u2518
2557
- `,o=I(""),i=s;i+=I("TestRelic AI - Playwright Test Report"),i+=o;let l=[];if(e.passed>0&&l.push(`${e.passed} \u2713`),e.failed>0&&l.push(`${e.failed} \u2717`),e.flaky>0&&l.push(`${e.flaky} \u26A0`),e.skipped>0&&l.push(`${e.skipped} skipped`),e.timedout>0&&l.push(`${e.timedout} timedout`),i+=I(`Tests: ${e.total} total (${l.join(" ")})`),e.totalNavigations>0&&(i+=I(`Navigations: ${e.totalNavigations} visits across ${e.uniqueNavigationUrls} unique URLs`)),e.totalApiCalls>0){i+=I(`API Calls: ${e.totalApiCalls} calls across ${e.uniqueApiUrls} unique endpoints`);let d=Object.entries(e.apiCallsByMethod).filter(([,f])=>f>0).map(([f,m])=>`${f}: ${m}`);d.length>0&&(i+=I(` ${d.join(" ")}`));let u=Object.entries(e.apiCallsByStatusRange).filter(([,f])=>f>0).map(([f,m])=>`${f}: ${m}`);u.length>0&&(i+=I(` ${u.join(" ")}`)),e.apiResponseTime&&(i+=I(` Avg response: ${e.apiResponseTime.avg}ms P95: ${e.apiResponseTime.p95}ms`));}if(e.totalAssertions>0&&(i+=I(`Assertions: ${e.totalAssertions} total (${e.passedAssertions} \u2713 ${e.failedAssertions} \u2717)`)),e.totalActionSteps>0){let d=[],u=e.actionStepsByCategory;u.ui_action&&d.push(`${u.ui_action} UI`),u.assertion&&d.push(`${u.assertion} assertions`),u.custom_step&&d.push(`${u.custom_step} custom`);let f=d.length>0?` (${d.join(" ")})`:"";i+=I(`Actions: ${e.totalActionSteps} steps${f}`);}i+=I(`Report: ${r}`),i+=I(`Data: ${t}`),i+=n,i+=`For more information visit us at https://docs.testrelic.ai
2558
- `,process.stderr.write(i);}var Ka=new Set(["pw:api","expect","test.step"]);function Ja(e){return e==="expect"?"assertion":e==="test.step"?"custom_step":"ui_action"}function $e(e,t,r){if(Ka.has(e.category)){let a=[];for(let n of e.steps)$e(n,t,a);let s=e.startTime.getTime()-t.getTime();r.push({title:e.title,category:Ja(e.category),timestamp:e.startTime.toISOString(),duration:e.duration,videoOffset:s>=0?s/1e3:null,status:e.error?"failed":"passed",error:e.error?.message??null,children:a});}else for(let a of e.steps)$e(a,t,r);}function ir(e,t){let r=[];for(let a of e)$e(a,t,r);return r}var Qa=new Set(["localhost","127.0.0.1","0.0.0.0"]);function lr(e){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&Qa.has(t.hostname)))throw createError(ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${t.protocol}//${t.hostname}`)}var Xa=3e3;async function je(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Xa);try{return (await fetch(`${e}/health`,{method:"GET",signal:t.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function dr(e){return new Promise(t=>setTimeout(t,e))}async function or(e){try{let r=(await e.json()).error;if(r&&typeof r.message=="string"){let a=r.details;if(Array.isArray(a)&&a.length>0){let s=a.map(n=>`${n.field}: ${n.message}`).join(", ");return `${r.message} (${s})`}return r.message}}catch{}return `HTTP ${e.status}`}async function Ve(e,t,r){let a=new AbortController,s=setTimeout(()=>a.abort(),r);try{let n=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:a.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 dr(l);let d=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:a.signal});if(d.ok){let u=await d.json();return {accessToken:u.accessToken,refreshToken:u.refreshToken,expiresIn:u.expiresIn,orgId:u.orgId,orgName:u.orgName,userId:u.userId,userName:u.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return n.status===400?{code:"validation_error",message:await or(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 or(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(s);}}function Ge(e){return "code"in e&&typeof e.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(e.code)}async function cr(e,t,r){let a=new AbortController,s=setTimeout(()=>a.abort(),r);try{let n=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:a.signal});if(n.status===429){let i=n.headers.get("Retry-After"),l=i?parseInt(i,10)*1e3:5e3;!isNaN(l)&&l>0&&(await dr(l),n=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:a.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(s);}}async function pr(e,t,r,a,s,n){let o=new AbortController,i=setTimeout(()=>o.abort(),s);try{let l={gitId:r,displayName:a};n&&(l.branch=n);let d=await fetch(`${e}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(l),signal:o.signal});if(!d.ok)return null;let u=await d.json();return {repoId:u.repoId,displayName:u.displayName}}catch{return null}finally{clearTimeout(i);}}var ss=5e3;function D(e,t){try{return execSync(e,{cwd:t,timeout:ss,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function ur(e){let t=D("git rev-parse --abbrev-ref HEAD",e),r=D("git rev-parse --short HEAD",e),a=D("git log -1 --pretty=%s",e),s=D("git log -1 --format=%an",e)??D("git config user.name",e),n=ns(e),o=n?Z(n):null;return {branch:t,commitSha:r,commitMessage:a,commitAuthor:s,remoteUrl:o}}function ns(e){let t=D("git remote get-url origin",e);if(t)return t;let r=D("git remote",e);if(!r)return null;let a=r.split(`
2559
- `)[0]?.trim();return a?D(`git remote get-url ${a}`,e):null}function Z(e){let t=e.trim();return t=t.replace(/^[a-z+]+:\/\//,""),t=t.replace(/^[^@]+@/,""),t=t.replace(/:(?!\d)/,"/"),t=t.replace(/\.git$/,""),t=t.replace(/\/+$/,""),t=t.replace(/^[^@/]+@/,""),t.toLowerCase()}function fr(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function We(e){try{let t=readFileSync(join(e,"package.json"),"utf-8"),r=JSON.parse(t);return typeof r.name=="string"&&r.name.length>0?r.name:null}catch{return null}}function Q(e){let t=We(e);return t||`local/${basename(e)}`}var us=1048576,fs="1.0.0",gr=10;function X(e,t,r,a,s,n,o,i){try{mkdirSync(e,{recursive:!0});let l=Date.now(),d=`${l}-${t}-${r}.json`,u=join(e,d),f={version:fs,queuedAt:new Date(l).toISOString(),reason:a,retryCount:0,targetEndpoint:s,method:n,payload:o,headers:i},m=u+".tmp";writeFileSync(m,JSON.stringify(f,null,2),"utf-8"),renameSync(m,u);}catch(l){l.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
2557
+ `,o=I(""),i=s;i+=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+=I(`Tests: ${t.total} total (${l.join(" ")})`),t.totalNavigations>0&&(i+=I(`Navigations: ${t.totalNavigations} visits across ${t.uniqueNavigationUrls} unique URLs`)),t.totalApiCalls>0){i+=I(`API Calls: ${t.totalApiCalls} calls across ${t.uniqueApiUrls} unique endpoints`);let d=Object.entries(t.apiCallsByMethod).filter(([,f])=>f>0).map(([f,h])=>`${f}: ${h}`);d.length>0&&(i+=I(` ${d.join(" ")}`));let p=Object.entries(t.apiCallsByStatusRange).filter(([,f])=>f>0).map(([f,h])=>`${f}: ${h}`);p.length>0&&(i+=I(` ${p.join(" ")}`)),t.apiResponseTime&&(i+=I(` Avg response: ${t.apiResponseTime.avg}ms P95: ${t.apiResponseTime.p95}ms`));}if(t.totalAssertions>0&&(i+=I(`Assertions: ${t.totalAssertions} total (${t.passedAssertions} \u2713 ${t.failedAssertions} \u2717)`)),t.totalActionSteps>0){let 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+=I(`Actions: ${t.totalActionSteps} steps${f}`);}i+=I(`Report: ${r}`),i+=I(`Data: ${e}`),i+=n,i+=`For more information visit us at https://docs.testrelic.ai
2558
+ `,process.stderr.write(i);}var rs=new Set(["pw:api","expect","test.step"]);function as(t){return t==="expect"?"assertion":t==="test.step"?"custom_step":"ui_action"}function Ve(t,e,r){if(rs.has(t.category)){let a=[];for(let n of t.steps)Ve(n,e,a);let s=t.startTime.getTime()-e.getTime();r.push({title:t.title,category:as(t.category),timestamp:t.startTime.toISOString(),duration:t.duration,videoOffset:s>=0?s/1e3:null,status:t.error?"failed":"passed",error:t.error?.message??null,children: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 is=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:"&&is.has(e.hostname)))throw createError(ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${e.protocol}//${e.hostname}`)}var os=3e3;async function Ge(t){let e=new AbortController,r=setTimeout(()=>e.abort(),os);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 s=a.map(n=>`${n.field}: ${n.message}`).join(", ");return `${r.message} (${s})`}return r.message}}catch{}return `HTTP ${t.status}`}async function We(t,e,r){let a=new AbortController,s=setTimeout(()=>a.abort(),r);try{let n=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:a.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 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 n.status===400?{code:"validation_error",message:await hr(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 hr(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(s);}}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,s=setTimeout(()=>a.abort(),r);try{let n=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:a.signal});if(n.status===429){let i=n.headers.get("Retry-After"),l=i?parseInt(i,10)*1e3:5e3;!isNaN(l)&&l>0&&(await vr(l),n=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:a.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(s);}}async function br(t,e,r,a,s,n){let o=new AbortController,i=setTimeout(()=>o.abort(),s);try{let l={gitId:r,displayName:a};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 ps=5e3;function N(t,e){try{return execSync(t,{cwd:e,timeout:ps,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function xr(t){let e=N("git rev-parse --abbrev-ref HEAD",t),r=N("git rev-parse --short HEAD",t),a=N("git log -1 --pretty=%s",t),s=N("git log -1 --format=%an",t)??N("git config user.name",t),n=fs(t),o=n?Z(n):null;return {branch:e,commitSha:r,commitMessage:a,commitAuthor:s,remoteUrl:o}}function fs(t){let e=N("git remote get-url origin",t);if(e)return e;let r=N("git remote",t);if(!r)return null;let a=r.split(`
2559
+ `)[0]?.trim();return a?N(`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=readFileSync(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/${basename(t)}`}var xs=1048576,ws="1.0.0",kr=10;function X(t,e,r,a,s,n,o,i){try{mkdirSync(t,{recursive:!0});let l=Date.now(),d=`${l}-${e}-${r}.json`,p=join(t,d),f={version:ws,queuedAt:new Date(l).toISOString(),reason:a,retryCount:0,targetEndpoint:s,method:n,payload:o,headers:i},h=p+".tmp";writeFileSync(h,JSON.stringify(f,null,2),"utf-8"),renameSync(h,p);}catch(l){l.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
2560
2560
  `):process.stderr.write(`\u26A0 TestRelic: Unable to queue upload data.
2561
- `);}}async function vr(e,t,r){let a;try{a=readdirSync(e).filter(n=>n.endsWith(".json")&&!n.endsWith(".tmp")).sort();}catch{return}if(a.length===0)return;let s=[];for(let n=0;n<a.length;n+=gr)s.push(a.slice(n,n+gr));for(let n of s)for(let o of n){let i=join(e,o);try{if(!statSync(i).isFile())continue;let d=readFileSync(i,"utf-8"),u=JSON.parse(d);if(!isValidQueueEntry(u)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${o}
2562
- `),unlinkSync(i);continue}let f=u,m=JSON.stringify(f.payload),c={...f.headers,Authorization:`Bearer ${r}`},p=m;if(Buffer.byteLength(m,"utf-8")>us&&(p=gzipSync(Buffer.from(m,"utf-8")),c["Content-Encoding"]="gzip"),(await fetch(f.targetEndpoint,{method:f.method,headers:c,body:p})).ok)unlinkSync(i);else return}catch{return}}}function yr(e,t){try{let r=readdirSync(e).filter(s=>s.endsWith(".json")&&!s.endsWith(".tmp")),a=Date.now();for(let s of r){let n=join(e,s);try{let o=readFileSync(n,"utf-8"),l=JSON.parse(o).queuedAt;if(typeof l=="string"){let d=new Date(l).getTime();a-d>t&&unlinkSync(n);}}catch{try{unlinkSync(n);}catch{}}}}catch{}}var xs=3e5,ws=864e5,ks=6e4,br=3e4,Ye="https://platform.testrelic.ai/settings/api-keys",de=class{constructor(t){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=t,this.authState={mode:"pending",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null};}async initialize(){if(!this.config||!this.config.apiKey){this.setLocalMode("no_api_key"),process.stderr.write(`\u2139 TestRelic: No API key configured. Running in local mode.
2563
- `);return}try{if(lr(this.config.endpoint),this.gitMetadata=ur(),!await je(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 Ve(this.config.endpoint,this.config.apiKey,this.config.timeout);if(Ge(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&&(yr(this.config.queueDirectory,this.config.queueMaxAge),this.startBackgroundFlush()),this.startHealthCheck();}catch(t){this.setLocalMode("unexpected_error"),process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. Running in local mode. ${t instanceof Error?t.message:String(t)}
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 t=this.authState.expiresAt??0;if(Date.now()+xs<t)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await cr(this.config.endpoint,this.authState.refreshToken,this.config.timeout);return r?(this.authState.accessToken=r.accessToken,this.authState.refreshToken=r.refreshToken,this.authState.expiresAt=Date.now()+r.expiresIn*1e3,!0):(this.switchToLocalMode("token_refresh_failed"),!1)}catch{return this.switchToLocalMode("token_refresh_error"),false}}switchToLocalMode(t){this.authState.mode!=="local"&&(this.authState.mode="local",this.failureReason=t,process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${t}).
2567
- `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,new Promise(t=>setTimeout(t,br))]);}catch{}this.flushPromise=null;}this.authState={mode:"local",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null},this.repoId=null,this.gitMetadata=null;}setLocalMode(t){this.authState.mode="local",this.failureReason=t;}handleAuthError(t,r){switch(t){case "invalid_key":this.setLocalMode("invalid_api_key"),process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
2568
- \u2192 Manage keys: ${Ye}
2561
+ `);}}async function Cr(t,e,r){let a;try{a=readdirSync(t).filter(n=>n.endsWith(".json")&&!n.endsWith(".tmp")).sort();}catch{return}if(a.length===0)return;let s=[];for(let n=0;n<a.length;n+=kr)s.push(a.slice(n,n+kr));for(let n of s)for(let o of n){let i=join(t,o);try{if(!statSync(i).isFile())continue;let d=readFileSync(i,"utf-8"),p=JSON.parse(d);if(!isValidQueueEntry(p)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${o}
2562
+ `),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")>xs&&(u=gzipSync(Buffer.from(h,"utf-8")),c["Content-Encoding"]="gzip"),(await fetch(f.targetEndpoint,{method:f.method,headers:c,body:u})).ok)unlinkSync(i);else return}catch{return}}}function Rr(t,e){try{let r=readdirSync(t).filter(s=>s.endsWith(".json")&&!s.endsWith(".tmp")),a=Date.now();for(let s of r){let n=join(t,s);try{let o=readFileSync(n,"utf-8"),l=JSON.parse(o).queuedAt;if(typeof l=="string"){let d=new Date(l).getTime();a-d>e&&unlinkSync(n);}}catch{try{unlinkSync(n);}catch{}}}}catch{}}var _s=3e5,Is=864e5,Ls=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()+_s<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}
2569
2569
  `);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: ${Ye}
2570
+ \u2192 Generate a new key: ${Qe}
2571
2571
  `);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: ${Ye}
2572
+ \u2192 Manage keys: ${Qe}
2573
2573
  `);break;case "rate_limited":this.setLocalMode("rate_limited"),process.stderr.write(`\u26A0 TestRelic: Rate limited during authentication. Running in local mode.
2574
2574
  `);break;case "timeout":this.setLocalMode("auth_timeout"),process.stderr.write(`\u26A0 TestRelic: Authentication timed out. Running in local mode.
2575
2575
  `);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 t=this.gitMetadata?.remoteUrl?Z(this.gitMetadata.remoteUrl):null,r=t?fr(t):this.config.projectName??Q(process.cwd()),a=t??this.config.projectName??Q(process.cwd()),s=this.readRepoCache(a);if(s){this.repoId=s.repoId;return}try{let n=await pr(this.config.endpoint,this.authState.accessToken,a,r,this.config.timeout,this.gitMetadata?.branch);n&&(this.repoId=n.repoId,this.writeRepoCache(a,n.repoId,n.displayName));}catch{}!t&&!this.config.projectName&&!We(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(t){if(!this.config)return null;let r=join(this.config.queueDirectory,"..","cache","repo.json");try{if(!existsSync(r))return null;let a=readFileSync(r,"utf-8"),s=JSON.parse(a);if(s.gitId!==t||Date.now()-s.resolvedAt>ws)return null;let n=this.hashApiKey();return n&&s.apiKeyHash!==n?null:s}catch{return null}}writeRepoCache(t,r,a){if(!this.config)return;let s=join(this.config.queueDirectory,"..","cache"),n=join(s,"repo.json");try{mkdirSync(s,{recursive:!0});let o={repoId:r,gitId:t,displayName:a,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=n+".tmp";writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),renameSync(i,n);}catch{}}hashApiKey(){return this.config?.apiKey?createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let t=this.authState.accessToken,r=this.config.queueDirectory,a=this.config.endpoint;this.flushPromise=Promise.race([vr(r,a,t),new Promise(s=>setTimeout(s,br))]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let t=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await je(t))return;if(this.config?.apiKey){let a=await Ve(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!Ge(a)){let s=a;this.authState={mode:"cloud",accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:Date.now()+s.expiresIn*1e3,orgId:s.orgId,orgName:s.orgName,userId:s.userId,userName:s.userName},this.failureReason=null,process.stderr.write(`\u2713 TestRelic: Cloud connectivity restored.
2578
- `),this.startBackgroundFlush();}}}catch{}},ks);}};var Ts=new Set(["smoke","regression","nightly","ci"]);function ce(){let e=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(e&&Ts.has(e))return e}var Cs=1048576,pe=[1e3,3e3,9e3],ue=3,Rs=40*1048576,As=new Set(["e2e","mobile","unit"]);function Ze(e){if(e&&e.length>0&&e.every(s=>s.testType==="api")){let s=new Map;for(let i of e){let l=i.apiProtocol??"rest";s.set(l,(s.get(l)??0)+1);}let n="rest",o=0;for(let[i,l]of s)l>o&&(o=l,n=i);return {testType:"api",apiProtocol:n,metadata:{testType:"api",primaryProtocol:n}}}let t=new Map;for(let s of e??[])As.has(s.testType)&&t.set(s.testType,(t.get(s.testType)??0)+1);let r=null,a=0;for(let[s,n]of t)n>a&&(a=n,r=s);return {testType:r??"e2e"}}function Qe(e,t,r,a,s,n){let o=n?.cloudPlatform?n.cloudPlatform:a?.provider&&a.provider!=="unknown"?a.provider:"local",i=ce(),l=Ze(s),d=l.testType==="api"?l:null,u=d&&s?s.map(m=>m.apiProtocol?m:{...m,apiProtocol:d.apiProtocol}):s,f={runId:e.testRunId,repoGitId:t,startedAt:e.startedAt,summary:e.summary,timeline:e.timeline,environment:o,...i?{runType:i}:{},...d?{testType:d.testType,apiProtocol:d.apiProtocol,metadata:d.metadata}:{testType:l.testType},...u&&u.length>0?{tests:u}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...e.completedAt?{finishedAt:e.completedAt}:{},...e.totalDuration?{duration:e.totalDuration}:{},...a?.provider?{ciProvider:a.provider}:{},...a?.runUrl?{ciRunUrl:a.runUrl}:{},...n?.cloudPlatform?{cloudPlatform:n.cloudPlatform}:{},...n?.cloudBuildId?{cloudBuildId:n.cloudBuildId}:{},...n?.cloudSessionId?{cloudSessionId:n.cloudSessionId}:{}};if(f.tests&&f.tests.length>0){let m=JSON.stringify(f);if(Buffer.byteLength(m,"utf-8")>Rs){let c=f.tests.map(({consoleLogs:p,networkRequests:g,...h})=>h);return {...f,tests:c}}}return f}async function fe(e){return new Promise(t=>setTimeout(t,e))}function _s(e){let t={};for(let[r,a]of Object.entries(e))a!=null&&(t[r]=a);return t}async function xr(e,t,r){for(let a=0;a<ue;a++)try{let s=await fetch(e,t);if(s.ok)return s;if(s.status===401&&r&&a===0){let n=await r();if(n){let o={...t,headers:{...t.headers,Authorization:`Bearer ${n}`}},i=await fetch(e,o);if(i.ok)return i}return null}if(s.status===429&&a<ue-1){let n=s.headers.get("Retry-After"),o=n?parseInt(n,10)*1e3:pe[a];!isNaN(o)&&o>0?await fe(o):await fe(pe[a]);continue}if(s.status>=500&&a<ue-1){await fe(pe[a]);continue}return s}catch{if(a<ue-1){await fe(pe[a]);continue}return null}return null}function Is(e){let t=JSON.stringify(e),r={"Content-Type":"application/json"};if(Buffer.byteLength(t,"utf-8")>Cs){let a=gzipSync(Buffer.from(t,"utf-8"));return r["Content-Encoding"]="gzip",{body:a,headers:r}}return {body:t,headers:r}}async function wr(e,t,r,a){let s=`${e}/runs`,{body:n,headers:o}=Is(r);o.Authorization=`Bearer ${t}`;let i=await xr(s,{method:"POST",headers:o,body:n},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:s,method:"POST"}}async function kr(e,t,r){let a=`${e}/runs/init`;try{let s=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(_s(r))});return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function Tr(e,t,r,a){let s=`${e}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a)}).catch(()=>{});}async function Sr(e,t,r,a){let s=`${e}/runs/${r}/finalize`;return (await xr(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(a)}))?.ok??false}function Xe(e,t,r,a){let s=`${e}/runs/${r}/finalize`,n=new Date,o={finishedAt:n.toISOString(),duration:n.getTime()-new Date(a).getTime(),summary:{}};fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(o)}).catch(()=>{});}function Cr(e,t,r,a){let s=[],n=[],o=null,i=0,l=null,d=0,u=null,f=0,m=e.filter(g=>g.name===ATTACHMENT_NAME&&g.body),c=false;if(m.length>0)for(let g of m)try{let h=JSON.parse(g.body.toString());if(isTestRelicFilePayload(h)){s=s.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&&(u=h.apiCallsFile,f+=h.apiCallsCount),c=!0;continue}if(isTestRelicDataPayload(h)){s=s.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}"
2579
- `);}return c||(s=t.filter(g=>g.type==="lambdatest-navigation"&&g.description).map(g=>{try{return JSON.parse(g.description)}catch{return null}}).filter(g=>g!==null)),s.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 timeline data cannot be captured.
2580
- `),{navigations:s,apiAssertions:n,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:l,consoleLogsCount:d,apiCallsFile:u,apiCallsCount:f}}function ge(e=process.env){let t=Ps(e.TESTRELIC_CLOUD_PLATFORM);if(t)return {cloudPlatform:t,cloudBuildId:e.TESTRELIC_CLOUD_BUILD_ID||void 0,cloudSessionId:e.TESTRELIC_CLOUD_SESSION_ID||void 0};if(e.BROWSERSTACK_USERNAME||e.BROWSERSTACK_ACCESS_KEY)return {cloudPlatform:"browserstack",cloudBuildId:e.BROWSERSTACK_BUILD_NAME||e.BROWSERSTACK_BUILD_ID||void 0,cloudSessionId:e.BROWSERSTACK_SESSION_ID||void 0};if(e.LT_USERNAME||e.LAMBDATEST_USERNAME||e.LT_ACCESS_KEY||e.LAMBDATEST_ACCESS_KEY)return {cloudPlatform:"lambdatest",cloudBuildId:e.LT_BUILD||e.LAMBDATEST_BUILD||void 0,cloudSessionId:e.LT_SESSION_ID||e.LAMBDATEST_SESSION_ID||void 0};let r=e.PLAYWRIGHT_WS_ENDPOINT;if(r){if(/cdp\.lambdatest\.com/i.test(r))return {cloudPlatform:"lambdatest"};if(/cdp\.browserstack\.com/i.test(r))return {cloudPlatform:"browserstack"}}return {}}function Ps(e){if(!e)return;let t=e.toLowerCase().trim();if(t==="browserstack"||t==="bs")return "browserstack";if(t==="lambdatest"||t==="lt")return "lambdatest"}var Os=5,he=[1e3,3e3,9e3],U=3,qs={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip"},et=0,tt=[];async function Hs(){et>=Os&&await new Promise(e=>tt.push(e)),et++;}function Us(){et--,tt.length>0&&tt.shift()();}async function me(e){return new Promise(t=>setTimeout(t,e))}function zs(e){let t=e.substring(e.lastIndexOf(".")).toLowerCase();return qs[t]??"application/octet-stream"}function $s(e){try{return statSync(e).size}catch{return 0}}async function js(e,t,r,a,s){let n=`${e}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:basename(r.filePath),contentType:s,type:r.type,sizeBytes:a});for(let i=0;i<U;i++)try{let l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:o});if(l.ok)return await l.json();if(l.status>=500&&i<U-1){await me(he[i]);continue}return null}catch{if(i<U-1){await me(he[i]);continue}return null}return null}async function Vs(e,t,r,a){for(let s=0;s<U;s++)try{let n=createReadStream(t),o=Readable.toWeb(n),i=await fetch(e,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(a)},body:o,duplex:"half"});if(i.ok)return !0;if(i.status>=500&&s<U-1){await me(he[s]);continue}return !1}catch{if(s<U-1){await me(he[s]);continue}return false}return false}async function Gs(e,t,r){let a=`${e}/artifacts/confirm`;try{return (await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({artifactId:r})})).ok}catch{return false}}async function Ws(e,t,r,a){let s=$s(r.filePath);if(s===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(s>a*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let n=zs(r.filePath);await Hs();try{let o=await js(e,t,r,s,n);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await Vs(o.uploadUrl,r.filePath,n,s))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let l=await Gs(e,t,o.artifactId);return {success:l,storageKey:o.storageKey,artifactId:o.artifactId,error:l?null:"confirm_failed"}}finally{Us();}}async function Rr(e,t,r,a){let s=new Map,n=r.map(async o=>{let i=await Ws(e,t,o,a);s.set(o.filePath,i);});return await Promise.allSettled(n),s}function rt(e){let r=e.getGitMetadata()?.remoteUrl;return r?Z(r):e.getConfig()?.projectName??Q(process.cwd())}async function _r(e,t,r,a,s){if(!e.isCloudMode()||t!=="realtime"&&t!=="both"||!await e.ensureValidToken())return null;let o=e.getGitMetadata(),i=P(),l=ge(),d=ce();return (await kr(e.getEndpoint(),e.getAccessToken(),{runId:r,repoGitId:rt(e),branch:o?.branch??null,commit:o?.commitSha??null,commitMessage:o?.commitMessage??null,commitAuthor:o?.commitAuthor??null,startedAt:a,totalTests:null,ciProvider:i?.provider??null,ciRunUrl:i?.runUrl??null,environment:s??l.cloudPlatform??null,cloudPlatform:l.cloudPlatform??null,cloudBuildId:l.cloudBuildId??null,cloudSessionId:l.cloudSessionId??null,...d?{runType:d}:{},testType:"e2e"}))?.runId??null}var Ks=true,Js=50;async function Ys(e,t,r,a){let s=new Map;if(!(t?.uploadArtifacts??Ks)||!await e.ensureValidToken())return s;let i=[],l=new Map;for(let c of a){if(c.artifacts.screenshot){let p=join(c.outputDir,c.artifacts.screenshot);i.push({filePath:p,runId:r,testId:c.testId,type:"screenshot"}),l.set(p,{testId:c.testId,field:"screenshot"});}if(c.artifacts.video){let p=join(c.outputDir,c.artifacts.video);i.push({filePath:p,runId:r,testId:c.testId,type:"video"}),l.set(p,{testId:c.testId,field:"video"});}}if(i.length===0)return s;let d=t?.artifactMaxSizeMb??Js,u=await Rr(e.getEndpoint(),e.getAccessToken(),i,d),f=new Map;for(let[c,p]of u){if(!p.success||!p.storageKey)continue;let g=l.get(c);if(!g)continue;let h=f.get(g.testId)??{};g.field==="screenshot"&&(h.screenshotKey=p.storageKey),g.field==="video"&&(h.videoKey=p.storageKey),f.set(g.testId,h);}for(let c of a){let p=f.get(c.testId);s.set(c.testId,{...c.artifacts,...p?.screenshotKey?{screenshotKey:p.screenshotKey}:{},...p?.videoKey?{videoKey:p.videoKey}:{}});}let m=Array.from(u.values()).filter(c=>c.success).length;return m>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${m} artifact(s) to cloud storage.
2581
- `),s}async function at(e,t,r,a,s,n,o,i,l,d,u){try{if(e.isCloudMode()&&s&&(r==="realtime"||r==="both")){let m=await e.ensureValidToken(),c=e.getGitMetadata(),p=Ze(u),g={finishedAt:o,duration:i,summary:l,...c?.commitMessage?{commitMessage:c.commitMessage}:{},testType:p.testType,...p.testType==="api"?{apiProtocol:p.apiProtocol,metadata:p.metadata}:{}};if(m){if(!await Sr(e.getEndpoint(),e.getAccessToken(),s,g)){let w=t?.queueDirectory??".testrelic/queue";X(w,a,"finalize","finalize_failed_after_retries",`${e.getEndpoint()}/runs/${s}/finalize`,"POST",g,{"Content-Type":"application/json"});}}else {let h=t?.queueDirectory??".testrelic/queue";X(h,a,"finalize",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs/${s}/finalize`,"POST",g,{"Content-Type":"application/json"});}}let f=new Map;if(e.isCloudMode()&&d&&d.length>0&&(f=await Ys(e,t,a,d)),e.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await e.ensureValidToken()){let c=e.getGitMetadata(),p=P(),g=rt(e),h=Zs(n,f),w=Qe(h,g,c,p,u,ge()),S=await wr(e.getEndpoint(),e.getAccessToken(),w,async()=>await e.ensureValidToken()?e.getAccessToken():null);if(!S.success){let y=S,b=t?.queueDirectory??".testrelic/queue";X(b,a,"batch",y.reason,y.targetEndpoint,y.method,y.payload,{"Content-Type":"application/json"});}}else {let c=t?.queueDirectory??".testrelic/queue",p=e.getGitMetadata(),g=P(),h=rt(e),w=Qe(n,h,p,g,void 0,ge());X(c,a,"batch",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs`,"POST",w,{"Content-Type":"application/json"});}await e.dispose();}catch{try{await e.dispose();}catch{}}}function Zs(e,t){if(t.size===0)return e;let r=e.timeline.map(a=>{let s=a.testId;if(!s)return a;let n=t.get(s);return n?{...a,...n.screenshotKey?{screenshotKey:n.screenshotKey}:{},...n.videoKey?{videoKey:n.videoKey}:{}}:a});return {...e,timeline:r}}function z(e){try{return readFileSync(e,"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 nt(e){switch(e){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function sn(e,t,r){let a=`${e}::${t}::${r}`;return createHash("sha256").update(a).digest("hex").substring(0,16)}function nn(e){return e.length<=3?"":e[e.length-2]}function on(e){let t=e.findIndex(r=>r.status==="passed");return t>0?`passed on retry ${t}`:null}function ln(e){return process.env.BROWSERSTACK_USERNAME?"BrowserStack":e?{"github-actions":"GitHub Actions","gitlab-ci":"GitLab CI",jenkins:"Jenkins",circleci:"CircleCI","bitbucket-pipelines":"Bitbucket Pipelines"}[e.provider]??"CI":"Local"}function dn(){let e=platform();return e==="win32"?"Windows":e==="darwin"?"macOS":"Linux"}function cn(e){let t=e.parent?.project?.()?.use;if(!t)return;let{browserName:r,channel:a}=t;if(a){let n=a.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":a}if(r){let n=r.toLowerCase();return n==="chromium"?"Chromium":n==="firefox"?"Firefox":n==="webkit"?"WebKit":r}let s=t.defaultBrowserType;if(s){let n=s.toLowerCase();return n==="chromium"?"Chromium":n==="firefox"?"Firefox":n==="webkit"?"WebKit":s}}function pn(e,t,r){let a=r.parent?.project?.(),s="unknown";a!==void 0&&(a.use.isMobile===true?s="mobile":s="e2e");let n=["e2e","api","unit","mobile"];for(let l of n)if(e.some(d=>d===`@${l}`||d===l))return l;let o=t.replace(/\\/g,"/"),i=["e2e","api","unit"];for(let l of i)if(o.includes(`/${l}/`))return l;return s}var un="__testrelic_api_config";function fn(e){return JSON.stringify(e,(t,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var ve=class{constructor(t){this.rootDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=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=wt(t),this.apiConfig=xt(t);}async onBegin(t,r){try{if(this.rootDir=t.rootDir,this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??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 a=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${a} tests)
2583
- `),this.activeReportMode==="streaming"){let n=dirname(this.config.outputPath);this.streamingWriter=new G(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&&Xe(this.cloudClient.getEndpoint(),i,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",o),process.on("SIGINT",o);}if(this.config.includeArtifacts){let n=dirname(this.config.outputPath);this.runTimestamp=Yt(join(n,"artifacts"));try{tr(join(n,"artifacts"));}catch{}}let s=P();this.detectedOs=dn(),this.detectedSource=ln(s);try{this.cloudClient=new de(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&&Xe(this.cloudClient.getEndpoint(),o,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",n),process.on("SIGINT",n);}}catch{}}onTestBegin(t,r){try{t.annotations.push({type:un,description:fn(this.apiConfig)});}catch{}}onTestEnd(t,r){try{let a=r,s=t.outcome(),n;s==="flaky"?n="flaky":s==="skipped"?n="skipped":n=nt(a.status);let o=a.startTime.toISOString(),i=new Date(a.startTime.getTime()+a.duration).toISOString(),l=t.tags?[...t.tags]:t.annotations.filter(R=>R.type==="tag").map(R=>R.description??""),d=Cr(a.attachments,t.annotations,t.title,n==="skipped");(d.navigations.length>0||d.networkRequestsCount>0||d.apiCallsCount>0)&&(this.fixtureDataReceived=!0);let u=null;if(n==="failed"||n==="flaky"){let C=(n==="flaky"?t.results.find(B=>B.status!=="passed")?.errors??[]:a.errors)[0];if(C){let B=Tt(this.config.redactPatterns),$=C.location?.line??null,j=null;this.config.includeCodeSnippets&&$!==null&&C.location?.file&&(j=kt(C.location.file,$,this.config.codeContextLines),j&&(j=B(j))),u={message:B(C.message??"Unknown error"),line:$,code:j,stack:this.config.includeStackTrace&&C.stack?B(C.stack):null};}}let f=t.titlePath().filter(Boolean),m=relative(this.rootDir||".",t.location.file),c=nn(f),p=f.join(" > "),g=m,h=sn(g,c,p),w=pn(l,g,t),S=w!=="mobile"&&d.apiCallsCount>0?"api":w,y=s==="flaky",b=on(t.results),T=nt(t.expectedStatus),v=nt(a.status),k=null;if(this.config.includeArtifacts&&n!=="skipped"&&a.attachments){let R=dirname(this.config.outputPath),C=f[f.length-1]??t.title;k=Zt(a.attachments,C,a.retry,R,this.runTimestamp||void 0);}let A=this.config.includeActionSteps&&a.steps?ir(a.steps,a.startTime):null,q=cn(t),M={titlePath:f,title:p,status:n,duration:a.duration,startedAt:o,completedAt:i,retryCount:t.results.length-1,retry:a.retry,tags:l,failure:u,specFile:m,navigations:d.navigations,testId:h,filePath:g,suiteName:c,testType:S,isFlaky:y,retryStatus:b,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:q,os:this.detectedOs||void 0,source:this.detectedSource||void 0},it=d.consoleLogsFile&&d.consoleLogsCount>0?z(d.consoleLogsFile):void 0,ot=d.networkRequestsFile&&d.networkRequestsCount>0?z(d.networkRequestsFile):void 0;this.cloudTestsBuffer.push({testId:h,title:p,status:n,duration:a.duration,suiteName:c,filePath:g,testType:S,isFlaky:y,startedAt:o,completedAt:i,tags:l,failure:u,retry:a.retry,retryCount:t.results.length-1,retryStatus:b,browser:q,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...A&&A.length>0?{actions:A}:{},...it?{consoleLogs:it}:{},...ot?{networkRequests:ot}:{}});try{let R=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(R==="realtime"||R==="both")){let C=this.cloudClient.getAccessToken();C&&Tr(this.cloudClient.getEndpoint(),C,this.cloudRunId,this.buildCloudTestPayload(M));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let R=ye(g,f,t.id??"",a.retry),C=a.retry===t.results.length-1,B={id:R,navigations:d.navigations,apiAssertions:d.apiAssertions,actions:A??[],artifacts:k,failureDiagnostic:u,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]??t.title,titlePath:f,filePath:g,status:n,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:u?.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++,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}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:h,artifacts:k,outputDir: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(t){try{let r=new Date().toISOString(),a=new Date(this.startedAt).getTime(),n=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(`
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()),s=this.readRepoCache(a);if(s){this.repoId=s.repoId;return}try{let n=await br(this.config.endpoint,this.authState.accessToken,a,r,this.config.timeout,this.gitMetadata?.branch);n&&(this.repoId=n.repoId,this.writeRepoCache(a,n.repoId,n.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=join(this.config.queueDirectory,"..","cache","repo.json");try{if(!existsSync(r))return null;let a=readFileSync(r,"utf-8"),s=JSON.parse(a);if(s.gitId!==e||Date.now()-s.resolvedAt>Is)return null;let n=this.hashApiKey();return n&&s.apiKeyHash!==n?null:s}catch{return null}}writeRepoCache(e,r,a){if(!this.config)return;let s=join(this.config.queueDirectory,"..","cache"),n=join(s,"repo.json");try{mkdirSync(s,{recursive:!0});let o={repoId:r,gitId:e,displayName:a,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=n+".tmp";writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),renameSync(i,n);}catch{}}hashApiKey(){return this.config?.apiKey?createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let e=this.authState.accessToken,r=this.config.queueDirectory,a=this.config.endpoint;this.flushPromise=Promise.race([Cr(r,a,e),new Promise(s=>setTimeout(s,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 s=a;this.authState={mode:"cloud",accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:Date.now()+s.expiresIn*1e3,orgId:s.orgId,orgName:s.orgName,userId:s.userId,userName:s.userName},this.failureReason=null,process.stderr.write(`\u2713 TestRelic: Cloud connectivity restored.
2578
+ `),this.startBackgroundFlush();}}}catch{}},Ls);}};var Ms=new Set(["smoke","regression","nightly","ci"]);function ue(){let t=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(t&&Ms.has(t))return t}var Ps=1048576,pe=[1e3,3e3,9e3],fe=3,Fs=40*1048576,Ns=new Set(["e2e","mobile","unit"]);function et(t){if(t&&t.length>0&&t.every(s=>s.testType==="api")){let s=new Map;for(let i of t){let l=i.apiProtocol??"rest";s.set(l,(s.get(l)??0)+1);}let n="rest",o=0;for(let[i,l]of s)l>o&&(o=l,n=i);return {testType:"api",apiProtocol:n,metadata:{testType:"api",primaryProtocol:n}}}let e=new Map;for(let s of t??[])Ns.has(s.testType)&&e.set(s.testType,(e.get(s.testType)??0)+1);let r=null,a=0;for(let[s,n]of e)n>a&&(a=n,r=s);return {testType:r??"e2e"}}function tt(t,e,r,a,s,n){let o=n?.cloudPlatform?n.cloudPlatform:a?.provider&&a.provider!=="unknown"?a.provider:"local",i=ue(),l=et(s),d=l.testType==="api"?l:null,p=d&&s?s.map(h=>h.apiProtocol?h:{...h,apiProtocol:d.apiProtocol}):s,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}:{},...n?.cloudPlatform?{cloudPlatform:n.cloudPlatform}:{},...n?.cloudBuildId?{cloudBuildId:n.cloudBuildId}:{},...n?.cloudSessionId?{cloudSessionId:n.cloudSessionId}:{}};if(f.tests&&f.tests.length>0){let h=JSON.stringify(f);if(Buffer.byteLength(h,"utf-8")>Fs){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.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}}):[]}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 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 a=r.status==="failed"?"failed":"passed",s=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,n=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 {kind:n,description:s??r.description??`${n} assertion`,status:a,detail:o}})}async function ge(t){return new Promise(e=>setTimeout(e,t))}function Ds(t){let e={};for(let[r,a]of Object.entries(t))a!=null&&(e[r]=a);return e}async function _r(t,e,r){for(let a=0;a<fe;a++)try{let s=await fetch(t,e);if(s.ok)return s;if(s.status===401&&r&&a===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(s.status===429&&a<fe-1){let n=s.headers.get("Retry-After"),o=n?parseInt(n,10)*1e3:pe[a];!isNaN(o)&&o>0?await ge(o):await ge(pe[a]);continue}if(s.status>=500&&a<fe-1){await ge(pe[a]);continue}return s}catch{if(a<fe-1){await ge(pe[a]);continue}return null}return null}function Bs(t){let e=JSON.stringify(t),r={"Content-Type":"application/json"};if(Buffer.byteLength(e,"utf-8")>Ps){let a=gzipSync(Buffer.from(e,"utf-8"));return r["Content-Encoding"]="gzip",{body:a,headers:r}}return {body:e,headers:r}}async function Ir(t,e,r,a){let s=`${t}/runs`,{body:n,headers:o}=Bs(r);o.Authorization=`Bearer ${e}`;let i=await _r(s,{method:"POST",headers:o,body:n},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:s,method:"POST"}}async function Lr(t,e,r){let a=`${t}/runs/init`;try{let s=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(Ds(r))});return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function Mr(t,e,r,a){let s=`${t}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(a)}).catch(()=>{});}async function Er(t,e,r,a){let s=`${t}/runs/${r}/finalize`;return (await _r(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(a)}))?.ok??false}function nt(t,e,r,a){let s=`${t}/runs/${r}/finalize`,n=new Date,o={finishedAt:n.toISOString(),duration:n.getTime()-new Date(a).getTime(),summary:{}};fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}).catch(()=>{});}function Pr(t,e,r,a){let s=[],n=[],o=null,i=0,l=null,d=0,p=null,f=0,h=t.filter(g=>g.name===ATTACHMENT_NAME&&g.body),c=false;if(h.length>0)for(let g of h)try{let m=JSON.parse(g.body.toString());if(isTestRelicFilePayload(m)){s=s.concat(m.navigations),n=n.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(isTestRelicDataPayload(m)){s=s.concat(m.navigations),Array.isArray(m.apiAssertions)&&(n=n.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||(s=e.filter(g=>g.type==="lambdatest-navigation"&&g.description).map(g=>{try{return JSON.parse(g.description)}catch{return null}}).filter(g=>g!==null)),s.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 timeline data cannot be captured.
2580
+ `),{navigations:s,apiAssertions:n,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:l,consoleLogsCount:d,apiCallsFile:p,apiCallsCount:f}}function he(t=process.env){let e=Us(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 Us(t){if(!t)return;let e=t.toLowerCase().trim();if(e==="browserstack"||e==="bs")return "browserstack";if(e==="lambdatest"||e==="lt")return "lambdatest"}var Gs=5,me=[1e3,3e3,9e3],z=3,Ws={".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 Ks(){it>=Gs&&await new Promise(t=>ot.push(t)),it++;}function Js(){it--,ot.length>0&&ot.shift()();}async function ve(t){return new Promise(e=>setTimeout(e,t))}function Ys(t){let e=t.substring(t.lastIndexOf(".")).toLowerCase();return Ws[e]??"application/octet-stream"}function Zs(t){try{return statSync(t).size}catch{return 0}}async function Qs(t,e,r,a,s){let n=`${t}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:basename(r.filePath),contentType:s,type:r.type,sizeBytes:a});for(let i=0;i<z;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<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 Xs(t,e,r,a){for(let s=0;s<z;s++)try{let n=createReadStream(e),o=Readable.toWeb(n),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&&s<z-1){await ve(me[s]);continue}return !1}catch{if(s<z-1){await ve(me[s]);continue}return false}return false}async function en(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 tn(t,e,r,a){let s=Zs(r.filePath);if(s===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(s>a*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let n=Ys(r.filePath);await Ks();try{let o=await Qs(t,e,r,s,n);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await Xs(o.uploadUrl,r.filePath,n,s))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let l=await en(t,e,o.artifactId);return {success:l,storageKey:o.storageKey,artifactId:o.artifactId,error:l?null:"confirm_failed"}}finally{Js();}}async function Fr(t,e,r,a){let s=new Map,n=r.map(async o=>{let i=await tn(t,e,o,a);s.set(o.filePath,i);});return await Promise.allSettled(n),s}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,s){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:s??l.cloudPlatform??null,cloudPlatform:l.cloudPlatform??null,cloudBuildId:l.cloudBuildId??null,cloudSessionId:l.cloudSessionId??null,...d?{runType:d}:{},testType:"e2e"}))?.runId??null}var rn=true,an=50;async function sn(t,e,r,a){let s=new Map;if(!(e?.uploadArtifacts??rn)||!await t.ensureValidToken())return s;let i=[],l=new Map;for(let c of a){if(c.artifacts.screenshot){let u=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=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 s;let d=e?.artifactMaxSizeMb??an,p=await Fr(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);s.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
+ `),s}async function dt(t,e,r,a,s,n,o,i,l,d,p){try{if(t.isCloudMode()&&s&&(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(),s,g)){let b=e?.queueDirectory??".testrelic/queue";X(b,a,"finalize","finalize_failed_after_retries",`${t.getEndpoint()}/runs/${s}/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/${s}/finalize`,"POST",g,{"Content-Type":"application/json"});}}let f=new Map;if(t.isCloudMode()&&d&&d.length>0&&(f=await sn(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=nn(n,f),b=tt(m,g,c,u,p,he()),S=await Ir(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(n,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 nn(t,e){if(e.size===0)return t;let r=t.timeline.map(a=>{let s=a.testId;if(!s)return a;let n=e.get(s);return n?{...a,...n.screenshotKey?{screenshotKey:n.screenshotKey}:{},...n.videoKey?{videoKey:n.videoKey}:{}}:a});return {...t,timeline:r}}function q(t){try{return 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 fn(t,e,r){let a=`${t}::${e}::${r}`;return createHash("sha256").update(a).digest("hex").substring(0,16)}function gn(t){return t.length<=3?"":t[t.length-2]}function hn(t){let e=t.findIndex(r=>r.status==="passed");return e>0?`passed on retry ${e}`:null}function mn(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 vn(){let t=platform();return t==="win32"?"Windows":t==="darwin"?"macOS":"Linux"}function yn(t){let e=t.parent?.project?.()?.use;if(!e)return;let{browserName:r,channel:a}=e;if(a){let n=a.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":a}if(r){let n=r.toLowerCase();return n==="chromium"?"Chromium":n==="firefox"?"Firefox":n==="webkit"?"WebKit":r}let s=e.defaultBrowserType;if(s){let n=s.toLowerCase();return n==="chromium"?"Chromium":n==="firefox"?"Firefox":n==="webkit"?"WebKit":s}}function bn(t,e,r){let a=r.parent?.project?.(),s="unknown";a!==void 0&&(a.use.isMobile===true?s="mobile":s="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 s}var xn="__testrelic_api_config";function wn(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.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=It(e),this.apiConfig=_t(e);}async onBegin(e,r){try{if(this.rootDir=e.rootDir,this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??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 a=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${a} tests)
2583
+ `),this.activeReportMode==="streaming"){let n=dirname(this.config.outputPath);this.streamingWriter=new G(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=dirname(this.config.outputPath);this.runTimestamp=sr(join(n,"artifacts"));try{dr(join(n,"artifacts"));}catch{}}let s=P();this.detectedOs=vn(),this.detectedSource=mn(s);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 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:xn,description:wn(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let a=r,s=e.outcome(),n;s==="flaky"?n="flaky":s==="skipped"?n="skipped":n=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,n==="skipped");(d.navigations.length>0||d.networkRequestsCount>0||d.apiCallsCount>0)&&(this.fixtureDataReceived=!0);let p=null;if(n==="failed"||n==="flaky"){let C=(n==="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=relative(this.rootDir||".",e.location.file),c=gn(f),u=f.join(" > "),g=h,m=fn(g,c,u),b=bn(l,g,e),S=b!=="mobile"&&d.apiCallsCount>0?"api":b,y=s==="flaky",x=hn(e.results),T=ut(e.expectedStatus),v=ut(a.status),k=null;if(this.config.includeArtifacts&&n!=="skipped"&&a.attachments){let R=dirname(this.config.outputPath),C=f[f.length-1]??e.title;k=nr(a.attachments,C,a.retry,R,this.runTimestamp||void 0);}let A=this.config.includeActionSteps&&a.steps?gr(a.steps,a.startTime):null,H=yn(e),M={titlePath:f,title:u,status:n,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?st(d.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:m,title:u,status:n,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}:{},...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:n,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++,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}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: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(),n=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(`
2585
2585
  \u26A0 TestRelic: No fixture data received from any test.
2586
2586
  To enable network logs, video sync, and timeline tracking, import the TestRelic fixture:
2587
2587
  import { test, expect } from '@testrelic/playwright-analytics/fixture';
2588
2588
  instead of:
2589
2589
  import { test, expect } from '@playwright/test';
2590
2590
 
2591
- `),await Jt();let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let l=dirname(this.config.outputPath);i=Xt(l,this.runTimestamp);let d=join(l,"artifact-manifest.json"),u=JSON.stringify(i),f=d+".tmp";writeFileSync(f,u,"utf-8"),renameSync(f,d);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await this.finalizeStreamingReport(r,n,t,i);else {let l=this.buildTimeline(),d=new Map;for(let c of this.collectedTests){let p=d.get(c.testId);(!p||c.retry>p.retry)&&d.set(c.testId,c);}let u=Array.from(d.values()),f=nr(u,l.length),m={schemaVersion:xe,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:n,summary:f,ci:P(),metadata:this.config.metadata,timeline:l,shardRunIds:null};if(this.writeReport(m),await Ne(m,this.config,i),ze(f,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient){let c=this.collectArtifactEntries(),p=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await at(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,m,r,n,f,c,p);}}}catch{}}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let t=dirname(this.config.outputPath),r=[];for(let a of this.collectedTests)a.artifacts&&r.push({testId:a.testId,artifacts:a.artifacts,outputDir:t});return r}async finalizeStreamingReport(t,r,a,s){if(!this.streamingWriter)return;let{totalApiCalls:n,totalAssertions:o,totalNavigations:i,totalNetworkRequests:l,totalConsoleLogs:d,totalActionSteps:u}=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:u};let f=new Map,m=new Map;for(let b of this.testIndex){let T=`${b.filePath}::${b.titlePath.join(" > ")}`,v=f.get(T);(v===void 0||b.retryIndex>v)&&f.set(T,b.retryIndex);}let c=0;for(let b of this.testIndex){let T=`${b.filePath}::${b.titlePath.join(" > ")}`,v=f.get(T);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 p=Array.from(m.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}
2592
- `);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: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:{}},w={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:t,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:p,enrichedSummary:h,validation:g,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(w);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 Ne(this.buildStreamingReport(w,h,t,r),this.config,s),ze(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}
2591
+ `),await ar();let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let l=dirname(this.config.outputPath);i=or(l,this.runTimestamp);let d=join(l,"artifact-manifest.json"),p=JSON.stringify(i),f=d+".tmp";writeFileSync(f,p,"utf-8"),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=fr(p,l.length),h={schemaVersion:ke,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:n,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,n,f,c,u);}}}catch{}}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let e=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,s){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,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}
2592
+ `);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,s),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}
2593
2593
  [testrelic] ${this.testIndex.length} test detail files on disk
2594
2594
  [testrelic] View report: npx testrelic serve ${y}
2595
2595
  `),this.streamingWriter.getWriteErrors().length>0&&process.stderr.write(`[testrelic] WARNING: ${this.streamingWriter.getWriteErrors().length} write error(s) during streaming
2596
- `),this.streamingWriter.dispose(),this.cloudClient){let b=this.buildStreamingReport(w,h,t,r),T=this.collectArtifactEntries(),v=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await at(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,b,t,r,h,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(t,r,a,s){return {schemaVersion:xe,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:a,totalDuration:s,summary:r,ci:P(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let t=process.memoryUsage(),r=t.heapUsed/1024/1024;if(r<200)return;let a=t.heapUsed/t.heapTotal;a>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
2596
+ `),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,s){return {schemaVersion:ke,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:a,totalDuration:s,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.
2597
2597
  `),this.switchToStreamingMode()):a>.8&&process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
2598
- `);}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let t=dirname(this.config.outputPath);this.streamingWriter=new G(t);for(let r of this.collectedTests){let a=ye(r.filePath,r.titlePath,r.testId,r.retry),s={id:a,navigations:r.navigations??[],apiAssertions:r.apiAssertions??[],actions:r.actions??[],artifacts:r.artifacts,failureDiagnostic:r.failure,hasNetworkFile:r.networkRequestsFile!==null,networkRequestsCount:r.networkRequestsCount,hasConsoleFile:r.consoleLogsFile!==null,consoleLogsCount:r.consoleLogsCount,hasApiCallsFile:r.apiCallsFile!==null,apiCallsCount:r.apiCallsCount,startedAt:r.startedAt};this.streamingWriter.writeTestDetail(a,s,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let n={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(`
2599
- `)[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 t=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls:null,apiAssertions:r.apiAssertions,testId:r.testId,filePath:r.filePath,suiteName:r.suiteName,testType:r.testType,isFlaky:r.isFlaky,retryStatus:r.retryStatus,expectedStatus:r.expectedStatus,actualStatus:r.actualStatus,artifacts:r.artifacts,networkRequests:null,actions:r.actions,consoleLogs:null}));return sr(t,{navigationTypes:this.config.navigationTypes})}readJsonlFile(t){if(!t)return null;let r=z(t);return r.length>0?r:null}toTestResult(t,r){let a=null,s=null,n=null;return r?.loadFiles&&(a=this.readJsonlFile(t.networkRequestsFile),s=this.readJsonlFile(t.consoleLogsFile),n=this.readJsonlFile(t.apiCallsFile)),{title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retryCount:t.retryCount,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,retryStatus:t.retryStatus,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,networkRequests:a,apiCalls:n,apiAssertions:t.apiAssertions,actions:t.actions??null,consoleLogs:s}}buildCloudTestPayload(t){let r={title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retry:t.retry,retryCount:t.retryCount,retryStatus:t.retryStatus,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,apiAssertions:t.apiAssertions,actions:t.actions??[],navigations:t.navigations??[],steps:t.actions??[],browser:t.browser,os:t.os,source:t.source};if(t.consoleLogsFile&&(r.consoleLogs=z(t.consoleLogsFile)),t.networkRequestsFile&&(r.networkRequests=z(t.networkRequestsFile)),t.apiCallsFile){let a=z(t.apiCallsFile);r.apiCalls=a,(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=a.map(s=>{let n=s;return {method:n.method??"GET",url:n.url??"",status:n.responseStatusCode??0,statusCode:n.responseStatusCode??0,type:"xhr",size:typeof n.responseBody=="string"?n.responseBody.length:0,duration:n.responseTimeMs??0,responseTimeMs:n.responseTimeMs??0,requestHeaders:n.requestHeaders??null,responseHeaders:n.responseHeaders??null,requestBody:n.requestBody??null,responseBody:n.responseBody??null,timestamp:n.timestamp??new Date().toISOString(),startedAt:n.timestamp??new Date().toISOString()}}));}return r}writeReport(t){try{let r=JSON.stringify(t),a=this.config.outputPath,s=dirname(a);mkdirSync(s,{recursive:!0});let n=a+".tmp";writeFileSync(n,r,"utf-8"),renameSync(n,a);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
2600
- `);}}};export{ve as default};//# sourceMappingURL=reporter-entry.js.map
2598
+ `);}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let e=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),s={id:a,navigations:r.navigations??[],apiAssertions:r.apiAssertions??[],actions:r.actions??[],artifacts:r.artifacts,failureDiagnostic:r.failure,hasNetworkFile:r.networkRequestsFile!==null,networkRequestsCount:r.networkRequestsCount,hasConsoleFile:r.consoleLogsFile!==null,consoleLogsCount:r.consoleLogsCount,hasApiCallsFile:r.apiCallsFile!==null,apiCallsCount:r.apiCallsCount,startedAt:r.startedAt};this.streamingWriter.writeTestDetail(a,s,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let n={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(`
2599
+ `)[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 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,s=null,n=null;return r?.loadFiles&&(a=this.readJsonlFile(e.networkRequestsFile),s=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:a,apiCalls:n,apiAssertions:e.apiAssertions,actions:e.actions??null,consoleLogs:s}}buildCloudTestPayload(e){let r={title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retry:e.retry,retryCount:e.retryCount,retryStatus:e.retryStatus,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,actions:e.actions??[],navigations:e.navigations??[],steps:e.actions??[],browser:e.browser,os:e.os,source:e.source};if(e.apiAssertions&&e.apiAssertions.length>0&&(r.protocolAssertions=st(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,s=dirname(a);mkdirSync(s,{recursive:!0});let n=a+".tmp";writeFileSync(n,r,"utf-8"),renameSync(n,a);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
2600
+ `);}}};export{ye as default};//# sourceMappingURL=reporter-entry.js.map
2601
2601
  //# sourceMappingURL=reporter-entry.js.map