@testrelic/playwright-analytics 2.3.16 → 2.3.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var crypto=require('crypto'),fs$1=require('fs'),path=require('path'),core=require('@testrelic/core'),child_process=require('child_process'),http=require('http'),os$1=require('os'),readline=require('readline'),promises=require('fs/promises'),zlib=require('zlib'),stream=require('stream'),test=require('@playwright/test'),perf_hooks=require('perf_hooks');var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Gr=".testrelic-report";function kt(e,t,r,n){let s=`${e}|${t.join("|")}|${r}|${n}`;return crypto.createHash("sha256").update(s).digest("hex").substring(0,12)}var G=class{constructor(t){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=path.join(t,Gr),this.testsDir=path.join(this.reportDir,"tests"),fs$1.mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(t,r,n){try{let s=path.join(this.testsDir,t);fs$1.mkdirSync(s,{recursive:!0});let a=path.join(s,"meta.json"),o=a+".tmp",i=JSON.stringify(r);return fs$1.writeFileSync(o,i,"utf-8"),fs$1.renameSync(o,a),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),n?.networkRequestsFile&&this.moveFile(n.networkRequestsFile,path.join(s,"network.jsonl")),n?.consoleLogsFile&&this.moveFile(n.consoleLogsFile,path.join(s,"console.jsonl")),n?.apiCallsFile&&this.moveFile(n.apiCallsFile,path.join(s,"api-calls.jsonl")),!0}catch(s){let a=s instanceof Error?s.message:String(s);return this.writeErrors.push({testId:t,error:a,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${t}: ${a}
2
- `),false}}moveFile(t,r){try{fs$1.renameSync(t,r);}catch{try{let{copyFileSync:n}=jr("fs");n(t,r);try{fs$1.unlinkSync(t);}catch{}}catch(n){process.stderr.write(`[testrelic] Failed to move file ${t} \u2192 ${r}: ${n instanceof Error?n.message:String(n)}
3
- `);}}}writeIndex(t){let r=path.join(this.reportDir,"index.json"),n=r+".tmp",s=JSON.stringify(t);fs$1.writeFileSync(n,s,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeCompactIndex(t){let r=path.join(this.reportDir,"index-compact.json"),n=r+".tmp",s=t.map(({titlePath:o,project:i,...l})=>l),a=JSON.stringify(s);fs$1.writeFileSync(n,a,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}writeSummary(t){let r=path.join(this.reportDir,"summary.json"),n=r+".tmp",s=JSON.stringify(t);fs$1.writeFileSync(n,s,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeManifest(t){let r=path.join(this.reportDir,"manifest.json"),n=r+".tmp",s=JSON.stringify(t);fs$1.writeFileSync(n,s,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var en=".testrelic",rn=5,nn=new Set(["__proto__","constructor","prototype"]),fe=Object.freeze({apiKey:null,endpoint:"https://api.testrelic.com/api/v1",uploadStrategy:"batch",timeout:3e4,projectName:null,queueMaxAge:6048e5,queueDirectory:".testrelic/queue",uploadArtifacts:true,artifactMaxSizeMb:50}),sn={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function he(e){let t=path.resolve(e);for(let r=0;r<=rn;r++){let n=path.join(t,en);if(fs$1.existsSync(n))return n;let s=path.dirname(t);if(s===t)break;t=s;}return null}function me(e){try{let t=fs$1.readFileSync(e,"utf-8"),r=JSON.parse(t);return typeof r!="object"||r===null||Array.isArray(r)||!ve(r)?null:r}catch{return null}}function ve(e){for(let t of Object.keys(e)){if(nn.has(t))return false;let r=e[t];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!ve(r))return false}return true}function ye(e){let t=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(e);if(t)return process.env[t[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(e);return r?process.env[r[1]]??null:e}function Ct(e){let t=Object.create(null);for(let r of Object.keys(e)){let n=e[r];typeof n=="string"&&n.startsWith("$")?t[r]=ye(n):typeof n=="object"&&n!==null&&!Array.isArray(n)?t[r]=Ct(n):t[r]=n;}return t}function ge(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let r=parseInt(t[1],10),n=t[2],s=sn[n];return !s||r<=0?null:r*s}function be(e,t){let r=Object.create(null);if(Object.assign(r,fe),e){let l=e.cloud;l&&typeof l=="object"&&(typeof l.endpoint=="string"&&(r.endpoint=l.endpoint),typeof l.upload=="string"&&(r.uploadStrategy=l.upload),typeof l.timeout=="number"&&(r.timeout=l.timeout),typeof l.apiKey=="string"&&l.apiKey.length>0&&(r.apiKey=l.apiKey));let d=e.project;d&&typeof d=="object"&&typeof d.name=="string"&&(r.projectName=d.name);let c=e.queue;if(c&&typeof c=="object"){if(typeof c.maxAge=="string"){let p=ge(c.maxAge);p!==null&&(r.queueMaxAge=p);}typeof c.directory=="string"&&(r.queueDirectory=c.directory);}}if(t){if(typeof t.apiKey=="string"&&t.apiKey.length>0){let l=t.apiKey.startsWith("$")?ye(t.apiKey):t.apiKey;l&&(r.apiKey=l);}if(typeof t.endpoint=="string"&&(r.endpoint=t.endpoint),typeof t.upload=="string"&&(r.uploadStrategy=t.upload),typeof t.timeout=="number"&&(r.timeout=t.timeout),typeof t.projectName=="string"&&(r.projectName=t.projectName),typeof t.queueMaxAge=="string"){let l=ge(t.queueMaxAge);l!==null&&(r.queueMaxAge=l);}typeof t.queueDirectory=="string"&&(r.queueDirectory=t.queueDirectory),typeof t.uploadArtifacts=="boolean"&&(r.uploadArtifacts=t.uploadArtifacts),typeof t.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=t.artifactMaxSizeMb);}let n=process.env.TESTRELIC_API_KEY;n&&n.length>0&&(r.apiKey=n);let s=process.env.TESTRELIC_CLOUD_ENDPOINT;s&&core.isValidEndpointUrl(s)&&(r.endpoint=s);let a=process.env.TESTRELIC_UPLOAD_STRATEGY;a&&["batch","realtime","both"].includes(a)&&(r.uploadStrategy=a);let o=process.env.TESTRELIC_CLOUD_TIMEOUT;if(o){let l=parseInt(o,10);!isNaN(l)&&l>=1e3&&l<=12e4&&(r.timeout=l);}let i=Object.freeze(r);return core.isValidCloudConfig(i)?i:fe}var dn=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],cn=["authorization","cookie","set-cookie","x-api-key"],un=["password","secret","token","apiKey","api_key"];function we(e){let t=Object.create(null);return t.trackApiCalls=e?.trackApiCalls??true,t.captureRequestHeaders=e?.captureRequestHeaders??true,t.captureResponseHeaders=e?.captureResponseHeaders??true,t.captureRequestBody=e?.captureRequestBody??true,t.captureResponseBody=e?.captureResponseBody??true,t.captureAssertions=e?.captureAssertions??true,t.redactHeaders=e?.redactHeaders??[...cn],t.redactBodyFields=e?.redactBodyFields??[...un],t.apiIncludeUrls=e?.apiIncludeUrls??[],t.apiExcludeUrls=e?.apiExcludeUrls??[],Object.freeze(t)}function xe(e){if(e!==void 0&&!core.isValidConfig(e))throw core.createError(core.ErrorCode.CONFIG_INVALID,"Invalid reporter configuration");let t=Object.create(null);t.outputPath=e?.outputPath??"./test-results/analytics-timeline.json",t.includeStackTrace=e?.includeStackTrace??false,t.includeCodeSnippets=e?.includeCodeSnippets??true,t.codeContextLines=e?.codeContextLines??3,t.includeNetworkStats=e?.includeNetworkStats??true,t.navigationTypes=e?.navigationTypes??null,t.redactPatterns=[...dn,...e?.redactPatterns??[]],t.testRunId=e?.testRunId??null,t.metadata=e?.metadata??null;let r=t.outputPath;t.openReport=e?.openReport??true,t.htmlReportPath=e?.htmlReportPath??r.replace(/\.json$/,".html"),t.includeArtifacts=e?.includeArtifacts??true,t.trackApiCalls=e?.trackApiCalls??true,t.quiet=e?.quiet??false,t.includeActionSteps=e?.includeActionSteps??true,t.captureConsoleLogs=e?.captureConsoleLogs??true;let n=he(process.cwd()),s=n?me(n):null,a=s?Ct(s):null,o=be(a,e?.cloud);return t.cloud=o.apiKey?o:null,t.reportMode=e?.reportMode??"streaming",t.streamingThreshold=e?.streamingThreshold??0,Object.freeze(t)}var rt="1.3.0";function ke(e,t,r){try{let s=fs$1.readFileSync(e,"utf-8").split(`
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var crypto=require('crypto'),fs$1=require('fs'),path=require('path'),core=require('@testrelic/core'),child_process=require('child_process'),http=require('http'),os$1=require('os'),readline=require('readline'),promises=require('fs/promises'),zlib=require('zlib'),stream=require('stream'),test=require('@playwright/test'),perf_hooks=require('perf_hooks');var $r=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Wr=".testrelic-report";function kt(e,t,r,n){let s=`${e}|${t.join("|")}|${r}|${n}`;return crypto.createHash("sha256").update(s).digest("hex").substring(0,12)}var G=class{constructor(t){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=path.join(t,Wr),this.testsDir=path.join(this.reportDir,"tests"),fs$1.mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(t,r,n){try{let s=path.join(this.testsDir,t);fs$1.mkdirSync(s,{recursive:!0});let a=path.join(s,"meta.json"),o=a+".tmp",i=JSON.stringify(r);return fs$1.writeFileSync(o,i,"utf-8"),fs$1.renameSync(o,a),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),n?.networkRequestsFile&&this.moveFile(n.networkRequestsFile,path.join(s,"network.jsonl")),n?.consoleLogsFile&&this.moveFile(n.consoleLogsFile,path.join(s,"console.jsonl")),n?.apiCallsFile&&this.moveFile(n.apiCallsFile,path.join(s,"api-calls.jsonl")),!0}catch(s){let a=s instanceof Error?s.message:String(s);return this.writeErrors.push({testId:t,error:a,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${t}: ${a}
2
+ `),false}}moveFile(t,r){try{fs$1.renameSync(t,r);}catch{try{let{copyFileSync:n}=$r("fs");n(t,r);try{fs$1.unlinkSync(t);}catch{}}catch(n){process.stderr.write(`[testrelic] Failed to move file ${t} \u2192 ${r}: ${n instanceof Error?n.message:String(n)}
3
+ `);}}}writeIndex(t){let r=path.join(this.reportDir,"index.json"),n=r+".tmp",s=JSON.stringify(t);fs$1.writeFileSync(n,s,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeCompactIndex(t){let r=path.join(this.reportDir,"index-compact.json"),n=r+".tmp",s=t.map(({titlePath:o,project:i,...l})=>l),a=JSON.stringify(s);fs$1.writeFileSync(n,a,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}writeSummary(t){let r=path.join(this.reportDir,"summary.json"),n=r+".tmp",s=JSON.stringify(t);fs$1.writeFileSync(n,s,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeManifest(t){let r=path.join(this.reportDir,"manifest.json"),n=r+".tmp",s=JSON.stringify(t);fs$1.writeFileSync(n,s,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var tn=".testrelic",en=5,rn=new Set(["__proto__","constructor","prototype"]),fe=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,projectName:null,queueMaxAge:6048e5,queueDirectory:".testrelic/queue",uploadArtifacts:true,artifactMaxSizeMb:50}),nn={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function he(e){let t=path.resolve(e);for(let r=0;r<=en;r++){let n=path.join(t,tn);if(fs$1.existsSync(n))return n;let s=path.dirname(t);if(s===t)break;t=s;}return null}function me(e){try{let t=fs$1.readFileSync(e,"utf-8"),r=JSON.parse(t);return typeof r!="object"||r===null||Array.isArray(r)||!ve(r)?null:r}catch{return null}}function ve(e){for(let t of Object.keys(e)){if(rn.has(t))return false;let r=e[t];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!ve(r))return false}return true}function ye(e){let t=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(e);if(t)return process.env[t[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(e);return r?process.env[r[1]]??null:e}function Ct(e){let t=Object.create(null);for(let r of Object.keys(e)){let n=e[r];typeof n=="string"&&n.startsWith("$")?t[r]=ye(n):typeof n=="object"&&n!==null&&!Array.isArray(n)?t[r]=Ct(n):t[r]=n;}return t}function ge(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let r=parseInt(t[1],10),n=t[2],s=nn[n];return !s||r<=0?null:r*s}function be(e,t){let r=Object.create(null);if(Object.assign(r,fe),e){let l=e.cloud;l&&typeof l=="object"&&(typeof l.endpoint=="string"&&(r.endpoint=l.endpoint),typeof l.upload=="string"&&(r.uploadStrategy=l.upload),typeof l.timeout=="number"&&(r.timeout=l.timeout),typeof l.apiKey=="string"&&l.apiKey.length>0&&(r.apiKey=l.apiKey));let d=e.project;d&&typeof d=="object"&&typeof d.name=="string"&&(r.projectName=d.name);let c=e.queue;if(c&&typeof c=="object"){if(typeof c.maxAge=="string"){let p=ge(c.maxAge);p!==null&&(r.queueMaxAge=p);}typeof c.directory=="string"&&(r.queueDirectory=c.directory);}}if(t){if(typeof t.apiKey=="string"&&t.apiKey.length>0){let l=t.apiKey.startsWith("$")?ye(t.apiKey):t.apiKey;l&&(r.apiKey=l);}if(typeof t.endpoint=="string"&&(r.endpoint=t.endpoint),typeof t.upload=="string"&&(r.uploadStrategy=t.upload),typeof t.timeout=="number"&&(r.timeout=t.timeout),typeof t.projectName=="string"&&(r.projectName=t.projectName),typeof t.queueMaxAge=="string"){let l=ge(t.queueMaxAge);l!==null&&(r.queueMaxAge=l);}typeof t.queueDirectory=="string"&&(r.queueDirectory=t.queueDirectory),typeof t.uploadArtifacts=="boolean"&&(r.uploadArtifacts=t.uploadArtifacts),typeof t.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=t.artifactMaxSizeMb);}let n=process.env.TESTRELIC_API_KEY;n&&n.length>0&&(r.apiKey=n);let s=process.env.TESTRELIC_CLOUD_ENDPOINT;s&&core.isValidEndpointUrl(s)&&(r.endpoint=s);let a=process.env.TESTRELIC_UPLOAD_STRATEGY;a&&["batch","realtime","both"].includes(a)&&(r.uploadStrategy=a);let o=process.env.TESTRELIC_CLOUD_TIMEOUT;if(o){let l=parseInt(o,10);!isNaN(l)&&l>=1e3&&l<=12e4&&(r.timeout=l);}let i=Object.freeze(r);return core.isValidCloudConfig(i)?i:fe}var ln=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],dn=["authorization","cookie","set-cookie","x-api-key"],cn=["password","secret","token","apiKey","api_key"];function we(e){let t=Object.create(null);return t.trackApiCalls=e?.trackApiCalls??true,t.captureRequestHeaders=e?.captureRequestHeaders??true,t.captureResponseHeaders=e?.captureResponseHeaders??true,t.captureRequestBody=e?.captureRequestBody??true,t.captureResponseBody=e?.captureResponseBody??true,t.captureAssertions=e?.captureAssertions??true,t.redactHeaders=e?.redactHeaders??[...dn],t.redactBodyFields=e?.redactBodyFields??[...cn],t.apiIncludeUrls=e?.apiIncludeUrls??[],t.apiExcludeUrls=e?.apiExcludeUrls??[],Object.freeze(t)}function xe(e){if(e!==void 0&&!core.isValidConfig(e))throw core.createError(core.ErrorCode.CONFIG_INVALID,"Invalid reporter configuration");let t=Object.create(null);t.outputPath=e?.outputPath??"./test-results/analytics-timeline.json",t.includeStackTrace=e?.includeStackTrace??false,t.includeCodeSnippets=e?.includeCodeSnippets??true,t.codeContextLines=e?.codeContextLines??3,t.includeNetworkStats=e?.includeNetworkStats??true,t.navigationTypes=e?.navigationTypes??null,t.redactPatterns=[...ln,...e?.redactPatterns??[]],t.testRunId=e?.testRunId??null,t.metadata=e?.metadata??null;let r=t.outputPath;t.openReport=e?.openReport??true,t.htmlReportPath=e?.htmlReportPath??r.replace(/\.json$/,".html"),t.includeArtifacts=e?.includeArtifacts??true,t.trackApiCalls=e?.trackApiCalls??true,t.quiet=e?.quiet??false,t.includeActionSteps=e?.includeActionSteps??true,t.captureConsoleLogs=e?.captureConsoleLogs??true;let n=he(process.cwd()),s=n?me(n):null,a=s?Ct(s):null,o=be(a,e?.cloud);return t.cloud=o.apiKey?o:null,t.reportMode=e?.reportMode??"streaming",t.streamingThreshold=e?.streamingThreshold??0,Object.freeze(t)}var et="1.3.0";function ke(e,t,r){try{let s=fs$1.readFileSync(e,"utf-8").split(`
4
4
  `);if(t<1||t>s.length)return null;let a=Math.max(1,t-r),o=Math.min(s.length,t+r),i=[];for(let l=a;l<=o;l++){let d=l===t?">":" ",c=String(l).padStart(String(o).length," ");i.push(`${d} ${c} | ${s[l-1]}`);}return i.join(`
5
- `)}catch{return null}}function Ce(e){return t=>{let r=t;for(let n of e)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 fn(e){return e.GITHUB_ACTIONS!=="true"?null:{provider:"github-actions",buildId:e.GITHUB_RUN_ID??null,commitSha:e.GITHUB_SHA??null,branch:e.GITHUB_REF_NAME??null,runUrl:e.GITHUB_SERVER_URL&&e.GITHUB_REPOSITORY&&e.GITHUB_RUN_ID?`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`:null}}function gn(e){return e.GITLAB_CI!=="true"?null:{provider:"gitlab-ci",buildId:e.CI_PIPELINE_ID??null,commitSha:e.CI_COMMIT_SHA??null,branch:e.CI_COMMIT_BRANCH??e.CI_COMMIT_REF_NAME??null,runUrl:e.CI_PIPELINE_URL??null}}function hn(e){if(!e.JENKINS_URL)return null;let t=e.GIT_BRANCH??null;return t?.startsWith("origin/")&&(t=t.slice(7)),{provider:"jenkins",buildId:e.BUILD_ID??null,commitSha:e.GIT_COMMIT??null,branch:t,runUrl:e.BUILD_URL??null}}function mn(e){return e.CIRCLECI!=="true"?null:{provider:"circleci",buildId:e.CIRCLE_BUILD_NUM??null,commitSha:e.CIRCLE_SHA1??null,branch:e.CIRCLE_BRANCH??null,runUrl:e.CIRCLE_BUILD_URL??null}}function vn(e){if(!e.BITBUCKET_PIPELINE_UUID)return null;let t=e.BITBUCKET_WORKSPACE&&e.BITBUCKET_REPO_SLUG&&e.BITBUCKET_PIPELINE_UUID?`https://bitbucket.org/${e.BITBUCKET_WORKSPACE}/${e.BITBUCKET_REPO_SLUG}/pipelines/results/${e.BITBUCKET_PIPELINE_UUID}`:null;return {provider:"bitbucket-pipelines",buildId:e.BITBUCKET_BUILD_NUMBER??null,commitSha:e.BITBUCKET_COMMIT??null,branch:e.BITBUCKET_BRANCH??null,runUrl:t}}var yn=[fn,gn,hn,mn,vn];function D(e){let t=process.env;for(let r of yn){let n=r(t);if(n)return n}return null}var Tt=`
5
+ `)}catch{return null}}function Ce(e){return t=>{let r=t;for(let n of e)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 pn(e){return e.GITHUB_ACTIONS!=="true"?null:{provider:"github-actions",buildId:e.GITHUB_RUN_ID??null,commitSha:e.GITHUB_SHA??null,branch:e.GITHUB_REF_NAME??null,runUrl:e.GITHUB_SERVER_URL&&e.GITHUB_REPOSITORY&&e.GITHUB_RUN_ID?`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`:null}}function fn(e){return e.GITLAB_CI!=="true"?null:{provider:"gitlab-ci",buildId:e.CI_PIPELINE_ID??null,commitSha:e.CI_COMMIT_SHA??null,branch:e.CI_COMMIT_BRANCH??e.CI_COMMIT_REF_NAME??null,runUrl:e.CI_PIPELINE_URL??null}}function gn(e){if(!e.JENKINS_URL)return null;let t=e.GIT_BRANCH??null;return t?.startsWith("origin/")&&(t=t.slice(7)),{provider:"jenkins",buildId:e.BUILD_ID??null,commitSha:e.GIT_COMMIT??null,branch:t,runUrl:e.BUILD_URL??null}}function hn(e){return e.CIRCLECI!=="true"?null:{provider:"circleci",buildId:e.CIRCLE_BUILD_NUM??null,commitSha:e.CIRCLE_SHA1??null,branch:e.CIRCLE_BRANCH??null,runUrl:e.CIRCLE_BUILD_URL??null}}function mn(e){if(!e.BITBUCKET_PIPELINE_UUID)return null;let t=e.BITBUCKET_WORKSPACE&&e.BITBUCKET_REPO_SLUG&&e.BITBUCKET_PIPELINE_UUID?`https://bitbucket.org/${e.BITBUCKET_WORKSPACE}/${e.BITBUCKET_REPO_SLUG}/pipelines/results/${e.BITBUCKET_PIPELINE_UUID}`:null;return {provider:"bitbucket-pipelines",buildId:e.BITBUCKET_BUILD_NUMBER??null,commitSha:e.BITBUCKET_COMMIT??null,branch:e.BITBUCKET_BRANCH??null,runUrl:t}}var vn=[pn,fn,gn,hn,mn];function D(e){let t=process.env;for(let r of vn){let n=r(t);if(n)return n}return null}var Tt=`
6
6
  /* Theme Variables */
7
7
  :root,[data-theme="dark"]{
8
8
  --bg:#0f1117;--bg-1:#161b22;--bg-2:#1c2128;--bg-3:#21262d;--bg-code:#13111c;
@@ -2312,7 +2312,7 @@ function _updateCard(cls,val){
2312
2312
  if(i>=sizes.length)i=sizes.length-1;
2313
2313
  return parseFloat((bytes/Math.pow(k,i)).toFixed(1))+' '+sizes[i];
2314
2314
  }
2315
- `;var bn=`
2315
+ `;var yn=`
2316
2316
  (function(){
2317
2317
  var data=JSON.parse(document.getElementById('report-data').textContent);
2318
2318
  ${At}
@@ -2383,7 +2383,7 @@ ${""}
2383
2383
  </aside>
2384
2384
  <script id="report-data" type="application/json">${n}</script>
2385
2385
  ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:""}
2386
- <script>${bn}</script>
2386
+ <script>${yn}</script>
2387
2387
  </body>
2388
2388
  </html>`}function Pt(e,t,r,n){let s=e.replace(/<\//g,"<\\/"),a=t.replace(/<\//g,"<\\/"),o=n?n.replace(/<\//g,"<\\/"):null,i={};try{i=JSON.parse(e);}catch{}let l=`{
2389
2389
  "schemaVersion":"2.0",
@@ -2543,27 +2543,27 @@ ${o?`<script id="artifact-manifest-data" type="application/json">${o}</script>`:
2543
2543
  </body>
2544
2544
  </html>`}function Ft(e){try{let t=process.platform,r;t==="darwin"?r=`open "${e}"`:t==="win32"?r=`start "" "${e}"`:r=`xdg-open "${e}"`,child_process.exec(r,n=>{n&&process.stderr.write(`[testrelic] Failed to open browser: ${n.message}
2545
2545
  `);});}catch{}}var Se=path.join(os$1.tmpdir(),"testrelic-data"),M=class{constructor(t){this.count=0;this.closed=false;fs$1.mkdirSync(Se,{recursive:true}),this.filePath=path.join(Se,`${t}-${crypto.randomUUID().substring(0,8)}.jsonl`),this.fd=fs$1.openSync(this.filePath,"w");}append(t){if(this.closed)return;let r=JSON.stringify(t)+`
2546
- `;fs$1.writeSync(this.fd,r),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{fs$1.closeSync(this.fd);}catch{}}}cleanup(){try{fs$1.unlinkSync(this.filePath);}catch{}}};async function Ae(e,t,r,n){let s=(t-1)*r,a=[],o=0,i=readline.createInterface({input:fs$1.createReadStream(e,{encoding:"utf-8"}),crlfDelay:1/0});for await(let c of i)if(c.length!==0){if(o>=s&&a.length<r)try{a.push(JSON.parse(c));}catch{}if(o++,a.length>=r&&n!==void 0)break}let l=n??o,d=Math.max(1,Math.ceil(l/r));return {items:a,total:l,page:t,pageSize:r,totalPages:d}}var Le=/^[a-f0-9]{12}$/,Dt=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Me=500;function x(e,t,r){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(r));}function Ne(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type");}function at(e){try{return fs$1.existsSync(e)?JSON.parse(fs$1.readFileSync(e,"utf-8")):null}catch{return null}}function it(e){let t=0;try{let r=fs$1.readdirSync(e,{withFileTypes:!0});for(let n of r){let s=path.join(e,n.name);n.isFile()?t+=fs$1.statSync(s).size:n.isDirectory()&&(t+=it(s));}}catch{}return t}function Ee(e,t,r,n){let s=at(path.join(r,"index.json"));x(t,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-n)/1e3)});}function Pe(e,t,r){let n=at(path.join(r,"summary.json"));if(!n){x(t,404,{error:"Summary not found"});return}x(t,200,n);}function Fe(e,t,r){let n=at(path.join(r,"index.json"));if(!n){x(t,404,{error:"Test index not found"});return}let a=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,o=Math.max(1,parseInt(a.get("page")??"1",10)||1),i=Math.min(Me,Math.max(1,parseInt(a.get("pageSize")??"100",10)||100)),l=a.get("status")?.split(",").filter(Boolean)??null,d=a.get("file")??null,c=a.get("search")?.toLowerCase()??null,p=a.get("tag")?.split(",").filter(Boolean)??null,f=a.get("sort")??"file",u=a.get("order")==="desc"?-1:1,g=n;l&&l.length>0&&(g=g.filter(w=>l.includes(w.status))),d&&(g=g.filter(w=>w.filePath===d||w.filePath.startsWith(d+"/"))),c&&(g=g.filter(w=>w.title.toLowerCase().includes(c)||w.filePath.toLowerCase().includes(c))),p&&p.length>0&&(g=g.filter(w=>p.some(b=>w.tags.includes(b)))),g=[...g].sort((w,b)=>{let T=0;switch(f){case "duration":T=w.duration-b.duration;break;case "status":T=w.status.localeCompare(b.status);break;case "title":T=w.title.localeCompare(b.title);break;default:T=w.filePath.localeCompare(b.filePath);break}return T*u});let h=g.length,m=Math.max(1,Math.ceil(h/i)),y=(o-1)*i,k=g.slice(y,y+i);x(t,200,{tests:k,pagination:{page:o,pageSize:i,totalItems:h,totalPages:m},filters:{status:l,file:d,search:c,tag:p}});}function De(e,t,r,n){if(!Le.test(n)){x(t,400,{error:"Invalid test ID format"});return}let s=path.join(r,"tests",n,"meta.json"),a=path.join(r,"tests",`${n}.json`),o=fs$1.existsSync(s)?s:fs$1.existsSync(a)?a:null;if(!o){x(t,404,{error:`Test not found: ${n}`});return}try{let i=fs$1.readFileSync(o,"utf-8");t.writeHead(200,{"Content-Type":"application/json"}),t.end(i);}catch(i){x(t,500,{error:i instanceof Error?i.message:String(i)});}}async function Be(e,t,r,n,s){if(!Le.test(n)){x(t,400,{error:"Invalid test ID format"});return}let o=path.join(r,"tests",n,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!fs$1.existsSync(o)){x(t,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let l=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,d=Math.max(1,parseInt(l.get("page")??"1",10)||1),c=Math.min(Me,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),p,f=path.join(r,"tests",n,"meta.json");if(fs$1.existsSync(f))try{let g=JSON.parse(fs$1.readFileSync(f,"utf-8"));switch(s){case "network":p=g.networkRequestsCount;break;case "console":p=g.consoleLogsCount;break;case "api-calls":p=g.apiCallsCount;break}}catch{}let u=await Ae(o,d,c,p);x(t,200,u);}catch(i){x(t,500,{error:i instanceof Error?i.message:String(i)});}}function qe(e,t,r){let n=at(path.join(r,"index.json"));if(!n){x(t,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(t,200,{files:a});}function Oe(e,t,r){if(!fs$1.existsSync(r)){x(t,200,{runs:[],totalSizeBytes:0});return}try{let n=[],s=0,a=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!Dt.test(o.name))continue;let i=path.join(r,o.name),l=it(i),d=fs$1.readdirSync(i,{withFileTypes:!0}).filter(c=>c.isDirectory());n.push({folderName:o.name,totalSizeBytes:l,testCount:d.length}),s+=l;}n.sort((o,i)=>i.folderName.localeCompare(o.folderName)),x(t,200,{runs:n,totalSizeBytes:s});}catch(n){x(t,500,{error:n instanceof Error?n.message:String(n)});}}function He(e,t,r){try{let n=0,s=0;if(fs$1.existsSync(r)){let a=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!Dt.test(o.name))continue;let i=path.join(r,o.name),l=it(i);fs$1.rmSync(i,{recursive:!0,force:!0}),s+=l,n++;}}x(t,200,{deletedCount:n,freedBytes:s});}catch(n){x(t,500,{error:n instanceof Error?n.message:String(n)});}}function Ue(e,t,r,n){if(!Dt.test(n)){x(t,400,{error:"Invalid folder name"});return}let s=path.join(r,n);try{if(!fs$1.statSync(s).isDirectory()){x(t,404,{error:"Not found"});return}}catch{x(t,404,{error:"Not found"});return}try{let a=it(s);fs$1.rmSync(s,{recursive:!0,force:!0}),x(t,200,{deleted:n,freedBytes:a});}catch(a){x(t,500,{error:a instanceof Error?a.message:String(a)});}}function ze(e,t,r){x(t,200,{status:"shutting_down"}),r.close();}function Bt(e,t,r){if(!fs$1.existsSync(r)){x(t,404,{error:"File not found"});return}try{let n=fs$1.readFileSync(r),s=path.extname(r).toLowerCase(),a=Mn[s]??"application/octet-stream";t.writeHead(200,{"Content-Type":a}),t.end(n);}catch(n){x(t,500,{error:n instanceof Error?n.message:String(n)});}}var Mn={".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 Fn=9323,Dn=10,Bn=1800*1e3;function J(e,t){return new Promise((r,n)=>{let s=t?.port??Fn,a=Date.now(),o,i=0,l=fs$1.existsSync(path.join(e,"artifacts"))?path.join(e,"artifacts"):fs$1.existsSync(path.join(e,"..","artifacts"))?path.join(e,"..","artifacts"):path.join(e,"artifacts");function d(){clearTimeout(o),o=setTimeout(()=>{p.close();},Bn);}let c=t?.htmlPath??null;if(!c){let u=path.dirname(e);try{let g=fs$1.readdirSync(u).find(h=>h.endsWith(".html"));g&&(c=path.join(u,g));}catch{}}let p=http.createServer((u,g)=>{if(d(),Ne(g),u.method==="OPTIONS"){g.writeHead(204),g.end();return}let h;try{h=new URL(u.url??"/",`http://${u.headers.host??"localhost"}`).pathname;}catch{x(g,400,{error:"Invalid URL"});return}if(u.method==="GET"&&(h==="/"||h==="/index.html")){if(c&&fs$1.existsSync(c)){Bt(u,g,c);return}x(g,404,{error:"HTML report not found"});return}if(u.method==="GET"&&h==="/api/health"){Ee(u,g,e,a);return}if(u.method==="GET"&&h==="/api/summary"){Pe(u,g,e);return}if(u.method==="GET"&&h==="/api/tests"){Fe(u,g,e);return}if(u.method==="GET"&&h==="/api/files"){qe(u,g,e);return}let m=h.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(u.method==="GET"&&m){Be(u,g,e,m[1],m[2]);return}let y=h.match(/^\/api\/tests\/([a-f0-9]+)$/);if(u.method==="GET"&&y){De(u,g,e,y[1]);return}if(u.method==="GET"&&h==="/api/artifacts"){Oe(u,g,l);return}if(u.method==="DELETE"&&h==="/api/artifacts"){He(u,g,l);return}let k=h.match(/^\/api\/artifacts\/(.+)$/);if(u.method==="DELETE"&&k){Ue(u,g,l,decodeURIComponent(k[1]));return}if(u.method==="GET"&&h.startsWith("/artifacts/")){let w=decodeURIComponent(h.slice(11));if(w.includes("..")||w.includes("\0")){x(g,400,{error:"Invalid path"});return}Bt(u,g,path.join(l,w));return}if(u.method==="POST"&&h==="/api/shutdown"){ze(u,g,p);return}x(g,404,{error:"Not found"});});function f(u){let g=h=>{h.code==="EADDRINUSE"&&i<Dn?(i++,f(u+1)):n(h);};p.once("error",g),p.listen(u,"127.0.0.1",()=>{p.removeListener("error",g);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());})});});}f(s);})}async function $e(e){let t=await J(e);return {port:t.port,dispose:t.dispose}}function Hn(e,t,r){let n=JSON.stringify(e),s=r?JSON.stringify(r):null;return Te(n,t,s)}async function Ot(e,t,r){try{let n=null,s=null,a=t.reportMode==="streaming"||t.reportMode==="auto"&&e.timeline.length===0&&e.summary.total>=t.streamingThreshold,o,i=t.htmlReportPath,l=path.dirname(i);fs$1.mkdirSync(l,{recursive:!0});let d="",c="[]",p=null;if(a){d=JSON.stringify(e.summary);let u=path.dirname(t.outputPath),g=path.join(u,".testrelic-report");try{let h=path.join(g,"index-compact.json"),m=path.join(g,"index.json");fs$1.existsSync(h)?c=fs$1.readFileSync(h,"utf-8"):fs$1.existsSync(m)&&(c=fs$1.readFileSync(m,"utf-8"));}catch{}p=r?JSON.stringify(r):null,o=Pt(d,c,null,p);}else o=Hn(e,null,r);let f=i+".tmp";if(fs$1.writeFileSync(f,o,"utf-8"),fs$1.renameSync(f,i),a){if(e.ci===null){let u=path.dirname(t.outputPath),g=path.join(u,".testrelic-report"),h=path.resolve(i);try{if(await zn(),n=await $n(g),!n){s=await J(g,{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(`
2546
+ `;fs$1.writeSync(this.fd,r),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{fs$1.closeSync(this.fd);}catch{}}}cleanup(){try{fs$1.unlinkSync(this.filePath);}catch{}}};async function Ae(e,t,r,n){let s=(t-1)*r,a=[],o=0,i=readline.createInterface({input:fs$1.createReadStream(e,{encoding:"utf-8"}),crlfDelay:1/0});for await(let c of i)if(c.length!==0){if(o>=s&&a.length<r)try{a.push(JSON.parse(c));}catch{}if(o++,a.length>=r&&n!==void 0)break}let l=n??o,d=Math.max(1,Math.ceil(l/r));return {items:a,total:l,page:t,pageSize:r,totalPages:d}}var Le=/^[a-f0-9]{12}$/,Dt=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Me=500;function x(e,t,r){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(r));}function Ne(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type");}function st(e){try{return fs$1.existsSync(e)?JSON.parse(fs$1.readFileSync(e,"utf-8")):null}catch{return null}}function at(e){let t=0;try{let r=fs$1.readdirSync(e,{withFileTypes:!0});for(let n of r){let s=path.join(e,n.name);n.isFile()?t+=fs$1.statSync(s).size:n.isDirectory()&&(t+=at(s));}}catch{}return t}function Ee(e,t,r,n){let s=st(path.join(r,"index.json"));x(t,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-n)/1e3)});}function Pe(e,t,r){let n=st(path.join(r,"summary.json"));if(!n){x(t,404,{error:"Summary not found"});return}x(t,200,n);}function Fe(e,t,r){let n=st(path.join(r,"index.json"));if(!n){x(t,404,{error:"Test index not found"});return}let a=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,o=Math.max(1,parseInt(a.get("page")??"1",10)||1),i=Math.min(Me,Math.max(1,parseInt(a.get("pageSize")??"100",10)||100)),l=a.get("status")?.split(",").filter(Boolean)??null,d=a.get("file")??null,c=a.get("search")?.toLowerCase()??null,p=a.get("tag")?.split(",").filter(Boolean)??null,f=a.get("sort")??"file",u=a.get("order")==="desc"?-1:1,g=n;l&&l.length>0&&(g=g.filter(w=>l.includes(w.status))),d&&(g=g.filter(w=>w.filePath===d||w.filePath.startsWith(d+"/"))),c&&(g=g.filter(w=>w.title.toLowerCase().includes(c)||w.filePath.toLowerCase().includes(c))),p&&p.length>0&&(g=g.filter(w=>p.some(b=>w.tags.includes(b)))),g=[...g].sort((w,b)=>{let T=0;switch(f){case "duration":T=w.duration-b.duration;break;case "status":T=w.status.localeCompare(b.status);break;case "title":T=w.title.localeCompare(b.title);break;default:T=w.filePath.localeCompare(b.filePath);break}return T*u});let h=g.length,m=Math.max(1,Math.ceil(h/i)),y=(o-1)*i,k=g.slice(y,y+i);x(t,200,{tests:k,pagination:{page:o,pageSize:i,totalItems:h,totalPages:m},filters:{status:l,file:d,search:c,tag:p}});}function De(e,t,r,n){if(!Le.test(n)){x(t,400,{error:"Invalid test ID format"});return}let s=path.join(r,"tests",n,"meta.json"),a=path.join(r,"tests",`${n}.json`),o=fs$1.existsSync(s)?s:fs$1.existsSync(a)?a:null;if(!o){x(t,404,{error:`Test not found: ${n}`});return}try{let i=fs$1.readFileSync(o,"utf-8");t.writeHead(200,{"Content-Type":"application/json"}),t.end(i);}catch(i){x(t,500,{error:i instanceof Error?i.message:String(i)});}}async function Be(e,t,r,n,s){if(!Le.test(n)){x(t,400,{error:"Invalid test ID format"});return}let o=path.join(r,"tests",n,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!fs$1.existsSync(o)){x(t,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let l=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,d=Math.max(1,parseInt(l.get("page")??"1",10)||1),c=Math.min(Me,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),p,f=path.join(r,"tests",n,"meta.json");if(fs$1.existsSync(f))try{let g=JSON.parse(fs$1.readFileSync(f,"utf-8"));switch(s){case "network":p=g.networkRequestsCount;break;case "console":p=g.consoleLogsCount;break;case "api-calls":p=g.apiCallsCount;break}}catch{}let u=await Ae(o,d,c,p);x(t,200,u);}catch(i){x(t,500,{error:i instanceof Error?i.message:String(i)});}}function qe(e,t,r){let n=st(path.join(r,"index.json"));if(!n){x(t,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(t,200,{files:a});}function Oe(e,t,r){if(!fs$1.existsSync(r)){x(t,200,{runs:[],totalSizeBytes:0});return}try{let n=[],s=0,a=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!Dt.test(o.name))continue;let i=path.join(r,o.name),l=at(i),d=fs$1.readdirSync(i,{withFileTypes:!0}).filter(c=>c.isDirectory());n.push({folderName:o.name,totalSizeBytes:l,testCount:d.length}),s+=l;}n.sort((o,i)=>i.folderName.localeCompare(o.folderName)),x(t,200,{runs:n,totalSizeBytes:s});}catch(n){x(t,500,{error:n instanceof Error?n.message:String(n)});}}function He(e,t,r){try{let n=0,s=0;if(fs$1.existsSync(r)){let a=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!Dt.test(o.name))continue;let i=path.join(r,o.name),l=at(i);fs$1.rmSync(i,{recursive:!0,force:!0}),s+=l,n++;}}x(t,200,{deletedCount:n,freedBytes:s});}catch(n){x(t,500,{error:n instanceof Error?n.message:String(n)});}}function Ue(e,t,r,n){if(!Dt.test(n)){x(t,400,{error:"Invalid folder name"});return}let s=path.join(r,n);try{if(!fs$1.statSync(s).isDirectory()){x(t,404,{error:"Not found"});return}}catch{x(t,404,{error:"Not found"});return}try{let a=at(s);fs$1.rmSync(s,{recursive:!0,force:!0}),x(t,200,{deleted:n,freedBytes:a});}catch(a){x(t,500,{error:a instanceof Error?a.message:String(a)});}}function ze(e,t,r){x(t,200,{status:"shutting_down"}),r.close();}function Bt(e,t,r){if(!fs$1.existsSync(r)){x(t,404,{error:"File not found"});return}try{let n=fs$1.readFileSync(r),s=path.extname(r).toLowerCase(),a=Ln[s]??"application/octet-stream";t.writeHead(200,{"Content-Type":a}),t.end(n);}catch(n){x(t,500,{error:n instanceof Error?n.message:String(n)});}}var Ln={".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 Pn=9323,Fn=10,Dn=1800*1e3;function J(e,t){return new Promise((r,n)=>{let s=t?.port??Pn,a=Date.now(),o,i=0,l=fs$1.existsSync(path.join(e,"artifacts"))?path.join(e,"artifacts"):fs$1.existsSync(path.join(e,"..","artifacts"))?path.join(e,"..","artifacts"):path.join(e,"artifacts");function d(){clearTimeout(o),o=setTimeout(()=>{p.close();},Dn);}let c=t?.htmlPath??null;if(!c){let u=path.dirname(e);try{let g=fs$1.readdirSync(u).find(h=>h.endsWith(".html"));g&&(c=path.join(u,g));}catch{}}let p=http.createServer((u,g)=>{if(d(),Ne(g),u.method==="OPTIONS"){g.writeHead(204),g.end();return}let h;try{h=new URL(u.url??"/",`http://${u.headers.host??"localhost"}`).pathname;}catch{x(g,400,{error:"Invalid URL"});return}if(u.method==="GET"&&(h==="/"||h==="/index.html")){if(c&&fs$1.existsSync(c)){Bt(u,g,c);return}x(g,404,{error:"HTML report not found"});return}if(u.method==="GET"&&h==="/api/health"){Ee(u,g,e,a);return}if(u.method==="GET"&&h==="/api/summary"){Pe(u,g,e);return}if(u.method==="GET"&&h==="/api/tests"){Fe(u,g,e);return}if(u.method==="GET"&&h==="/api/files"){qe(u,g,e);return}let m=h.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(u.method==="GET"&&m){Be(u,g,e,m[1],m[2]);return}let y=h.match(/^\/api\/tests\/([a-f0-9]+)$/);if(u.method==="GET"&&y){De(u,g,e,y[1]);return}if(u.method==="GET"&&h==="/api/artifacts"){Oe(u,g,l);return}if(u.method==="DELETE"&&h==="/api/artifacts"){He(u,g,l);return}let k=h.match(/^\/api\/artifacts\/(.+)$/);if(u.method==="DELETE"&&k){Ue(u,g,l,decodeURIComponent(k[1]));return}if(u.method==="GET"&&h.startsWith("/artifacts/")){let w=decodeURIComponent(h.slice(11));if(w.includes("..")||w.includes("\0")){x(g,400,{error:"Invalid path"});return}Bt(u,g,path.join(l,w));return}if(u.method==="POST"&&h==="/api/shutdown"){ze(u,g,p);return}x(g,404,{error:"Not found"});});function f(u){let g=h=>{h.code==="EADDRINUSE"&&i<Fn?(i++,f(u+1)):n(h);};p.once("error",g),p.listen(u,"127.0.0.1",()=>{p.removeListener("error",g);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());})});});}f(s);})}async function $e(e){let t=await J(e);return {port:t.port,dispose:t.dispose}}function On(e,t,r){let n=JSON.stringify(e),s=r?JSON.stringify(r):null;return Te(n,t,s)}async function Ot(e,t,r){try{let n=null,s=null,a=t.reportMode==="streaming"||t.reportMode==="auto"&&e.timeline.length===0&&e.summary.total>=t.streamingThreshold,o,i=t.htmlReportPath,l=path.dirname(i);fs$1.mkdirSync(l,{recursive:!0});let d="",c="[]",p=null;if(a){d=JSON.stringify(e.summary);let u=path.dirname(t.outputPath),g=path.join(u,".testrelic-report");try{let h=path.join(g,"index-compact.json"),m=path.join(g,"index.json");fs$1.existsSync(h)?c=fs$1.readFileSync(h,"utf-8"):fs$1.existsSync(m)&&(c=fs$1.readFileSync(m,"utf-8"));}catch{}p=r?JSON.stringify(r):null,o=Pt(d,c,null,p);}else o=On(e,null,r);let f=i+".tmp";if(fs$1.writeFileSync(f,o,"utf-8"),fs$1.renameSync(f,i),a){if(e.ci===null){let u=path.dirname(t.outputPath),g=path.join(u,".testrelic-report"),h=path.resolve(i);try{if(await Un(),n=await zn(g),!n){s=await J(g,{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(`
2547
2547
  Report server: http://127.0.0.1:${n}
2548
2548
  `);try{let m=Pt(d,c,n,p),y=i+".tmp";fs$1.writeFileSync(y,m,"utf-8"),fs$1.renameSync(y,i);}catch{}}}catch{}}}else if(t.openReport&&e.ci===null&&t.includeArtifacts){let u=path.dirname(t.outputPath),g=path.join(u,"artifacts");if(fs$1.existsSync(g))try{let h=await $e(g);n=h.port,process.on("exit",()=>{h.dispose();});}catch{}}if(t.openReport&&e.ci===null)if(a&&n)Ft(`http://127.0.0.1:${n}`);else {let u=path.resolve(i);Ft(u);}}catch(n){process.stderr.write(`[testrelic] Failed to write HTML report: ${n instanceof Error?n.message:String(n)}
2549
- `);}}var dt=9323,Je=10;async function Un(){for(let e=dt;e<dt+Je;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),500),n=await fetch(`http://127.0.0.1:${e}/api/health`,{signal:t.signal});if(clearTimeout(r),n.ok)return e}catch{}return null}async function zn(){for(let e=dt;e<dt+Je;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),1e3);await fetch(`http://127.0.0.1:${e}/api/shutdown`,{method:"POST",signal:t.signal}),clearTimeout(r);}catch{}await new Promise(e=>setTimeout(e,300));}async function $n(e){let r=[path.join(__dirname,"cli.cjs"),path.join(__dirname,"cli.js"),path.join(__dirname,"..","dist","cli.cjs"),path.join(__dirname,"..","dist","cli.js")].find(n=>fs$1.existsSync(n));if(!r){let n=await J(e);return process.on("exit",()=>{n?.dispose();}),n.port}return new Promise(n=>{let s=child_process.spawn(process.execPath,[r,"serve",e],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),a="",o=false,i=setTimeout(()=>{o||(o=true,s.stderr?.removeAllListeners(),Un().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 Wn=20,Ht=0,Ut=[];async function Ye(e,t){Ht>=Wn&&await new Promise(r=>Ut.push(r)),Ht++;try{return await promises.copyFile(e,t),!0}catch{return false}finally{Ht--,Ut.length>0&&Ut.shift()();}}var Y=[];async function Ze(){Y.length!==0&&(await Promise.allSettled(Y),Y.length=0);}function Qe(e){let t=new Date,r=a=>String(a).padStart(2,"0"),n=`${t.getFullYear()}-${r(t.getMonth()+1)}-${r(t.getDate())}T${r(t.getHours())}-${r(t.getMinutes())}-${r(t.getSeconds())}`;if(!fs$1.existsSync(path.join(e,n)))return n;let s=1;for(;fs$1.existsSync(path.join(e,`${n}-${s}`));)s++;return `${n}-${s}`}function Gn(e){let t=e.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return t.length>100&&(t=t.substring(0,100).replace(/-+$/,"")),t||"unnamed-test"}function Xe(e,t,r,n,s){let a=e.find(f=>f.name==="screenshot"&&f.path),o=e.find(f=>f.name==="video"&&f.path);if(!a&&!o)return null;let i=Gn(t);r>0&&(i+=`--retry-${r}`);let l=s?["artifacts",s,i]:["artifacts",i],d=path.join(n,...l),c=l,p={};try{fs$1.mkdirSync(d,{recursive:!0});}catch{return null}if(a?.path&&fs$1.existsSync(a.path)){let u=`screenshot${path.extname(a.path)||".png"}`,g=path.join(d,u);Y.push(Ye(a.path,g).then(()=>{})),p.screenshot=`${c.join("/")}/${u}`;}if(o?.path&&fs$1.existsSync(o.path)){let u=`video${path.extname(o.path)||".webm"}`,g=path.join(d,u);Y.push(Ye(o.path,g).then(()=>{})),p.video=`${c.join("/")}/${u}`;}return !p.screenshot&&!p.video?null:p}var Yn=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Zn="1.0";function Qn(e){let t=path.extname(e).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(t)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(t)?"video":"other"}function tr(e,t,r){let n=[];try{let s=fs$1.readdirSync(e,{withFileTypes:!0});for(let a of s){if(!a.isFile())continue;let o=path.join(e,a.name),i=fs$1.statSync(o);n.push({name:a.name,type:Qn(a.name),relativePath:`artifacts/${t}/${r}/${a.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:n}}function Xn(e,t){let r=path.join(e,t),n=[],s=0;try{let o=fs$1.readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let l=tr(path.join(r,i.name),t,i.name);n.push(l);for(let d of l.files)s+=d.sizeBytes;}}catch{}let a=t.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:t,timestamp:a,totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}}function er(e,t){let r=path.join(e,"artifacts"),n=[],s=[],a=0;try{let i=fs$1.readdirSync(r,{withFileTypes:!0});for(let l of i)if(l.isDirectory())if(Yn.test(l.name)){let d=Xn(r,l.name);n.push({...d,isCurrentRun:l.name===t});}else {let d=tr(path.join(r,l.name),l.name,l.name);s.push(d);for(let c of d.files)a+=c.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:Zn,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:n,serverPort:null}}function ss(e){let t=e,{root:r}=path.parse(t);for(;t!==r;){if(fs$1.existsSync(path.join(t,".git")))return t;t=path.join(t,"..");}return null}function nr(e){try{let t=ss(e);if(!t)return;let r=path.join(t,".gitignore"),n=path.relative(t,e).replace(/\\/g,"/"),s=n.endsWith("/")?n:`${n}/`;if(fs$1.existsSync(r)&&fs$1.readFileSync(r,"utf-8").split(`
2549
+ `);}}var lt=9323,Je=10;async function Hn(){for(let e=lt;e<lt+Je;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),500),n=await fetch(`http://127.0.0.1:${e}/api/health`,{signal:t.signal});if(clearTimeout(r),n.ok)return e}catch{}return null}async function Un(){for(let e=lt;e<lt+Je;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),1e3);await fetch(`http://127.0.0.1:${e}/api/shutdown`,{method:"POST",signal:t.signal}),clearTimeout(r);}catch{}await new Promise(e=>setTimeout(e,300));}async function zn(e){let r=[path.join(__dirname,"cli.cjs"),path.join(__dirname,"cli.js"),path.join(__dirname,"..","dist","cli.cjs"),path.join(__dirname,"..","dist","cli.js")].find(n=>fs$1.existsSync(n));if(!r){let n=await J(e);return process.on("exit",()=>{n?.dispose();}),n.port}return new Promise(n=>{let s=child_process.spawn(process.execPath,[r,"serve",e],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),a="",o=false,i=setTimeout(()=>{o||(o=true,s.stderr?.removeAllListeners(),Hn().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 Vn=20,Ht=0,Ut=[];async function Ye(e,t){Ht>=Vn&&await new Promise(r=>Ut.push(r)),Ht++;try{return await promises.copyFile(e,t),!0}catch{return false}finally{Ht--,Ut.length>0&&Ut.shift()();}}var Y=[];async function Ze(){Y.length!==0&&(await Promise.allSettled(Y),Y.length=0);}function Qe(e){let t=new Date,r=a=>String(a).padStart(2,"0"),n=`${t.getFullYear()}-${r(t.getMonth()+1)}-${r(t.getDate())}T${r(t.getHours())}-${r(t.getMinutes())}-${r(t.getSeconds())}`;if(!fs$1.existsSync(path.join(e,n)))return n;let s=1;for(;fs$1.existsSync(path.join(e,`${n}-${s}`));)s++;return `${n}-${s}`}function Wn(e){let t=e.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return t.length>100&&(t=t.substring(0,100).replace(/-+$/,"")),t||"unnamed-test"}function Xe(e,t,r,n,s){let a=e.find(f=>f.name==="screenshot"&&f.path),o=e.find(f=>f.name==="video"&&f.path);if(!a&&!o)return null;let i=Wn(t);r>0&&(i+=`--retry-${r}`);let l=s?["artifacts",s,i]:["artifacts",i],d=path.join(n,...l),c=l,p={};try{fs$1.mkdirSync(d,{recursive:!0});}catch{return null}if(a?.path&&fs$1.existsSync(a.path)){let u=`screenshot${path.extname(a.path)||".png"}`,g=path.join(d,u);Y.push(Ye(a.path,g).then(()=>{})),p.screenshot=`${c.join("/")}/${u}`;}if(o?.path&&fs$1.existsSync(o.path)){let u=`video${path.extname(o.path)||".webm"}`,g=path.join(d,u);Y.push(Ye(o.path,g).then(()=>{})),p.video=`${c.join("/")}/${u}`;}return !p.screenshot&&!p.video?null:p}var Kn=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Yn="1.0";function Zn(e){let t=path.extname(e).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(t)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(t)?"video":"other"}function tr(e,t,r){let n=[];try{let s=fs$1.readdirSync(e,{withFileTypes:!0});for(let a of s){if(!a.isFile())continue;let o=path.join(e,a.name),i=fs$1.statSync(o);n.push({name:a.name,type:Zn(a.name),relativePath:`artifacts/${t}/${r}/${a.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:n}}function Qn(e,t){let r=path.join(e,t),n=[],s=0;try{let o=fs$1.readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let l=tr(path.join(r,i.name),t,i.name);n.push(l);for(let d of l.files)s+=d.sizeBytes;}}catch{}let a=t.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:t,timestamp:a,totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}}function er(e,t){let r=path.join(e,"artifacts"),n=[],s=[],a=0;try{let i=fs$1.readdirSync(r,{withFileTypes:!0});for(let l of i)if(l.isDirectory())if(Kn.test(l.name)){let d=Qn(r,l.name);n.push({...d,isCurrentRun:l.name===t});}else {let d=tr(path.join(r,l.name),l.name,l.name);s.push(d);for(let c of d.files)a+=c.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:Yn,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:n,serverPort:null}}function ns(e){let t=e,{root:r}=path.parse(t);for(;t!==r;){if(fs$1.existsSync(path.join(t,".git")))return t;t=path.join(t,"..");}return null}function nr(e){try{let t=ns(e);if(!t)return;let r=path.join(t,".gitignore"),n=path.relative(t,e).replace(/\\/g,"/"),s=n.endsWith("/")?n:`${n}/`;if(fs$1.existsSync(r)&&fs$1.readFileSync(r,"utf-8").split(`
2550
2550
  `).map(l=>l.trim()).some(l=>l===s||l===n))return;let a=`
2551
2551
  # TestRelic test artifacts
2552
2552
  ${s}
2553
- `;fs$1.appendFileSync(r,a,"utf-8");}catch{}}function ir(e,t){let r=[];for(let n of e){let s=as(n),a=is(n),o=os(n,s,a,t),i=ls(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(ds),cs(r,e),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 as(e){return {title:e.title,fullTitle:e.titlePath,status:e.status,duration:e.duration,retries:e.retryCount,retry:e.retry,tags:e.tags,failure:e.failure}}function is(e){return {title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,retryStatus:e.retryStatus,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,networkRequests:e.networkRequests,apiCalls:e.apiCalls,apiAssertions:e.apiAssertions,actions:e.actions,consoleLogs:e.consoleLogs}}function os(e,t,r,n){let s=[];for(let a of e.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:e.specFile,test:t,tests:[r],_testTitle:e.title});return s}function ls(e,t,r){if(!e.apiCalls||e.apiCalls.length===0)return [];let n=e.apiAssertions??[];return e.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:ar(s.responseBody)}),{type:"api_call",callId:s.id,method:s.method,url:s.url,timestamp:s.timestamp,responseTime:s.error?null:s.responseTimeMs,request:{headers:s.requestHeaders,body:ar(s.requestBody)},response:o,...s.error?{error:s.error}:{},assertions:a,specFile:e.specFile,test:t,tests:[r],_testTitle:e.title}})}function ds(e,t){let r=new Date(e.timestamp).getTime(),n=new Date(t.timestamp).getTime();if(r!==n)return r-n;let s={navigation:0,api_call:1},a=s[e.type],o=s[t.type];return a!==o?a-o:e.type==="api_call"&&t.type==="api_call"&&e.callId&&t.callId?sr(e.callId)-sr(t.callId):0}function sr(e){let t=e.match(/(\d+)$/);return t?parseInt(t[1],10):0}function cs(e,t){for(let r=0;r<e.length;r++){let n=e[r];if(n.type!=="navigation")continue;let s=new Date(n.timestamp).getTime(),a=null;for(let o=r+1;o<e.length;o++)if(e[o]._testTitle===n._testTitle){a=new Date(e[o].timestamp).getTime();break}if(a!==null)n.durationOnUrl=Math.max(0,a-s);else {let o=t.find(i=>i.title===n._testTitle);if(o){let i=new Date(o.completedAt).getTime();n.durationOnUrl=Math.max(0,i-s);}}}}function ar(e){if(e==null)return null;try{return JSON.parse(e)}catch{return e}}function jt(e,t){let r=e.length,n=Math.min(Math.ceil(t/100*r)-1,r-1);return e[Math.max(0,n)]}function us(e){try{let t=new URL(e);return t.origin+t.pathname}catch{return e}}function ps(e){return e==null?"error":e>=200&&e<300?"2xx":e>=300&&e<400?"3xx":e>=400&&e<500?"4xx":e>=500&&e<600?"5xx":"error"}function or(e,t){let r=0,n=0,s=0,a=0,o=0;for(let v of e)switch(v.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 v of e)v.apiCalls&&i.push(...v.apiCalls);let l=i.length,d=new Set,c={},p={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},f=[];for(let v of i)d.add(us(v.url)),c[v.method]=(c[v.method]??0)+1,p[ps(v.responseStatusCode)]+=1,f.push(v.responseTimeMs);let u=null;if(f.length>0){let v=[...f].sort((A,S)=>A-S),C=v.reduce((A,S)=>A+S,0);u={avg:Math.round(C/v.length),min:v[0],max:v[v.length-1],p50:jt(v,50),p95:jt(v,95),p99:jt(v,99)};}let g=0,h=0,m=0;for(let v of e)if(v.apiAssertions)for(let C of v.apiAssertions)g++,C.status==="passed"?h++:m++;let y=0,k=new Set;for(let v of e){y+=v.navigations.length;for(let C of v.navigations)k.add(C.url);}let w=0,b={};function T(v){for(let C of v)w++,b[C.category]=(b[C.category]??0)+1,C.children.length>0&&T(C.children);}for(let v of e)v.actions&&T(v.actions);return {total:e.length,passed:r,failed:n,flaky:s,skipped:a,timedout:o,totalApiCalls:l,uniqueApiUrls:d.size,apiCallsByMethod:c,apiCallsByStatusRange:p,apiResponseTime:u,totalAssertions:g,passedAssertions:h,failedAssertions:m,totalNavigations:y,uniqueNavigationUrls:k.size,totalTimelineSteps:t,totalActionSteps:w,actionStepsByCategory:b}}function fs(e){let t=56-e.length;return t>0?e+" ".repeat(t):e}function I(e){return `\u2502 ${fs(e)} \u2502
2553
+ `;fs$1.appendFileSync(r,a,"utf-8");}catch{}}function ir(e,t){let r=[];for(let n of e){let s=ss(n),a=as(n),o=is(n,s,a,t),i=os(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(ls),ds(r,e),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 ss(e){return {title:e.title,fullTitle:e.titlePath,status:e.status,duration:e.duration,retries:e.retryCount,retry:e.retry,tags:e.tags,failure:e.failure}}function as(e){return {title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,retryStatus:e.retryStatus,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,networkRequests:e.networkRequests,apiCalls:e.apiCalls,apiAssertions:e.apiAssertions,actions:e.actions,consoleLogs:e.consoleLogs}}function is(e,t,r,n){let s=[];for(let a of e.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:e.specFile,test:t,tests:[r],_testTitle:e.title});return s}function os(e,t,r){if(!e.apiCalls||e.apiCalls.length===0)return [];let n=e.apiAssertions??[];return e.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:ar(s.responseBody)}),{type:"api_call",callId:s.id,method:s.method,url:s.url,timestamp:s.timestamp,responseTime:s.error?null:s.responseTimeMs,request:{headers:s.requestHeaders,body:ar(s.requestBody)},response:o,...s.error?{error:s.error}:{},assertions:a,specFile:e.specFile,test:t,tests:[r],_testTitle:e.title}})}function ls(e,t){let r=new Date(e.timestamp).getTime(),n=new Date(t.timestamp).getTime();if(r!==n)return r-n;let s={navigation:0,api_call:1},a=s[e.type],o=s[t.type];return a!==o?a-o:e.type==="api_call"&&t.type==="api_call"&&e.callId&&t.callId?sr(e.callId)-sr(t.callId):0}function sr(e){let t=e.match(/(\d+)$/);return t?parseInt(t[1],10):0}function ds(e,t){for(let r=0;r<e.length;r++){let n=e[r];if(n.type!=="navigation")continue;let s=new Date(n.timestamp).getTime(),a=null;for(let o=r+1;o<e.length;o++)if(e[o]._testTitle===n._testTitle){a=new Date(e[o].timestamp).getTime();break}if(a!==null)n.durationOnUrl=Math.max(0,a-s);else {let o=t.find(i=>i.title===n._testTitle);if(o){let i=new Date(o.completedAt).getTime();n.durationOnUrl=Math.max(0,i-s);}}}}function ar(e){if(e==null)return null;try{return JSON.parse(e)}catch{return e}}function jt(e,t){let r=e.length,n=Math.min(Math.ceil(t/100*r)-1,r-1);return e[Math.max(0,n)]}function cs(e){try{let t=new URL(e);return t.origin+t.pathname}catch{return e}}function us(e){return e==null?"error":e>=200&&e<300?"2xx":e>=300&&e<400?"3xx":e>=400&&e<500?"4xx":e>=500&&e<600?"5xx":"error"}function or(e,t){let r=0,n=0,s=0,a=0,o=0;for(let v of e)switch(v.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 v of e)v.apiCalls&&i.push(...v.apiCalls);let l=i.length,d=new Set,c={},p={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},f=[];for(let v of i)d.add(cs(v.url)),c[v.method]=(c[v.method]??0)+1,p[us(v.responseStatusCode)]+=1,f.push(v.responseTimeMs);let u=null;if(f.length>0){let v=[...f].sort((A,S)=>A-S),C=v.reduce((A,S)=>A+S,0);u={avg:Math.round(C/v.length),min:v[0],max:v[v.length-1],p50:jt(v,50),p95:jt(v,95),p99:jt(v,99)};}let g=0,h=0,m=0;for(let v of e)if(v.apiAssertions)for(let C of v.apiAssertions)g++,C.status==="passed"?h++:m++;let y=0,k=new Set;for(let v of e){y+=v.navigations.length;for(let C of v.navigations)k.add(C.url);}let w=0,b={};function T(v){for(let C of v)w++,b[C.category]=(b[C.category]??0)+1,C.children.length>0&&T(C.children);}for(let v of e)v.actions&&T(v.actions);return {total:e.length,passed:r,failed:n,flaky:s,skipped:a,timedout:o,totalApiCalls:l,uniqueApiUrls:d.size,apiCallsByMethod:c,apiCallsByStatusRange:p,apiResponseTime:u,totalAssertions:g,passedAssertions:h,failedAssertions:m,totalNavigations:y,uniqueNavigationUrls:k.size,totalTimelineSteps:t,totalActionSteps:w,actionStepsByCategory:b}}function ps(e){let t=56-e.length;return t>0?e+" ".repeat(t):e}function I(e){return `\u2502 ${ps(e)} \u2502
2554
2554
  `}function Vt(e,t,r,n){if(n||e.total===0)return;let s=`\u250C${"\u2500".repeat(58)}\u2510
2555
2555
  `,a=`\u2514${"\u2500".repeat(58)}\u2518
2556
2556
  `,o=I(""),i=s;i+=I("TestRelic AI - Playwright Test Report"),i+=o;let l=[];if(e.passed>0&&l.push(`${e.passed} \u2713`),e.failed>0&&l.push(`${e.failed} \u2717`),e.flaky>0&&l.push(`${e.flaky} \u26A0`),e.skipped>0&&l.push(`${e.skipped} skipped`),e.timedout>0&&l.push(`${e.timedout} timedout`),i+=I(`Tests: ${e.total} total (${l.join(" ")})`),e.totalNavigations>0&&(i+=I(`Navigations: ${e.totalNavigations} visits across ${e.uniqueNavigationUrls} unique URLs`)),e.totalApiCalls>0){i+=I(`API Calls: ${e.totalApiCalls} calls across ${e.uniqueApiUrls} unique endpoints`);let d=Object.entries(e.apiCallsByMethod).filter(([,p])=>p>0).map(([p,f])=>`${p}: ${f}`);d.length>0&&(i+=I(` ${d.join(" ")}`));let c=Object.entries(e.apiCallsByStatusRange).filter(([,p])=>p>0).map(([p,f])=>`${p}: ${f}`);c.length>0&&(i+=I(` ${c.join(" ")}`)),e.apiResponseTime&&(i+=I(` Avg response: ${e.apiResponseTime.avg}ms P95: ${e.apiResponseTime.p95}ms`));}if(e.totalAssertions>0&&(i+=I(`Assertions: ${e.totalAssertions} total (${e.passedAssertions} \u2713 ${e.failedAssertions} \u2717)`)),e.totalActionSteps>0){let d=[],c=e.actionStepsByCategory;c.ui_action&&d.push(`${c.ui_action} UI`),c.assertion&&d.push(`${c.assertion} assertions`),c.custom_step&&d.push(`${c.custom_step} custom`);let p=d.length>0?` (${d.join(" ")})`:"";i+=I(`Actions: ${e.totalActionSteps} steps${p}`);}i+=I(`Report: ${r}`),i+=I(`Data: ${t}`),i+=a,i+=`For more information visit us at https://docs.testrelic.ai
2557
- `,process.stderr.write(i);}var gs=new Set(["pw:api","expect","test.step"]);function hs(e){return e==="expect"?"assertion":e==="test.step"?"custom_step":"ui_action"}function Wt(e,t,r){if(gs.has(e.category)){let n=[];for(let a of e.steps)Wt(a,t,n);let s=e.startTime.getTime()-t.getTime();r.push({title:e.title,category:hs(e.category),timestamp:e.startTime.toISOString(),duration:e.duration,videoOffset:s>=0?s/1e3:null,status:e.error?"failed":"passed",error:e.error?.message??null,children:n});}else for(let n of e.steps)Wt(n,t,r);}function lr(e,t){let r=[];for(let n of e)Wt(n,t,r);return r}var ys=new Set(["localhost","127.0.0.1","0.0.0.0"]);function cr(e){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&ys.has(t.hostname)))throw core.createError(core.ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${t.protocol}//${t.hostname}`)}var bs=3e3;async function Gt(e){let t=new AbortController,r=setTimeout(()=>t.abort(),bs);try{return (await fetch(`${e}/health`,{method:"GET",signal:t.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function ur(e){return new Promise(t=>setTimeout(t,e))}async function dr(e){try{let r=(await e.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 ${e.status}`}async function Jt(e,t,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),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 ur(l);let d=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:n.signal});if(d.ok){let c=await d.json();return {accessToken:c.accessToken,refreshToken:c.refreshToken,expiresIn:c.expiresIn,orgId:c.orgId,orgName:c.orgName,userId:c.userId,userName:c.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return a.status===400?{code:"validation_error",message:await dr(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 dr(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 Kt(e){return "code"in e&&typeof e.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(e.code)}async function pr(e,t,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),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 ur(l),a=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),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 fr(e,t,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(`${e}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(l),signal:o.signal});if(!d.ok)return null;let c=await d.json();return {repoId:c.repoId,displayName:c.displayName}}catch{return null}finally{clearTimeout(i);}}var Ts=5e3,gr=500;function O(e,t){try{return child_process.execSync(e,{cwd:t,timeout:Ts,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function hr(e){let t=O("git rev-parse --abbrev-ref HEAD",e),r=O("git rev-parse HEAD",e),n=O("git log -1 --pretty=%s",e),s=n&&n.length>gr?n.substring(0,gr)+"\u2026":n,a=Ss(e),o=a?Q(a):null;return {branch:t,commitSha:r,commitMessage:s,remoteUrl:o}}function Ss(e){let t=O("git remote get-url origin",e);if(t)return t;let r=O("git remote",e);if(!r)return null;let n=r.split(`
2558
- `)[0]?.trim();return n?O(`git remote get-url ${n}`,e):null}function Q(e){let t=e.trim();return t=t.replace(/^[a-z+]+:\/\//,""),t=t.replace(/^[^@]+@/,""),t=t.replace(/:(?!\d)/,"/"),t=t.replace(/\.git$/,""),t=t.replace(/\/+$/,""),t=t.replace(/^[^@/]+@/,""),t.toLowerCase()}function mr(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function Yt(e){try{let t=fs$1.readFileSync(path.join(e,"package.json"),"utf-8"),r=JSON.parse(t);return typeof r.name=="string"&&r.name.length>0?r.name:null}catch{return null}}function X(e){let t=Yt(e);return t||`local/${path.basename(e)}`}var Ms="1.0.0",vr=10;function tt(e,t,r,n,s,a,o,i){try{fs$1.mkdirSync(e,{recursive:!0});let l=Date.now(),d=`${l}-${t}-${r}.json`,c=path.join(e,d),p={version:Ms,queuedAt:new Date(l).toISOString(),reason:n,retryCount:0,targetEndpoint:s,method:a,payload:o,headers:i},f=c+".tmp";fs$1.writeFileSync(f,JSON.stringify(p,null,2),"utf-8"),fs$1.renameSync(f,c);}catch(l){l.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
2557
+ `,process.stderr.write(i);}var fs=new Set(["pw:api","expect","test.step"]);function gs(e){return e==="expect"?"assertion":e==="test.step"?"custom_step":"ui_action"}function Wt(e,t,r){if(fs.has(e.category)){let n=[];for(let a of e.steps)Wt(a,t,n);let s=e.startTime.getTime()-t.getTime();r.push({title:e.title,category:gs(e.category),timestamp:e.startTime.toISOString(),duration:e.duration,videoOffset:s>=0?s/1e3:null,status:e.error?"failed":"passed",error:e.error?.message??null,children:n});}else for(let n of e.steps)Wt(n,t,r);}function lr(e,t){let r=[];for(let n of e)Wt(n,t,r);return r}var vs=new Set(["localhost","127.0.0.1","0.0.0.0"]);function cr(e){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&vs.has(t.hostname)))throw core.createError(core.ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${t.protocol}//${t.hostname}`)}var ys=3e3;async function Gt(e){let t=new AbortController,r=setTimeout(()=>t.abort(),ys);try{return (await fetch(`${e}/health`,{method:"GET",signal:t.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function ur(e){return new Promise(t=>setTimeout(t,e))}async function dr(e){try{let r=(await e.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 ${e.status}`}async function Jt(e,t,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),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 ur(l);let d=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:n.signal});if(d.ok){let c=await d.json();return {accessToken:c.accessToken,refreshToken:c.refreshToken,expiresIn:c.expiresIn,orgId:c.orgId,orgName:c.orgName,userId:c.userId,userName:c.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return a.status===400?{code:"validation_error",message:await dr(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 dr(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 Kt(e){return "code"in e&&typeof e.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(e.code)}async function pr(e,t,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),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 ur(l),a=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),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 fr(e,t,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(`${e}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(l),signal:o.signal});if(!d.ok)return null;let c=await d.json();return {repoId:c.repoId,displayName:c.displayName}}catch{return null}finally{clearTimeout(i);}}var Cs=5e3;function O(e,t){try{return child_process.execSync(e,{cwd:t,timeout:Cs,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function gr(e){let t=O("git rev-parse --abbrev-ref HEAD",e),r=O("git rev-parse --short HEAD",e),n=O("git log -1 --pretty=%s",e),s=Ts(e),a=s?Q(s):null;return {branch:t,commitSha:r,commitMessage:n,remoteUrl:a}}function Ts(e){let t=O("git remote get-url origin",e);if(t)return t;let r=O("git remote",e);if(!r)return null;let n=r.split(`
2558
+ `)[0]?.trim();return n?O(`git remote get-url ${n}`,e):null}function Q(e){let t=e.trim();return t=t.replace(/^[a-z+]+:\/\//,""),t=t.replace(/^[^@]+@/,""),t=t.replace(/:(?!\d)/,"/"),t=t.replace(/\.git$/,""),t=t.replace(/\/+$/,""),t=t.replace(/^[^@/]+@/,""),t.toLowerCase()}function hr(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function Yt(e){try{let t=fs$1.readFileSync(path.join(e,"package.json"),"utf-8"),r=JSON.parse(t);return typeof r.name=="string"&&r.name.length>0?r.name:null}catch{return null}}function X(e){let t=Yt(e);return t||`local/${path.basename(e)}`}var Ls="1.0.0",mr=10;function tt(e,t,r,n,s,a,o,i){try{fs$1.mkdirSync(e,{recursive:!0});let l=Date.now(),d=`${l}-${t}-${r}.json`,c=path.join(e,d),p={version:Ls,queuedAt:new Date(l).toISOString(),reason:n,retryCount:0,targetEndpoint:s,method:a,payload:o,headers:i},f=c+".tmp";fs$1.writeFileSync(f,JSON.stringify(p,null,2),"utf-8"),fs$1.renameSync(f,c);}catch(l){l.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
2559
2559
  `):process.stderr.write(`\u26A0 TestRelic: Unable to queue upload data.
2560
- `);}}async function wr(e,t,r){let n;try{n=fs$1.readdirSync(e).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+=vr)s.push(n.slice(a,a+vr));for(let a of s)for(let o of a){let i=path.join(e,o);try{if(!fs$1.statSync(i).isFile())continue;let d=fs$1.readFileSync(i,"utf-8"),c=JSON.parse(d);if(!core.isValidQueueEntry(c)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${o}
2561
- `),fs$1.unlinkSync(i);continue}let p=c;if((await fetch(p.targetEndpoint,{method:p.method,headers:{...p.headers,Authorization:`Bearer ${r}`},body:JSON.stringify(p.payload)})).ok)fs$1.unlinkSync(i);else return}catch{return}}}function xr(e,t){try{let r=fs$1.readdirSync(e).filter(s=>s.endsWith(".json")&&!s.endsWith(".tmp")),n=Date.now();for(let s of r){let a=path.join(e,s);try{let o=fs$1.readFileSync(a,"utf-8"),l=JSON.parse(o).queuedAt;if(typeof l=="string"){let d=new Date(l).getTime();n-d>t&&fs$1.unlinkSync(a);}}catch{try{fs$1.unlinkSync(a);}catch{}}}}catch{}}var qs=3e5,Os=864e5,Hs=6e4,kr=3e4,Xt="https://app.testrelic.com/settings/api-keys",pt=class{constructor(t){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=t,this.authState={mode:"pending",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null};}async initialize(){if(!this.config||!this.config.apiKey){this.setLocalMode("no_api_key"),process.stderr.write(`\u2139 TestRelic: No API key configured. Running in local mode.
2562
- `);return}try{if(cr(this.config.endpoint),this.gitMetadata=hr(),!await Gt(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.
2560
+ `);}}async function br(e,t,r){let n;try{n=fs$1.readdirSync(e).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+=mr)s.push(n.slice(a,a+mr));for(let a of s)for(let o of a){let i=path.join(e,o);try{if(!fs$1.statSync(i).isFile())continue;let d=fs$1.readFileSync(i,"utf-8"),c=JSON.parse(d);if(!core.isValidQueueEntry(c)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${o}
2561
+ `),fs$1.unlinkSync(i);continue}let p=c;if((await fetch(p.targetEndpoint,{method:p.method,headers:{...p.headers,Authorization:`Bearer ${r}`},body:JSON.stringify(p.payload)})).ok)fs$1.unlinkSync(i);else return}catch{return}}}function wr(e,t){try{let r=fs$1.readdirSync(e).filter(s=>s.endsWith(".json")&&!s.endsWith(".tmp")),n=Date.now();for(let s of r){let a=path.join(e,s);try{let o=fs$1.readFileSync(a,"utf-8"),l=JSON.parse(o).queuedAt;if(typeof l=="string"){let d=new Date(l).getTime();n-d>t&&fs$1.unlinkSync(a);}}catch{try{fs$1.unlinkSync(a);}catch{}}}}catch{}}var Bs=3e5,qs=864e5,Os=6e4,xr=3e4,Xt="https://platform.testrelic.ai/settings/api-keys",ut=class{constructor(t){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=t,this.authState={mode:"pending",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null};}async initialize(){if(!this.config||!this.config.apiKey){this.setLocalMode("no_api_key"),process.stderr.write(`\u2139 TestRelic: No API key configured. Running in local mode.
2562
+ `);return}try{if(cr(this.config.endpoint),this.gitMetadata=gr(),!await Gt(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.
2563
2563
  `);return}let r=await Jt(this.config.endpoint,this.config.apiKey,this.config.timeout);if(Kt(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})
2564
- `),await this.resolveRepoId(),this.config.queueDirectory&&(xr(this.config.queueDirectory,this.config.queueMaxAge),this.startBackgroundFlush()),this.startHealthCheck();}catch(t){this.setLocalMode("unexpected_error"),process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. Running in local mode. ${t instanceof Error?t.message:String(t)}
2565
- `);}}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://api.testrelic.com/api/v1"}async ensureValidToken(){if(!this.isCloudMode()||!this.authState.accessToken)return false;let t=this.authState.expiresAt??0;if(Date.now()+qs<t)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await pr(this.config.endpoint,this.authState.refreshToken,this.config.timeout);return r?(this.authState.accessToken=r.accessToken,this.authState.refreshToken=r.refreshToken,this.authState.expiresAt=Date.now()+r.expiresIn*1e3,!0):(this.switchToLocalMode("token_refresh_failed"),!1)}catch{return this.switchToLocalMode("token_refresh_error"),false}}switchToLocalMode(t){this.authState.mode!=="local"&&(this.authState.mode="local",this.failureReason=t,process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${t}).
2566
- `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,new Promise(t=>setTimeout(t,kr))]);}catch{}this.flushPromise=null;}this.authState={mode:"local",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null},this.repoId=null,this.gitMetadata=null;}setLocalMode(t){this.authState.mode="local",this.failureReason=t;}handleAuthError(t,r){switch(t){case "invalid_key":this.setLocalMode("invalid_api_key"),process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
2564
+ `),await this.resolveRepoId(),this.config.queueDirectory&&(wr(this.config.queueDirectory,this.config.queueMaxAge),this.startBackgroundFlush()),this.startHealthCheck();}catch(t){this.setLocalMode("unexpected_error"),process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. Running in local mode. ${t instanceof Error?t.message:String(t)}
2565
+ `);}}getMode(){return this.authState.mode}isCloudMode(){return this.authState.mode==="cloud"}isLocalMode(){return this.authState.mode==="local"}getAccessToken(){return this.authState.accessToken}getRepoId(){return this.repoId}getGitMetadata(){return this.gitMetadata}getConfig(){return this.config}getFailureReason(){return this.failureReason}getEndpoint(){return this.config?.endpoint??"https://platform.testrelic.ai/api/v1"}async ensureValidToken(){if(!this.isCloudMode()||!this.authState.accessToken)return false;let t=this.authState.expiresAt??0;if(Date.now()+Bs<t)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await pr(this.config.endpoint,this.authState.refreshToken,this.config.timeout);return r?(this.authState.accessToken=r.accessToken,this.authState.refreshToken=r.refreshToken,this.authState.expiresAt=Date.now()+r.expiresIn*1e3,!0):(this.switchToLocalMode("token_refresh_failed"),!1)}catch{return this.switchToLocalMode("token_refresh_error"),false}}switchToLocalMode(t){this.authState.mode!=="local"&&(this.authState.mode="local",this.failureReason=t,process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${t}).
2566
+ `));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,new Promise(t=>setTimeout(t,xr))]);}catch{}this.flushPromise=null;}this.authState={mode:"local",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null},this.repoId=null,this.gitMetadata=null;}setLocalMode(t){this.authState.mode="local",this.failureReason=t;}handleAuthError(t,r){switch(t){case "invalid_key":this.setLocalMode("invalid_api_key"),process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
2567
2567
  \u2192 Manage keys: ${Xt}
2568
2568
  `);break;case "expired_key":this.setLocalMode("expired_api_key"),process.stderr.write(`\u26A0 TestRelic: API key has expired. Running in local mode.
2569
2569
  \u2192 Generate a new key: ${Xt}
@@ -2572,14 +2572,14 @@ ${s}
2572
2572
  `);break;case "rate_limited":this.setLocalMode("rate_limited"),process.stderr.write(`\u26A0 TestRelic: Rate limited during authentication. Running in local mode.
2573
2573
  `);break;case "timeout":this.setLocalMode("auth_timeout"),process.stderr.write(`\u26A0 TestRelic: Authentication timed out. Running in local mode.
2574
2574
  `);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
2575
- `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let t=this.gitMetadata?.remoteUrl?Q(this.gitMetadata.remoteUrl):null,r=t?mr(t):this.config.projectName??X(process.cwd()),n=t??this.config.projectName??X(process.cwd()),s=this.readRepoCache(n);if(s){this.repoId=s.repoId;return}try{let a=await fr(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{}!t&&!this.config.projectName&&!Yt(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
2576
- `);}readRepoCache(t){if(!this.config)return null;let r=path.join(this.config.queueDirectory,"..","cache","repo.json");try{if(!fs$1.existsSync(r))return null;let n=fs$1.readFileSync(r,"utf-8"),s=JSON.parse(n);if(s.gitId!==t||Date.now()-s.resolvedAt>Os)return null;let a=this.hashApiKey();return a&&s.apiKeyHash!==a?null:s}catch{return null}}writeRepoCache(t,r,n){if(!this.config)return;let s=path.join(this.config.queueDirectory,"..","cache"),a=path.join(s,"repo.json");try{fs$1.mkdirSync(s,{recursive:!0});let o={repoId:r,gitId:t,displayName:n,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=a+".tmp";fs$1.writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),fs$1.renameSync(i,a);}catch{}}hashApiKey(){return this.config?.apiKey?crypto.createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let t=this.authState.accessToken,r=this.config.queueDirectory,n=this.config.endpoint;this.flushPromise=Promise.race([wr(r,n,t),new Promise(s=>setTimeout(s,kr))]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let t=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await Gt(t))return;if(this.config?.apiKey){let n=await Jt(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!Kt(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.
2577
- `),this.startBackgroundFlush();}}}catch{}},Hs);}};var zs=1048576,ft=[1e3,3e3,9e3],gt=3;function te(e,t,r,n,s){return {runId:e.testRunId,repoGitId:t,startedAt:e.startedAt,summary:e.summary,timeline:e.timeline,...s&&s.length>0?{tests:s}:{},...r?.branch??n?.branch?{branch:r?.branch??n?.branch}:{},...r?.commitSha??n?.commitSha?{commit:r?.commitSha??n?.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...e.completedAt?{finishedAt:e.completedAt}:{},...e.totalDuration?{duration:e.totalDuration}:{},...n?.provider?{ciProvider:n.provider}:{},...n?.runUrl?{ciRunUrl:n.runUrl}:{}}}async function ht(e){return new Promise(t=>setTimeout(t,e))}function $s(e){let t={};for(let[r,n]of Object.entries(e))n!=null&&(t[r]=n);return t}async function Cr(e,t,r){for(let n=0;n<gt;n++)try{let s=await fetch(e,t);if(s.ok)return s;if(s.status===401&&r&&n===0){let a=await r();if(a){let o={...t,headers:{...t.headers,Authorization:`Bearer ${a}`}},i=await fetch(e,o);if(i.ok)return i}return null}if(s.status===429&&n<gt-1){let a=s.headers.get("Retry-After"),o=a?parseInt(a,10)*1e3:ft[n];!isNaN(o)&&o>0?await ht(o):await ht(ft[n]);continue}if(s.status>=500&&n<gt-1){await ht(ft[n]);continue}return s}catch{if(n<gt-1){await ht(ft[n]);continue}return null}return null}function js(e){let t=JSON.stringify(e),r={"Content-Type":"application/json"};if(Buffer.byteLength(t,"utf-8")>zs){let n=zlib.gzipSync(Buffer.from(t,"utf-8"));return r["Content-Encoding"]="gzip",{body:n,headers:r}}return {body:t,headers:r}}async function Tr(e,t,r,n){let s=`${e}/runs`,{body:a,headers:o}=js(r);o.Authorization=`Bearer ${t}`;let i=await Cr(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 Sr(e,t,r){let n=`${e}/runs/init`;try{let s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify($s(r))});return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function Rr(e,t,r,n){let s=`${e}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)}).catch(()=>{});}async function Ar(e,t,r,n){let s=`${e}/runs/${r}/finalize`;return (await Cr(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)}))?.ok??false}function ee(e,t,r,n){let s=`${e}/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 ${t}`},body:JSON.stringify(o)}).catch(()=>{});}function _r(e,t,r,n){let s=[],a=[],o=null,i=0,l=null,d=0,c=null,p=0,f=e.filter(h=>h.name===core.ATTACHMENT_NAME&&h.body),u=false;if(f.length>0)for(let h of f)try{let m=JSON.parse(h.body.toString());if(core.isTestRelicFilePayload(m)){s=s.concat(m.navigations),a=a.concat(m.apiAssertions),m.networkRequestsFile&&(o=m.networkRequestsFile,i+=m.networkRequestsCount),m.consoleLogsFile&&(l=m.consoleLogsFile,d+=m.consoleLogsCount),m.apiCallsFile&&(c=m.apiCallsFile,p+=m.apiCallsCount),u=!0;continue}if(core.isTestRelicDataPayload(m)){s=s.concat(m.navigations),Array.isArray(m.apiAssertions)&&(a=a.concat(m.apiAssertions)),i+=m.networkRequests?.length??0,p+=m.apiCalls?.length??0;let y=m.consoleLogs;Array.isArray(y)&&(d+=y.length),u=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
2575
+ `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let t=this.gitMetadata?.remoteUrl?Q(this.gitMetadata.remoteUrl):null,r=t?hr(t):this.config.projectName??X(process.cwd()),n=t??this.config.projectName??X(process.cwd()),s=this.readRepoCache(n);if(s){this.repoId=s.repoId;return}try{let a=await fr(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{}!t&&!this.config.projectName&&!Yt(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
2576
+ `);}readRepoCache(t){if(!this.config)return null;let r=path.join(this.config.queueDirectory,"..","cache","repo.json");try{if(!fs$1.existsSync(r))return null;let n=fs$1.readFileSync(r,"utf-8"),s=JSON.parse(n);if(s.gitId!==t||Date.now()-s.resolvedAt>qs)return null;let a=this.hashApiKey();return a&&s.apiKeyHash!==a?null:s}catch{return null}}writeRepoCache(t,r,n){if(!this.config)return;let s=path.join(this.config.queueDirectory,"..","cache"),a=path.join(s,"repo.json");try{fs$1.mkdirSync(s,{recursive:!0});let o={repoId:r,gitId:t,displayName:n,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=a+".tmp";fs$1.writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),fs$1.renameSync(i,a);}catch{}}hashApiKey(){return this.config?.apiKey?crypto.createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let t=this.authState.accessToken,r=this.config.queueDirectory,n=this.config.endpoint;this.flushPromise=Promise.race([br(r,n,t),new Promise(s=>setTimeout(s,xr))]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let t=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await Gt(t))return;if(this.config?.apiKey){let n=await Jt(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!Kt(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.
2577
+ `),this.startBackgroundFlush();}}}catch{}},Os);}};var Us=1048576,pt=[1e3,3e3,9e3],ft=3;function te(e,t,r,n,s){return {runId:e.testRunId,repoGitId:t,startedAt:e.startedAt,summary:e.summary,timeline:e.timeline,...{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...e.completedAt?{finishedAt:e.completedAt}:{},...e.totalDuration?{duration:e.totalDuration}:{},...n?.provider?{ciProvider:n.provider}:{},...n?.runUrl?{ciRunUrl:n.runUrl}:{}}}async function gt(e){return new Promise(t=>setTimeout(t,e))}function zs(e){let t={};for(let[r,n]of Object.entries(e))n!=null&&(t[r]=n);return t}async function kr(e,t,r){for(let n=0;n<ft;n++)try{let s=await fetch(e,t);if(s.ok)return s;if(s.status===401&&r&&n===0){let a=await r();if(a){let o={...t,headers:{...t.headers,Authorization:`Bearer ${a}`}},i=await fetch(e,o);if(i.ok)return i}return null}if(s.status===429&&n<ft-1){let a=s.headers.get("Retry-After"),o=a?parseInt(a,10)*1e3:pt[n];!isNaN(o)&&o>0?await gt(o):await gt(pt[n]);continue}if(s.status>=500&&n<ft-1){await gt(pt[n]);continue}return s}catch{if(n<ft-1){await gt(pt[n]);continue}return null}return null}function $s(e){let t=JSON.stringify(e),r={"Content-Type":"application/json"};if(Buffer.byteLength(t,"utf-8")>Us){let n=zlib.gzipSync(Buffer.from(t,"utf-8"));return r["Content-Encoding"]="gzip",{body:n,headers:r}}return {body:t,headers:r}}async function Cr(e,t,r,n){let s=`${e}/runs`,{body:a,headers:o}=$s(r);o.Authorization=`Bearer ${t}`;let i=await kr(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 Tr(e,t,r){let n=`${e}/runs/init`;try{let s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(zs(r))});return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function Sr(e,t,r,n){let s=`${e}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)}).catch(()=>{});}async function Rr(e,t,r,n){let s=`${e}/runs/${r}/finalize`;return (await kr(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)}))?.ok??false}function ee(e,t,r,n){let s=`${e}/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 ${t}`},body:JSON.stringify(o)}).catch(()=>{});}function Ar(e,t,r,n){let s=[],a=[],o=null,i=0,l=null,d=0,c=null,p=0,f=e.filter(h=>h.name===core.ATTACHMENT_NAME&&h.body),u=false;if(f.length>0)for(let h of f)try{let m=JSON.parse(h.body.toString());if(core.isTestRelicFilePayload(m)){s=s.concat(m.navigations),a=a.concat(m.apiAssertions),m.networkRequestsFile&&(o=m.networkRequestsFile,i+=m.networkRequestsCount),m.consoleLogsFile&&(l=m.consoleLogsFile,d+=m.consoleLogsCount),m.apiCallsFile&&(c=m.apiCallsFile,p+=m.apiCallsCount),u=!0;continue}if(core.isTestRelicDataPayload(m)){s=s.concat(m.navigations),Array.isArray(m.apiAssertions)&&(a=a.concat(m.apiAssertions)),i+=m.networkRequests?.length??0,p+=m.apiCalls?.length??0;let y=m.consoleLogs;Array.isArray(y)&&(d+=y.length),u=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
2578
2578
  `);}return u||(s=t.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&&!u&&process.stderr.write(`[testrelic] Warning: No data found for test "${r}". Make sure your tests import { test, expect } from '@testrelic/playwright-analytics/fixture' instead of '@playwright/test'. Without the TestRelic fixture, network logs, video sync, and timeline data cannot be captured.
2579
- `),{navigations:s,apiAssertions:a,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:l,consoleLogsCount:d,apiCallsFile:c,apiCallsCount:p}}var Qs=5,mt=[1e3,3e3,9e3],H=3,Xs={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip"},re=0,ne=[];async function ta(){re>=Qs&&await new Promise(e=>ne.push(e)),re++;}function ea(){re--,ne.length>0&&ne.shift()();}async function vt(e){return new Promise(t=>setTimeout(t,e))}function ra(e){let t=e.substring(e.lastIndexOf(".")).toLowerCase();return Xs[t]??"application/octet-stream"}function na(e){try{return fs$1.statSync(e).size}catch{return 0}}async function sa(e,t,r,n,s){let a=`${e}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:path.basename(r.filePath),contentType:s,type:r.type,sizeBytes:n});for(let i=0;i<H;i++)try{let l=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:o});if(l.ok)return await l.json();if(l.status>=500&&i<H-1){await vt(mt[i]);continue}return null}catch{if(i<H-1){await vt(mt[i]);continue}return null}return null}async function aa(e,t,r,n){for(let s=0;s<H;s++)try{let a=fs$1.createReadStream(t),o=stream.Readable.toWeb(a),i=await fetch(e,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(n)},body:o,duplex:"half"});if(i.ok)return !0;if(i.status>=500&&s<H-1){await vt(mt[s]);continue}return !1}catch{if(s<H-1){await vt(mt[s]);continue}return false}return false}async function ia(e,t,r){let n=`${e}/artifacts/confirm`;try{return (await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({artifactId:r})})).ok}catch{return false}}async function oa(e,t,r,n){let s=na(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=ra(r.filePath);await ta();try{let o=await sa(e,t,r,s,a);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await aa(o.uploadUrl,r.filePath,a,s))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let l=await ia(e,t,o.artifactId);return {success:l,storageKey:o.storageKey,artifactId:o.artifactId,error:l?null:"confirm_failed"}}finally{ea();}}async function Ir(e,t,r,n){let s=new Map,a=r.map(async o=>{let i=await oa(e,t,o,n);s.set(o.filePath,i);});return await Promise.allSettled(a),s}function se(e){let r=e.getGitMetadata()?.remoteUrl;return r?Q(r):e.getConfig()?.projectName??X(process.cwd())}async function Mr(e,t,r,n){if(!e.isCloudMode()||t!=="realtime"&&t!=="both"||!await e.ensureValidToken())return null;let a=e.getGitMetadata(),o=D();return (await Sr(e.getEndpoint(),e.getAccessToken(),{runId:r,repoGitId:se(e),branch:a?.branch??o?.branch??null,commit:a?.commitSha??o?.commitSha??null,startedAt:n,totalTests:null,ciProvider:o?.provider??null,ciRunUrl:o?.runUrl??null}))?.runId??null}async function la(e,t,r,n){let s=new Map;if(!t.uploadArtifacts||!await e.ensureValidToken())return s;let o=[],i=new Map;for(let p of n){if(p.artifacts.screenshot){let f=path.join(p.outputDir,p.artifacts.screenshot);o.push({filePath:f,runId:r,testId:p.testId,type:"screenshot"}),i.set(f,{testId:p.testId,field:"screenshot"});}if(p.artifacts.video){let f=path.join(p.outputDir,p.artifacts.video);o.push({filePath:f,runId:r,testId:p.testId,type:"video"}),i.set(f,{testId:p.testId,field:"video"});}}if(o.length===0)return s;let l=await Ir(e.getEndpoint(),e.getAccessToken(),o,t.artifactMaxSizeMb),d=new Map;for(let[p,f]of l){if(!f.success||!f.storageKey)continue;let u=i.get(p);if(!u)continue;let g=d.get(u.testId)??{};u.field==="screenshot"&&(g.screenshotKey=f.storageKey),u.field==="video"&&(g.videoKey=f.storageKey),d.set(u.testId,g);}for(let p of n){let f=d.get(p.testId);s.set(p.testId,{...p.artifacts,...f?.screenshotKey?{screenshotKey:f.screenshotKey}:{},...f?.videoKey?{videoKey:f.videoKey}:{}});}let c=Array.from(l.values()).filter(p=>p.success).length;return c>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${c} artifact(s) to cloud storage.
2580
- `),s}async function ae(e,t,r,n,s,a,o,i,l,d){try{if(e.isCloudMode()&&s&&(r==="realtime"||r==="both")){let p=await e.ensureValidToken(),f={finishedAt:o,duration:i,summary:l};if(p){if(!await Ar(e.getEndpoint(),e.getAccessToken(),s,f)){let g=t?.queueDirectory??".testrelic/queue";tt(g,n,"finalize","finalize_failed_after_retries",`${e.getEndpoint()}/runs/${s}/finalize`,"POST",f,{"Content-Type":"application/json"});}}else {let u=t?.queueDirectory??".testrelic/queue";tt(u,n,"finalize",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs/${s}/finalize`,"POST",f,{"Content-Type":"application/json"});}}let c=new Map;if(e.isCloudMode()&&t&&d&&d.length>0&&(c=await la(e,t,n,d)),e.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await e.ensureValidToken()){let f=e.getGitMetadata(),u=D(),g=se(e),h=da(a,c),m=te(h,g,f,u),y=await Tr(e.getEndpoint(),e.getAccessToken(),m,async()=>await e.ensureValidToken()?e.getAccessToken():null);if(!y.success){let k=y,w=t?.queueDirectory??".testrelic/queue";tt(w,n,"batch",k.reason,k.targetEndpoint,k.method,k.payload,{"Content-Type":"application/json"});}}else {let f=t?.queueDirectory??".testrelic/queue",u=e.getGitMetadata(),g=D(),h=se(e),m=te(a,h,u,g,tests);tt(f,n,"batch",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs`,"POST",m,{"Content-Type":"application/json"});}await e.dispose();}catch{try{await e.dispose();}catch{}}}function da(e,t){if(t.size===0)return e;let r=e.timeline.map(n=>{let s=n.testId;if(!s)return n;let a=t.get(s);return a?{...n,...a.screenshotKey?{screenshotKey:a.screenshotKey}:{},...a.videoKey?{videoKey:a.videoKey}:{}}:n});return {...e,timeline:r}}function et(e){try{return fs$1.readFileSync(e,"utf-8").split(`
2581
- `).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function oe(e){switch(e){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function ha(e,t,r){let n=`${e}::${t}::${r}`;return crypto.createHash("sha256").update(n).digest("hex").substring(0,16)}function ma(e){return e.length<=4?"":e[e.length-2]}function va(e){let t=e.findIndex(r=>r.status==="passed");return t>0?`passed on retry ${t}`:null}function ya(e,t){let r=["e2e","api","unit"];for(let s of r)if(e.some(a=>a===`@${s}`||a===s))return s;let n=t.replace(/\\/g,"/");for(let s of r)if(n.includes(`/${s}/`))return s;return "unknown"}var ba="__testrelic_api_config";function wa(e){return JSON.stringify(e,(t,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var yt=class{constructor(t){this.rootDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.testCount=0;this.cloudClient=null;this.cloudRunId=null;this.runTimestamp="";this.pendingArtifactEntries=[];this.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=xe(t),this.apiConfig=we(t);}async onBegin(t,r){try{if(this.rootDir=t.rootDir,this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??crypto.randomUUID(),this.config.reportMode==="auto"){let s=r.allTests().length;this.activeReportMode=s>=this.config.streamingThreshold?"streaming":"embedded";}else this.activeReportMode=this.config.reportMode;let n=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${n} tests)
2582
- `),this.activeReportMode==="streaming"){let s=path.dirname(this.config.outputPath);this.streamingWriter=new G(s);let a=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let o={testRunId:this.testRunId??"",startedAt:this.startedAt,completedAt:new Date().toISOString(),totalDuration:Date.now()-new Date(this.startedAt).getTime(),...this.summaryCounters,metadata:null,reportMode:"streaming",files:[],enrichedSummary:null,validation:null,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(o);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let o=this.cloudClient.getAccessToken();o&&ee(this.cloudClient.getEndpoint(),o,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",a),process.on("SIGINT",a);}if(this.config.includeArtifacts){let s=path.dirname(this.config.outputPath);this.runTimestamp=Qe(path.join(s,"artifacts"));try{nr(path.join(s,"artifacts"));}catch{}}try{this.cloudClient=new pt(this.config.cloud),await this.cloudClient.initialize(),this.cloudRunId=await Mr(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt);}catch{this.cloudClient?.switchToLocalMode("init_error");}if(this.activeReportMode!=="streaming"){let s=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let a=this.cloudClient.getAccessToken();a&&ee(this.cloudClient.getEndpoint(),a,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",s),process.on("SIGINT",s);}}catch{}}onTestBegin(t,r){try{t.annotations.push({type:ba,description:wa(this.apiConfig)});}catch{}}onTestEnd(t,r){try{let n=r,s=t.outcome(),a;s==="flaky"?a="flaky":s==="skipped"?a="skipped":a=oe(n.status);let o=n.startTime.toISOString(),i=new Date(n.startTime.getTime()+n.duration).toISOString(),l=t.tags?[...t.tags]:t.annotations.filter(S=>S.type==="tag").map(S=>S.description??""),d=_r(n.attachments,t.annotations,t.title,a==="skipped");(d.navigations.length>0||d.networkRequestsCount>0||d.apiCallsCount>0)&&(this.fixtureDataReceived=!0);let c=null;if(a==="failed"||a==="flaky"){let R=(a==="flaky"?t.results.find(F=>F.status!=="passed")?.errors??[]:n.errors)[0];if(R){let F=Ce(this.config.redactPatterns),j=R.location?.line??null,V=null;this.config.includeCodeSnippets&&j!==null&&R.location?.file&&(V=ke(R.location.file,j,this.config.codeContextLines),V&&(V=F(V))),c={message:F(R.message??"Unknown error"),line:j,code:V,stack:this.config.includeStackTrace&&R.stack?F(R.stack):null};}}let p=t.titlePath().filter(Boolean),f=path.relative(this.rootDir||".",t.location.file),u=ma(p),g=p.join(" > "),h=f,m=ha(h,u,g),y=ya(l,h),k=s==="flaky",w=va(t.results),b=oe(t.expectedStatus),T=oe(n.status),v=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments){let S=path.dirname(this.config.outputPath),R=p[p.length-1]??t.title;v=Xe(n.attachments,R,n.retry,S,this.runTimestamp||void 0);}let C=this.config.includeActionSteps&&n.steps?lr(n.steps,n.startTime):null,A={titlePath:p,title:g,status:a,duration:n.duration,startedAt:o,completedAt:i,retryCount:t.results.length-1,retry:n.retry,tags:l,failure:c,specFile:f,navigations:d.navigations,testId:m,filePath:h,suiteName:u,testType:y,isFlaky:k,retryStatus:w,expectedStatus:b,actualStatus:T,artifacts:v,apiAssertions:d.apiAssertions,actions:C,networkRequestsFile:d.networkRequestsFile,networkRequestsCount:d.networkRequestsCount,consoleLogsFile:d.consoleLogsFile,consoleLogsCount:d.consoleLogsCount,apiCallsFile:d.apiCallsFile,apiCallsCount:d.apiCallsCount};try{let S=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(S==="realtime"||S==="both")){let R=this.cloudClient.getAccessToken();R&&Rr(this.cloudClient.getEndpoint(),R,this.cloudRunId,this.buildCloudTestPayload(A));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let S=kt(h,p,t.id??"",n.retry),R=n.retry===t.results.length-1,F={id:S,navigations:d.navigations,apiAssertions:d.apiAssertions,actions:C??[],artifacts:v,failureDiagnostic:c,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(S,F,{networkRequestsFile:d.networkRequestsFile,consoleLogsFile:d.consoleLogsFile,apiCallsFile:d.apiCallsFile});let j={id:S,title:p[p.length-1]??t.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:v!==null,hasActionSteps:(C?.length??0)>0,errorMessage:c?.message?.split(`
2579
+ `),{navigations:s,apiAssertions:a,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:l,consoleLogsCount:d,apiCallsFile:c,apiCallsCount:p}}var Zs=5,ht=[1e3,3e3,9e3],H=3,Qs={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip"},re=0,ne=[];async function Xs(){re>=Zs&&await new Promise(e=>ne.push(e)),re++;}function ta(){re--,ne.length>0&&ne.shift()();}async function mt(e){return new Promise(t=>setTimeout(t,e))}function ea(e){let t=e.substring(e.lastIndexOf(".")).toLowerCase();return Qs[t]??"application/octet-stream"}function ra(e){try{return fs$1.statSync(e).size}catch{return 0}}async function na(e,t,r,n,s){let a=`${e}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:path.basename(r.filePath),contentType:s,type:r.type,sizeBytes:n});for(let i=0;i<H;i++)try{let l=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:o});if(l.ok)return await l.json();if(l.status>=500&&i<H-1){await mt(ht[i]);continue}return null}catch{if(i<H-1){await mt(ht[i]);continue}return null}return null}async function sa(e,t,r,n){for(let s=0;s<H;s++)try{let a=fs$1.createReadStream(t),o=stream.Readable.toWeb(a),i=await fetch(e,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(n)},body:o,duplex:"half"});if(i.ok)return !0;if(i.status>=500&&s<H-1){await mt(ht[s]);continue}return !1}catch{if(s<H-1){await mt(ht[s]);continue}return false}return false}async function aa(e,t,r){let n=`${e}/artifacts/confirm`;try{return (await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({artifactId:r})})).ok}catch{return false}}async function ia(e,t,r,n){let s=ra(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=ea(r.filePath);await Xs();try{let o=await na(e,t,r,s,a);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await sa(o.uploadUrl,r.filePath,a,s))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let l=await aa(e,t,o.artifactId);return {success:l,storageKey:o.storageKey,artifactId:o.artifactId,error:l?null:"confirm_failed"}}finally{ta();}}async function _r(e,t,r,n){let s=new Map,a=r.map(async o=>{let i=await ia(e,t,o,n);s.set(o.filePath,i);});return await Promise.allSettled(a),s}function se(e){let r=e.getGitMetadata()?.remoteUrl;return r?Q(r):e.getConfig()?.projectName??X(process.cwd())}async function Lr(e,t,r,n){if(!e.isCloudMode()||t!=="realtime"&&t!=="both"||!await e.ensureValidToken())return null;let a=e.getGitMetadata(),o=D();return (await Tr(e.getEndpoint(),e.getAccessToken(),{runId:r,repoGitId:se(e),branch:a?.branch??null,commit:a?.commitSha??null,commitMessage:a?.commitMessage??null,startedAt:n,totalTests:null,ciProvider:o?.provider??null,ciRunUrl:o?.runUrl??null}))?.runId??null}async function oa(e,t,r,n){let s=new Map;if(!t.uploadArtifacts||!await e.ensureValidToken())return s;let o=[],i=new Map;for(let p of n){if(p.artifacts.screenshot){let f=path.join(p.outputDir,p.artifacts.screenshot);o.push({filePath:f,runId:r,testId:p.testId,type:"screenshot"}),i.set(f,{testId:p.testId,field:"screenshot"});}if(p.artifacts.video){let f=path.join(p.outputDir,p.artifacts.video);o.push({filePath:f,runId:r,testId:p.testId,type:"video"}),i.set(f,{testId:p.testId,field:"video"});}}if(o.length===0)return s;let l=await _r(e.getEndpoint(),e.getAccessToken(),o,t.artifactMaxSizeMb),d=new Map;for(let[p,f]of l){if(!f.success||!f.storageKey)continue;let u=i.get(p);if(!u)continue;let g=d.get(u.testId)??{};u.field==="screenshot"&&(g.screenshotKey=f.storageKey),u.field==="video"&&(g.videoKey=f.storageKey),d.set(u.testId,g);}for(let p of n){let f=d.get(p.testId);s.set(p.testId,{...p.artifacts,...f?.screenshotKey?{screenshotKey:f.screenshotKey}:{},...f?.videoKey?{videoKey:f.videoKey}:{}});}let c=Array.from(l.values()).filter(p=>p.success).length;return c>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${c} artifact(s) to cloud storage.
2580
+ `),s}async function ae(e,t,r,n,s,a,o,i,l,d){try{if(e.isCloudMode()&&s&&(r==="realtime"||r==="both")){let p=await e.ensureValidToken(),f=e.getGitMetadata(),u={finishedAt:o,duration:i,summary:l,...f?.commitMessage?{commitMessage:f.commitMessage}:{}};if(p){if(!await Rr(e.getEndpoint(),e.getAccessToken(),s,u)){let h=t?.queueDirectory??".testrelic/queue";tt(h,n,"finalize","finalize_failed_after_retries",`${e.getEndpoint()}/runs/${s}/finalize`,"POST",u,{"Content-Type":"application/json"});}}else {let g=t?.queueDirectory??".testrelic/queue";tt(g,n,"finalize",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs/${s}/finalize`,"POST",u,{"Content-Type":"application/json"});}}let c=new Map;if(e.isCloudMode()&&t&&d&&d.length>0&&(c=await oa(e,t,n,d)),e.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await e.ensureValidToken()){let f=e.getGitMetadata(),u=D(),g=se(e),h=la(a,c),m=te(h,g,f,u),y=await Cr(e.getEndpoint(),e.getAccessToken(),m,async()=>await e.ensureValidToken()?e.getAccessToken():null);if(!y.success){let k=y,w=t?.queueDirectory??".testrelic/queue";tt(w,n,"batch",k.reason,k.targetEndpoint,k.method,k.payload,{"Content-Type":"application/json"});}}else {let f=t?.queueDirectory??".testrelic/queue",u=e.getGitMetadata(),g=D(),h=se(e),m=te(a,h,u,g);tt(f,n,"batch",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs`,"POST",m,{"Content-Type":"application/json"});}await e.dispose();}catch{try{await e.dispose();}catch{}}}function la(e,t){if(t.size===0)return e;let r=e.timeline.map(n=>{let s=n.testId;if(!s)return n;let a=t.get(s);return a?{...n,...a.screenshotKey?{screenshotKey:a.screenshotKey}:{},...a.videoKey?{videoKey:a.videoKey}:{}}:n});return {...e,timeline:r}}function vt(e){try{return fs$1.readFileSync(e,"utf-8").split(`
2581
+ `).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function oe(e){switch(e){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function ga(e,t,r){let n=`${e}::${t}::${r}`;return crypto.createHash("sha256").update(n).digest("hex").substring(0,16)}function ha(e){return e.length<=4?"":e[e.length-2]}function ma(e){let t=e.findIndex(r=>r.status==="passed");return t>0?`passed on retry ${t}`:null}function va(e,t){let r=["e2e","api","unit"];for(let s of r)if(e.some(a=>a===`@${s}`||a===s))return s;let n=t.replace(/\\/g,"/");for(let s of r)if(n.includes(`/${s}/`))return s;return "unknown"}var ya="__testrelic_api_config";function ba(e){return JSON.stringify(e,(t,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var yt=class{constructor(t){this.rootDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.testCount=0;this.cloudClient=null;this.cloudRunId=null;this.runTimestamp="";this.pendingArtifactEntries=[];this.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=xe(t),this.apiConfig=we(t);}async onBegin(t,r){try{if(this.rootDir=t.rootDir,this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??crypto.randomUUID(),this.config.reportMode==="auto"){let s=r.allTests().length;this.activeReportMode=s>=this.config.streamingThreshold?"streaming":"embedded";}else this.activeReportMode=this.config.reportMode;let n=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${n} tests)
2582
+ `),this.activeReportMode==="streaming"){let s=path.dirname(this.config.outputPath);this.streamingWriter=new G(s);let a=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let o={testRunId:this.testRunId??"",startedAt:this.startedAt,completedAt:new Date().toISOString(),totalDuration:Date.now()-new Date(this.startedAt).getTime(),...this.summaryCounters,metadata:null,reportMode:"streaming",files:[],enrichedSummary:null,validation:null,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(o);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let o=this.cloudClient.getAccessToken();o&&ee(this.cloudClient.getEndpoint(),o,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",a),process.on("SIGINT",a);}if(this.config.includeArtifacts){let s=path.dirname(this.config.outputPath);this.runTimestamp=Qe(path.join(s,"artifacts"));try{nr(path.join(s,"artifacts"));}catch{}}try{this.cloudClient=new ut(this.config.cloud),await this.cloudClient.initialize(),this.cloudRunId=await Lr(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt);}catch{this.cloudClient?.switchToLocalMode("init_error");}if(this.activeReportMode!=="streaming"){let s=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let a=this.cloudClient.getAccessToken();a&&ee(this.cloudClient.getEndpoint(),a,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",s),process.on("SIGINT",s);}}catch{}}onTestBegin(t,r){try{t.annotations.push({type:ya,description:ba(this.apiConfig)});}catch{}}onTestEnd(t,r){try{let n=r,s=t.outcome(),a;s==="flaky"?a="flaky":s==="skipped"?a="skipped":a=oe(n.status);let o=n.startTime.toISOString(),i=new Date(n.startTime.getTime()+n.duration).toISOString(),l=t.tags?[...t.tags]:t.annotations.filter(S=>S.type==="tag").map(S=>S.description??""),d=Ar(n.attachments,t.annotations,t.title,a==="skipped");(d.navigations.length>0||d.networkRequestsCount>0||d.apiCallsCount>0)&&(this.fixtureDataReceived=!0);let c=null;if(a==="failed"||a==="flaky"){let R=(a==="flaky"?t.results.find(F=>F.status!=="passed")?.errors??[]:n.errors)[0];if(R){let F=Ce(this.config.redactPatterns),j=R.location?.line??null,V=null;this.config.includeCodeSnippets&&j!==null&&R.location?.file&&(V=ke(R.location.file,j,this.config.codeContextLines),V&&(V=F(V))),c={message:F(R.message??"Unknown error"),line:j,code:V,stack:this.config.includeStackTrace&&R.stack?F(R.stack):null};}}let p=t.titlePath().filter(Boolean),f=path.relative(this.rootDir||".",t.location.file),u=ha(p),g=p.join(" > "),h=f,m=ga(h,u,g),y=va(l,h),k=s==="flaky",w=ma(t.results),b=oe(t.expectedStatus),T=oe(n.status),v=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments){let S=path.dirname(this.config.outputPath),R=p[p.length-1]??t.title;v=Xe(n.attachments,R,n.retry,S,this.runTimestamp||void 0);}let C=this.config.includeActionSteps&&n.steps?lr(n.steps,n.startTime):null,A={titlePath:p,title:g,status:a,duration:n.duration,startedAt:o,completedAt:i,retryCount:t.results.length-1,retry:n.retry,tags:l,failure:c,specFile:f,navigations:d.navigations,testId:m,filePath:h,suiteName:u,testType:y,isFlaky:k,retryStatus:w,expectedStatus:b,actualStatus:T,artifacts:v,apiAssertions:d.apiAssertions,actions:C,networkRequestsFile:d.networkRequestsFile,networkRequestsCount:d.networkRequestsCount,consoleLogsFile:d.consoleLogsFile,consoleLogsCount:d.consoleLogsCount,apiCallsFile:d.apiCallsFile,apiCallsCount:d.apiCallsCount};try{let S=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(S==="realtime"||S==="both")){let R=this.cloudClient.getAccessToken();R&&Sr(this.cloudClient.getEndpoint(),R,this.cloudRunId,this.buildCloudTestPayload(A));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let S=kt(h,p,t.id??"",n.retry),R=n.retry===t.results.length-1,F={id:S,navigations:d.navigations,apiAssertions:d.apiAssertions,actions:C??[],artifacts:v,failureDiagnostic:c,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(S,F,{networkRequestsFile:d.networkRequestsFile,consoleLogsFile:d.consoleLogsFile,apiCallsFile:d.apiCallsFile});let j={id:S,title:p[p.length-1]??t.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:v!==null,hasActionSteps:(C?.length??0)>0,errorMessage:c?.message?.split(`
2583
2583
  `)[0]??null,networkCount:d.networkRequestsCount,consoleCount:d.consoleLogsCount,actionCount:C?.length??0,isRetry:!R};if(this.testIndex.push(j),R)switch(this.summaryCounters.total++,a){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.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+=C?.length??0,v&&this.pendingArtifactEntries.push({testId:m,artifacts:v,outputDir:path.dirname(this.config.outputPath)}),A.actions=null,A.apiAssertions=null,A.navigations=[],A.artifacts=null,A.failure=null,A.networkRequestsFile=null,A.consoleLogsFile=null,A.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(A),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(t){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(`
2584
2584
  \u26A0 TestRelic: No fixture data received from any test.
2585
2585
  To enable network logs, video sync, and timeline tracking, import the TestRelic fixture:
@@ -2587,15 +2587,15 @@ ${s}
2587
2587
  instead of:
2588
2588
  import { test, expect } from '@playwright/test';
2589
2589
 
2590
- `),await Ze();let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let l=path.dirname(this.config.outputPath);i=er(l,this.runTimestamp);let d=path.join(l,"artifact-manifest.json"),c=JSON.stringify(i),p=d+".tmp";fs$1.writeFileSync(p,c,"utf-8"),fs$1.renameSync(p,d);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await this.finalizeStreamingReport(r,a,t,i);else {let l=this.buildTimeline(),d=new Map;for(let u of this.collectedTests){let g=d.get(u.testId);(!g||u.retry>g.retry)&&d.set(u.testId,u);}let c=Array.from(d.values()),p=or(c,l.length),f={schemaVersion:rt,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:a,summary:p,ci:D(),metadata:this.config.metadata,timeline:l,shardRunIds:null};if(this.writeReport(f),await Ot(f,this.config,i),Vt(p,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient){let u=this.collectArtifactEntries();await ae(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,f,r,a,p,u);}}}catch{}}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let t=path.dirname(this.config.outputPath),r=[];for(let n of this.collectedTests)n.artifacts&&r.push({testId:n.testId,artifacts:n.artifacts,outputDir:t});return r}async finalizeStreamingReport(t,r,n,s){if(!this.streamingWriter)return;let{totalApiCalls:a,totalAssertions:o,totalNavigations:i,totalNetworkRequests:l,totalConsoleLogs:d,totalActionSteps:c}=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:c};let p=new Map,f=new Map;for(let b of this.testIndex){let T=`${b.filePath}::${b.titlePath.join(" > ")}`,v=p.get(T);(v===void 0||b.retryIndex>v)&&p.set(T,b.retryIndex);}let u=0;for(let b of this.testIndex){let T=`${b.filePath}::${b.titlePath.join(" > ")}`,v=p.get(T);if(b.isRetry=b.retryIndex<v,b.isRetry)continue;switch(u++,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 C=f.get(b.filePath);switch(C||(C={filePath:b.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},f.set(b.filePath,C)),C.total++,b.status){case "passed":C.passed++;break;case "failed":C.failed++;break;case "flaky":C.flaky++;break;case "skipped":C.skipped++;break;case "timedout":C.timedOut++;break}}let g=Array.from(f.values());this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let h={reporterTotal:this.summaryCounters.total,indexTotal:u,playwrightStatus:n.status,isValid:this.summaryCounters.total===u};h.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${h.reporterTotal}, index: ${h.indexTotal}
2590
+ `),await Ze();let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let l=path.dirname(this.config.outputPath);i=er(l,this.runTimestamp);let d=path.join(l,"artifact-manifest.json"),c=JSON.stringify(i),p=d+".tmp";fs$1.writeFileSync(p,c,"utf-8"),fs$1.renameSync(p,d);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await this.finalizeStreamingReport(r,a,t,i);else {let l=this.buildTimeline(),d=new Map;for(let u of this.collectedTests){let g=d.get(u.testId);(!g||u.retry>g.retry)&&d.set(u.testId,u);}let c=Array.from(d.values()),p=or(c,l.length),f={schemaVersion:et,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:a,summary:p,ci:D(),metadata:this.config.metadata,timeline:l,shardRunIds:null};if(this.writeReport(f),await Ot(f,this.config,i),Vt(p,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient){let u=this.collectArtifactEntries();await ae(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,f,r,a,p,u);}}}catch{}}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let t=path.dirname(this.config.outputPath),r=[];for(let n of this.collectedTests)n.artifacts&&r.push({testId:n.testId,artifacts:n.artifacts,outputDir:t});return r}async finalizeStreamingReport(t,r,n,s){if(!this.streamingWriter)return;let{totalApiCalls:a,totalAssertions:o,totalNavigations:i,totalNetworkRequests:l,totalConsoleLogs:d,totalActionSteps:c}=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:c};let p=new Map,f=new Map;for(let b of this.testIndex){let T=`${b.filePath}::${b.titlePath.join(" > ")}`,v=p.get(T);(v===void 0||b.retryIndex>v)&&p.set(T,b.retryIndex);}let u=0;for(let b of this.testIndex){let T=`${b.filePath}::${b.titlePath.join(" > ")}`,v=p.get(T);if(b.isRetry=b.retryIndex<v,b.isRetry)continue;switch(u++,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 C=f.get(b.filePath);switch(C||(C={filePath:b.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},f.set(b.filePath,C)),C.total++,b.status){case "passed":C.passed++;break;case "failed":C.failed++;break;case "flaky":C.flaky++;break;case "skipped":C.skipped++;break;case "timedout":C.timedOut++;break}}let g=Array.from(f.values());this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let h={reporterTotal:this.summaryCounters.total,indexTotal:u,playwrightStatus:n.status,isValid:this.summaryCounters.total===u};h.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${h.reporterTotal}, index: ${h.indexTotal}
2591
2591
  `);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:t,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:g,enrichedSummary:m,validation:h,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(y);let k={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(k),await Ot(this.buildStreamingReport(y,m,t,r),this.config,s),Vt(m,this.config.outputPath,this.config.htmlReportPath,this.config.quiet);let w=this.streamingWriter.getReportDir();if(process.stderr.write(`[testrelic] Streaming report written to ${w}
2592
2592
  [testrelic] ${this.testIndex.length} test detail files on disk
2593
2593
  [testrelic] View report: npx testrelic serve ${w}
2594
2594
  `),this.streamingWriter.getWriteErrors().length>0&&process.stderr.write(`[testrelic] WARNING: ${this.streamingWriter.getWriteErrors().length} write error(s) during streaming
2595
- `),this.streamingWriter.dispose(),this.cloudClient){let b=this.buildStreamingReport(y,m,t,r),T=this.collectArtifactEntries();await ae(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,b,t,r,m,T);}this.testIndex.length=0,this.collectedTests.length=0,this.pendingArtifactEntries.length=0,this.streamingWriter=null,this.cloudClient=null;}buildStreamingReport(t,r,n,s){return {schemaVersion:rt,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:n,totalDuration:s,summary:r,ci:D(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let t=process.memoryUsage(),r=t.heapUsed/1024/1024;if(r<200)return;let n=t.heapUsed/t.heapTotal;n>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
2595
+ `),this.streamingWriter.dispose(),this.cloudClient){let b=this.buildStreamingReport(y,m,t,r),T=this.collectArtifactEntries();await ae(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,b,t,r,m,T);}this.testIndex.length=0,this.collectedTests.length=0,this.pendingArtifactEntries.length=0,this.streamingWriter=null,this.cloudClient=null;}buildStreamingReport(t,r,n,s){return {schemaVersion:et,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:n,totalDuration:s,summary:r,ci:D(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let t=process.memoryUsage(),r=t.heapUsed/1024/1024;if(r<200)return;let n=t.heapUsed/t.heapTotal;n>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
2596
2596
  `),this.switchToStreamingMode()):n>.8&&process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
2597
2597
  `);}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let t=path.dirname(this.config.outputPath);this.streamingWriter=new G(t);for(let r of this.collectedTests){let n=kt(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(`
2598
- `)[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 t=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls:null,apiAssertions:r.apiAssertions,testId:r.testId,filePath:r.filePath,suiteName:r.suiteName,testType:r.testType,isFlaky:r.isFlaky,retryStatus:r.retryStatus,expectedStatus:r.expectedStatus,actualStatus:r.actualStatus,artifacts:r.artifacts,networkRequests:null,actions:r.actions,consoleLogs:null}));return ir(t,{navigationTypes:this.config.navigationTypes})}toTestResult(t,r){let n=null,s=null,a=null;return r?.loadFiles&&(n=t.networkRequestsFile?et(t.networkRequestsFile):null,s=t.consoleLogsFile?et(t.consoleLogsFile):null,a=t.apiCallsFile?et(t.apiCallsFile):null),{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:n,apiCalls:a,apiAssertions:t.apiAssertions,actions:t.actions??null,consoleLogs:s}}buildCloudTestPayload(t){let r={title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,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,apiAssertions:t.apiAssertions,actions:t.actions??[],navigations:t.navigations??[],steps:t.actions??[]};return t.consoleLogsFile&&(r.consoleLogs=et(t.consoleLogsFile)),t.networkRequestsFile&&(r.networkRequests=et(t.networkRequestsFile)),r}writeReport(t){try{let r=JSON.stringify(t),n=this.config.outputPath,s=path.dirname(n);fs$1.mkdirSync(s,{recursive:!0});let a=n+".tmp";fs$1.writeFileSync(a,r,"utf-8"),fs$1.renameSync(a,n);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
2599
- `);}}};var Sa=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Ra(e){let t=e.toLowerCase();return Sa.some(r=>t.includes(r))}var bt=class e{constructor(t,r){this.page=t;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=t.goto.bind(t),this.origGoBack=t.goBack.bind(t),this.origGoForward=t.goForward.bind(t),this.origReload=t.reload.bind(t);try{this.includeNetworkStats&&(this.networkWriter=new M("network")),this.consoleWriter=new M("console");}catch{}this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async finalizeCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[,t]of this.pendingRequests)this.networkWriter&&(this.networkWriter.append({url:t.url,method:t.method,resourceType:t.resourceType,statusCode:0,responseTimeMs:Date.now()-t.startTimeMs,startedAt:t.startedAt,requestHeaders:t.headers,requestBody:t.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:t.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.networkRequestCount++);this.pendingRequests.clear(),this.networkWriter?.close(),this.consoleWriter?.close();}static mapConsoleType(t){switch(t){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 t=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:t,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(t){}dispose(){this.page.goto=this.origGoto,this.page.goBack=this.origGoBack,this.page.goForward=this.origGoForward,this.page.reload=this.origReload;for(let{event:t,handler:r}of this.listeners)this.page.off(t,r);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}getRecords(){return this.records}interceptMethods(){let t=this,r=this.page;r.goto=async function(n,s){return t.recordNavigation(n,"goto"),t.origGoto(n,s)},r.goBack=async function(n){let s=await t.origGoBack(n);return t.recordNavigation(r.url(),"back"),s},r.goForward=async function(n){let s=await t.origGoForward(n);return t.recordNavigation(r.url(),"forward"),s},r.reload=async function(n){return t.recordNavigation(r.url(),"refresh"),t.origReload(n)};}attachListeners(){let t=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",t),this.listeners.push({event:"domcontentloaded",handler:t});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 c=a.location();c&&c.url&&(l=`${c.url}:${c.lineNumber}:${c.columnNumber}`);}catch{}let d=e.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++),c=l.postData()??null,p={url:l.url(),method:l.method(),resourceType:this.mapResourceType(l.resourceType()),headers:l.headers(),postData:c,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 k=l.headers()["content-length"];k&&(this.currentNetworkCounter.totalBytes+=parseInt(k,10)||0);let w=l.request().resourceType(),b=this.mapResourceType(w);this.currentNetworkCounter.byType[b]++;}let d=l.request().__testrelic_id;if(!d)return;let c=this.pendingRequests.get(d);if(!c)return;this.pendingRequests.delete(d);let p=Date.now()-c.startTimeMs,f=l.headers(),u=f["content-type"]??null,g=parseInt(f["content-length"]??"0",10)||0,h=u?!Ra(u):!1,m=(async()=>{let y=null;if(!h)try{y=(await l.body()).toString("utf-8");}catch{}let k={url:c.url,method:c.method,resourceType:c.resourceType,statusCode:l.status(),responseTimeMs:p,startedAt:c.startedAt,requestHeaders:c.headers,requestBody:c.postData,responseBody:y,responseHeaders:f,contentType:u,responseSize:g,requestBodyTruncated:c.postDataTruncated,responseBodyTruncated:!1,isBinary:h,error:null};this.networkWriter&&(this.networkWriter.append(k),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 c=this.pendingRequests.get(d);if(!c)return;this.pendingRequests.delete(d);let p={url:c.url,method:c.method,resourceType:c.resourceType,statusCode:0,responseTimeMs:Date.now()-c.startTimeMs,startedAt:c.startedAt,requestHeaders:c.headers,requestBody:c.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:c.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 t=history.pushState.bind(history),r=history.replaceState.bind(history);history.pushState=function(...n){t(...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(t,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:t,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(t){switch(t){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 Pr=Symbol.for("__testrelic_call_id"),Aa="__testrelic_api_assertions",z=new WeakMap,U=class{constructor(){this.assertions=[];this.currentCallId=null;}recordAssertion(t){this.assertions.push(t);}getAssertions(){return this.assertions}setCurrentCallId(t){this.currentCallId=t;}getCurrentCallId(){return this.currentCallId}getData(){return [...this.assertions]}flushLegacyAnnotations(t){this.assertions.length!==0&&t.annotations.push({type:Aa,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}};var Fr="[REDACTED]";function de(e,t){if(e===null||t.length===0)return e;let r=new Set(t.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(e))Object.hasOwn(e,s)&&(n[s]=r.has(s.toLowerCase())?Fr:e[s]);return n}function wt(e,t){if(e===null||t.length===0)return e;let r;try{r=JSON.parse(e);}catch{return e}if(typeof r!="object"||r===null)return e;let n=new Set(t),s=le(r,n);return JSON.stringify(s)}function le(e,t){if(Array.isArray(e))return e.map(r=>le(r,t));if(typeof e=="object"&&e!==null){let r={};for(let n of Object.keys(e)){if(!Object.hasOwn(e,n))continue;let s=e[n];t.has(n)?r[n]=Fr:r[n]=le(s,t);}return r}return e}function Br(e,t,r){if(r.length>0){for(let n of r)if(Dr(e,n))return false}if(t.length>0){for(let n of t)if(Dr(e,n))return true;return false}return true}function Dr(e,t){try{return t instanceof RegExp?t.test(e):_a(t).test(e)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(t)}`),false}}function _a(e){let t="",r=0;for(;r<e.length;){let n=e[r];n==="*"&&e[r+1]==="*"?(t+=".*",r+=2,e[r]==="/"&&r++):n==="*"?(t+="[^/]*",r++):n==="?"?(t+="[^/]",r++):".+^${}()|[]\\".includes(n)?(t+="\\"+n,r++):(t+=n,r++);}return new RegExp(t)}var Ia=["get","post","put","patch","delete","head","fetch"],La=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Ma(e){let t=e.toLowerCase();return La.some(r=>t.includes(r))}function Na(e){if(!e)return null;if(e.data!==void 0&&e.data!==null){let t=e.data;return typeof t=="string"?t:Buffer.isBuffer(t)?t.toString("base64"):JSON.stringify(t)}if(e.form!==void 0&&e.form!==null)return JSON.stringify(e.form);if(e.multipart!==void 0&&e.multipart!==null){let t=e.multipart,r={};for(let[n,s]of Object.entries(t))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 xt=class xt{constructor(t,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=t,this.assertionTracker=r??null,this.apiConfig=n??xt.DEFAULT_API_CONFIG;try{this.apiCallWriter=new M("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(t){return t!=null&&typeof t=="object"?z.get(t)??null:this.primitiveCallIds.get(t)??null}intercept(){for(let r of Ia){let n=this.context[r].bind(this.context);this.originals.set(r,n),this.context[r]=this.createWrapper(r,n);}let t=this.context.dispose.bind(this.context);this.originals.set("dispose",t),this.context.dispose=async r=>(this.disposed=true,t(r));}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0}}flushLegacyAnnotations(t){}dispose(){for(let[t,r]of this.originals)this.context[t]=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(t,r){let n=this,s=t.headers.bind(t);t.headers=function(){let u=s();return z.set(u,r),u};let a=t.headersArray.bind(t);t.headersArray=function(){let u=a();return z.set(u,r),u};let o=t.json.bind(t);t.json=async function(){let u=await o();return u!=null&&typeof u=="object"&&z.set(u,r),u};let i=t.status.bind(t);t.status=function(){let u=i();return n.primitiveCallIds.set(u,r),u};let l=t.statusText.bind(t);t.statusText=function(){let u=l();return n.primitiveCallIds.set(u,r),u};let d=t.ok.bind(t);t.ok=function(){let u=d();return n.primitiveCallIds.set(u,r),u};let c=t.text.bind(t);t.text=async function(){let u=await c();return n.primitiveCallIds.set(u,r),u};let p=t.body.bind(t);t.body=async function(){let u=await p();return z.set(u,r),u};}createWrapper(t,r){let n=this;return async function(a,o){if(!Br(a,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return r(a,o);let i=`api-call-${n.callCounter++}`,l=new Date().toISOString(),d=t==="fetch"?(o?.method??"GET").toUpperCase():t.toUpperCase(),c=Na(o),p=perf_hooks.performance.now();n._lastCallId=i,n.assertionTracker&&n.assertionTracker.setCurrentCallId(i);let f;try{f=await r(a,o);}catch(u){let g=perf_hooks.performance.now();try{let h=n.apiConfig.captureRequestBody?wt(c,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((g-p)*100)/100,isBinary:!1,error:u instanceof Error?u.message:String(u)};n.apiCallWriter&&(n.apiCallWriter.append(m),n.apiCallCount++);}catch{}throw u}try{let u=perf_hooks.performance.now(),g=f.headers(),h=g["content-type"]??null,m=h?!Ma(h):!1,y=null;n.apiConfig.captureRequestHeaders&&o?.headers&&(y=o.headers);let k=null;n.apiConfig.captureResponseHeaders&&(k=g);let w=n.apiConfig.captureRequestBody?c:null,b=null;if(n.apiConfig.captureResponseBody)try{m?b=(await f.body()).toString("base64"):b=await f.text();}catch{}y=de(y,n.apiConfig.redactHeaders),k=de(k,n.apiConfig.redactHeaders),w=wt(w,n.apiConfig.redactBodyFields),b=wt(b,n.apiConfig.redactBodyFields);let T={id:i,timestamp:l,method:d,url:f.url(),requestHeaders:y,requestBody:w,responseStatusCode:f.status(),responseStatusText:f.statusText(),responseHeaders:k,responseBody:b,responseTimeMs:Math.round((u-p)*100)/100,isBinary:m,error:null};n.apiCallWriter&&(n.apiCallWriter.append(T),n.apiCallCount++);}catch{}try{f[Pr]=i,n.tagResponseMethods(f,i);}catch{}return f}}};xt.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 $=xt;var Pa="__testrelic_api_config",Fa="__testrelic_config_trackApiCalls";function ue(e){let t=e.annotations.find(n=>n.type===Pa&&n.description!==void 0);if(t)try{return JSON.parse(t.description,Da)}catch{}let r=e.annotations.find(n=>n.type===Fa&&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 Da(e,t){if(typeof t=="object"&&t!==null&&t.__regexp===true&&typeof t.source=="string"){let{source:r,flags:n}=t;return new RegExp(r,n)}return t}var Ur={page:async({page:e},t,r)=>{let n=new bt(e);try{await n.init();}catch{}await t(e);try{let{navigations:s,networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:l}=await n.getFileData(),d={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:l,apiCallsFile:null,apiCallsCount:0};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:e},t,r)=>{let n=ue(r);if(!n.trackApiCalls){await t(e);return}let s=new U,a=new $(e,s,n);a.intercept(),await t(e);try{let{apiCallsFile:o,apiCallsCount:i}=a.getFileData(),l=n.captureAssertions?s.getData():[],d={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:l,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:o,apiCallsCount:i};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};test.test.extend(Ur);var Ha={request:async({request:e},t,r)=>{let n=ue(r);if(!n.trackApiCalls){await t(e);return}let s=new U,a=new $(e,s,n);a.intercept();let o=null;try{o=new M("api-console");}catch{}let i=0,l=process.stdout.write,d=process.stderr.write;process.stdout.write=function(c,...p){try{let f=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!f.startsWith("[testrelic]")&&!f.startsWith("\u2139 TestRelic")&&!f.startsWith("\u2713 TestRelic")&&!f.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stdout",text:f.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return l.apply(process.stdout,[c,...p])},process.stderr.write=function(c,...p){try{let f=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!f.startsWith("[testrelic]")&&!f.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stderr",text:f.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return d.apply(process.stderr,[c,...p])};try{await t(e);}finally{process.stdout.write=l,process.stderr.write=d;}try{o?.close();let{apiCallsFile:c,apiCallsCount:p}=a.getFileData(),f=n.captureAssertions?s.getData():[],u={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:f,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:i>0?o?.getPath()??null:null,consoleLogsCount:i,apiCallsFile:c,apiCallsCount:p};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(u)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};var zr="@testrelic/playwright-analytics";function za(e){return Array.isArray(e)?e.some(t=>Array.isArray(t)&&typeof t[0]=="string"&&t[0]===zr):false}function $a(e,t){let n={video:"on",screenshot:"on",trace:"on",...e.use??{}},s;Array.isArray(e.reporter)?s=e.reporter:typeof e.reporter=="string"?s=[[e.reporter]]:s=[["list"]];let a=za(s)?s:[...s,[zr,t??{}]];return test.defineConfig({...e,use:n,reporter:a})}var $r=false;function Kl(e,t,r="manual_record"){if(!e||!e.annotations){$r||($r=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
2600
- `));return}let n={url:t,navigationType:r,timestamp:new Date().toISOString()};e.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}Object.defineProperty(exports,"ATTACHMENT_CONTENT_TYPE",{enumerable:true,get:function(){return core.ATTACHMENT_CONTENT_TYPE}});Object.defineProperty(exports,"ATTACHMENT_NAME",{enumerable:true,get:function(){return core.ATTACHMENT_NAME}});Object.defineProperty(exports,"PAYLOAD_VERSION",{enumerable:true,get:function(){return core.PAYLOAD_VERSION}});Object.defineProperty(exports,"isTestRelicDataPayload",{enumerable:true,get:function(){return core.isTestRelicDataPayload}});exports.SCHEMA_VERSION=rt;exports.default=yt;exports.defineConfig=$a;exports.recordNavigation=Kl;exports.testRelicApiFixture=Ha;exports.testRelicFixture=Ur;//# sourceMappingURL=index.cjs.map
2598
+ `)[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 t=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls:null,apiAssertions:r.apiAssertions,testId:r.testId,filePath:r.filePath,suiteName:r.suiteName,testType:r.testType,isFlaky:r.isFlaky,retryStatus:r.retryStatus,expectedStatus:r.expectedStatus,actualStatus:r.actualStatus,artifacts:r.artifacts,networkRequests:null,actions:r.actions,consoleLogs:null}));return ir(t,{navigationTypes:this.config.navigationTypes})}readJsonlFile(t){if(!t)return null;let r=vt(t);return r.length>0?r:null}toTestResult(t,r){let n=null,s=null,a=null;return r?.loadFiles&&(n=this.readJsonlFile(t.networkRequestsFile),s=this.readJsonlFile(t.consoleLogsFile),a=this.readJsonlFile(t.apiCallsFile)),{title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retryCount:t.retryCount,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,retryStatus:t.retryStatus,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,networkRequests:n,apiCalls:a,apiAssertions:t.apiAssertions,actions:t.actions??null,consoleLogs:s}}buildCloudTestPayload(t){let r={title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,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,apiAssertions:t.apiAssertions,actions:t.actions??[],navigations:t.navigations??[],steps:t.actions??[]};if(t.consoleLogsFile&&(r.consoleLogs=vt(t.consoleLogsFile)),t.networkRequestsFile&&(r.networkRequests=vt(t.networkRequestsFile)),t.apiCallsFile){let n=vt(t.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(t){try{let r=JSON.stringify(t),n=this.config.outputPath,s=path.dirname(n);fs$1.mkdirSync(s,{recursive:!0});let a=n+".tmp";fs$1.writeFileSync(a,r,"utf-8"),fs$1.renameSync(a,n);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
2599
+ `);}}};var Ta=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Sa(e){let t=e.toLowerCase();return Ta.some(r=>t.includes(r))}var bt=class e{constructor(t,r){this.page=t;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=t.goto.bind(t),this.origGoBack=t.goBack.bind(t),this.origGoForward=t.goForward.bind(t),this.origReload=t.reload.bind(t);try{this.includeNetworkStats&&(this.networkWriter=new M("network")),this.consoleWriter=new M("console");}catch{}this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async finalizeCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[,t]of this.pendingRequests)this.networkWriter&&(this.networkWriter.append({url:t.url,method:t.method,resourceType:t.resourceType,statusCode:0,responseTimeMs:Date.now()-t.startTimeMs,startedAt:t.startedAt,requestHeaders:t.headers,requestBody:t.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:t.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.networkRequestCount++);this.pendingRequests.clear(),this.networkWriter?.close(),this.consoleWriter?.close();}static mapConsoleType(t){switch(t){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 t=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:t,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(t){}dispose(){this.page.goto=this.origGoto,this.page.goBack=this.origGoBack,this.page.goForward=this.origGoForward,this.page.reload=this.origReload;for(let{event:t,handler:r}of this.listeners)this.page.off(t,r);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}getRecords(){return this.records}interceptMethods(){let t=this,r=this.page;r.goto=async function(n,s){return t.recordNavigation(n,"goto"),t.origGoto(n,s)},r.goBack=async function(n){let s=await t.origGoBack(n);return t.recordNavigation(r.url(),"back"),s},r.goForward=async function(n){let s=await t.origGoForward(n);return t.recordNavigation(r.url(),"forward"),s},r.reload=async function(n){return t.recordNavigation(r.url(),"refresh"),t.origReload(n)};}attachListeners(){let t=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",t),this.listeners.push({event:"domcontentloaded",handler:t});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 c=a.location();c&&c.url&&(l=`${c.url}:${c.lineNumber}:${c.columnNumber}`);}catch{}let d=e.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++),c=l.postData()??null,p={url:l.url(),method:l.method(),resourceType:this.mapResourceType(l.resourceType()),headers:l.headers(),postData:c,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 k=l.headers()["content-length"];k&&(this.currentNetworkCounter.totalBytes+=parseInt(k,10)||0);let w=l.request().resourceType(),b=this.mapResourceType(w);this.currentNetworkCounter.byType[b]++;}let d=l.request().__testrelic_id;if(!d)return;let c=this.pendingRequests.get(d);if(!c)return;this.pendingRequests.delete(d);let p=Date.now()-c.startTimeMs,f=l.headers(),u=f["content-type"]??null,g=parseInt(f["content-length"]??"0",10)||0,h=u?!Sa(u):!1,m=(async()=>{let y=null;if(!h)try{y=(await l.body()).toString("utf-8");}catch{}let k={url:c.url,method:c.method,resourceType:c.resourceType,statusCode:l.status(),responseTimeMs:p,startedAt:c.startedAt,requestHeaders:c.headers,requestBody:c.postData,responseBody:y,responseHeaders:f,contentType:u,responseSize:g,requestBodyTruncated:c.postDataTruncated,responseBodyTruncated:!1,isBinary:h,error:null};this.networkWriter&&(this.networkWriter.append(k),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 c=this.pendingRequests.get(d);if(!c)return;this.pendingRequests.delete(d);let p={url:c.url,method:c.method,resourceType:c.resourceType,statusCode:0,responseTimeMs:Date.now()-c.startTimeMs,startedAt:c.startedAt,requestHeaders:c.headers,requestBody:c.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:c.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 t=history.pushState.bind(history),r=history.replaceState.bind(history);history.pushState=function(...n){t(...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(t,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:t,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(t){switch(t){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 Er=Symbol.for("__testrelic_call_id"),Ra="__testrelic_api_assertions",z=new WeakMap,U=class{constructor(){this.assertions=[];this.currentCallId=null;}recordAssertion(t){this.assertions.push(t);}getAssertions(){return this.assertions}setCurrentCallId(t){this.currentCallId=t;}getCurrentCallId(){return this.currentCallId}getData(){return [...this.assertions]}flushLegacyAnnotations(t){this.assertions.length!==0&&t.annotations.push({type:Ra,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}};var Pr="[REDACTED]";function de(e,t){if(e===null||t.length===0)return e;let r=new Set(t.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(e))Object.hasOwn(e,s)&&(n[s]=r.has(s.toLowerCase())?Pr:e[s]);return n}function wt(e,t){if(e===null||t.length===0)return e;let r;try{r=JSON.parse(e);}catch{return e}if(typeof r!="object"||r===null)return e;let n=new Set(t),s=le(r,n);return JSON.stringify(s)}function le(e,t){if(Array.isArray(e))return e.map(r=>le(r,t));if(typeof e=="object"&&e!==null){let r={};for(let n of Object.keys(e)){if(!Object.hasOwn(e,n))continue;let s=e[n];t.has(n)?r[n]=Pr:r[n]=le(s,t);}return r}return e}function Dr(e,t,r){if(r.length>0){for(let n of r)if(Fr(e,n))return false}if(t.length>0){for(let n of t)if(Fr(e,n))return true;return false}return true}function Fr(e,t){try{return t instanceof RegExp?t.test(e):Aa(t).test(e)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(t)}`),false}}function Aa(e){let t="",r=0;for(;r<e.length;){let n=e[r];n==="*"&&e[r+1]==="*"?(t+=".*",r+=2,e[r]==="/"&&r++):n==="*"?(t+="[^/]*",r++):n==="?"?(t+="[^/]",r++):".+^${}()|[]\\".includes(n)?(t+="\\"+n,r++):(t+=n,r++);}return new RegExp(t)}var _a=["get","post","put","patch","delete","head","fetch"],Ia=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function La(e){let t=e.toLowerCase();return Ia.some(r=>t.includes(r))}function Ma(e){if(!e)return null;if(e.data!==void 0&&e.data!==null){let t=e.data;return typeof t=="string"?t:Buffer.isBuffer(t)?t.toString("base64"):JSON.stringify(t)}if(e.form!==void 0&&e.form!==null)return JSON.stringify(e.form);if(e.multipart!==void 0&&e.multipart!==null){let t=e.multipart,r={};for(let[n,s]of Object.entries(t))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 xt=class xt{constructor(t,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=t,this.assertionTracker=r??null,this.apiConfig=n??xt.DEFAULT_API_CONFIG;try{this.apiCallWriter=new M("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(t){return t!=null&&typeof t=="object"?z.get(t)??null:this.primitiveCallIds.get(t)??null}intercept(){for(let r of _a){let n=this.context[r].bind(this.context);this.originals.set(r,n),this.context[r]=this.createWrapper(r,n);}let t=this.context.dispose.bind(this.context);this.originals.set("dispose",t),this.context.dispose=async r=>(this.disposed=true,t(r));}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0}}flushLegacyAnnotations(t){}dispose(){for(let[t,r]of this.originals)this.context[t]=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(t,r){let n=this,s=t.headers.bind(t);t.headers=function(){let u=s();return z.set(u,r),u};let a=t.headersArray.bind(t);t.headersArray=function(){let u=a();return z.set(u,r),u};let o=t.json.bind(t);t.json=async function(){let u=await o();return u!=null&&typeof u=="object"&&z.set(u,r),u};let i=t.status.bind(t);t.status=function(){let u=i();return n.primitiveCallIds.set(u,r),u};let l=t.statusText.bind(t);t.statusText=function(){let u=l();return n.primitiveCallIds.set(u,r),u};let d=t.ok.bind(t);t.ok=function(){let u=d();return n.primitiveCallIds.set(u,r),u};let c=t.text.bind(t);t.text=async function(){let u=await c();return n.primitiveCallIds.set(u,r),u};let p=t.body.bind(t);t.body=async function(){let u=await p();return z.set(u,r),u};}createWrapper(t,r){let n=this;return async function(a,o){if(!Dr(a,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return r(a,o);let i=`api-call-${n.callCounter++}`,l=new Date().toISOString(),d=t==="fetch"?(o?.method??"GET").toUpperCase():t.toUpperCase(),c=Ma(o),p=perf_hooks.performance.now();n._lastCallId=i,n.assertionTracker&&n.assertionTracker.setCurrentCallId(i);let f;try{f=await r(a,o);}catch(u){let g=perf_hooks.performance.now();try{let h=n.apiConfig.captureRequestBody?wt(c,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((g-p)*100)/100,isBinary:!1,error:u instanceof Error?u.message:String(u)};n.apiCallWriter&&(n.apiCallWriter.append(m),n.apiCallCount++);}catch{}throw u}try{let u=perf_hooks.performance.now(),g=f.headers(),h=g["content-type"]??null,m=h?!La(h):!1,y=null;n.apiConfig.captureRequestHeaders&&o?.headers&&(y=o.headers);let k=null;n.apiConfig.captureResponseHeaders&&(k=g);let w=n.apiConfig.captureRequestBody?c:null,b=null;if(n.apiConfig.captureResponseBody)try{m?b=(await f.body()).toString("base64"):b=await f.text();}catch{}y=de(y,n.apiConfig.redactHeaders),k=de(k,n.apiConfig.redactHeaders),w=wt(w,n.apiConfig.redactBodyFields),b=wt(b,n.apiConfig.redactBodyFields);let T={id:i,timestamp:l,method:d,url:f.url(),requestHeaders:y,requestBody:w,responseStatusCode:f.status(),responseStatusText:f.statusText(),responseHeaders:k,responseBody:b,responseTimeMs:Math.round((u-p)*100)/100,isBinary:m,error:null};n.apiCallWriter&&(n.apiCallWriter.append(T),n.apiCallCount++);}catch{}try{f[Er]=i,n.tagResponseMethods(f,i);}catch{}return f}}};xt.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 $=xt;var Ea="__testrelic_api_config",Pa="__testrelic_config_trackApiCalls";function ue(e){let t=e.annotations.find(n=>n.type===Ea&&n.description!==void 0);if(t)try{return JSON.parse(t.description,Fa)}catch{}let r=e.annotations.find(n=>n.type===Pa&&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 Fa(e,t){if(typeof t=="object"&&t!==null&&t.__regexp===true&&typeof t.source=="string"){let{source:r,flags:n}=t;return new RegExp(r,n)}return t}var Hr={page:async({page:e},t,r)=>{let n=new bt(e);try{await n.init();}catch{}await t(e);try{let{navigations:s,networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:l}=await n.getFileData(),d={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:l,apiCallsFile:null,apiCallsCount:0};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:e},t,r)=>{let n=ue(r);if(!n.trackApiCalls){await t(e);return}let s=new U,a=new $(e,s,n);a.intercept(),await t(e);try{let{apiCallsFile:o,apiCallsCount:i}=a.getFileData(),l=n.captureAssertions?s.getData():[],d={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:l,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:o,apiCallsCount:i};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};test.test.extend(Hr);var Oa={request:async({request:e},t,r)=>{let n=ue(r);if(!n.trackApiCalls){await t(e);return}let s=new U,a=new $(e,s,n);a.intercept();let o=null;try{o=new M("api-console");}catch{}let i=0,l=process.stdout.write,d=process.stderr.write;process.stdout.write=function(c,...p){try{let f=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!f.startsWith("[testrelic]")&&!f.startsWith("\u2139 TestRelic")&&!f.startsWith("\u2713 TestRelic")&&!f.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stdout",text:f.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return l.apply(process.stdout,[c,...p])},process.stderr.write=function(c,...p){try{let f=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!f.startsWith("[testrelic]")&&!f.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stderr",text:f.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return d.apply(process.stderr,[c,...p])};try{await t(e);}finally{process.stdout.write=l,process.stderr.write=d;}try{o?.close();let{apiCallsFile:c,apiCallsCount:p}=a.getFileData(),f=n.captureAssertions?s.getData():[],u={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:f,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:i>0?o?.getPath()??null:null,consoleLogsCount:i,apiCallsFile:c,apiCallsCount:p};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(u)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};var Ur="@testrelic/playwright-analytics";function Ua(e){return Array.isArray(e)?e.some(t=>Array.isArray(t)&&typeof t[0]=="string"&&t[0]===Ur):false}function za(e,t){let n={video:"on",screenshot:"on",trace:"on",...e.use??{}},s;Array.isArray(e.reporter)?s=e.reporter:typeof e.reporter=="string"?s=[[e.reporter]]:s=[["list"]];let a=Ua(s)?s:[...s,[Ur,t??{}]];return test.defineConfig({...e,use:n,reporter:a})}var zr=false;function Jl(e,t,r="manual_record"){if(!e||!e.annotations){zr||(zr=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
2600
+ `));return}let n={url:t,navigationType:r,timestamp:new Date().toISOString()};e.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}Object.defineProperty(exports,"ATTACHMENT_CONTENT_TYPE",{enumerable:true,get:function(){return core.ATTACHMENT_CONTENT_TYPE}});Object.defineProperty(exports,"ATTACHMENT_NAME",{enumerable:true,get:function(){return core.ATTACHMENT_NAME}});Object.defineProperty(exports,"PAYLOAD_VERSION",{enumerable:true,get:function(){return core.PAYLOAD_VERSION}});Object.defineProperty(exports,"isTestRelicDataPayload",{enumerable:true,get:function(){return core.isTestRelicDataPayload}});exports.SCHEMA_VERSION=et;exports.default=yt;exports.defineConfig=za;exports.recordNavigation=Jl;exports.testRelicApiFixture=Oa;exports.testRelicFixture=Hr;//# sourceMappingURL=index.cjs.map
2601
2601
  //# sourceMappingURL=index.cjs.map