@testrelic/playwright-analytics 2.7.0 → 2.8.0-next.63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import {randomUUID,createHash}from'crypto';import {mkdirSync,openSync,writeSync,closeSync,unlinkSync,writeFileSync,renameSync,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 {PAYLOAD_VERSION,ATTACHMENT_NAME,ATTACHMENT_CONTENT_TYPE,isValidConfig,createError,ErrorCode,isTestRelicFilePayload,isTestRelicDataPayload,isValidEndpointUrl,isValidCloudConfig,isValidQueueEntry}from'@testrelic/core';export{ATTACHMENT_CONTENT_TYPE,ATTACHMENT_NAME,PAYLOAD_VERSION,isTestRelicDataPayload}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';import {test,defineConfig}from'@playwright/test';import {performance}from'perf_hooks';var Xr=(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 tn=".testrelic-report";function Se(t,e,r,n){let s=`${t}|${e.join("|")}|${r}|${n}`;return createHash("sha256").update(s).digest("hex").substring(0,12)}var K=class{constructor(e){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=join(e,tn),this.testsDir=join(this.reportDir,"tests"),mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(e,r,n){try{let s=join(this.testsDir,e);mkdirSync(s,{recursive:!0});let a=join(s,"meta.json"),o=a+".tmp",i=JSON.stringify(r);return writeFileSync(o,i,"utf-8"),renameSync(o,a),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),n?.networkRequestsFile&&this.moveFile(n.networkRequestsFile,join(s,"network.jsonl")),n?.consoleLogsFile&&this.moveFile(n.consoleLogsFile,join(s,"console.jsonl")),n?.apiCallsFile&&this.moveFile(n.apiCallsFile,join(s,"api-calls.jsonl")),!0}catch(s){let a=s instanceof Error?s.message:String(s);return this.writeErrors.push({testId:e,error:a,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${e}: ${a}
2
- `),false}}moveFile(e,r){try{renameSync(e,r);}catch{try{let{copyFileSync:n}=Xr("fs");n(e,r);try{unlinkSync(e);}catch{}}catch(n){process.stderr.write(`[testrelic] Failed to move file ${e} \u2192 ${r}: ${n instanceof Error?n.message:String(n)}
3
- `);}}}writeIndex(e){let r=join(this.reportDir,"index.json"),n=r+".tmp",s=JSON.stringify(e);writeFileSync(n,s,"utf-8"),renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeCompactIndex(e){let r=join(this.reportDir,"index-compact.json"),n=r+".tmp",s=e.map(({titlePath:o,project:i,...l})=>l),a=JSON.stringify(s);writeFileSync(n,a,"utf-8"),renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}writeSummary(e){let r=join(this.reportDir,"summary.json"),n=r+".tmp",s=JSON.stringify(e);writeFileSync(n,s,"utf-8"),renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeManifest(e){let r=join(this.reportDir,"manifest.json"),n=r+".tmp",s=JSON.stringify(e);writeFileSync(n,s,"utf-8"),renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var Tt=".testrelic",ln="testrelic-config.json",dn=".testrelic",cn=5,un=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:`${Tt}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),pn={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function Ct(t){let e=resolve(t);for(let r=0;r<=cn;r++){let n=join(e,Tt,ln);if(existsSync(n))try{if(statSync(n).isFile())return n}catch{}let s=join(e,dn);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 a=dirname(e);if(a===e)break;e=a;}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)||!Rt(r)?null:r}catch{return null}}function Rt(t){for(let e of Object.keys(t)){if(un.has(e))return false;let r=t[e];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!Rt(r))return false}return true}function At(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 Re(t){let e=Object.create(null);for(let r of Object.keys(t)){let n=t[r];typeof n=="string"&&n.startsWith("$")?e[r]=At(n):typeof n=="object"&&n!==null&&!Array.isArray(n)?e[r]=Re(n):e[r]=n;}return e}function kt(t){let e=/^(\d+)\s*([smhd])$/.exec(t.trim());if(!e)return null;let r=parseInt(e[1],10),n=e[2],s=pn[n];return !s||r<=0?null:r*s}function _t(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 u=t.queue;if(u&&typeof u=="object"){if(typeof u.maxAge=="string"){let f=kt(u.maxAge);f!==null&&(r.queueMaxAge=f);}typeof u.directory=="string"&&(r.queueDirectory=u.directory);}}if(e){if(typeof e.apiKey=="string"&&e.apiKey.length>0){let l=e.apiKey.startsWith("$")?At(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=kt(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 n=process.env.TESTRELIC_API_KEY;n&&n.length>0&&(r.apiKey=n);let s=process.env.TESTRELIC_CLOUD_ENDPOINT;s&&isValidEndpointUrl(s)&&(r.endpoint=s);let a=process.env.TESTRELIC_UPLOAD_STRATEGY;a&&["batch","realtime","both"].includes(a)&&(r.uploadStrategy=a);let o=process.env.TESTRELIC_CLOUD_TIMEOUT;if(o){let l=parseInt(o,10);!isNaN(l)&&l>=1e3&&l<=12e4&&(r.timeout=l);}let i=Object.freeze(r);return isValidCloudConfig(i)?i:xt}var mn=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],yn=["authorization","cookie","set-cookie","x-api-key"],vn=["password","secret","token","apiKey","api_key"];function It(t){let e=Object.create(null);return e.trackApiCalls=t?.trackApiCalls??true,e.captureRequestHeaders=t?.captureRequestHeaders??true,e.captureResponseHeaders=t?.captureResponseHeaders??true,e.captureRequestBody=t?.captureRequestBody??true,e.captureResponseBody=t?.captureResponseBody??true,e.captureAssertions=t?.captureAssertions??true,e.redactHeaders=t?.redactHeaders??[...yn],e.redactBodyFields=t?.redactBodyFields??[...vn],e.apiIncludeUrls=t?.apiIncludeUrls??[],e.apiExcludeUrls=t?.apiExcludeUrls??[],Object.freeze(e)}function Lt(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=[...mn,...t?.redactPatterns??[]],e.testRunId=t?.testRunId??null,e.metadata=t?.metadata??null;let r=e.outputPath;e.openReport=t?.openReport??true,e.htmlReportPath=t?.htmlReportPath??r.replace(/\.json$/,".html"),e.includeArtifacts=t?.includeArtifacts??true,e.trackApiCalls=t?.trackApiCalls??true,e.quiet=t?.quiet??false,e.includeActionSteps=t?.includeActionSteps??true,e.captureConsoleLogs=t?.captureConsoleLogs??true;let n=Ct(process.cwd()),s=n?St(n):null,a=s?Re(s):null,o=_t(a,t?.cloud);return e.cloud=o.apiKey?o:null,e.reportMode=t?.reportMode??"streaming",e.streamingThreshold=t?.streamingThreshold??0,Object.freeze(e)}var ne="1.3.0";function Et(t,e,r){try{let s=readFileSync(t,"utf-8").split(`
1
+ import {randomUUID,createHash}from'crypto';import {mkdirSync,openSync,writeSync,closeSync,unlinkSync,writeFileSync,renameSync,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 {PAYLOAD_VERSION,ATTACHMENT_NAME,ATTACHMENT_CONTENT_TYPE,isValidConfig,createError,ErrorCode,isTestRelicFilePayload,isTestRelicDataPayload,isValidEndpointUrl,isValidCloudConfig,isValidQueueEntry}from'@testrelic/core';export{ATTACHMENT_CONTENT_TYPE,ATTACHMENT_NAME,PAYLOAD_VERSION,isTestRelicDataPayload}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';import {test,defineConfig}from'@playwright/test';import {performance}from'perf_hooks';var en=(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 nn=".testrelic-report";function Re(t,e,r,n){let s=`${t}|${e.join("|")}|${r}|${n}`;return createHash("sha256").update(s).digest("hex").substring(0,12)}var Y=class{constructor(e){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=join(e,nn),this.testsDir=join(this.reportDir,"tests"),mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(e,r,n){try{let s=join(this.testsDir,e);mkdirSync(s,{recursive:!0});let a=join(s,"meta.json"),o=a+".tmp",i=JSON.stringify(r);return writeFileSync(o,i,"utf-8"),renameSync(o,a),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),n?.networkRequestsFile&&this.moveFile(n.networkRequestsFile,join(s,"network.jsonl")),n?.consoleLogsFile&&this.moveFile(n.consoleLogsFile,join(s,"console.jsonl")),n?.apiCallsFile&&this.moveFile(n.apiCallsFile,join(s,"api-calls.jsonl")),!0}catch(s){let a=s instanceof Error?s.message:String(s);return this.writeErrors.push({testId:e,error:a,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${e}: ${a}
2
+ `),false}}moveFile(e,r){try{renameSync(e,r);}catch{try{let{copyFileSync:n}=en("fs");n(e,r);try{unlinkSync(e);}catch{}}catch(n){process.stderr.write(`[testrelic] Failed to move file ${e} \u2192 ${r}: ${n instanceof Error?n.message:String(n)}
3
+ `);}}}writeIndex(e){let r=join(this.reportDir,"index.json"),n=r+".tmp",s=JSON.stringify(e);writeFileSync(n,s,"utf-8"),renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeCompactIndex(e){let r=join(this.reportDir,"index-compact.json"),n=r+".tmp",s=e.map(({titlePath:o,project:i,...l})=>l),a=JSON.stringify(s);writeFileSync(n,a,"utf-8"),renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}writeSummary(e){let r=join(this.reportDir,"summary.json"),n=r+".tmp",s=JSON.stringify(e);writeFileSync(n,s,"utf-8"),renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeManifest(e){let r=join(this.reportDir,"manifest.json"),n=r+".tmp",s=JSON.stringify(e);writeFileSync(n,s,"utf-8"),renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var St=".testrelic",cn="testrelic-config.json",un=".testrelic",pn=5,fn=new Set(["__proto__","constructor","prototype"]),Tt=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${St}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),gn={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function Rt(t){let e=resolve(t);for(let r=0;r<=pn;r++){let n=join(e,St,cn);if(existsSync(n))try{if(statSync(n).isFile())return n}catch{}let s=join(e,un);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 a=dirname(e);if(a===e)break;e=a;}return null}function At(t){try{let e=readFileSync(t,"utf-8"),r=JSON.parse(e);return typeof r!="object"||r===null||Array.isArray(r)||!_t(r)?null:r}catch{return null}}function _t(t){for(let e of Object.keys(t)){if(fn.has(e))return false;let r=t[e];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!_t(r))return false}return true}function It(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 Ae(t){let e=Object.create(null);for(let r of Object.keys(t)){let n=t[r];typeof n=="string"&&n.startsWith("$")?e[r]=It(n):typeof n=="object"&&n!==null&&!Array.isArray(n)?e[r]=Ae(n):e[r]=n;}return e}function Ct(t){let e=/^(\d+)\s*([smhd])$/.exec(t.trim());if(!e)return null;let r=parseInt(e[1],10),n=e[2],s=gn[n];return !s||r<=0?null:r*s}function Lt(t,e){let r=Object.create(null);if(Object.assign(r,Tt),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 u=t.queue;if(u&&typeof u=="object"){if(typeof u.maxAge=="string"){let p=Ct(u.maxAge);p!==null&&(r.queueMaxAge=p);}typeof u.directory=="string"&&(r.queueDirectory=u.directory);}}if(e){if(typeof e.apiKey=="string"&&e.apiKey.length>0){let l=e.apiKey.startsWith("$")?It(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=Ct(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 n=process.env.TESTRELIC_API_KEY;n&&n.length>0&&(r.apiKey=n);let s=process.env.TESTRELIC_CLOUD_ENDPOINT;s&&isValidEndpointUrl(s)&&(r.endpoint=s);let a=process.env.TESTRELIC_UPLOAD_STRATEGY;a&&["batch","realtime","both"].includes(a)&&(r.uploadStrategy=a);let o=process.env.TESTRELIC_CLOUD_TIMEOUT;if(o){let l=parseInt(o,10);!isNaN(l)&&l>=1e3&&l<=12e4&&(r.timeout=l);}let i=Object.freeze(r);return isValidCloudConfig(i)?i:Tt}var vn=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],bn=["authorization","cookie","set-cookie","x-api-key"],wn=["password","secret","token","apiKey","api_key"];function Pt(t){let e=Object.create(null);return e.trackApiCalls=t?.trackApiCalls??true,e.captureRequestHeaders=t?.captureRequestHeaders??true,e.captureResponseHeaders=t?.captureResponseHeaders??true,e.captureRequestBody=t?.captureRequestBody??true,e.captureResponseBody=t?.captureResponseBody??true,e.captureAssertions=t?.captureAssertions??true,e.redactHeaders=t?.redactHeaders??[...bn],e.redactBodyFields=t?.redactBodyFields??[...wn],e.apiIncludeUrls=t?.apiIncludeUrls??[],e.apiExcludeUrls=t?.apiExcludeUrls??[],Object.freeze(e)}function Et(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=[...vn,...t?.redactPatterns??[]],e.testRunId=t?.testRunId??null,e.metadata=t?.metadata??null;let r=e.outputPath;e.openReport=t?.openReport??true,e.htmlReportPath=t?.htmlReportPath??r.replace(/\.json$/,".html"),e.includeArtifacts=t?.includeArtifacts??true,e.trackApiCalls=t?.trackApiCalls??true,e.quiet=t?.quiet??false,e.includeActionSteps=t?.includeActionSteps??true,e.captureConsoleLogs=t?.captureConsoleLogs??true;let n=Rt(process.cwd()),s=n?At(n):null,a=s?Ae(s):null,o=Lt(a,t?.cloud);return e.cloud=o.apiKey?o:null,e.reportMode=t?.reportMode??"streaming",e.streamingThreshold=t?.streamingThreshold??0,Object.freeze(e)}var se="1.3.0";function Mt(t,e,r){try{let s=readFileSync(t,"utf-8").split(`
6
6
  `);if(e<1||e>s.length)return null;let a=Math.max(1,e-r),o=Math.min(s.length,e+r),i=[];for(let l=a;l<=o;l++){let d=l===e?">":" ",u=String(l).padStart(String(o).length," ");i.push(`${d} ${u} | ${s[l-1]}`);}return i.join(`
7
- `)}catch{return null}}function Mt(t){return e=>{let r=e;for(let n of t)if(typeof n=="string"){let s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(s,"g"),"[REDACTED]");}else {let s=n.flags.includes("g")?n.flags:n.flags+"g",a=new RegExp(n.source,s);r=r.replace(a,"[REDACTED]");}return r}}function wn(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 xn(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 kn(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 Tn(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 Cn(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 Sn=[wn,xn,kn,Tn,Cn];function P(t){let e=process.env;for(let r of Sn){let n=r(e);if(n)return n}return null}var Ae=`
7
+ `)}catch{return null}}function Nt(t){return e=>{let r=e;for(let n of t)if(typeof n=="string"){let s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(s,"g"),"[REDACTED]");}else {let s=n.flags.includes("g")?n.flags:n.flags+"g",a=new RegExp(n.source,s);r=r.replace(a,"[REDACTED]");}return r}}function kn(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 Tn(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 Cn(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 Sn(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 Rn(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 An=[kn,Tn,Cn,Sn,Rn];function N(t){let e=process.env;for(let r of An){let n=r(e);if(n)return n}return null}var _e=`
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 _e=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 196 247" fill="none">
564
+ `;var Ie=`<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>`,Ie=`<svg width="32" height="40" viewBox="0 0 196 247" fill="none" xmlns="http://www.w3.org/2000/svg">
568
+ </linearGradient></defs></svg>`,Le=`<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 Le=`
572
+ </linearGradient></defs></svg>`;var Pe=`
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,''):''}
@@ -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 Pe=`
1805
+ `;var Ne=`
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 Ne=`
2075
+ `;var Fe=`
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 Fe=`
2121
+ `;var De=`
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 De=`
2308
+ `;var Be=`
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 Rn=`
2317
+ `;var _n=`
2318
2318
  (function(){
2319
2319
  var data=JSON.parse(document.getElementById('report-data').textContent);
2320
- ${Le}
2321
- ${Ne}
2320
+ ${Pe}
2322
2321
  ${Fe}
2322
+ ${De}
2323
2323
  ${Ee}
2324
2324
  ${Me}
2325
- ${De}
2326
- ${Pe}
2325
+ ${Be}
2326
+ ${Ne}
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 Pt(t,e,r){let n=t.replace(/<\//g,"<\\/"),s=r?r.replace(/<\//g,"<\\/"):null;return `<!-- TestRelic AI Analytics Report \u2014 self-contained, no external dependencies -->
2334
+ })();`;function Ft(t,e,r){let n=t.replace(/<\//g,"<\\/"),s=r?r.replace(/<\//g,"<\\/"):null;return `<!-- TestRelic AI Analytics Report \u2014 self-contained, no external dependencies -->
2335
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(_e).toString("base64")}">
2344
- <style>${Ae}</style>
2343
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Ie).toString("base64")}">
2344
+ <style>${_e}</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
- ${Ie}
2351
+ ${Le}
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">${n}</script>
2387
2387
  ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:""}
2388
- <script>${Rn}</script>
2388
+ <script>${_n}</script>
2389
2389
  </body>
2390
- </html>`}function Be(t,e,r,n){let s=t.replace(/<\//g,"<\\/"),a=e.replace(/<\//g,"<\\/"),o=n?n.replace(/<\//g,"<\\/"):null,i={};try{i=JSON.parse(t);}catch{}let l=`{
2390
+ </html>`}function Oe(t,e,r,n){let s=t.replace(/<\//g,"<\\/"),a=e.replace(/<\//g,"<\\/"),o=n?n.replace(/<\//g,"<\\/"):null,i={};try{i=JSON.parse(t);}catch{}let 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
- ${Le}
2475
- ${Ne}
2474
+ ${Pe}
2476
2475
  ${Fe}
2476
+ ${De}
2477
2477
  ${Ee}
2478
2478
  ${Me}
2479
- ${De}
2480
- ${Pe}
2479
+ ${Be}
2480
+ ${Ne}
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(_e).toString("base64")}">
2500
- <style>${Ae}</style>
2499
+ <link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Ie).toString("base64")}">
2500
+ <style>${_e}</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
- ${Ie}
2507
+ ${Le}
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,61 +2543,61 @@ ${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 Oe(t){try{let e=process.platform,r;e==="darwin"?r=`open "${t}"`:e==="win32"?r=`start "" "${t}"`:r=`xdg-open "${t}"`,exec(r,n=>{n&&process.stderr.write(`[testrelic] Failed to open browser: ${n.message}
2547
- `);});}catch{}}var Nt=join(tmpdir(),"testrelic-data"),E=class{constructor(e){this.count=0;this.closed=false;mkdirSync(Nt,{recursive:true}),this.filePath=join(Nt,`${e}-${randomUUID().substring(0,8)}.jsonl`),this.fd=openSync(this.filePath,"w");}append(e){if(this.closed)return;let r=JSON.stringify(e)+`
2548
- `;writeSync(this.fd,r),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{closeSync(this.fd);}catch{}}}cleanup(){try{unlinkSync(this.filePath);}catch{}}};async function Dt(t,e,r,n){let s=(e-1)*r,a=[],o=0,i=createInterface({input:createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let u of i)if(u.length!==0){if(o>=s&&a.length<r)try{a.push(JSON.parse(u));}catch{}if(o++,a.length>=r&&n!==void 0)break}let l=n??o,d=Math.max(1,Math.ceil(l/r));return {items:a,total:l,page:e,pageSize:r,totalPages:d}}var qt=/^[a-f0-9]{12}$/,qe=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Ht=500;function x(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function Ut(t){t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type");}function ie(t){try{return existsSync(t)?JSON.parse(readFileSync(t,"utf-8")):null}catch{return null}}function oe(t){let e=0;try{let r=readdirSync(t,{withFileTypes:!0});for(let n of r){let s=join(t,n.name);n.isFile()?e+=statSync(s).size:n.isDirectory()&&(e+=oe(s));}}catch{}return e}function zt(t,e,r,n){let s=ie(join(r,"index.json"));x(e,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-n)/1e3)});}function jt(t,e,r){let n=ie(join(r,"summary.json"));if(!n){x(e,404,{error:"Summary not found"});return}x(e,200,n);}function $t(t,e,r){let n=ie(join(r,"index.json"));if(!n){x(e,404,{error:"Test index not found"});return}let a=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,o=Math.max(1,parseInt(a.get("page")??"1",10)||1),i=Math.min(Ht,Math.max(1,parseInt(a.get("pageSize")??"100",10)||100)),l=a.get("status")?.split(",").filter(Boolean)??null,d=a.get("file")??null,u=a.get("search")?.toLowerCase()??null,f=a.get("tag")?.split(",").filter(Boolean)??null,g=a.get("sort")??"file",c=a.get("order")==="desc"?-1:1,p=n;l&&l.length>0&&(p=p.filter(v=>l.includes(v.status))),d&&(p=p.filter(v=>v.filePath===d||v.filePath.startsWith(d+"/"))),u&&(p=p.filter(v=>v.title.toLowerCase().includes(u)||v.filePath.toLowerCase().includes(u))),f&&f.length>0&&(p=p.filter(v=>f.some(w=>v.tags.includes(w)))),p=[...p].sort((v,w)=>{let C=0;switch(g){case "duration":C=v.duration-w.duration;break;case "status":C=v.status.localeCompare(w.status);break;case "title":C=v.title.localeCompare(w.title);break;default:C=v.filePath.localeCompare(w.filePath);break}return C*c});let h=p.length,m=Math.max(1,Math.ceil(h/i)),b=(o-1)*i,T=p.slice(b,b+i);x(e,200,{tests:T,pagination:{page:o,pageSize:i,totalItems:h,totalPages:m},filters:{status:l,file:d,search:u,tag:f}});}function Wt(t,e,r,n){if(!qt.test(n)){x(e,400,{error:"Invalid test ID format"});return}let s=join(r,"tests",n,"meta.json"),a=join(r,"tests",`${n}.json`),o=existsSync(s)?s:existsSync(a)?a:null;if(!o){x(e,404,{error:`Test not found: ${n}`});return}try{let i=readFileSync(o,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(i);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}async function Vt(t,e,r,n,s){if(!qt.test(n)){x(e,400,{error:"Invalid test ID format"});return}let o=join(r,"tests",n,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!existsSync(o)){x(e,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let l=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,d=Math.max(1,parseInt(l.get("page")??"1",10)||1),u=Math.min(Ht,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),f,g=join(r,"tests",n,"meta.json");if(existsSync(g))try{let p=JSON.parse(readFileSync(g,"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 Dt(o,d,u,f);x(e,200,c);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}function Gt(t,e,r){let n=ie(join(r,"index.json"));if(!n){x(e,404,{error:"Test index not found"});return}let s=new Map;for(let o of n){if(o.isRetry)continue;let i=s.get(o.filePath);switch(i||(i={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},s.set(o.filePath,i)),i.total++,o.status){case "passed":i.passed++;break;case "failed":i.failed++;break;case "flaky":i.flaky++;break;case "skipped":i.skipped++;break;case "timedout":i.timedOut++;break}}let a=Array.from(s.entries()).map(([o,i])=>({filePath:o,...i})).sort((o,i)=>o.filePath.localeCompare(i.filePath));x(e,200,{files:a});}function Jt(t,e,r){if(!existsSync(r)){x(e,200,{runs:[],totalSizeBytes:0});return}try{let n=[],s=0,a=readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!qe.test(o.name))continue;let i=join(r,o.name),l=oe(i),d=readdirSync(i,{withFileTypes:!0}).filter(u=>u.isDirectory());n.push({folderName:o.name,totalSizeBytes:l,testCount:d.length}),s+=l;}n.sort((o,i)=>i.folderName.localeCompare(o.folderName)),x(e,200,{runs:n,totalSizeBytes:s});}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}function Kt(t,e,r){try{let n=0,s=0;if(existsSync(r)){let a=readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!qe.test(o.name))continue;let i=join(r,o.name),l=oe(i);rmSync(i,{recursive:!0,force:!0}),s+=l,n++;}}x(e,200,{deletedCount:n,freedBytes:s});}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}function Yt(t,e,r,n){if(!qe.test(n)){x(e,400,{error:"Invalid folder name"});return}let s=join(r,n);try{if(!statSync(s).isDirectory()){x(e,404,{error:"Not found"});return}}catch{x(e,404,{error:"Not found"});return}try{let a=oe(s);rmSync(s,{recursive:!0,force:!0}),x(e,200,{deleted:n,freedBytes:a});}catch(a){x(e,500,{error:a instanceof Error?a.message:String(a)});}}function Zt(t,e,r){x(e,200,{status:"shutting_down"}),r.close();}function He(t,e,r){if(!existsSync(r)){x(e,404,{error:"File not found"});return}try{let n=readFileSync(r),s=extname(r).toLowerCase(),a=On[s]??"application/octet-stream";e.writeHead(200,{"Content-Type":a}),e.end(n);}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}var On={".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 zn=9323,jn=10,$n=1800*1e3;function Y(t,e){return new Promise((r,n)=>{let s=e?.port??zn,a=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();},$n);}let u=e?.htmlPath??null;if(!u){let c=dirname(t);try{let p=readdirSync(c).find(h=>h.endsWith(".html"));p&&(u=join(c,p));}catch{}}let f=createServer((c,p)=>{if(d(),Ut(p),c.method==="OPTIONS"){p.writeHead(204),p.end();return}let h;try{h=new URL(c.url??"/",`http://${c.headers.host??"localhost"}`).pathname;}catch{x(p,400,{error:"Invalid URL"});return}if(c.method==="GET"&&(h==="/"||h==="/index.html")){if(u&&existsSync(u)){He(c,p,u);return}x(p,404,{error:"HTML report not found"});return}if(c.method==="GET"&&h==="/api/health"){zt(c,p,t,a);return}if(c.method==="GET"&&h==="/api/summary"){jt(c,p,t);return}if(c.method==="GET"&&h==="/api/tests"){$t(c,p,t);return}if(c.method==="GET"&&h==="/api/files"){Gt(c,p,t);return}let m=h.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(c.method==="GET"&&m){Vt(c,p,t,m[1],m[2]);return}let b=h.match(/^\/api\/tests\/([a-f0-9]+)$/);if(c.method==="GET"&&b){Wt(c,p,t,b[1]);return}if(c.method==="GET"&&h==="/api/artifacts"){Jt(c,p,l);return}if(c.method==="DELETE"&&h==="/api/artifacts"){Kt(c,p,l);return}let T=h.match(/^\/api\/artifacts\/(.+)$/);if(c.method==="DELETE"&&T){Yt(c,p,l,decodeURIComponent(T[1]));return}if(c.method==="GET"&&h.startsWith("/artifacts/")){let v=decodeURIComponent(h.slice(11));if(v.includes("..")||v.includes("\0")){x(p,400,{error:"Invalid path"});return}He(c,p,join(l,v));return}if(c.method==="POST"&&h==="/api/shutdown"){Zt(c,p,f);return}x(p,404,{error:"Not found"});});function g(c){let p=h=>{h.code==="EADDRINUSE"&&i<jn?(i++,g(c+1)):n(h);};f.once("error",p),f.listen(c,"127.0.0.1",()=>{f.removeListener("error",p);let h=f.address();if(!h||typeof h=="string"){n(new Error("Failed to get server address"));return}d(),r({port:h.port,dispose:()=>new Promise(m=>{clearTimeout(o),f.close(()=>m());})});});}g(s);})}async function Xt(t){let e=await Y(t);return {port:e.port,dispose:e.dispose}}function Gn(t,e,r){let n=JSON.stringify(t),s=r?JSON.stringify(r):null;return Pt(n,e,s)}async function ze(t,e,r){try{let n=null,s=null,a=e.reportMode==="streaming"||e.reportMode==="auto"&&t.timeline.length===0&&t.summary.total>=e.streamingThreshold,o,i=e.htmlReportPath,l=dirname(i);mkdirSync(l,{recursive:!0});let d="",u="[]",f=null;if(a){d=JSON.stringify(t.summary);let c=dirname(e.outputPath),p=join(c,".testrelic-report");try{let h=join(p,"index-compact.json"),m=join(p,"index.json");existsSync(h)?u=readFileSync(h,"utf-8"):existsSync(m)&&(u=readFileSync(m,"utf-8"));}catch{}f=r?JSON.stringify(r):null,o=Be(d,u,null,f);}else o=Gn(t,null,r);let g=i+".tmp";if(writeFileSync(g,o,"utf-8"),renameSync(g,i),a){if(t.ci===null){let c=dirname(e.outputPath),p=join(c,".testrelic-report"),h=resolve(i);try{if(await Kn(),n=await Yn(p),!n){s=await Y(p,{htmlPath:h}),n=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(n){process.stderr.write(`
2546
+ </html>`}function qe(t){try{let e=process.platform,r;e==="darwin"?r=`open "${t}"`:e==="win32"?r=`start "" "${t}"`:r=`xdg-open "${t}"`,exec(r,n=>{n&&process.stderr.write(`[testrelic] Failed to open browser: ${n.message}
2547
+ `);});}catch{}}var Dt=join(tmpdir(),"testrelic-data"),E=class{constructor(e){this.count=0;this.closed=false;mkdirSync(Dt,{recursive:true}),this.filePath=join(Dt,`${e}-${randomUUID().substring(0,8)}.jsonl`),this.fd=openSync(this.filePath,"w");}append(e){if(this.closed)return;let r=JSON.stringify(e)+`
2548
+ `;writeSync(this.fd,r),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{closeSync(this.fd);}catch{}}}cleanup(){try{unlinkSync(this.filePath);}catch{}}};async function Ot(t,e,r,n){let s=(e-1)*r,a=[],o=0,i=createInterface({input:createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let u of i)if(u.length!==0){if(o>=s&&a.length<r)try{a.push(JSON.parse(u));}catch{}if(o++,a.length>=r&&n!==void 0)break}let l=n??o,d=Math.max(1,Math.ceil(l/r));return {items:a,total:l,page:e,pageSize:r,totalPages:d}}var Ut=/^[a-f0-9]{12}$/,He=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,zt=500;function x(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function jt(t){t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type");}function oe(t){try{return existsSync(t)?JSON.parse(readFileSync(t,"utf-8")):null}catch{return null}}function le(t){let e=0;try{let r=readdirSync(t,{withFileTypes:!0});for(let n of r){let s=join(t,n.name);n.isFile()?e+=statSync(s).size:n.isDirectory()&&(e+=le(s));}}catch{}return e}function $t(t,e,r,n){let s=oe(join(r,"index.json"));x(e,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-n)/1e3)});}function Wt(t,e,r){let n=oe(join(r,"summary.json"));if(!n){x(e,404,{error:"Summary not found"});return}x(e,200,n);}function Vt(t,e,r){let n=oe(join(r,"index.json"));if(!n){x(e,404,{error:"Test index not found"});return}let a=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,o=Math.max(1,parseInt(a.get("page")??"1",10)||1),i=Math.min(zt,Math.max(1,parseInt(a.get("pageSize")??"100",10)||100)),l=a.get("status")?.split(",").filter(Boolean)??null,d=a.get("file")??null,u=a.get("search")?.toLowerCase()??null,p=a.get("tag")?.split(",").filter(Boolean)??null,g=a.get("sort")??"file",c=a.get("order")==="desc"?-1:1,f=n;l&&l.length>0&&(f=f.filter(v=>l.includes(v.status))),d&&(f=f.filter(v=>v.filePath===d||v.filePath.startsWith(d+"/"))),u&&(f=f.filter(v=>v.title.toLowerCase().includes(u)||v.filePath.toLowerCase().includes(u))),p&&p.length>0&&(f=f.filter(v=>p.some(b=>v.tags.includes(b)))),f=[...f].sort((v,b)=>{let C=0;switch(g){case "duration":C=v.duration-b.duration;break;case "status":C=v.status.localeCompare(b.status);break;case "title":C=v.title.localeCompare(b.title);break;default:C=v.filePath.localeCompare(b.filePath);break}return C*c});let h=f.length,m=Math.max(1,Math.ceil(h/i)),y=(o-1)*i,T=f.slice(y,y+i);x(e,200,{tests:T,pagination:{page:o,pageSize:i,totalItems:h,totalPages:m},filters:{status:l,file:d,search:u,tag:p}});}function Gt(t,e,r,n){if(!Ut.test(n)){x(e,400,{error:"Invalid test ID format"});return}let s=join(r,"tests",n,"meta.json"),a=join(r,"tests",`${n}.json`),o=existsSync(s)?s:existsSync(a)?a:null;if(!o){x(e,404,{error:`Test not found: ${n}`});return}try{let i=readFileSync(o,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(i);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}async function Jt(t,e,r,n,s){if(!Ut.test(n)){x(e,400,{error:"Invalid test ID format"});return}let o=join(r,"tests",n,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!existsSync(o)){x(e,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let l=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,d=Math.max(1,parseInt(l.get("page")??"1",10)||1),u=Math.min(zt,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),p,g=join(r,"tests",n,"meta.json");if(existsSync(g))try{let f=JSON.parse(readFileSync(g,"utf-8"));switch(s){case "network":p=f.networkRequestsCount;break;case "console":p=f.consoleLogsCount;break;case "api-calls":p=f.apiCallsCount;break}}catch{}let c=await Ot(o,d,u,p);x(e,200,c);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}function Kt(t,e,r){let n=oe(join(r,"index.json"));if(!n){x(e,404,{error:"Test index not found"});return}let s=new Map;for(let o of n){if(o.isRetry)continue;let i=s.get(o.filePath);switch(i||(i={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},s.set(o.filePath,i)),i.total++,o.status){case "passed":i.passed++;break;case "failed":i.failed++;break;case "flaky":i.flaky++;break;case "skipped":i.skipped++;break;case "timedout":i.timedOut++;break}}let a=Array.from(s.entries()).map(([o,i])=>({filePath:o,...i})).sort((o,i)=>o.filePath.localeCompare(i.filePath));x(e,200,{files:a});}function Yt(t,e,r){if(!existsSync(r)){x(e,200,{runs:[],totalSizeBytes:0});return}try{let n=[],s=0,a=readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!He.test(o.name))continue;let i=join(r,o.name),l=le(i),d=readdirSync(i,{withFileTypes:!0}).filter(u=>u.isDirectory());n.push({folderName:o.name,totalSizeBytes:l,testCount:d.length}),s+=l;}n.sort((o,i)=>i.folderName.localeCompare(o.folderName)),x(e,200,{runs:n,totalSizeBytes:s});}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}function Zt(t,e,r){try{let n=0,s=0;if(existsSync(r)){let a=readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!He.test(o.name))continue;let i=join(r,o.name),l=le(i);rmSync(i,{recursive:!0,force:!0}),s+=l,n++;}}x(e,200,{deletedCount:n,freedBytes:s});}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}function Xt(t,e,r,n){if(!He.test(n)){x(e,400,{error:"Invalid folder name"});return}let s=join(r,n);try{if(!statSync(s).isDirectory()){x(e,404,{error:"Not found"});return}}catch{x(e,404,{error:"Not found"});return}try{let a=le(s);rmSync(s,{recursive:!0,force:!0}),x(e,200,{deleted:n,freedBytes:a});}catch(a){x(e,500,{error:a instanceof Error?a.message:String(a)});}}function Qt(t,e,r){x(e,200,{status:"shutting_down"}),r.close();}function Ue(t,e,r){if(!existsSync(r)){x(e,404,{error:"File not found"});return}try{let n=readFileSync(r),s=extname(r).toLowerCase(),a=Hn[s]??"application/octet-stream";e.writeHead(200,{"Content-Type":a}),e.end(n);}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}var Hn={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".json":"application/json",".html":"text/html",".css":"text/css",".js":"text/javascript",".svg":"image/svg+xml"};var $n=9323,Wn=10,Vn=1800*1e3;function Z(t,e){return new Promise((r,n)=>{let s=e?.port??$n,a=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(()=>{p.close();},Vn);}let u=e?.htmlPath??null;if(!u){let c=dirname(t);try{let f=readdirSync(c).find(h=>h.endsWith(".html"));f&&(u=join(c,f));}catch{}}let p=createServer((c,f)=>{if(d(),jt(f),c.method==="OPTIONS"){f.writeHead(204),f.end();return}let h;try{h=new URL(c.url??"/",`http://${c.headers.host??"localhost"}`).pathname;}catch{x(f,400,{error:"Invalid URL"});return}if(c.method==="GET"&&(h==="/"||h==="/index.html")){if(u&&existsSync(u)){Ue(c,f,u);return}x(f,404,{error:"HTML report not found"});return}if(c.method==="GET"&&h==="/api/health"){$t(c,f,t,a);return}if(c.method==="GET"&&h==="/api/summary"){Wt(c,f,t);return}if(c.method==="GET"&&h==="/api/tests"){Vt(c,f,t);return}if(c.method==="GET"&&h==="/api/files"){Kt(c,f,t);return}let m=h.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(c.method==="GET"&&m){Jt(c,f,t,m[1],m[2]);return}let y=h.match(/^\/api\/tests\/([a-f0-9]+)$/);if(c.method==="GET"&&y){Gt(c,f,t,y[1]);return}if(c.method==="GET"&&h==="/api/artifacts"){Yt(c,f,l);return}if(c.method==="DELETE"&&h==="/api/artifacts"){Zt(c,f,l);return}let T=h.match(/^\/api\/artifacts\/(.+)$/);if(c.method==="DELETE"&&T){Xt(c,f,l,decodeURIComponent(T[1]));return}if(c.method==="GET"&&h.startsWith("/artifacts/")){let v=decodeURIComponent(h.slice(11));if(v.includes("..")||v.includes("\0")){x(f,400,{error:"Invalid path"});return}Ue(c,f,join(l,v));return}if(c.method==="POST"&&h==="/api/shutdown"){Qt(c,f,p);return}x(f,404,{error:"Not found"});});function g(c){let f=h=>{h.code==="EADDRINUSE"&&i<Wn?(i++,g(c+1)):n(h);};p.once("error",f),p.listen(c,"127.0.0.1",()=>{p.removeListener("error",f);let h=p.address();if(!h||typeof h=="string"){n(new Error("Failed to get server address"));return}d(),r({port:h.port,dispose:()=>new Promise(m=>{clearTimeout(o),p.close(()=>m());})});});}g(s);})}async function er(t){let e=await Z(t);return {port:e.port,dispose:e.dispose}}function Kn(t,e,r){let n=JSON.stringify(t),s=r?JSON.stringify(r):null;return Ft(n,e,s)}async function je(t,e,r){try{let n=null,s=null,a=e.reportMode==="streaming"||e.reportMode==="auto"&&t.timeline.length===0&&t.summary.total>=e.streamingThreshold,o,i=e.htmlReportPath,l=dirname(i);mkdirSync(l,{recursive:!0});let d="",u="[]",p=null;if(a){d=JSON.stringify(t.summary);let c=dirname(e.outputPath),f=join(c,".testrelic-report");try{let h=join(f,"index-compact.json"),m=join(f,"index.json");existsSync(h)?u=readFileSync(h,"utf-8"):existsSync(m)&&(u=readFileSync(m,"utf-8"));}catch{}p=r?JSON.stringify(r):null,o=Oe(d,u,null,p);}else o=Kn(t,null,r);let g=i+".tmp";if(writeFileSync(g,o,"utf-8"),renameSync(g,i),a){if(t.ci===null){let c=dirname(e.outputPath),f=join(c,".testrelic-report"),h=resolve(i);try{if(await Zn(),n=await Xn(f),!n){s=await Z(f,{htmlPath:h}),n=s.port;let m=setInterval(()=>{},6e4),y=()=>{clearInterval(m),s?.dispose();};process.on("SIGINT",y),process.on("SIGTERM",y),setTimeout(y,1800*1e3).unref();}if(n){process.stderr.write(`
2549
2549
  Report server: http://127.0.0.1:${n}
2550
- `);try{let m=Be(d,u,n,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),p=join(c,"artifacts");if(existsSync(p))try{let h=await Xt(p);n=h.port,process.on("exit",()=>{h.dispose();});}catch{}}if(e.openReport&&t.ci===null)if(a&&n)Oe(`http://127.0.0.1:${n}`);else {let c=resolve(i);Oe(c);}}catch(n){process.stderr.write(`[testrelic] Failed to write HTML report: ${n instanceof Error?n.message:String(n)}
2551
- `);}}var ce=9323,nr=10;async function Jn(){for(let t=ce;t<ce+nr;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${t}/api/health`,{signal:e.signal});if(clearTimeout(r),n.ok)return t}catch{}return null}async function Kn(){for(let t=ce;t<ce+nr;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 Yn(t){let r=[join(__dirname,"cli.cjs"),join(__dirname,"cli.js"),join(__dirname,"..","dist","cli.cjs"),join(__dirname,"..","dist","cli.js")].find(n=>existsSync(n));if(!r){let n=await Y(t);return process.on("exit",()=>{n?.dispose();}),n.port}return new Promise(n=>{let s=spawn(process.execPath,[r,"serve",t],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),a="",o=false,i=setTimeout(()=>{o||(o=true,s.stderr?.removeAllListeners(),Jn().then(n));},5e3);s.stderr?.on("data",l=>{a+=l.toString();let d=a.match(/127\.0\.0\.1:(\d+)/);d&&!o&&(o=true,clearTimeout(i),s.stderr?.removeAllListeners(),s.unref(),n(Number(d[1])));}),s.on("error",()=>{o||(o=true,clearTimeout(i),n(null));}),s.on("exit",()=>{o||(o=true,clearTimeout(i),n(null));}),s.unref();})}var Qn=20,je=0,$e=[];async function ar(t,e){je>=Qn&&await new Promise(r=>$e.push(r)),je++;try{return await copyFile(t,e),!0}catch{return false}finally{je--,$e.length>0&&$e.shift()();}}var X=[];async function ir(){X.length!==0&&(await Promise.allSettled(X),X.length=0);}function or(t){let e=new Date,r=a=>String(a).padStart(2,"0"),n=`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())}T${r(e.getHours())}-${r(e.getMinutes())}-${r(e.getSeconds())}`;if(!existsSync(join(t,n)))return n;let s=1;for(;existsSync(join(t,`${n}-${s}`));)s++;return `${n}-${s}`}function es(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 lr(t,e,r,n,s){let a=t.find(g=>g.name==="screenshot"&&g.path),o=t.find(g=>g.name==="video"&&g.path);if(!a&&!o)return null;let i=es(e);r>0&&(i+=`--retry-${r}`);let l=s?["artifacts",s,i]:["artifacts",i],d=join(n,...l),u=l,f={};try{mkdirSync(d,{recursive:!0});}catch{return null}if(a?.path&&existsSync(a.path)){let c=`screenshot${extname(a.path)||".png"}`,p=join(d,c);X.push(ar(a.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);X.push(ar(o.path,p).then(()=>{})),f.video=`${u.join("/")}/${c}`;}return !f.screenshot&&!f.video?null:f}var ns=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,ss="1.0";function as(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 dr(t,e,r){let n=[];try{let s=readdirSync(t,{withFileTypes:!0});for(let a of s){if(!a.isFile())continue;let o=join(t,a.name),i=statSync(o);n.push({name:a.name,type:as(a.name),relativePath:`artifacts/${e}/${r}/${a.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:n}}function is(t,e){let r=join(t,e),n=[],s=0;try{let o=readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let l=dr(join(r,i.name),e,i.name);n.push(l);for(let d of l.files)s+=d.sizeBytes;}}catch{}let a=e.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return n.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:e,timestamp:a,totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}}function cr(t,e){let r=join(t,"artifacts"),n=[],s=[],a=0;try{let i=readdirSync(r,{withFileTypes:!0});for(let l of i)if(l.isDirectory())if(ns.test(l.name)){let d=is(r,l.name);n.push({...d,isCurrentRun:l.name===e});}else {let d=dr(join(r,l.name),l.name,l.name);s.push(d);for(let u of d.files)a+=u.sizeBytes;}}catch{}n.sort((i,l)=>l.timestamp.localeCompare(i.timestamp)),s.length>0&&(s.sort((i,l)=>i.testName.localeCompare(l.testName)),n.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:a,testCount:s.length,tests:s,isCurrentRun:false}));let o=n.reduce((i,l)=>i+l.totalSizeBytes,0);return {schemaVersion:ss,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:n,serverPort:null}}function us(t){let e=t,{root:r}=parse(e);for(;e!==r;){if(existsSync(join(e,".git")))return e;e=join(e,"..");}return null}function pr(t){try{let e=us(t);if(!e)return;let r=join(e,".gitignore"),n=relative(e,t).replace(/\\/g,"/"),s=n.endsWith("/")?n:`${n}/`;if(existsSync(r)&&readFileSync(r,"utf-8").split(`
2550
+ `);try{let m=Oe(d,u,n,p),y=i+".tmp";writeFileSync(y,m,"utf-8"),renameSync(y,i);}catch{}}}catch{}}}else if(e.openReport&&t.ci===null&&e.includeArtifacts){let c=dirname(e.outputPath),f=join(c,"artifacts");if(existsSync(f))try{let h=await er(f);n=h.port,process.on("exit",()=>{h.dispose();});}catch{}}if(e.openReport&&t.ci===null)if(a&&n)qe(`http://127.0.0.1:${n}`);else {let c=resolve(i);qe(c);}}catch(n){process.stderr.write(`[testrelic] Failed to write HTML report: ${n instanceof Error?n.message:String(n)}
2551
+ `);}}var ue=9323,ar=10;async function Yn(){for(let t=ue;t<ue+ar;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${t}/api/health`,{signal:e.signal});if(clearTimeout(r),n.ok)return t}catch{}return null}async function Zn(){for(let t=ue;t<ue+ar;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),1e3);await fetch(`http://127.0.0.1:${t}/api/shutdown`,{method:"POST",signal:e.signal}),clearTimeout(r);}catch{}await new Promise(t=>setTimeout(t,300));}async function Xn(t){let r=[join(__dirname,"cli.cjs"),join(__dirname,"cli.js"),join(__dirname,"..","dist","cli.cjs"),join(__dirname,"..","dist","cli.js")].find(n=>existsSync(n));if(!r){let n=await Z(t);return process.on("exit",()=>{n?.dispose();}),n.port}return new Promise(n=>{let s=spawn(process.execPath,[r,"serve",t],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),a="",o=false,i=setTimeout(()=>{o||(o=true,s.stderr?.removeAllListeners(),Yn().then(n));},5e3);s.stderr?.on("data",l=>{a+=l.toString();let d=a.match(/127\.0\.0\.1:(\d+)/);d&&!o&&(o=true,clearTimeout(i),s.stderr?.removeAllListeners(),s.unref(),n(Number(d[1])));}),s.on("error",()=>{o||(o=true,clearTimeout(i),n(null));}),s.on("exit",()=>{o||(o=true,clearTimeout(i),n(null));}),s.unref();})}var ts=20,$e=0,We=[];async function or(t,e){$e>=ts&&await new Promise(r=>We.push(r)),$e++;try{return await copyFile(t,e),!0}catch{return false}finally{$e--,We.length>0&&We.shift()();}}var Q=[];async function lr(){Q.length!==0&&(await Promise.allSettled(Q),Q.length=0);}function dr(t){let e=new Date,r=a=>String(a).padStart(2,"0"),n=`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())}T${r(e.getHours())}-${r(e.getMinutes())}-${r(e.getSeconds())}`;if(!existsSync(join(t,n)))return n;let s=1;for(;existsSync(join(t,`${n}-${s}`));)s++;return `${n}-${s}`}function rs(t){let e=t.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return e.length>100&&(e=e.substring(0,100).replace(/-+$/,"")),e||"unnamed-test"}function cr(t,e,r,n,s){let a=t.find(g=>g.name==="screenshot"&&g.path),o=t.find(g=>g.name==="video"&&g.path);if(!a&&!o)return null;let i=rs(e);r>0&&(i+=`--retry-${r}`);let l=s?["artifacts",s,i]:["artifacts",i],d=join(n,...l),u=l,p={};try{mkdirSync(d,{recursive:!0});}catch{return null}if(a?.path&&existsSync(a.path)){let c=`screenshot${extname(a.path)||".png"}`,f=join(d,c);Q.push(or(a.path,f).then(()=>{})),p.screenshot=`${u.join("/")}/${c}`;}if(o?.path&&existsSync(o.path)){let c=`video${extname(o.path)||".webm"}`,f=join(d,c);Q.push(or(o.path,f).then(()=>{})),p.video=`${u.join("/")}/${c}`;}return !p.screenshot&&!p.video?null:p}var as=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,is="1.0";function os(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 ur(t,e,r){let n=[];try{let s=readdirSync(t,{withFileTypes:!0});for(let a of s){if(!a.isFile())continue;let o=join(t,a.name),i=statSync(o);n.push({name:a.name,type:os(a.name),relativePath:`artifacts/${e}/${r}/${a.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:n}}function ls(t,e){let r=join(t,e),n=[],s=0;try{let o=readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let l=ur(join(r,i.name),e,i.name);n.push(l);for(let d of l.files)s+=d.sizeBytes;}}catch{}let a=e.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return n.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:e,timestamp:a,totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}}function pr(t,e){let r=join(t,"artifacts"),n=[],s=[],a=0;try{let i=readdirSync(r,{withFileTypes:!0});for(let l of i)if(l.isDirectory())if(as.test(l.name)){let d=ls(r,l.name);n.push({...d,isCurrentRun:l.name===e});}else {let d=ur(join(r,l.name),l.name,l.name);s.push(d);for(let u of d.files)a+=u.sizeBytes;}}catch{}n.sort((i,l)=>l.timestamp.localeCompare(i.timestamp)),s.length>0&&(s.sort((i,l)=>i.testName.localeCompare(l.testName)),n.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:a,testCount:s.length,tests:s,isCurrentRun:false}));let o=n.reduce((i,l)=>i+l.totalSizeBytes,0);return {schemaVersion:is,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:n,serverPort:null}}function fs(t){let e=t,{root:r}=parse(e);for(;e!==r;){if(existsSync(join(e,".git")))return e;e=join(e,"..");}return null}function gr(t){try{let e=fs(t);if(!e)return;let r=join(e,".gitignore"),n=relative(e,t).replace(/\\/g,"/"),s=n.endsWith("/")?n:`${n}/`;if(existsSync(r)&&readFileSync(r,"utf-8").split(`
2552
2552
  `).map(l=>l.trim()).some(l=>l===s||l===n))return;let a=`
2553
2553
  # TestRelic test artifacts
2554
2554
  ${s}
2555
- `;appendFileSync(r,a,"utf-8");}catch{}}function hr(t,e){let r=[];for(let n of t){let s=ps(n),a=fs(n),o=gs(n,s,a,e),i=hs(n,s,a);if(o.length===0&&i.length===0){r.push({type:"navigation",url:"about:blank",timestamp:n.startedAt,durationOnUrl:n.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:n.specFile,test:s,tests:[a],_testTitle:n.title});continue}r.push(...o,...i);}return r.sort(ms),ys(r,t),r.map((n,s)=>n.type==="navigation"?{...{index:s,type:"navigation",url:n.url,timestamp:n.timestamp,durationOnUrl:n.durationOnUrl??0,navigationType:n.navigationType,domContentLoadedAt:n.domContentLoadedAt??null,networkIdleAt:n.networkIdleAt??null,networkStats:n.networkStats??null,specFile:n.specFile,test:n.test},tests:n.tests}:{...{index:s,type:"api_call",callId:n.callId,method:n.method,url:n.url,timestamp:n.timestamp,responseTime:n.responseTime??null,request:n.request,response:n.response??null,...n.error?{error:n.error}:{},assertions:n.assertions??[],specFile:n.specFile,test:n.test},tests:n.tests})}function ps(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 fs(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 gs(t,e,r,n){let s=[];for(let a of t.navigations)n.navigationTypes!==null&&!n.navigationTypes.includes(a.navigationType)||s.push({type:"navigation",url:a.url,timestamp:a.timestamp,durationOnUrl:0,navigationType:a.navigationType,domContentLoadedAt:a.domContentLoadedAt??null,networkIdleAt:a.networkIdleAt??null,networkStats:a.networkStats??null,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title});return s}function hs(t,e,r){if(!t.apiCalls||t.apiCalls.length===0)return [];let n=t.apiAssertions??[];return t.apiCalls.map(s=>{let a=n.filter(i=>i.callId===s.id).map(i=>({type:i.type,expected:i.expected,actual:i.actual,status:i.status,location:i.location,...i.expression!==void 0?{expression:i.expression}:{}})),o=null;return s.responseStatusCode!==null&&s.responseStatusText!==null&&(o={statusCode:s.responseStatusCode,statusText:s.responseStatusText,headers:s.responseHeaders,body:gr(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:gr(s.requestBody)},response:o,...s.error?{error:s.error}:{},assertions:a,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title}})}function ms(t,e){let r=new Date(t.timestamp).getTime(),n=new Date(e.timestamp).getTime();if(r!==n)return r-n;let s={navigation:0,api_call:1},a=s[t.type],o=s[e.type];return a!==o?a-o:t.type==="api_call"&&e.type==="api_call"&&t.callId&&e.callId?fr(t.callId)-fr(e.callId):0}function fr(t){let e=t.match(/(\d+)$/);return e?parseInt(e[1],10):0}function ys(t,e){for(let r=0;r<t.length;r++){let n=t[r];if(n.type!=="navigation")continue;let s=new Date(n.timestamp).getTime(),a=null;for(let o=r+1;o<t.length;o++)if(t[o]._testTitle===n._testTitle){a=new Date(t[o].timestamp).getTime();break}if(a!==null)n.durationOnUrl=Math.max(0,a-s);else {let o=e.find(i=>i.title===n._testTitle);if(o){let i=new Date(o.completedAt).getTime();n.durationOnUrl=Math.max(0,i-s);}}}}function gr(t){if(t==null)return null;try{return JSON.parse(t)}catch{return t}}function Ge(t,e){let r=t.length,n=Math.min(Math.ceil(e/100*r)-1,r-1);return t[Math.max(0,n)]}function vs(t){try{let e=new URL(t);return e.origin+e.pathname}catch{return t}}function bs(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 mr(t,e){let r=0,n=0,s=0,a=0,o=0;for(let y of t)switch(y.status){case "passed":r++;break;case "failed":n++;break;case "flaky":s++;break;case "skipped":a++;break;case "timedout":o++;break}let i=[];for(let y of t)y.apiCalls&&i.push(...y.apiCalls);let l=i.length,d=new Set,u={},f={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},g=[];for(let y of i)d.add(vs(y.url)),u[y.method]=(u[y.method]??0)+1,f[bs(y.responseStatusCode)]+=1,g.push(y.responseTimeMs);let c=null;if(g.length>0){let y=[...g].sort((q,R)=>q-R),k=y.reduce((q,R)=>q+R,0);c={avg:Math.round(k/y.length),min:y[0],max:y[y.length-1],p50:Ge(y,50),p95:Ge(y,95),p99:Ge(y,99)};}let p=0,h=0,m=0;for(let y of t)if(y.apiAssertions)for(let k of y.apiAssertions)p++,k.status==="passed"?h++:m++;let b=0,T=new Set;for(let y of t){b+=y.navigations.length;for(let k of y.navigations)T.add(k.url);}let v=0,w={};function C(y){for(let k of y)v++,w[k.category]=(w[k.category]??0)+1,k.children.length>0&&C(k.children);}for(let y of t)y.actions&&C(y.actions);return {total:t.length,passed:r,failed:n,flaky:s,skipped:a,timedout:o,totalApiCalls:l,uniqueApiUrls:d.size,apiCallsByMethod:u,apiCallsByStatusRange:f,apiResponseTime:c,totalAssertions:p,passedAssertions:h,failedAssertions:m,totalNavigations:b,uniqueNavigationUrls:T.size,totalTimelineSteps:e,totalActionSteps:v,actionStepsByCategory:w}}function ws(t){let e=56-t.length;return e>0?t+" ".repeat(e):t}function I(t){return `\u2502 ${ws(t)} \u2502
2556
- `}function Je(t,e,r,n){if(n||t.total===0)return;let s=`\u250C${"\u2500".repeat(58)}\u2510
2555
+ `;appendFileSync(r,a,"utf-8");}catch{}}function yr(t,e){let r=[];for(let n of t){let s=gs(n),a=hs(n),o=ms(n,s,a,e),i=ys(n,s,a);if(o.length===0&&i.length===0){r.push({type:"navigation",url:"about:blank",timestamp:n.startedAt,durationOnUrl:n.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:n.specFile,test:s,tests:[a],_testTitle:n.title});continue}r.push(...o,...i);}return r.sort(vs),bs(r,t),r.map((n,s)=>n.type==="navigation"?{...{index:s,type:"navigation",url:n.url,timestamp:n.timestamp,durationOnUrl:n.durationOnUrl??0,navigationType:n.navigationType,domContentLoadedAt:n.domContentLoadedAt??null,networkIdleAt:n.networkIdleAt??null,networkStats:n.networkStats??null,specFile:n.specFile,test:n.test},tests:n.tests}:{...{index:s,type:"api_call",callId:n.callId,method:n.method,url:n.url,timestamp:n.timestamp,responseTime:n.responseTime??null,request:n.request,response:n.response??null,...n.error?{error:n.error}:{},assertions:n.assertions??[],specFile:n.specFile,test:n.test},tests:n.tests})}function gs(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 hs(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 ms(t,e,r,n){let s=[];for(let a of t.navigations)n.navigationTypes!==null&&!n.navigationTypes.includes(a.navigationType)||s.push({type:"navigation",url:a.url,timestamp:a.timestamp,durationOnUrl:0,navigationType:a.navigationType,domContentLoadedAt:a.domContentLoadedAt??null,networkIdleAt:a.networkIdleAt??null,networkStats:a.networkStats??null,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title});return s}function ys(t,e,r){if(!t.apiCalls||t.apiCalls.length===0)return [];let n=t.apiAssertions??[];return t.apiCalls.map(s=>{let a=n.filter(i=>i.callId===s.id).map(i=>({type:i.type,expected:i.expected,actual:i.actual,status:i.status,location:i.location,...i.expression!==void 0?{expression:i.expression}:{}})),o=null;return s.responseStatusCode!==null&&s.responseStatusText!==null&&(o={statusCode:s.responseStatusCode,statusText:s.responseStatusText,headers:s.responseHeaders,body:mr(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:mr(s.requestBody)},response:o,...s.error?{error:s.error}:{},assertions:a,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title}})}function vs(t,e){let r=new Date(t.timestamp).getTime(),n=new Date(e.timestamp).getTime();if(r!==n)return r-n;let s={navigation:0,api_call:1},a=s[t.type],o=s[e.type];return a!==o?a-o:t.type==="api_call"&&e.type==="api_call"&&t.callId&&e.callId?hr(t.callId)-hr(e.callId):0}function hr(t){let e=t.match(/(\d+)$/);return e?parseInt(e[1],10):0}function bs(t,e){for(let r=0;r<t.length;r++){let n=t[r];if(n.type!=="navigation")continue;let s=new Date(n.timestamp).getTime(),a=null;for(let o=r+1;o<t.length;o++)if(t[o]._testTitle===n._testTitle){a=new Date(t[o].timestamp).getTime();break}if(a!==null)n.durationOnUrl=Math.max(0,a-s);else {let o=e.find(i=>i.title===n._testTitle);if(o){let i=new Date(o.completedAt).getTime();n.durationOnUrl=Math.max(0,i-s);}}}}function mr(t){if(t==null)return null;try{return JSON.parse(t)}catch{return t}}function Je(t,e){let r=t.length,n=Math.min(Math.ceil(e/100*r)-1,r-1);return t[Math.max(0,n)]}function ws(t){try{let e=new URL(t);return e.origin+e.pathname}catch{return t}}function xs(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 vr(t,e){let r=0,n=0,s=0,a=0,o=0;for(let w of t)switch(w.status){case "passed":r++;break;case "failed":n++;break;case "flaky":s++;break;case "skipped":a++;break;case "timedout":o++;break}let i=[];for(let w of t)w.apiCalls&&i.push(...w.apiCalls);let l=i.length,d=new Set,u={},p={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},g=[];for(let w of i)d.add(ws(w.url)),u[w.method]=(u[w.method]??0)+1,p[xs(w.responseStatusCode)]+=1,g.push(w.responseTimeMs);let c=null;if(g.length>0){let w=[...g].sort((A,H)=>A-H),k=w.reduce((A,H)=>A+H,0);c={avg:Math.round(k/w.length),min:w[0],max:w[w.length-1],p50:Je(w,50),p95:Je(w,95),p99:Je(w,99)};}let f=0,h=0,m=0;for(let w of t)if(w.apiAssertions)for(let k of w.apiAssertions)f++,k.status==="passed"?h++:m++;let y=0,T=new Set;for(let w of t){y+=w.navigations.length;for(let k of w.navigations)T.add(k.url);}let v=0,b={};function C(w){for(let k of w)v++,b[k.category]=(b[k.category]??0)+1,k.children.length>0&&C(k.children);}for(let w of t)w.actions&&C(w.actions);return {total:t.length,passed:r,failed:n,flaky:s,skipped:a,timedout:o,totalApiCalls:l,uniqueApiUrls:d.size,apiCallsByMethod:u,apiCallsByStatusRange:p,apiResponseTime:c,totalAssertions:f,passedAssertions:h,failedAssertions:m,totalNavigations:y,uniqueNavigationUrls:T.size,totalTimelineSteps:e,totalActionSteps:v,actionStepsByCategory:b}}function ks(t){let e=56-t.length;return e>0?t+" ".repeat(e):t}function I(t){return `\u2502 ${ks(t)} \u2502
2556
+ `}function Ke(t,e,r,n){if(n||t.total===0)return;let s=`\u250C${"\u2500".repeat(58)}\u2510
2557
2557
  `,a=`\u2514${"\u2500".repeat(58)}\u2518
2558
- `,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,g])=>`${f}: ${g}`);d.length>0&&(i+=I(` ${d.join(" ")}`));let u=Object.entries(t.apiCallsByStatusRange).filter(([,f])=>f>0).map(([f,g])=>`${f}: ${g}`);u.length>0&&(i+=I(` ${u.join(" ")}`)),t.apiResponseTime&&(i+=I(` Avg response: ${t.apiResponseTime.avg}ms P95: ${t.apiResponseTime.p95}ms`));}if(t.totalAssertions>0&&(i+=I(`Assertions: ${t.totalAssertions} total (${t.passedAssertions} \u2713 ${t.failedAssertions} \u2717)`)),t.totalActionSteps>0){let d=[],u=t.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: ${t.totalActionSteps} steps${f}`);}i+=I(`Report: ${r}`),i+=I(`Data: ${e}`),i+=a,i+=`For more information visit us at https://docs.testrelic.ai
2559
- `,process.stderr.write(i);}var xs=new Set(["pw:api","expect","test.step"]);function ks(t){return t==="expect"?"assertion":t==="test.step"?"custom_step":"ui_action"}function Ke(t,e,r){if(xs.has(t.category)){let n=[];for(let a of t.steps)Ke(a,e,n);let s=t.startTime.getTime()-e.getTime();r.push({title:t.title,category:ks(t.category),timestamp:t.startTime.toISOString(),duration:t.duration,videoOffset:s>=0?s/1e3:null,status:t.error?"failed":"passed",error:t.error?.message??null,children:n});}else for(let n of t.steps)Ke(n,e,r);}function yr(t,e){let r=[];for(let n of t)Ke(n,e,r);return r}var Ss=new Set(["localhost","127.0.0.1","0.0.0.0"]);function br(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Ss.has(e.hostname)))throw createError(ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${e.protocol}//${e.hostname}`)}var Rs=3e3;async function Ye(t){let e=new AbortController,r=setTimeout(()=>e.abort(),Rs);try{return (await fetch(`${t}/health`,{method:"GET",signal:e.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function wr(t){return new Promise(e=>setTimeout(e,t))}async function vr(t){try{let r=(await t.json()).error;if(r&&typeof r.message=="string"){let n=r.details;if(Array.isArray(n)&&n.length>0){let s=n.map(a=>`${a.field}: ${a.message}`).join(", ");return `${r.message} (${s})`}return r.message}}catch{}return `HTTP ${t.status}`}async function Ze(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:n.signal});if(a.ok){let i=await a.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,orgId:i.orgId,orgName:i.orgName,userId:i.userId,userName:i.userName}}if(a.status===429){let i=a.headers.get("Retry-After"),l=i?parseInt(i,10)*1e3:5e3;if(!isNaN(l)&&l>0){await wr(l);let d=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:n.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 a.status===400?{code:"validation_error",message:await vr(a),statusCode:400}:a.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:a.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await vr(a),statusCode:a.status}}catch(a){return a instanceof DOMException&&a.name==="AbortError"?{code:"timeout",message:"Token exchange timed out.",statusCode:null}:{code:"network_error",message:"Failed to reach cloud for token exchange.",statusCode:null}}finally{clearTimeout(s);}}function Xe(t){return "code"in t&&typeof t.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(t.code)}async function xr(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:n.signal});if(a.status===429){let i=a.headers.get("Retry-After"),l=i?parseInt(i,10)*1e3:5e3;!isNaN(l)&&l>0&&(await wr(l),a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:n.signal}));}if(!a.ok)return null;let o=await a.json();return {accessToken:o.accessToken,refreshToken:o.refreshToken,expiresIn:o.expiresIn}}catch{return null}finally{clearTimeout(s);}}async function kr(t,e,r,n,s,a){let o=new AbortController,i=setTimeout(()=>o.abort(),s);try{let l={gitId:r,displayName:n};a&&(l.branch=a);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 u=await d.json();return {repoId:u.repoId,displayName:u.displayName}}catch{return null}finally{clearTimeout(i);}}var Es=5e3;function F(t,e){try{return execSync(t,{cwd:e,timeout:Es,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function Tr(t){let e=F("git rev-parse --abbrev-ref HEAD",t),r=F("git rev-parse --short HEAD",t),n=F("git log -1 --pretty=%s",t),s=F("git log -1 --format=%an",t)??F("git config user.name",t),a=Ms(t),o=a?ee(a):null;return {branch:e,commitSha:r,commitMessage:n,commitAuthor:s,remoteUrl:o}}function Ms(t){let e=F("git remote get-url origin",t);if(e)return e;let r=F("git remote",t);if(!r)return null;let n=r.split(`
2560
- `)[0]?.trim();return n?F(`git remote get-url ${n}`,t):null}function ee(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 Cr(t){let e=t.split("/").filter(Boolean);return e[e.length-1]??t}function Qe(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 te(t){let e=Qe(t);return e||`local/${basename(t)}`}var qs=1048576,Hs="1.0.0",Sr=10;function re(t,e,r,n,s,a,o,i){try{mkdirSync(t,{recursive:!0});let l=Date.now(),d=`${l}-${e}-${r}.json`,u=join(t,d),f={version:Hs,queuedAt:new Date(l).toISOString(),reason:n,retryCount:0,targetEndpoint:s,method:a,payload:o,headers:i},g=u+".tmp";writeFileSync(g,JSON.stringify(f,null,2),"utf-8"),renameSync(g,u);}catch(l){l.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
2558
+ `,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(([,p])=>p>0).map(([p,g])=>`${p}: ${g}`);d.length>0&&(i+=I(` ${d.join(" ")}`));let u=Object.entries(t.apiCallsByStatusRange).filter(([,p])=>p>0).map(([p,g])=>`${p}: ${g}`);u.length>0&&(i+=I(` ${u.join(" ")}`)),t.apiResponseTime&&(i+=I(` Avg response: ${t.apiResponseTime.avg}ms P95: ${t.apiResponseTime.p95}ms`));}if(t.totalAssertions>0&&(i+=I(`Assertions: ${t.totalAssertions} total (${t.passedAssertions} \u2713 ${t.failedAssertions} \u2717)`)),t.totalActionSteps>0){let d=[],u=t.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 p=d.length>0?` (${d.join(" ")})`:"";i+=I(`Actions: ${t.totalActionSteps} steps${p}`);}i+=I(`Report: ${r}`),i+=I(`Data: ${e}`),i+=a,i+=`For more information visit us at https://docs.testrelic.ai
2559
+ `,process.stderr.write(i);}var Ts=new Set(["pw:api","expect","test.step"]);function Cs(t){return t==="expect"?"assertion":t==="test.step"?"custom_step":"ui_action"}function Ye(t,e,r){if(Ts.has(t.category)){let n=[];for(let a of t.steps)Ye(a,e,n);let s=t.startTime.getTime()-e.getTime();r.push({title:t.title,category:Cs(t.category),timestamp:t.startTime.toISOString(),duration:t.duration,videoOffset:s>=0?s/1e3:null,status:t.error?"failed":"passed",error:t.error?.message??null,children:n});}else for(let n of t.steps)Ye(n,e,r);}function br(t,e){let r=[];for(let n of t)Ye(n,e,r);return r}var As=new Set(["localhost","127.0.0.1","0.0.0.0"]);function xr(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&As.has(e.hostname)))throw createError(ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${e.protocol}//${e.hostname}`)}var _s=3e3;async function Ze(t){let e=new AbortController,r=setTimeout(()=>e.abort(),_s);try{return (await fetch(`${t}/health`,{method:"GET",signal:e.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function kr(t){return new Promise(e=>setTimeout(e,t))}async function wr(t){try{let r=(await t.json()).error;if(r&&typeof r.message=="string"){let n=r.details;if(Array.isArray(n)&&n.length>0){let s=n.map(a=>`${a.field}: ${a.message}`).join(", ");return `${r.message} (${s})`}return r.message}}catch{}return `HTTP ${t.status}`}async function Xe(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:n.signal});if(a.ok){let i=await a.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,orgId:i.orgId,orgName:i.orgName,userId:i.userId,userName:i.userName}}if(a.status===429){let i=a.headers.get("Retry-After"),l=i?parseInt(i,10)*1e3:5e3;if(!isNaN(l)&&l>0){await kr(l);let d=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:n.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 a.status===400?{code:"validation_error",message:await wr(a),statusCode:400}:a.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:a.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await wr(a),statusCode:a.status}}catch(a){return a instanceof DOMException&&a.name==="AbortError"?{code:"timeout",message:"Token exchange timed out.",statusCode:null}:{code:"network_error",message:"Failed to reach cloud for token exchange.",statusCode:null}}finally{clearTimeout(s);}}function Qe(t){return "code"in t&&typeof t.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(t.code)}async function Tr(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:n.signal});if(a.status===429){let i=a.headers.get("Retry-After"),l=i?parseInt(i,10)*1e3:5e3;!isNaN(l)&&l>0&&(await kr(l),a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:n.signal}));}if(!a.ok)return null;let o=await a.json();return {accessToken:o.accessToken,refreshToken:o.refreshToken,expiresIn:o.expiresIn}}catch{return null}finally{clearTimeout(s);}}async function Cr(t,e,r,n,s,a){let o=new AbortController,i=setTimeout(()=>o.abort(),s);try{let l={gitId:r,displayName:n};a&&(l.branch=a);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 u=await d.json();return {repoId:u.repoId,displayName:u.displayName}}catch{return null}finally{clearTimeout(i);}}var Ms=5e3;function D(t,e){try{return execSync(t,{cwd:e,timeout:Ms,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function Sr(t){let e=D("git rev-parse --abbrev-ref HEAD",t),r=D("git rev-parse --short HEAD",t),n=D("git log -1 --pretty=%s",t),s=D("git log -1 --format=%an",t)??D("git config user.name",t),a=Ns(t),o=a?te(a):null;return {branch:e,commitSha:r,commitMessage:n,commitAuthor:s,remoteUrl:o}}function Ns(t){let e=D("git remote get-url origin",t);if(e)return e;let r=D("git remote",t);if(!r)return null;let n=r.split(`
2560
+ `)[0]?.trim();return n?D(`git remote get-url ${n}`,t):null}function te(t){let e=t.trim();return e=e.replace(/^[a-z+]+:\/\//,""),e=e.replace(/^[^@]+@/,""),e=e.replace(/:(?!\d)/,"/"),e=e.replace(/\.git$/,""),e=e.replace(/\/+$/,""),e=e.replace(/^[^@/]+@/,""),e.toLowerCase()}function Rr(t){let e=t.split("/").filter(Boolean);return e[e.length-1]??t}function et(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 re(t){let e=et(t);return e||`local/${basename(t)}`}var Us=1048576,zs="1.0.0",Ar=10;function ne(t,e,r,n,s,a,o,i){try{mkdirSync(t,{recursive:!0});let l=Date.now(),d=`${l}-${e}-${r}.json`,u=join(t,d),p={version:zs,queuedAt:new Date(l).toISOString(),reason:n,retryCount:0,targetEndpoint:s,method:a,payload:o,headers:i},g=u+".tmp";writeFileSync(g,JSON.stringify(p,null,2),"utf-8"),renameSync(g,u);}catch(l){l.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
2561
2561
  `):process.stderr.write(`\u26A0 TestRelic: Unable to queue upload data.
2562
- `);}}async function _r(t,e,r){let n;try{n=readdirSync(t).filter(a=>a.endsWith(".json")&&!a.endsWith(".tmp")).sort();}catch{return}if(n.length===0)return;let s=[];for(let a=0;a<n.length;a+=Sr)s.push(n.slice(a,a+Sr));for(let a of s)for(let o of a){let i=join(t,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}
2563
- `),unlinkSync(i);continue}let f=u,g=JSON.stringify(f.payload),c={...f.headers,Authorization:`Bearer ${r}`},p=g;if(Buffer.byteLength(g,"utf-8")>qs&&(p=gzipSync(Buffer.from(g,"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 Ir(t,e){try{let r=readdirSync(t).filter(s=>s.endsWith(".json")&&!s.endsWith(".tmp")),n=Date.now();for(let s of r){let a=join(t,s);try{let o=readFileSync(a,"utf-8"),l=JSON.parse(o).queuedAt;if(typeof l=="string"){let d=new Date(l).getTime();n-d>e&&unlinkSync(a);}}catch{try{unlinkSync(a);}catch{}}}}catch{}}var Gs=3e5,Js=864e5,Ks=6e4,Lr=3e4,rt="https://platform.testrelic.ai/settings/api-keys",fe=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.
2564
- `);return}try{if(br(this.config.endpoint),this.gitMetadata=Tr(),!await Ye(this.config.endpoint)){this.setLocalMode("cloud_unreachable"),process.stderr.write(`\u26A0 TestRelic: Cloud unreachable. Switching to local mode. Data will be queued for later upload.
2565
- `);return}let r=await Ze(this.config.endpoint,this.config.apiKey,this.config.timeout);if(Xe(r)){this.handleAuthError(r.code,r.statusCode);return}let n=r;this.authState={mode:"cloud",accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:Date.now()+n.expiresIn*1e3,orgId:n.orgId,orgName:n.orgName,userId:n.userId,userName:n.userName},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${n.orgName} / ${n.userName})
2566
- `),await this.resolveRepoId(),this.config.queueDirectory&&(Ir(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)}
2567
- `);}}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()+Gs<e)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await xr(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}).
2568
- `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,new Promise(e=>setTimeout(e,Lr))]);}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.
2569
- \u2192 Manage keys: ${rt}
2562
+ `);}}async function Lr(t,e,r){let n;try{n=readdirSync(t).filter(a=>a.endsWith(".json")&&!a.endsWith(".tmp")).sort();}catch{return}if(n.length===0)return;let s=[];for(let a=0;a<n.length;a+=Ar)s.push(n.slice(a,a+Ar));for(let a of s)for(let o of a){let i=join(t,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}
2563
+ `),unlinkSync(i);continue}let p=u,g=JSON.stringify(p.payload),c={...p.headers,Authorization:`Bearer ${r}`},f=g;if(Buffer.byteLength(g,"utf-8")>Us&&(f=gzipSync(Buffer.from(g,"utf-8")),c["Content-Encoding"]="gzip"),(await fetch(p.targetEndpoint,{method:p.method,headers:c,body:f})).ok)unlinkSync(i);else return}catch{return}}}function Pr(t,e){try{let r=readdirSync(t).filter(s=>s.endsWith(".json")&&!s.endsWith(".tmp")),n=Date.now();for(let s of r){let a=join(t,s);try{let o=readFileSync(a,"utf-8"),l=JSON.parse(o).queuedAt;if(typeof l=="string"){let d=new Date(l).getTime();n-d>e&&unlinkSync(a);}}catch{try{unlinkSync(a);}catch{}}}}catch{}}var Ks=3e5,Ys=864e5,Zs=6e4,Er=3e4,nt="https://platform.testrelic.ai/settings/api-keys",ge=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.
2564
+ `);return}try{if(xr(this.config.endpoint),this.gitMetadata=Sr(),!await Ze(this.config.endpoint)){this.setLocalMode("cloud_unreachable"),process.stderr.write(`\u26A0 TestRelic: Cloud unreachable. Switching to local mode. Data will be queued for later upload.
2565
+ `);return}let r=await Xe(this.config.endpoint,this.config.apiKey,this.config.timeout);if(Qe(r)){this.handleAuthError(r.code,r.statusCode);return}let n=r;this.authState={mode:"cloud",accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:Date.now()+n.expiresIn*1e3,orgId:n.orgId,orgName:n.orgName,userId:n.userId,userName:n.userName},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${n.orgName} / ${n.userName})
2566
+ `),await this.resolveRepoId(),this.config.queueDirectory&&(Pr(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)}
2567
+ `);}}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()+Ks<e)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await Tr(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}).
2568
+ `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,new Promise(e=>setTimeout(e,Er))]);}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.
2569
+ \u2192 Manage keys: ${nt}
2570
2570
  `);break;case "expired_key":this.setLocalMode("expired_api_key"),process.stderr.write(`\u26A0 TestRelic: API key has expired. Running in local mode.
2571
- \u2192 Generate a new key: ${rt}
2571
+ \u2192 Generate a new key: ${nt}
2572
2572
  `);break;case "validation_error":this.setLocalMode("validation_error"),process.stderr.write(`\u26A0 TestRelic: API key format invalid. Running in local mode.
2573
- \u2192 Manage keys: ${rt}
2573
+ \u2192 Manage keys: ${nt}
2574
2574
  `);break;case "rate_limited":this.setLocalMode("rate_limited"),process.stderr.write(`\u26A0 TestRelic: Rate limited during authentication. Running in local mode.
2575
2575
  `);break;case "timeout":this.setLocalMode("auth_timeout"),process.stderr.write(`\u26A0 TestRelic: Authentication timed out. Running in local mode.
2576
2576
  `);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
