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