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