2577
- `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?ee(this.gitMetadata.remoteUrl):null,r=e?Cr(e):this.config.projectName??te(process.cwd()),n=e??this.config.projectName??te(process.cwd()),s=this.readRepoCache(n);if(s){this.repoId=s.repoId;return}try{let a=await kr(this.config.endpoint,this.authState.accessToken,n,r,this.config.timeout,this.gitMetadata?.branch);a&&(this.repoId=a.repoId,this.writeRepoCache(n,a.repoId,a.displayName));}catch{}!e&&!this.config.projectName&&!Qe(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
2578
- `);}readRepoCache(e){if(!this.config)return null;let r=join(this.config.queueDirectory,"..","cache","repo.json");try{if(!existsSync(r))return null;let n=readFileSync(r,"utf-8"),s=JSON.parse(n);if(s.gitId!==e||Date.now()-s.resolvedAt>Js)return null;let a=this.hashApiKey();return a&&s.apiKeyHash!==a?null:s}catch{return null}}writeRepoCache(e,r,n){if(!this.config)return;let s=join(this.config.queueDirectory,"..","cache"),a=join(s,"repo.json");try{mkdirSync(s,{recursive:!0});let o={repoId:r,gitId:e,displayName:n,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=a+".tmp";writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),renameSync(i,a);}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,n=this.config.endpoint;this.flushPromise=Promise.race([_r(r,n,e),new Promise(s=>setTimeout(s,Lr))]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let e=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await Ye(e))return;if(this.config?.apiKey){let n=await Ze(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!Xe(n)){let s=n;this.authState={mode:"cloud",accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:Date.now()+s.expiresIn*1e3,orgId:s.orgId,orgName:s.orgName,userId:s.userId,userName:s.userName},this.failureReason=null,process.stderr.write(`\u2713 TestRelic: Cloud connectivity restored.
2579
- `),this.startBackgroundFlush();}}}catch{}},Ks);}};var Ys=new Set(["smoke","regression","nightly","ci"]);function ge(){let t=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(t&&Ys.has(t))return t}var Xs=1048576,he=[1e3,3e3,9e3],me=3,Qs=40*1048576;function nt(t,e,r,n,s,a){let o=a?.cloudPlatform?a.cloudPlatform:n?.provider&&n.provider!=="unknown"?n.provider:"local",i=ge(),l={runId:t.testRunId,repoGitId:e,startedAt:t.startedAt,summary:t.summary,timeline:t.timeline,environment:o,...i?{runType:i}:{},...s&&s.length>0?{tests:s}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...n?.provider?{ciProvider:n.provider}:{},...n?.runUrl?{ciRunUrl:n.runUrl}:{},...a?.cloudPlatform?{cloudPlatform:a.cloudPlatform}:{},...a?.cloudBuildId?{cloudBuildId:a.cloudBuildId}:{},...a?.cloudSessionId?{cloudSessionId:a.cloudSessionId}:{}};if(l.tests&&l.tests.length>0){let d=JSON.stringify(l);if(Buffer.byteLength(d,"utf-8")>Qs){let u=l.tests.map(({consoleLogs:f,networkRequests:g,...c})=>c);return {...l,tests:u}}}return l}async function ye(t){return new Promise(e=>setTimeout(e,t))}function ea(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}async function Er(t,e,r){for(let n=0;n<me;n++)try{let s=await fetch(t,e);if(s.ok)return s;if(s.status===401&&r&&n===0){let a=await r();if(a){let o={...e,headers:{...e.headers,Authorization:`Bearer ${a}`}},i=await fetch(t,o);if(i.ok)return i}return null}if(s.status===429&&n<me-1){let a=s.headers.get("Retry-After"),o=a?parseInt(a,10)*1e3:he[n];!isNaN(o)&&o>0?await ye(o):await ye(he[n]);continue}if(s.status>=500&&n<me-1){await ye(he[n]);continue}return s}catch{if(n<me-1){await ye(he[n]);continue}return null}return null}function ta(t){let e=JSON.stringify(t),r={"Content-Type":"application/json"};if(Buffer.byteLength(e,"utf-8")>Xs){let n=gzipSync(Buffer.from(e,"utf-8"));return r["Content-Encoding"]="gzip",{body:n,headers:r}}return {body:e,headers:r}}async function Mr(t,e,r,n){let s=`${t}/runs`,{body:a,headers:o}=ta(r);o.Authorization=`Bearer ${e}`;let i=await Er(s,{method:"POST",headers:o,body:a},n);return i?.ok?{success:true,statusCode:i.status,error:null}:i?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:i?`Upload failed with status ${i.status}`:"Upload failed after retries",statusCode:i?.status??null,payload:r,targetEndpoint:s,method:"POST"}}async function Pr(t,e,r){let n=`${t}/runs/init`;try{let s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(ea(r))});return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function Nr(t,e,r,n){let s=`${t}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}).catch(()=>{});}async function Fr(t,e,r,n){let s=`${t}/runs/${r}/finalize`;return (await Er(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}))?.ok??false}function st(t,e,r,n){let s=`${t}/runs/${r}/finalize`,a=new Date,o={finishedAt:a.toISOString(),duration:a.getTime()-new Date(n).getTime(),summary:{}};fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}).catch(()=>{});}function Dr(t,e,r,n){let s=[],a=[],o=null,i=0,l=null,d=0,u=null,f=0,g=t.filter(h=>h.name===ATTACHMENT_NAME&&h.body),c=false;if(g.length>0)for(let h of g)try{let m=JSON.parse(h.body.toString());if(isTestRelicFilePayload(m)){s=s.concat(m.navigations),a=a.concat(m.apiAssertions),m.networkRequestsFile&&(o=m.networkRequestsFile,i+=m.networkRequestsCount),m.consoleLogsFile&&(l=m.consoleLogsFile,d+=m.consoleLogsCount),m.apiCallsFile&&(u=m.apiCallsFile,f+=m.apiCallsCount),c=!0;continue}if(isTestRelicDataPayload(m)){s=s.concat(m.navigations),Array.isArray(m.apiAssertions)&&(a=a.concat(m.apiAssertions)),i+=m.networkRequests?.length??0,f+=m.apiCalls?.length??0;let b=m.consoleLogs;Array.isArray(b)&&(d+=b.length),c=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
2580
- `);}return c||(s=e.filter(h=>h.type==="lambdatest-navigation"&&h.description).map(h=>{try{return JSON.parse(h.description)}catch{return null}}).filter(h=>h!==null)),s.length===0&&i===0&&f===0&&!n&&!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.
2581
- `),{navigations:s,apiAssertions:a,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:l,consoleLogsCount:d,apiCallsFile:u,apiCallsCount:f}}function ve(t=process.env){let e=aa(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 aa(t){if(!t)return;let e=t.toLowerCase().trim();if(e==="browserstack"||e==="bs")return "browserstack";if(e==="lambdatest"||e==="lt")return "lambdatest"}var ca=5,be=[1e3,3e3,9e3],U=3,ua={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip"},at=0,it=[];async function pa(){at>=ca&&await new Promise(t=>it.push(t)),at++;}function fa(){at--,it.length>0&&it.shift()();}async function we(t){return new Promise(e=>setTimeout(e,t))}function ga(t){let e=t.substring(t.lastIndexOf(".")).toLowerCase();return ua[e]??"application/octet-stream"}function ha(t){try{return statSync(t).size}catch{return 0}}async function ma(t,e,r,n,s){let a=`${t}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:basename(r.filePath),contentType:s,type:r.type,sizeBytes:n});for(let i=0;i<U;i++)try{let l=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:o});if(l.ok)return await l.json();if(l.status>=500&&i<U-1){await we(be[i]);continue}return null}catch{if(i<U-1){await we(be[i]);continue}return null}return null}async function ya(t,e,r,n){for(let s=0;s<U;s++)try{let a=createReadStream(e),o=Readable.toWeb(a),i=await fetch(t,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(n)},body:o,duplex:"half"});if(i.ok)return !0;if(i.status>=500&&s<U-1){await we(be[s]);continue}return !1}catch{if(s<U-1){await we(be[s]);continue}return false}return false}async function va(t,e,r){let n=`${t}/artifacts/confirm`;try{return (await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({artifactId:r})})).ok}catch{return false}}async function ba(t,e,r,n){let s=ha(r.filePath);if(s===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(s>n*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let a=ga(r.filePath);await pa();try{let o=await ma(t,e,r,s,a);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await ya(o.uploadUrl,r.filePath,a,s))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let l=await va(t,e,o.artifactId);return {success:l,storageKey:o.storageKey,artifactId:o.artifactId,error:l?null:"confirm_failed"}}finally{fa();}}async function Br(t,e,r,n){let s=new Map,a=r.map(async o=>{let i=await ba(t,e,o,n);s.set(o.filePath,i);});return await Promise.allSettled(a),s}function ot(t){let r=t.getGitMetadata()?.remoteUrl;return r?ee(r):t.getConfig()?.projectName??te(process.cwd())}async function qr(t,e,r,n,s){if(!t.isCloudMode()||e!=="realtime"&&e!=="both"||!await t.ensureValidToken())return null;let o=t.getGitMetadata(),i=P(),l=ve(),d=ge();return (await Pr(t.getEndpoint(),t.getAccessToken(),{runId:r,repoGitId:ot(t),branch:o?.branch??null,commit:o?.commitSha??null,commitMessage:o?.commitMessage??null,commitAuthor:o?.commitAuthor??null,startedAt:n,totalTests:null,ciProvider:i?.provider??null,ciRunUrl:i?.runUrl??null,environment:s??l.cloudPlatform??null,cloudPlatform:l.cloudPlatform??null,cloudBuildId:l.cloudBuildId??null,cloudSessionId:l.cloudSessionId??null,...d?{runType:d}:{}}))?.runId??null}var wa=true,xa=50;async function ka(t,e,r,n){let s=new Map;if(!(e?.uploadArtifacts??wa)||!await t.ensureValidToken())return s;let i=[],l=new Map;for(let c of n){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=e?.artifactMaxSizeMb??xa,u=await Br(t.getEndpoint(),t.getAccessToken(),i,d),f=new Map;for(let[c,p]of u){if(!p.success||!p.storageKey)continue;let h=l.get(c);if(!h)continue;let m=f.get(h.testId)??{};h.field==="screenshot"&&(m.screenshotKey=p.storageKey),h.field==="video"&&(m.videoKey=p.storageKey),f.set(h.testId,m);}for(let c of n){let p=f.get(c.testId);s.set(c.testId,{...c.artifacts,...p?.screenshotKey?{screenshotKey:p.screenshotKey}:{},...p?.videoKey?{videoKey:p.videoKey}:{}});}let g=Array.from(u.values()).filter(c=>c.success).length;return g>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${g} artifact(s) to cloud storage.
2582
- `),s}async function lt(t,e,r,n,s,a,o,i,l,d,u){try{if(t.isCloudMode()&&s&&(r==="realtime"||r==="both")){let g=await t.ensureValidToken(),c=t.getGitMetadata(),p={finishedAt:o,duration:i,summary:l,...c?.commitMessage?{commitMessage:c.commitMessage}:{}};if(g){if(!await Fr(t.getEndpoint(),t.getAccessToken(),s,p)){let m=e?.queueDirectory??".testrelic/queue";re(m,n,"finalize","finalize_failed_after_retries",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",p,{"Content-Type":"application/json"});}}else {let h=e?.queueDirectory??".testrelic/queue";re(h,n,"finalize",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",p,{"Content-Type":"application/json"});}}let f=new Map;if(t.isCloudMode()&&d&&d.length>0&&(f=await ka(t,e,n,d)),t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await t.ensureValidToken()){let c=t.getGitMetadata(),p=P(),h=ot(t),m=Ta(a,f),b=nt(m,h,c,p,u,ve()),T=await Mr(t.getEndpoint(),t.getAccessToken(),b,async()=>await t.ensureValidToken()?t.getAccessToken():null);if(!T.success){let v=T,w=e?.queueDirectory??".testrelic/queue";re(w,n,"batch",v.reason,v.targetEndpoint,v.method,v.payload,{"Content-Type":"application/json"});}}else {let c=e?.queueDirectory??".testrelic/queue",p=t.getGitMetadata(),h=P(),m=ot(t),b=nt(a,m,p,h,void 0,ve());re(c,n,"batch",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs`,"POST",b,{"Content-Type":"application/json"});}await t.dispose();}catch{try{await t.dispose();}catch{}}}function Ta(t,e){if(e.size===0)return t;let r=t.timeline.map(n=>{let s=n.testId;if(!s)return n;let a=e.get(s);return a?{...n,...a.screenshotKey?{screenshotKey:a.screenshotKey}:{},...a.videoKey?{videoKey:a.videoKey}:{}}:n});return {...t,timeline:r}}function z(t){try{return readFileSync(t,"utf-8").split(`
2583
- `).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function ct(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 La(t,e,r){let n=`${t}::${e}::${r}`;return createHash("sha256").update(n).digest("hex").substring(0,16)}function Ea(t){return t.length<=3?"":t[t.length-2]}function Ma(t){let e=t.findIndex(r=>r.status==="passed");return e>0?`passed on retry ${e}`:null}function Pa(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 Na(){let t=platform();return t==="win32"?"Windows":t==="darwin"?"macOS":"Linux"}function Fa(t){let e=t.parent?.project?.()?.use;if(!e)return;let{browserName:r,channel:n}=e;if(n){let a=n.toLowerCase();return a==="chrome"||a==="chrome-stable"?"Chrome":a.startsWith("chrome-beta")?"Chrome Beta":a.startsWith("chrome-dev")?"Chrome Dev":a.startsWith("chrome-canary")?"Chrome Canary":a==="msedge"||a==="msedge-stable"?"Microsoft Edge":a.startsWith("msedge-beta")?"Edge Beta":a.startsWith("msedge-dev")?"Edge Dev":a.startsWith("msedge-canary")?"Edge Canary":n}if(r){let a=r.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":r}let s=e.defaultBrowserType;if(s){let a=s.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":s}}function Da(t,e,r){let n=r.parent?.project?.(),s="unknown";n!==void 0&&(n.use.isMobile===true?s="mobile":s="e2e");let a=["e2e","api","unit","mobile"];for(let l of a)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 Ba="__testrelic_api_config";function Oa(t){return JSON.stringify(t,(e,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var xe=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=Lt(e),this.apiConfig=It(e);}async onBegin(e,r){try{if(this.rootDir=e.rootDir,this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??randomUUID(),this.config.reportMode==="auto"){let a=r.allTests().length;this.activeReportMode=a>=this.config.streamingThreshold?"streaming":"embedded";}else this.activeReportMode=this.config.reportMode;let n=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${n} tests)
2584
- `),this.activeReportMode==="streaming"){let a=dirname(this.config.outputPath);this.streamingWriter=new K(a);let o=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let i={testRunId:this.testRunId??"",startedAt:this.startedAt,completedAt:new Date().toISOString(),totalDuration:Date.now()-new Date(this.startedAt).getTime(),...this.summaryCounters,metadata:null,reportMode:"streaming",files:[],enrichedSummary:null,validation:null,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(i);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let i=this.cloudClient.getAccessToken();i&&st(this.cloudClient.getEndpoint(),i,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",o),process.on("SIGINT",o);}if(this.config.includeArtifacts){let a=dirname(this.config.outputPath);this.runTimestamp=or(join(a,"artifacts"));try{pr(join(a,"artifacts"));}catch{}}let s=P();this.detectedOs=Na(),this.detectedSource=Pa(s);try{this.cloudClient=new fe(this.config.cloud),await this.cloudClient.initialize(),this.cloudRunId=await qr(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource);}catch{this.cloudClient?.switchToLocalMode("init_error");}if(this.activeReportMode!=="streaming"){let a=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let o=this.cloudClient.getAccessToken();o&&st(this.cloudClient.getEndpoint(),o,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",a),process.on("SIGINT",a);}}catch{}}onTestBegin(e,r){try{e.annotations.push({type:Ba,description:Oa(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let n=r,s=e.outcome(),a;s==="flaky"?a="flaky":s==="skipped"?a="skipped":a=ct(n.status);let o=n.startTime.toISOString(),i=new Date(n.startTime.getTime()+n.duration).toISOString(),l=e.tags?[...e.tags]:e.annotations.filter(A=>A.type==="tag").map(A=>A.description??""),d=Dr(n.attachments,e.annotations,e.title,a==="skipped");(d.navigations.length>0||d.networkRequestsCount>0||d.apiCallsCount>0)&&(this.fixtureDataReceived=!0);let u=null;if(a==="failed"||a==="flaky"){let S=(a==="flaky"?e.results.find(B=>B.status!=="passed")?.errors??[]:n.errors)[0];if(S){let B=Mt(this.config.redactPatterns),V=S.location?.line??null,G=null;this.config.includeCodeSnippets&&V!==null&&S.location?.file&&(G=Et(S.location.file,V,this.config.codeContextLines),G&&(G=B(G))),u={message:B(S.message??"Unknown error"),line:V,code:G,stack:this.config.includeStackTrace&&S.stack?B(S.stack):null};}}let f=e.titlePath().filter(Boolean),g=relative(this.rootDir||".",e.location.file),c=Ea(f),p=f.join(" > "),h=g,m=La(h,c,p),b=Da(l,h,e),T=s==="flaky",v=Ma(e.results),w=ct(e.expectedStatus),C=ct(n.status),y=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments){let A=dirname(this.config.outputPath),S=f[f.length-1]??e.title;y=lr(n.attachments,S,n.retry,A,this.runTimestamp||void 0);}let k=this.config.includeActionSteps&&n.steps?yr(n.steps,n.startTime):null,q=Fa(e),R={titlePath:f,title:p,status:a,duration:n.duration,startedAt:o,completedAt:i,retryCount:e.results.length-1,retry:n.retry,tags:l,failure:u,specFile:g,navigations:d.navigations,testId:m,filePath:h,suiteName:c,testType:b,isFlaky:T,retryStatus:v,expectedStatus:w,actualStatus:C,artifacts:y,apiAssertions:d.apiAssertions,actions:k,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},ht=d.consoleLogsFile&&d.consoleLogsCount>0?z(d.consoleLogsFile):void 0,mt=d.networkRequestsFile&&d.networkRequestsCount>0?z(d.networkRequestsFile):void 0;this.cloudTestsBuffer.push({testId:m,title:p,status:a,duration:n.duration,suiteName:c,filePath:h,testType:b,isFlaky:T,startedAt:o,completedAt:i,tags:l,failure:u,retry:n.retry,retryCount:e.results.length-1,retryStatus:v,browser:q,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...k&&k.length>0?{actions:k}:{},...ht?{consoleLogs:ht}:{},...mt?{networkRequests:mt}:{}});try{let A=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(A==="realtime"||A==="both")){let S=this.cloudClient.getAccessToken();S&&Nr(this.cloudClient.getEndpoint(),S,this.cloudRunId,this.buildCloudTestPayload(R));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let A=Se(h,f,e.id??"",n.retry),S=n.retry===e.results.length-1,B={id:A,navigations:d.navigations,apiAssertions:d.apiAssertions,actions:k??[],artifacts:y,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(A,B,{networkRequestsFile:d.networkRequestsFile,consoleLogsFile:d.consoleLogsFile,apiCallsFile:d.apiCallsFile});let V={id:A,title:f[f.length-1]??e.title,titlePath:f,filePath:h,status:a,duration:n.duration,project:f[1]??"",retryIndex:n.retry,tags:l,hasNetworkData:d.networkRequestsCount>0,hasConsoleData:d.consoleLogsCount>0,hasArtifacts:y!==null,hasActionSteps:(k?.length??0)>0,errorMessage:u?.message?.split(`
2585
- `)[0]??null,networkCount:d.networkRequestsCount,consoleCount:d.consoleLogsCount,actionCount:k?.length??0,isRetry:!S};if(this.testIndex.push(V),S)switch(this.summaryCounters.total++,a){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.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+=k?.length??0,y&&this.pendingArtifactEntries.push({testId:m,artifacts:y,outputDir:dirname(this.config.outputPath)}),R.actions=null,R.apiAssertions=null,R.navigations=[],R.artifacts=null,R.failure=null,R.networkRequestsFile=null,R.consoleLogsFile=null,R.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(R),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(e){try{let r=new Date().toISOString(),n=new Date(this.startedAt).getTime(),a=new Date(r).getTime()-n,o=this.activeReportMode==="streaming"?this.testIndex.some(l=>l.status!=="skipped"):this.collectedTests.some(l=>l.status!=="skipped");!this.fixtureDataReceived&&o&&process.stderr.write(`
2577
+ `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?te(this.gitMetadata.remoteUrl):null,r=e?Rr(e):this.config.projectName??re(process.cwd()),n=e??this.config.projectName??re(process.cwd()),s=this.readRepoCache(n);if(s){this.repoId=s.repoId;return}try{let a=await Cr(this.config.endpoint,this.authState.accessToken,n,r,this.config.timeout,this.gitMetadata?.branch);a&&(this.repoId=a.repoId,this.writeRepoCache(n,a.repoId,a.displayName));}catch{}!e&&!this.config.projectName&&!et(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
2578
+ `);}readRepoCache(e){if(!this.config)return null;let r=join(this.config.queueDirectory,"..","cache","repo.json");try{if(!existsSync(r))return null;let n=readFileSync(r,"utf-8"),s=JSON.parse(n);if(s.gitId!==e||Date.now()-s.resolvedAt>Ys)return null;let a=this.hashApiKey();return a&&s.apiKeyHash!==a?null:s}catch{return null}}writeRepoCache(e,r,n){if(!this.config)return;let s=join(this.config.queueDirectory,"..","cache"),a=join(s,"repo.json");try{mkdirSync(s,{recursive:!0});let o={repoId:r,gitId:e,displayName:n,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=a+".tmp";writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),renameSync(i,a);}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,n=this.config.endpoint;this.flushPromise=Promise.race([Lr(r,n,e),new Promise(s=>setTimeout(s,Er))]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let e=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await Ze(e))return;if(this.config?.apiKey){let n=await Xe(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!Qe(n)){let s=n;this.authState={mode:"cloud",accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:Date.now()+s.expiresIn*1e3,orgId:s.orgId,orgName:s.orgName,userId:s.userId,userName:s.userName},this.failureReason=null,process.stderr.write(`\u2713 TestRelic: Cloud connectivity restored.
2579
+ `),this.startBackgroundFlush();}}}catch{}},Zs);}};var Xs=new Set(["smoke","regression","nightly","ci"]);function he(){let t=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(t&&Xs.has(t))return t}var ea=1048576,me=[1e3,3e3,9e3],ye=3,ta=40*1048576,ra=new Set(["e2e","mobile","unit"]);function st(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 a="rest",o=0;for(let[i,l]of s)l>o&&(o=l,a=i);return {testType:"api",apiProtocol:a,metadata:{testType:"api",primaryProtocol:a}}}let e=new Map;for(let s of t??[])ra.has(s.testType)&&e.set(s.testType,(e.get(s.testType)??0)+1);let r=null,n=0;for(let[s,a]of e)a>n&&(n=a,r=s);return {testType:r??"e2e"}}function at(t,e,r,n,s,a){let o=a?.cloudPlatform?a.cloudPlatform:n?.provider&&n.provider!=="unknown"?n.provider:"local",i=he(),l=st(s),d=l.testType==="api"?l:null,u=d&&s?s.map(g=>g.apiProtocol?g:{...g,apiProtocol:d.apiProtocol}):s,p={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},...u&&u.length>0?{tests:u}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...n?.provider?{ciProvider:n.provider}:{},...n?.runUrl?{ciRunUrl:n.runUrl}:{},...a?.cloudPlatform?{cloudPlatform:a.cloudPlatform}:{},...a?.cloudBuildId?{cloudBuildId:a.cloudBuildId}:{},...a?.cloudSessionId?{cloudSessionId:a.cloudSessionId}:{}};if(p.tests&&p.tests.length>0){let g=JSON.stringify(p);if(Buffer.byteLength(g,"utf-8")>ta){let c=p.tests.map(({consoleLogs:f,networkRequests:h,...m})=>m);return {...p,tests:c}}}return p}async function ve(t){return new Promise(e=>setTimeout(e,t))}function na(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}async function Mr(t,e,r){for(let n=0;n<ye;n++)try{let s=await fetch(t,e);if(s.ok)return s;if(s.status===401&&r&&n===0){let a=await r();if(a){let o={...e,headers:{...e.headers,Authorization:`Bearer ${a}`}},i=await fetch(t,o);if(i.ok)return i}return null}if(s.status===429&&n<ye-1){let a=s.headers.get("Retry-After"),o=a?parseInt(a,10)*1e3:me[n];!isNaN(o)&&o>0?await ve(o):await ve(me[n]);continue}if(s.status>=500&&n<ye-1){await ve(me[n]);continue}return s}catch{if(n<ye-1){await ve(me[n]);continue}return null}return null}function sa(t){let e=JSON.stringify(t),r={"Content-Type":"application/json"};if(Buffer.byteLength(e,"utf-8")>ea){let n=gzipSync(Buffer.from(e,"utf-8"));return r["Content-Encoding"]="gzip",{body:n,headers:r}}return {body:e,headers:r}}async function Nr(t,e,r,n){let s=`${t}/runs`,{body:a,headers:o}=sa(r);o.Authorization=`Bearer ${e}`;let i=await Mr(s,{method:"POST",headers:o,body:a},n);return i?.ok?{success:true,statusCode:i.status,error:null}:i?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:i?`Upload failed with status ${i.status}`:"Upload failed after retries",statusCode:i?.status??null,payload:r,targetEndpoint:s,method:"POST"}}async function Fr(t,e,r){let n=`${t}/runs/init`;try{let s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(na(r))});return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function Dr(t,e,r,n){let s=`${t}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}).catch(()=>{});}async function Br(t,e,r,n){let s=`${t}/runs/${r}/finalize`;return (await Mr(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}))?.ok??false}function it(t,e,r,n){let s=`${t}/runs/${r}/finalize`,a=new Date,o={finishedAt:a.toISOString(),duration:a.getTime()-new Date(n).getTime(),summary:{}};fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}).catch(()=>{});}function Or(t,e,r,n){let s=[],a=[],o=null,i=0,l=null,d=0,u=null,p=0,g=t.filter(h=>h.name===ATTACHMENT_NAME&&h.body),c=false;if(g.length>0)for(let h of g)try{let m=JSON.parse(h.body.toString());if(isTestRelicFilePayload(m)){s=s.concat(m.navigations),a=a.concat(m.apiAssertions),m.networkRequestsFile&&(o=m.networkRequestsFile,i+=m.networkRequestsCount),m.consoleLogsFile&&(l=m.consoleLogsFile,d+=m.consoleLogsCount),m.apiCallsFile&&(u=m.apiCallsFile,p+=m.apiCallsCount),c=!0;continue}if(isTestRelicDataPayload(m)){s=s.concat(m.navigations),Array.isArray(m.apiAssertions)&&(a=a.concat(m.apiAssertions)),i+=m.networkRequests?.length??0,p+=m.apiCalls?.length??0;let y=m.consoleLogs;Array.isArray(y)&&(d+=y.length),c=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
2580
+ `);}return c||(s=e.filter(h=>h.type==="lambdatest-navigation"&&h.description).map(h=>{try{return JSON.parse(h.description)}catch{return null}}).filter(h=>h!==null)),s.length===0&&i===0&&p===0&&!n&&!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.
2581
+ `),{navigations:s,apiAssertions:a,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:l,consoleLogsCount:d,apiCallsFile:u,apiCallsCount:p}}function be(t=process.env){let e=la(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 la(t){if(!t)return;let e=t.toLowerCase().trim();if(e==="browserstack"||e==="bs")return "browserstack";if(e==="lambdatest"||e==="lt")return "lambdatest"}var fa=5,we=[1e3,3e3,9e3],z=3,ga={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip"},ot=0,lt=[];async function ha(){ot>=fa&&await new Promise(t=>lt.push(t)),ot++;}function ma(){ot--,lt.length>0&&lt.shift()();}async function xe(t){return new Promise(e=>setTimeout(e,t))}function ya(t){let e=t.substring(t.lastIndexOf(".")).toLowerCase();return ga[e]??"application/octet-stream"}function va(t){try{return statSync(t).size}catch{return 0}}async function ba(t,e,r,n,s){let a=`${t}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:basename(r.filePath),contentType:s,type:r.type,sizeBytes:n});for(let i=0;i<z;i++)try{let l=await fetch(a,{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 xe(we[i]);continue}return null}catch{if(i<z-1){await xe(we[i]);continue}return null}return null}async function wa(t,e,r,n){for(let s=0;s<z;s++)try{let a=createReadStream(e),o=Readable.toWeb(a),i=await fetch(t,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(n)},body:o,duplex:"half"});if(i.ok)return !0;if(i.status>=500&&s<z-1){await xe(we[s]);continue}return !1}catch{if(s<z-1){await xe(we[s]);continue}return false}return false}async function xa(t,e,r){let n=`${t}/artifacts/confirm`;try{return (await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({artifactId:r})})).ok}catch{return false}}async function ka(t,e,r,n){let s=va(r.filePath);if(s===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(s>n*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let a=ya(r.filePath);await ha();try{let o=await ba(t,e,r,s,a);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await wa(o.uploadUrl,r.filePath,a,s))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let l=await xa(t,e,o.artifactId);return {success:l,storageKey:o.storageKey,artifactId:o.artifactId,error:l?null:"confirm_failed"}}finally{ma();}}async function qr(t,e,r,n){let s=new Map,a=r.map(async o=>{let i=await ka(t,e,o,n);s.set(o.filePath,i);});return await Promise.allSettled(a),s}function dt(t){let r=t.getGitMetadata()?.remoteUrl;return r?te(r):t.getConfig()?.projectName??re(process.cwd())}async function Ur(t,e,r,n,s){if(!t.isCloudMode()||e!=="realtime"&&e!=="both"||!await t.ensureValidToken())return null;let o=t.getGitMetadata(),i=N(),l=be(),d=he();return (await Fr(t.getEndpoint(),t.getAccessToken(),{runId:r,repoGitId:dt(t),branch:o?.branch??null,commit:o?.commitSha??null,commitMessage:o?.commitMessage??null,commitAuthor:o?.commitAuthor??null,startedAt:n,totalTests:null,ciProvider:i?.provider??null,ciRunUrl:i?.runUrl??null,environment:s??l.cloudPlatform??null,cloudPlatform:l.cloudPlatform??null,cloudBuildId:l.cloudBuildId??null,cloudSessionId:l.cloudSessionId??null,...d?{runType:d}:{},testType:"e2e"}))?.runId??null}var Ta=true,Ca=50;async function Sa(t,e,r,n){let s=new Map;if(!(e?.uploadArtifacts??Ta)||!await t.ensureValidToken())return s;let i=[],l=new Map;for(let c of n){if(c.artifacts.screenshot){let f=join(c.outputDir,c.artifacts.screenshot);i.push({filePath:f,runId:r,testId:c.testId,type:"screenshot"}),l.set(f,{testId:c.testId,field:"screenshot"});}if(c.artifacts.video){let f=join(c.outputDir,c.artifacts.video);i.push({filePath:f,runId:r,testId:c.testId,type:"video"}),l.set(f,{testId:c.testId,field:"video"});}}if(i.length===0)return s;let d=e?.artifactMaxSizeMb??Ca,u=await qr(t.getEndpoint(),t.getAccessToken(),i,d),p=new Map;for(let[c,f]of u){if(!f.success||!f.storageKey)continue;let h=l.get(c);if(!h)continue;let m=p.get(h.testId)??{};h.field==="screenshot"&&(m.screenshotKey=f.storageKey),h.field==="video"&&(m.videoKey=f.storageKey),p.set(h.testId,m);}for(let c of n){let f=p.get(c.testId);s.set(c.testId,{...c.artifacts,...f?.screenshotKey?{screenshotKey:f.screenshotKey}:{},...f?.videoKey?{videoKey:f.videoKey}:{}});}let g=Array.from(u.values()).filter(c=>c.success).length;return g>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${g} artifact(s) to cloud storage.
2582
+ `),s}async function ct(t,e,r,n,s,a,o,i,l,d,u){try{if(t.isCloudMode()&&s&&(r==="realtime"||r==="both")){let g=await t.ensureValidToken(),c=t.getGitMetadata(),f=st(u),h={finishedAt:o,duration:i,summary:l,...c?.commitMessage?{commitMessage:c.commitMessage}:{},testType:f.testType,...f.testType==="api"?{apiProtocol:f.apiProtocol,metadata:f.metadata}:{}};if(g){if(!await Br(t.getEndpoint(),t.getAccessToken(),s,h)){let y=e?.queueDirectory??".testrelic/queue";ne(y,n,"finalize","finalize_failed_after_retries",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",h,{"Content-Type":"application/json"});}}else {let m=e?.queueDirectory??".testrelic/queue";ne(m,n,"finalize",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",h,{"Content-Type":"application/json"});}}let p=new Map;if(t.isCloudMode()&&d&&d.length>0&&(p=await Sa(t,e,n,d)),t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await t.ensureValidToken()){let c=t.getGitMetadata(),f=N(),h=dt(t),m=Ra(a,p),y=at(m,h,c,f,u,be()),T=await Nr(t.getEndpoint(),t.getAccessToken(),y,async()=>await t.ensureValidToken()?t.getAccessToken():null);if(!T.success){let v=T,b=e?.queueDirectory??".testrelic/queue";ne(b,n,"batch",v.reason,v.targetEndpoint,v.method,v.payload,{"Content-Type":"application/json"});}}else {let c=e?.queueDirectory??".testrelic/queue",f=t.getGitMetadata(),h=N(),m=dt(t),y=at(a,m,f,h,void 0,be());ne(c,n,"batch",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs`,"POST",y,{"Content-Type":"application/json"});}await t.dispose();}catch{try{await t.dispose();}catch{}}}function Ra(t,e){if(e.size===0)return t;let r=t.timeline.map(n=>{let s=n.testId;if(!s)return n;let a=e.get(s);return a?{...n,...a.screenshotKey?{screenshotKey:a.screenshotKey}:{},...a.videoKey?{videoKey:a.videoKey}:{}}:n});return {...t,timeline:r}}function j(t){try{return readFileSync(t,"utf-8").split(`
2583
+ `).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function pt(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 Ma(t,e,r){let n=`${t}::${e}::${r}`;return createHash("sha256").update(n).digest("hex").substring(0,16)}function Na(t){return t.length<=3?"":t[t.length-2]}function Fa(t){let e=t.findIndex(r=>r.status==="passed");return e>0?`passed on retry ${e}`:null}function Da(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 Ba(){let t=platform();return t==="win32"?"Windows":t==="darwin"?"macOS":"Linux"}function Oa(t){let e=t.parent?.project?.()?.use;if(!e)return;let{browserName:r,channel:n}=e;if(n){let a=n.toLowerCase();return a==="chrome"||a==="chrome-stable"?"Chrome":a.startsWith("chrome-beta")?"Chrome Beta":a.startsWith("chrome-dev")?"Chrome Dev":a.startsWith("chrome-canary")?"Chrome Canary":a==="msedge"||a==="msedge-stable"?"Microsoft Edge":a.startsWith("msedge-beta")?"Edge Beta":a.startsWith("msedge-dev")?"Edge Dev":a.startsWith("msedge-canary")?"Edge Canary":n}if(r){let a=r.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":r}let s=e.defaultBrowserType;if(s){let a=s.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":s}}function qa(t,e,r){let n=r.parent?.project?.(),s="unknown";n!==void 0&&(n.use.isMobile===true?s="mobile":s="e2e");let a=["e2e","api","unit","mobile"];for(let l of a)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 Ha="__testrelic_api_config";function Ua(t){return JSON.stringify(t,(e,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var ke=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=Et(e),this.apiConfig=Pt(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 a=r.allTests().length;this.activeReportMode=a>=this.config.streamingThreshold?"streaming":"embedded";}else this.activeReportMode=this.config.reportMode;let n=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${n} tests)
2584
+ `),this.activeReportMode==="streaming"){let a=dirname(this.config.outputPath);this.streamingWriter=new Y(a);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&&it(this.cloudClient.getEndpoint(),i,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",o),process.on("SIGINT",o);}if(this.config.includeArtifacts){let a=dirname(this.config.outputPath);this.runTimestamp=dr(join(a,"artifacts"));try{gr(join(a,"artifacts"));}catch{}}let s=N();this.detectedOs=Ba(),this.detectedSource=Da(s);try{this.cloudClient=new ge(this.config.cloud),await this.cloudClient.initialize(),this.cloudRunId=await Ur(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource);}catch{this.cloudClient?.switchToLocalMode("init_error");}if(this.activeReportMode!=="streaming"){let a=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let o=this.cloudClient.getAccessToken();o&&it(this.cloudClient.getEndpoint(),o,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",a),process.on("SIGINT",a);}}catch{}}onTestBegin(e,r){try{e.annotations.push({type:Ha,description:Ua(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let n=r,s=e.outcome(),a;s==="flaky"?a="flaky":s==="skipped"?a="skipped":a=pt(n.status);let o=n.startTime.toISOString(),i=new Date(n.startTime.getTime()+n.duration).toISOString(),l=e.tags?[...e.tags]:e.annotations.filter(R=>R.type==="tag").map(R=>R.description??""),d=Or(n.attachments,e.annotations,e.title,a==="skipped");(d.navigations.length>0||d.networkRequestsCount>0||d.apiCallsCount>0)&&(this.fixtureDataReceived=!0);let u=null;if(a==="failed"||a==="flaky"){let S=(a==="flaky"?e.results.find(O=>O.status!=="passed")?.errors??[]:n.errors)[0];if(S){let O=Nt(this.config.redactPatterns),G=S.location?.line??null,J=null;this.config.includeCodeSnippets&&G!==null&&S.location?.file&&(J=Mt(S.location.file,G,this.config.codeContextLines),J&&(J=O(J))),u={message:O(S.message??"Unknown error"),line:G,code:J,stack:this.config.includeStackTrace&&S.stack?O(S.stack):null};}}let p=e.titlePath().filter(Boolean),g=relative(this.rootDir||".",e.location.file),c=Na(p),f=p.join(" > "),h=g,m=Ma(h,c,f),y=qa(l,h,e),T=y!=="mobile"&&d.apiCallsCount>0?"api":y,v=s==="flaky",b=Fa(e.results),C=pt(e.expectedStatus),w=pt(n.status),k=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments){let R=dirname(this.config.outputPath),S=p[p.length-1]??e.title;k=cr(n.attachments,S,n.retry,R,this.runTimestamp||void 0);}let A=this.config.includeActionSteps&&n.steps?br(n.steps,n.startTime):null,H=Oa(e),P={titlePath:p,title:f,status:a,duration:n.duration,startedAt:o,completedAt:i,retryCount:e.results.length-1,retry:n.retry,tags:l,failure:u,specFile:g,navigations:d.navigations,testId:m,filePath:h,suiteName:c,testType:T,isFlaky:v,retryStatus:b,expectedStatus:C,actualStatus:w,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},yt=d.consoleLogsFile&&d.consoleLogsCount>0?j(d.consoleLogsFile):void 0,vt=d.networkRequestsFile&&d.networkRequestsCount>0?j(d.networkRequestsFile):void 0;this.cloudTestsBuffer.push({testId:m,title:f,status:a,duration:n.duration,suiteName:c,filePath:h,testType:T,isFlaky:v,startedAt:o,completedAt:i,tags:l,failure:u,retry:n.retry,retryCount:e.results.length-1,retryStatus:b,browser:H,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...A&&A.length>0?{actions:A}:{},...yt?{consoleLogs:yt}:{},...vt?{networkRequests:vt}:{}});try{let R=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(R==="realtime"||R==="both")){let S=this.cloudClient.getAccessToken();S&&Dr(this.cloudClient.getEndpoint(),S,this.cloudRunId,this.buildCloudTestPayload(P));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let R=Re(h,p,e.id??"",n.retry),S=n.retry===e.results.length-1,O={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,O,{networkRequestsFile:d.networkRequestsFile,consoleLogsFile:d.consoleLogsFile,apiCallsFile:d.apiCallsFile});let G={id:R,title:p[p.length-1]??e.title,titlePath:p,filePath:h,status:a,duration:n.duration,project:p[1]??"",retryIndex:n.retry,tags:l,hasNetworkData:d.networkRequestsCount>0,hasConsoleData:d.consoleLogsCount>0,hasArtifacts:k!==null,hasActionSteps:(A?.length??0)>0,errorMessage:u?.message?.split(`
2585
+ `)[0]??null,networkCount:d.networkRequestsCount,consoleCount:d.consoleLogsCount,actionCount:A?.length??0,isRetry:!S};if(this.testIndex.push(G),S)switch(this.summaryCounters.total++,a){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.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)}),P.actions=null,P.apiAssertions=null,P.navigations=[],P.artifacts=null,P.failure=null,P.networkRequestsFile=null,P.consoleLogsFile=null,P.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(P),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(e){try{let r=new Date().toISOString(),n=new Date(this.startedAt).getTime(),a=new Date(r).getTime()-n,o=this.activeReportMode==="streaming"?this.testIndex.some(l=>l.status!=="skipped"):this.collectedTests.some(l=>l.status!=="skipped");!this.fixtureDataReceived&&o&&process.stderr.write(`
2586
2586
  \u26A0 TestRelic: No fixture data received from any test.
2587
2587
  To enable network logs, video sync, and timeline tracking, import the TestRelic fixture:
2588
2588
  import { test, expect } from '@testrelic/playwright-analytics/fixture';
2589
2589
  instead of:
2590
2590
  import { test, expect } from '@playwright/test';
2591
2591
 
2592
- `),await ir();let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let l=dirname(this.config.outputPath);i=cr(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,a,e,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=mr(u,l.length),g={schemaVersion:ne,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:a,summary:f,ci:P(),metadata:this.config.metadata,timeline:l,shardRunIds:null};if(this.writeReport(g),await ze(g,this.config,i),Je(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 lt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,g,r,a,f,c,p);}}}catch{}}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let e=dirname(this.config.outputPath),r=[];for(let n of this.collectedTests)n.artifacts&&r.push({testId:n.testId,artifacts:n.artifacts,outputDir:e});return r}async finalizeStreamingReport(e,r,n,s){if(!this.streamingWriter)return;let{totalApiCalls:a,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:a,totalAssertions:o,totalNavigations:i,totalNetworkRequests:l,totalConsoleLogs:d,totalActionSteps:u};let f=new Map,g=new Map;for(let w of this.testIndex){let C=`${w.filePath}::${w.titlePath.join(" > ")}`,y=f.get(C);(y===void 0||w.retryIndex>y)&&f.set(C,w.retryIndex);}let c=0;for(let w of this.testIndex){let C=`${w.filePath}::${w.titlePath.join(" > ")}`,y=f.get(C);if(w.isRetry=w.retryIndex<y,w.isRetry)continue;switch(c++,this.summaryCounters.total++,w.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=g.get(w.filePath);switch(k||(k={filePath:w.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},g.set(w.filePath,k)),k.total++,w.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(g.values());this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let h={reporterTotal:this.summaryCounters.total,indexTotal:c,playwrightStatus:n.status,isValid:this.summaryCounters.total===c};h.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${h.reporterTotal}, index: ${h.indexTotal}
2593
- `);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:p,enrichedSummary:m,validation:h,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(b);let T={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(T),await ze(this.buildStreamingReport(b,m,e,r),this.config,s),Je(m,this.config.outputPath,this.config.htmlReportPath,this.config.quiet);let v=this.streamingWriter.getReportDir();if(process.stderr.write(`[testrelic] Streaming report written to ${v}
2592
+ `),await lr();let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let l=dirname(this.config.outputPath);i=pr(l,this.runTimestamp);let d=join(l,"artifact-manifest.json"),u=JSON.stringify(i),p=d+".tmp";writeFileSync(p,u,"utf-8"),renameSync(p,d);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await this.finalizeStreamingReport(r,a,e,i);else {let l=this.buildTimeline(),d=new Map;for(let c of this.collectedTests){let f=d.get(c.testId);(!f||c.retry>f.retry)&&d.set(c.testId,c);}let u=Array.from(d.values()),p=vr(u,l.length),g={schemaVersion:se,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:a,summary:p,ci:N(),metadata:this.config.metadata,timeline:l,shardRunIds:null};if(this.writeReport(g),await je(g,this.config,i),Ke(p,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient){let c=this.collectArtifactEntries(),f=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await ct(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,g,r,a,p,c,f);}}}catch{}}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let e=dirname(this.config.outputPath),r=[];for(let n of this.collectedTests)n.artifacts&&r.push({testId:n.testId,artifacts:n.artifacts,outputDir:e});return r}async finalizeStreamingReport(e,r,n,s){if(!this.streamingWriter)return;let{totalApiCalls:a,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:a,totalAssertions:o,totalNavigations:i,totalNetworkRequests:l,totalConsoleLogs:d,totalActionSteps:u};let p=new Map,g=new Map;for(let b of this.testIndex){let C=`${b.filePath}::${b.titlePath.join(" > ")}`,w=p.get(C);(w===void 0||b.retryIndex>w)&&p.set(C,b.retryIndex);}let c=0;for(let b of this.testIndex){let C=`${b.filePath}::${b.titlePath.join(" > ")}`,w=p.get(C);if(b.isRetry=b.retryIndex<w,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=g.get(b.filePath);switch(k||(k={filePath:b.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},g.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 f=Array.from(g.values());this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let h={reporterTotal:this.summaryCounters.total,indexTotal:c,playwrightStatus:n.status,isValid:this.summaryCounters.total===c};h.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${h.reporterTotal}, index: ${h.indexTotal}
2593
+ `);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:{}},y={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:e,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:f,enrichedSummary:m,validation:h,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(y);let T={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(T),await je(this.buildStreamingReport(y,m,e,r),this.config,s),Ke(m,this.config.outputPath,this.config.htmlReportPath,this.config.quiet);let v=this.streamingWriter.getReportDir();if(process.stderr.write(`[testrelic] Streaming report written to ${v}
2594
2594
  [testrelic] ${this.testIndex.length} test detail files on disk
2595
2595
  [testrelic] View report: npx testrelic serve ${v}
2596
2596
  `),this.streamingWriter.getWriteErrors().length>0&&process.stderr.write(`[testrelic] WARNING: ${this.streamingWriter.getWriteErrors().length} write error(s) during streaming
2597
- `),this.streamingWriter.dispose(),this.cloudClient){let w=this.buildStreamingReport(b,m,e,r),C=this.collectArtifactEntries(),y=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await lt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,w,e,r,m,C,y);}this.testIndex.length=0,this.collectedTests.length=0,this.pendingArtifactEntries.length=0,this.cloudTestsBuffer.length=0,this.streamingWriter=null,this.cloudClient=null;}buildStreamingReport(e,r,n,s){return {schemaVersion:ne,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:n,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 n=e.heapUsed/e.heapTotal;n>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
2597
+ `),this.streamingWriter.dispose(),this.cloudClient){let b=this.buildStreamingReport(y,m,e,r),C=this.collectArtifactEntries(),w=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await ct(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,b,e,r,m,C,w);}this.testIndex.length=0,this.collectedTests.length=0,this.pendingArtifactEntries.length=0,this.cloudTestsBuffer.length=0,this.streamingWriter=null,this.cloudClient=null;}buildStreamingReport(e,r,n,s){return {schemaVersion:se,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:n,totalDuration:s,summary:r,ci:N(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let e=process.memoryUsage(),r=e.heapUsed/1024/1024;if(r<200)return;let n=e.heapUsed/e.heapTotal;n>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
2598
2598
  `),this.switchToStreamingMode()):n>.8&&process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
2599
- `);}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let e=dirname(this.config.outputPath);this.streamingWriter=new K(e);for(let r of this.collectedTests){let n=Se(r.filePath,r.titlePath,r.testId,r.retry),s={id:n,navigations:r.navigations??[],apiAssertions:r.apiAssertions??[],actions:r.actions??[],artifacts:r.artifacts,failureDiagnostic:r.failure,hasNetworkFile:r.networkRequestsFile!==null,networkRequestsCount:r.networkRequestsCount,hasConsoleFile:r.consoleLogsFile!==null,consoleLogsCount:r.consoleLogsCount,hasApiCallsFile:r.apiCallsFile!==null,apiCallsCount:r.apiCallsCount,startedAt:r.startedAt};this.streamingWriter.writeTestDetail(n,s,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let a={id:n,title:r.titlePath[r.titlePath.length-1]??r.title,titlePath:r.titlePath,filePath:r.filePath,status:r.status,duration:r.duration,project:r.titlePath[1]??"",retryIndex:r.retry,tags:r.tags,hasNetworkData:r.networkRequestsCount>0,hasConsoleData:r.consoleLogsCount>0,hasArtifacts:r.artifacts!==null,hasActionSteps:(r.actions?.length??0)>0,errorMessage:r.failure?.message?.split(`
2600
- `)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,isRetry:!1};switch(this.testIndex.push(a),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 hr(e,{navigationTypes:this.config.navigationTypes})}readJsonlFile(e){if(!e)return null;let r=z(e);return r.length>0?r:null}toTestResult(e,r){let n=null,s=null,a=null;return r?.loadFiles&&(n=this.readJsonlFile(e.networkRequestsFile),s=this.readJsonlFile(e.consoleLogsFile),a=this.readJsonlFile(e.apiCallsFile)),{title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,retryStatus:e.retryStatus,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,networkRequests:n,apiCalls:a,apiAssertions:e.apiAssertions,actions:e.actions??null,consoleLogs:s}}buildCloudTestPayload(e){let r={title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retry:e.retry,retryCount:e.retryCount,retryStatus:e.retryStatus,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,apiAssertions:e.apiAssertions,actions:e.actions??[],navigations:e.navigations??[],steps:e.actions??[],browser:e.browser,os:e.os,source:e.source};if(e.consoleLogsFile&&(r.consoleLogs=z(e.consoleLogsFile)),e.networkRequestsFile&&(r.networkRequests=z(e.networkRequestsFile)),e.apiCallsFile){let n=z(e.apiCallsFile);r.apiCalls=n,(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=n.map(s=>{let a=s;return {method:a.method??"GET",url:a.url??"",status:a.responseStatusCode??0,statusCode:a.responseStatusCode??0,type:"xhr",size:typeof a.responseBody=="string"?a.responseBody.length:0,duration:a.responseTimeMs??0,responseTimeMs:a.responseTimeMs??0,requestHeaders:a.requestHeaders??null,responseHeaders:a.responseHeaders??null,requestBody:a.requestBody??null,responseBody:a.responseBody??null,timestamp:a.timestamp??new Date().toISOString(),startedAt:a.timestamp??new Date().toISOString()}}));}return r}writeReport(e){try{let r=JSON.stringify(e),n=this.config.outputPath,s=dirname(n);mkdirSync(s,{recursive:!0});let a=n+".tmp";writeFileSync(a,r,"utf-8"),renameSync(a,n);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
2601
- `);}}};var ja=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function $a(t){let e=t.toLowerCase();return ja.some(r=>e.includes(r))}var ke=class t{constructor(e,r){this.page=e;this.records=[];this.listeners=[];this.currentNetworkCounter=null;this.pendingRequests=new Map;this.networkWriter=null;this.consoleWriter=null;this.pendingBodyReads=[];this.requestIdCounter=0;this.networkRequestCount=0;this.consoleLogCount=0;this.includeNetworkStats=r?.includeNetworkStats??true,this.origGoto=e.goto.bind(e),this.origGoBack=e.goBack.bind(e),this.origGoForward=e.goForward.bind(e),this.origReload=e.reload.bind(e);try{this.includeNetworkStats&&(this.networkWriter=new E("network")),this.consoleWriter=new E("console");}catch{}this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async finalizeCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[,e]of this.pendingRequests)this.networkWriter&&(this.networkWriter.append({url:e.url,method:e.method,resourceType:e.resourceType,statusCode:0,responseTimeMs:Date.now()-e.startTimeMs,startedAt:e.startedAt,requestHeaders:e.headers,requestBody:e.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:e.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.networkRequestCount++);this.pendingRequests.clear(),this.networkWriter?.close(),this.consoleWriter?.close();}static mapConsoleType(e){switch(e){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getFileData(){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}});let e=this.records.map(r=>({url:r.url,navigationType:r.navigationType,timestamp:r.timestamp,domContentLoadedAt:r.domContentLoadedAt,networkIdleAt:r.networkIdleAt,networkStats:r.networkStats}));return this.includeNetworkStats?await this.finalizeCapturedRequests():this.consoleWriter?.close(),{navigations:e,networkRequestsFile:this.networkWriter?.getCount()?this.networkWriter.getPath():null,networkRequestsCount:this.networkWriter?.getCount()??0,consoleLogsFile:this.consoleWriter?.getCount()?this.consoleWriter.getPath():null,consoleLogsCount:this.consoleWriter?.getCount()??0}}async flushLegacyAnnotations(e){}dispose(){this.page.goto=this.origGoto,this.page.goBack=this.origGoBack,this.page.goForward=this.origGoForward,this.page.reload=this.origReload;for(let{event:e,handler:r}of this.listeners)this.page.off(e,r);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}getRecords(){return this.records}interceptMethods(){let e=this,r=this.page;r.goto=async function(n,s){return e.recordNavigation(n,"goto"),e.origGoto(n,s)},r.goBack=async function(n){let s=await e.origGoBack(n);return e.recordNavigation(r.url(),"back"),s},r.goForward=async function(n){let s=await e.origGoForward(n);return e.recordNavigation(r.url(),"forward"),s},r.reload=async function(n){return e.recordNavigation(r.url(),"refresh"),e.origReload(n)};}attachListeners(){let e=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",e),this.listeners.push({event:"domcontentloaded",handler:e});let r=s=>{try{let a=s;if(typeof a.parentFrame=="function"&&a.parentFrame()!==null)return;let o=a.url(),i=this.records[this.records.length-1];if(i&&Date.now()-new Date(i.timestamp).getTime()<50&&i.url===o)return;this.recordNavigation(o,"navigation");}catch{}};this.page.on("framenavigated",r),this.listeners.push({event:"framenavigated",handler:r});let n=s=>{try{let a=s,o=a.type(),i=a.text();if(o==="debug"&&i.startsWith("__testrelic_nav:")){try{let l=JSON.parse(i.slice(16));l.type&&l.url&&this.recordNavigation(l.url,l.type);}catch{}return}{let l=null;try{let u=a.location();u&&u.url&&(l=`${u.url}:${u.lineNumber}:${u.columnNumber}`);}catch{}let d=t.mapConsoleType(o);this.consoleWriter&&(this.consoleWriter.append({level:d,text:i,timestamp:new Date().toISOString(),location:l}),this.consoleLogCount++);}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=i=>{this.currentNetworkCounter&&this.currentNetworkCounter.totalRequests++;try{let l=i,d=String(this.requestIdCounter++),u=l.postData()??null,f={url:l.url(),method:l.method(),resourceType:this.mapResourceType(l.resourceType()),headers:l.headers(),postData:u,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now()};this.pendingRequests.set(d,f),i.__testrelic_id=d;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let a=i=>{try{let l=i;if(this.currentNetworkCounter){let b=l.status();b>=400&&(this.currentNetworkCounter.failedRequests++,this.currentNetworkCounter.failedRequestUrls.push(b+" "+l.url()));let T=l.headers()["content-length"];T&&(this.currentNetworkCounter.totalBytes+=parseInt(T,10)||0);let v=l.request().resourceType(),w=this.mapResourceType(v);this.currentNetworkCounter.byType[w]++;}let d=l.request().__testrelic_id;if(!d)return;let u=this.pendingRequests.get(d);if(!u)return;this.pendingRequests.delete(d);let f=Date.now()-u.startTimeMs,g=l.headers(),c=g["content-type"]??null,p=parseInt(g["content-length"]??"0",10)||0,h=c?!$a(c):!1,m=(async()=>{let b=null;if(!h)try{b=(await l.body()).toString("utf-8");}catch{}let T={url:u.url,method:u.method,resourceType:u.resourceType,statusCode:l.status(),responseTimeMs:f,startedAt:u.startedAt,requestHeaders:u.headers,requestBody:u.postData,responseBody:b,responseHeaders:g,contentType:c,responseSize:p,requestBodyTruncated:u.postDataTruncated,responseBodyTruncated:!1,isBinary:h,error:null};this.networkWriter&&(this.networkWriter.append(T),this.networkRequestCount++);})();this.pendingBodyReads.push(m);}catch{}};this.page.on("response",a),this.listeners.push({event:"response",handler:a});let o=i=>{if(this.currentNetworkCounter){this.currentNetworkCounter.failedRequests++;try{let l=i;this.currentNetworkCounter.failedRequestUrls.push("ERR "+l.url());}catch{}}try{let l=i,d=l.__testrelic_id;if(!d)return;let u=this.pendingRequests.get(d);if(!u)return;this.pendingRequests.delete(d);let f={url:u.url,method:u.method,resourceType:u.resourceType,statusCode:0,responseTimeMs:Date.now()-u.startTimeMs,startedAt:u.startedAt,requestHeaders:u.headers,requestBody:u.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:u.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:l.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(f),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",o),this.listeners.push({event:"requestfailed",handler:o});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let e=history.pushState.bind(history),r=history.replaceState.bind(history);history.pushState=function(...n){e(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){r(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(e,r){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}}),this.records.push({url:e,navigationType:r,timestamp:new Date().toISOString()}),this.includeNetworkStats&&(this.currentNetworkCounter=this.createNetworkCounter());}createNetworkCounter(){return {totalRequests:0,failedRequests:0,failedRequestUrls:[],totalBytes:0,byType:{xhr:0,document:0,script:0,stylesheet:0,image:0,font:0,other:0}}}mapResourceType(e){switch(e){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};var zr=Symbol.for("__testrelic_call_id"),Wa="__testrelic_api_assertions",$=new WeakMap,j=class{constructor(){this.assertions=[];this.currentCallId=null;}recordAssertion(e){this.assertions.push(e);}getAssertions(){return this.assertions}setCurrentCallId(e){this.currentCallId=e;}getCurrentCallId(){return this.currentCallId}getData(){return [...this.assertions]}flushLegacyAnnotations(e){this.assertions.length!==0&&e.annotations.push({type:Wa,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}};var jr="[REDACTED]";function pt(t,e){if(t===null||e.length===0)return t;let r=new Set(e.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(t))Object.hasOwn(t,s)&&(n[s]=r.has(s.toLowerCase())?jr:t[s]);return n}function Te(t,e){if(t===null||e.length===0)return t;let r;try{r=JSON.parse(t);}catch{return t}if(typeof r!="object"||r===null)return t;let n=new Set(e),s=ut(r,n);return JSON.stringify(s)}function ut(t,e){if(Array.isArray(t))return t.map(r=>ut(r,e));if(typeof t=="object"&&t!==null){let r={};for(let n of Object.keys(t)){if(!Object.hasOwn(t,n))continue;let s=t[n];e.has(n)?r[n]=jr:r[n]=ut(s,e);}return r}return t}function Wr(t,e,r){if(r.length>0){for(let n of r)if($r(t,n))return false}if(e.length>0){for(let n of e)if($r(t,n))return true;return false}return true}function $r(t,e){try{return e instanceof RegExp?e.test(t):Va(e).test(t)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(e)}`),false}}function Va(t){let e="",r=0;for(;r<t.length;){let n=t[r];n==="*"&&t[r+1]==="*"?(e+=".*",r+=2,t[r]==="/"&&r++):n==="*"?(e+="[^/]*",r++):n==="?"?(e+="[^/]",r++):".+^${}()|[]\\".includes(n)?(e+="\\"+n,r++):(e+=n,r++);}return new RegExp(e)}var Ga=["get","post","put","patch","delete","head","fetch"],Ja=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Ka(t){let e=t.toLowerCase();return Ja.some(r=>e.includes(r))}function Ya(t){if(!t)return null;if(t.data!==void 0&&t.data!==null){let e=t.data;return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString("base64"):JSON.stringify(e)}if(t.form!==void 0&&t.form!==null)return JSON.stringify(t.form);if(t.multipart!==void 0&&t.multipart!==null){let e=t.multipart,r={};for(let[n,s]of Object.entries(e))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?r[n]=String(s):s&&typeof s=="object"&&"name"in s?r[n]=`[file: ${s.name}]`:r[n]="[binary]";return JSON.stringify(r)}return null}var Ce=class Ce{constructor(e,r,n){this.originals=new Map;this.apiCallWriter=null;this.callCounter=0;this.apiCallCount=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=e,this.assertionTracker=r??null,this.apiConfig=n??Ce.DEFAULT_API_CONFIG;try{this.apiCallWriter=new E("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(e){return e!=null&&typeof e=="object"?$.get(e)??null:this.primitiveCallIds.get(e)??null}intercept(){for(let r of Ga){let n=this.context[r].bind(this.context);this.originals.set(r,n),this.context[r]=this.createWrapper(r,n);}let e=this.context.dispose.bind(this.context);this.originals.set("dispose",e),this.context.dispose=async r=>(this.disposed=true,e(r));}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0}}flushLegacyAnnotations(e){}dispose(){for(let[e,r]of this.originals)this.context[e]=r;this.originals.clear(),this.apiCallWriter?.close(),this.callCounter=0,this.apiCallCount=0,this._lastCallId=null,this.primitiveCallIds.clear();}get isDisposed(){return this.disposed}getCapturedCallCount(){return this.apiCallCount}tagResponseMethods(e,r){let n=this,s=e.headers.bind(e);e.headers=function(){let c=s();return $.set(c,r),c};let a=e.headersArray.bind(e);e.headersArray=function(){let c=a();return $.set(c,r),c};let o=e.json.bind(e);e.json=async function(){let c=await o();return c!=null&&typeof c=="object"&&$.set(c,r),c};let i=e.status.bind(e);e.status=function(){let c=i();return n.primitiveCallIds.set(c,r),c};let l=e.statusText.bind(e);e.statusText=function(){let c=l();return n.primitiveCallIds.set(c,r),c};let d=e.ok.bind(e);e.ok=function(){let c=d();return n.primitiveCallIds.set(c,r),c};let u=e.text.bind(e);e.text=async function(){let c=await u();return n.primitiveCallIds.set(c,r),c};let f=e.body.bind(e);e.body=async function(){let c=await f();return $.set(c,r),c};}createWrapper(e,r){let n=this;return async function(a,o){if(!Wr(a,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return r(a,o);let i=`api-call-${n.callCounter++}`,l=new Date().toISOString(),d=e==="fetch"?(o?.method??"GET").toUpperCase():e.toUpperCase(),u=Ya(o),f=performance.now();n._lastCallId=i,n.assertionTracker&&n.assertionTracker.setCurrentCallId(i);let g;try{g=await r(a,o);}catch(c){let p=performance.now();try{let h=n.apiConfig.captureRequestBody?Te(u,n.apiConfig.redactBodyFields):null,m={id:i,timestamp:l,method:d,url:a,requestHeaders:null,requestBody:h,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((p-f)*100)/100,isBinary:!1,error:c instanceof Error?c.message:String(c)};n.apiCallWriter&&(n.apiCallWriter.append(m),n.apiCallCount++);}catch{}throw c}try{let c=performance.now(),p=g.headers(),h=p["content-type"]??null,m=h?!Ka(h):!1,b=null;n.apiConfig.captureRequestHeaders&&o?.headers&&(b=o.headers);let T=null;n.apiConfig.captureResponseHeaders&&(T=p);let v=n.apiConfig.captureRequestBody?u:null,w=null;if(n.apiConfig.captureResponseBody)try{m?w=(await g.body()).toString("base64"):w=await g.text();}catch{}b=pt(b,n.apiConfig.redactHeaders),T=pt(T,n.apiConfig.redactHeaders),v=Te(v,n.apiConfig.redactBodyFields),w=Te(w,n.apiConfig.redactBodyFields);let C={id:i,timestamp:l,method:d,url:g.url(),requestHeaders:b,requestBody:v,responseStatusCode:g.status(),responseStatusText:g.statusText(),responseHeaders:T,responseBody:w,responseTimeMs:Math.round((c-f)*100)/100,isBinary:m,error:null};n.apiCallWriter&&(n.apiCallWriter.append(C),n.apiCallCount++);}catch{}try{g[zr]=i,n.tagResponseMethods(g,i);}catch{}return g}}};Ce.DEFAULT_API_CONFIG=Object.freeze({trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]});var W=Ce;var Xa="__testrelic_api_config",Qa="__testrelic_config_trackApiCalls";function gt(t){let e=t.annotations.find(n=>n.type===Xa&&n.description!==void 0);if(e)try{return JSON.parse(e.description,ei)}catch{}let r=t.annotations.find(n=>n.type===Qa&&n.description!==void 0);return r?{trackApiCalls:r.description!=="false",captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}:{trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}}function ei(t,e){if(typeof e=="object"&&e!==null&&e.__regexp===true&&typeof e.source=="string"){let{source:r,flags:n}=e;return new RegExp(r,n)}return e}var Kr={page:async({page:t},e,r)=>{let n=new ke(t);try{await n.init();}catch{}await e(t);try{let{navigations:s,networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:l}=await n.getFileData(),d={testRelicData:!0,version:PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:l,apiCallsFile:null,apiCallsCount:0};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:t},e,r)=>{let n=gt(r);if(!n.trackApiCalls){await e(t);return}let s=new j,a=new W(t,s,n);a.intercept(),await e(t);try{let{apiCallsFile:o,apiCallsCount:i}=a.getFileData(),l=n.captureAssertions?s.getData():[],d={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],apiAssertions:l,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:o,apiCallsCount:i};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};test.extend(Kr);var si={request:async({request:t},e,r)=>{let n=gt(r);if(!n.trackApiCalls){await e(t);return}let s=new j,a=new W(t,s,n);a.intercept();let o=null;try{o=new E("api-console");}catch{}let i=0,l=process.stdout.write,d=process.stderr.write;process.stdout.write=function(u,...f){try{let g=typeof u=="string"?u:Buffer.isBuffer(u)?u.toString("utf-8"):String(u);!g.startsWith("[testrelic]")&&!g.startsWith("\u2139 TestRelic")&&!g.startsWith("\u2713 TestRelic")&&!g.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stdout",text:g.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return l.apply(process.stdout,[u,...f])},process.stderr.write=function(u,...f){try{let g=typeof u=="string"?u:Buffer.isBuffer(u)?u.toString("utf-8"):String(u);!g.startsWith("[testrelic]")&&!g.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stderr",text:g.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return d.apply(process.stderr,[u,...f])};try{await e(t);}finally{process.stdout.write=l,process.stderr.write=d;}try{o?.close();let{apiCallsFile:u,apiCallsCount:f}=a.getFileData(),g=n.captureAssertions?s.getData():[],c={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],apiAssertions:g,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:i>0?o?.getPath()??null:null,consoleLogsCount:i,apiCallsFile:u,apiCallsCount:f};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(c)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};var Yr="@testrelic/playwright-analytics";function ii(t){return Array.isArray(t)?t.some(e=>Array.isArray(e)&&typeof e[0]=="string"&&e[0]===Yr):false}function oi(t,e){let n={video:"on",screenshot:"on",trace:"on",...t.use??{}},s;Array.isArray(t.reporter)?s=t.reporter:typeof t.reporter=="string"?s=[[t.reporter]]:s=[["list"]];let a=ii(s)?s:[...s,[Yr,e??{}]];return defineConfig({...t,use:n,reporter:a})}var Zr=false;function wd(t,e,r="manual_record"){if(!t||!t.annotations){Zr||(Zr=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
2602
- `));return}let n={url:e,navigationType:r,timestamp:new Date().toISOString()};t.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}export{ne as SCHEMA_VERSION,xe as default,oi as defineConfig,wd as recordNavigation,si as testRelicApiFixture,Kr as testRelicFixture};//# sourceMappingURL=index.js.map
2599
+ `);}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let e=dirname(this.config.outputPath);this.streamingWriter=new Y(e);for(let r of this.collectedTests){let n=Re(r.filePath,r.titlePath,r.testId,r.retry),s={id:n,navigations:r.navigations??[],apiAssertions:r.apiAssertions??[],actions:r.actions??[],artifacts:r.artifacts,failureDiagnostic:r.failure,hasNetworkFile:r.networkRequestsFile!==null,networkRequestsCount:r.networkRequestsCount,hasConsoleFile:r.consoleLogsFile!==null,consoleLogsCount:r.consoleLogsCount,hasApiCallsFile:r.apiCallsFile!==null,apiCallsCount:r.apiCallsCount,startedAt:r.startedAt};this.streamingWriter.writeTestDetail(n,s,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let a={id:n,title:r.titlePath[r.titlePath.length-1]??r.title,titlePath:r.titlePath,filePath:r.filePath,status:r.status,duration:r.duration,project:r.titlePath[1]??"",retryIndex:r.retry,tags:r.tags,hasNetworkData:r.networkRequestsCount>0,hasConsoleData:r.consoleLogsCount>0,hasArtifacts:r.artifacts!==null,hasActionSteps:(r.actions?.length??0)>0,errorMessage:r.failure?.message?.split(`
2600
+ `)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,isRetry:!1};switch(this.testIndex.push(a),this.summaryCounters.total++,r.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.summaryCounters.totalApiCalls+=r.apiCallsCount,this.summaryCounters.totalAssertions+=r.apiAssertions?.length??0,this.summaryCounters.totalNavigations+=r.navigations?.length??0,this.summaryCounters.totalNetworkRequests+=r.networkRequestsCount,this.summaryCounters.totalConsoleLogs+=r.consoleLogsCount,this.summaryCounters.totalActionSteps+=r.actions?.length??0;}this.collectedTests.length=0;}catch{}}buildTimeline(){let e=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls:null,apiAssertions:r.apiAssertions,testId:r.testId,filePath:r.filePath,suiteName:r.suiteName,testType:r.testType,isFlaky:r.isFlaky,retryStatus:r.retryStatus,expectedStatus:r.expectedStatus,actualStatus:r.actualStatus,artifacts:r.artifacts,networkRequests:null,actions:r.actions,consoleLogs:null}));return yr(e,{navigationTypes:this.config.navigationTypes})}readJsonlFile(e){if(!e)return null;let r=j(e);return r.length>0?r:null}toTestResult(e,r){let n=null,s=null,a=null;return r?.loadFiles&&(n=this.readJsonlFile(e.networkRequestsFile),s=this.readJsonlFile(e.consoleLogsFile),a=this.readJsonlFile(e.apiCallsFile)),{title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,retryStatus:e.retryStatus,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,networkRequests:n,apiCalls:a,apiAssertions:e.apiAssertions,actions:e.actions??null,consoleLogs:s}}buildCloudTestPayload(e){let r={title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retry:e.retry,retryCount:e.retryCount,retryStatus:e.retryStatus,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,apiAssertions:e.apiAssertions,actions:e.actions??[],navigations:e.navigations??[],steps:e.actions??[],browser:e.browser,os:e.os,source:e.source};if(e.consoleLogsFile&&(r.consoleLogs=j(e.consoleLogsFile)),e.networkRequestsFile&&(r.networkRequests=j(e.networkRequestsFile)),e.apiCallsFile){let n=j(e.apiCallsFile);r.apiCalls=n,(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=n.map(s=>{let a=s;return {method:a.method??"GET",url:a.url??"",status:a.responseStatusCode??0,statusCode:a.responseStatusCode??0,type:"xhr",size:typeof a.responseBody=="string"?a.responseBody.length:0,duration:a.responseTimeMs??0,responseTimeMs:a.responseTimeMs??0,requestHeaders:a.requestHeaders??null,responseHeaders:a.responseHeaders??null,requestBody:a.requestBody??null,responseBody:a.responseBody??null,timestamp:a.timestamp??new Date().toISOString(),startedAt:a.timestamp??new Date().toISOString()}}));}return r}writeReport(e){try{let r=JSON.stringify(e),n=this.config.outputPath,s=dirname(n);mkdirSync(s,{recursive:!0});let a=n+".tmp";writeFileSync(a,r,"utf-8"),renameSync(a,n);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
2601
+ `);}}};var Va=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Ga(t){let e=t.toLowerCase();return Va.some(r=>e.includes(r))}var Te=class t{constructor(e,r){this.page=e;this.records=[];this.listeners=[];this.currentNetworkCounter=null;this.pendingRequests=new Map;this.networkWriter=null;this.consoleWriter=null;this.pendingBodyReads=[];this.requestIdCounter=0;this.networkRequestCount=0;this.consoleLogCount=0;this.includeNetworkStats=r?.includeNetworkStats??true,this.origGoto=e.goto.bind(e),this.origGoBack=e.goBack.bind(e),this.origGoForward=e.goForward.bind(e),this.origReload=e.reload.bind(e);try{this.includeNetworkStats&&(this.networkWriter=new E("network")),this.consoleWriter=new E("console");}catch{}this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async finalizeCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[,e]of this.pendingRequests)this.networkWriter&&(this.networkWriter.append({url:e.url,method:e.method,resourceType:e.resourceType,statusCode:0,responseTimeMs:Date.now()-e.startTimeMs,startedAt:e.startedAt,requestHeaders:e.headers,requestBody:e.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:e.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.networkRequestCount++);this.pendingRequests.clear(),this.networkWriter?.close(),this.consoleWriter?.close();}static mapConsoleType(e){switch(e){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getFileData(){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}});let e=this.records.map(r=>({url:r.url,navigationType:r.navigationType,timestamp:r.timestamp,domContentLoadedAt:r.domContentLoadedAt,networkIdleAt:r.networkIdleAt,networkStats:r.networkStats}));return this.includeNetworkStats?await this.finalizeCapturedRequests():this.consoleWriter?.close(),{navigations:e,networkRequestsFile:this.networkWriter?.getCount()?this.networkWriter.getPath():null,networkRequestsCount:this.networkWriter?.getCount()??0,consoleLogsFile:this.consoleWriter?.getCount()?this.consoleWriter.getPath():null,consoleLogsCount:this.consoleWriter?.getCount()??0}}async flushLegacyAnnotations(e){}dispose(){this.page.goto=this.origGoto,this.page.goBack=this.origGoBack,this.page.goForward=this.origGoForward,this.page.reload=this.origReload;for(let{event:e,handler:r}of this.listeners)this.page.off(e,r);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}getRecords(){return this.records}interceptMethods(){let e=this,r=this.page;r.goto=async function(n,s){return e.recordNavigation(n,"goto"),e.origGoto(n,s)},r.goBack=async function(n){let s=await e.origGoBack(n);return e.recordNavigation(r.url(),"back"),s},r.goForward=async function(n){let s=await e.origGoForward(n);return e.recordNavigation(r.url(),"forward"),s},r.reload=async function(n){return e.recordNavigation(r.url(),"refresh"),e.origReload(n)};}attachListeners(){let e=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",e),this.listeners.push({event:"domcontentloaded",handler:e});let r=s=>{try{let a=s;if(typeof a.parentFrame=="function"&&a.parentFrame()!==null)return;let o=a.url(),i=this.records[this.records.length-1];if(i&&Date.now()-new Date(i.timestamp).getTime()<50&&i.url===o)return;this.recordNavigation(o,"navigation");}catch{}};this.page.on("framenavigated",r),this.listeners.push({event:"framenavigated",handler:r});let n=s=>{try{let a=s,o=a.type(),i=a.text();if(o==="debug"&&i.startsWith("__testrelic_nav:")){try{let l=JSON.parse(i.slice(16));l.type&&l.url&&this.recordNavigation(l.url,l.type);}catch{}return}{let l=null;try{let u=a.location();u&&u.url&&(l=`${u.url}:${u.lineNumber}:${u.columnNumber}`);}catch{}let d=t.mapConsoleType(o);this.consoleWriter&&(this.consoleWriter.append({level:d,text:i,timestamp:new Date().toISOString(),location:l}),this.consoleLogCount++);}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=i=>{this.currentNetworkCounter&&this.currentNetworkCounter.totalRequests++;try{let l=i,d=String(this.requestIdCounter++),u=l.postData()??null,p={url:l.url(),method:l.method(),resourceType:this.mapResourceType(l.resourceType()),headers:l.headers(),postData:u,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now()};this.pendingRequests.set(d,p),i.__testrelic_id=d;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let a=i=>{try{let l=i;if(this.currentNetworkCounter){let y=l.status();y>=400&&(this.currentNetworkCounter.failedRequests++,this.currentNetworkCounter.failedRequestUrls.push(y+" "+l.url()));let T=l.headers()["content-length"];T&&(this.currentNetworkCounter.totalBytes+=parseInt(T,10)||0);let v=l.request().resourceType(),b=this.mapResourceType(v);this.currentNetworkCounter.byType[b]++;}let d=l.request().__testrelic_id;if(!d)return;let u=this.pendingRequests.get(d);if(!u)return;this.pendingRequests.delete(d);let p=Date.now()-u.startTimeMs,g=l.headers(),c=g["content-type"]??null,f=parseInt(g["content-length"]??"0",10)||0,h=c?!Ga(c):!1,m=(async()=>{let y=null;if(!h)try{y=(await l.body()).toString("utf-8");}catch{}let T={url:u.url,method:u.method,resourceType:u.resourceType,statusCode:l.status(),responseTimeMs:p,startedAt:u.startedAt,requestHeaders:u.headers,requestBody:u.postData,responseBody:y,responseHeaders:g,contentType:c,responseSize:f,requestBodyTruncated:u.postDataTruncated,responseBodyTruncated:!1,isBinary:h,error:null};this.networkWriter&&(this.networkWriter.append(T),this.networkRequestCount++);})();this.pendingBodyReads.push(m);}catch{}};this.page.on("response",a),this.listeners.push({event:"response",handler:a});let o=i=>{if(this.currentNetworkCounter){this.currentNetworkCounter.failedRequests++;try{let l=i;this.currentNetworkCounter.failedRequestUrls.push("ERR "+l.url());}catch{}}try{let l=i,d=l.__testrelic_id;if(!d)return;let u=this.pendingRequests.get(d);if(!u)return;this.pendingRequests.delete(d);let p={url:u.url,method:u.method,resourceType:u.resourceType,statusCode:0,responseTimeMs:Date.now()-u.startTimeMs,startedAt:u.startedAt,requestHeaders:u.headers,requestBody:u.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:u.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:l.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(p),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",o),this.listeners.push({event:"requestfailed",handler:o});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let e=history.pushState.bind(history),r=history.replaceState.bind(history);history.pushState=function(...n){e(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){r(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(e,r){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}}),this.records.push({url:e,navigationType:r,timestamp:new Date().toISOString()}),this.includeNetworkStats&&(this.currentNetworkCounter=this.createNetworkCounter());}createNetworkCounter(){return {totalRequests:0,failedRequests:0,failedRequestUrls:[],totalBytes:0,byType:{xhr:0,document:0,script:0,stylesheet:0,image:0,font:0,other:0}}}mapResourceType(e){switch(e){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};var $r=Symbol.for("__testrelic_call_id"),Ja="__testrelic_api_assertions",W=new WeakMap,$=class{constructor(){this.assertions=[];this.currentCallId=null;}recordAssertion(e){this.assertions.push(e);}getAssertions(){return this.assertions}setCurrentCallId(e){this.currentCallId=e;}getCurrentCallId(){return this.currentCallId}getData(){return [...this.assertions]}flushLegacyAnnotations(e){this.assertions.length!==0&&e.annotations.push({type:Ja,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}};var Wr="[REDACTED]";function gt(t,e){if(t===null||e.length===0)return t;let r=new Set(e.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(t))Object.hasOwn(t,s)&&(n[s]=r.has(s.toLowerCase())?Wr:t[s]);return n}function Ce(t,e){if(t===null||e.length===0)return t;let r;try{r=JSON.parse(t);}catch{return t}if(typeof r!="object"||r===null)return t;let n=new Set(e),s=ft(r,n);return JSON.stringify(s)}function ft(t,e){if(Array.isArray(t))return t.map(r=>ft(r,e));if(typeof t=="object"&&t!==null){let r={};for(let n of Object.keys(t)){if(!Object.hasOwn(t,n))continue;let s=t[n];e.has(n)?r[n]=Wr:r[n]=ft(s,e);}return r}return t}function Gr(t,e,r){if(r.length>0){for(let n of r)if(Vr(t,n))return false}if(e.length>0){for(let n of e)if(Vr(t,n))return true;return false}return true}function Vr(t,e){try{return e instanceof RegExp?e.test(t):Ka(e).test(t)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(e)}`),false}}function Ka(t){let e="",r=0;for(;r<t.length;){let n=t[r];n==="*"&&t[r+1]==="*"?(e+=".*",r+=2,t[r]==="/"&&r++):n==="*"?(e+="[^/]*",r++):n==="?"?(e+="[^/]",r++):".+^${}()|[]\\".includes(n)?(e+="\\"+n,r++):(e+=n,r++);}return new RegExp(e)}var Ya=["get","post","put","patch","delete","head","fetch"],Za=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Xa(t){let e=t.toLowerCase();return Za.some(r=>e.includes(r))}function Qa(t){if(!t)return null;if(t.data!==void 0&&t.data!==null){let e=t.data;return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString("base64"):JSON.stringify(e)}if(t.form!==void 0&&t.form!==null)return JSON.stringify(t.form);if(t.multipart!==void 0&&t.multipart!==null){let e=t.multipart,r={};for(let[n,s]of Object.entries(e))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?r[n]=String(s):s&&typeof s=="object"&&"name"in s?r[n]=`[file: ${s.name}]`:r[n]="[binary]";return JSON.stringify(r)}return null}var Se=class Se{constructor(e,r,n){this.originals=new Map;this.apiCallWriter=null;this.callCounter=0;this.apiCallCount=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=e,this.assertionTracker=r??null,this.apiConfig=n??Se.DEFAULT_API_CONFIG;try{this.apiCallWriter=new E("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(e){return e!=null&&typeof e=="object"?W.get(e)??null:this.primitiveCallIds.get(e)??null}intercept(){for(let r of Ya){let n=this.context[r].bind(this.context);this.originals.set(r,n),this.context[r]=this.createWrapper(r,n);}let e=this.context.dispose.bind(this.context);this.originals.set("dispose",e),this.context.dispose=async r=>(this.disposed=true,e(r));}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0}}flushLegacyAnnotations(e){}dispose(){for(let[e,r]of this.originals)this.context[e]=r;this.originals.clear(),this.apiCallWriter?.close(),this.callCounter=0,this.apiCallCount=0,this._lastCallId=null,this.primitiveCallIds.clear();}get isDisposed(){return this.disposed}getCapturedCallCount(){return this.apiCallCount}tagResponseMethods(e,r){let n=this,s=e.headers.bind(e);e.headers=function(){let c=s();return W.set(c,r),c};let a=e.headersArray.bind(e);e.headersArray=function(){let c=a();return W.set(c,r),c};let o=e.json.bind(e);e.json=async function(){let c=await o();return c!=null&&typeof c=="object"&&W.set(c,r),c};let i=e.status.bind(e);e.status=function(){let c=i();return n.primitiveCallIds.set(c,r),c};let l=e.statusText.bind(e);e.statusText=function(){let c=l();return n.primitiveCallIds.set(c,r),c};let d=e.ok.bind(e);e.ok=function(){let c=d();return n.primitiveCallIds.set(c,r),c};let u=e.text.bind(e);e.text=async function(){let c=await u();return n.primitiveCallIds.set(c,r),c};let p=e.body.bind(e);e.body=async function(){let c=await p();return W.set(c,r),c};}createWrapper(e,r){let n=this;return async function(a,o){if(!Gr(a,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return r(a,o);let i=`api-call-${n.callCounter++}`,l=new Date().toISOString(),d=e==="fetch"?(o?.method??"GET").toUpperCase():e.toUpperCase(),u=Qa(o),p=performance.now();n._lastCallId=i,n.assertionTracker&&n.assertionTracker.setCurrentCallId(i);let g;try{g=await r(a,o);}catch(c){let f=performance.now();try{let h=n.apiConfig.captureRequestBody?Ce(u,n.apiConfig.redactBodyFields):null,m={id:i,timestamp:l,method:d,url:a,requestHeaders:null,requestBody:h,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((f-p)*100)/100,isBinary:!1,error:c instanceof Error?c.message:String(c)};n.apiCallWriter&&(n.apiCallWriter.append(m),n.apiCallCount++);}catch{}throw c}try{let c=performance.now(),f=g.headers(),h=f["content-type"]??null,m=h?!Xa(h):!1,y=null;n.apiConfig.captureRequestHeaders&&o?.headers&&(y=o.headers);let T=null;n.apiConfig.captureResponseHeaders&&(T=f);let v=n.apiConfig.captureRequestBody?u:null,b=null;if(n.apiConfig.captureResponseBody)try{m?b=(await g.body()).toString("base64"):b=await g.text();}catch{}y=gt(y,n.apiConfig.redactHeaders),T=gt(T,n.apiConfig.redactHeaders),v=Ce(v,n.apiConfig.redactBodyFields),b=Ce(b,n.apiConfig.redactBodyFields);let C={id:i,timestamp:l,method:d,url:g.url(),requestHeaders:y,requestBody:v,responseStatusCode:g.status(),responseStatusText:g.statusText(),responseHeaders:T,responseBody:b,responseTimeMs:Math.round((c-p)*100)/100,isBinary:m,error:null};n.apiCallWriter&&(n.apiCallWriter.append(C),n.apiCallCount++);}catch{}try{g[$r]=i,n.tagResponseMethods(g,i);}catch{}return g}}};Se.DEFAULT_API_CONFIG=Object.freeze({trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]});var V=Se;var ti="__testrelic_api_config",ri="__testrelic_config_trackApiCalls";function mt(t){let e=t.annotations.find(n=>n.type===ti&&n.description!==void 0);if(e)try{return JSON.parse(e.description,ni)}catch{}let r=t.annotations.find(n=>n.type===ri&&n.description!==void 0);return r?{trackApiCalls:r.description!=="false",captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}:{trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}}function ni(t,e){if(typeof e=="object"&&e!==null&&e.__regexp===true&&typeof e.source=="string"){let{source:r,flags:n}=e;return new RegExp(r,n)}return e}var Zr={page:async({page:t},e,r)=>{let n=new Te(t);try{await n.init();}catch{}await e(t);try{let{navigations:s,networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:l}=await n.getFileData(),d={testRelicData:!0,version:PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:l,apiCallsFile:null,apiCallsCount:0};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:t},e,r)=>{let n=mt(r);if(!n.trackApiCalls){await e(t);return}let s=new $,a=new V(t,s,n);a.intercept(),await e(t);try{let{apiCallsFile:o,apiCallsCount:i}=a.getFileData(),l=n.captureAssertions?s.getData():[],d={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],apiAssertions:l,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:o,apiCallsCount:i};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};test.extend(Zr);var oi={request:async({request:t},e,r)=>{let n=mt(r);if(!n.trackApiCalls){await e(t);return}let s=new $,a=new V(t,s,n);a.intercept();let o=null;try{o=new E("api-console");}catch{}let i=0,l=process.stdout.write,d=process.stderr.write;process.stdout.write=function(u,...p){try{let g=typeof u=="string"?u:Buffer.isBuffer(u)?u.toString("utf-8"):String(u);!g.startsWith("[testrelic]")&&!g.startsWith("\u2139 TestRelic")&&!g.startsWith("\u2713 TestRelic")&&!g.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stdout",text:g.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return l.apply(process.stdout,[u,...p])},process.stderr.write=function(u,...p){try{let g=typeof u=="string"?u:Buffer.isBuffer(u)?u.toString("utf-8"):String(u);!g.startsWith("[testrelic]")&&!g.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stderr",text:g.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return d.apply(process.stderr,[u,...p])};try{await e(t);}finally{process.stdout.write=l,process.stderr.write=d;}try{o?.close();let{apiCallsFile:u,apiCallsCount:p}=a.getFileData(),g=n.captureAssertions?s.getData():[],c={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],apiAssertions:g,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:i>0?o?.getPath()??null:null,consoleLogsCount:i,apiCallsFile:u,apiCallsCount:p};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(c)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};var Xr="@testrelic/playwright-analytics";function di(t){return Array.isArray(t)?t.some(e=>Array.isArray(e)&&typeof e[0]=="string"&&e[0]===Xr):false}function ci(t,e){let n={video:"on",screenshot:"on",trace:"on",...t.use??{}},s;Array.isArray(t.reporter)?s=t.reporter:typeof t.reporter=="string"?s=[[t.reporter]]:s=[["list"]];let a=di(s)?s:[...s,[Xr,e??{}]];return defineConfig({...t,use:n,reporter:a})}var Qr=false;function Td(t,e,r="manual_record"){if(!t||!t.annotations){Qr||(Qr=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
2602
+ `));return}let n={url:e,navigationType:r,timestamp:new Date().toISOString()};t.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}export{se as SCHEMA_VERSION,ke as default,ci as defineConfig,Td as recordNavigation,oi as testRelicApiFixture,Zr as testRelicFixture};//# sourceMappingURL=index.js.map
2603
2603
  //# sourceMappingURL=index.js.map