@testrelic/playwright-analytics 2.9.0 → 2.11.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 +75 -71
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +75 -71
- package/dist/index.js.map +1 -1
- package/dist/reporter-entry.cjs +79 -75
- package/dist/reporter-entry.cjs.map +1 -1
- package/dist/reporter-entry.d.cts +3 -0
- package/dist/reporter-entry.d.ts +3 -0
- package/dist/reporter-entry.js +79 -75
- package/dist/reporter-entry.js.map +1 -1
- package/package.json +1 -1
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$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'),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 p=t.queue;if(p&&typeof p=="object"){if(typeof p.maxAge=="string"){let f=
|
|
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 Kr=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Zr=".testrelic-report";function we(t,e,r,s){let a=`${t}|${e.join("|")}|${r}|${s}`;return crypto.createHash("sha256").update(a).digest("hex").substring(0,12)}var K=class{constructor(e){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=path.join(e,Zr),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,s){try{let a=path.join(this.testsDir,e);fs$1.mkdirSync(a,{recursive:!0});let n=path.join(a,"meta.json"),o=n+".tmp",i=JSON.stringify(r);return fs$1.writeFileSync(o,i,"utf-8"),fs$1.renameSync(o,n),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),s?.networkRequestsFile&&this.moveFile(s.networkRequestsFile,path.join(a,"network.jsonl")),s?.consoleLogsFile&&this.moveFile(s.consoleLogsFile,path.join(a,"console.jsonl")),s?.apiCallsFile&&this.moveFile(s.apiCallsFile,path.join(a,"api-calls.jsonl")),!0}catch(a){let n=a instanceof Error?a.message:String(a);return this.writeErrors.push({testId:e,error:n,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${e}: ${n}
|
|
2
|
+
`),false}}moveFile(e,r){try{fs$1.renameSync(e,r);}catch{try{let{copyFileSync:s}=Kr("fs");s(e,r);try{fs$1.unlinkSync(e);}catch{}}catch(s){process.stderr.write(`[testrelic] Failed to move file ${e} \u2192 ${r}: ${s instanceof Error?s.message:String(s)}
|
|
3
|
+
`);}}}writeIndex(e){let r=path.join(this.reportDir,"index.json"),s=r+".tmp",a=JSON.stringify(e);fs$1.writeFileSync(s,a,"utf-8"),fs$1.renameSync(s,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}writeCompactIndex(e){let r=path.join(this.reportDir,"index-compact.json"),s=r+".tmp",a=e.map(({titlePath:o,project:i,...l})=>l),n=JSON.stringify(a);fs$1.writeFileSync(s,n,"utf-8"),fs$1.renameSync(s,r),this.totalBytesWritten+=Buffer.byteLength(n,"utf-8");}writeSummary(e){let r=path.join(this.reportDir,"summary.json"),s=r+".tmp",a=JSON.stringify(e);fs$1.writeFileSync(s,a,"utf-8"),fs$1.renameSync(s,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}writeManifest(e){let r=path.join(this.reportDir,"manifest.json"),s=r+".tmp",a=JSON.stringify(e);fs$1.writeFileSync(s,a,"utf-8"),fs$1.renameSync(s,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var It=".testrelic",ss="testrelic-config.json",as=".testrelic",ns=5,is=new Set(["__proto__","constructor","prototype"]),Rt=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${It}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),os={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function _t(t){let e=path.resolve(t);for(let r=0;r<=ns;r++){let s=path.join(e,It,ss);if(fs$1.existsSync(s))try{if(fs$1.statSync(s).isFile())return s}catch{}let a=path.join(e,as);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 n=path.dirname(e);if(n===e)break;e=n;}return null}function Mt(t){try{let e=fs$1.readFileSync(t,"utf-8"),r=JSON.parse(e);return typeof r!="object"||r===null||Array.isArray(r)||!Lt(r)?null:r}catch{return null}}function Lt(t){for(let e of Object.keys(t)){if(is.has(e))return false;let r=t[e];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!Lt(r))return false}return true}function Et(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 ke(t){let e=Object.create(null);for(let r of Object.keys(t)){let s=t[r];typeof s=="string"&&s.startsWith("$")?e[r]=Et(s):typeof s=="object"&&s!==null&&!Array.isArray(s)?e[r]=ke(s):e[r]=s;}return e}function At(t){let e=/^(\d+)\s*([smhd])$/.exec(t.trim());if(!e)return null;let r=parseInt(e[1],10),s=e[2],a=os[s];return !a||r<=0?null:r*a}function Pt(t,e){let r=Object.create(null);if(Object.assign(r,Rt),t){let l=t.cloud;l&&typeof l=="object"&&(typeof l.endpoint=="string"&&(r.endpoint=l.endpoint),typeof l.upload=="string"&&(r.uploadStrategy=l.upload),typeof l.timeout=="number"&&(r.timeout=l.timeout),typeof l.apiKey=="string"&&l.apiKey.length>0&&(r.apiKey=l.apiKey));let d=t["testrelic-repo"]??t.project;d&&typeof d=="object"&&typeof d.name=="string"&&(r.projectName=d.name),t.project&&!t["testrelic-repo"]&&process.stderr.write(`[testrelic] Deprecation: "project" key in config is deprecated. Rename it to "testrelic-repo".
|
|
5
|
+
`);let p=t.queue;if(p&&typeof p=="object"){if(typeof p.maxAge=="string"){let f=At(p.maxAge);f!==null&&(r.queueMaxAge=f);}typeof p.directory=="string"&&(r.queueDirectory=p.directory);}}if(e){if(typeof e.apiKey=="string"&&e.apiKey.length>0){let l=e.apiKey.startsWith("$")?Et(e.apiKey):e.apiKey;l&&(r.apiKey=l);}if(typeof e.endpoint=="string"&&(r.endpoint=e.endpoint),typeof e.upload=="string"&&(r.uploadStrategy=e.upload),typeof e.timeout=="number"&&(r.timeout=e.timeout),typeof e.projectName=="string"&&(r.projectName=e.projectName),typeof e.queueMaxAge=="string"){let l=At(e.queueMaxAge);l!==null&&(r.queueMaxAge=l);}typeof e.queueDirectory=="string"&&(r.queueDirectory=e.queueDirectory),typeof e.uploadArtifacts=="boolean"&&(r.uploadArtifacts=e.uploadArtifacts),typeof e.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=e.artifactMaxSizeMb);}let s=process.env.TESTRELIC_API_KEY;s&&s.length>0&&(r.apiKey=s);let a=process.env.TESTRELIC_CLOUD_ENDPOINT;a&&core.isValidEndpointUrl(a)&&(r.endpoint=a);let n=process.env.TESTRELIC_UPLOAD_STRATEGY;n&&["batch","realtime","both"].includes(n)&&(r.uploadStrategy=n);let o=process.env.TESTRELIC_CLOUD_TIMEOUT;if(o){let l=parseInt(o,10);!isNaN(l)&&l>=1e3&&l<=12e4&&(r.timeout=l);}let i=Object.freeze(r);return core.isValidCloudConfig(i)?i:Rt}var us=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],ps=["authorization","cookie","set-cookie","x-api-key"],fs=["password","secret","token","apiKey","api_key"];function Nt(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??[...ps],e.redactBodyFields=t?.redactBodyFields??[...fs],e.apiIncludeUrls=t?.apiIncludeUrls??[],e.apiExcludeUrls=t?.apiExcludeUrls??[],Object.freeze(e)}function Ft(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=[...us,...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 s=_t(process.cwd()),a=s?Mt(s):null,n=a?ke(a):null,o=Pt(n,t?.cloud);return e.cloud=o.apiKey?o:null,e.reportMode=t?.reportMode??"streaming",e.streamingThreshold=t?.streamingThreshold??0,Object.freeze(e)}var Te="1.3.0";function Dt(t,e,r){try{let a=fs$1.readFileSync(t,"utf-8").split(`
|
|
6
|
+
`);if(e<1||e>a.length)return null;let n=Math.max(1,e-r),o=Math.min(a.length,e+r),i=[];for(let l=n;l<=o;l++){let d=l===e?">":" ",p=String(l).padStart(String(o).length," ");i.push(`${d} ${p} | ${a[l-1]}`);}return i.join(`
|
|
7
|
+
`)}catch{return null}}function Bt(t){return e=>{let r=e;for(let s of t)if(typeof s=="string"){let a=s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(a,"g"),"[REDACTED]");}else {let a=s.flags.includes("g")?s.flags:s.flags+"g",n=new RegExp(s.source,a);r=r.replace(n,"[REDACTED]");}return r}}function hs(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 ms(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 vs(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 ys(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 bs(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 xs=[hs,ms,vs,ys,bs];function N(t){let e=process.env;for(let r of xs){let s=r(e);if(s)return s}return null}var Se=`
|
|
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 Ce=`<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>`,Re=`<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 Ae=`
|
|
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 Ie=`
|
|
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'};
|
|
@@ -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 Me=`
|
|
1806
1806
|
/* \u2500\u2500 Event Delegation \u2500\u2500 */
|
|
1807
1807
|
document.addEventListener('click',function(e){
|
|
1808
1808
|
var target=e.target;
|
|
@@ -2118,7 +2118,7 @@ function _updateCard(cls,val){
|
|
|
2118
2118
|
h+='</div>';
|
|
2119
2119
|
return h;
|
|
2120
2120
|
}
|
|
2121
|
-
`;var
|
|
2121
|
+
`;var Ee=`
|
|
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 Pe=`
|
|
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 ws=`
|
|
2318
2318
|
(function(){
|
|
2319
2319
|
var data=JSON.parse(document.getElementById('report-data').textContent);
|
|
2320
|
-
${Re}
|
|
2321
|
-
${Le}
|
|
2322
|
-
${Me}
|
|
2323
2320
|
${Ae}
|
|
2324
|
-
${
|
|
2321
|
+
${Le}
|
|
2325
2322
|
${Ee}
|
|
2326
2323
|
${Ie}
|
|
2324
|
+
${_e}
|
|
2325
|
+
${Pe}
|
|
2326
|
+
${Me}
|
|
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 Ot(t,e,r){let s=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(Ce).toString("base64")}">
|
|
2344
|
+
<style>${Se}</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
|
+
${Re}
|
|
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,15 +2383,15 @@ ${""}
|
|
|
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">${s}</script>
|
|
2387
|
+
${a?`<script id="artifact-manifest-data" type="application/json">${a}</script>`:""}
|
|
2388
|
+
<script>${ws}</script>
|
|
2389
2389
|
</body>
|
|
2390
|
-
</html>`}function
|
|
2390
|
+
</html>`}function Ne(t,e,r,s){let a=t.replace(/<\//g,"<\\/"),n=e.replace(/<\//g,"<\\/"),o=s?s.replace(/<\//g,"<\\/"):null,i={};try{i=JSON.parse(t);}catch{}let l=`{
|
|
2391
2391
|
"schemaVersion":"2.0",
|
|
2392
2392
|
"reportMode":"streaming",
|
|
2393
2393
|
"serverPort":${r??"null"},
|
|
2394
|
-
"summary":${
|
|
2394
|
+
"summary":${a},
|
|
2395
2395
|
"index":${n},
|
|
2396
2396
|
"timeline":[],
|
|
2397
2397
|
"testRunId":${JSON.stringify(String(i.testRunId??""))},
|
|
@@ -2400,7 +2400,7 @@ ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:
|
|
|
2400
2400
|
"totalDuration":${Number(i.totalDuration)||0},
|
|
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
|
-
"shardRunIds":null
|
|
2403
|
+
"shardRunIds":${i.shardRunIds?JSON.stringify(i.shardRunIds).replace(/<\//g,"<\\/"):"null"}
|
|
2404
2404
|
}`,d=`
|
|
2405
2405
|
(function(){
|
|
2406
2406
|
var data=JSON.parse(document.getElementById('report-data').textContent);
|
|
@@ -2471,13 +2471,13 @@ ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:
|
|
|
2471
2471
|
window.__trServerPort=_serverPort;
|
|
2472
2472
|
window.__trIsStreaming=true;
|
|
2473
2473
|
|
|
2474
|
-
${Re}
|
|
2475
|
-
${Le}
|
|
2476
|
-
${Me}
|
|
2477
2474
|
${Ae}
|
|
2478
|
-
${
|
|
2475
|
+
${Le}
|
|
2479
2476
|
${Ee}
|
|
2480
2477
|
${Ie}
|
|
2478
|
+
${_e}
|
|
2479
|
+
${Pe}
|
|
2480
|
+
${Me}
|
|
2481
2481
|
applyTheme();
|
|
2482
2482
|
renderRunMeta();
|
|
2483
2483
|
renderSummary();
|
|
@@ -2496,15 +2496,15 @@ ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:
|
|
|
2496
2496
|
<title>TestRelic AI Analytics Report</title>
|
|
2497
2497
|
${r?`<meta name="report-server-port" content="${r}">`:""}
|
|
2498
2498
|
${r?`<meta name="artifact-server-port" content="${r}">`:""}
|
|
2499
|
-
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(
|
|
2500
|
-
<style>${
|
|
2499
|
+
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(Ce).toString("base64")}">
|
|
2500
|
+
<style>${Se}</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
|
+
${Re}
|
|
2508
2508
|
<div class="brand-text">
|
|
2509
2509
|
<span class="brand-title">TestRelic AI</span>
|
|
2510
2510
|
<span class="brand-sub">Analytics Report</span>
|
|
@@ -2543,59 +2543,63 @@ ${r?`<meta name="artifact-server-port" content="${r}">`:""}
|
|
|
2543
2543
|
${o?`<script id="artifact-manifest-data" type="application/json">${o}</script>`:""}
|
|
2544
2544
|
<script>${d}</script>
|
|
2545
2545
|
</body>
|
|
2546
|
-
</html>`}function Fe(t){try{let e=process.platform,r;e==="darwin"?r=`open "${t}"`:e==="win32"?r=`start "" "${t}"`:r=`xdg-open "${t}"`,child_process.exec(r,
|
|
2547
|
-
`);});}catch{}}path.join(os$1.tmpdir(),"testrelic-data");async function
|
|
2548
|
-
Report server: http://127.0.0.1:${
|
|
2549
|
-
`);try{let
|
|
2550
|
-
`);}}var
|
|
2551
|
-
`).map(l=>l.trim()).some(l=>l===
|
|
2546
|
+
</html>`}function Fe(t){try{let e=process.platform,r;e==="darwin"?r=`open "${t}"`:e==="win32"?r=`start "" "${t}"`:r=`xdg-open "${t}"`,child_process.exec(r,s=>{s&&process.stderr.write(`[testrelic] Failed to open browser: ${s.message}
|
|
2547
|
+
`);});}catch{}}path.join(os$1.tmpdir(),"testrelic-data");async function qt(t,e,r,s){let a=(e-1)*r,n=[],o=0,i=readline.createInterface({input:fs$1.createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let p of i)if(p.length!==0){if(o>=a&&n.length<r)try{n.push(JSON.parse(p));}catch{}if(o++,n.length>=r&&s!==void 0)break}let l=s??o,d=Math.max(1,Math.ceil(l/r));return {items:n,total:l,page:e,pageSize:r,totalPages:d}}var zt=/^[a-f0-9]{12}$/,De=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,$t=500;function x(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function jt(t){t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type");}function ae(t){try{return fs$1.existsSync(t)?JSON.parse(fs$1.readFileSync(t,"utf-8")):null}catch{return null}}function ne(t){let e=0;try{let r=fs$1.readdirSync(t,{withFileTypes:!0});for(let s of r){let a=path.join(t,s.name);s.isFile()?e+=fs$1.statSync(a).size:s.isDirectory()&&(e+=ne(a));}}catch{}return e}function Vt(t,e,r,s){let a=ae(path.join(r,"index.json"));x(e,200,{status:"ok",reportMode:"streaming",testCount:a?.length??0,uptime:Math.floor((Date.now()-s)/1e3)});}function Gt(t,e,r){let s=ae(path.join(r,"summary.json"));if(!s){x(e,404,{error:"Summary not found"});return}x(e,200,s);}function Wt(t,e,r){let s=ae(path.join(r,"index.json"));if(!s){x(e,404,{error:"Test index not found"});return}let n=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,o=Math.max(1,parseInt(n.get("page")??"1",10)||1),i=Math.min($t,Math.max(1,parseInt(n.get("pageSize")??"100",10)||100)),l=n.get("status")?.split(",").filter(Boolean)??null,d=n.get("file")??null,p=n.get("search")?.toLowerCase()??null,f=n.get("tag")?.split(",").filter(Boolean)??null,m=n.get("sort")??"file",c=n.get("order")==="desc"?-1:1,u=s;l&&l.length>0&&(u=u.filter(y=>l.includes(y.status))),d&&(u=u.filter(y=>y.filePath===d||y.filePath.startsWith(d+"/"))),p&&(u=u.filter(y=>y.title.toLowerCase().includes(p)||y.filePath.toLowerCase().includes(p))),f&&f.length>0&&(u=u.filter(y=>f.some(b=>y.tags.includes(b)))),u=[...u].sort((y,b)=>{let S=0;switch(m){case "duration":S=y.duration-b.duration;break;case "status":S=y.status.localeCompare(b.status);break;case "title":S=y.title.localeCompare(b.title);break;default:S=y.filePath.localeCompare(b.filePath);break}return S*c});let g=u.length,h=Math.max(1,Math.ceil(g/i)),w=(o-1)*i,C=u.slice(w,w+i);x(e,200,{tests:C,pagination:{page:o,pageSize:i,totalItems:g,totalPages:h},filters:{status:l,file:d,search:p,tag:f}});}function Kt(t,e,r,s){if(!zt.test(s)){x(e,400,{error:"Invalid test ID format"});return}let a=path.join(r,"tests",s,"meta.json"),n=path.join(r,"tests",`${s}.json`),o=fs$1.existsSync(a)?a:fs$1.existsSync(n)?n:null;if(!o){x(e,404,{error:`Test not found: ${s}`});return}try{let i=fs$1.readFileSync(o,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(i);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}async function Jt(t,e,r,s,a){if(!zt.test(s)){x(e,400,{error:"Invalid test ID format"});return}let o=path.join(r,"tests",s,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[a]);if(!fs$1.existsSync(o)){x(e,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let l=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,d=Math.max(1,parseInt(l.get("page")??"1",10)||1),p=Math.min($t,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),f,m=path.join(r,"tests",s,"meta.json");if(fs$1.existsSync(m))try{let u=JSON.parse(fs$1.readFileSync(m,"utf-8"));switch(a){case "network":f=u.networkRequestsCount;break;case "console":f=u.consoleLogsCount;break;case "api-calls":f=u.apiCallsCount;break}}catch{}let c=await qt(o,d,p,f);x(e,200,c);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}function Yt(t,e,r){let s=ae(path.join(r,"index.json"));if(!s){x(e,404,{error:"Test index not found"});return}let a=new Map;for(let o of s){if(o.isRetry)continue;let i=a.get(o.filePath);switch(i||(i={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},a.set(o.filePath,i)),i.total++,o.status){case "passed":i.passed++;break;case "failed":i.failed++;break;case "flaky":i.flaky++;break;case "skipped":i.skipped++;break;case "timedout":i.timedOut++;break}}let n=Array.from(a.entries()).map(([o,i])=>({filePath:o,...i})).sort((o,i)=>o.filePath.localeCompare(i.filePath));x(e,200,{files:n});}function Zt(t,e,r){if(!fs$1.existsSync(r)){x(e,200,{runs:[],totalSizeBytes:0});return}try{let s=[],a=0,n=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of n){if(!o.isDirectory()||!De.test(o.name))continue;let i=path.join(r,o.name),l=ne(i),d=fs$1.readdirSync(i,{withFileTypes:!0}).filter(p=>p.isDirectory());s.push({folderName:o.name,totalSizeBytes:l,testCount:d.length}),a+=l;}s.sort((o,i)=>i.folderName.localeCompare(o.folderName)),x(e,200,{runs:s,totalSizeBytes:a});}catch(s){x(e,500,{error:s instanceof Error?s.message:String(s)});}}function Qt(t,e,r){try{let s=0,a=0;if(fs$1.existsSync(r)){let n=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of n){if(!o.isDirectory()||!De.test(o.name))continue;let i=path.join(r,o.name),l=ne(i);fs$1.rmSync(i,{recursive:!0,force:!0}),a+=l,s++;}}x(e,200,{deletedCount:s,freedBytes:a});}catch(s){x(e,500,{error:s instanceof Error?s.message:String(s)});}}function Xt(t,e,r,s){if(!De.test(s)){x(e,400,{error:"Invalid folder name"});return}let a=path.join(r,s);try{if(!fs$1.statSync(a).isDirectory()){x(e,404,{error:"Not found"});return}}catch{x(e,404,{error:"Not found"});return}try{let n=ne(a);fs$1.rmSync(a,{recursive:!0,force:!0}),x(e,200,{deleted:s,freedBytes:n});}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}function er(t,e,r){x(e,200,{status:"shutting_down"}),r.close();}function Be(t,e,r){if(!fs$1.existsSync(r)){x(e,404,{error:"File not found"});return}try{let s=fs$1.readFileSync(r),a=path.extname(r).toLowerCase(),n=Is[a]??"application/octet-stream";e.writeHead(200,{"Content-Type":n}),e.end(s);}catch(s){x(e,500,{error:s instanceof Error?s.message:String(s)});}}var Is={".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 Es=9323,Ps=10,Ns=1800*1e3;function J(t,e){return new Promise((r,s)=>{let a=e?.port??Es,n=Date.now(),o,i=0,l=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 d(){clearTimeout(o),o=setTimeout(()=>{f.close();},Ns);}let p=e?.htmlPath??null;if(!p){let c=path.dirname(t);try{let u=fs$1.readdirSync(c).find(g=>g.endsWith(".html"));u&&(p=path.join(c,u));}catch{}}let f=http.createServer((c,u)=>{if(d(),jt(u),c.method==="OPTIONS"){u.writeHead(204),u.end();return}let g;try{g=new URL(c.url??"/",`http://${c.headers.host??"localhost"}`).pathname;}catch{x(u,400,{error:"Invalid URL"});return}if(c.method==="GET"&&(g==="/"||g==="/index.html")){if(p&&fs$1.existsSync(p)){Be(c,u,p);return}x(u,404,{error:"HTML report not found"});return}if(c.method==="GET"&&g==="/api/health"){Vt(c,u,t,n);return}if(c.method==="GET"&&g==="/api/summary"){Gt(c,u,t);return}if(c.method==="GET"&&g==="/api/tests"){Wt(c,u,t);return}if(c.method==="GET"&&g==="/api/files"){Yt(c,u,t);return}let h=g.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(c.method==="GET"&&h){Jt(c,u,t,h[1],h[2]);return}let w=g.match(/^\/api\/tests\/([a-f0-9]+)$/);if(c.method==="GET"&&w){Kt(c,u,t,w[1]);return}if(c.method==="GET"&&g==="/api/artifacts"){Zt(c,u,l);return}if(c.method==="DELETE"&&g==="/api/artifacts"){Qt(c,u,l);return}let C=g.match(/^\/api\/artifacts\/(.+)$/);if(c.method==="DELETE"&&C){Xt(c,u,l,decodeURIComponent(C[1]));return}if(c.method==="GET"&&g.startsWith("/artifacts/")){let y=decodeURIComponent(g.slice(11));if(y.includes("..")||y.includes("\0")){x(u,400,{error:"Invalid path"});return}Be(c,u,path.join(l,y));return}if(c.method==="POST"&&g==="/api/shutdown"){er(c,u,f);return}x(u,404,{error:"Not found"});});function m(c){let u=g=>{g.code==="EADDRINUSE"&&i<Ps?(i++,m(c+1)):s(g);};f.once("error",u),f.listen(c,"127.0.0.1",()=>{f.removeListener("error",u);let g=f.address();if(!g||typeof g=="string"){s(new Error("Failed to get server address"));return}d(),r({port:g.port,dispose:()=>new Promise(h=>{clearTimeout(o),f.close(()=>h());})});});}m(a);})}async function tr(t){let e=await J(t);return {port:e.port,dispose:e.dispose}}function Bs(t,e,r){let s=JSON.stringify(t),a=r?JSON.stringify(r):null;return Ot(s,e,a)}async function qe(t,e,r){try{let s=null,a=null,n=e.reportMode==="streaming"||e.reportMode==="auto"&&t.timeline.length===0&&t.summary.total>=e.streamingThreshold,o,i=e.htmlReportPath,l=path.dirname(i);fs$1.mkdirSync(l,{recursive:!0});let d="",p="[]",f=null;if(n){d=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 c=path.dirname(e.outputPath),u=path.join(c,".testrelic-report");try{let g=path.join(u,"index-compact.json"),h=path.join(u,"index.json");fs$1.existsSync(g)?p=fs$1.readFileSync(g,"utf-8"):fs$1.existsSync(h)&&(p=fs$1.readFileSync(h,"utf-8"));}catch{}f=r?JSON.stringify(r):null,o=Ne(d,p,null,f);}else o=Bs(t,null,r);let m=i+".tmp";if(fs$1.writeFileSync(m,o,"utf-8"),fs$1.renameSync(m,i),n){if(t.ci===null){let c=path.dirname(e.outputPath),u=path.join(c,".testrelic-report"),g=path.resolve(i);try{if(await qs(),s=await Hs(u),!s){a=await J(u,{htmlPath:g}),s=a.port;let h=setInterval(()=>{},6e4),w=()=>{clearInterval(h),a?.dispose();};process.on("SIGINT",w),process.on("SIGTERM",w),setTimeout(w,1800*1e3).unref();}if(s){process.stderr.write(`
|
|
2548
|
+
Report server: http://127.0.0.1:${s}
|
|
2549
|
+
`);try{let h=Ne(d,p,s,f),w=i+".tmp";fs$1.writeFileSync(w,h,"utf-8"),fs$1.renameSync(w,i);}catch{}}}catch{}}}else if(e.openReport&&t.ci===null&&e.includeArtifacts){let c=path.dirname(e.outputPath),u=path.join(c,"artifacts");if(fs$1.existsSync(u))try{let g=await tr(u);s=g.port,process.on("exit",()=>{g.dispose();});}catch{}}if(e.openReport&&t.ci===null)if(n&&s)Fe(`http://127.0.0.1:${s}`);else {let c=path.resolve(i);Fe(c);}}catch(s){process.stderr.write(`[testrelic] Failed to write HTML report: ${s instanceof Error?s.message:String(s)}
|
|
2550
|
+
`);}}var le=9323,ir=10;async function Os(){for(let t=le;t<le+ir;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),500),s=await fetch(`http://127.0.0.1:${t}/api/health`,{signal:e.signal});if(clearTimeout(r),s.ok)return t}catch{}return null}async function qs(){for(let t=le;t<le+ir;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 Hs(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(s=>fs$1.existsSync(s));if(!r){let s=await J(t);return process.on("exit",()=>{s?.dispose();}),s.port}return new Promise(s=>{let a=child_process.spawn(process.execPath,[r,"serve",t],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),n="",o=false,i=setTimeout(()=>{o||(o=true,a.stderr?.removeAllListeners(),Os().then(s));},5e3);a.stderr?.on("data",l=>{n+=l.toString();let d=n.match(/127\.0\.0\.1:(\d+)/);d&&!o&&(o=true,clearTimeout(i),a.stderr?.removeAllListeners(),a.unref(),s(Number(d[1])));}),a.on("error",()=>{o||(o=true,clearTimeout(i),s(null));}),a.on("exit",()=>{o||(o=true,clearTimeout(i),s(null));}),a.unref();})}var $s=20,He=0,Ue=[];async function lr(t,e){He>=$s&&await new Promise(r=>Ue.push(r)),He++;try{return await promises.copyFile(t,e),!0}catch{return false}finally{He--,Ue.length>0&&Ue.shift()();}}var Z=[];async function dr(){Z.length!==0&&(await Promise.allSettled(Z),Z.length=0);}function cr(t){let e=new Date,r=n=>String(n).padStart(2,"0"),s=`${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,s)))return s;let a=1;for(;fs$1.existsSync(path.join(t,`${s}-${a}`));)a++;return `${s}-${a}`}function js(t){let e=t.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return e.length>100&&(e=e.substring(0,100).replace(/-+$/,"")),e||"unnamed-test"}function ur(t,e,r,s,a){let n=t.find(m=>m.name==="screenshot"&&m.path),o=t.find(m=>m.name==="video"&&m.path);if(!n&&!o)return null;let i=js(e);r>0&&(i+=`--retry-${r}`);let l=a?["artifacts",a,i]:["artifacts",i],d=path.join(s,...l),p=l,f={};try{fs$1.mkdirSync(d,{recursive:!0});}catch{return null}if(n?.path&&fs$1.existsSync(n.path)){let c=`screenshot${path.extname(n.path)||".png"}`,u=path.join(d,c);Z.push(lr(n.path,u).then(()=>{})),f.screenshot=`${p.join("/")}/${c}`;}if(o?.path&&fs$1.existsSync(o.path)){let c=`video${path.extname(o.path)||".webm"}`,u=path.join(d,c);Z.push(lr(o.path,u).then(()=>{})),f.video=`${p.join("/")}/${c}`;}return !f.screenshot&&!f.video?null:f}var Ws=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Ks="1.0";function Js(t){let e=path.extname(t).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(e)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(e)?"video":"other"}function pr(t,e,r){let s=[];try{let a=fs$1.readdirSync(t,{withFileTypes:!0});for(let n of a){if(!n.isFile())continue;let o=path.join(t,n.name),i=fs$1.statSync(o);s.push({name:n.name,type:Js(n.name),relativePath:`artifacts/${e}/${r}/${n.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:s}}function Ys(t,e){let r=path.join(t,e),s=[],a=0;try{let o=fs$1.readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let l=pr(path.join(r,i.name),e,i.name);s.push(l);for(let d of l.files)a+=d.sizeBytes;}}catch{}let n=e.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return s.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:e,timestamp:n,totalSizeBytes:a,testCount:s.length,tests:s,isCurrentRun:false}}function fr(t,e){let r=path.join(t,"artifacts"),s=[],a=[],n=0;try{let i=fs$1.readdirSync(r,{withFileTypes:!0});for(let l of i)if(l.isDirectory())if(Ws.test(l.name)){let d=Ys(r,l.name);s.push({...d,isCurrentRun:l.name===e});}else {let d=pr(path.join(r,l.name),l.name,l.name);a.push(d);for(let p of d.files)n+=p.sizeBytes;}}catch{}s.sort((i,l)=>l.timestamp.localeCompare(i.timestamp)),a.length>0&&(a.sort((i,l)=>i.testName.localeCompare(l.testName)),s.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:n,testCount:a.length,tests:a,isCurrentRun:false}));let o=s.reduce((i,l)=>i+l.totalSizeBytes,0);return {schemaVersion:Ks,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:s,serverPort:null}}function ta(t){let e=t,{root:r}=path.parse(e);for(;e!==r;){if(fs$1.existsSync(path.join(e,".git")))return e;e=path.join(e,"..");}return null}function hr(t){try{let e=ta(t);if(!e)return;let r=path.join(e,".gitignore"),s=path.relative(e,t).replace(/\\/g,"/"),a=s.endsWith("/")?s:`${s}/`;if(fs$1.existsSync(r)&&fs$1.readFileSync(r,"utf-8").split(`
|
|
2551
|
+
`).map(l=>l.trim()).some(l=>l===a||l===s))return;let n=`
|
|
2552
2552
|
# TestRelic test artifacts
|
|
2553
|
-
${
|
|
2554
|
-
`;fs$1.appendFileSync(r,n,"utf-8");}catch{}}function
|
|
2555
|
-
`}function
|
|
2553
|
+
${a}
|
|
2554
|
+
`;fs$1.appendFileSync(r,n,"utf-8");}catch{}}function yr(t,e){let r=[];for(let s of t){let a=ra(s),n=sa(s),o=aa(s,a,n,e),i=na(s,a,n);if(o.length===0&&i.length===0){r.push({type:"navigation",url:"about:blank",timestamp:s.startedAt,durationOnUrl:s.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:s.specFile,test:a,tests:[n],_testTitle:s.title});continue}r.push(...o,...i);}return r.sort(ia),oa(r,t),r.map((s,a)=>s.type==="navigation"?{...{index:a,type:"navigation",url:s.url,timestamp:s.timestamp,durationOnUrl:s.durationOnUrl??0,navigationType:s.navigationType,domContentLoadedAt:s.domContentLoadedAt??null,networkIdleAt:s.networkIdleAt??null,networkStats:s.networkStats??null,specFile:s.specFile,test:s.test},tests:s.tests}:{...{index:a,type:"api_call",callId:s.callId,method:s.method,url:s.url,timestamp:s.timestamp,responseTime:s.responseTime??null,request:s.request,response:s.response??null,...s.error?{error:s.error}:{},assertions:s.assertions??[],specFile:s.specFile,test:s.test},tests:s.tests})}function ra(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 sa(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 aa(t,e,r,s){let a=[];for(let n of t.navigations)s.navigationTypes!==null&&!s.navigationTypes.includes(n.navigationType)||a.push({type:"navigation",url:n.url,timestamp:n.timestamp,durationOnUrl:0,navigationType:n.navigationType,domContentLoadedAt:n.domContentLoadedAt??null,networkIdleAt:n.networkIdleAt??null,networkStats:n.networkStats??null,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title});return a}function na(t,e,r){if(!t.apiCalls||t.apiCalls.length===0)return [];let s=t.apiAssertions??[];return t.apiCalls.map(a=>{let n=s.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}:{}})),o=null;return a.responseStatusCode!==null&&a.responseStatusText!==null&&(o={statusCode:a.responseStatusCode,statusText:a.responseStatusText,headers:a.responseHeaders,body:vr(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:vr(a.requestBody)},response:o,...a.error?{error:a.error}:{},assertions:n,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title}})}function ia(t,e){let r=new Date(t.timestamp).getTime(),s=new Date(e.timestamp).getTime();if(r!==s)return r-s;let a={navigation:0,api_call:1},n=a[t.type],o=a[e.type];return n!==o?n-o:t.type==="api_call"&&e.type==="api_call"&&t.callId&&e.callId?mr(t.callId)-mr(e.callId):0}function mr(t){let e=t.match(/(\d+)$/);return e?parseInt(e[1],10):0}function oa(t,e){for(let r=0;r<t.length;r++){let s=t[r];if(s.type!=="navigation")continue;let a=new Date(s.timestamp).getTime(),n=null;for(let o=r+1;o<t.length;o++)if(t[o]._testTitle===s._testTitle){n=new Date(t[o].timestamp).getTime();break}if(n!==null)s.durationOnUrl=Math.max(0,n-a);else {let o=e.find(i=>i.title===s._testTitle);if(o){let i=new Date(o.completedAt).getTime();s.durationOnUrl=Math.max(0,i-a);}}}}function vr(t){if(t==null)return null;try{return JSON.parse(t)}catch{return t}}function H(t,e){let r=t.length,s=Math.min(Math.ceil(e/100*r)-1,r-1);return t[Math.max(0,s)]}function je(t){try{let e=new URL(t);return e.origin+e.pathname}catch{return t}}function la(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 br(t,e){let r=0,s=0,a=0,n=0,o=0;for(let v of t)switch(v.status){case "passed":r++;break;case "failed":s++;break;case "flaky":a++;break;case "skipped":n++;break;case "timedout":o++;break}let i=[];for(let v of t)v.apiCalls&&i.push(...v.apiCalls);let l=i.length,d=new Set,p={},f={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},m=[];for(let v of i)d.add(je(v.url)),p[v.method]=(p[v.method]??0)+1,f[la(v.responseStatusCode)]+=1,m.push(v.responseTimeMs);let c=null;if(m.length>0){let v=[...m].sort((A,z)=>A-z),k=v.reduce((A,z)=>A+z,0);c={avg:Math.round(k/v.length),min:v[0],max:v[v.length-1],p50:H(v,50),p95:H(v,95),p99:H(v,99)};}let u=0,g=0,h=0;for(let v of t)if(v.apiAssertions)for(let k of v.apiAssertions)u++,k.status==="passed"?g++:h++;let w=0,C=new Set;for(let v of t){w+=v.navigations.length;for(let k of v.navigations)C.add(k.url);}let y=0,b={};function S(v){for(let k of v)y++,b[k.category]=(b[k.category]??0)+1,k.children.length>0&&S(k.children);}for(let v of t)v.actions&&S(v.actions);return {total:t.length,passed:r,failed:s,flaky:a,skipped:n,timedout:o,totalApiCalls:l,uniqueApiUrls:d.size,apiCallsByMethod:p,apiCallsByStatusRange:f,apiResponseTime:c,totalAssertions:u,passedAssertions:g,failedAssertions:h,totalNavigations:w,uniqueNavigationUrls:C.size,totalTimelineSteps:e,totalActionSteps:y,actionStepsByCategory:b}}function da(t){let e=56-t.length;return e>0?t+" ".repeat(e):t}function M(t){return `\u2502 ${da(t)} \u2502
|
|
2555
|
+
`}function Ve(t,e,r,s){if(s||t.total===0)return;let a=`\u250C${"\u2500".repeat(58)}\u2510
|
|
2556
2556
|
`,n=`\u2514${"\u2500".repeat(58)}\u2518
|
|
2557
|
-
`,o=
|
|
2558
|
-
`,process.stderr.write(i);}var
|
|
2559
|
-
`)[0]?.trim();return
|
|
2557
|
+
`,o=M(""),i=a;i+=M("TestRelic AI - Playwright Test Report"),i+=o;let l=[];if(t.passed>0&&l.push(`${t.passed} \u2713`),t.failed>0&&l.push(`${t.failed} \u2717`),t.flaky>0&&l.push(`${t.flaky} \u26A0`),t.skipped>0&&l.push(`${t.skipped} skipped`),t.timedout>0&&l.push(`${t.timedout} timedout`),i+=M(`Tests: ${t.total} total (${l.join(" ")})`),t.totalNavigations>0&&(i+=M(`Navigations: ${t.totalNavigations} visits across ${t.uniqueNavigationUrls} unique URLs`)),t.totalApiCalls>0){i+=M(`API Calls: ${t.totalApiCalls} calls across ${t.uniqueApiUrls} unique endpoints`);let d=Object.entries(t.apiCallsByMethod).filter(([,f])=>f>0).map(([f,m])=>`${f}: ${m}`);d.length>0&&(i+=M(` ${d.join(" ")}`));let p=Object.entries(t.apiCallsByStatusRange).filter(([,f])=>f>0).map(([f,m])=>`${f}: ${m}`);p.length>0&&(i+=M(` ${p.join(" ")}`)),t.apiResponseTime&&(i+=M(` Avg response: ${t.apiResponseTime.avg}ms P95: ${t.apiResponseTime.p95}ms`));}if(t.totalAssertions>0&&(i+=M(`Assertions: ${t.totalAssertions} total (${t.passedAssertions} \u2713 ${t.failedAssertions} \u2717)`)),t.totalActionSteps>0){let d=[],p=t.actionStepsByCategory;p.ui_action&&d.push(`${p.ui_action} UI`),p.assertion&&d.push(`${p.assertion} assertions`),p.custom_step&&d.push(`${p.custom_step} custom`);let f=d.length>0?` (${d.join(" ")})`:"";i+=M(`Actions: ${t.totalActionSteps} steps${f}`);}i+=M(`Report: ${r}`),i+=M(`Data: ${e}`),i+=n,i+=`For more information visit us at https://docs.testrelic.ai
|
|
2558
|
+
`,process.stderr.write(i);}var ca=new Set(["pw:api","expect","test.step"]);function ua(t){return t==="expect"?"assertion":t==="test.step"?"custom_step":"ui_action"}function Ge(t,e,r){if(ca.has(t.category)){let s=[];for(let n of t.steps)Ge(n,e,s);let a=t.startTime.getTime()-e.getTime();r.push({title:t.title,category:ua(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:s});}else for(let s of t.steps)Ge(s,e,r);}function xr(t,e){let r=[];for(let s of t)Ge(s,e,r);return r}var ga=new Set(["localhost","127.0.0.1","0.0.0.0"]);function kr(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&ga.has(e.hostname)))throw core.createError(core.ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${e.protocol}//${e.hostname}`)}var ha=3e3;async function We(t){let e=new AbortController,r=setTimeout(()=>e.abort(),ha);try{return (await fetch(`${t}/health`,{method:"GET",signal:e.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function Tr(t){return new Promise(e=>setTimeout(e,t))}async function wr(t){try{let r=(await t.json()).error;if(r&&typeof r.message=="string"){let s=r.details;if(Array.isArray(s)&&s.length>0){let a=s.map(n=>`${n.field}: ${n.message}`).join(", ");return `${r.message} (${a})`}return r.message}}catch{}return `HTTP ${t.status}`}async function Ke(t,e,r){let s=new AbortController,a=setTimeout(()=>s.abort(),r);try{let n=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:s.signal});if(n.ok){let i=await n.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,orgId:i.orgId,orgName:i.orgName,userId:i.userId,userName:i.userName}}if(n.status===429){let i=n.headers.get("Retry-After"),l=i?parseInt(i,10)*1e3:5e3;if(!isNaN(l)&&l>0){await Tr(l);let d=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:s.signal});if(d.ok){let p=await d.json();return {accessToken:p.accessToken,refreshToken:p.refreshToken,expiresIn:p.expiresIn,orgId:p.orgId,orgName:p.orgName,userId:p.userId,userName:p.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return n.status===400?{code:"validation_error",message:await wr(n),statusCode:400}:n.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:n.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await wr(n),statusCode:n.status}}catch(n){return n instanceof DOMException&&n.name==="AbortError"?{code:"timeout",message:"Token exchange timed out.",statusCode:null}:{code:"network_error",message:"Failed to reach cloud for token exchange.",statusCode:null}}finally{clearTimeout(a);}}function Je(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 Sr(t,e,r){let s=new AbortController,a=setTimeout(()=>s.abort(),r);try{let n=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:s.signal});if(n.status===429){let i=n.headers.get("Retry-After"),l=i?parseInt(i,10)*1e3:5e3;!isNaN(l)&&l>0&&(await Tr(l),n=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:s.signal}));}if(!n.ok)return null;let o=await n.json();return {accessToken:o.accessToken,refreshToken:o.refreshToken,expiresIn:o.expiresIn}}catch{return null}finally{clearTimeout(a);}}async function Cr(t,e,r,s,a,n){let o=new AbortController,i=setTimeout(()=>o.abort(),a);try{let l={gitId:r,displayName:s};n&&(l.branch=n);let d=await fetch(`${t}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(l),signal:o.signal});if(!d.ok)return null;let p=await d.json();return {repoId:p.repoId,displayName:p.displayName}}catch{return null}finally{clearTimeout(i);}}var xa=5e3;function D(t,e){try{return child_process.execSync(t,{cwd:e,timeout:xa,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function Rr(t){let e=D("git rev-parse --abbrev-ref HEAD",t),r=D("git rev-parse --short HEAD",t),s=D("git log -1 --pretty=%s",t),a=D("git log -1 --format=%an",t)??D("git config user.name",t),n=wa(t),o=n?X(n):null;return {branch:e,commitSha:r,commitMessage:s,commitAuthor:a,remoteUrl:o}}function wa(t){let e=D("git remote get-url origin",t);if(e)return e;let r=D("git remote",t);if(!r)return null;let s=r.split(`
|
|
2559
|
+
`)[0]?.trim();return s?D(`git remote get-url ${s}`,t):null}function X(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 Ar(t){let e=t.split("/").filter(Boolean);return e[e.length-1]??t}function Ye(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 ee(t){let e=Ye(t);return e||`local/${path.basename(t)}`}var ka=new Set(["smoke","regression","nightly","ci"]);function ce(){let t=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(t&&ka.has(t))return t}var Ca=1048576,ue=[1e3,3e3,9e3],pe=3,Ze=90*1048576,Ra=new Set(["e2e","mobile","unit"]);function Xe(t){if(t&&t.length>0&&t.every(a=>a.testType==="api")){let a=new Map;for(let i of t){let l=i.apiProtocol??"rest";a.set(l,(a.get(l)??0)+1);}let n="rest",o=0;for(let[i,l]of a)l>o&&(o=l,n=i);return {testType:"api",apiProtocol:n,metadata:{testType:"api",primaryProtocol:n}}}let e=new Map;for(let a of t??[])Ra.has(a.testType)&&e.set(a.testType,(e.get(a.testType)??0)+1);let r=null,s=0;for(let[a,n]of e)n>s&&(s=n,r=a);return {testType:r??"e2e"}}function et(t,e,r,s,a,n){let o=n?.cloudPlatform?n.cloudPlatform:s?.provider&&s.provider!=="unknown"?s.provider:"local",i=ce(),l=Xe(a),d=l.testType==="api"?l:null,p=d&&a?a.map(m=>m.apiProtocol?m:{...m,apiProtocol:d.apiProtocol}):a;return {runId:t.testRunId,repoGitId:e,startedAt:t.startedAt,summary:t.summary,timeline:t.timeline,environment:o,...i?{runType:i}:{},...d?{testType:d.testType,apiProtocol:d.apiProtocol,metadata:d.metadata}:{testType:l.testType},...p&&p.length>0?{tests:p}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...s?.provider?{ciProvider:s.provider}:{},...s?.runUrl?{ciRunUrl:s.runUrl}:{},...n?.cloudPlatform?{cloudPlatform:n.cloudPlatform}:{},...n?.cloudBuildId?{cloudBuildId:n.cloudBuildId}:{},...n?.cloudSessionId?{cloudSessionId:n.cloudSessionId}:{}}}function Qe(t){return typeof t=="string"?Buffer.byteLength(t,"utf-8"):0}function tt(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:Qe(e.responseBody),bytesOut:typeof e.bytesOut=="number"?e.bytesOut:Qe(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 rt(t){return Array.isArray(t)?t.map(e=>{let r=e.responseStatusCode??e.statusCode??0,s=e.timestamp??null;return {method:e.method??"GET",url:e.url??"",status:r,statusCode:r,type:"xhr",size:Qe(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:s,startedAt:s}}):[]}function st(t){if(!Array.isArray(t))return [];let e=r=>{if(r==null)return String(r);if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}};return t.map(r=>{let s=r.status==="failed"?"failed":"passed",a=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,n=r.kind??r.type??"assertion",o=s==="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:n,description:a??r.description??`${n} assertion`,status:s,detail:o}})}async function fe(t){return new Promise(e=>setTimeout(e,t))}function Aa(t){let e={};for(let[r,s]of Object.entries(t))s!=null&&(e[r]=s);return e}async function _r(t,e,r){for(let s=0;s<pe;s++)try{let a=await fetch(t,e);if(a.ok)return a;if(a.status===401&&r&&s===0){let n=await r();if(n){let o={...e,headers:{...e.headers,Authorization:`Bearer ${n}`}},i=await fetch(t,o);if(i.ok)return i}return null}if(a.status===429&&s<pe-1){let n=a.headers.get("Retry-After"),o=n?parseInt(n,10)*1e3:ue[s];!isNaN(o)&&o>0?await fe(o):await fe(ue[s]);continue}if(a.status>=500&&s<pe-1){await fe(ue[s]);continue}return a}catch{if(s<pe-1){await fe(ue[s]);continue}return null}return null}var Ia=util.promisify(zlib.gzip);function Ir(t,e){if(!Array.isArray(t.tests))return t;let r=t.tests.map(s=>{let{consoleLogs:a,networkRequests:n,apiCalls:o,...i}=s;return e?i:{...i,...o!==void 0?{apiCalls:o}:{}}});return {...t,tests:r}}async function at(t){let e={"Content-Type":"application/json"},r=JSON.stringify(t),s=t,a=Array.isArray(s?.tests)?s.tests.length:0;if(a>0&&Buffer.byteLength(r,"utf-8")>Ze){let n=Math.round(Ze/1048576);process.stderr.write(`[testrelic] WARNING: batch payload exceeds ${n}MB \u2014 dropping consoleLogs/networkRequests from ${a} test(s) to avoid HTTP 413. Console/network detail will be missing in the cloud.
|
|
2560
|
+
`),r=JSON.stringify(Ir(s,false)),Buffer.byteLength(r,"utf-8")>Ze&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${n}MB after dropping logs \u2014 also dropping apiCalls from ${a} test(s). API request/response detail will be missing in the cloud.
|
|
2561
|
+
`),r=JSON.stringify(Ir(s,true)));}return Buffer.byteLength(r,"utf-8")>Ca?(e["Content-Encoding"]="gzip",{body:await Ia(Buffer.from(r,"utf-8")),headers:e}):{body:r,headers:e}}async function Mr(t,e,r,s){let a=`${t}/runs`,{body:n,headers:o}=await at(r);o.Authorization=`Bearer ${e}`;let i=await _r(a,{method:"POST",headers:o,body:n},s);return i?.ok?{success:true,statusCode:i.status,error:null}:i?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:i?`Upload failed with status ${i.status}`:"Upload failed after retries",statusCode:i?.status??null,payload:r,targetEndpoint:a,method:"POST"}}async function Lr(t,e,r){let s=`${t}/runs/init`;try{let a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(Aa(r))});return a.ok?{runId:(await a.json()).runId}:null}catch{return null}}function Er(t,e,r,s){let a=`${t}/runs/${r}/tests`;fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(s)}).catch(()=>{});}async function Pr(t,e,r,s){let a=`${t}/runs/${r}/finalize`;return (await _r(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(s)}))?.ok??false}function nt(t,e,r,s){let a=`${t}/runs/${r}/finalize`,n=new Date,o={finishedAt:n.toISOString(),duration:n.getTime()-new Date(s).getTime(),summary:{}};fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}).catch(()=>{});}var Na="1.0.0",Nr=10;function te(t,e,r,s,a,n,o,i){try{fs$1.mkdirSync(t,{recursive:!0});let l=Date.now(),d=`${l}-${e}-${r}.json`,p=path.join(t,d),f={version:Na,queuedAt:new Date(l).toISOString(),reason:s,retryCount:0,targetEndpoint:a,method:n,payload:o,headers:i},m=p+".tmp";fs$1.writeFileSync(m,JSON.stringify(f,null,2),"utf-8"),fs$1.renameSync(m,p);}catch(l){l.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
|
|
2560
2562
|
`):process.stderr.write(`\u26A0 TestRelic: Unable to queue upload data.
|
|
2561
|
-
`);}}async function
|
|
2562
|
-
`),fs$1.unlinkSync(i);continue}let f=p,
|
|
2563
|
-
`);return}try{if(
|
|
2564
|
-
`);return}let r=await
|
|
2565
|
-
`),await this.resolveRepoId(),this.config.queueDirectory&&(
|
|
2566
|
-
`);}}getMode(){return this.authState.mode}isCloudMode(){return this.authState.mode==="cloud"}isLocalMode(){return this.authState.mode==="local"}getAccessToken(){return this.authState.accessToken}getRepoId(){return this.repoId}getGitMetadata(){return this.gitMetadata}getConfig(){return this.config}getFailureReason(){return this.failureReason}getEndpoint(){return this.config?.endpoint??"https://platform.testrelic.ai/api/v1"}async ensureValidToken(){if(!this.isCloudMode()||!this.authState.accessToken)return false;let e=this.authState.expiresAt??0;if(Date.now()+
|
|
2567
|
-
`));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,new Promise(e=>setTimeout(e,
|
|
2568
|
-
\u2192 Manage keys: ${
|
|
2563
|
+
`);}}async function Br(t,e,r){let s;try{s=fs$1.readdirSync(t).filter(n=>n.endsWith(".json")&&!n.endsWith(".tmp")).sort();}catch{return}if(s.length===0)return;let a=[];for(let n=0;n<s.length;n+=Nr)a.push(s.slice(n,n+Nr));for(let n of a)for(let o of n){let i=path.join(t,o);try{if(!fs$1.statSync(i).isFile())continue;let d=fs$1.readFileSync(i,"utf-8"),p=JSON.parse(d);if(!core.isValidQueueEntry(p)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${o}
|
|
2564
|
+
`),fs$1.unlinkSync(i);continue}let f=p,{body:m,headers:c}=await at(f.payload),u={...f.headers,...c,Authorization:`Bearer ${r}`};if((await fetch(f.targetEndpoint,{method:f.method,headers:u,body:m})).ok)fs$1.unlinkSync(i);else return}catch{return}}}function Or(t,e){try{let r=fs$1.readdirSync(t).filter(a=>a.endsWith(".json")&&!a.endsWith(".tmp")),s=Date.now();for(let a of r){let n=path.join(t,a);try{let o=fs$1.readFileSync(n,"utf-8"),l=JSON.parse(o).queuedAt;if(typeof l=="string"){let d=new Date(l).getTime();s-d>e&&fs$1.unlinkSync(n);}}catch{try{fs$1.unlinkSync(n);}catch{}}}}catch{}}var Ua=3e5,za=864e5,$a=6e4,qr=3e4,lt="https://platform.testrelic.ai/settings/api-keys",he=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.
|
|
2565
|
+
`);return}try{if(kr(this.config.endpoint),this.gitMetadata=Rr(),!await We(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.
|
|
2566
|
+
`);return}let r=await Ke(this.config.endpoint,this.config.apiKey,this.config.timeout);if(Je(r)){this.handleAuthError(r.code,r.statusCode);return}let s=r;this.authState={mode:"cloud",accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:Date.now()+s.expiresIn*1e3,orgId:s.orgId,orgName:s.orgName,userId:s.userId,userName:s.userName},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${s.orgName} / ${s.userName})
|
|
2567
|
+
`),await this.resolveRepoId(),this.config.queueDirectory&&(Or(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)}
|
|
2568
|
+
`);}}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()+Ua<e)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await Sr(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}).
|
|
2569
|
+
`));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,new Promise(e=>setTimeout(e,qr))]);}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.
|
|
2570
|
+
\u2192 Manage keys: ${lt}
|
|
2569
2571
|
`);break;case "expired_key":this.setLocalMode("expired_api_key"),process.stderr.write(`\u26A0 TestRelic: API key has expired. Running in local mode.
|
|
2570
|
-
\u2192 Generate a new key: ${
|
|
2572
|
+
\u2192 Generate a new key: ${lt}
|
|
2571
2573
|
`);break;case "validation_error":this.setLocalMode("validation_error"),process.stderr.write(`\u26A0 TestRelic: API key format invalid. Running in local mode.
|
|
2572
|
-
\u2192 Manage keys: ${
|
|
2574
|
+
\u2192 Manage keys: ${lt}
|
|
2573
2575
|
`);break;case "rate_limited":this.setLocalMode("rate_limited"),process.stderr.write(`\u26A0 TestRelic: Rate limited during authentication. Running in local mode.
|
|
2574
2576
|
`);break;case "timeout":this.setLocalMode("auth_timeout"),process.stderr.write(`\u26A0 TestRelic: Authentication timed out. Running in local mode.
|
|
2575
2577
|
`);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
|
|
2576
|
-
`);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?
|
|
2577
|
-
`);}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
|
|
2578
|
-
`),this.startBackgroundFlush();}}}catch{}}
|
|
2579
|
-
`);}return c||(
|
|
2580
|
-
`),{navigations:
|
|
2581
|
-
`),
|
|
2582
|
-
`).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function
|
|
2583
|
-
`),this.activeReportMode==="streaming"){let n=path.dirname(this.config.outputPath);this.streamingWriter=new
|
|
2584
|
-
`)[0]??null,networkCount:d.networkRequestsCount,consoleCount:d.consoleLogsCount,actionCount:A?.length??0,isRetry:!
|
|
2578
|
+
`);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?X(this.gitMetadata.remoteUrl):null,r=e?Ar(e):this.config.projectName??ee(process.cwd()),s=e??this.config.projectName??ee(process.cwd()),a=this.readRepoCache(s);if(a){this.repoId=a.repoId;return}try{let n=await Cr(this.config.endpoint,this.authState.accessToken,s,r,this.config.timeout,this.gitMetadata?.branch);n&&(this.repoId=n.repoId,this.writeRepoCache(s,n.repoId,n.displayName));}catch{}!e&&!this.config.projectName&&!Ye(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
|
|
2579
|
+
`);}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 s=fs$1.readFileSync(r,"utf-8"),a=JSON.parse(s);if(a.gitId!==e||Date.now()-a.resolvedAt>za)return null;let n=this.hashApiKey();return n&&a.apiKeyHash!==n?null:a}catch{return null}}writeRepoCache(e,r,s){if(!this.config)return;let a=path.join(this.config.queueDirectory,"..","cache"),n=path.join(a,"repo.json");try{fs$1.mkdirSync(a,{recursive:!0});let o={repoId:r,gitId:e,displayName:s,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=n+".tmp";fs$1.writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),fs$1.renameSync(i,n);}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,s=this.config.endpoint;this.flushPromise=Promise.race([Br(r,s,e),new Promise(a=>setTimeout(a,qr))]).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 We(e))return;if(this.config?.apiKey){let s=await Ke(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!Je(s)){let a=s;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.
|
|
2580
|
+
`),this.startBackgroundFlush();}}}catch{}},$a);}};function Hr(t,e,r,s){let a=[],n=[],o=null,i=0,l=null,d=0,p=null,f=0,m=t.filter(g=>g.name===core.ATTACHMENT_NAME&&g.body),c=false;if(m.length>0)for(let g of m)try{let h=JSON.parse(g.body.toString());if(core.isTestRelicFilePayload(h)){a=a.concat(h.navigations),n=n.concat(h.apiAssertions),h.networkRequestsFile&&(o=h.networkRequestsFile,i+=h.networkRequestsCount),h.consoleLogsFile&&(l=h.consoleLogsFile,d+=h.consoleLogsCount),h.apiCallsFile&&(p=h.apiCallsFile,f+=h.apiCallsCount),c=!0;continue}if(core.isTestRelicDataPayload(h)){a=a.concat(h.navigations),Array.isArray(h.apiAssertions)&&(n=n.concat(h.apiAssertions)),i+=h.networkRequests?.length??0,f+=h.apiCalls?.length??0;let w=h.consoleLogs;Array.isArray(w)&&(d+=w.length),c=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
|
|
2581
|
+
`);}return c||(a=e.filter(g=>g.type==="lambdatest-navigation"&&g.description).map(g=>{try{return JSON.parse(g.description)}catch{return null}}).filter(g=>g!==null)),a.length===0&&i===0&&f===0&&!s&&!c&&process.stderr.write(`[testrelic] Warning: No data found for test "${r}". Make sure your tests import { test, expect } from '@testrelic/playwright-analytics/fixture' instead of '@playwright/test'. Without the TestRelic fixture, network logs, video sync, and Test Navigation data cannot be captured.
|
|
2582
|
+
`),{navigations:a,apiAssertions:n,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:l,consoleLogsCount:d,apiCallsFile:p,apiCallsCount:f}}function me(t=process.env){let e=Wa(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 Wa(t){if(!t)return;let e=t.toLowerCase().trim();if(e==="browserstack"||e==="bs")return "browserstack";if(e==="lambdatest"||e==="lt")return "lambdatest"}var Qa=5,ve=[1e3,3e3,9e3],V=3,Xa={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip"},dt=0,ct=[];async function en(){dt>=Qa&&await new Promise(t=>ct.push(t)),dt++;}function tn(){dt--,ct.length>0&&ct.shift()();}async function ye(t){return new Promise(e=>setTimeout(e,t))}function rn(t){let e=t.substring(t.lastIndexOf(".")).toLowerCase();return Xa[e]??"application/octet-stream"}function sn(t){try{return fs$1.statSync(t).size}catch{return 0}}async function an(t,e,r,s,a){let n=`${t}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:path.basename(r.filePath),contentType:a,type:r.type,sizeBytes:s});for(let i=0;i<V;i++)try{let l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:o});if(l.ok)return await l.json();if(l.status>=500&&i<V-1){await ye(ve[i]);continue}return null}catch{if(i<V-1){await ye(ve[i]);continue}return null}return null}async function nn(t,e,r,s){for(let a=0;a<V;a++)try{let n=fs$1.createReadStream(e),o=stream.Readable.toWeb(n),i=await fetch(t,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(s)},body:o,duplex:"half"});if(i.ok)return !0;if(i.status>=500&&a<V-1){await ye(ve[a]);continue}return !1}catch{if(a<V-1){await ye(ve[a]);continue}return false}return false}async function on(t,e,r){let s=`${t}/artifacts/confirm`;try{return (await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({artifactId:r})})).ok}catch{return false}}async function ln(t,e,r,s){let a=sn(r.filePath);if(a===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(a>s*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let n=rn(r.filePath);await en();try{let o=await an(t,e,r,a,n);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await nn(o.uploadUrl,r.filePath,n,a))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let l=await on(t,e,o.artifactId);return {success:l,storageKey:o.storageKey,artifactId:o.artifactId,error:l?null:"confirm_failed"}}finally{tn();}}async function Ur(t,e,r,s){let a=new Map,n=r.map(async o=>{let i=await ln(t,e,o,s);a.set(o.filePath,i);});return await Promise.allSettled(n),a}function ut(t){let r=t.getGitMetadata()?.remoteUrl;return r?X(r):t.getConfig()?.projectName??ee(process.cwd())}async function $r(t,e,r,s,a){if(!t.isCloudMode()||e!=="realtime"&&e!=="both"||!await t.ensureValidToken())return null;let o=t.getGitMetadata(),i=N(),l=me(),d=ce();return (await Lr(t.getEndpoint(),t.getAccessToken(),{runId:r,repoGitId:ut(t),branch:o?.branch??null,commit:o?.commitSha??null,commitMessage:o?.commitMessage??null,commitAuthor:o?.commitAuthor??null,startedAt:s,totalTests:null,ciProvider:i?.provider??null,ciRunUrl:i?.runUrl??null,environment:a??l.cloudPlatform??null,cloudPlatform:l.cloudPlatform??null,cloudBuildId:l.cloudBuildId??null,cloudSessionId:l.cloudSessionId??null,...d?{runType:d}:{},testType:"e2e"}))?.runId??null}var dn=true,cn=50;async function un(t,e,r,s){let a=new Map;if(!(e?.uploadArtifacts??dn)||!await t.ensureValidToken())return a;let i=[],l=new Map;for(let c of s){if(c.artifacts.screenshot){let u=path.join(c.outputDir,c.artifacts.screenshot);i.push({filePath:u,runId:r,testId:c.testId,type:"screenshot"}),l.set(u,{testId:c.testId,field:"screenshot"});}if(c.artifacts.video){let u=path.join(c.outputDir,c.artifacts.video);i.push({filePath:u,runId:r,testId:c.testId,type:"video"}),l.set(u,{testId:c.testId,field:"video"});}}if(i.length===0)return a;let d=e?.artifactMaxSizeMb??cn,p=await Ur(t.getEndpoint(),t.getAccessToken(),i,d),f=new Map;for(let[c,u]of p){if(!u.success||!u.storageKey)continue;let g=l.get(c);if(!g)continue;let h=f.get(g.testId)??{};g.field==="screenshot"&&(h.screenshotKey=u.storageKey),g.field==="video"&&(h.videoKey=u.storageKey),f.set(g.testId,h);}for(let c of s){let u=f.get(c.testId);a.set(c.testId,{...c.artifacts,...u?.screenshotKey?{screenshotKey:u.screenshotKey}:{},...u?.videoKey?{videoKey:u.videoKey}:{}});}let m=Array.from(p.values()).filter(c=>c.success).length;return m>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${m} artifact(s) to cloud storage.
|
|
2583
|
+
`),a}async function pt(t,e,r,s,a,n,o,i,l,d,p){try{if(t.isCloudMode()&&a&&(r==="realtime"||r==="both")){let m=await t.ensureValidToken(),c=t.getGitMetadata(),u=Xe(p),g={finishedAt:o,duration:i,summary:l,...c?.commitMessage?{commitMessage:c.commitMessage}:{},testType:u.testType,...u.testType==="api"?{apiProtocol:u.apiProtocol,metadata:u.metadata}:{}};if(m){if(!await Pr(t.getEndpoint(),t.getAccessToken(),a,g)){let w=e?.queueDirectory??".testrelic/queue";te(w,s,"finalize","finalize_failed_after_retries",`${t.getEndpoint()}/runs/${a}/finalize`,"POST",g,{"Content-Type":"application/json"});}}else {let h=e?.queueDirectory??".testrelic/queue";te(h,s,"finalize",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs/${a}/finalize`,"POST",g,{"Content-Type":"application/json"});}}let f=new Map;if(t.isCloudMode()&&d&&d.length>0&&(f=await un(t,e,s,d)),t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await t.ensureValidToken()){let c=t.getGitMetadata(),u=N(),g=ut(t),h=pn(n,f),w=et(h,g,c,u,p,me()),C=await Mr(t.getEndpoint(),t.getAccessToken(),w,async()=>await t.ensureValidToken()?t.getAccessToken():null);if(!C.success){let y=C,b=e?.queueDirectory??".testrelic/queue";te(b,s,"batch",y.reason,y.targetEndpoint,y.method,y.payload,{"Content-Type":"application/json"});}}else {let c=e?.queueDirectory??".testrelic/queue",u=t.getGitMetadata(),g=N(),h=ut(t),w=et(n,h,u,g,void 0,me());te(c,s,"batch",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs`,"POST",w,{"Content-Type":"application/json"});}await t.dispose();}catch{try{await t.dispose();}catch{}}}function pn(t,e){if(e.size===0)return t;let r=t.timeline.map(s=>{let a=s.testId;if(!a)return s;let n=e.get(a);return n?{...s,...n.screenshotKey?{screenshotKey:n.screenshotKey}:{},...n.videoKey?{videoKey:n.videoKey}:{}}:s});return {...t,timeline:r}}function U(t){try{return fs$1.readFileSync(t,"utf-8").split(`
|
|
2584
|
+
`).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function gt(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 bn(t,e,r){let s=`${t}::${e}::${r}`;return crypto.createHash("sha256").update(s).digest("hex").substring(0,16)}function xn(t){return t.length<=3?"":t[t.length-2]}function wn(t){let e=t.findIndex(r=>r.status==="passed");return e>0?`passed on retry ${e}`:null}function kn(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 Gr(t,e){for(let r of t)e[r.category]=(e[r.category]??0)+1,r.children.length>0&&Gr(r.children,e);}function Tn(t){if(t.length===0)return null;let e=[...t].sort((s,a)=>s-a),r=e.reduce((s,a)=>s+a,0);return {avg:Math.round(r/e.length),min:e[0],max:e[e.length-1],p50:H(e,50),p95:H(e,95),p99:H(e,99)}}function Sn(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 Cn(){let t=os$1.platform();return t==="win32"?"Windows":t==="darwin"?"macOS":"Linux"}function Rn(t){let e=t.parent?.project?.()?.use;if(!e)return;let{browserName:r,channel:s}=e;if(s){let n=s.toLowerCase();return n==="chrome"||n==="chrome-stable"?"Chrome":n.startsWith("chrome-beta")?"Chrome Beta":n.startsWith("chrome-dev")?"Chrome Dev":n.startsWith("chrome-canary")?"Chrome Canary":n==="msedge"||n==="msedge-stable"?"Microsoft Edge":n.startsWith("msedge-beta")?"Edge Beta":n.startsWith("msedge-dev")?"Edge Dev":n.startsWith("msedge-canary")?"Edge Canary":s}if(r){let n=r.toLowerCase();return n==="chromium"?"Chromium":n==="firefox"?"Firefox":n==="webkit"?"WebKit":r}let a=e.defaultBrowserType;if(a){let n=a.toLowerCase();return n==="chromium"?"Chromium":n==="firefox"?"Firefox":n==="webkit"?"WebKit":a}}function An(t,e,r){let s=r.parent?.project?.(),a="unknown";s!==void 0&&(s.use.isMobile===true?a="mobile":a="e2e");let n=["e2e","api","unit","mobile"];for(let l of n)if(t.some(d=>d===`@${l}`||d===l))return l;let o=e.replace(/\\/g,"/"),i=["e2e","api","unit"];for(let l of i)if(o.includes(`/${l}/`))return l;return a}var In="__testrelic_api_config";function _n(t){return JSON.stringify(t,(e,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var be=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.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.streamingAgg={apiUrlSet:new Set,methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,navUrlSet:new Set,actionCategoryCounts:{}};this.config=Ft(e),this.apiConfig=Nt(e);}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 n=r.allTests().length;this.activeReportMode=n>=this.config.streamingThreshold?"streaming":"embedded";}else this.activeReportMode=this.config.reportMode;let s=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${s} tests)
|
|
2585
|
+
`),this.activeReportMode==="streaming"){let n=path.dirname(this.config.outputPath);this.streamingWriter=new K(n);let o=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let i={testRunId:this.testRunId??"",startedAt:this.startedAt,completedAt:new Date().toISOString(),totalDuration:Date.now()-new Date(this.startedAt).getTime(),...this.summaryCounters,metadata:null,reportMode:"streaming",files:[],enrichedSummary:null,validation:null,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(i);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let i=this.cloudClient.getAccessToken();i&&nt(this.cloudClient.getEndpoint(),i,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",o),process.on("SIGINT",o);}if(this.config.includeArtifacts){let n=path.dirname(this.config.outputPath);this.runTimestamp=cr(path.join(n,"artifacts"));try{hr(path.join(n,"artifacts"));}catch{}}let a=N();this.detectedOs=Cn(),this.detectedSource=Sn(a);try{this.cloudClient=new he(this.config.cloud),await this.cloudClient.initialize(),this.cloudRunId=await $r(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource);}catch{this.cloudClient?.switchToLocalMode("init_error");}if(this.activeReportMode!=="streaming"){let n=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let o=this.cloudClient.getAccessToken();o&&nt(this.cloudClient.getEndpoint(),o,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",n),process.on("SIGINT",n);}}catch{}}onTestBegin(e,r){try{e.annotations.push({type:In,description:_n(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let s=r,a=e.outcome(),n;a==="flaky"?n="flaky":a==="skipped"?n="skipped":n=gt(s.status);let o=s.startTime.toISOString(),i=new Date(s.startTime.getTime()+s.duration).toISOString(),l=e.tags?[...e.tags]:e.annotations.filter(I=>I.type==="tag").map(I=>I.description??""),d=Hr(s.attachments,e.annotations,e.title,n==="skipped");(d.navigations.length>0||d.networkRequestsCount>0||d.apiCallsCount>0)&&(this.fixtureDataReceived=!0),d.navigations.length>0&&(this.navigationsCaptured=!0),!this.config.captureNavigation&&d.navigations.length>0&&(d={...d,navigations:[]});let p=null;if(n==="failed"||n==="flaky"){let R=(n==="flaky"?e.results.find(O=>O.status!=="passed")?.errors??[]:s.errors)[0];if(R){let O=Bt(this.config.redactPatterns),G=R.location?.line??null,T=null;this.config.includeCodeSnippets&&G!==null&&R.location?.file&&(T=Dt(R.location.file,G,this.config.codeContextLines),T&&(T=O(T))),p={message:O(R.message??"Unknown error"),line:G,code:T,stack:this.config.includeStackTrace&&R.stack?O(R.stack):null};}}let f=e.titlePath().filter(Boolean),m=path.relative(this.rootDir||".",e.location.file),c=xn(f),u=f.join(" > "),g=m,h=bn(g,c,u),w=An(l,g,e),C=w!=="mobile"&&d.apiCallsCount>0?"api":w,y=a==="flaky",b=wn(e.results),S=gt(e.expectedStatus),v=gt(s.status),k=null;if(this.config.includeArtifacts&&n!=="skipped"&&s.attachments){let I=path.dirname(this.config.outputPath),R=f[f.length-1]??e.title;k=ur(s.attachments,R,s.retry,I,this.runTimestamp||void 0);}let A=this.config.includeActionSteps&&s.steps?xr(s.steps,s.startTime):null,z=Rn(e),E={titlePath:f,title:u,status:n,duration:s.duration,startedAt:o,completedAt:i,retryCount:e.results.length-1,retry:s.retry,tags:l,failure:p,specFile:m,navigations:d.navigations,testId:h,filePath:g,suiteName:c,testType:C,isFlaky:y,retryStatus:b,expectedStatus:S,actualStatus:v,artifacts:k,apiAssertions:d.apiAssertions,actions:A,networkRequestsFile:d.networkRequestsFile,networkRequestsCount:d.networkRequestsCount,consoleLogsFile:d.consoleLogsFile,consoleLogsCount:d.consoleLogsCount,apiCallsFile:d.apiCallsFile,apiCallsCount:d.apiCallsCount,browser:z,os:this.detectedOs||void 0,source:this.detectedSource||void 0},ht=d.consoleLogsFile&&d.consoleLogsCount>0?U(d.consoleLogsFile):void 0,xe=d.networkRequestsFile&&d.networkRequestsCount>0?U(d.networkRequestsFile):void 0,$=d.apiCallsFile&&d.apiCallsCount>0?U(d.apiCallsFile):void 0,mt=$?tt($):void 0,vt=!xe&&$?rt($):void 0,yt=d.apiAssertions&&d.apiAssertions.length>0?st(d.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:h,title:u,status:n,duration:s.duration,suiteName:c,filePath:g,testType:C,isFlaky:y,startedAt:o,completedAt:i,tags:l,failure:p,retry:s.retry,retryCount:e.results.length-1,retryStatus:b,browser:z,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...A&&A.length>0?{actions:A}:{},...d.navigations&&d.navigations.length>0?{navigations:d.navigations}:{},...ht?{consoleLogs:ht}:{},...xe?{networkRequests:xe}:vt?{networkRequests:vt}:{},...mt?{apiCalls:mt}:{},...yt?{protocolAssertions:yt}:{}});try{let I=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(I==="realtime"||I==="both")){let R=this.cloudClient.getAccessToken();R&&Er(this.cloudClient.getEndpoint(),R,this.cloudRunId,this.buildCloudTestPayload(E));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let I=we(g,f,e.id??"",s.retry),R=s.retry===e.results.length-1,O={id:I,navigations:d.navigations,apiAssertions:d.apiAssertions,actions:A??[],artifacts:k,failureDiagnostic:p,hasNetworkFile:d.networkRequestsFile!==null,networkRequestsCount:d.networkRequestsCount,hasConsoleFile:d.consoleLogsFile!==null,consoleLogsCount:d.consoleLogsCount,hasApiCallsFile:d.apiCallsFile!==null,apiCallsCount:d.apiCallsCount,startedAt:o};this.streamingWriter.writeTestDetail(I,O,{networkRequestsFile:d.networkRequestsFile,consoleLogsFile:d.consoleLogsFile,apiCallsFile:d.apiCallsFile});let G={id:I,title:f[f.length-1]??e.title,titlePath:f,filePath:g,status:n,duration:s.duration,project:f[1]??"",retryIndex:s.retry,tags:l,hasNetworkData:d.networkRequestsCount>0,hasConsoleData:d.consoleLogsCount>0,hasArtifacts:k!==null,hasActionSteps:(A?.length??0)>0,errorMessage:p?.message?.split(`
|
|
2586
|
+
`)[0]??null,networkCount:d.networkRequestsCount,consoleCount:d.consoleLogsCount,actionCount:A?.length??0,isRetry:!R};if(this.testIndex.push(G),R)switch(this.summaryCounters.total++,n){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}if(this.summaryCounters.totalApiCalls+=d.apiCallsCount,this.summaryCounters.totalAssertions+=d.apiAssertions.length,this.summaryCounters.totalNavigations+=d.navigations.length,this.summaryCounters.totalNetworkRequests+=d.networkRequestsCount,this.summaryCounters.totalConsoleLogs+=d.consoleLogsCount,this.summaryCounters.totalActionSteps+=A?.length??0,$)for(let T of $){let bt=typeof T.method=="string"?T.method:"OTHER";this.streamingAgg.methodCounts[bt]=(this.streamingAgg.methodCounts[bt]??0)+1;let xt=typeof T.url=="string"?T.url:null;xt&&this.streamingAgg.apiUrlSet.add(je(xt));let Wr=typeof T.responseStatusCode=="number"?T.responseStatusCode:typeof T.statusCode=="number"?T.statusCode:null;this.streamingAgg.statusRanges[kn(Wr)]++;let wt=typeof T.responseTimeMs=="number"?T.responseTimeMs:typeof T.durationMs=="number"?T.durationMs:null;wt!==null&&this.streamingAgg.responseTimes.push(wt);}for(let T of d.apiAssertions)T.status==="passed"?this.streamingAgg.passedAssertions++:this.streamingAgg.failedAssertions++;for(let T of d.navigations)T.url&&this.streamingAgg.navUrlSet.add(T.url);A&&Gr(A,this.streamingAgg.actionCategoryCounts),k&&this.pendingArtifactEntries.push({testId:h,artifacts:k,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(),s=new Date(this.startedAt).getTime(),n=new Date(r).getTime()-s,o=this.activeReportMode==="streaming"?this.testIndex.some(l=>l.status!=="skipped"):this.collectedTests.some(l=>l.status!=="skipped");!this.fixtureDataReceived&&o&&process.stderr.write(`
|
|
2585
2587
|
\u26A0 TestRelic: No fixture data received from any test.
|
|
2586
|
-
To enable network logs, video sync, and
|
|
2588
|
+
To enable network logs, video sync, and Test Navigation tracking, import the TestRelic fixture:
|
|
2587
2589
|
import { test, expect } from '@testrelic/playwright-analytics/fixture';
|
|
2588
2590
|
instead of:
|
|
2589
2591
|
import { test, expect } from '@playwright/test';
|
|
2590
2592
|
|
|
2591
|
-
`),
|
|
2592
|
-
`)
|
|
2593
|
+
`),this.config.captureNavigation?this.fixtureDataReceived&&!this.navigationsCaptured&&o&&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).
|
|
2594
|
+
`):process.stderr.write(`[testrelic] Test Navigation capture is disabled (captureNavigation: false). Remove the option or set it to true to capture the navigation graph.
|
|
2595
|
+
`),await dr();let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let l=path.dirname(this.config.outputPath);i=fr(l,this.runTimestamp);let d=path.join(l,"artifact-manifest.json"),p=JSON.stringify(i),f=d+".tmp";fs$1.writeFileSync(f,p,"utf-8"),fs$1.renameSync(f,d);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await this.finalizeStreamingReport(r,n,e,i);else {let l=this.buildTimeline(),d=new Map;for(let c of this.collectedTests){let u=d.get(c.testId);(!u||c.retry>u.retry)&&d.set(c.testId,c);}let p=Array.from(d.values()),f=br(p,l.length),m={schemaVersion:Te,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:n,summary:f,ci:N(),metadata:this.config.metadata,timeline:l,shardRunIds:null};if(this.writeReport(m),await qe(m,this.config,i),Ve(f,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient){let c=this.collectArtifactEntries(),u=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await pt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,m,r,n,f,c,u);}}}catch{}}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let e=path.dirname(this.config.outputPath),r=[];for(let s of this.collectedTests)s.artifacts&&r.push({testId:s.testId,artifacts:s.artifacts,outputDir:e});return r}async finalizeStreamingReport(e,r,s,a){if(!this.streamingWriter)return;let{totalApiCalls:n,totalAssertions:o,totalNavigations:i,totalNetworkRequests:l,totalConsoleLogs:d,totalActionSteps:p}=this.summaryCounters;this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:n,totalAssertions:o,totalNavigations:i,totalNetworkRequests:l,totalConsoleLogs:d,totalActionSteps:p};let f=new Map,m=new Map;for(let b of this.testIndex){let S=`${b.filePath}::${b.titlePath.join(" > ")}`,v=f.get(S);(v===void 0||b.retryIndex>v)&&f.set(S,b.retryIndex);}let c=0;for(let b of this.testIndex){let S=`${b.filePath}::${b.titlePath.join(" > ")}`,v=f.get(S);if(b.isRetry=b.retryIndex<v,b.isRetry)continue;switch(c++,this.summaryCounters.total++,b.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}let k=m.get(b.filePath);switch(k||(k={filePath:b.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},m.set(b.filePath,k)),k.total++,b.status){case "passed":k.passed++;break;case "failed":k.failed++;break;case "flaky":k.flaky++;break;case "skipped":k.skipped++;break;case "timedout":k.timedOut++;break}}let u=Array.from(m.values());this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let g={reporterTotal:this.summaryCounters.total,indexTotal:c,playwrightStatus:s.status,isValid:this.summaryCounters.total===c};g.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${g.reporterTotal}, index: ${g.indexTotal}
|
|
2596
|
+
`);let h={total:this.summaryCounters.total,passed:this.summaryCounters.passed,failed:this.summaryCounters.failed,flaky:this.summaryCounters.flaky,skipped:this.summaryCounters.skipped,timedout:this.summaryCounters.timedOut,totalApiCalls:this.summaryCounters.totalApiCalls,uniqueApiUrls:this.streamingAgg.apiUrlSet.size,apiCallsByMethod:{...this.streamingAgg.methodCounts},apiCallsByStatusRange:{"2xx":this.streamingAgg.statusRanges["2xx"],"3xx":this.streamingAgg.statusRanges["3xx"],"4xx":this.streamingAgg.statusRanges["4xx"],"5xx":this.streamingAgg.statusRanges["5xx"],error:this.streamingAgg.statusRanges.error},apiResponseTime:Tn(this.streamingAgg.responseTimes),totalAssertions:this.summaryCounters.totalAssertions,passedAssertions:this.streamingAgg.passedAssertions,failedAssertions:this.streamingAgg.failedAssertions,totalNavigations:this.summaryCounters.totalNavigations,uniqueNavigationUrls:this.streamingAgg.navUrlSet.size,totalTimelineSteps:this.testIndex.length,totalActionSteps:this.summaryCounters.totalActionSteps,actionStepsByCategory:{...this.streamingAgg.actionCategoryCounts}},w={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:e,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:u,enrichedSummary:h,validation:g,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(w);let C={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(C),await qe(this.buildStreamingReport(w,h,e,r),this.config,a),Ve(h,this.config.outputPath,this.config.htmlReportPath,this.config.quiet);let y=this.streamingWriter.getReportDir();if(process.stderr.write(`[testrelic] Streaming report written to ${y}
|
|
2593
2597
|
[testrelic] ${this.testIndex.length} test detail files on disk
|
|
2594
2598
|
[testrelic] View report: npx testrelic serve ${y}
|
|
2595
2599
|
`),this.streamingWriter.getWriteErrors().length>0&&process.stderr.write(`[testrelic] WARNING: ${this.streamingWriter.getWriteErrors().length} write error(s) during streaming
|
|
2596
|
-
`),this.streamingWriter.dispose(),this.cloudClient){let
|
|
2597
|
-
`),this.switchToStreamingMode()):
|
|
2598
|
-
`);}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let e=path.dirname(this.config.outputPath);this.streamingWriter=new
|
|
2599
|
-
`)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,isRetry:!1};switch(this.testIndex.push(n),this.summaryCounters.total++,r.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.summaryCounters.totalApiCalls+=r.apiCallsCount,this.summaryCounters.totalAssertions+=r.apiAssertions?.length??0,this.summaryCounters.totalNavigations+=r.navigations?.length??0,this.summaryCounters.totalNetworkRequests+=r.networkRequestsCount,this.summaryCounters.totalConsoleLogs+=r.consoleLogsCount,this.summaryCounters.totalActionSteps+=r.actions?.length??0;}this.collectedTests.length=0;}catch{}}buildTimeline(){let e=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls:null,apiAssertions:r.apiAssertions,testId:r.testId,filePath:r.filePath,suiteName:r.suiteName,testType:r.testType,isFlaky:r.isFlaky,retryStatus:r.retryStatus,expectedStatus:r.expectedStatus,actualStatus:r.actualStatus,artifacts:r.artifacts,networkRequests:null,actions:r.actions,consoleLogs:null}));return
|
|
2600
|
-
`);}}};module.exports=
|
|
2600
|
+
`),this.streamingWriter.dispose(),this.cloudClient){let b=this.buildStreamingReport(w,h,e,r),S=this.collectArtifactEntries(),v=this.cloudTestsBuffer.slice();this.cloudTestsBuffer.length=0,await pt(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,b,e,r,h,S,v);}this.testIndex.length=0,this.collectedTests.length=0,this.pendingArtifactEntries.length=0,this.cloudTestsBuffer.length=0,this.streamingWriter=null,this.cloudClient=null;}buildStreamingReport(e,r,s,a){return {schemaVersion:Te,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:s,totalDuration:a,summary:r,ci:N(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let e=process.memoryUsage(),r=e.heapUsed/1024/1024;if(r<200)return;let s=e.heapUsed/e.heapTotal;s>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
|
|
2601
|
+
`),this.switchToStreamingMode()):s>.8&&process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
|
|
2602
|
+
`);}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let e=path.dirname(this.config.outputPath);this.streamingWriter=new K(e);for(let r of this.collectedTests){let s=we(r.filePath,r.titlePath,r.testId,r.retry),a={id:s,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(s,a,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let n={id:s,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(`
|
|
2603
|
+
`)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,isRetry:!1};switch(this.testIndex.push(n),this.summaryCounters.total++,r.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.summaryCounters.totalApiCalls+=r.apiCallsCount,this.summaryCounters.totalAssertions+=r.apiAssertions?.length??0,this.summaryCounters.totalNavigations+=r.navigations?.length??0,this.summaryCounters.totalNetworkRequests+=r.networkRequestsCount,this.summaryCounters.totalConsoleLogs+=r.consoleLogsCount,this.summaryCounters.totalActionSteps+=r.actions?.length??0;}this.collectedTests.length=0;}catch{}}buildTimeline(){let e=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls:null,apiAssertions:r.apiAssertions,testId:r.testId,filePath:r.filePath,suiteName:r.suiteName,testType:r.testType,isFlaky:r.isFlaky,retryStatus:r.retryStatus,expectedStatus:r.expectedStatus,actualStatus:r.actualStatus,artifacts:r.artifacts,networkRequests:null,actions:r.actions,consoleLogs:null}));return yr(e,{navigationTypes:this.config.navigationTypes})}readJsonlFile(e){if(!e)return null;let r=U(e);return r.length>0?r:null}toTestResult(e,r){let s=null,a=null,n=null;return r?.loadFiles&&(s=this.readJsonlFile(e.networkRequestsFile),a=this.readJsonlFile(e.consoleLogsFile),n=this.readJsonlFile(e.apiCallsFile)),{title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,retryStatus:e.retryStatus,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,networkRequests:s,apiCalls:n,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=st(e.apiAssertions)),e.consoleLogsFile&&(r.consoleLogs=U(e.consoleLogsFile)),e.networkRequestsFile&&(r.networkRequests=U(e.networkRequestsFile)),e.apiCallsFile){let s=U(e.apiCallsFile);r.apiCalls=tt(s),(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=rt(s));}return r}writeReport(e){try{let r=JSON.stringify(e),s=this.config.outputPath,a=path.dirname(s);fs$1.mkdirSync(a,{recursive:!0});let n=s+".tmp";fs$1.writeFileSync(n,r,"utf-8"),fs$1.renameSync(n,s);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
|
|
2604
|
+
`);}}};module.exports=be;//# sourceMappingURL=reporter-entry.cjs.map
|
|
2601
2605
|
//# sourceMappingURL=reporter-entry.cjs.map
|