@testrelic/playwright-analytics 2.16.4-next.193 → 2.16.4-next.230
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api-fixture.cjs +7 -7
- package/dist/api-fixture.cjs.map +1 -1
- package/dist/api-fixture.d.cts +4 -1
- package/dist/api-fixture.d.ts +4 -1
- package/dist/api-fixture.js +7 -7
- package/dist/api-fixture.js.map +1 -1
- package/dist/cli.cjs +7 -2
- package/dist/fixture-marker-Buz_DCfv.d.cts +34 -0
- package/dist/fixture-marker-Buz_DCfv.d.ts +34 -0
- package/dist/fixture.cjs +6 -6
- package/dist/fixture.cjs.map +1 -1
- package/dist/fixture.d.cts +6 -1
- package/dist/fixture.d.ts +6 -1
- package/dist/fixture.js +6 -6
- package/dist/fixture.js.map +1 -1
- package/dist/index.cjs +112 -112
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +112 -112
- package/dist/index.js.map +1 -1
- package/dist/reporter-entry.cjs +107 -107
- package/dist/reporter-entry.cjs.map +1 -1
- package/dist/reporter-entry.d.cts +10 -0
- package/dist/reporter-entry.d.ts +10 -0
- package/dist/reporter-entry.js +107 -107
- package/dist/reporter-entry.js.map +1 -1
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});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'),test=require('@playwright/test'),perf_hooks=require('perf_hooks'),url=require('url');var
|
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});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'),test=require('@playwright/test'),perf_hooks=require('perf_hooks'),url=require('url');var Ia=".testrelic-report";function dt(t,e,r,n){let s=`${t}|${e.join("|")}|${r}|${n}`;return crypto.createHash("sha256").update(s).digest("hex").substring(0,12)}function ct(t,e,r){let n=`${t}|${e.join("|")}|${r}`;return crypto.createHash("sha256").update(n).digest("hex").substring(0,12)}var ve=class{constructor(e){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=path.join(e,Ia),this.testsDir=path.join(this.reportDir,"tests"),fs$1.mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}getTestDetailPaths(e){let r=path.join(this.testsDir,e);return {meta:path.join(r,"meta.json"),networkRequests:path.join(r,"network.jsonl"),consoleLogs:path.join(r,"console.jsonl"),apiCalls:path.join(r,"api-calls.jsonl")}}writeTestDetail(e,r,n){try{let s=path.join(this.testsDir,e);fs$1.mkdirSync(s,{recursive:!0});let a=this.getTestDetailPaths(e),i=a.meta,o=i+".tmp",l=JSON.stringify(r);return fs$1.writeFileSync(o,l,"utf-8"),fs$1.renameSync(o,i),this.totalBytesWritten+=Buffer.byteLength(l,"utf-8"),n?.networkRequestsFile&&this.moveFile(n.networkRequestsFile,a.networkRequests),n?.consoleLogsFile&&this.moveFile(n.consoleLogsFile,a.consoleLogs),n?.apiCallsFile&&this.moveFile(n.apiCallsFile,a.apiCalls),!0}catch(s){let a=s instanceof Error?s.message:String(s);return this.writeErrors.push({testId:e,error:a,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${e}: ${a}
|
|
2
2
|
`),false}}moveFile(e,r){try{fs$1.renameSync(e,r);}catch{try{fs$1.copyFileSync(e,r);try{fs$1.unlinkSync(e);}catch{}}catch(n){process.stderr.write(`[testrelic] Failed to move file ${e} \u2192 ${r}: ${n instanceof Error?n.message:String(n)}
|
|
3
|
-
`);}}}writeIndex(e){let r=path.join(this.reportDir,"index.json"),n=r+".tmp",s=JSON.stringify(e);fs$1.writeFileSync(n,s,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeCompactIndex(e){let r=path.join(this.reportDir,"index-compact.json"),n=r+".tmp",s=e.map(({titlePath:i,project:o,...l})=>l),a=JSON.stringify(s);fs$1.writeFileSync(n,a,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}writeSummary(e){let r=path.join(this.reportDir,"summary.json"),n=r+".tmp",s=JSON.stringify(e);fs$1.writeFileSync(n,s,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeManifest(e){let r=path.join(this.reportDir,"manifest.json"),n=r+".tmp",s=JSON.stringify(e);fs$1.writeFileSync(n,s,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var
|
|
4
|
-
`),s}catch{}let a=path.dirname(e);if(a===e)break;e=a;}return null}function
|
|
5
|
-
`);let c=t.queue;if(c&&typeof c=="object"){if(typeof c.maxAge=="string"){let
|
|
3
|
+
`);}}}writeIndex(e){let r=path.join(this.reportDir,"index.json"),n=r+".tmp",s=JSON.stringify(e);fs$1.writeFileSync(n,s,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeCompactIndex(e){let r=path.join(this.reportDir,"index-compact.json"),n=r+".tmp",s=e.map(({titlePath:i,project:o,...l})=>l),a=JSON.stringify(s);fs$1.writeFileSync(n,a,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}writeSummary(e){let r=path.join(this.reportDir,"summary.json"),n=r+".tmp",s=JSON.stringify(e);fs$1.writeFileSync(n,s,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeManifest(e){let r=path.join(this.reportDir,"manifest.json"),n=r+".tmp",s=JSON.stringify(e);fs$1.writeFileSync(n,s,"utf-8"),fs$1.renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var $r=".testrelic",Da="testrelic-config.json",Fa=".testrelic",Ba=5,Oa=new Set(["__proto__","constructor","prototype"]),jr=Object.freeze({apiKey:null,endpoint:"https://platform.testrelic.ai/api/v1",uploadStrategy:"batch",timeout:3e4,uploadBudgetMs:12e4,projectName:null,queueMaxAge:6048e5,queueDirectory:`${$r}/queue`,uploadArtifacts:true,artifactMaxSizeMb:50}),qa={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function Wr(t){let e=path.resolve(t);for(let r=0;r<=Ba;r++){let n=path.join(e,$r,Da);if(fs$1.existsSync(n))try{if(fs$1.statSync(n).isFile())return n}catch{}let s=path.join(e,Fa);if(fs$1.existsSync(s))try{if(fs$1.statSync(s).isFile())return process.stderr.write(`[testrelic] Deprecation: config file ".testrelic" has moved to ".testrelic/testrelic-config.json". Please migrate your config file to the new location.
|
|
4
|
+
`),s}catch{}let a=path.dirname(e);if(a===e)break;e=a;}return null}function Gr(t){try{let e=fs$1.readFileSync(t,"utf-8"),r=JSON.parse(e);return typeof r!="object"||r===null||Array.isArray(r)||!Kr(r)?null:r}catch{return null}}function Kr(t){for(let e of Object.keys(t)){if(Oa.has(e))return false;let r=t[e];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!Kr(r))return false}return true}function Jr(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 ut(t){let e=Object.create(null);for(let r of Object.keys(t)){let n=t[r];typeof n=="string"&&n.startsWith("$")?e[r]=Jr(n):typeof n=="object"&&n!==null&&!Array.isArray(n)?e[r]=ut(n):e[r]=n;}return e}function Vr(t){let e=/^(\d+)\s*([smhd])$/.exec(t.trim());if(!e)return null;let r=parseInt(e[1],10),n=e[2],s=qa[n];return !s||r<=0?null:r*s}function Yr(t,e){let r=Object.create(null);if(Object.assign(r,jr),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.uploadBudgetMs=="number"&&(r.uploadBudgetMs=l.uploadBudgetMs),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 c=t.queue;if(c&&typeof c=="object"){if(typeof c.maxAge=="string"){let p=Vr(c.maxAge);p!==null&&(r.queueMaxAge=p);}typeof c.directory=="string"&&(r.queueDirectory=c.directory);}}if(e){if(typeof e.apiKey=="string"&&e.apiKey.length>0){let l=e.apiKey.startsWith("$")?Jr(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.uploadBudgetMs=="number"&&(r.uploadBudgetMs=e.uploadBudgetMs),typeof e.projectName=="string"&&(r.projectName=e.projectName),typeof e.queueMaxAge=="string"){let l=Vr(e.queueMaxAge);l!==null&&(r.queueMaxAge=l);}typeof e.queueDirectory=="string"&&(r.queueDirectory=e.queueDirectory),typeof e.uploadArtifacts=="boolean"&&(r.uploadArtifacts=e.uploadArtifacts),typeof e.artifactMaxSizeMb=="number"&&(r.artifactMaxSizeMb=e.artifactMaxSizeMb);}let n=process.env.TESTRELIC_API_KEY;n&&n.length>0&&(r.apiKey=n);let s=process.env.TESTRELIC_CLOUD_ENDPOINT;s&&core.isValidEndpointUrl(s)&&(r.endpoint=s);let a=process.env.TESTRELIC_UPLOAD_STRATEGY;a&&["batch","realtime","both"].includes(a)&&(r.uploadStrategy=a);let i=process.env.TESTRELIC_CLOUD_TIMEOUT;if(i){let l=parseInt(i,10);!isNaN(l)&&l>=1e3&&l<=12e4&&(r.timeout=l);}let o=Object.freeze(r);return core.isValidCloudConfig(o)?o:jr}var ja=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],Va=["authorization","cookie","set-cookie","x-api-key"],$a=["password","secret","token","apiKey","api_key"];function Xr(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??[...Va],e.redactBodyFields=t?.redactBodyFields??[...$a],e.apiIncludeUrls=t?.apiIncludeUrls??[],e.apiExcludeUrls=t?.apiExcludeUrls??[],Object.freeze(e)}function Zr(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=[...ja,...t?.redactPatterns??[]],e.testRunId=t?.testRunId??null,e.metadata=t?.metadata??null;let r=e.outputPath;e.openReport=t?.openReport??true,e.htmlReportPath=t?.htmlReportPath??r.replace(/\.json$/,".html"),e.includeArtifacts=t?.includeArtifacts??true,e.trackApiCalls=t?.trackApiCalls??true,e.quiet=t?.quiet??false,e.includeActionSteps=t?.includeActionSteps??true,e.captureConsoleLogs=t?.captureConsoleLogs??true;let n=Wr(process.cwd()),s=n?Gr(n):null,a=s?ut(s):null,i=Yr(a,t?.cloud);return e.cloud=i.apiKey?i:null,e.reportMode=t?.reportMode??"streaming",e.streamingThreshold=t?.streamingThreshold??0,Object.freeze(e)}var Ae="1.10.0";function Qr(t,e,r){try{let s=fs$1.readFileSync(t,"utf-8").split(`
|
|
6
6
|
`);if(e<1||e>s.length)return null;let a=Math.max(1,e-r),i=Math.min(s.length,e+r),o=[];for(let l=a;l<=i;l++){let d=l===e?">":" ",c=String(l).padStart(String(i).length," ");o.push(`${d} ${c} | ${s[l-1]}`);}return o.join(`
|
|
7
|
-
`)}catch{return null}}function
|
|
7
|
+
`)}catch{return null}}function en(t){return e=>{let r=e;for(let n of t)if(typeof n=="string"){let s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(s,"g"),"[REDACTED]");}else {let s=n.flags.includes("g")?n.flags:n.flags+"g",a=new RegExp(n.source,s);r=r.replace(a,"[REDACTED]");}return r}}function Ga(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 Ka(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 Ja(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 Ya(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 Xa(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 Za=[Ga,Ka,Ja,Ya,Xa];function G(t){let e=process.env;for(let r of Za){let n=r(e);if(n)return n}return null}var pt=`
|
|
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;
|
|
@@ -570,15 +570,15 @@ body{
|
|
|
570
570
|
.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}
|
|
571
571
|
.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}
|
|
572
572
|
.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}
|
|
573
|
-
`;var
|
|
573
|
+
`;var ft=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 196 247" fill="none">
|
|
574
574
|
<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)"/>
|
|
575
575
|
<defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
|
|
576
576
|
<stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
|
|
577
|
-
</linearGradient></defs></svg>`,
|
|
577
|
+
</linearGradient></defs></svg>`,gt=`<svg width="32" height="40" viewBox="0 0 196 247" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
578
578
|
<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)"/>
|
|
579
579
|
<defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
|
|
580
580
|
<stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
|
|
581
|
-
</linearGradient></defs></svg>`;var
|
|
581
|
+
</linearGradient></defs></svg>`;var ht={"failed|failed":"passed","failed|passed":"failed"},tn={"failed|failed":"Failed as expected","failed|passed":"Expected to fail, but passed."};function Qa(t,e){return `${e??"passed"}|${t}`}function ei(t,e){return ht[Qa(t,e)]??t}function mt(t,e){let r={passed:t.passed,failed:t.failed,flaky:t.flaky,skipped:t.skipped,timedout:t.timedout},n=0,s=0;for(let a of e){let i=ei(a.status,a.expectedStatus);i!==a.status&&(r[a.status]--,r[i]++,i==="passed"?n++:s++);}return {total:t.total,...r,expectedFailures:n,unexpectedPasses:s}}var vt=`
|
|
582
582
|
/* \u2500\u2500 Utilities \u2500\u2500 */
|
|
583
583
|
function esc(s){if(!s)return '';return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,''')}
|
|
584
584
|
function stripAnsi(s){return s?s.replace(/\\u001b\\[[0-9;]*m/g,'').replace(/\\x1b\\[[0-9;]*m/g,''):''}
|
|
@@ -595,7 +595,7 @@ body{
|
|
|
595
595
|
interpolated as JSON data (not code), so the report and the terminal box
|
|
596
596
|
cannot disagree about a pair. Defined before the data transformation
|
|
597
597
|
below, which is their first caller. */
|
|
598
|
-
var PW_VERDICT=${JSON.stringify(
|
|
598
|
+
var PW_VERDICT=${JSON.stringify(ht)};var PW_NOTE=${JSON.stringify(tn)};
|
|
599
599
|
function pwKey(s,e){return (e||'passed')+'|'+s;}
|
|
600
600
|
function pwVerdict(s,e){return PW_VERDICT[pwKey(s,e)]||s;}
|
|
601
601
|
function pwNote(s,e){return PW_NOTE[pwKey(s,e)]||null;}
|
|
@@ -1279,7 +1279,7 @@ body{
|
|
|
1279
1279
|
clearTimeout(_searchTimer);
|
|
1280
1280
|
_searchTimer=setTimeout(function(){searchQuery=q;applyFilters();},150);
|
|
1281
1281
|
}
|
|
1282
|
-
`;var
|
|
1282
|
+
`;var yt=`
|
|
1283
1283
|
/* \u2500\u2500 Network Visualization Helpers \u2500\u2500 */
|
|
1284
1284
|
var RES_COLORS={xhr:'#60a5fa',document:'#818cf8',script:'#fbbf24',stylesheet:'#a78bfa',image:'#34d399',font:'#f472b6',other:'#6b7280'};
|
|
1285
1285
|
var RES_LABELS={xhr:'XHR',document:'Doc',script:'JS',stylesheet:'CSS',image:'Img',font:'Font',other:'Other'};
|
|
@@ -2014,7 +2014,7 @@ body{
|
|
|
2014
2014
|
var countEl=ndt.querySelector('.ndt-count');
|
|
2015
2015
|
if(countEl)countEl.textContent=visible+' / '+rows.length+' requests';
|
|
2016
2016
|
}
|
|
2017
|
-
`;var
|
|
2017
|
+
`;var bt=`
|
|
2018
2018
|
var _filterState={status:{},type:{},specFile:{},visual:{},evidence:{}};
|
|
2019
2019
|
|
|
2020
2020
|
/* Evidence filters: one predicate per chip, so API and mobile runs share the
|
|
@@ -2273,7 +2273,7 @@ function _updateCard(cls,val){
|
|
|
2273
2273
|
var el=document.querySelector('.'+cls+' .s-count');
|
|
2274
2274
|
if(el)el.textContent=''+val;
|
|
2275
2275
|
}
|
|
2276
|
-
`;var
|
|
2276
|
+
`;var xt=`
|
|
2277
2277
|
/* \u2500\u2500 Event Delegation \u2500\u2500 */
|
|
2278
2278
|
document.addEventListener('click',function(e){
|
|
2279
2279
|
var target=e.target;
|
|
@@ -2544,7 +2544,7 @@ function _updateCard(cls,val){
|
|
|
2544
2544
|
var d=document.getElementById('filter-drawer');if(d)d.classList.remove('open');
|
|
2545
2545
|
var b=document.getElementById('filter-drawer-backdrop');if(b)b.classList.remove('open');
|
|
2546
2546
|
}
|
|
2547
|
-
`;var
|
|
2547
|
+
`;var wt=`
|
|
2548
2548
|
/* \u2500\u2500 Category badge helpers \u2500\u2500 */
|
|
2549
2549
|
function actionBadgeClass(cat){
|
|
2550
2550
|
if(cat==='assertion')return 'action-badge-assertion';
|
|
@@ -2590,7 +2590,7 @@ function _updateCard(cls,val){
|
|
|
2590
2590
|
h+='</div>';
|
|
2591
2591
|
return h;
|
|
2592
2592
|
}
|
|
2593
|
-
`;var
|
|
2593
|
+
`;var kt=`
|
|
2594
2594
|
/* \u2500\u2500 Console Log Level Colors & Labels \u2500\u2500 */
|
|
2595
2595
|
var LOG_COLORS={log:'#9ca3af',warn:'#fbbf24',error:'#f87171',info:'#60a5fa',debug:'#a78bfa',stdout:'#9ca3af',stderr:'#f87171'};
|
|
2596
2596
|
var LOG_LABELS={log:'LOG',warn:'WARN',error:'ERR',info:'INFO',debug:'DBG',stdout:'OUT',stderr:'ERR'};
|
|
@@ -2777,7 +2777,7 @@ function _updateCard(cls,val){
|
|
|
2777
2777
|
}
|
|
2778
2778
|
return h;
|
|
2779
2779
|
}
|
|
2780
|
-
`;var
|
|
2780
|
+
`;var Ct=`
|
|
2781
2781
|
/* \u2500\u2500 Artifact Utilities \u2500\u2500 */
|
|
2782
2782
|
function formatBytes(bytes){
|
|
2783
2783
|
if(bytes===0)return '0 B';
|
|
@@ -2786,7 +2786,7 @@ function _updateCard(cls,val){
|
|
|
2786
2786
|
if(i>=sizes.length)i=sizes.length-1;
|
|
2787
2787
|
return parseFloat((bytes/Math.pow(k,i)).toFixed(1))+' '+sizes[i];
|
|
2788
2788
|
}
|
|
2789
|
-
`;var
|
|
2789
|
+
`;var Tt=`
|
|
2790
2790
|
/* \u2500\u2500 Visual Regression \u2500\u2500 */
|
|
2791
2791
|
|
|
2792
2792
|
function visStatusLabel(status){
|
|
@@ -2943,7 +2943,7 @@ function _updateCard(cls,val){
|
|
|
2943
2943
|
if(otop)otop.style.opacity=String(el.value/100);
|
|
2944
2944
|
}
|
|
2945
2945
|
});
|
|
2946
|
-
`;var
|
|
2946
|
+
`;var St=`
|
|
2947
2947
|
/* \u2500\u2500 DOM comparison \u2500\u2500 */
|
|
2948
2948
|
|
|
2949
2949
|
/* Rank-cycled so a row and its box always share a colour. */
|
|
@@ -3095,7 +3095,7 @@ function _updateCard(cls,val){
|
|
|
3095
3095
|
var card=row.closest('.vis-card');
|
|
3096
3096
|
if(card&&!row.classList.contains('pinned'))domSetActive(card,row.getAttribute('data-dom-row'),false);
|
|
3097
3097
|
});
|
|
3098
|
-
`;var
|
|
3098
|
+
`;var Rt=`
|
|
3099
3099
|
/* \u2500\u2500 Verdict band \u2500\u2500 */
|
|
3100
3100
|
|
|
3101
3101
|
/* Both report modes hand us a summary; streaming's carries fewer fields. */
|
|
@@ -3416,7 +3416,7 @@ function _updateCard(cls,val){
|
|
|
3416
3416
|
if(!card)return;
|
|
3417
3417
|
openTest(card.getAttribute('data-testid'));
|
|
3418
3418
|
});
|
|
3419
|
-
`,
|
|
3419
|
+
`,At=`
|
|
3420
3420
|
var overviewViewEl=document.getElementById('view-overview');
|
|
3421
3421
|
var detailViewEl=document.getElementById('view-detail');
|
|
3422
3422
|
var detailNavEl=document.getElementById('detail-nav');
|
|
@@ -3557,7 +3557,7 @@ function _updateCard(cls,val){
|
|
|
3557
3557
|
|
|
3558
3558
|
window.addEventListener('hashchange',routeFromHash);
|
|
3559
3559
|
window.addEventListener('popstate',routeFromHash);
|
|
3560
|
-
`;var
|
|
3560
|
+
`;var _t=`
|
|
3561
3561
|
var API_METHOD_COLOR={GET:'#60a5fa',POST:'#34d399',PUT:'#fbbf24',PATCH:'#a78bfa',DELETE:'#f87171',HEAD:'#6b7280',OPTIONS:'#6b7280'};
|
|
3562
3562
|
var API_STATUS_ORDER=['2xx','3xx','4xx','5xx','error'];
|
|
3563
3563
|
var API_STATUS_COLOR={'2xx':'#22c55e','3xx':'#60a5fa','4xx':'#fb923c','5xx':'#ef4444','error':'#ef4444'};
|
|
@@ -3783,7 +3783,7 @@ function _updateCard(cls,val){
|
|
|
3783
3783
|
}
|
|
3784
3784
|
return '';
|
|
3785
3785
|
}
|
|
3786
|
-
`;var
|
|
3786
|
+
`;var It=`
|
|
3787
3787
|
.vis-header{font-size:11px;font-weight:700;color:var(--fg-1);text-transform:uppercase;letter-spacing:.06em;margin-bottom:12px;display:flex;align-items:center;gap:6px}
|
|
3788
3788
|
.vis-header svg{opacity:.6}
|
|
3789
3789
|
.vis-count{font-weight:400;color:var(--fg-2);font-size:10px}
|
|
@@ -3816,7 +3816,7 @@ function _updateCard(cls,val){
|
|
|
3816
3816
|
|
|
3817
3817
|
/* A checkerboard behind the diff so fully transparent regions stay legible. */
|
|
3818
3818
|
.vis-diff-wrap{background-image:linear-gradient(45deg,var(--bd-xs) 25%,transparent 25%),linear-gradient(-45deg,var(--bd-xs) 25%,transparent 25%),linear-gradient(45deg,transparent 75%,var(--bd-xs) 75%),linear-gradient(-45deg,transparent 75%,var(--bd-xs) 75%);background-size:16px 16px;background-position:0 0,0 8px,8px -8px,-8px 0;border-radius:8px}
|
|
3819
|
-
`,
|
|
3819
|
+
`,Mt=`
|
|
3820
3820
|
.dom-figure{position:relative;line-height:0;border:1px solid var(--bd);border-radius:8px;overflow:hidden;margin-bottom:12px}
|
|
3821
3821
|
.dom-img{display:block;width:100%;height:auto}
|
|
3822
3822
|
.dom-ov{position:absolute;top:0;left:0;right:0;bottom:0;pointer-events:none}
|
|
@@ -3848,7 +3848,7 @@ function _updateCard(cls,val){
|
|
|
3848
3848
|
.dom-from{color:#ef4444;word-break:break-all}
|
|
3849
3849
|
.dom-arrow{color:var(--fg-2)}
|
|
3850
3850
|
.dom-to{color:#2dd4a8;word-break:break-all}
|
|
3851
|
-
`;var
|
|
3851
|
+
`;var Pt=`
|
|
3852
3852
|
/* \u2500\u2500 Wider shell \u2500\u2500
|
|
3853
3853
|
960px was sized for a list. The row now carries evidence and timing, and
|
|
3854
3854
|
the detail panel shows two screenshots side by side; both were cramped. */
|
|
@@ -3975,7 +3975,7 @@ function _updateCard(cls,val){
|
|
|
3975
3975
|
.verdict{flex-direction:column}
|
|
3976
3976
|
.verdict-side{width:100%}
|
|
3977
3977
|
}
|
|
3978
|
-
`,
|
|
3978
|
+
`,Et=`
|
|
3979
3979
|
/* The overlay is gone. Anything still carrying .drawer must not float. */
|
|
3980
3980
|
.drawer,.drawer-backdrop{display:none}
|
|
3981
3981
|
|
|
@@ -3996,7 +3996,7 @@ function _updateCard(cls,val){
|
|
|
3996
3996
|
/* The page scrolls now, so the old panel body must not scroll inside it. */
|
|
3997
3997
|
#view-detail .drawer-body{flex:none;overflow:visible;padding:0}
|
|
3998
3998
|
.detail-page .detail-rail,.detail-page .drawer-rail{top:16px}
|
|
3999
|
-
`;var
|
|
3999
|
+
`;var Lt=`
|
|
4000
4000
|
/* \u2500\u2500 Run-level type band \u2500\u2500 */
|
|
4001
4001
|
.tband{display:grid;gap:16px;margin-bottom:20px}
|
|
4002
4002
|
.tband-3{grid-template-columns:1.1fr 1.1fr .9fr}
|
|
@@ -4094,21 +4094,21 @@ function _updateCard(cls,val){
|
|
|
4094
4094
|
@media (max-width:1100px){
|
|
4095
4095
|
.tband-3,.tband-2{grid-template-columns:1fr}
|
|
4096
4096
|
}
|
|
4097
|
-
`;var
|
|
4097
|
+
`;var ti=`
|
|
4098
4098
|
(function(){
|
|
4099
4099
|
var data=JSON.parse(document.getElementById('report-data').textContent);
|
|
4100
|
-
${ot}
|
|
4101
|
-
${ut}
|
|
4102
|
-
${pt}
|
|
4103
|
-
${lt}
|
|
4104
|
-
${dt}
|
|
4105
|
-
${ft}
|
|
4106
|
-
${ht}
|
|
4107
|
-
${gt}
|
|
4108
|
-
${ct}
|
|
4109
|
-
${mt}
|
|
4110
|
-
${yt}
|
|
4111
4100
|
${vt}
|
|
4101
|
+
${wt}
|
|
4102
|
+
${kt}
|
|
4103
|
+
${yt}
|
|
4104
|
+
${bt}
|
|
4105
|
+
${Ct}
|
|
4106
|
+
${St}
|
|
4107
|
+
${Tt}
|
|
4108
|
+
${xt}
|
|
4109
|
+
${Rt}
|
|
4110
|
+
${_t}
|
|
4111
|
+
${At}
|
|
4112
4112
|
applyTheme();
|
|
4113
4113
|
renderRunMeta();
|
|
4114
4114
|
renderSummary();
|
|
@@ -4119,7 +4119,7 @@ function _updateCard(cls,val){
|
|
|
4119
4119
|
renderNeedsAttention();
|
|
4120
4120
|
routeFromHash();
|
|
4121
4121
|
var _lo=document.getElementById('loading-overlay');if(_lo)_lo.remove();
|
|
4122
|
-
})();`;function
|
|
4122
|
+
})();`;function rn(t,e,r){let n=t.replace(/<\//g,"<\\/"),s=r?r.replace(/<\//g,"<\\/"):null;return `<!-- TestRelic AI Analytics Report \u2014 self-contained, no external dependencies -->
|
|
4123
4123
|
<!DOCTYPE html>
|
|
4124
4124
|
<html lang="en" data-theme="">
|
|
4125
4125
|
<head>
|
|
@@ -4128,15 +4128,15 @@ function _updateCard(cls,val){
|
|
|
4128
4128
|
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: blob: file: 'self'; media-src blob: data: file: 'self'; connect-src 'self' http://127.0.0.1:*;">
|
|
4129
4129
|
<title>TestRelic AI Analytics Report</title>
|
|
4130
4130
|
${""}
|
|
4131
|
-
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(
|
|
4132
|
-
<style>${
|
|
4131
|
+
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(ft).toString("base64")}">
|
|
4132
|
+
<style>${pt}${It}${Mt}${Pt}${Et}${Lt}</style>
|
|
4133
4133
|
<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>
|
|
4134
4134
|
</head>
|
|
4135
4135
|
<body>
|
|
4136
4136
|
<div class="wrap">
|
|
4137
4137
|
<div class="top-bar">
|
|
4138
4138
|
<div class="brand">
|
|
4139
|
-
${
|
|
4139
|
+
${gt}
|
|
4140
4140
|
<div class="brand-text">
|
|
4141
4141
|
<span class="brand-title">TestRelic AI</span>
|
|
4142
4142
|
<span class="brand-sub">Analytics Report</span>
|
|
@@ -4173,9 +4173,9 @@ ${""}
|
|
|
4173
4173
|
</aside>
|
|
4174
4174
|
<script id="report-data" type="application/json">${n}</script>
|
|
4175
4175
|
${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:""}
|
|
4176
|
-
<script>${
|
|
4176
|
+
<script>${ti}</script>
|
|
4177
4177
|
</body>
|
|
4178
|
-
</html>`}function
|
|
4178
|
+
</html>`}function Nt(t,e,r,n,s){let a=t.replace(/<\//g,"<\\/"),i=s?s.replace(/<\//g,"<\\/"):"null",o=e.replace(/<\//g,"<\\/"),l=n?n.replace(/<\//g,"<\\/"):null,d={};try{d=JSON.parse(t);}catch{}let c=`{
|
|
4179
4179
|
"schemaVersion":"2.0",
|
|
4180
4180
|
"reportMode":"streaming",
|
|
4181
4181
|
"serverPort":${r??"null"},
|
|
@@ -4190,7 +4190,7 @@ ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:
|
|
|
4190
4190
|
"ci":${d.ci?JSON.stringify(d.ci).replace(/<\//g,"<\\/"):"null"},
|
|
4191
4191
|
"metadata":${d.metadata?JSON.stringify(d.metadata).replace(/<\//g,"<\\/"):"null"},
|
|
4192
4192
|
"shardRunIds":${d.shardRunIds?JSON.stringify(d.shardRunIds).replace(/<\//g,"<\\/"):"null"}
|
|
4193
|
-
}`,
|
|
4193
|
+
}`,p=`
|
|
4194
4194
|
(function(){
|
|
4195
4195
|
var data=JSON.parse(document.getElementById('report-data').textContent);
|
|
4196
4196
|
var _serverPort=data.serverPort||null;
|
|
@@ -4260,18 +4260,18 @@ ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:
|
|
|
4260
4260
|
window.__trServerPort=_serverPort;
|
|
4261
4261
|
window.__trIsStreaming=true;
|
|
4262
4262
|
|
|
4263
|
-
${ot}
|
|
4264
|
-
${ut}
|
|
4265
|
-
${pt}
|
|
4266
|
-
${lt}
|
|
4267
|
-
${dt}
|
|
4268
|
-
${ft}
|
|
4269
|
-
${ht}
|
|
4270
|
-
${gt}
|
|
4271
|
-
${ct}
|
|
4272
|
-
${mt}
|
|
4273
|
-
${yt}
|
|
4274
4263
|
${vt}
|
|
4264
|
+
${wt}
|
|
4265
|
+
${kt}
|
|
4266
|
+
${yt}
|
|
4267
|
+
${bt}
|
|
4268
|
+
${Ct}
|
|
4269
|
+
${St}
|
|
4270
|
+
${Tt}
|
|
4271
|
+
${xt}
|
|
4272
|
+
${Rt}
|
|
4273
|
+
${_t}
|
|
4274
|
+
${At}
|
|
4275
4275
|
applyTheme();
|
|
4276
4276
|
renderRunMeta();
|
|
4277
4277
|
renderSummary();
|
|
@@ -4295,15 +4295,15 @@ ${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:
|
|
|
4295
4295
|
<title>TestRelic AI Analytics Report</title>
|
|
4296
4296
|
${r?`<meta name="report-server-port" content="${r}">`:""}
|
|
4297
4297
|
${r?`<meta name="artifact-server-port" content="${r}">`:""}
|
|
4298
|
-
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(
|
|
4299
|
-
<style>${
|
|
4298
|
+
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(ft).toString("base64")}">
|
|
4299
|
+
<style>${pt}${It}${Mt}${Pt}${Et}${Lt}</style>
|
|
4300
4300
|
<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>
|
|
4301
4301
|
</head>
|
|
4302
4302
|
<body>
|
|
4303
4303
|
<div class="wrap">
|
|
4304
4304
|
<div class="top-bar">
|
|
4305
4305
|
<div class="brand">
|
|
4306
|
-
${
|
|
4306
|
+
${gt}
|
|
4307
4307
|
<div class="brand-text">
|
|
4308
4308
|
<span class="brand-title">TestRelic AI</span>
|
|
4309
4309
|
<span class="brand-sub">Analytics Report</span>
|
|
@@ -4340,81 +4340,81 @@ ${r?`<meta name="artifact-server-port" content="${r}">`:""}
|
|
|
4340
4340
|
</aside>
|
|
4341
4341
|
<script id="report-data" type="application/json">${c}</script>
|
|
4342
4342
|
${l?`<script id="artifact-manifest-data" type="application/json">${l}</script>`:""}
|
|
4343
|
-
<script>${
|
|
4343
|
+
<script>${p}</script>
|
|
4344
4344
|
</body>
|
|
4345
|
-
</html>`}function
|
|
4346
|
-
`);});}catch{}}var
|
|
4347
|
-
`;fs$1.writeSync(this.fd,r),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{fs$1.closeSync(this.fd);}catch{}}}cleanup(){try{fs$1.unlinkSync(this.filePath);}catch{}}};async function Yr(t,e,r,n){let s=(e-1)*r,a=[],i=0,o=readline.createInterface({input:fs$1.createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let c of o)if(c.length!==0){if(i>=s&&a.length<r)try{a.push(JSON.parse(c));}catch{}if(i++,a.length>=r&&n!==void 0)break}let l=n??i,d=Math.max(1,Math.ceil(l/r));return {items:a,total:l,page:e,pageSize:r,totalPages:d}}var en=/^[a-f0-9]{12}$/,_t=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,tn=500;function A(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function rn(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 Te(t){try{return fs$1.existsSync(t)?JSON.parse(fs$1.readFileSync(t,"utf-8")):null}catch{return null}}function Re(t){let e=0;try{let r=fs$1.readdirSync(t,{withFileTypes:!0});for(let n of r){let s=path.join(t,n.name);n.isFile()?e+=fs$1.statSync(s).size:n.isDirectory()&&(e+=Re(s));}}catch{}return e}function nn(t,e,r,n){let s=Te(path.join(r,"index.json"));A(e,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-n)/1e3)});}function sn(t,e,r){let n=Te(path.join(r,"summary.json"));if(!n){A(e,404,{error:"Summary not found"});return}A(e,200,n);}function an(t,e,r){let n=Te(path.join(r,"index.json"));if(!n){A(e,404,{error:"Test index not found"});return}let a=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,i=Math.max(1,parseInt(a.get("page")??"1",10)||1),o=Math.min(tn,Math.max(1,parseInt(a.get("pageSize")??"100",10)||100)),l=a.get("status")?.split(",").filter(Boolean)??null,d=a.get("file")??null,c=a.get("search")?.toLowerCase()??null,u=a.get("tag")?.split(",").filter(Boolean)??null,f=a.get("sort")??"file",g=a.get("order")==="desc"?-1:1,p=n;l&&l.length>0&&(p=p.filter(y=>l.includes(y.status))),d&&(p=p.filter(y=>y.filePath===d||y.filePath.startsWith(d+"/"))),c&&(p=p.filter(y=>y.title.toLowerCase().includes(c)||y.filePath.toLowerCase().includes(c))),u&&u.length>0&&(p=p.filter(y=>u.some(w=>y.tags.includes(w)))),p=[...p].sort((y,w)=>{let x=0;switch(f){case "duration":x=y.duration-w.duration;break;case "status":x=y.status.localeCompare(w.status);break;case "title":x=y.title.localeCompare(w.title);break;default:x=y.filePath.localeCompare(w.filePath);break}return x*g});let h=p.length,b=Math.max(1,Math.ceil(h/o)),v=(i-1)*o,m=p.slice(v,v+o);A(e,200,{tests:m,pagination:{page:i,pageSize:o,totalItems:h,totalPages:b},filters:{status:l,file:d,search:c,tag:u}});}function on(t,e,r,n){if(!en.test(n)){A(e,400,{error:"Invalid test ID format"});return}let s=path.join(r,"tests",n,"meta.json"),a=path.join(r,"tests",`${n}.json`),i=fs$1.existsSync(s)?s:fs$1.existsSync(a)?a:null;if(!i){A(e,404,{error:`Test not found: ${n}`});return}try{let o=fs$1.readFileSync(i,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(o);}catch{A(e,500,{error:"Failed to read the test data file"});}}async function ln(t,e,r,n,s){if(!en.test(n)){A(e,400,{error:"Invalid test ID format"});return}let i=path.join(r,"tests",n,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!fs$1.existsSync(i)){A(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),c=Math.min(tn,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),u,f=path.join(r,"tests",n,"meta.json");if(fs$1.existsSync(f))try{let p=JSON.parse(fs$1.readFileSync(f,"utf-8"));switch(s){case "network":u=p.networkRequestsCount;break;case "console":u=p.consoleLogsCount;break;case "api-calls":u=p.apiCallsCount;break}}catch{}let g=await Yr(i,d,c,u);A(e,200,g);}catch{A(e,500,{error:"Failed to read the report data"});}}function dn(t,e,r){let n=Te(path.join(r,"index.json"));if(!n){A(e,404,{error:"Test index not found"});return}let s=new Map;for(let i of n){if(i.isRetry)continue;let o=s.get(i.filePath);switch(o||(o={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},s.set(i.filePath,o)),o.total++,i.status){case "passed":o.passed++;break;case "failed":o.failed++;break;case "flaky":o.flaky++;break;case "skipped":o.skipped++;break;case "timedout":o.timedOut++;break}}let a=Array.from(s.entries()).map(([i,o])=>({filePath:i,...o})).sort((i,o)=>i.filePath.localeCompare(o.filePath));A(e,200,{files:a});}function cn(t,e,r){if(!fs$1.existsSync(r)){A(e,200,{runs:[],totalSizeBytes:0});return}try{let n=[],s=0,a=fs$1.readdirSync(r,{withFileTypes:!0});for(let i of a){if(!i.isDirectory()||!_t.test(i.name))continue;let o=path.join(r,i.name),l=Re(o),d=fs$1.readdirSync(o,{withFileTypes:!0}).filter(c=>c.isDirectory());n.push({folderName:i.name,totalSizeBytes:l,testCount:d.length}),s+=l;}n.sort((i,o)=>o.folderName.localeCompare(i.folderName)),A(e,200,{runs:n,totalSizeBytes:s});}catch{A(e,500,{error:"Failed to read the report data"});}}function un(t,e,r){try{let n=0,s=0;if(fs$1.existsSync(r)){let a=fs$1.readdirSync(r,{withFileTypes:!0});for(let i of a){if(!i.isDirectory()||!_t.test(i.name))continue;let o=path.join(r,i.name),l=Re(o);fs$1.rmSync(o,{recursive:!0,force:!0}),s+=l,n++;}}A(e,200,{deletedCount:n,freedBytes:s});}catch{A(e,500,{error:"Failed to read the report data"});}}function pn(t,e,r,n){if(!_t.test(n)){A(e,400,{error:"Invalid folder name"});return}let s=path.join(r,n);try{if(!fs$1.statSync(s).isDirectory()){A(e,404,{error:"Not found"});return}}catch{A(e,404,{error:"Not found"});return}try{let a=Re(s);fs$1.rmSync(s,{recursive:!0,force:!0}),A(e,200,{deleted:n,freedBytes:a});}catch{A(e,500,{error:"Failed to read the report data"});}}function fn(t,e,r){A(e,200,{status:"shutting_down"}),r.close();}function It(t,e,r){if(!fs$1.existsSync(r)){A(e,404,{error:"File not found"});return}try{let n=fs$1.statSync(r).size,s=path.extname(r).toLowerCase(),a=ni[s]??"application/octet-stream",i=ri(t.headers.range,n);if(i==="unsatisfiable"){e.writeHead(416,{"Content-Range":`bytes */${n}`,"Accept-Ranges":"bytes"}),e.end();return}if(i){e.writeHead(206,{"Content-Type":a,"Content-Length":i.end-i.start+1,"Content-Range":`bytes ${i.start}-${i.end}/${n}`,"Accept-Ranges":"bytes"}),Zr(fs$1.createReadStream(r,{start:i.start,end:i.end}),e);return}e.writeHead(200,{"Content-Type":a,"Content-Length":n,"Accept-Ranges":"bytes"}),Zr(fs$1.createReadStream(r),e);}catch{A(e,500,{error:"Failed to read the report data"});}}function Zr(t,e){t.on("error",()=>{t.destroy(),e.destroy();}),e.on("close",()=>{t.destroy();}),t.pipe(e);}function ri(t,e){if(!t)return null;let r=/^bytes=(\d*)-(\d*)$/.exec(t.trim());if(!r)return null;let[,n,s]=r;if(n===""&&s==="")return null;let a,i;if(n===""){let o=Number(s);if(o<=0)return "unsatisfiable";a=Math.max(0,e-o),i=e-1;}else a=Number(n),i=s===""?e-1:Math.min(Number(s),e-1);return !Number.isFinite(a)||!Number.isFinite(i)?null:e===0||a>=e||a>i?"unsatisfiable":{start:a,end:i}}var ni={".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 oi=9323,li=10,di=1800*1e3;function me(t,e){return new Promise((r,n)=>{let s=e?.port??oi,a=Date.now(),i,o=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(i),i=setTimeout(()=>{u.close();},di);}let c=e?.htmlPath??null;if(!c){let g=path.dirname(t);try{let p=fs$1.readdirSync(g).find(h=>h.endsWith(".html"));p&&(c=path.join(g,p));}catch{}}let u=http.createServer((g,p)=>{if(d(),rn(p),g.method==="OPTIONS"){p.writeHead(204),p.end();return}let h;try{h=new URL(g.url??"/",`http://${g.headers.host??"localhost"}`).pathname;}catch{A(p,400,{error:"Invalid URL"});return}if(g.method==="GET"&&(h==="/"||h==="/index.html")){if(c&&fs$1.existsSync(c)){It(g,p,c);return}A(p,404,{error:"HTML report not found"});return}if(g.method==="GET"&&h==="/api/health"){nn(g,p,t,a);return}if(g.method==="GET"&&h==="/api/summary"){sn(g,p,t);return}if(g.method==="GET"&&h==="/api/tests"){an(g,p,t);return}if(g.method==="GET"&&h==="/api/files"){dn(g,p,t);return}let b=h.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(g.method==="GET"&&b){ln(g,p,t,b[1],b[2]);return}let v=h.match(/^\/api\/tests\/([a-f0-9]+)$/);if(g.method==="GET"&&v){on(g,p,t,v[1]);return}if(g.method==="GET"&&h==="/api/artifacts"){cn(g,p,l);return}if(g.method==="DELETE"&&h==="/api/artifacts"){un(g,p,l);return}let m=h.match(/^\/api\/artifacts\/(.+)$/);if(g.method==="DELETE"&&m){pn(g,p,l,decodeURIComponent(m[1]));return}if(g.method==="GET"&&h.startsWith("/artifacts/")){let y=decodeURIComponent(h.slice(11));if(y.includes("..")||y.includes("\0")){A(p,400,{error:"Invalid path"});return}It(g,p,path.join(l,y));return}if(g.method==="POST"&&h==="/api/shutdown"){fn(g,p,u);return}A(p,404,{error:"Not found"});});function f(g){let p=h=>{h.code==="EADDRINUSE"&&o<li?(o++,f(g+1)):n(h);};u.once("error",p),u.listen(g,"127.0.0.1",()=>{u.removeListener("error",p);let h=u.address();if(!h||typeof h=="string"){n(new Error("Failed to get server address"));return}d(),r({port:h.port,dispose:()=>new Promise(b=>{clearTimeout(i),u.close(()=>b());})});});}f(s);})}async function gn(t){let e=await me(t);return {port:e.port,dispose:e.dispose}}function pi(t,e,r,n){let s=JSON.stringify(n?{...t,presentedSummary:n}:t),a=r?JSON.stringify(r):null;return Gr(s,e,a)}async function Pt(t,e,r,n){try{let s=null,a=null,i=e.reportMode==="streaming"||e.reportMode==="auto"&&t.timeline.length===0&&t.summary.total>=e.streamingThreshold,o,l=e.htmlReportPath,d=path.dirname(l);fs$1.mkdirSync(d,{recursive:!0});let c="",u="[]",f=null,g=n?JSON.stringify(n):null;if(i){c=JSON.stringify({...t.summary,testRunId:t.testRunId,startedAt:t.startedAt,completedAt:t.completedAt,totalDuration:t.totalDuration,ci:t.ci,metadata:t.metadata,shardRunIds:t.shardRunIds});let h=path.dirname(e.outputPath),b=path.join(h,".testrelic-report");try{let v=path.join(b,"index-compact.json"),m=path.join(b,"index.json");fs$1.existsSync(v)?u=fs$1.readFileSync(v,"utf-8"):fs$1.existsSync(m)&&(u=fs$1.readFileSync(m,"utf-8"));}catch{}f=r?JSON.stringify(r):null,o=St(c,u,null,f,g);}else o=pi(t,null,r,n);let p=l+".tmp";if(fs$1.writeFileSync(p,o,"utf-8"),fs$1.renameSync(p,l),i){if(t.ci===null){let h=path.dirname(e.outputPath),b=path.join(h,".testrelic-report"),v=path.resolve(l);try{if(await gi(),s=await hi(b),!s){a=await me(b,{htmlPath:v}),s=a.port;let m=setInterval(()=>{},6e4),y=()=>{clearInterval(m),a?.dispose();};process.on("SIGINT",y),process.on("SIGTERM",y),setTimeout(y,1800*1e3).unref();}if(s){process.stderr.write(`
|
|
4345
|
+
</html>`}function Dt(t){try{let e=process.platform,r,n;e==="darwin"?(r="open",n=[t]):e==="win32"?(r="explorer.exe",n=[t]):(r="xdg-open",n=[t]),child_process.execFile(r,n,s=>{s&&process.stderr.write(`[testrelic] Failed to open browser: ${s.message}
|
|
4346
|
+
`);});}catch{}}var nn=path.join(os$1.tmpdir(),"testrelic-data"),V=class{constructor(e){this.count=0;this.closed=false;fs$1.mkdirSync(nn,{recursive:true}),this.filePath=path.join(nn,`${e}-${crypto.randomUUID().substring(0,8)}.jsonl`),this.fd=fs$1.openSync(this.filePath,"w");}append(e){if(this.closed)return;let r=JSON.stringify(e)+`
|
|
4347
|
+
`;fs$1.writeSync(this.fd,r),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{fs$1.closeSync(this.fd);}catch{}}}cleanup(){try{fs$1.unlinkSync(this.filePath);}catch{}}};async function an(t,e,r,n){let s=(e-1)*r,a=[],i=0,o=readline.createInterface({input:fs$1.createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let c of o)if(c.length!==0){if(i>=s&&a.length<r)try{a.push(JSON.parse(c));}catch{}if(i++,a.length>=r&&n!==void 0)break}let l=n??i,d=Math.max(1,Math.ceil(l/r));return {items:a,total:l,page:e,pageSize:r,totalPages:d}}function $(t){try{return fs$1.readFileSync(t,"utf-8").split(`
|
|
4348
|
+
`).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}var cn=/^[a-f0-9]{12}$/,Ot=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,un=500;function _(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function pn(t){t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type");}function Ie(t){try{return fs$1.existsSync(t)?JSON.parse(fs$1.readFileSync(t,"utf-8")):null}catch{return null}}function Me(t){let e=0;try{let r=fs$1.readdirSync(t,{withFileTypes:!0});for(let n of r){let s=path.join(t,n.name);n.isFile()?e+=fs$1.statSync(s).size:n.isDirectory()&&(e+=Me(s));}}catch{}return e}function fn(t,e,r,n){let s=Ie(path.join(r,"index.json"));_(e,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-n)/1e3)});}function gn(t,e,r){let n=Ie(path.join(r,"summary.json"));if(!n){_(e,404,{error:"Summary not found"});return}_(e,200,n);}function hn(t,e,r){let n=Ie(path.join(r,"index.json"));if(!n){_(e,404,{error:"Test index not found"});return}let a=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,i=Math.max(1,parseInt(a.get("page")??"1",10)||1),o=Math.min(un,Math.max(1,parseInt(a.get("pageSize")??"100",10)||100)),l=a.get("status")?.split(",").filter(Boolean)??null,d=a.get("file")??null,c=a.get("search")?.toLowerCase()??null,p=a.get("tag")?.split(",").filter(Boolean)??null,u=a.get("sort")??"file",f=a.get("order")==="desc"?-1:1,g=n;l&&l.length>0&&(g=g.filter(y=>l.includes(y.status))),d&&(g=g.filter(y=>y.filePath===d||y.filePath.startsWith(d+"/"))),c&&(g=g.filter(y=>y.title.toLowerCase().includes(c)||y.filePath.toLowerCase().includes(c))),p&&p.length>0&&(g=g.filter(y=>p.some(x=>y.tags.includes(x)))),g=[...g].sort((y,x)=>{let C=0;switch(u){case "duration":C=y.duration-x.duration;break;case "status":C=y.status.localeCompare(x.status);break;case "title":C=y.title.localeCompare(x.title);break;default:C=y.filePath.localeCompare(x.filePath);break}return C*f});let h=g.length,m=Math.max(1,Math.ceil(h/o)),b=(i-1)*o,v=g.slice(b,b+o);_(e,200,{tests:v,pagination:{page:i,pageSize:o,totalItems:h,totalPages:m},filters:{status:l,file:d,search:c,tag:p}});}function mn(t,e,r,n){if(!cn.test(n)){_(e,400,{error:"Invalid test ID format"});return}let s=path.join(r,"tests",n,"meta.json"),a=path.join(r,"tests",`${n}.json`),i=fs$1.existsSync(s)?s:fs$1.existsSync(a)?a:null;if(!i){_(e,404,{error:`Test not found: ${n}`});return}try{let o=fs$1.readFileSync(i,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(o);}catch{_(e,500,{error:"Failed to read the test data file"});}}async function vn(t,e,r,n,s){if(!cn.test(n)){_(e,400,{error:"Invalid test ID format"});return}let i=path.join(r,"tests",n,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!fs$1.existsSync(i)){_(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),c=Math.min(un,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),p,u=path.join(r,"tests",n,"meta.json");if(fs$1.existsSync(u))try{let g=JSON.parse(fs$1.readFileSync(u,"utf-8"));switch(s){case "network":p=g.networkRequestsCount;break;case "console":p=g.consoleLogsCount;break;case "api-calls":p=g.apiCallsCount;break}}catch{}let f=await an(i,d,c,p);_(e,200,f);}catch{_(e,500,{error:"Failed to read the report data"});}}function yn(t,e,r){let n=Ie(path.join(r,"index.json"));if(!n){_(e,404,{error:"Test index not found"});return}let s=new Map;for(let i of n){if(i.isRetry)continue;let o=s.get(i.filePath);switch(o||(o={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},s.set(i.filePath,o)),o.total++,i.status){case "passed":o.passed++;break;case "failed":o.failed++;break;case "flaky":o.flaky++;break;case "skipped":o.skipped++;break;case "timedout":o.timedOut++;break}}let a=Array.from(s.entries()).map(([i,o])=>({filePath:i,...o})).sort((i,o)=>i.filePath.localeCompare(o.filePath));_(e,200,{files:a});}function bn(t,e,r){if(!fs$1.existsSync(r)){_(e,200,{runs:[],totalSizeBytes:0});return}try{let n=[],s=0,a=fs$1.readdirSync(r,{withFileTypes:!0});for(let i of a){if(!i.isDirectory()||!Ot.test(i.name))continue;let o=path.join(r,i.name),l=Me(o),d=fs$1.readdirSync(o,{withFileTypes:!0}).filter(c=>c.isDirectory());n.push({folderName:i.name,totalSizeBytes:l,testCount:d.length}),s+=l;}n.sort((i,o)=>o.folderName.localeCompare(i.folderName)),_(e,200,{runs:n,totalSizeBytes:s});}catch{_(e,500,{error:"Failed to read the report data"});}}function xn(t,e,r){try{let n=0,s=0;if(fs$1.existsSync(r)){let a=fs$1.readdirSync(r,{withFileTypes:!0});for(let i of a){if(!i.isDirectory()||!Ot.test(i.name))continue;let o=path.join(r,i.name),l=Me(o);fs$1.rmSync(o,{recursive:!0,force:!0}),s+=l,n++;}}_(e,200,{deletedCount:n,freedBytes:s});}catch{_(e,500,{error:"Failed to read the report data"});}}function wn(t,e,r,n){if(!Ot.test(n)){_(e,400,{error:"Invalid folder name"});return}let s=path.join(r,n);try{if(!fs$1.statSync(s).isDirectory()){_(e,404,{error:"Not found"});return}}catch{_(e,404,{error:"Not found"});return}try{let a=Me(s);fs$1.rmSync(s,{recursive:!0,force:!0}),_(e,200,{deleted:n,freedBytes:a});}catch{_(e,500,{error:"Failed to read the report data"});}}function kn(t,e,r){_(e,200,{status:"shutting_down"}),r.close();}function qt(t,e,r){if(!fs$1.existsSync(r)){_(e,404,{error:"File not found"});return}try{let n=fs$1.statSync(r).size,s=path.extname(r).toLowerCase(),a=hi[s]??"application/octet-stream",i=gi(t.headers.range,n);if(i==="unsatisfiable"){e.writeHead(416,{"Content-Range":`bytes */${n}`,"Accept-Ranges":"bytes"}),e.end();return}if(i){e.writeHead(206,{"Content-Type":a,"Content-Length":i.end-i.start+1,"Content-Range":`bytes ${i.start}-${i.end}/${n}`,"Accept-Ranges":"bytes"}),ln(fs$1.createReadStream(r,{start:i.start,end:i.end}),e);return}e.writeHead(200,{"Content-Type":a,"Content-Length":n,"Accept-Ranges":"bytes"}),ln(fs$1.createReadStream(r),e);}catch{_(e,500,{error:"Failed to read the report data"});}}function ln(t,e){t.on("error",()=>{t.destroy(),e.destroy();}),e.on("close",()=>{t.destroy();}),t.pipe(e);}function gi(t,e){if(!t)return null;let r=/^bytes=(\d*)-(\d*)$/.exec(t.trim());if(!r)return null;let[,n,s]=r;if(n===""&&s==="")return null;let a,i;if(n===""){let o=Number(s);if(o<=0)return "unsatisfiable";a=Math.max(0,e-o),i=e-1;}else a=Number(n),i=s===""?e-1:Math.min(Number(s),e-1);return !Number.isFinite(a)||!Number.isFinite(i)?null:e===0||a>=e||a>i?"unsatisfiable":{start:a,end:i}}var hi={".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 bi=9323,xi=10,wi=1800*1e3;function ye(t,e){return new Promise((r,n)=>{let s=e?.port??bi,a=Date.now(),i,o=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(i),i=setTimeout(()=>{p.close();},wi);}let c=e?.htmlPath??null;if(!c){let f=path.dirname(t);try{let g=fs$1.readdirSync(f).find(h=>h.endsWith(".html"));g&&(c=path.join(f,g));}catch{}}let p=http.createServer((f,g)=>{if(d(),pn(g),f.method==="OPTIONS"){g.writeHead(204),g.end();return}let h;try{h=new URL(f.url??"/",`http://${f.headers.host??"localhost"}`).pathname;}catch{_(g,400,{error:"Invalid URL"});return}if(f.method==="GET"&&(h==="/"||h==="/index.html")){if(c&&fs$1.existsSync(c)){qt(f,g,c);return}_(g,404,{error:"HTML report not found"});return}if(f.method==="GET"&&h==="/api/health"){fn(f,g,t,a);return}if(f.method==="GET"&&h==="/api/summary"){gn(f,g,t);return}if(f.method==="GET"&&h==="/api/tests"){hn(f,g,t);return}if(f.method==="GET"&&h==="/api/files"){yn(f,g,t);return}let m=h.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(f.method==="GET"&&m){vn(f,g,t,m[1],m[2]);return}let b=h.match(/^\/api\/tests\/([a-f0-9]+)$/);if(f.method==="GET"&&b){mn(f,g,t,b[1]);return}if(f.method==="GET"&&h==="/api/artifacts"){bn(f,g,l);return}if(f.method==="DELETE"&&h==="/api/artifacts"){xn(f,g,l);return}let v=h.match(/^\/api\/artifacts\/(.+)$/);if(f.method==="DELETE"&&v){wn(f,g,l,decodeURIComponent(v[1]));return}if(f.method==="GET"&&h.startsWith("/artifacts/")){let y=decodeURIComponent(h.slice(11));if(y.includes("..")||y.includes("\0")){_(g,400,{error:"Invalid path"});return}qt(f,g,path.join(l,y));return}if(f.method==="POST"&&h==="/api/shutdown"){kn(f,g,p);return}_(g,404,{error:"Not found"});});function u(f){let g=h=>{h.code==="EADDRINUSE"&&o<xi?(o++,u(f+1)):n(h);};p.once("error",g),p.listen(f,"127.0.0.1",()=>{p.removeListener("error",g);let h=p.address();if(!h||typeof h=="string"){n(new Error("Failed to get server address"));return}d(),r({port:h.port,dispose:()=>new Promise(m=>{clearTimeout(i),p.close(()=>m());})});});}u(s);})}async function Cn(t){let e=await ye(t);return {port:e.port,dispose:e.dispose}}function Ti(t,e,r,n){let s=JSON.stringify(n?{...t,presentedSummary:n}:t),a=r?JSON.stringify(r):null;return rn(s,e,a)}async function Ut(t,e,r,n){try{let s=null,a=null,i=e.reportMode==="streaming"||e.reportMode==="auto"&&t.timeline.length===0&&t.summary.total>=e.streamingThreshold,o,l=e.htmlReportPath,d=path.dirname(l);fs$1.mkdirSync(d,{recursive:!0});let c="",p="[]",u=null,f=n?JSON.stringify(n):null;if(i){c=JSON.stringify({...t.summary,testRunId:t.testRunId,startedAt:t.startedAt,completedAt:t.completedAt,totalDuration:t.totalDuration,ci:t.ci,metadata:t.metadata,shardRunIds:t.shardRunIds});let h=path.dirname(e.outputPath),m=path.join(h,".testrelic-report");try{let b=path.join(m,"index-compact.json"),v=path.join(m,"index.json");fs$1.existsSync(b)?p=fs$1.readFileSync(b,"utf-8"):fs$1.existsSync(v)&&(p=fs$1.readFileSync(v,"utf-8"));}catch{}u=r?JSON.stringify(r):null,o=Nt(c,p,null,u,f);}else o=Ti(t,null,r,n);let g=l+".tmp";if(fs$1.writeFileSync(g,o,"utf-8"),fs$1.renameSync(g,l),i){if(t.ci===null){let h=path.dirname(e.outputPath),m=path.join(h,".testrelic-report"),b=path.resolve(l);try{if(await Ri(),s=await Ai(m),!s){a=await ye(m,{htmlPath:b}),s=a.port;let v=setInterval(()=>{},6e4),y=()=>{clearInterval(v),a?.dispose();};process.on("SIGINT",y),process.on("SIGTERM",y),setTimeout(y,1800*1e3).unref();}if(s){process.stderr.write(`
|
|
4348
4349
|
Report server: http://127.0.0.1:${s}
|
|
4349
|
-
`);try{let
|
|
4350
|
-
`);}}var Ie=9323,bn=10;async function fi(){for(let t=Ie;t<Ie+bn;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${t}/api/health`,{signal:e.signal});if(clearTimeout(r),n.ok)return t}catch{}return null}async function gi(){for(let t=Ie;t<Ie+bn;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 hi(t){let r=[path.join(__dirname,"cli.cjs"),path.join(__dirname,"cli.js"),path.join(__dirname,"..","dist","cli.cjs"),path.join(__dirname,"..","dist","cli.js")].find(n=>fs$1.existsSync(n));if(!r){let n=await me(t);return process.on("exit",()=>{n?.dispose();}),n.port}return new Promise(n=>{let s=child_process.spawn(process.execPath,[r,"serve",t],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),a="",i=false,o=setTimeout(()=>{i||(i=true,s.stderr?.removeAllListeners(),fi().then(n));},5e3);s.stderr?.on("data",l=>{a+=l.toString();let d=a.match(/127\.0\.0\.1:(\d+)/);d&&!i&&(i=true,clearTimeout(o),s.stderr?.removeAllListeners(),s.unref(),n(Number(d[1])));}),s.on("error",()=>{i||(i=true,clearTimeout(o),n(null));}),s.on("exit",()=>{i||(i=true,clearTimeout(o),n(null));}),s.unref();})}var xn=Buffer.from([137,80,78,71,13,10,26,10]),mi=16,vi=20,Me=24;function wn(t){if(t.length<Me||!t.subarray(0,xn.length).equals(xn))return null;let e=t.readUInt32BE(mi),r=t.readUInt32BE(vi);return e===0||r===0?null:{width:e,height:r}}var yi=/(?:^|\D)(\d+) pixels \(ratio [\d.]+ of all image pixels\) are different/,kn=/Expected an image (\d+)px by (\d+)px, received (\d+)px by (\d+)px/;function Cn(t){return t?kn.test(t):false}var bi=/^[ \t]*Snapshot:[ \t]*(\S(?:.*\S)?)[ \t]*$/m;function Sn(t){if(!t)return {};let e={},r=yi.exec(t);if(r){let a=Number.parseInt(r[1],10);Number.isFinite(a)&&(e.diffPixels=a);}let n=kn.exec(t);if(n){let[,a,i,o,l]=n,d=[a,i,o,l].map(c=>Number.parseInt(c,10));d.every(c=>Number.isFinite(c))&&(e.expectedWidth=d[0],e.expectedHeight=d[1],e.actualWidth=d[2],e.actualHeight=d[3]);}let s=bi.exec(t);return s&&(e.snapshotName=s[1]),e}function Tn(t,e){if(t===void 0||!e)return;let r=e.width*e.height;if(!(r<=0))return t/r}var Ri=20,Et=0,Nt=[];async function ve(t,e){Et>=Ri&&await new Promise(r=>Nt.push(r)),Et++;try{return await promises.copyFile(t,e),!0}catch{return false}finally{Et--,Nt.length>0&&Nt.shift()();}}var W=[];async function _n(){W.length!==0&&(await Promise.allSettled(W),W.length=0);}function In(t){let e=new Date,r=a=>String(a).padStart(2,"0"),n=`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())}T${r(e.getHours())}-${r(e.getMinutes())}-${r(e.getSeconds())}`;if(!fs$1.existsSync(path.join(t,n)))return n;let s=1;for(;fs$1.existsSync(path.join(t,`${n}-${s}`));)s++;return `${n}-${s}`}function Lt(t){let e=t.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-|-$/g,"");return e.length>100&&(e=e.substring(0,100).replace(/-+$/,"")),e||"unnamed-test"}var Ai=8;function Mn(t,e,r){let n=Lt(t),s=r?Lt(r).substring(0,Ai):"";return s&&(n+=`--${s}`),e>0&&(n+=`--retry-${e}`),n}function Pn(t,e,r,n,s,a){let i=t.find(p=>p.name==="screenshot"&&p.path),o=t.find(p=>p.name==="video"&&p.path),l=t.find(p=>p.name==="trace"&&p.path);if(!i&&!o&&!l)return null;let d=Mn(e,r,a),c=s?["artifacts",s,d]:["artifacts",d],u=path.join(n,...c),f=c,g={};try{fs$1.mkdirSync(u,{recursive:!0});}catch{return null}if(i?.path&&fs$1.existsSync(i.path)){let h=`screenshot${path.extname(i.path)||".png"}`,b=path.join(u,h);W.push(ve(i.path,b).then(()=>{})),g.screenshot=`${f.join("/")}/${h}`;}if(o?.path&&fs$1.existsSync(o.path)){let h=`video${path.extname(o.path)||".webm"}`,b=path.join(u,h);W.push(ve(o.path,b).then(()=>{})),g.video=`${f.join("/")}/${h}`;}if(l?.path&&fs$1.existsSync(l.path)){let h=`trace${path.extname(l.path)||".zip"}`,b=path.join(u,h);W.push(ve(l.path,b).then(()=>{})),g.trace=`${f.join("/")}/${h}`;}return !g.screenshot&&!g.video&&!g.trace?null:g}var Dt="visual",_i=6;function Ii(t){let e=crypto.createHash("sha256").update(t).digest("hex").substring(0,_i);return `${Lt(t)}--${e}`}function Rn(t){let e=null;try{e=fs$1.openSync(t,"r");let r=Buffer.alloc(Me),n=fs$1.readSync(e,r,0,Me,0);return wn(r.subarray(0,n))}catch{return null}finally{if(e!==null)try{fs$1.closeSync(e);}catch{}}}var An=[{key:"expectedPath",dest:"baseline",field:"baseline"},{key:"actualPath",dest:"actual",field:"actual"},{key:"diffPath",dest:"diff",field:"diff"},{key:"previousPath",dest:"previous",field:"previous"}],Mi=[{key:"baselineDomPath",dest:"baseline.dom.json",field:"baselineDom"},{key:"actualDomPath",dest:"actual.dom.json",field:"actualDom"}];function Pi(t,e,r,n){let s=Ii(t.name),a=path.join(e,s),i=An.some(p=>t[p.key]);if(i||t.dom)try{fs$1.mkdirSync(a,{recursive:!0});}catch{return null}let o={},l=false;for(let p of An){let h=t[p.key];if(!h||!fs$1.existsSync(h))continue;let b=path.extname(h)||".png",v=`${p.dest}${b}`;W.push(ve(h,path.join(a,v)).then(()=>{})),o[p.field]=`${r}/${Dt}/${s}/${v}`,l=true;}let d=t.dom;if(d)for(let p of Mi){let h=d[p.key];!h||!fs$1.existsSync(h)||(W.push(ve(h,path.join(a,p.dest)).then(()=>{})),o[p.field]=`${r}/${Dt}/${s}/${p.dest}`);}if(!l&&i)return null;let c=t.expectedPath?Rn(t.expectedPath):t.actualPath?Rn(t.actualPath):null,u=Tn(t.diffPixels,c),f=t.committedPath??t.expectedPath,g=f?path.relative(n,f).replace(/\\/g,"/"):void 0;return {name:t.name,status:t.status,source:t.source,...o,...g?{baselinePath:g}:{},...c?{width:c.width,height:c.height}:{},...t.actualWidth!==void 0?{actualWidth:t.actualWidth}:{},...t.actualHeight!==void 0?{actualHeight:t.actualHeight}:{},...t.diffPixels!==void 0?{diffPixels:t.diffPixels}:{},...u!==void 0?{diffPixelRatio:u}:{},...d?{domChanges:d.changes,domChangeCount:d.total,domRootCauses:d.rootCauses,domTruncated:d.truncated,domCaptureBox:d.captureBox}:{}}}function En(t,e,r,n,s,a,i=process.cwd()){if(t.length===0)return null;let o=Mn(e,r,a),l=s?["artifacts",s,o]:["artifacts",o],d=path.join(n,...l,Dt),c=l.join("/");try{fs$1.mkdirSync(d,{recursive:!0});}catch{return null}let u=[];for(let f of t){let g=Pi(f,d,c,i);g&&u.push(g);}return u.length>0?u:null}function Nn(t){let{styleProps:e,defaults:r,inherited:n,maxNodes:s,maxText:a,maskBoxes:i,viewportBox:o,fullPage:l}=t,d={};for(let S=0;S<n.length;S++)d[n[S]]=true;let c=window.scrollX||window.pageXOffset||0,u=window.scrollY||window.pageYOffset||0,f=[],g=0,p=[];for(let S=0;S<i.length;S++){let k=i[S];p.push([k[0]+c,k[1]+u,k[2],k[3]]);}function h(S,k,R,C){for(let T=0;T<p.length;T++){let I=p[T];if(S<I[0]+I[2]&&S+R>I[0]&&k<I[1]+I[3]&&k+C>I[1])return true}return false}function b(S){let k=S.parentElement;if(!k)return 0;let R=k.children,C=0;for(let T=0;T<R.length;T++){let I=R[T];if(I===S)break;I.tagName===S.tagName&&C++;}return C}function v(S){let k="",R=S.childNodes;for(let C=0;C<R.length;C++){let T=R[C];T.nodeType===3&&(k+=T.nodeValue??"");}return k=k.replace(/\s+/g," ").trim(),k.length>a?k.slice(0,a):k}function m(S,k){let R;for(let C=0;C<e.length;C++){let T=e[C],I=S.getPropertyValue(T);if(I){if(d[T]){if(k&&k.getPropertyValue(T)===I)continue}else if(r[T]===I)continue;R||(R={}),R[T]=I;}}return R}let y=[{el:document.body,parentPath:"",parentComputed:null}];for(;y.length>0;){let S=y.pop(),k=S.el,R=window.getComputedStyle(k);if(R.display==="none")continue;let C=k.tagName.toLowerCase(),T=k.id?"#"+k.id:S.parentPath?S.parentPath+">"+C+"["+b(k)+"]":C,I=k.children;for(let E=I.length-1;E>=0;E--)y.push({el:I[E],parentPath:T,parentComputed:R});if(R.visibility==="hidden")continue;let N=k.getBoundingClientRect();if(N.width<=0||N.height<=0)continue;if(f.length>=s){g++;continue}let z=Math.round(N.left+c),ce=Math.round(N.top+u),ue=Math.round(N.width),pe=Math.round(N.height),M={p:T,t:C,r:[z,ce,ue,pe]};k.id&&(M.i=k.id);let P=k.getAttribute("class");P&&(M.c=P.replace(/\s+/g," ").trim());let D=v(k);D&&(M.x=D);let j=m(R,S.parentComputed);j&&(M.s=j),h(z,ce,ue,pe)&&(M.m=1),f.push(M);}let w=Math.max(document.documentElement.scrollWidth,window.innerWidth),x=Math.max(document.documentElement.scrollHeight,window.innerHeight),_;return o?_=[Math.round(o[0]+c),Math.round(o[1]+u),Math.round(o[2]),Math.round(o[3])]:l?_=[0,0,w,x]:_=[Math.round(c),Math.round(u),window.innerWidth,window.innerHeight],{version:"1.0",url:location.href,viewport:{width:window.innerWidth,height:window.innerHeight},content:{width:w,height:x},captureBox:_,nodes:f,truncatedNodes:g}}var Bi=["display","position","color","background-color","background-image","border-top-width","border-right-width","border-bottom-width","border-left-width","border-color","border-style","border-radius","box-shadow","opacity","transform","margin-top","margin-right","margin-bottom","margin-left","padding-top","padding-right","padding-bottom","padding-left","font-family","font-size","font-weight","line-height","letter-spacing","text-align","text-decoration-line","text-transform","flex-direction","justify-content","align-items","gap","z-index","overflow"],Oi={position:"static","background-color":"rgba(0, 0, 0, 0)","background-image":"none","border-top-width":"0px","border-right-width":"0px","border-bottom-width":"0px","border-left-width":"0px","border-style":"none","border-radius":"0px","box-shadow":"none",opacity:"1",transform:"none","margin-top":"0px","margin-right":"0px","margin-bottom":"0px","margin-left":"0px","padding-top":"0px","padding-right":"0px","padding-bottom":"0px","padding-left":"0px","text-decoration-line":"none","flex-direction":"row","justify-content":"normal","align-items":"normal",gap:"normal","z-index":"auto",overflow:"visible"},qi=["color","font-family","font-size","font-weight","line-height","letter-spacing","text-align","text-transform"],Hi=1024*1024,Ui=1500,zi=200;async function ji(t){let e=[];for(let r of t)try{let n=await r.boundingBox();n&&e.push([n.x,n.y,n.width,n.height]);}catch{}return e}async function Ln(t){let e=t.config??{};try{let r=t.maskLocators?.length?await ji(t.maskLocators):[],n=null;if(t.bounded){let a=await t.bounded.boundingBox();a&&(n=[a.x,a.y,a.width,a.height]);}let s={styleProps:Bi,defaults:Oi,inherited:qi,maxNodes:e.maxNodes??Ui,maxText:e.maxText??zi,maskBoxes:r,viewportBox:n,fullPage:t.fullPage===!0};return await t.target.evaluate(Nn,s)}catch{return null}}function Dn(t,e=Hi){let r=JSON.stringify(t);if(Buffer.byteLength(r,"utf-8")<=e)return {json:r,truncatedBytes:false};let n=t.nodes.slice(),s=0;for(;n.length>0&&Buffer.byteLength(r,"utf-8")>e;){let a=Math.max(1,Math.floor(n.length*.1));n.splice(-a,a),s+=a,r=JSON.stringify({...t,nodes:n,truncatedNodes:t.truncatedNodes+s});}return {json:r,truncatedBytes:true}}function Fn(t){return t.replace(/\.[A-Za-z0-9]+$/,"")+".dom.json"}function Bn(t){try{if(!fs$1.existsSync(t))return null;let e=JSON.parse(fs$1.readFileSync(t,"utf-8"));return Vi(e)?e:null}catch{return null}}function On(t,e){try{return fs$1.mkdirSync(path.dirname(t),{recursive:!0}),fs$1.writeFileSync(t,e,"utf-8"),!0}catch{return false}}function Vi(t){if(typeof t!="object"||t===null)return false;let e=t;return typeof e.version=="string"&&Array.isArray(e.nodes)&&Array.isArray(e.captureBox)&&e.captureBox.length===4}var $i=new Set(["moved","resized"]);function Ee(t){return t.some(e=>!$i.has(e))}function Bt(t){let e=t.t;if(t.i&&(e+="#"+t.i),t.c){let r=t.c.split(" ").filter(Boolean).slice(0,3);r.length>0&&(e+="."+r.join("."));}return e}function Wi(t,e){let r=[],n=Math.abs(t.r[0]-e.r[0]),s=Math.abs(t.r[1]-e.r[1]),a=Math.abs(t.r[2]-e.r[2]),i=Math.abs(t.r[3]-e.r[3]);return (n>1||s>1)&&r.push("moved"),(a>1||i>1)&&r.push("resized"),r}function Gi(t,e){let r=t.s??{},n=e.s??{},s=new Set([...Object.keys(r),...Object.keys(n)]),a=[];for(let i of s){let o=r[i],l=n[i];o!==l&&a.push({prop:i,from:o??"(initial)",to:l??"(initial)"});}return a.sort((i,o)=>i.prop.localeCompare(o.prop)),a}function qn(t){return t.i?"i:"+t.t+"#"+t.i:t.c?"c:"+t.t+"."+t.c:null}function Ki(t,e){let r=new Map;for(let u of t)r.set(u.p,u);let n=[],s=[],a=new Set;for(let u of e){let f=r.get(u.p);if(f&&f.t!==u.t){s.push(u);continue}f&&!a.has(f)?(a.add(f),n.push({before:f,after:u})):s.push(u);}let i=t.filter(u=>!a.has(u)),o=new Map;for(let u of i){let f=qn(u);if(!f)continue;let g=o.get(f);g?g.push(u):o.set(f,[u]);}let l=[],d=new Set;for(let u of s){let f=qn(u),p=(f?o.get(f):void 0)?.find(h=>!d.has(h));p?(d.add(p),n.push({before:p,after:u})):l.push(u);}let c=i.filter(u=>!d.has(u));return {pairs:n,removed:c,added:l}}function Ji(t,e){let r=[];return (t.i??"")!==(e.i??"")&&r.push({prop:"id",from:t.i??"(none)",to:e.i??"(none)"}),(t.c??"")!==(e.c??"")&&r.push({prop:"class",from:t.c??"(none)",to:e.c??"(none)"}),r}function Ot(t,e){let r=(e[2]??0)*(e[3]??0);return r<=0?0:Math.min(1,t.r[2]*t.r[3]/r)}function Hn(t,e,r={}){let n=r.maxChanges??50,s=r.includeText!==false,a=r.includeStyles!==false,i=t.nodes.filter(p=>p.m!==1),o=e.nodes.filter(p=>p.m!==1),{pairs:l,removed:d,added:c}=Ki(i,o),u=[];for(let{before:p,after:h}of l){let b=Wi(p,h),v=a?Gi(p,h):[];v.length>0&&b.push("restyled");let m=Ji(p,h);m.length>0&&b.push("attrs");let y=s&&(p.x??"")!==(h.x??"");if(y&&b.push("text"),b.length===0)continue;let w=Ot(h,e.captureBox);u.push({score:w,change:{path:h.p,label:Bt(h),kinds:b,rect:h.r,baselineRect:p.r,areaPct:w,...m.length>0?{attrs:m}:{},...v.length>0?{styles:v}:{},...y?{text:{from:p.x??"",to:h.x??""}}:{}}});}for(let p of c){let h=Ot(p,e.captureBox);u.push({score:h,change:{path:p.p,label:Bt(p),kinds:["added"],rect:p.r,areaPct:h}});}for(let p of d){let h=Ot(p,t.captureBox);u.push({score:h,change:{path:p.p,label:Bt(p),kinds:["removed"],baselineRect:p.r,areaPct:h}});}let f=u.filter(p=>Ee(p.change.kinds)).length;return u.sort((p,h)=>{if(f>0){let b=Ee(p.change.kinds)?1:0,v=Ee(h.change.kinds)?1:0;if(b!==v)return v-b}return h.score-p.score}),{changes:u.slice(0,n).map((p,h)=>({rank:h+1,...p.change,...f>0&&!Ee(p.change.kinds)?{consequence:true}:{}})),total:u.length,rootCauses:f}}var Yi="__testrelic_snapshot_path_probe__.png",Un=Symbol.for("testrelic.snapshotPathWarned");function Xi(){let t=globalThis,e=t[Un];return e||(e={warned:false},t[Un]=e),e}function Ne(t){try{let e=t.snapshotPath(Yi,{kind:"screenshot"});return typeof e=="string"&&!e.includes("[object Object]")}catch{return false}}function Le(t){let e=Xi();e.warned||(e.warned=true,process.stderr.write(`[testrelic] ${t} needs Playwright >= 1.51 for testInfo.snapshotPath(name, { kind }); this project's Playwright resolves that call the older way. Everything else in the reporter is unaffected \u2014 upgrade Playwright to enable it.
|
|
4351
|
-
`));}var
|
|
4350
|
+
`);try{let v=Nt(c,p,s,u,f),y=l+".tmp";fs$1.writeFileSync(y,v,"utf-8"),fs$1.renameSync(y,l);}catch{}}}catch{}}}else if(e.openReport&&t.ci===null&&e.includeArtifacts){let h=path.dirname(e.outputPath),m=path.join(h,"artifacts");if(fs$1.existsSync(m))try{let b=await Cn(m);s=b.port,process.on("exit",()=>{b.dispose();});}catch{}}if(e.openReport&&t.ci===null)if(i&&s)Dt(`http://127.0.0.1:${s}`);else {let h=path.resolve(l);Dt(h);}}catch(s){process.stderr.write(`[testrelic] Failed to write HTML report: ${s instanceof Error?s.message:String(s)}
|
|
4351
|
+
`);}}var Le=9323,_n=10;async function Si(){for(let t=Le;t<Le+_n;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${t}/api/health`,{signal:e.signal});if(clearTimeout(r),n.ok)return t}catch{}return null}async function Ri(){for(let t=Le;t<Le+_n;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 Ai(t){let r=[path.join(__dirname,"cli.cjs"),path.join(__dirname,"cli.js"),path.join(__dirname,"..","dist","cli.cjs"),path.join(__dirname,"..","dist","cli.js")].find(n=>fs$1.existsSync(n));if(!r){let n=await ye(t);return process.on("exit",()=>{n?.dispose();}),n.port}return new Promise(n=>{let s=child_process.spawn(process.execPath,[r,"serve",t],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),a="",i=false,o=setTimeout(()=>{i||(i=true,s.stderr?.removeAllListeners(),Si().then(n));},5e3);s.stderr?.on("data",l=>{a+=l.toString();let d=a.match(/127\.0\.0\.1:(\d+)/);d&&!i&&(i=true,clearTimeout(o),s.stderr?.removeAllListeners(),s.unref(),n(Number(d[1])));}),s.on("error",()=>{i||(i=true,clearTimeout(o),n(null));}),s.on("exit",()=>{i||(i=true,clearTimeout(o),n(null));}),s.unref();})}var In=Buffer.from([137,80,78,71,13,10,26,10]),_i=16,Ii=20,Ne=24;function Mn(t){if(t.length<Ne||!t.subarray(0,In.length).equals(In))return null;let e=t.readUInt32BE(_i),r=t.readUInt32BE(Ii);return e===0||r===0?null:{width:e,height:r}}var Mi=/(?:^|\D)(\d+) pixels \(ratio [\d.]+ of all image pixels\) are different/,Pn=/Expected an image (\d+)px by (\d+)px, received (\d+)px by (\d+)px/;function En(t){return t?Pn.test(t):false}var Pi=/^[ \t]*Snapshot:[ \t]*(\S(?:.*\S)?)[ \t]*$/m;function Ln(t){if(!t)return {};let e={},r=Mi.exec(t);if(r){let a=Number.parseInt(r[1],10);Number.isFinite(a)&&(e.diffPixels=a);}let n=Pn.exec(t);if(n){let[,a,i,o,l]=n,d=[a,i,o,l].map(c=>Number.parseInt(c,10));d.every(c=>Number.isFinite(c))&&(e.expectedWidth=d[0],e.expectedHeight=d[1],e.actualWidth=d[2],e.actualHeight=d[3]);}let s=Pi.exec(t);return s&&(e.snapshotName=s[1]),e}function Nn(t,e){if(t===void 0||!e)return;let r=e.width*e.height;if(!(r<=0))return t/r}var Oi=20,zt=0,jt=[];async function be(t,e){zt>=Oi&&await new Promise(r=>jt.push(r)),zt++;try{return await promises.copyFile(t,e),!0}catch{return false}finally{zt--,jt.length>0&&jt.shift()();}}var J=[];async function Bn(){J.length!==0&&(await Promise.allSettled(J),J.length=0);}function On(t){let e=new Date,r=a=>String(a).padStart(2,"0"),n=`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())}T${r(e.getHours())}-${r(e.getMinutes())}-${r(e.getSeconds())}`;if(!fs$1.existsSync(path.join(t,n)))return n;let s=1;for(;fs$1.existsSync(path.join(t,`${n}-${s}`));)s++;return `${n}-${s}`}function Vt(t){let e=t.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-|-$/g,"");return e.length>100&&(e=e.substring(0,100).replace(/-+$/,"")),e||"unnamed-test"}var qi=8;function qn(t,e,r){let n=Vt(t),s=r?Vt(r).substring(0,qi):"";return s&&(n+=`--${s}`),e>0&&(n+=`--retry-${e}`),n}function Hn(t,e,r,n,s,a){let i=t.find(g=>g.name==="screenshot"&&g.path),o=t.find(g=>g.name==="video"&&g.path),l=t.find(g=>g.name==="trace"&&g.path);if(!i&&!o&&!l)return null;let d=qn(e,r,a),c=s?["artifacts",s,d]:["artifacts",d],p=path.join(n,...c),u=c,f={};try{fs$1.mkdirSync(p,{recursive:!0});}catch{return null}if(i?.path&&fs$1.existsSync(i.path)){let h=`screenshot${path.extname(i.path)||".png"}`,m=path.join(p,h);J.push(be(i.path,m).then(()=>{})),f.screenshot=`${u.join("/")}/${h}`;}if(o?.path&&fs$1.existsSync(o.path)){let h=`video${path.extname(o.path)||".webm"}`,m=path.join(p,h);J.push(be(o.path,m).then(()=>{})),f.video=`${u.join("/")}/${h}`;}if(l?.path&&fs$1.existsSync(l.path)){let h=`trace${path.extname(l.path)||".zip"}`,m=path.join(p,h);J.push(be(l.path,m).then(()=>{})),f.trace=`${u.join("/")}/${h}`;}return !f.screenshot&&!f.video&&!f.trace?null:f}var $t="visual",Hi=6;function Ui(t){let e=crypto.createHash("sha256").update(t).digest("hex").substring(0,Hi);return `${Vt(t)}--${e}`}function Dn(t){let e=null;try{e=fs$1.openSync(t,"r");let r=Buffer.alloc(Ne),n=fs$1.readSync(e,r,0,Ne,0);return Mn(r.subarray(0,n))}catch{return null}finally{if(e!==null)try{fs$1.closeSync(e);}catch{}}}var Fn=[{key:"expectedPath",dest:"baseline",field:"baseline"},{key:"actualPath",dest:"actual",field:"actual"},{key:"diffPath",dest:"diff",field:"diff"},{key:"previousPath",dest:"previous",field:"previous"}],zi=[{key:"baselineDomPath",dest:"baseline.dom.json",field:"baselineDom"},{key:"actualDomPath",dest:"actual.dom.json",field:"actualDom"}];function ji(t,e,r,n){let s=Ui(t.name),a=path.join(e,s),i=Fn.some(g=>t[g.key]);if(i||t.dom)try{fs$1.mkdirSync(a,{recursive:!0});}catch{return null}let o={},l=false;for(let g of Fn){let h=t[g.key];if(!h||!fs$1.existsSync(h))continue;let m=path.extname(h)||".png",b=`${g.dest}${m}`;J.push(be(h,path.join(a,b)).then(()=>{})),o[g.field]=`${r}/${$t}/${s}/${b}`,l=true;}let d=t.dom;if(d)for(let g of zi){let h=d[g.key];!h||!fs$1.existsSync(h)||(J.push(be(h,path.join(a,g.dest)).then(()=>{})),o[g.field]=`${r}/${$t}/${s}/${g.dest}`);}if(!l&&i)return null;let c=t.expectedPath?Dn(t.expectedPath):t.actualPath?Dn(t.actualPath):null,p=Nn(t.diffPixels,c),u=t.committedPath??t.expectedPath,f=u?path.relative(n,u).replace(/\\/g,"/"):void 0;return {name:t.name,status:t.status,source:t.source,...o,...f?{baselinePath:f}:{},...c?{width:c.width,height:c.height}:{},...t.actualWidth!==void 0?{actualWidth:t.actualWidth}:{},...t.actualHeight!==void 0?{actualHeight:t.actualHeight}:{},...t.diffPixels!==void 0?{diffPixels:t.diffPixels}:{},...p!==void 0?{diffPixelRatio:p}:{},...d?{domChanges:d.changes,domChangeCount:d.total,domRootCauses:d.rootCauses,domTruncated:d.truncated,domCaptureBox:d.captureBox}:{}}}function Un(t,e,r,n,s,a,i=process.cwd()){if(t.length===0)return null;let o=qn(e,r,a),l=s?["artifacts",s,o]:["artifacts",o],d=path.join(n,...l,$t),c=l.join("/");try{fs$1.mkdirSync(d,{recursive:!0});}catch{return null}let p=[];for(let u of t){let f=ji(u,d,c,i);f&&p.push(f);}return p.length>0?p:null}function zn(t){let{styleProps:e,defaults:r,inherited:n,maxNodes:s,maxText:a,maskBoxes:i,viewportBox:o,fullPage:l}=t,d={};for(let T=0;T<n.length;T++)d[n[T]]=true;let c=window.scrollX||window.pageXOffset||0,p=window.scrollY||window.pageYOffset||0,u=[],f=0,g=[];for(let T=0;T<i.length;T++){let k=i[T];g.push([k[0]+c,k[1]+p,k[2],k[3]]);}function h(T,k,R,w){for(let S=0;S<g.length;S++){let A=g[S];if(T<A[0]+A[2]&&T+R>A[0]&&k<A[1]+A[3]&&k+w>A[1])return true}return false}function m(T){let k=T.parentElement;if(!k)return 0;let R=k.children,w=0;for(let S=0;S<R.length;S++){let A=R[S];if(A===T)break;A.tagName===T.tagName&&w++;}return w}function b(T){let k="",R=T.childNodes;for(let w=0;w<R.length;w++){let S=R[w];S.nodeType===3&&(k+=S.nodeValue??"");}return k=k.replace(/\s+/g," ").trim(),k.length>a?k.slice(0,a):k}function v(T,k){let R;for(let w=0;w<e.length;w++){let S=e[w],A=T.getPropertyValue(S);if(A){if(d[S]){if(k&&k.getPropertyValue(S)===A)continue}else if(r[S]===A)continue;R||(R={}),R[S]=A;}}return R}let y=[{el:document.body,parentPath:"",parentComputed:null}];for(;y.length>0;){let T=y.pop(),k=T.el,R=window.getComputedStyle(k);if(R.display==="none")continue;let w=k.tagName.toLowerCase(),S=k.id?"#"+k.id:T.parentPath?T.parentPath+">"+w+"["+m(k)+"]":w,A=k.children;for(let j=A.length-1;j>=0;j--)y.push({el:A[j],parentPath:S,parentComputed:R});if(R.visibility==="hidden")continue;let N=k.getBoundingClientRect();if(N.width<=0||N.height<=0)continue;if(u.length>=s){f++;continue}let pe=Math.round(N.left+c),fe=Math.round(N.top+p),se=Math.round(N.width),q=Math.round(N.height),M={p:S,t:w,r:[pe,fe,se,q]};k.id&&(M.i=k.id);let P=k.getAttribute("class");P&&(M.c=P.replace(/\s+/g," ").trim());let E=b(k);E&&(M.x=E);let F=v(R,T.parentComputed);F&&(M.s=F),h(pe,fe,se,q)&&(M.m=1),u.push(M);}let x=Math.max(document.documentElement.scrollWidth,window.innerWidth),C=Math.max(document.documentElement.scrollHeight,window.innerHeight),I;return o?I=[Math.round(o[0]+c),Math.round(o[1]+p),Math.round(o[2]),Math.round(o[3])]:l?I=[0,0,x,C]:I=[Math.round(c),Math.round(p),window.innerWidth,window.innerHeight],{version:"1.0",url:location.href,viewport:{width:window.innerWidth,height:window.innerHeight},content:{width:x,height:C},captureBox:I,nodes:u,truncatedNodes:f}}var Ji=["display","position","color","background-color","background-image","border-top-width","border-right-width","border-bottom-width","border-left-width","border-color","border-style","border-radius","box-shadow","opacity","transform","margin-top","margin-right","margin-bottom","margin-left","padding-top","padding-right","padding-bottom","padding-left","font-family","font-size","font-weight","line-height","letter-spacing","text-align","text-decoration-line","text-transform","flex-direction","justify-content","align-items","gap","z-index","overflow"],Yi={position:"static","background-color":"rgba(0, 0, 0, 0)","background-image":"none","border-top-width":"0px","border-right-width":"0px","border-bottom-width":"0px","border-left-width":"0px","border-style":"none","border-radius":"0px","box-shadow":"none",opacity:"1",transform:"none","margin-top":"0px","margin-right":"0px","margin-bottom":"0px","margin-left":"0px","padding-top":"0px","padding-right":"0px","padding-bottom":"0px","padding-left":"0px","text-decoration-line":"none","flex-direction":"row","justify-content":"normal","align-items":"normal",gap:"normal","z-index":"auto",overflow:"visible"},Xi=["color","font-family","font-size","font-weight","line-height","letter-spacing","text-align","text-transform"],Zi=1024*1024,Qi=1500,eo=200;async function to(t){let e=[];for(let r of t)try{let n=await r.boundingBox();n&&e.push([n.x,n.y,n.width,n.height]);}catch{}return e}async function jn(t){let e=t.config??{};try{let r=t.maskLocators?.length?await to(t.maskLocators):[],n=null;if(t.bounded){let a=await t.bounded.boundingBox();a&&(n=[a.x,a.y,a.width,a.height]);}let s={styleProps:Ji,defaults:Yi,inherited:Xi,maxNodes:e.maxNodes??Qi,maxText:e.maxText??eo,maskBoxes:r,viewportBox:n,fullPage:t.fullPage===!0};return await t.target.evaluate(zn,s)}catch{return null}}function Vn(t,e=Zi){let r=JSON.stringify(t);if(Buffer.byteLength(r,"utf-8")<=e)return {json:r,truncatedBytes:false};let n=t.nodes.slice(),s=0;for(;n.length>0&&Buffer.byteLength(r,"utf-8")>e;){let a=Math.max(1,Math.floor(n.length*.1));n.splice(-a,a),s+=a,r=JSON.stringify({...t,nodes:n,truncatedNodes:t.truncatedNodes+s});}return {json:r,truncatedBytes:true}}function $n(t){return t.replace(/\.[A-Za-z0-9]+$/,"")+".dom.json"}function Wn(t){try{if(!fs$1.existsSync(t))return null;let e=JSON.parse(fs$1.readFileSync(t,"utf-8"));return ro(e)?e:null}catch{return null}}function Gn(t,e){try{return fs$1.mkdirSync(path.dirname(t),{recursive:!0}),fs$1.writeFileSync(t,e,"utf-8"),!0}catch{return false}}function ro(t){if(typeof t!="object"||t===null)return false;let e=t;return typeof e.version=="string"&&Array.isArray(e.nodes)&&Array.isArray(e.captureBox)&&e.captureBox.length===4}var no=new Set(["moved","resized"]);function Fe(t){return t.some(e=>!no.has(e))}function Gt(t){let e=t.t;if(t.i&&(e+="#"+t.i),t.c){let r=t.c.split(" ").filter(Boolean).slice(0,3);r.length>0&&(e+="."+r.join("."));}return e}function so(t,e){let r=[],n=Math.abs(t.r[0]-e.r[0]),s=Math.abs(t.r[1]-e.r[1]),a=Math.abs(t.r[2]-e.r[2]),i=Math.abs(t.r[3]-e.r[3]);return (n>1||s>1)&&r.push("moved"),(a>1||i>1)&&r.push("resized"),r}function ao(t,e){let r=t.s??{},n=e.s??{},s=new Set([...Object.keys(r),...Object.keys(n)]),a=[];for(let i of s){let o=r[i],l=n[i];o!==l&&a.push({prop:i,from:o??"(initial)",to:l??"(initial)"});}return a.sort((i,o)=>i.prop.localeCompare(o.prop)),a}function Kn(t){return t.i?"i:"+t.t+"#"+t.i:t.c?"c:"+t.t+"."+t.c:null}function io(t,e){let r=new Map;for(let p of t)r.set(p.p,p);let n=[],s=[],a=new Set;for(let p of e){let u=r.get(p.p);if(u&&u.t!==p.t){s.push(p);continue}u&&!a.has(u)?(a.add(u),n.push({before:u,after:p})):s.push(p);}let i=t.filter(p=>!a.has(p)),o=new Map;for(let p of i){let u=Kn(p);if(!u)continue;let f=o.get(u);f?f.push(p):o.set(u,[p]);}let l=[],d=new Set;for(let p of s){let u=Kn(p),g=(u?o.get(u):void 0)?.find(h=>!d.has(h));g?(d.add(g),n.push({before:g,after:p})):l.push(p);}let c=i.filter(p=>!d.has(p));return {pairs:n,removed:c,added:l}}function oo(t,e){let r=[];return (t.i??"")!==(e.i??"")&&r.push({prop:"id",from:t.i??"(none)",to:e.i??"(none)"}),(t.c??"")!==(e.c??"")&&r.push({prop:"class",from:t.c??"(none)",to:e.c??"(none)"}),r}function Kt(t,e){let r=(e[2]??0)*(e[3]??0);return r<=0?0:Math.min(1,t.r[2]*t.r[3]/r)}function Jn(t,e,r={}){let n=r.maxChanges??50,s=r.includeText!==false,a=r.includeStyles!==false,i=t.nodes.filter(g=>g.m!==1),o=e.nodes.filter(g=>g.m!==1),{pairs:l,removed:d,added:c}=io(i,o),p=[];for(let{before:g,after:h}of l){let m=so(g,h),b=a?ao(g,h):[];b.length>0&&m.push("restyled");let v=oo(g,h);v.length>0&&m.push("attrs");let y=s&&(g.x??"")!==(h.x??"");if(y&&m.push("text"),m.length===0)continue;let x=Kt(h,e.captureBox);p.push({score:x,change:{path:h.p,label:Gt(h),kinds:m,rect:h.r,baselineRect:g.r,areaPct:x,...v.length>0?{attrs:v}:{},...b.length>0?{styles:b}:{},...y?{text:{from:g.x??"",to:h.x??""}}:{}}});}for(let g of c){let h=Kt(g,e.captureBox);p.push({score:h,change:{path:g.p,label:Gt(g),kinds:["added"],rect:g.r,areaPct:h}});}for(let g of d){let h=Kt(g,t.captureBox);p.push({score:h,change:{path:g.p,label:Gt(g),kinds:["removed"],baselineRect:g.r,areaPct:h}});}let u=p.filter(g=>Fe(g.change.kinds)).length;return p.sort((g,h)=>{if(u>0){let m=Fe(g.change.kinds)?1:0,b=Fe(h.change.kinds)?1:0;if(m!==b)return b-m}return h.score-g.score}),{changes:p.slice(0,n).map((g,h)=>({rank:h+1,...g.change,...u>0&&!Fe(g.change.kinds)?{consequence:true}:{}})),total:p.length,rootCauses:u}}var lo="__testrelic_snapshot_path_probe__.png",Yn=Symbol.for("testrelic.snapshotPathWarned");function co(){let t=globalThis,e=t[Yn];return e||(e={warned:false},t[Yn]=e),e}function Be(t){try{let e=t.snapshotPath(lo,{kind:"screenshot"});return typeof e=="string"&&!e.includes("[object Object]")}catch{return false}}function Oe(t){let e=co();e.warned||(e.warned=true,process.stderr.write(`[testrelic] ${t} needs Playwright >= 1.51 for testInfo.snapshotPath(name, { kind }); this project's Playwright resolves that call the older way. Everything else in the reporter is unaffected \u2014 upgrade Playwright to enable it.
|
|
4352
|
+
`));}var Jt="testrelic-visual-dom",ho=new Set(["toHaveScreenshot","toMatchVisualBaseline"]);function Xn(t){if(typeof t!="object"||t===null)return false;let e=t;return typeof e.boundingBox=="function"&&typeof e.page=="function"}function mo(t){if(typeof t!="object"||t===null)return false;let e=t;return typeof e.evaluate=="function"&&typeof e.screenshot=="function"}function vo(t){let e=t[0];if(typeof e=="string")return e;if(Array.isArray(e))return e.join("/");if(typeof e=="object"&&e!==null){let r=e.name;if(typeof r=="string")return r}return null}function yo(t){for(let e of t)if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e;return {}}function bo(t){let e=t.mask;return Array.isArray(e)?e.filter(r=>typeof r=="object"&&r!==null&&typeof r.boundingBox=="function"):[]}function xo(t){return /\.(png|jpg|jpeg)$/i.test(t)?t:`${t}.png`}var wo=/^(.+)-(expected|actual|diff|previous)\.[A-Za-z0-9]+$/;function ko(t,e,r){let n=t.attachments;for(let s=e;s<n.length;s++){let a=wo.exec(n[s]?.name??"");if(a)return a[1]}return r}async function Co(t){let e=yo(t.args),r=Xn(t.received)?t.received:null,n=r?r.page():t.received;return jn({target:n,bounded:r,maskLocators:bo(e),fullPage:e.fullPage===true})}function To(t){let e=t.config?.updateSnapshots;return e==="all"||e==="changed"}async function So(t,e){let r=vo(t.args);if(!r)return;if(!Be(t.testInfo)){Oe("DOM comparison");return}let n=t.testInfo.snapshotPath(xo(r),{kind:"screenshot"}),s=$n(n),a=ko(t.testInfo,t.attachedBefore,path.basename(n,path.extname(n))),i=Vn(e),l=To(t.testInfo)?null:Wn(s);if(!l){Gn(s,i.json);return}let{changes:d,total:c,rootCauses:p}=Jn(l,e),u;try{u=t.testInfo.outputPath(`${a}.actual.dom.json`),fs$1.writeFileSync(u,i.json,"utf-8");}catch{u=void 0;}let f={stem:a,changes:d,total:c,rootCauses:p,truncated:i.truncatedBytes||e.truncatedNodes>0,captureBox:e.captureBox,...fs$1.existsSync(s)?{baselineDomPath:s}:{},...u?{actualDomPath:u}:{}};await t.testInfo.attach(Jt,{body:Buffer.from(JSON.stringify([f])),contentType:"application/json"});}function Zn(t,e){let r=function(i,...o){let l=t(i,...o);return !(Xn(i)||mo(i))||typeof l!="object"||l===null?l:new Proxy(l,{get(c,p,u){let f=Reflect.get(c,p,u);if(typeof p!="string"||!ho.has(p)||typeof f!="function")return f;let g=f;return async function(...m){let b=e(),v=null,y=b?.attachments.length??0;if(b)try{v=await Co({received:i,args:m,testInfo:b,attachedBefore:y});}catch{}try{return await g.apply(c,m)}finally{if(b&&v)try{await So({received:i,args:m,testInfo:b,attachedBefore:y},v);}catch{}}}}})},n=t,s=r;for(let a of Object.keys(n))s[a]=n[a];return r}var Yt="testrelic-visual",Ro=/^(.+)-(expected|actual|diff|previous)(\.[A-Za-z0-9]+)$/;function Ao(t){let e=new Map;for(let r of t)if(!(r.name!==Yt||!r.body))try{let n=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(n))continue;for(let s of n){let a=Io(s);a&&e.set(a.stem,a);}}catch{}return e}var _o=["passed","failed","new","updated"];function Io(t){if(typeof t!="object"||t===null)return null;let e=t;return typeof e.stem!="string"||!e.stem||typeof e.name!="string"||!e.name||typeof e.status!="string"||!_o.includes(e.status)?null:{stem:e.stem,name:e.name,status:e.status,...typeof e.committedPath=="string"&&e.committedPath?{committedPath:e.committedPath}:{}}}function Mo(t){let e=new Map;for(let r of t)if(!(r.name!==Jt||!r.body))try{let n=JSON.parse(r.body.toString("utf-8"));if(!Array.isArray(n))continue;for(let s of n){if(typeof s!="object"||s===null)continue;let a=s;typeof a.stem!="string"||!Array.isArray(a.changes)||e.set(a.stem,s);}}catch{}return e}function Po(t){let e=new Map;for(let r of t){if(!r.path)continue;let n=Ro.exec(r.name);if(!n)continue;let[,s,a]=n,i=e.get(s)??{};i[a]=r.path,e.set(s,i);}return e}function Eo(t){return !!(t.actual&&(t.expected||t.diff))}function Lo(t,e,r){return t.diff||En(r)?"failed":e?"updated":"new"}function No(t,e){if(t.length===0)return null;if(t.length===1)return t[0];if(!e)return null;let r=e.replace(/\.[A-Za-z0-9]+$/,""),n=t.filter(s=>s===r||s.endsWith(`/${r}`));return n.length===1?n[0]:null}function ts(t,e={}){if(t.length===0)return [];let r=Ao(t),n=Mo(t),s=Po(t);if(s.size===0&&r.size===0)return [];let a=e.updatingSnapshots===true,i=[];for(let[o,l]of s){let d=r.get(o);!d&&!Eo(l)||i.push({name:d?.name??o,status:d?.status??Lo(l,a,e.failureMessage),source:d?"toMatchVisualBaseline":"toHaveScreenshot",...l.expected?{expectedPath:l.expected}:{},...d?.committedPath?{committedPath:d.committedPath}:{},...l.actual?{actualPath:l.actual}:{},...l.diff?{diffPath:l.diff}:{},...l.previous?{previousPath:l.previous}:{},...n.has(o)?{dom:n.get(o)}:{}});}for(let[o,l]of r)s.has(o)||i.push({name:l.name,status:l.status,source:"toMatchVisualBaseline",...l.committedPath?{committedPath:l.committedPath}:{},...n.has(o)?{dom:n.get(o)}:{}});return Do(i,s,e.failureMessage)}function Do(t,e,r){let n=Ln(r);if(n.diffPixels===void 0&&n.actualWidth===void 0)return [...t];let s=t.filter(i=>i.status==="failed"&&Qn(i)).map(i=>es(i,e)),a=No(s,n.snapshotName);return a===null?[...t]:t.map(i=>Qn(i)&&es(i,e)===a?{...i,...n.diffPixels!==void 0?{diffPixels:n.diffPixels}:{},...n.actualWidth!==void 0?{actualWidth:n.actualWidth}:{},...n.actualHeight!==void 0?{actualHeight:n.actualHeight}:{}}:i)}function Qn(t){return !!(t.expectedPath||t.actualPath||t.diffPath||t.previousPath)}function es(t,e){if(e.has(t.name))return t.name;for(let[r,n]of e)if(n.actual===t.actualPath&&n.expected===t.expectedPath&&n.diff===t.diffPath)return r;return t.name}var Fo=new RegExp("[\x1B\x9B][[\\]()#;?]*(?:\\d{1,4}(?:;\\d{0,4})*)?[0-9A-PR-TZcf-nqry=><]","g");function ie(t){return !t||t.indexOf("\x1B")===-1&&t.indexOf("\x9B")===-1?t:t.replace(Fo,"")}function rs(t){return t==null?null:ie(t)}var Bo=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Oo="1.0",Xt="visual";function is(t){let e=path.extname(t).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(e)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(e)?"video":e===".zip"&&path.basename(t,e)==="trace"?"trace":"other"}function qo(t){if(t.endsWith(".dom.json"))return "dom";let e=path.basename(t,path.extname(t));return e==="baseline"?"baseline":e==="diff"?"diff":is(t)}function Ho(t,e,r){let n=[];try{for(let s of fs$1.readdirSync(t,{withFileTypes:!0})){if(!s.isFile())continue;let a=fs$1.statSync(path.join(t,s.name));n.push({name:`${Xt}/${r}/${s.name}`,type:qo(s.name),relativePath:`${e}/${Xt}/${r}/${s.name}`,sizeBytes:a.size});}}catch{}return n}function os(t,e,r){let n=[],s=`artifacts/${e}/${r}`;try{let a=fs$1.readdirSync(t,{withFileTypes:!0});for(let i of a){if(i.isDirectory()&&i.name===Xt){let d=path.join(t,i.name);for(let c of fs$1.readdirSync(d,{withFileTypes:!0}))c.isDirectory()&&n.push(...Ho(path.join(d,c.name),s,c.name));continue}if(!i.isFile())continue;let o=path.join(t,i.name),l=fs$1.statSync(o);n.push({name:i.name,type:is(i.name),relativePath:`${s}/${i.name}`,sizeBytes:l.size});}}catch{}return {testName:r,files:n}}function Uo(t,e){let r=path.join(t,e),n=[],s=0;try{let i=fs$1.readdirSync(r,{withFileTypes:!0});for(let o of i){if(!o.isDirectory())continue;let l=os(path.join(r,o.name),e,o.name);n.push(l);for(let d of l.files)s+=d.sizeBytes;}}catch{}let a=e.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return n.sort((i,o)=>i.testName.localeCompare(o.testName)),{folderName:e,timestamp:a,totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}}function ls(t,e){let r=path.join(t,"artifacts"),n=[],s=[],a=0;try{let o=fs$1.readdirSync(r,{withFileTypes:!0});for(let l of o)if(l.isDirectory())if(Bo.test(l.name)){let d=Uo(r,l.name);n.push({...d,isCurrentRun:l.name===e});}else {let d=os(path.join(r,l.name),l.name,l.name);s.push(d);for(let c of d.files)a+=c.sizeBytes;}}catch{}n.sort((o,l)=>l.timestamp.localeCompare(o.timestamp)),s.length>0&&(s.sort((o,l)=>o.testName.localeCompare(l.testName)),n.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:a,testCount:s.length,tests:s,isCurrentRun:false}));let i=n.reduce((o,l)=>o+l.totalSizeBytes,0);return {schemaVersion:Oo,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:i,runs:n,serverPort:null}}var Go=256;function Ko(t){let e=path.resolve(t);for(let r=0;r<Go;r++){if(fs$1.existsSync(path.join(e,".git")))return e;let n=path.dirname(e);if(n===e)return null;e=n;}return null}function us(t){try{let e=Ko(t);if(!e)return;let r=path.join(e,".gitignore"),n=path.relative(e,t).replace(/\\/g,"/"),s=n.endsWith("/")?n:`${n}/`;if(fs$1.existsSync(r)&&fs$1.readFileSync(r,"utf-8").split(`
|
|
4352
4353
|
`).map(l=>l.trim()).some(l=>l===s||l===n))return;let a=`
|
|
4353
4354
|
# TestRelic test artifacts
|
|
4354
4355
|
${s}
|
|
4355
|
-
`;fs$1.appendFileSync(r,a,"utf-8");}catch{}}var
|
|
4356
|
+
`;fs$1.appendFileSync(r,a,"utf-8");}catch{}}var ps=Symbol("testrelic.timeout"),fs=3e4,Zt=12e4,Qt=6e4,gs=15e3;async function te(t,e,r){let n,s=new Promise(a=>{n=setTimeout(()=>a(ps),e),typeof n?.unref=="function"&&n.unref();});try{let a=await Promise.race([t(),s]);if(a===ps){process.stderr.write(`[testrelic] ${r} timed out after ${Math.round(e/1e3)}s \u2014 continuing without it. Your tests are unaffected.
|
|
4356
4357
|
`);return}return a}catch(a){process.stderr.write(`[testrelic] ${r} failed \u2014 continuing without it. Your tests are unaffected. (${a instanceof Error?a.message:String(a)})
|
|
4357
|
-
`);return}finally{n&&clearTimeout(n);}}function
|
|
4358
|
-
`}function
|
|
4358
|
+
`);return}finally{n&&clearTimeout(n);}}function vs(t,e){let r=[];for(let n of t){let s=Jo(n),a=Yo(n),i=Xo(n,s,a,e),o=Zo(n,s,a);if(i.length===0&&o.length===0){r.push({type:"navigation",url:"about:blank",timestamp:n.startedAt,durationOnUrl:n.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:n.specFile,test:s,tests:[a],_testTitle:n.title});continue}r.push(...i,...o);}return r.sort(Qo),el(r,t),r.map((n,s)=>n.type==="navigation"?{...{index:s,type:"navigation",url:n.url,timestamp:n.timestamp,durationOnUrl:n.durationOnUrl??0,navigationType:n.navigationType,domContentLoadedAt:n.domContentLoadedAt??null,networkIdleAt:n.networkIdleAt??null,networkStats:n.networkStats??null,specFile:n.specFile,test:n.test},tests:n.tests}:{...{index:s,type:"api_call",callId:n.callId,method:n.method,url:n.url,timestamp:n.timestamp,responseTime:n.responseTime??null,request:n.request,response:n.response??null,...n.error?{error:n.error}:{},assertions:n.assertions??[],specFile:n.specFile,test:n.test},tests:n.tests})}function Jo(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 Yo(t){return {title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retryCount:t.retryCount,retry:t.retry,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 Xo(t,e,r,n){let s=[];for(let a of t.navigations)n.navigationTypes!==null&&!n.navigationTypes.includes(a.navigationType)||s.push({type:"navigation",url:a.url,timestamp:a.timestamp,durationOnUrl:0,navigationType:a.navigationType,domContentLoadedAt:a.domContentLoadedAt??null,networkIdleAt:a.networkIdleAt??null,networkStats:a.networkStats??null,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title});return s}function Zo(t,e,r){if(!t.apiCalls||t.apiCalls.length===0)return [];let n=t.apiAssertions??[];return t.apiCalls.map(s=>{let a=n.filter(o=>o.callId===s.id).map(o=>({type:o.type,expected:o.expected,actual:o.actual,status:o.status,location:o.location,...o.expression!==void 0?{expression:o.expression}:{}})),i=null;return s.responseStatusCode!==null&&s.responseStatusText!==null&&(i={statusCode:s.responseStatusCode,statusText:s.responseStatusText,headers:s.responseHeaders,body:ms(s.responseBody)}),{type:"api_call",callId:s.id,method:s.method,url:s.url,timestamp:s.timestamp,responseTime:s.error?null:s.responseTimeMs,request:{headers:s.requestHeaders,body:ms(s.requestBody)},response:i,...s.error?{error:s.error}:{},assertions:a,specFile:t.specFile,test:e,tests:[r],_testTitle:t.title}})}function Qo(t,e){let r=new Date(t.timestamp).getTime(),n=new Date(e.timestamp).getTime();if(r!==n)return r-n;let s={navigation:0,api_call:1},a=s[t.type],i=s[e.type];return a!==i?a-i:t.type==="api_call"&&e.type==="api_call"&&t.callId&&e.callId?hs(t.callId)-hs(e.callId):0}function hs(t){let e=t.match(/(\d+)$/);return e?parseInt(e[1],10):0}function el(t,e){for(let r=0;r<t.length;r++){let n=t[r];if(n.type!=="navigation")continue;let s=new Date(n.timestamp).getTime(),a=null;for(let i=r+1;i<t.length;i++)if(t[i]._testTitle===n._testTitle&&t[i].test.retry===n.test.retry){a=new Date(t[i].timestamp).getTime();break}if(a!==null)n.durationOnUrl=Math.max(0,a-s);else {let i=e.find(o=>o.title===n._testTitle&&o.retry===n.test.retry);if(i){let o=new Date(i.completedAt).getTime();n.durationOnUrl=Math.max(0,o-s);}}}}function ms(t){if(t==null)return null;try{return JSON.parse(t)}catch{return t}}function re(t,e){let r=t.length,n=Math.min(Math.ceil(e/100*r)-1,r-1);return t[Math.max(0,n)]}function er(t){try{let e=new URL(t);return e.origin+e.pathname}catch{return t}}function tl(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 ys(t,e){let r=0,n=0,s=0,a=0,i=0;for(let w of t)switch(w.status){case "passed":r++;break;case "failed":n++;break;case "flaky":s++;break;case "skipped":a++;break;case "timedout":i++;break}let o=[];for(let w of t)w.apiCalls&&o.push(...w.apiCalls);let l=o.length,d=new Set,c={},p={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},u=[];for(let w of o)d.add(er(w.url)),c[w.method]=(c[w.method]??0)+1,p[tl(w.responseStatusCode)]+=1,u.push(w.responseTimeMs);let f=null;if(u.length>0){let w=[...u].sort((A,N)=>A-N),S=w.reduce((A,N)=>A+N,0);f={avg:Math.round(S/w.length),min:w[0],max:w[w.length-1],p50:re(w,50),p95:re(w,95),p99:re(w,99)};}let g=0,h=0,m=0;for(let w of t)if(w.apiAssertions)for(let S of w.apiAssertions)g++,S.status==="passed"?h++:m++;let b=0,v=new Set;for(let w of t){b+=w.navigations.length;for(let S of w.navigations)v.add(S.url);}let y=0,x={};function C(w){for(let S of w)y++,x[S.category]=(x[S.category]??0)+1,S.children.length>0&&C(S.children);}for(let w of t)w.actions&&C(w.actions);let I=0,T=0,k=0,R=0;for(let w of t)if(w.visual)for(let S of w.visual)I++,S.status==="failed"?T++:(S.status==="new"||S.status==="updated")&&k++,R+=S.domChangeCount??0;return {total:t.length,passed:r,failed:n,flaky:s,skipped:a,timedout:i,totalApiCalls:l,uniqueApiUrls:d.size,apiCallsByMethod:c,apiCallsByStatusRange:p,apiResponseTime:f,totalAssertions:g,passedAssertions:h,failedAssertions:m,totalNavigations:b,uniqueNavigationUrls:v.size,totalTimelineSteps:e,totalActionSteps:y,actionStepsByCategory:x,visualChecks:I,visualFailures:T,visualNew:k,visualDomChanges:R}}function rl(t){let e=56-t.length;return e>0?t+" ".repeat(e):t}function D(t){return `\u2502 ${rl(t)} \u2502
|
|
4359
|
+
`}function tr(t,e,r,n,s){if(n||t.total===0)return;let a=`\u250C${"\u2500".repeat(58)}\u2510
|
|
4359
4360
|
`,i=`\u2514${"\u2500".repeat(58)}\u2518
|
|
4360
|
-
`,o=
|
|
4361
|
-
`,process.stderr.write(l);}var
|
|
4362
|
-
`)[0]?.trim();return n?
|
|
4363
|
-
`),n=JSON.stringify(
|
|
4364
|
-
`),n=JSON.stringify(
|
|
4365
|
-
`),n=JSON.stringify(
|
|
4366
|
-
`),n=JSON.stringify(
|
|
4361
|
+
`,o=D(""),l=a;l+=D("TestRelic AI - Playwright Test Report"),l+=o;let d=s??t,c=[];if(d.passed>0&&c.push(`${d.passed} \u2713`),d.failed>0&&c.push(`${d.failed} \u2717`),d.flaky>0&&c.push(`${d.flaky} \u26A0`),d.skipped>0&&c.push(`${d.skipped} skipped`),d.timedout>0&&c.push(`${d.timedout} timedout`),l+=D(`Tests: ${t.total} total (${c.join(" ")})`),s&&s.expectedFailures>0&&(l+=D(` ${s.expectedFailures} failed as expected (test.fail)`)),s&&s.unexpectedPasses>0&&(l+=D(` ${s.unexpectedPasses} expected to fail, but passed (test.fail)`)),t.totalNavigations>0&&(l+=D(`Navigations: ${t.totalNavigations} visits across ${t.uniqueNavigationUrls} unique URLs`)),t.totalApiCalls>0){l+=D(`API Calls: ${t.totalApiCalls} calls across ${t.uniqueApiUrls} unique endpoints`);let p=Object.entries(t.apiCallsByMethod).filter(([,f])=>f>0).map(([f,g])=>`${f}: ${g}`);p.length>0&&(l+=D(` ${p.join(" ")}`));let u=Object.entries(t.apiCallsByStatusRange).filter(([,f])=>f>0).map(([f,g])=>`${f}: ${g}`);u.length>0&&(l+=D(` ${u.join(" ")}`)),t.apiResponseTime&&(l+=D(` Avg response: ${t.apiResponseTime.avg}ms P95: ${t.apiResponseTime.p95}ms`));}if(t.totalAssertions>0&&(l+=D(`Assertions: ${t.totalAssertions} total (${t.passedAssertions} \u2713 ${t.failedAssertions} \u2717)`)),t.totalActionSteps>0){let p=[],u=t.actionStepsByCategory;u.ui_action&&p.push(`${u.ui_action} UI`),u.assertion&&p.push(`${u.assertion} assertions`),u.custom_step&&p.push(`${u.custom_step} custom`);let f=p.length>0?` (${p.join(" ")})`:"";l+=D(`Actions: ${t.totalActionSteps} steps${f}`);}l+=D(`Report: ${r}`),l+=D(`Data: ${e}`),l+=i,l+=`For more information visit us at https://docs.testrelic.ai
|
|
4362
|
+
`,process.stderr.write(l);}var nl=new Set(["pw:api","expect","test.step"]);function sl(t){return t==="expect"?"assertion":t==="test.step"?"custom_step":"ui_action"}function rr(t,e,r){if(nl.has(t.category)){let n=[];for(let a of t.steps)rr(a,e,n);let s=t.startTime.getTime()-e.getTime();r.push({title:t.title,category:sl(t.category),timestamp:t.startTime.toISOString(),duration:t.duration,videoOffset:s>=0?s/1e3:null,status:t.error?"failed":"passed",error:rs(t.error?.message),children:n});}else for(let n of t.steps)rr(n,e,r);}function bs(t,e){let r=[];for(let n of t)rr(n,e,r);return r}var ol=new Set(["localhost","127.0.0.1","0.0.0.0"]);function ws(t){let e=new URL(t);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&ol.has(e.hostname)))throw core.createError(core.ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${e.protocol}//${e.hostname}`)}var ll=3e3;async function nr(t){let e=new AbortController,r=setTimeout(()=>e.abort(),ll);try{return (await fetch(`${t}/health`,{method:"GET",signal:e.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function ks(t){return new Promise(e=>setTimeout(e,t))}async function xs(t){try{let r=(await t.json()).error;if(r&&typeof r.message=="string"){let n=r.details;if(Array.isArray(n)&&n.length>0){let s=n.map(a=>`${a.field}: ${a.message}`).join(", ");return `${r.message} (${s})`}return r.message}}catch{}return `HTTP ${t.status}`}async function sr(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:n.signal});if(a.ok){let o=await a.json();return {accessToken:o.accessToken,refreshToken:o.refreshToken,expiresIn:o.expiresIn,orgId:o.orgId,orgName:o.orgName,userId:o.userId,userName:o.userName}}if(a.status===429){let o=a.headers.get("Retry-After"),l=o?parseInt(o,10)*1e3:5e3;if(!isNaN(l)&&l>0){await ks(l);let d=await fetch(`${t}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:e}),signal:n.signal});if(d.ok){let c=await d.json();return {accessToken:c.accessToken,refreshToken:c.refreshToken,expiresIn:c.expiresIn,orgId:c.orgId,orgName:c.orgName,userId:c.userId,userName:c.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return a.status===400?{code:"validation_error",message:await xs(a),statusCode:400}:a.status===401?{code:"invalid_key",message:"API key is invalid or has been revoked.",statusCode:401}:a.status===403?{code:"expired_key",message:"API key has expired.",statusCode:403}:{code:"server_error",message:await xs(a),statusCode:a.status}}catch(a){return a instanceof DOMException&&a.name==="AbortError"?{code:"timeout",message:"Token exchange timed out.",statusCode:null}:{code:"network_error",message:"Failed to reach cloud for token exchange.",statusCode:null}}finally{clearTimeout(s);}}function ar(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 Cs(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:n.signal});if(a.status===429){let o=a.headers.get("Retry-After"),l=o?parseInt(o,10)*1e3:5e3;!isNaN(l)&&l>0&&(await ks(l),a=await fetch(`${t}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:e}),signal:n.signal}));}if(!a.ok)return null;let i=await a.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn}}catch{return null}finally{clearTimeout(s);}}async function Ts(t,e,r,n,s,a){let i=new AbortController,o=setTimeout(()=>i.abort(),s);try{let l={gitId:r,displayName:n};a&&(l.branch=a);let d=await fetch(`${t}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(l),signal:i.signal});if(!d.ok)return null;let c=await d.json();return {repoId:c.repoId,displayName:c.displayName}}catch{return null}finally{clearTimeout(o);}}var fl=5e3;function X(t,e){try{return child_process.execSync(t,{cwd:e,timeout:fl,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function Ss(t){let e=X("git rev-parse --abbrev-ref HEAD",t),r=X("git rev-parse --short HEAD",t),n=X("git log -1 --pretty=%s",t),s=X("git log -1 --format=%an",t)??X("git config user.name",t),a=gl(t),i=a?we(a):null;return {branch:e,commitSha:r,commitMessage:n,commitAuthor:s,remoteUrl:i}}function gl(t){let e=X("git remote get-url origin",t);if(e)return e;let r=X("git remote",t);if(!r)return null;let n=r.split(`
|
|
4363
|
+
`)[0]?.trim();return n?X(`git remote get-url ${n}`,t):null}function we(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 Rs(t){let e=t.split("/").filter(Boolean);return e[e.length-1]??t}function ir(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 ke(t){let e=ir(t);return e||`local/${path.basename(t)}`}var hl=new Set(["smoke","regression","nightly","ci"]);function qe(){let t=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(t&&hl.has(t))return t}async function Z(t,e,r){let n=new AbortController,s=setTimeout(()=>n.abort(),Math.max(1,r));try{return await fetch(t,{...e,signal:n.signal})}finally{clearTimeout(s);}}function As(t,e){let r=e+Math.ceil(Math.max(0,t)/1e3);return Math.min(6e5,Math.max(3e4,r))}var He=class{constructor(e=12e4,r=Date.now()){this.deadline=r+Math.max(0,e);}remaining(e=Date.now()){return Math.max(0,this.deadline-e)}expired(e=Date.now()){return this.remaining(e)===0}slice(e,r=Date.now()){return Math.min(e,this.remaining(r))}};var yl=1048576,Ue=[1e3,3e3,9e3],ze=3,Is=3e4,bl=90*1048576,xl=new Set(["e2e","mobile","unit"]);function lr(t){let e=new Ce;for(let r of t??[])e.add(r.testType,r.apiProtocol);return e.signal()}var Ce=class{constructor(){this.total=0;this.apiProtocols=new Map;this.nonApi=new Map;}add(e,r){if(this.total++,e==="api"){let n=r??"rest";this.apiProtocols.set(n,(this.apiProtocols.get(n)??0)+1);}else xl.has(e)&&this.nonApi.set(e,(this.nonApi.get(e)??0)+1);}signal(){let e=0;for(let s of this.apiProtocols.values())e+=s;if(this.total>0&&e===this.total){let s="rest",a=0;for(let[i,o]of this.apiProtocols)o>a&&(a=o,s=i);return {testType:"api",apiProtocol:s,metadata:{testType:"api",primaryProtocol:s}}}let r=null,n=0;for(let[s,a]of this.nonApi)a>n&&(n=a,r=s);return {testType:r??"e2e"}}};function dr(t,e,r,n,s,a){let i=a?.cloudPlatform?a.cloudPlatform:n?.provider&&n.provider!=="unknown"?n.provider:"local",o=qe(),l=lr(s),d=l.testType==="api"?l:null,c=d&&s?s.map(u=>u.apiProtocol?u:{...u,apiProtocol:d.apiProtocol}):s;return {runId:t.testRunId,repoGitId:e,startedAt:t.startedAt,summary:t.summary,timeline:t.timeline,environment:i,...o?{runType:o}:{},...d?{testType:d.testType,apiProtocol:d.apiProtocol,metadata:d.metadata}:{testType:l.testType},...c&&c.length>0?{tests:c}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...n?.provider?{ciProvider:n.provider}:{},...n?.runUrl?{ciRunUrl:n.runUrl}:{},...a?.cloudPlatform?{cloudPlatform:a.cloudPlatform}:{},...a?.cloudBuildId?{cloudBuildId:a.cloudBuildId}:{},...a?.cloudSessionId?{cloudSessionId:a.cloudSessionId}:{}}}function or(t){return typeof t=="string"?Buffer.byteLength(t,"utf-8"):0}function Ve(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:or(e.responseBody),bytesOut:typeof e.bytesOut=="number"?e.bytesOut:or(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 $e(t){return Array.isArray(t)?t.map(e=>{let r=e.responseStatusCode??e.statusCode??0,n=e.timestamp??null;return {method:e.method??"GET",url:e.url??"",status:r,statusCode:r,type:"xhr",size:or(e.responseBody),duration:e.responseTimeMs??e.durationMs??0,responseTimeMs:e.responseTimeMs??e.durationMs??0,requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null,timestamp:n,startedAt:n}}):[]}function We(t){if(!Array.isArray(t))return [];let e=r=>{if(r==null)return String(r);if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}};return t.map(r=>{let n=r.status==="failed"?"failed":"passed",s=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,a=r.kind??r.type??"assertion",i=n==="failed"?`expected ${e(r.expected)}, received ${e(r.actual)}`:r.expected!==void 0?`expected ${e(r.expected)}`:null;return {...r.callId!=null?{callId:r.callId}:{},kind:a,description:s??r.description??`${a} assertion`,status:n,detail:i}})}async function je(t){return new Promise(e=>setTimeout(e,t))}function wl(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}async function Ms(t,e,r,n=Is,s){for(let a=0;a<ze;a++){if(s?.expired())return null;let i=s?s.slice(n):n;if(i<=0)return null;try{let o=await Z(t,e,i);if(o.ok)return o;if(o.status===401&&r&&a===0){let l=await r();if(l){let d={...e,headers:{...e.headers,Authorization:`Bearer ${l}`}},c=await Z(t,d,i);if(c.ok)return c}return null}if(o.status===429&&a<ze-1){let l=o.headers.get("Retry-After"),d=l?parseInt(l,10)*1e3:Ue[a];!isNaN(d)&&d>0?await je(d):await je(Ue[a]);continue}if(o.status>=500&&a<ze-1){await je(Ue[a]);continue}return o}catch{if(a<ze-1){await je(Ue[a]);continue}return null}}return null}var kl=util.promisify(zlib.gzip);function _s(t,e){if(!Array.isArray(t.tests))return t;let r=t.tests.map(n=>{let{consoleLogs:s,networkRequests:a,apiCalls:i,...o}=n;return e?o:{...o,...i!==void 0?{apiCalls:i}:{}}});return {...t,tests:r}}var Cl=["consoleLogs","networkRequests","apiCalls","actions","navigations","protocolAssertions","visual"];function Tl(t){if(!Array.isArray(t.tests))return t;let e=new Set(Cl),r=t.tests.map(n=>{let s={};for(let a in n)if(!e.has(a))if(a==="failure"&&n[a]&&typeof n[a]=="object"){let i=n[a];s.failure={message:i.message??null,line:i.line??null};}else s[a]=n[a];return s});return {...t,tests:r}}function Sl(t){let e=new Set(["tests","timeline","unifiedTimeline","navigations"]),r={};for(let n in t)e.has(n)||(r[n]=t[n]);return r.tests=[],r}async function cr(t,e=bl){let r={"Content-Type":"application/json"},n=JSON.stringify(t),s=t,a=Array.isArray(s?.tests)?s.tests.length:0,i=o=>Buffer.byteLength(o,"utf-8")>e;if(a>0&&i(n)){let o=Math.max(1,Math.round(e/1048576));process.stderr.write(`[testrelic] WARNING: batch payload exceeds ${o}MB \u2014 dropping consoleLogs/networkRequests from ${a} test(s) to avoid HTTP 413. Console/network detail will be missing in the cloud.
|
|
4364
|
+
`),n=JSON.stringify(_s(s,false)),i(n)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${o}MB after dropping logs \u2014 also dropping apiCalls from ${a} test(s). API request/response detail will be missing in the cloud.
|
|
4365
|
+
`),n=JSON.stringify(_s(s,true))),i(n)&&(process.stderr.write(`[testrelic] WARNING: batch still exceeds ${o}MB \u2014 shedding remaining per-test detail (actions/navigations/assertions) from ${a} test(s). Only test results + summary will reach the cloud.
|
|
4366
|
+
`),n=JSON.stringify(Tl(s))),i(n)&&(process.stderr.write(`[testrelic] ERROR: batch still exceeds ${o}MB after shedding all per-test detail \u2014 uploading run summary only (${a} per-test result(s) omitted) to avoid losing the run to HTTP 413.
|
|
4367
|
+
`),n=JSON.stringify(Sl(s)));}if(Buffer.byteLength(n,"utf-8")>yl){r["Content-Encoding"]="gzip";let o=await kl(Buffer.from(n,"utf-8")),l=o.buffer;return {body:new Uint8Array(l,o.byteOffset,o.byteLength),headers:r}}return {body:n,headers:r}}async function Ps(t,e,r,n,s,a){let i=`${t}/runs`,{body:o,headers:l}=await cr(r);l.Authorization=`Bearer ${e}`;let d=await Ms(i,{method:"POST",headers:l,body:o},n,s,a);return d?.ok?{success:true,statusCode:d.status,error:null}:d?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:d?`Upload failed with status ${d.status}`:"Upload failed after retries",statusCode:d?.status??null,payload:r,targetEndpoint:i,method:"POST"}}async function Es(t,e,r,n){let s=`${t}/runs/init`;try{let a=await Z(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(wl(r))},n??Is);return a.ok?{runId:(await a.json()).runId}:null}catch{return null}}function Ls(t,e,r,n){let s=`${t}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}).catch(()=>{});}async function Ns(t,e,r,n){let s=`${t}/runs/${r}/finalize`;return (await Ms(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}))?.ok??false}function ur(t,e,r,n){let s=`${t}/runs/${r}/finalize`,a=new Date,i={finishedAt:a.toISOString(),duration:a.getTime()-new Date(n).getTime(),summary:{}};fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(i)}).catch(()=>{});}var Ml="1.0.0",Ds=10;function Fs(t){return t instanceof Error?t.message:String(t)}function Pl(t){return t>=400&&t<500&&t!==408&&t!==429}function Te(t,e,r,n,s,a,i,o){try{fs$1.mkdirSync(t,{recursive:!0});let l=Date.now(),d=`${l}-${e}-${r}.json`,c=path.join(t,d),p={version:Ml,queuedAt:new Date(l).toISOString(),reason:n,retryCount:0,targetEndpoint:s,method:a,payload:i,headers:o},u=c+".tmp";fs$1.writeFileSync(u,JSON.stringify(p,null,2),"utf-8"),fs$1.renameSync(u,c);}catch(l){l.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
|
|
4367
4368
|
`):process.stderr.write(`\u26A0 TestRelic: Unable to queue upload data.
|
|
4368
|
-
`);}}async function
|
|
4369
|
-
`),fs$1.unlinkSync(o);continue}l=c;}catch(d){process.stderr.write(`\u26A0 TestRelic: Skipping unreadable queue file ${i}: ${
|
|
4370
|
-
`);try{fs$1.unlinkSync(o);}catch{}continue}try{let{body:d,headers:c}=await
|
|
4371
|
-
`);try{fs$1.renameSync(o,`${o}.failed`);}catch{try{fs$1.unlinkSync(o);}catch{}}}else {process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 server returned HTTP ${
|
|
4372
|
-
`);return}}catch(d){process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 ${
|
|
4373
|
-
`);return}}}function
|
|
4374
|
-
`);return}try{if(
|
|
4375
|
-
`);return}let r=await
|
|
4376
|
-
`),await this.resolveRepoId(),this.config.queueDirectory&&(
|
|
4377
|
-
`);}}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()+
|
|
4378
|
-
`));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,
|
|
4379
|
-
\u2192 Manage keys: ${
|
|
4369
|
+
`);}}async function Hs(t,e,r){let n;try{n=fs$1.readdirSync(t).filter(a=>a.endsWith(".json")&&!a.endsWith(".tmp")).sort();}catch{return}if(n.length===0)return;let s=[];for(let a=0;a<n.length;a+=Ds)s.push(n.slice(a,a+Ds));for(let a of s)for(let i of a){let o=path.join(t,i),l;try{if(!fs$1.statSync(o).isFile())continue;let c=JSON.parse(fs$1.readFileSync(o,"utf-8"));if(!core.isValidQueueEntry(c)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${i}
|
|
4370
|
+
`),fs$1.unlinkSync(o);continue}l=c;}catch(d){process.stderr.write(`\u26A0 TestRelic: Skipping unreadable queue file ${i}: ${Fs(d)}
|
|
4371
|
+
`);try{fs$1.unlinkSync(o);}catch{}continue}try{let{body:d,headers:c}=await cr(l.payload),p={...l.headers,...c,Authorization:`Bearer ${r}`},u=await fetch(l.targetEndpoint,{method:l.method,headers:p,body:d});if(u.ok)fs$1.unlinkSync(o);else if(Pl(u.status)){process.stderr.write(`\u26A0 TestRelic: Queue entry ${i} rejected (HTTP ${u.status}) \u2014 moving aside; it will not be retried.
|
|
4372
|
+
`);try{fs$1.renameSync(o,`${o}.failed`);}catch{try{fs$1.unlinkSync(o);}catch{}}}else {process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 server returned HTTP ${u.status} for ${i}; will retry later.
|
|
4373
|
+
`);return}}catch(d){process.stderr.write(`\u26A0 TestRelic: Queue flush paused \u2014 ${Fs(d)}; will retry later.
|
|
4374
|
+
`);return}}}function Us(t,e){try{let r=fs$1.readdirSync(t).filter(s=>(s.endsWith(".json")||s.endsWith(".failed"))&&!s.endsWith(".tmp")),n=Date.now();for(let s of r){let a=path.join(t,s);try{let i=fs$1.readFileSync(a,"utf-8"),l=JSON.parse(i).queuedAt;if(typeof l=="string"){let d=new Date(l).getTime();n-d>e&&fs$1.unlinkSync(a);}}catch{try{fs$1.unlinkSync(a);}catch{}}}}catch{}}var Ol=3e5,ql=864e5,Hl=6e4,zs=3e4,gr="https://platform.testrelic.ai/settings/api-keys";function js(t){return new Promise(e=>{let r=setTimeout(e,t);typeof r?.unref=="function"&&r.unref();})}var Ge=class{constructor(e){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=e,this.authState={mode:"pending",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null};}async initialize(){if(!this.config||!this.config.apiKey){this.setLocalMode("no_api_key"),process.stderr.write(`\u2139 TestRelic: No API key configured. Running in local mode.
|
|
4375
|
+
`);return}try{if(ws(this.config.endpoint),this.gitMetadata=Ss(),!await nr(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.
|
|
4376
|
+
`);return}let r=await sr(this.config.endpoint,this.config.apiKey,this.config.timeout);if(ar(r)){this.handleAuthError(r.code,r.statusCode);return}let n=r;this.authState={mode:"cloud",accessToken:n.accessToken,refreshToken:n.refreshToken,expiresAt:Date.now()+n.expiresIn*1e3,orgId:n.orgId,orgName:n.orgName,userId:n.userId,userName:n.userName},process.stderr.write(`\u2713 TestRelic: Connected to cloud (${n.orgName} / ${n.userName})
|
|
4377
|
+
`),await this.resolveRepoId(),this.config.queueDirectory&&(Us(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)}
|
|
4378
|
+
`);}}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()+Ol<e)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await Cs(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}).
|
|
4379
|
+
`));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,js(zs)]);}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.
|
|
4380
|
+
\u2192 Manage keys: ${gr}
|
|
4380
4381
|
`);break;case "expired_key":this.setLocalMode("expired_api_key"),process.stderr.write(`\u26A0 TestRelic: API key has expired. Running in local mode.
|
|
4381
|
-
\u2192 Generate a new key: ${
|
|
4382
|
+
\u2192 Generate a new key: ${gr}
|
|
4382
4383
|
`);break;case "validation_error":this.setLocalMode("validation_error"),process.stderr.write(`\u26A0 TestRelic: API key format invalid. Running in local mode.
|
|
4383
|
-
\u2192 Manage keys: ${
|
|
4384
|
+
\u2192 Manage keys: ${gr}
|
|
4384
4385
|
`);break;case "rate_limited":this.setLocalMode("rate_limited"),process.stderr.write(`\u26A0 TestRelic: Rate limited during authentication. Running in local mode.
|
|
4385
4386
|
`);break;case "timeout":this.setLocalMode("auth_timeout"),process.stderr.write(`\u26A0 TestRelic: Authentication timed out. Running in local mode.
|
|
4386
4387
|
`);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
|
|
4387
|
-
`);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?
|
|
4388
|
-
`);}readRepoCache(e){if(!this.config)return null;let r=path.join(this.config.queueDirectory,"..","cache","repo.json");try{if(!fs$1.existsSync(r))return null;let n=fs$1.readFileSync(r,"utf-8"),s=JSON.parse(n);if(s.gitId!==e||Date.now()-s.resolvedAt>
|
|
4389
|
-
`),this.startBackgroundFlush();}}}catch{}},
|
|
4390
|
-
`);}
|
|
4391
|
-
`),{navigations:s,apiAssertions:a,networkRequestsFile:i,networkRequestsCount:o,consoleLogsFile:l,consoleLogsCount:d,apiCallsFile:c,apiCallsCount:u,apiStatusMix:f}}function Ue(t=process.env){let e=Nl(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 Nl(t){if(!t)return;let e=t.toLowerCase().trim();if(e==="browserstack"||e==="bs")return "browserstack";if(e==="lambdatest"||e==="lt")return "lambdatest"}var Ol=5,ze=[1e3,3e3,9e3],ie=3,cr=3e4,ql={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip",".json":"application/json"},lr=0,dr=[];async function Hl(){lr>=Ol&&await new Promise(t=>dr.push(t)),lr++;}function Ul(){lr--,dr.length>0&&dr.shift()();}async function je(t){return new Promise(e=>setTimeout(e,t))}function zl(t){let e=t.substring(t.lastIndexOf(".")).toLowerCase();return ql[e]??"application/octet-stream"}function jl(t){try{return fs$1.statSync(t).size}catch{return 0}}async function Vl(t,e,r,n,s){let a=`${t}/artifacts/upload-url`,i=JSON.stringify({runId:r.runId,testId:r.testId,...r.retry!==void 0?{retry:r.retry}:{},fileName:path.basename(r.filePath),contentType:s,type:r.type,sizeBytes:n});for(let o=0;o<ie;o++)try{let l=await J(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:i},cr);if(l.ok)return await l.json();if(l.status>=500&&o<ie-1){await je(ze[o]);continue}return null}catch{if(o<ie-1){await je(ze[o]);continue}return null}return null}async function $l(t,e,r,n){let s=ys(n,cr);for(let a=0;a<ie;a++)try{let i=fs$1.createReadStream(e),o=stream.Readable.toWeb(i),l=await J(t,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(n)},body:o,duplex:"half"},s);if(l.ok)return !0;if(l.status>=500&&a<ie-1){await je(ze[a]);continue}return !1}catch{if(a<ie-1){await je(ze[a]);continue}return false}return false}async function Wl(t,e,r){let n=`${t}/artifacts/confirm`;try{return (await J(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({artifactId:r})},cr)).ok}catch{return false}}async function Gl(t,e,r,n){let s=jl(r.filePath);if(s===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(s>n*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let a=zl(r.filePath);await Hl();try{let i=await Vl(t,e,r,s,a);if(!i)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await $l(i.uploadUrl,r.filePath,a,s))return {success:!1,storageKey:i.storageKey,artifactId:i.artifactId,error:"presigned_put_failed"};let l=await Wl(t,e,i.artifactId);return {success:l,storageKey:i.storageKey,artifactId:i.artifactId,error:l?null:"confirm_failed"}}finally{Ul();}}async function Fs(t,e,r,n,s){let a=new Map,i=r.map(async o=>{if(s?.expired()){a.set(o.filePath,{success:false,storageKey:null,artifactId:null,error:"upload_budget_exhausted"});return}let l=await Gl(t,e,o,n);a.set(o.filePath,l);});return await Promise.allSettled(i),a}function pr(t){let r=t.getGitMetadata()?.remoteUrl;return r?be(r):t.getConfig()?.projectName??xe(process.cwd())}async function Bs(t,e,r,n,s){if(!t.isCloudMode()||e!=="realtime"&&e!=="both"||!await t.ensureValidToken())return null;let i=t.getGitMetadata(),o=V(),l=Ue(),d=De();return (await Cs(t.getEndpoint(),t.getAccessToken(),{runId:r,repoGitId:pr(t),branch:i?.branch??null,commit:i?.commitSha??null,commitMessage:i?.commitMessage??null,commitAuthor:i?.commitAuthor??null,startedAt:n,totalTests:null,ciProvider:o?.provider??null,ciRunUrl:o?.runUrl??null,environment:s??l.cloudPlatform??null,cloudPlatform:l.cloudPlatform??null,cloudBuildId:l.cloudBuildId??null,cloudSessionId:l.cloudSessionId??null,...d?{runType:d}:{},testType:"e2e"}))?.runId??null}var Jl=[{field:"baseline",keyField:"baselineKey",type:"baseline"},{field:"actual",keyField:"actualKey",type:"screenshot"},{field:"diff",keyField:"diffKey",type:"diff"},{field:"baselineDom",keyField:"baselineDomKey",type:"dom"},{field:"actualDom",keyField:"actualDomKey",type:"dom"}];function fr(t,e){return `${t}#${e??0}`}function gr(t,e,r){return r===void 0?t.get(e):t.get(fr(e,r))}var Yl=true,Xl=50,ur={keyMap:new Map,visualKeyMap:new Map,total:0,uploaded:0};async function Zl(t,e,r,n,s){let a=new Map,i=new Map;if(!(e?.uploadArtifacts??Yl)||!await t.ensureValidToken())return ur;let d=[],c=new Map,u=new Map;for(let v of n){let m=fr(v.testId,v.retry),y={runId:r,testId:v.testId,...v.retry!==void 0?{retry:v.retry}:{}};if(v.artifacts.screenshot){let x=path.join(v.outputDir,v.artifacts.screenshot);d.push({filePath:x,...y,type:"screenshot"}),c.set(x,{attemptKey:m,field:"screenshot"});}if(v.artifacts.video){let x=path.join(v.outputDir,v.artifacts.video);d.push({filePath:x,...y,type:"video"}),c.set(x,{attemptKey:m,field:"video"});}if(v.artifacts.trace){let x=path.join(v.outputDir,v.artifacts.trace);d.push({filePath:x,...y,type:"trace"}),c.set(x,{attemptKey:m,field:"trace"});}let w=v.visual??[];for(let x=0;x<w.length;x++){let _=w[x];if(_)for(let S of Jl){let k=_[S.field];if(!k)continue;let R=path.join(v.outputDir,k);d.push({filePath:R,...y,type:S.type}),c.set(R,{attemptKey:m,field:"visual",visualIndex:x,visualKey:S.keyField});}}}if(d.length===0)return ur;let f=e?.artifactMaxSizeMb??Xl,g=await Fs(t.getEndpoint(),t.getAccessToken(),d,f,s),p=new Map;for(let[v,m]of g){if(!m.success||!m.storageKey)continue;let y=c.get(v);if(!y)continue;let w=p.get(y.attemptKey)??{};if(y.field==="screenshot"&&(w.screenshotKey=m.storageKey),y.field==="video"&&(w.videoKey=m.storageKey),y.field==="trace"&&(w.traceKey=m.storageKey),y.field==="visual"&&y.visualIndex!==void 0&&y.visualKey){let x=u.get(y.attemptKey)??new Map,_=x.get(y.visualIndex)??{};_[y.visualKey]=m.storageKey,x.set(y.visualIndex,_),u.set(y.attemptKey,x);}p.set(y.attemptKey,w);}let h=new Map;for(let v of n){let m=v.retry??0;(h.get(v.testId)??-1)<m&&h.set(v.testId,m);}for(let v of n){let m=fr(v.testId,v.retry),y=(v.retry??0)===h.get(v.testId);if(v.visual&&v.visual.length>0){let _=u.get(m),S=v.visual.map((k,R)=>({...k,..._?.get(R)??{}}));i.set(m,S),y&&i.set(v.testId,S);}let w=p.get(m),x={...v.artifacts,...w?.screenshotKey?{screenshotKey:w.screenshotKey}:{},...w?.videoKey?{videoKey:w.videoKey}:{},...w?.traceKey?{traceKey:w.traceKey}:{}};a.set(m,x),y&&a.set(v.testId,x);}let b=Array.from(g.values()).filter(v=>v.success).length;return b>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${b} artifact(s) to cloud storage.
|
|
4392
|
-
`),{keyMap:a,visualKeyMap:i,total:d.length,uploaded:b}}async function hr(t,e,r,n,s,a,i,o,l,d,c){let u={realtimeFinalizeAttempted:false,realtimeFinalized:false,batchAttempted:false,batchAcknowledged:false,artifactsTotal:0,artifactsUploaded:0,failureReason:null},f=new Fe(e?.uploadBudgetMs??12e4),g=p=>{u.failureReason||(u.failureReason=p);};try{if(t.isCloudMode()&&s&&(r==="realtime"||r==="both")){u.realtimeFinalizeAttempted=!0;let b=await t.ensureValidToken(),v=t.getGitMetadata(),m=Zt(c),y={finishedAt:i,duration:o,summary:l,...v?.commitMessage?{commitMessage:v.commitMessage}:{},testType:m.testType,...m.testType==="api"?{apiProtocol:m.apiProtocol,metadata:m.metadata}:{}};if(b){let w=await Ts(t.getEndpoint(),t.getAccessToken(),s,y);if(u.realtimeFinalized=w,!w){g("finalize_failed_after_retries");let x=e?.queueDirectory??".testrelic/queue";we(x,n,"finalize","finalize_failed_after_retries",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",y,{"Content-Type":"application/json"});}}else {g(t.getFailureReason()??"token_invalid");let w=e?.queueDirectory??".testrelic/queue";we(w,n,"finalize",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",y,{"Content-Type":"application/json"});}}let p=new Map,h=new Map;if(t.isCloudMode()&&d&&d.length>0){let b=await Zl(t,e,n,d,f);p=b.keyMap,h=b.visualKeyMap,u.artifactsTotal=b.total,u.artifactsUploaded=b.uploaded;}if(t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(u.batchAttempted=!0,await t.ensureValidToken()){let v=t.getGitMetadata(),m=V(),y=pr(t),w=ed(td(a,p),h),x=Qt(w,y,v,m,Ql(c,h),Ue()),_=await ks(t.getEndpoint(),t.getAccessToken(),x,async()=>await t.ensureValidToken()?t.getAccessToken():null,e?.timeout,f);if(u.batchAcknowledged=_.success,!_.success){let S=_;g(S.reason);let k=e?.queueDirectory??".testrelic/queue";we(k,n,"batch",S.reason,S.targetEndpoint,S.method,S.payload,{"Content-Type":"application/json"});}}else {g(t.getFailureReason()??"token_invalid");let v=e?.queueDirectory??".testrelic/queue",m=t.getGitMetadata(),y=V(),w=pr(t),x=Qt(a,w,m,y,void 0,Ue());we(v,n,"batch",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs`,"POST",x,{"Content-Type":"application/json"});}await t.dispose();}catch(p){g(p instanceof Error?p.message:"unexpected_upload_error");try{await t.dispose();}catch{}}return u}function Ql(t,e){return !t||e.size===0?t:t.map(r=>{let n=gr(e,r.testId,r.retry);return n?{...r,visual:n}:r})}function ed(t,e){if(e.size===0)return t;let r=t.timeline.map(n=>{let s=n.tests;if(!Array.isArray(s))return n;let a=false,i=s.map(o=>{let{testId:l,retry:d}=o;if(!l)return o;let c=gr(e,l,d);return c?(a=true,{...o,visual:c}):o});return a?{...n,tests:i}:n});return {...t,timeline:r}}function td(t,e){if(e.size===0)return t;let r=t.timeline.map(n=>{let s=n,a=s.testId;if(!a)return n;let i=gr(e,a,s.retry);return i?{...n,...i.screenshotKey?{screenshotKey:i.screenshotKey}:{},...i.videoKey?{videoKey:i.videoKey}:{}}:n});return {...t,timeline:r}}var rd=new Set(["batch","realtime","both"]),ke=Object.freeze({attempted:false,acknowledged:false,runId:null,endpoint:null,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:"cloud reporting was never initialised"});function nd(t){switch(t){case "no_api_key":return "cloud mode off \u2014 no API key configured";case "cloud_unreachable":case "network_error":return "cloud endpoint unreachable \u2014 the run stayed local";case "invalid_api_key":return "API key rejected as invalid or revoked \u2014 the run stayed local";case "expired_api_key":return "API key has expired \u2014 the run stayed local";case "validation_error":return "API key format rejected \u2014 the run stayed local";case "rate_limited":return "rate limited during authentication \u2014 the run stayed local";case "auth_timeout":return "authentication timed out \u2014 the run stayed local";case "token_expired_no_refresh":case "token_refresh_failed":case "token_refresh_error":return "access token could not be refreshed \u2014 the run stayed local";case "init_error":return "cloud initialisation timed out \u2014 the run stayed local";case "unexpected_error":return "cloud initialisation failed \u2014 the run stayed local";default:return t?`cloud mode off (${t}) \u2014 the run stayed local`:"cloud mode off \u2014 the run stayed local"}}function Os(t,e,r){if(!t)return ke;if(!t.isCloudMode())return {...ke,detail:nd(t.getFailureReason())};let n=e??"batch";if(!rd.has(n))return {...ke,detail:`upload strategy '${n}' is not recognised \u2014 nothing was sent`};let s=t.getEndpoint(),a=n==="realtime"||n==="both";return a&&r?{attempted:true,acknowledged:true,runId:r,endpoint:s,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:null}:{attempted:true,acknowledged:false,runId:null,endpoint:s,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:a?"run init failed \u2014 the platform did not acknowledge this run":`upload runs at the end of the run under the '${n}' strategy \u2014 not sent yet`}}function mr(t,e,r){if(!t.attempted)return t;if(!e)return {...t,detail:t.acknowledged?"upload timed out before it completed \u2014 the run may be incomplete on the platform":"upload timed out before the platform acknowledged this run",acknowledged:t.acknowledged};let n=t.acknowledged||e.batchAcknowledged,s=t.runId??(e.batchAcknowledged?r:null),a=e.realtimeFinalizeAttempted?e.realtimeFinalized:e.batchAcknowledged,i=null;return n?a||(i="run acknowledged but not closed out \u2014 finalize failed and was queued for retry"):i=e.failureReason?`upload failed (${e.failureReason}) \u2014 queued locally for retry`:"upload failed \u2014 the platform did not acknowledge this run",{attempted:true,acknowledged:n,runId:s,endpoint:t.endpoint,finalized:a,artifactsUploaded:e.artifactsUploaded,artifactsTotal:e.artifactsTotal,detail:i}}function Y(t){try{return fs$1.readFileSync(t,"utf-8").split(`
|
|
4393
|
-
`).filter(r=>r.length>0).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return []}}function cd(t){if(!t)return null;let e=t.split(`
|
|
4394
|
-
`).map(a=>a.trim()).filter(Boolean);if(e.length===0)return null;let r=e.filter(a=>!/^Error:\s*expect\(/.test(a));if(r.length===0)return e[0]??null;let n=r[0],s=r[1];return s!==void 0&&/^Received:/.test(s)&&/^Expected:/.test(n)?`${n} \xB7 ${s}`:n}function yr(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 ud(t,e,r){let n=`${t}::${e}::${r}`;return crypto.createHash("sha256").update(n).digest("hex").substring(0,16)}function pd(t){return t.length<=3?"":t[t.length-2]}function fd(t){let e=t.findIndex(r=>r.status==="passed");return e>0?`passed on retry ${e}`:null}function $s(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 gd(t){let e={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},r=e;for(let n of t){let s=typeof n.responseStatusCode=="number"?n.responseStatusCode:null;r[$s(s)]++;}return e}function zs(t){if(t){for(let e of t)if(e.status==="failed")return {type:e.type,expected:js(e.expected),actual:js(e.actual),...e.expression?{expression:e.expression}:{}}}}function js(t){if(t===void 0)return "undefined";if(t===null)return "null";let e;if(typeof t=="string")e=t;else try{e=JSON.stringify(t)??String(t);}catch{e=String(t);}return e.length>200?e.slice(0,200)+"\u2026":e}function $e(t,e){if(!t)return 0;let r=0;for(let n of t)n.status===e&&r++;return r}function Ws(t,e){for(let r of t)e[r.category]=(e[r.category]??0)+1,r.children.length>0&&Ws(r.children,e);}function hd(t){if(t.length===0)return null;let e=[...t].sort((n,s)=>n-s),r=e.reduce((n,s)=>n+s,0);return {avg:Math.round(r/e.length),min:e[0],max:e[e.length-1],p50:ee(e,50),p95:ee(e,95),p99:ee(e,99)}}var Gs=2e5,We=1e5;function Vs(t,e,r,n,s,a,i){let o={retryIndex:t,apiCalls:e?.length??0,apiUrls:[],methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,assertions:r.length,navigations:n.length,navUrls:[],networkRequests:s,consoleLogs:a,actionSteps:i?.length??0,actionCategories:{}};if(e){let d=new Set;for(let c of e){let u=typeof c.method=="string"?c.method:"OTHER";o.methodCounts[u]=(o.methodCounts[u]??0)+1;let f=typeof c.url=="string"?c.url:null;f&&d.size<We&&d.add(Vt(f));let g=typeof c.responseStatusCode=="number"?c.responseStatusCode:typeof c.statusCode=="number"?c.statusCode:null,p=g!==null&&Number.isFinite(g)?g:null;o.statusRanges[$s(p)]++;let h=typeof c.responseTimeMs=="number"?c.responseTimeMs:typeof c.durationMs=="number"?c.durationMs:null;h!==null&&Number.isFinite(h)&&o.responseTimes.length<Gs&&o.responseTimes.push(h);}o.apiUrls=Array.from(d);}for(let d of r)d.status==="passed"?o.passedAssertions++:o.failedAssertions++;let l=new Set;for(let d of n)d.url&&l.size<We&&l.add(d.url);return o.navUrls=Array.from(l),i&&Ws(i,o.actionCategories),o}function md(){return {apiUrlSet:new Set,methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,navUrlSet:new Set,actionCategoryCounts:{},volApiCalls:0,volAssertions:0,volNavigations:0,volNetworkRequests:0,volConsoleLogs:0,volActionSteps:0}}function vd(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 yd(){let t=os$1.platform();return t==="win32"?"Windows":t==="darwin"?"macOS":"Linux"}function bd(t){let e=t.parent?.project?.()?.use;if(!e)return;let{browserName:r,channel:n}=e;if(n){let a=n.toLowerCase();return a==="chrome"||a==="chrome-stable"?"Chrome":a.startsWith("chrome-beta")?"Chrome Beta":a.startsWith("chrome-dev")?"Chrome Dev":a.startsWith("chrome-canary")?"Chrome Canary":a==="msedge"||a==="msedge-stable"?"Microsoft Edge":a.startsWith("msedge-beta")?"Edge Beta":a.startsWith("msedge-dev")?"Edge Dev":a.startsWith("msedge-canary")?"Edge Canary":n}if(r){let a=r.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":r}let s=e.defaultBrowserType;if(s){let a=s.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":s}}function xd(t,e,r){let n=r.parent?.project?.(),s="unknown";n!==void 0&&(n.use.isMobile===true?s="mobile":s="e2e");let a=["e2e","api","unit","mobile"];for(let l of a)if(t.some(d=>d===`@${l}`||d===l))return l;let i=e.replace(/\\/g,"/"),o=["e2e","api","unit"];for(let l of o)if(i.includes(`/${l}/`))return l;return s}var wd="__testrelic_api_config";function kd(t){return JSON.stringify(t,(e,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var Ge=class{constructor(e){this.rootDir="";this.configDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.navigationsCaptured=false;this.memoryPressureWarned=false;this.testCount=0;this.cloudClient=null;this.cloudRunId=null;this.runTimestamp="";this.updatingSnapshots=false;this.cloudReceipt=ke;this.pendingArtifactEntries=[];this.detectedOs="";this.detectedSource="";this.cloudTestsBuffer=[];this.activeReportMode="embedded";this.streamingWriter=null;this.testIndex=[];this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0,visualChecks:0,visualFailures:0,visualDomChanges:0};this.streamingTestAgg=new Map;this.config=jr(e),this.apiConfig=zr(e);}upsertAggContribution(e,r){let n=this.streamingTestAgg.get(e);(!n||r.retryIndex>n.retryIndex)&&this.streamingTestAgg.set(e,r);}async onBegin(e,r){try{this.rootDir=e.rootDir,this.configDir=e.configFile?path.dirname(e.configFile):"";let n=e.updateSnapshots;if(this.updatingSnapshots=n==="all"||n==="changed",this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??crypto.randomUUID(),this.config.reportMode==="auto"){let o=r.allTests().length;this.activeReportMode=o>=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)
|
|
4395
|
-
`),this.activeReportMode==="streaming"){let o=path.dirname(this.config.outputPath);this.streamingWriter=new he(o);let l=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let d={testRunId:this.testRunId??"",startedAt:this.startedAt,completedAt:new Date().toISOString(),totalDuration:Date.now()-new Date(this.startedAt).getTime(),...this.summaryCounters,metadata:null,reportMode:"streaming",files:[],enrichedSummary:null,validation:null,writeErrors:this.streamingWriter.getWriteErrors(),cloudUpload:this.cloudReceipt};this.streamingWriter.writeSummary(d);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let d=this.cloudClient.getAccessToken();d&&sr(this.cloudClient.getEndpoint(),d,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",l),process.on("SIGINT",l);}if(this.config.includeArtifacts){let o=path.dirname(this.config.outputPath);this.runTimestamp=In(path.join(o,"artifacts"));try{rs(path.join(o,"artifacts"));}catch{}}let a=V();this.detectedOs=yd(),this.detectedSource=vd(a);let i=await Q(async()=>(this.cloudClient=new He(this.config.cloud),await this.cloudClient.initialize(),Bs(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource)),ss,"Cloud initialization");if(this.cloudRunId=i??null,i===void 0&&this.cloudClient?.switchToLocalMode("init_error"),this.cloudReceipt=Os(this.cloudClient,this.config.cloud?.uploadStrategy,this.cloudRunId),this.activeReportMode!=="streaming"){let o=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let l=this.cloudClient.getAccessToken();l&&sr(this.cloudClient.getEndpoint(),l,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",o),process.on("SIGINT",o);}}catch{}}onTestBegin(e,r){try{e.annotations.push({type:wd,description:kd(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let n=r,s=e.outcome(),a;s==="flaky"?a="flaky":s==="skipped"?a="skipped":a=yr(n.status);let i=n.startTime.toISOString(),o=new Date(n.startTime.getTime()+n.duration).toISOString(),l=e.tags?[...e.tags]:e.annotations.filter(M=>M.type==="tag").map(M=>M.description??""),d=Ds(n.attachments,e.annotations,e.title,a==="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 c=null;if(a==="failed"||a==="flaky"){let P=(a==="flaky"?e.results.find(D=>D.status!=="passed")?.errors??[]:n.errors)[0];if(P){let D=$r(this.config.redactPatterns),j=P.location?.file??null,E=d.apiAssertions.find(ha=>ha.status==="failed")?.location??null,re=E!==null&&(j===null||path.resolve(j)!==path.resolve(e.location.file)),_r=re?E.file:j,Ze=re?E.line:P.location?.line??null,fe=null;this.config.includeCodeSnippets&&Ze!==null&&_r&&(fe=Vr(_r,Ze,this.config.codeContextLines),fe&&(fe=D(fe))),c={message:D(se(P.message??"Unknown error")),line:Ze,code:fe,stack:this.config.includeStackTrace&&P.stack?D(se(P.stack)):null};}}let u=e.titlePath().filter(Boolean),f=path.relative(this.rootDir||".",e.location.file).replace(/\\/g,"/"),g=pd(u),p=u.join(" > "),h=f,b=ud(h,g,p),v=xd(l,h,e),m=v!=="mobile"&&d.apiCallsCount>0?"api":v,y=s==="flaky",w=fd(e.results),x=yr(e.expectedStatus),_=yr(n.status),S=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments){let M=path.dirname(this.config.outputPath),P=u[u.length-1]??e.title;S=Pn(n.attachments,P,n.retry,M,this.runTimestamp||void 0,b);}let k=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments)try{let M=Wn(n.attachments,{updatingSnapshots:this.updatingSnapshots,failureMessage:n.errors.map(P=>P.message??"").join(`
|
|
4396
|
-
`)});if(M.length>0){let P=path.dirname(this.config.outputPath),D=u[u.length-1]??e.title;k=En(M,D,n.retry,P,this.runTimestamp||void 0,b,this.configDir||this.rootDir||process.cwd());}}catch{}let R=this.config.includeActionSteps&&n.steps?cs(n.steps,n.startTime):null,C=bd(e),T={titlePath:u,title:p,status:a,duration:n.duration,startedAt:i,completedAt:o,retryCount:e.results.length-1,retry:n.retry,tags:l,failure:c,specFile:f,navigations:d.navigations,testId:b,filePath:h,suiteName:g,testType:m,isFlaky:y,retryStatus:w,expectedStatus:x,actualStatus:_,artifacts:S,visual:k,apiAssertions:d.apiAssertions,actions:R,networkRequestsFile:d.networkRequestsFile,networkRequestsCount:d.networkRequestsCount,consoleLogsFile:d.consoleLogsFile,consoleLogsCount:d.consoleLogsCount,apiCallsFile:d.apiCallsFile,apiCallsCount:d.apiCallsCount,apiStatusMix:d.apiStatusMix,browser:C,os:this.detectedOs||void 0,source:this.detectedSource||void 0},I=d.consoleLogsFile&&d.consoleLogsCount>0?Y(d.consoleLogsFile):void 0,N=d.networkRequestsFile&&d.networkRequestsCount>0?Y(d.networkRequestsFile):void 0,z=d.apiCallsFile&&d.apiCallsCount>0?Y(d.apiCallsFile):void 0,ce=z?er(z):void 0,ue=!N&&z?tr(z):void 0,pe=d.apiAssertions&&d.apiAssertions.length>0?rr(d.apiAssertions):void 0;this.cloudTestsBuffer.push({testId:b,title:p,status:a,duration:n.duration,suiteName:g,filePath:h,testType:m,isFlaky:y,startedAt:i,completedAt:o,tags:l,failure:c,retry:n.retry,retryCount:e.results.length-1,retryStatus:w,browser:C,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...R&&R.length>0?{actions:R}:{},...d.navigations&&d.navigations.length>0?{navigations:d.navigations}:{},...I?{consoleLogs:I}:{},...N?{networkRequests:N}:ue?{networkRequests:ue}:{},...ce?{apiCalls:ce}:{},...pe?{protocolAssertions:pe}:{},...k&&k.length>0?{visual:k}:{}});try{let M=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(M==="realtime"||M==="both")){let P=this.cloudClient.getAccessToken();P&&Ss(this.cloudClient.getEndpoint(),P,this.cloudRunId,this.buildCloudTestPayload(T));}}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter){let M=Qe(h,u,e.id??"",n.retry),P=n.retry===e.results.length-1,D={id:M,...x!=="passed"?{expectedStatus:x}:{},navigations:d.navigations,apiAssertions:d.apiAssertions,actions:R??[],artifacts:S,visual:k,failureDiagnostic:c,hasNetworkFile:d.networkRequestsFile!==null,networkRequestsCount:d.networkRequestsCount,hasConsoleFile:d.consoleLogsFile!==null,consoleLogsCount:d.consoleLogsCount,hasApiCallsFile:d.apiCallsFile!==null,apiCallsCount:d.apiCallsCount,startedAt:i};this.streamingWriter.writeTestDetail(M,D,{networkRequestsFile:d.networkRequestsFile,consoleLogsFile:d.consoleLogsFile,apiCallsFile:d.apiCallsFile});let j={id:M,title:u[u.length-1]??e.title,titlePath:u,filePath:h,status:a,...x!=="passed"?{expectedStatus:x}:{},duration:n.duration,project:u[1]??"",retryIndex:n.retry,tags:l,hasNetworkData:d.networkRequestsCount>0,hasConsoleData:d.consoleLogsCount>0,hasArtifacts:S!==null,hasActionSteps:(R?.length??0)>0,visualCount:k?.length??0,visualFailedCount:k?.filter(E=>E.status==="failed").length??0,domChangeCount:k?.reduce((E,re)=>E+(re.domChangeCount??0),0)??0,...(()=>{let E=k?.find(re=>re.diff);return E?.diff?{visualDiffPath:E.diff}:{}})(),errorMessage:cd(c?.message),networkCount:d.networkRequestsCount,consoleCount:d.consoleLogsCount,actionCount:R?.length??0,testType:m,apiCallCount:d.apiCallsCount,...d.apiStatusMix?{apiStatusMix:d.apiStatusMix}:{},assertionsPassed:$e(d.apiAssertions,"passed"),assertionsFailed:$e(d.apiAssertions,"failed"),...(()=>{let E=zs(d.apiAssertions);return E?{firstFailedAssertion:E}:{}})(),isRetry:!P,retryGroupKey:et(h,u,e.id??"")};if(this.testIndex.push(j),P)switch(this.summaryCounters.total++,a){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.upsertAggContribution(`${h}::${u.join(" > ")}`,Vs(n.retry,z,d.apiAssertions,d.navigations,d.networkRequestsCount,d.consoleLogsCount,R)),(S||k)&&this.pendingArtifactEntries.push({testId:b,retry:n.retry,artifacts:S??{},visual:k,outputDir:path.dirname(this.config.outputPath)}),T.actions=null,T.apiAssertions=null,T.navigations=[],T.artifacts=null,T.failure=null,T.networkRequestsFile=null,T.consoleLogsFile=null,T.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(T),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(e){try{let r=new Date().toISOString(),n=new Date(this.startedAt).getTime(),a=new Date(r).getTime()-n,i=this.activeReportMode==="streaming"?this.testIndex.some(l=>l.status!=="skipped"):this.collectedTests.some(l=>l.status!=="skipped");!this.fixtureDataReceived&&i&&process.stderr.write(`
|
|
4388
|
+
`);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?we(this.gitMetadata.remoteUrl):null,r=e?Rs(e):this.config.projectName??ke(process.cwd()),n=e??this.config.projectName??ke(process.cwd()),s=this.readRepoCache(n);if(s){this.repoId=s.repoId;return}try{let a=await Ts(this.config.endpoint,this.authState.accessToken,n,r,this.config.timeout,this.gitMetadata?.branch);a&&(this.repoId=a.repoId,this.writeRepoCache(n,a.repoId,a.displayName));}catch{}!e&&!this.config.projectName&&!ir(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
|
|
4389
|
+
`);}readRepoCache(e){if(!this.config)return null;let r=path.join(this.config.queueDirectory,"..","cache","repo.json");try{if(!fs$1.existsSync(r))return null;let n=fs$1.readFileSync(r,"utf-8"),s=JSON.parse(n);if(s.gitId!==e||Date.now()-s.resolvedAt>ql)return null;let a=this.hashApiKey();return a&&s.apiKeyHash!==a?null:s}catch{return null}}writeRepoCache(e,r,n){if(!this.config)return;let s=path.join(this.config.queueDirectory,"..","cache"),a=path.join(s,"repo.json");try{fs$1.mkdirSync(s,{recursive:!0});let i={repoId:r,gitId:e,displayName:n,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},o=a+".tmp";fs$1.writeFileSync(o,JSON.stringify(i,null,2),"utf-8"),fs$1.renameSync(o,a);}catch{}}hashApiKey(){return this.config?.apiKey?crypto.createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let e=this.authState.accessToken,r=this.config.queueDirectory,n=this.config.endpoint;this.flushPromise=Promise.race([Hs(r,n,e),js(zs)]).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 nr(e))return;if(this.config?.apiKey){let n=await sr(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!ar(n)){let s=n;this.authState={mode:"cloud",accessToken:s.accessToken,refreshToken:s.refreshToken,expiresAt:Date.now()+s.expiresIn*1e3,orgId:s.orgId,orgName:s.orgName,userId:s.userId,userName:s.userName},this.failureReason=null,process.stderr.write(`\u2713 TestRelic: Cloud connectivity restored.
|
|
4390
|
+
`),this.startBackgroundFlush();}}}catch{}},Hl),typeof this.healthCheckTimer?.unref=="function"&&this.healthCheckTimer.unref();}};function Vs(t){if(!t.cloudMode)return "none";let e=t.uploadStrategy;return !e||e==="batch"||e==="both"?e==="both"&&t.sentRealtime?"summary":t.streaming?"deferred":"inline":"none"}function hr(t){for(let e of t)if(fs$1.existsSync(e))return $(e);return []}function Ke(t){let e=t.consoleLogs?hr(t.consoleLogs):void 0,r=t.networkRequests?hr(t.networkRequests):void 0,n=t.apiCalls?hr(t.apiCalls):void 0,s=!r&&n?$e(n):void 0;return {...e?{consoleLogs:e}:{},...r?{networkRequests:r}:s?{networkRequests:s}:{},...n?{apiCalls:Ve(n)}:{}}}function Je(t,e){return {...t&&t.length>0?{actions:t}:{},...e&&e.length>0?{protocolAssertions:We(e)}:{}}}function jl(t){try{let e=JSON.parse(fs$1.readFileSync(t,"utf-8"));return typeof e=="object"&&e!==null?e:null}catch{return null}}function $s(t){let{deferred:e}=t;if(!e)return t.test;let r=jl(e.metaFile);return {...t.test,...Je(Array.isArray(r?.actions)?r.actions:null,Array.isArray(r?.apiAssertions)?r.apiAssertions:null),...Ke(e.heavy)}}var mr="_testrelic-fixture",Vl="application/json",$l='{"testRelicFixture":true}';async function Wl({},t,e){try{await e.attach(mr,{body:Buffer.from($l),contentType:Vl});}catch{}await t();}var Ye=[Wl,{auto:true,box:true}];function Yl(t,e){return e?t?{"2xx":t["2xx"]+e["2xx"],"3xx":t["3xx"]+e["3xx"],"4xx":t["4xx"]+e["4xx"],"5xx":t["5xx"]+e["5xx"],error:t.error+e.error}:{...e}:t}function Ws(t,e,r){let n=[],s=[],a=null,i=0,o=null,l=0,d=null,c=0,p=null,u=t.filter(h=>h.name===core.ATTACHMENT_NAME&&h.body),f=false;if(u.length>0)for(let h of u)try{let m=JSON.parse(h.body.toString());if(core.isTestRelicFilePayload(m)){n=n.concat(m.navigations),s=s.concat(m.apiAssertions),m.networkRequestsFile&&(a=m.networkRequestsFile,i+=m.networkRequestsCount),m.consoleLogsFile&&(o=m.consoleLogsFile,l+=m.consoleLogsCount),m.apiCallsFile&&(d=m.apiCallsFile,c+=m.apiCallsCount),p=Yl(p,m.apiStatusMix),f=!0;continue}if(core.isTestRelicDataPayload(m)){n=n.concat(m.navigations),Array.isArray(m.apiAssertions)&&(s=s.concat(m.apiAssertions)),i+=m.networkRequests?.length??0,c+=m.apiCalls?.length??0;let b=m.consoleLogs;Array.isArray(b)&&(l+=b.length),f=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
|
|
4391
|
+
`);}f||(n=e.filter(h=>h.type==="lambdatest-navigation"&&h.description).map(h=>{try{return JSON.parse(h.description)}catch{return null}}).filter(h=>h!==null));let g=t.some(h=>h.name===mr);return {navigations:n,apiAssertions:s,networkRequestsFile:a,networkRequestsCount:i,consoleLogsFile:o,consoleLogsCount:l,apiCallsFile:d,apiCallsCount:c,apiStatusMix:p,payloadAttached:f,fixtureMarker:g}}var Xl=`
|
|
4397
4392
|
\u26A0 TestRelic: No fixture data received from any test.
|
|
4398
4393
|
To enable network logs, video sync, and Test Navigation tracking, import the TestRelic fixture:
|
|
4399
4394
|
import { test, expect } from '@testrelic/playwright-analytics/fixture';
|
|
4400
4395
|
instead of:
|
|
4401
4396
|
import { test, expect } from '@playwright/test';
|
|
4402
4397
|
|
|
4403
|
-
|
|
4398
|
+
`,Xe=class{constructor(){this.tests=new Map;}record(e,r,n,s){let i=(this.tests.get(e)?.flags??0)|(n?1:0)|(s?2:0);this.tests.set(e,{flags:i,title:r});}message(){let e=this.tests.size;if(e===0)return null;let r=false,n=0,s=0,a=[];for(let{flags:d,title:c}of this.tests.values())d!==0&&(r=true),(d&1)===0&&((d&2)!==0?s++:n++,a.length<3&&a.push(`"${c}"`));if(!r)return Xl;let i=n+s;if(i===0)return null;let o=[];n>0&&o.push(`${n} did not run through the TestRelic fixture (import { test, expect } from '@testrelic/playwright-analytics/fixture' in their spec files instead of '@playwright/test')`),s>0&&o.push(`${s} ran through the fixture without using its page or request fixture (for example a page from browser.newPage(), or trackApiCalls: false); pass such pages to trackPage(page, testInfo) to capture them`);let l=i>a.length?", \u2026":"";return `[testrelic] ${i} of ${e} tests captured no network, console or navigation data: ${o.join("; ")}. For example: ${a.join(", ")}${l}
|
|
4399
|
+
`}};function Ze(t=process.env){let e=Zl(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 Zl(t){if(!t)return;let e=t.toLowerCase().trim();if(e==="browserstack"||e==="bs")return "browserstack";if(e==="lambdatest"||e==="lt")return "lambdatest"}var nd=5,Qe=[1e3,3e3,9e3],le=3,br=3e4,sd={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip",".json":"application/json"},vr=0,yr=[];async function ad(){vr>=nd&&await new Promise(t=>yr.push(t)),vr++;}function id(){vr--,yr.length>0&&yr.shift()();}async function et(t){return new Promise(e=>setTimeout(e,t))}function od(t){let e=t.substring(t.lastIndexOf(".")).toLowerCase();return sd[e]??"application/octet-stream"}function ld(t){try{return fs$1.statSync(t).size}catch{return 0}}async function dd(t,e,r,n,s){let a=`${t}/artifacts/upload-url`,i=JSON.stringify({runId:r.runId,testId:r.testId,...r.retry!==void 0?{retry:r.retry}:{},fileName:path.basename(r.filePath),contentType:s,type:r.type,sizeBytes:n});for(let o=0;o<le;o++)try{let l=await Z(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:i},br);if(l.ok)return await l.json();if(l.status>=500&&o<le-1){await et(Qe[o]);continue}return null}catch{if(o<le-1){await et(Qe[o]);continue}return null}return null}async function cd(t,e,r,n){let s=As(n,br);for(let a=0;a<le;a++)try{let i=fs$1.createReadStream(e),o=stream.Readable.toWeb(i),l=await Z(t,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(n)},body:o,duplex:"half"},s);if(l.ok)return !0;if(l.status>=500&&a<le-1){await et(Qe[a]);continue}return !1}catch{if(a<le-1){await et(Qe[a]);continue}return false}return false}async function ud(t,e,r){let n=`${t}/artifacts/confirm`;try{return (await Z(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({artifactId:r})},br)).ok}catch{return false}}async function pd(t,e,r,n){let s=ld(r.filePath);if(s===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(s>n*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let a=od(r.filePath);await ad();try{let i=await dd(t,e,r,s,a);if(!i)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await cd(i.uploadUrl,r.filePath,a,s))return {success:!1,storageKey:i.storageKey,artifactId:i.artifactId,error:"presigned_put_failed"};let l=await ud(t,e,i.artifactId);return {success:l,storageKey:i.storageKey,artifactId:i.artifactId,error:l?null:"confirm_failed"}}finally{id();}}async function Gs(t,e,r,n,s){let a=new Map,i=r.map(async o=>{if(s?.expired()){a.set(o.filePath,{success:false,storageKey:null,artifactId:null,error:"upload_budget_exhausted"});return}let l=await pd(t,e,o,n);a.set(o.filePath,l);});return await Promise.allSettled(i),a}function wr(t){let r=t.getGitMetadata()?.remoteUrl;return r?we(r):t.getConfig()?.projectName??ke(process.cwd())}async function Ks(t,e,r,n,s){if(!t.isCloudMode()||e!=="realtime"&&e!=="both"||!await t.ensureValidToken())return null;let i=t.getGitMetadata(),o=G(),l=Ze(),d=qe();return (await Es(t.getEndpoint(),t.getAccessToken(),{runId:r,repoGitId:wr(t),branch:i?.branch??null,commit:i?.commitSha??null,commitMessage:i?.commitMessage??null,commitAuthor:i?.commitAuthor??null,startedAt:n,totalTests:null,ciProvider:o?.provider??null,ciRunUrl:o?.runUrl??null,environment:s??l.cloudPlatform??null,cloudPlatform:l.cloudPlatform??null,cloudBuildId:l.cloudBuildId??null,cloudSessionId:l.cloudSessionId??null,...d?{runType:d}:{},testType:"e2e"}))?.runId??null}var gd=[{field:"baseline",keyField:"baselineKey",type:"baseline"},{field:"actual",keyField:"actualKey",type:"screenshot"},{field:"diff",keyField:"diffKey",type:"diff"},{field:"baselineDom",keyField:"baselineDomKey",type:"dom"},{field:"actualDom",keyField:"actualDomKey",type:"dom"}];function kr(t,e){return `${t}#${e??0}`}function Cr(t,e,r){return r===void 0?t.get(e):t.get(kr(e,r))}var hd=true,md=50;function Tr(t){return t?.uploadArtifacts??hd}var xr={keyMap:new Map,visualKeyMap:new Map,total:0,uploaded:0};async function vd(t,e,r,n,s){let a=new Map,i=new Map;if(!Tr(e)||!await t.ensureValidToken())return xr;let l=[],d=new Map,c=new Map;for(let m of n){let b=kr(m.testId,m.retry),v={runId:r,testId:m.testId,...m.retry!==void 0?{retry:m.retry}:{}};if(m.artifacts.screenshot){let x=path.join(m.outputDir,m.artifacts.screenshot);l.push({filePath:x,...v,type:"screenshot"}),d.set(x,{attemptKey:b,field:"screenshot"});}if(m.artifacts.video){let x=path.join(m.outputDir,m.artifacts.video);l.push({filePath:x,...v,type:"video"}),d.set(x,{attemptKey:b,field:"video"});}if(m.artifacts.trace){let x=path.join(m.outputDir,m.artifacts.trace);l.push({filePath:x,...v,type:"trace"}),d.set(x,{attemptKey:b,field:"trace"});}let y=m.visual??[];for(let x=0;x<y.length;x++){let C=y[x];if(C)for(let I of gd){let T=C[I.field];if(!T)continue;let k=path.join(m.outputDir,T);l.push({filePath:k,...v,type:I.type}),d.set(k,{attemptKey:b,field:"visual",visualIndex:x,visualKey:I.keyField});}}}if(l.length===0)return xr;let p=e?.artifactMaxSizeMb??md,u=await Gs(t.getEndpoint(),t.getAccessToken(),l,p,s),f=new Map;for(let[m,b]of u){if(!b.success||!b.storageKey)continue;let v=d.get(m);if(!v)continue;let y=f.get(v.attemptKey)??{};if(v.field==="screenshot"&&(y.screenshotKey=b.storageKey),v.field==="video"&&(y.videoKey=b.storageKey),v.field==="trace"&&(y.traceKey=b.storageKey),v.field==="visual"&&v.visualIndex!==void 0&&v.visualKey){let x=c.get(v.attemptKey)??new Map,C=x.get(v.visualIndex)??{};C[v.visualKey]=b.storageKey,x.set(v.visualIndex,C),c.set(v.attemptKey,x);}f.set(v.attemptKey,y);}let g=new Map;for(let m of n){let b=m.retry??0;(g.get(m.testId)??-1)<b&&g.set(m.testId,b);}for(let m of n){let b=kr(m.testId,m.retry),v=(m.retry??0)===g.get(m.testId);if(m.visual&&m.visual.length>0){let C=c.get(b),I=m.visual.map((T,k)=>({...T,...C?.get(k)??{}}));i.set(b,I),v&&i.set(m.testId,I);}let y=f.get(b),x={...m.artifacts,...y?.screenshotKey?{screenshotKey:y.screenshotKey}:{},...y?.videoKey?{videoKey:y.videoKey}:{},...y?.traceKey?{traceKey:y.traceKey}:{}};a.set(b,x),v&&a.set(m.testId,x);}let h=Array.from(u.values()).filter(m=>m.success).length;return h>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${h} artifact(s) to cloud storage.
|
|
4400
|
+
`),{keyMap:a,visualKeyMap:i,total:l.length,uploaded:h}}async function Sr(t,e,r,n,s,a,i,o,l,d,c,p){let u={realtimeFinalizeAttempted:false,realtimeFinalized:false,batchAttempted:false,batchAcknowledged:false,artifactsTotal:0,artifactsUploaded:0,failureReason:null},f=new He(e?.uploadBudgetMs??12e4),g=h=>{u.failureReason||(u.failureReason=h);};try{if(t.isCloudMode()&&s&&(r==="realtime"||r==="both")){u.realtimeFinalizeAttempted=!0;let b=await t.ensureValidToken(),v=t.getGitMetadata(),y=p??lr(c),x={finishedAt:i,duration:o,summary:l,...v?.commitMessage?{commitMessage:v.commitMessage}:{},testType:y.testType,...y.testType==="api"?{apiProtocol:y.apiProtocol,metadata:y.metadata}:{}};if(b){let C=await Ns(t.getEndpoint(),t.getAccessToken(),s,x);if(u.realtimeFinalized=C,!C){g("finalize_failed_after_retries");let I=e?.queueDirectory??".testrelic/queue";Te(I,n,"finalize","finalize_failed_after_retries",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",x,{"Content-Type":"application/json"});}}else {g(t.getFailureReason()??"token_invalid");let C=e?.queueDirectory??".testrelic/queue";Te(C,n,"finalize",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",x,{"Content-Type":"application/json"});}}let h=new Map,m=new Map;if(t.isCloudMode()&&d&&d.length>0){let b=await vd(t,e,n,d,f);h=b.keyMap,m=b.visualKeyMap,u.artifactsTotal=b.total,u.artifactsUploaded=b.uploaded;}if(t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(u.batchAttempted=!0,await t.ensureValidToken()){let v=t.getGitMetadata(),y=G(),x=wr(t),C=bd(xd(a,h),m),I=dr(C,x,v,y,yd(c,m),Ze()),T=await Ps(t.getEndpoint(),t.getAccessToken(),I,async()=>await t.ensureValidToken()?t.getAccessToken():null,e?.timeout,f);if(u.batchAcknowledged=T.success,!T.success){let k=T;g(k.reason);let R=e?.queueDirectory??".testrelic/queue";Te(R,n,"batch",k.reason,k.targetEndpoint,k.method,k.payload,{"Content-Type":"application/json"});}}else {g(t.getFailureReason()??"token_invalid");let v=e?.queueDirectory??".testrelic/queue",y=t.getGitMetadata(),x=G(),C=wr(t),I=dr(a,C,y,x,void 0,Ze());Te(v,n,"batch",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs`,"POST",I,{"Content-Type":"application/json"});}await t.dispose();}catch(h){g(h instanceof Error?h.message:"unexpected_upload_error");try{await t.dispose();}catch{}}return u}function yd(t,e){return !t||e.size===0?t:t.map(r=>{let n=Cr(e,r.testId,r.retry);return n?{...r,visual:n}:r})}function bd(t,e){if(e.size===0)return t;let r=t.timeline.map(n=>{let s=n.tests;if(!Array.isArray(s))return n;let a=false,i=s.map(o=>{let{testId:l,retry:d}=o;if(!l)return o;let c=Cr(e,l,d);return c?(a=true,{...o,visual:c}):o});return a?{...n,tests:i}:n});return {...t,timeline:r}}function xd(t,e){if(e.size===0)return t;let r=t.timeline.map(n=>{let s=n,a=s.testId;if(!a)return n;let i=Cr(e,a,s.retry);return i?{...n,...i.screenshotKey?{screenshotKey:i.screenshotKey}:{},...i.videoKey?{videoKey:i.videoKey}:{}}:n});return {...t,timeline:r}}var wd=new Set(["batch","realtime","both"]),Se=Object.freeze({attempted:false,acknowledged:false,runId:null,endpoint:null,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:"cloud reporting was never initialised"});function kd(t){switch(t){case "no_api_key":return "cloud mode off \u2014 no API key configured";case "cloud_unreachable":case "network_error":return "cloud endpoint unreachable \u2014 the run stayed local";case "invalid_api_key":return "API key rejected as invalid or revoked \u2014 the run stayed local";case "expired_api_key":return "API key has expired \u2014 the run stayed local";case "validation_error":return "API key format rejected \u2014 the run stayed local";case "rate_limited":return "rate limited during authentication \u2014 the run stayed local";case "auth_timeout":return "authentication timed out \u2014 the run stayed local";case "token_expired_no_refresh":case "token_refresh_failed":case "token_refresh_error":return "access token could not be refreshed \u2014 the run stayed local";case "init_error":return "cloud initialisation timed out \u2014 the run stayed local";case "unexpected_error":return "cloud initialisation failed \u2014 the run stayed local";default:return t?`cloud mode off (${t}) \u2014 the run stayed local`:"cloud mode off \u2014 the run stayed local"}}function Js(t,e,r){if(!t)return Se;if(!t.isCloudMode())return {...Se,detail:kd(t.getFailureReason())};let n=e??"batch";if(!wd.has(n))return {...Se,detail:`upload strategy '${n}' is not recognised \u2014 nothing was sent`};let s=t.getEndpoint(),a=n==="realtime"||n==="both";return a&&r?{attempted:true,acknowledged:true,runId:r,endpoint:s,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:null}:{attempted:true,acknowledged:false,runId:null,endpoint:s,finalized:false,artifactsUploaded:0,artifactsTotal:0,detail:a?"run init failed \u2014 the platform did not acknowledge this run":`upload runs at the end of the run under the '${n}' strategy \u2014 not sent yet`}}function Rr(t,e,r){if(!t.attempted)return t;if(!e)return {...t,detail:t.acknowledged?"upload timed out before it completed \u2014 the run may be incomplete on the platform":"upload timed out before the platform acknowledged this run",acknowledged:t.acknowledged};let n=t.acknowledged||e.batchAcknowledged,s=t.runId??(e.batchAcknowledged?r:null),a=e.realtimeFinalizeAttempted?e.realtimeFinalized:e.batchAcknowledged,i=null;return n?a||(i="run acknowledged but not closed out \u2014 finalize failed and was queued for retry"):i=e.failureReason?`upload failed (${e.failureReason}) \u2014 queued locally for retry`:"upload failed \u2014 the platform did not acknowledge this run",{attempted:true,acknowledged:n,runId:s,endpoint:t.endpoint,finalized:a,artifactsUploaded:e.artifactsUploaded,artifactsTotal:e.artifactsTotal,detail:i}}function _d(t){if(!t)return null;let e=t.split(`
|
|
4401
|
+
`).map(a=>a.trim()).filter(Boolean);if(e.length===0)return null;let r=e.filter(a=>!/^Error:\s*expect\(/.test(a));if(r.length===0)return e[0]??null;let n=r[0],s=r[1];return s!==void 0&&/^Received:/.test(s)&&/^Expected:/.test(n)?`${n} \xB7 ${s}`:n}function _r(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 Id(t,e,r){let n=`${t}::${e}::${r}`;return crypto.createHash("sha256").update(n).digest("hex").substring(0,16)}function Md(t){return t.length<=3?"":t[t.length-2]}function Pd(t){let e=t.findIndex(r=>r.status==="passed");return e>0?`passed on retry ${e}`:null}function ra(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 Ed(t){let e={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},r=e;for(let n of t){let s=typeof n.responseStatusCode=="number"?n.responseStatusCode:null;r[ra(s)]++;}return e}function Qs(t){if(t){for(let e of t)if(e.status==="failed")return {type:e.type,expected:ea(e.expected),actual:ea(e.actual),...e.expression?{expression:e.expression}:{}}}}function ea(t){if(t===void 0)return "undefined";if(t===null)return "null";let e;if(typeof t=="string")e=t;else try{e=JSON.stringify(t)??String(t);}catch{e=String(t);}return e.length>200?e.slice(0,200)+"\u2026":e}function rt(t,e){if(!t)return 0;let r=0;for(let n of t)n.status===e&&r++;return r}function na(t,e){for(let r of t)e[r.category]=(e[r.category]??0)+1,r.children.length>0&&na(r.children,e);}function Ld(t){if(t.length===0)return null;let e=[...t].sort((n,s)=>n-s),r=e.reduce((n,s)=>n+s,0);return {avg:Math.round(r/e.length),min:e[0],max:e[e.length-1],p50:re(e,50),p95:re(e,95),p99:re(e,99)}}var sa=2e5,nt=1e5;function ta(t,e,r,n,s,a,i){let o={retryIndex:t,apiCalls:e?.length??0,apiUrls:[],methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,assertions:r.length,navigations:n.length,navUrls:[],networkRequests:s,consoleLogs:a,actionSteps:i?.length??0,actionCategories:{}};if(e){let d=new Set;for(let c of e){let p=typeof c.method=="string"?c.method:"OTHER";o.methodCounts[p]=(o.methodCounts[p]??0)+1;let u=typeof c.url=="string"?c.url:null;u&&d.size<nt&&d.add(er(u));let f=typeof c.responseStatusCode=="number"?c.responseStatusCode:typeof c.statusCode=="number"?c.statusCode:null,g=f!==null&&Number.isFinite(f)?f:null;o.statusRanges[ra(g)]++;let h=typeof c.responseTimeMs=="number"?c.responseTimeMs:typeof c.durationMs=="number"?c.durationMs:null;h!==null&&Number.isFinite(h)&&o.responseTimes.length<sa&&o.responseTimes.push(h);}o.apiUrls=Array.from(d);}for(let d of r)d.status==="passed"?o.passedAssertions++:o.failedAssertions++;let l=new Set;for(let d of n)d.url&&l.size<nt&&l.add(d.url);return o.navUrls=Array.from(l),i&&na(i,o.actionCategories),o}function Nd(){return {apiUrlSet:new Set,methodCounts:{},statusRanges:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},responseTimes:[],passedAssertions:0,failedAssertions:0,navUrlSet:new Set,actionCategoryCounts:{},volApiCalls:0,volAssertions:0,volNavigations:0,volNetworkRequests:0,volConsoleLogs:0,volActionSteps:0}}function Dd(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 Fd(){let t=os$1.platform();return t==="win32"?"Windows":t==="darwin"?"macOS":"Linux"}function Bd(t){let e=t.parent?.project?.()?.use;if(!e)return;let{browserName:r,channel:n}=e;if(n){let a=n.toLowerCase();return a==="chrome"||a==="chrome-stable"?"Chrome":a.startsWith("chrome-beta")?"Chrome Beta":a.startsWith("chrome-dev")?"Chrome Dev":a.startsWith("chrome-canary")?"Chrome Canary":a==="msedge"||a==="msedge-stable"?"Microsoft Edge":a.startsWith("msedge-beta")?"Edge Beta":a.startsWith("msedge-dev")?"Edge Dev":a.startsWith("msedge-canary")?"Edge Canary":n}if(r){let a=r.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":r}let s=e.defaultBrowserType;if(s){let a=s.toLowerCase();return a==="chromium"?"Chromium":a==="firefox"?"Firefox":a==="webkit"?"WebKit":s}}function Od(t,e,r){let n=r.parent?.project?.(),s="unknown";n!==void 0&&(n.use.isMobile===true?s="mobile":s="e2e");let a=["e2e","api","unit","mobile"];for(let l of a)if(t.some(d=>d===`@${l}`||d===l))return l;let i=e.replace(/\\/g,"/"),o=["e2e","api","unit"];for(let l of o)if(i.includes(`/${l}/`))return l;return s}var qd="__testrelic_api_config";function Hd(t){return JSON.stringify(t,(e,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var st=class{constructor(e){this.rootDir="";this.configDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.fixtureCoverage=new Xe;this.navigationsCaptured=false;this.memoryPressureWarned=false;this.testCount=0;this.cloudClient=null;this.cloudRunId=null;this.runTimestamp="";this.updatingSnapshots=false;this.cloudReceipt=Se;this.pendingArtifactEntries=[];this.detectedOs="";this.detectedSource="";this.cloudTestsBuffer=[];this.runTestTypes=new Ce;this.activeReportMode="embedded";this.streamingWriter=null;this.testIndex=[];this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0,visualChecks:0,visualFailures:0,visualDomChanges:0};this.streamingTestAgg=new Map;this.config=Zr(e),this.apiConfig=Xr(e);}upsertAggContribution(e,r){let n=this.streamingTestAgg.get(e);(!n||r.retryIndex>n.retryIndex)&&this.streamingTestAgg.set(e,r);}async onBegin(e,r){try{this.rootDir=e.rootDir,this.configDir=e.configFile?path.dirname(e.configFile):"";let n=e.updateSnapshots;if(this.updatingSnapshots=n==="all"||n==="changed",this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??crypto.randomUUID(),this.config.reportMode==="auto"){let o=r.allTests().length;this.activeReportMode=o>=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)
|
|
4402
|
+
`),this.activeReportMode==="streaming"){let o=path.dirname(this.config.outputPath);this.streamingWriter=new ve(o);let l=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let d={testRunId:this.testRunId??"",startedAt:this.startedAt,completedAt:new Date().toISOString(),totalDuration:Date.now()-new Date(this.startedAt).getTime(),...this.summaryCounters,metadata:null,reportMode:"streaming",files:[],enrichedSummary:null,validation:null,writeErrors:this.streamingWriter.getWriteErrors(),cloudUpload:this.cloudReceipt};this.streamingWriter.writeSummary(d);}catch{}this.streamingWriter.dispose();}try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let d=this.cloudClient.getAccessToken();d&&ur(this.cloudClient.getEndpoint(),d,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",l),process.on("SIGINT",l);}if(this.config.includeArtifacts){let o=path.dirname(this.config.outputPath);this.runTimestamp=On(path.join(o,"artifacts"));try{us(path.join(o,"artifacts"));}catch{}}let a=G();this.detectedOs=Fd(),this.detectedSource=Dd(a);let i=await te(async()=>(this.cloudClient=new Ge(this.config.cloud),await this.cloudClient.initialize(),Ks(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt,this.detectedSource)),fs,"Cloud initialization");if(this.cloudRunId=i??null,i===void 0&&this.cloudClient?.switchToLocalMode("init_error"),this.cloudReceipt=Js(this.cloudClient,this.config.cloud?.uploadStrategy,this.cloudRunId),this.activeReportMode!=="streaming"){let o=()=>{try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId){let l=this.cloudClient.getAccessToken();l&&ur(this.cloudClient.getEndpoint(),l,this.cloudRunId,this.startedAt);}}catch{}};process.on("SIGTERM",o),process.on("SIGINT",o);}}catch{}}onTestBegin(e,r){try{e.annotations.push({type:qd,description:Hd(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let n=r,s=e.outcome(),a;s==="flaky"?a="flaky":s==="skipped"?a="skipped":a=_r(n.status);let i=n.startTime.toISOString(),o=new Date(n.startTime.getTime()+n.duration).toISOString(),l=e.tags?[...e.tags]:e.annotations.filter(P=>P.type==="tag").map(P=>P.description??""),d=Ws(n.attachments,e.annotations,e.title);(d.navigations.length>0||d.networkRequestsCount>0||d.apiCallsCount>0)&&(this.fixtureDataReceived=!0);let c=d.payloadAttached||d.navigations.length>0;d.navigations.length>0&&(this.navigationsCaptured=!0),!this.config.captureNavigation&&d.navigations.length>0&&(d={...d,navigations:[]});let p=null;if(a==="failed"||a==="flaky"){let E=(a==="flaky"?e.results.find(F=>F.status!=="passed")?.errors??[]:n.errors)[0];if(E){let F=en(this.config.redactPatterns),j=E.location?.file??null,ge=d.apiAssertions.find(Ra=>Ra.status==="failed")?.location??null,Re=ge!==null&&(j===null||path.resolve(j)!==path.resolve(e.location.file)),L=Re?ge.file:j,H=Re?ge.line:E.location?.line??null,he=null;this.config.includeCodeSnippets&&H!==null&&L&&(he=Qr(L,H,this.config.codeContextLines),he&&(he=F(he))),p={message:F(ie(E.message??"Unknown error")),line:H,code:he,stack:this.config.includeStackTrace&&E.stack?F(ie(E.stack)):null};}}let u=e.titlePath().filter(Boolean),f=path.relative(this.rootDir||".",e.location.file).replace(/\\/g,"/"),g=Md(u),h=u.join(" > "),m=f,b=Id(m,g,h);a!=="skipped"&&this.fixtureCoverage.record(`${m}::${h}::${e.id??""}`,h,c,d.fixtureMarker);let v=Od(l,m,e),y=v!=="mobile"&&d.apiCallsCount>0?"api":v,x=s==="flaky",C=Pd(e.results),I=_r(e.expectedStatus),T=_r(n.status),k=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments){let P=path.dirname(this.config.outputPath),E=u[u.length-1]??e.title;k=Hn(n.attachments,E,n.retry,P,this.runTimestamp||void 0,b);}let R=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments)try{let P=ts(n.attachments,{updatingSnapshots:this.updatingSnapshots,failureMessage:n.errors.map(E=>E.message??"").join(`
|
|
4403
|
+
`)});if(P.length>0){let E=path.dirname(this.config.outputPath),F=u[u.length-1]??e.title;R=Un(P,F,n.retry,E,this.runTimestamp||void 0,b,this.configDir||this.rootDir||process.cwd());}}catch{}let w=this.config.includeActionSteps&&n.steps?bs(n.steps,n.startTime):null,S=Bd(e),A={titlePath:u,title:h,status:a,duration:n.duration,startedAt:i,completedAt:o,retryCount:e.results.length-1,retry:n.retry,tags:l,failure:p,specFile:f,navigations:d.navigations,testId:b,filePath:m,suiteName:g,testType:y,isFlaky:x,retryStatus:C,expectedStatus:I,actualStatus:T,artifacts:k,visual:R,apiAssertions:d.apiAssertions,actions:w,networkRequestsFile:d.networkRequestsFile,networkRequestsCount:d.networkRequestsCount,consoleLogsFile:d.consoleLogsFile,consoleLogsCount:d.consoleLogsCount,apiCallsFile:d.apiCallsFile,apiCallsCount:d.apiCallsCount,apiStatusMix:d.apiStatusMix,browser:S,os:this.detectedOs||void 0,source:this.detectedSource||void 0},N=this.config.cloud?.uploadStrategy,pe=!1;try{if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(N==="realtime"||N==="both")){let P=this.cloudClient.getAccessToken();P&&(Ls(this.cloudClient.getEndpoint(),P,this.cloudRunId,this.buildCloudTestPayload(A)),pe=!0);}}catch{}this.runTestTypes.add(y);let fe=this.activeReportMode==="streaming"&&this.streamingWriter!==null,se=Vs({cloudMode:this.cloudClient?.isCloudMode()??!1,uploadStrategy:N,sentRealtime:pe,streaming:fe}),q=se==="none"?null:{testId:b,title:h,status:a,duration:n.duration,suiteName:g,filePath:m,testType:y,isFlaky:x,startedAt:i,completedAt:o,tags:l,failure:p,retry:n.retry,retryCount:e.results.length-1,retryStatus:C,browser:S,os:this.detectedOs||void 0,source:this.detectedSource||void 0,...d.navigations&&d.navigations.length>0?{navigations:d.navigations}:{},...R&&R.length>0?{visual:R}:{}},M={consoleLogs:d.consoleLogsFile&&d.consoleLogsCount>0?d.consoleLogsFile:null,networkRequests:d.networkRequestsFile&&d.networkRequestsCount>0?d.networkRequestsFile:null,apiCalls:d.apiCallsFile&&d.apiCallsCount>0?d.apiCallsFile:null};if(q&&!fe&&this.cloudTestsBuffer.push({test:se==="inline"?{...q,...Je(w,d.apiAssertions),...Ke({...M.consoleLogs?{consoleLogs:[M.consoleLogs]}:{},...M.networkRequests?{networkRequests:[M.networkRequests]}:{},...M.apiCalls?{apiCalls:[M.apiCalls]}:{}})}:q}),this.activeReportMode==="streaming"&&this.streamingWriter){let P=dt(m,u,e.id??"",n.retry),E=n.retry===e.results.length-1,F={id:P,...I!=="passed"?{expectedStatus:I}:{},navigations:d.navigations,apiAssertions:d.apiAssertions,actions:w??[],artifacts:k,visual:R,failureDiagnostic:p,hasNetworkFile:d.networkRequestsFile!==null,networkRequestsCount:d.networkRequestsCount,hasConsoleFile:d.consoleLogsFile!==null,consoleLogsCount:d.consoleLogsCount,hasApiCallsFile:d.apiCallsFile!==null,apiCallsCount:d.apiCallsCount,startedAt:i},j=M.apiCalls?$(M.apiCalls):void 0,ge=this.streamingWriter.writeTestDetail(P,F,{networkRequestsFile:d.networkRequestsFile,consoleLogsFile:d.consoleLogsFile,apiCallsFile:d.apiCallsFile});if(q){let L=this.streamingWriter.getTestDetailPaths(P),H={...M.consoleLogs?{consoleLogs:[M.consoleLogs,L.consoleLogs]}:{},...M.networkRequests?{networkRequests:[M.networkRequests,L.networkRequests]}:{},...M.apiCalls?{apiCalls:[M.apiCalls,L.apiCalls]}:{}};se==="summary"?this.cloudTestsBuffer.push({test:q}):ge?this.cloudTestsBuffer.push({test:q,deferred:{metaFile:L.meta,heavy:H}}):this.cloudTestsBuffer.push({test:{...q,...Je(w,d.apiAssertions),...Ke(H)}});}let Re={id:P,title:u[u.length-1]??e.title,titlePath:u,filePath:m,status:a,...I!=="passed"?{expectedStatus:I}:{},duration:n.duration,project:u[1]??"",retryIndex:n.retry,tags:l,hasNetworkData:d.networkRequestsCount>0,hasConsoleData:d.consoleLogsCount>0,hasArtifacts:k!==null,hasActionSteps:(w?.length??0)>0,visualCount:R?.length??0,visualFailedCount:R?.filter(L=>L.status==="failed").length??0,domChangeCount:R?.reduce((L,H)=>L+(H.domChangeCount??0),0)??0,...(()=>{let L=R?.find(H=>H.diff);return L?.diff?{visualDiffPath:L.diff}:{}})(),errorMessage:_d(p?.message),networkCount:d.networkRequestsCount,consoleCount:d.consoleLogsCount,actionCount:w?.length??0,testType:y,apiCallCount:d.apiCallsCount,...d.apiStatusMix?{apiStatusMix:d.apiStatusMix}:{},assertionsPassed:rt(d.apiAssertions,"passed"),assertionsFailed:rt(d.apiAssertions,"failed"),...(()=>{let L=Qs(d.apiAssertions);return L?{firstFailedAssertion:L}:{}})(),isRetry:!E,retryGroupKey:ct(m,u,e.id??"")};if(this.testIndex.push(Re),E)switch(this.summaryCounters.total++,a){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.upsertAggContribution(`${m}::${u.join(" > ")}`,ta(n.retry,j,d.apiAssertions,d.navigations,d.networkRequestsCount,d.consoleLogsCount,w)),(k||R)&&this.cloudClient?.isCloudMode()&&Tr(this.config.cloud)&&this.pendingArtifactEntries.push({testId:b,retry:n.retry,artifacts:k??{},visual:R,outputDir:path.dirname(this.config.outputPath)}),A.actions=null,A.apiAssertions=null,A.navigations=[],A.artifacts=null,A.failure=null,A.networkRequestsFile=null,A.consoleLogsFile=null,A.apiCallsFile=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(A),this.testCount++,this.checkMemoryPressure();}catch{}}async onEnd(e){try{let r=new Date().toISOString(),n=new Date(this.startedAt).getTime(),a=new Date(r).getTime()-n,i=this.activeReportMode==="streaming"?this.testIndex.some(d=>d.status!=="skipped"):this.collectedTests.some(d=>d.status!=="skipped"),o=this.fixtureCoverage.message();o&&process.stderr.write(o),this.config.captureNavigation?this.fixtureDataReceived&&!this.navigationsCaptured&&i&&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).
|
|
4404
4404
|
`):process.stderr.write(`[testrelic] Test Navigation capture is disabled (captureNavigation: false). Remove the option or set it to true to capture the navigation graph.
|
|
4405
|
-
`),await
|
|
4406
|
-
`);let
|
|
4405
|
+
`),await te(()=>Bn(),Qt,"Artifact flush");let l=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let d=path.dirname(this.config.outputPath);l=ls(d,this.runTimestamp);let c=path.join(d,"artifact-manifest.json"),p=JSON.stringify(l),u=c+".tmp";fs$1.writeFileSync(u,p,"utf-8"),fs$1.renameSync(u,c);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await te(()=>this.finalizeStreamingReport(r,a,e,l),Zt,"Report finalization");else {let d=this.buildTimeline(),c=new Map;for(let h of this.collectedTests){let m=c.get(h.testId);(!m||h.retry>m.retry)&&c.set(h.testId,h);}let p=Array.from(c.values()),u=ys(p,d.length),f={schemaVersion:Ae,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:a,summary:u,ci:G(),metadata:this.config.metadata,timeline:d,shardRunIds:null},g=mt(u,p);if(this.writeReport(f),await te(()=>Ut(f,this.config,l,g),Qt,"HTML report write"),tr(u,this.config.outputPath,this.config.htmlReportPath,this.config.quiet,g),this.cloudClient){let h=this.collectArtifactEntries(),m=this.drainCloudTestsBuffer(),b=await te(()=>Sr(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,f,r,a,u,h,m,this.runTestTypes.signal()),Zt,"Cloud upload");this.cloudReceipt=Rr(this.cloudReceipt,b,this.testRunId);}}}catch{}finally{await this.disposeCloudClient();}}drainCloudTestsBuffer(){let e=this.cloudTestsBuffer.map($s);return this.cloudTestsBuffer.length=0,e}async disposeCloudClient(){let e=this.cloudClient;e&&(this.cloudClient=null,await te(()=>e.dispose(),gs,"Cloud client shutdown"));}collectArtifactEntries(){if(this.activeReportMode==="streaming")return this.pendingArtifactEntries;let e=path.dirname(this.config.outputPath),r=[];for(let n of this.collectedTests)(n.artifacts||n.visual)&&r.push({testId:n.testId,retry:n.retry,artifacts:n.artifacts??{},visual:n.visual,outputDir:e});return r}async finalizeStreamingReport(e,r,n,s){if(!this.streamingWriter)return;this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0,visualChecks:0,visualFailures:0,visualDomChanges:0};let a=new Map,i=new Map;for(let v of this.testIndex){let y=`${v.filePath}::${v.titlePath.join(" > ")}`,x=a.get(y);(x===void 0||v.retryIndex>x)&&a.set(y,v.retryIndex);}let o=0,l=[];for(let v of this.testIndex){let y=`${v.filePath}::${v.titlePath.join(" > ")}`,x=a.get(y);if(v.isRetry=v.retryIndex<x,v.isRetry)continue;switch(l.push(v),o++,this.summaryCounters.total++,v.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.summaryCounters.visualChecks+=v.visualCount??0,this.summaryCounters.visualFailures+=v.visualFailedCount??0,this.summaryCounters.visualDomChanges+=v.domChangeCount??0;let C=i.get(v.filePath);switch(C||(C={filePath:v.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},i.set(v.filePath,C)),C.total++,v.status){case "passed":C.passed++;break;case "failed":C.failed++;break;case "flaky":C.flaky++;break;case "skipped":C.skipped++;break;case "timedout":C.timedOut++;break}}let d=Array.from(i.values()),c=Nd();for(let v of this.streamingTestAgg.values()){c.volApiCalls+=v.apiCalls,c.volAssertions+=v.assertions,c.volNavigations+=v.navigations,c.volNetworkRequests+=v.networkRequests,c.volConsoleLogs+=v.consoleLogs,c.volActionSteps+=v.actionSteps;for(let y in v.methodCounts)c.methodCounts[y]=(c.methodCounts[y]??0)+v.methodCounts[y];c.statusRanges["2xx"]+=v.statusRanges["2xx"],c.statusRanges["3xx"]+=v.statusRanges["3xx"],c.statusRanges["4xx"]+=v.statusRanges["4xx"],c.statusRanges["5xx"]+=v.statusRanges["5xx"],c.statusRanges.error+=v.statusRanges.error,c.passedAssertions+=v.passedAssertions,c.failedAssertions+=v.failedAssertions;for(let y in v.actionCategories)c.actionCategoryCounts[y]=(c.actionCategoryCounts[y]??0)+v.actionCategories[y];for(let y of v.apiUrls){if(c.apiUrlSet.size>=nt)break;c.apiUrlSet.add(y);}for(let y of v.navUrls){if(c.navUrlSet.size>=nt)break;c.navUrlSet.add(y);}for(let y of v.responseTimes){if(c.responseTimes.length>=sa)break;c.responseTimes.push(y);}}this.summaryCounters.totalApiCalls=c.volApiCalls,this.summaryCounters.totalAssertions=c.volAssertions,this.summaryCounters.totalNavigations=c.volNavigations,this.summaryCounters.totalNetworkRequests=c.volNetworkRequests,this.summaryCounters.totalConsoleLogs=c.volConsoleLogs,this.summaryCounters.totalActionSteps=c.volActionSteps,this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let p={reporterTotal:this.summaryCounters.total,indexTotal:o,playwrightStatus:n.status,isValid:this.summaryCounters.total===o};p.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${p.reporterTotal}, index: ${p.indexTotal}
|
|
4406
|
+
`);let u={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:c.apiUrlSet.size,apiCallsByMethod:{...c.methodCounts},apiCallsByStatusRange:{"2xx":c.statusRanges["2xx"],"3xx":c.statusRanges["3xx"],"4xx":c.statusRanges["4xx"],"5xx":c.statusRanges["5xx"],error:c.statusRanges.error},apiResponseTime:Ld(c.responseTimes),totalAssertions:this.summaryCounters.totalAssertions,passedAssertions:c.passedAssertions,failedAssertions:c.failedAssertions,totalNavigations:this.summaryCounters.totalNavigations,uniqueNavigationUrls:c.navUrlSet.size,totalTimelineSteps:o,totalActionSteps:this.summaryCounters.totalActionSteps,actionStepsByCategory:{...c.actionCategoryCounts},visualChecks:this.summaryCounters.visualChecks,visualFailures:this.summaryCounters.visualFailures,visualDomChanges:this.summaryCounters.visualDomChanges},f={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:e,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:d,enrichedSummary:u,validation:p,writeErrors:this.streamingWriter.getWriteErrors(),cloudUpload:this.cloudReceipt};this.streamingWriter.writeSummary(f);let g={schemaVersion:"2.0",generatedAt:new Date().toISOString(),reportMode:"streaming",summaryFile:"summary.json",indexFile:"index.json",testsDir:"tests",artifactsDir:"artifacts",testCount:this.testIndex.length,totalSizeBytes:this.streamingWriter.computeTotalSize()};this.streamingWriter.writeManifest(g);let h=mt(u,l);await Ut(this.buildStreamingReport(f,u,e,r),this.config,s,h),tr(u,this.config.outputPath,this.config.htmlReportPath,this.config.quiet,h);let m=this.streamingWriter.getReportDir();process.stderr.write(`[testrelic] Streaming report written to ${m}
|
|
4407
4407
|
[testrelic] ${this.testIndex.length} test detail files on disk
|
|
4408
|
-
[testrelic] View report: npx testrelic serve ${
|
|
4408
|
+
[testrelic] View report: npx testrelic serve ${m}
|
|
4409
4409
|
`),this.streamingWriter.getWriteErrors().length>0&&process.stderr.write(`[testrelic] WARNING: ${this.streamingWriter.getWriteErrors().length} write error(s) during streaming
|
|
4410
|
-
`);let
|
|
4410
|
+
`);let b=this.streamingWriter;try{if(this.cloudClient){let v=this.buildStreamingReport(f,u,e,r),y=this.collectArtifactEntries(),x=this.drainCloudTestsBuffer(),C=await Sr(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,v,e,r,u,y,x,this.runTestTypes.signal());this.cloudReceipt=Rr(this.cloudReceipt,C,this.testRunId);let I={...f,cloudUpload:this.cloudReceipt};try{b.writeSummary(I);}catch{}}}finally{b.dispose();}this.testIndex.length=0,this.collectedTests.length=0,this.pendingArtifactEntries.length=0,this.cloudTestsBuffer.length=0,this.streamingWriter=null,this.cloudClient=null;}buildStreamingReport(e,r,n,s){return {schemaVersion:Ae,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:n,totalDuration:s,summary:r,ci:G(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let e=process.memoryUsage(),r=e.heapUsed/1024/1024;if(r<200)return;let n=e.heapUsed/e.heapTotal;n>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
|
|
4411
4411
|
`),this.switchToStreamingMode()):n>.8&&r>=500&&!this.memoryPressureWarned&&(this.memoryPressureWarned=!0,process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
|
|
4412
|
-
`));}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let e=path.dirname(this.config.outputPath);this.streamingWriter=new
|
|
4413
|
-
`)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,testType:r.testType,apiCallCount:r.apiCallsCount,...r.apiStatusMix?{apiStatusMix:r.apiStatusMix}:s?{apiStatusMix:
|
|
4414
|
-
`);}}};var
|
|
4415
|
-
`);return
|
|
4416
|
-
`)){let r=e.match(/at\s+(?:.*?\s+\()?(.+?):\d+:\d+\)?$/);if(!r||r[1].startsWith("node:"))continue;let n=Math.max(r[1].lastIndexOf("/"),r[1].lastIndexOf("\\"));return n>0?r[1].slice(0,n+1):null}return null})();function
|
|
4417
|
-
`);return
|
|
4418
|
-
`),false}}function Bd(t){let e="",r=0;for(;r<t.length;){let n=t[r];n==="*"&&t[r+1]==="*"?(e+=".*",r+=2,t[r]==="/"&&r++):n==="*"?(e+="[^/]*",r++):n==="?"?(e+="[^/]",r++):".+^${}()|[]\\".includes(n)?(e+="\\"+n,r++):(e+=n,r++);}return new RegExp(e)}var Od=["get","post","put","patch","delete","head","fetch"],qd=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Hd(t){let e=t.toLowerCase();return qd.some(r=>e.includes(r))}function Ud(t){if(!t)return null;if(t.data!==void 0&&t.data!==null){let e=t.data;return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString("base64"):JSON.stringify(e)}if(t.form!==void 0&&t.form!==null)return JSON.stringify(t.form);if(t.multipart!==void 0&&t.multipart!==null){let e=t.multipart,r={};for(let[n,s]of Object.entries(e))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?r[n]=String(s):s&&typeof s=="object"&&"name"in s?r[n]=`[file: ${s.name}]`:r[n]="[binary]";return JSON.stringify(r)}return null}function sa(t){return t?"\u2022\u2022\u2022\u2022":""}function zd(t){if(!t)return [];let e;for(let[n,s]of Object.entries(t))if(n.toLowerCase()==="cookie"){e=s;break}if(!e)return [];let r=[];for(let n of e.split(";")){let s=n.trim();if(!s)continue;let a=s.indexOf("="),i=a===-1?s:s.slice(0,a).trim(),o=a===-1?"":s.slice(a+1).trim();i&&r.push({name:i,value:sa(o)});}return r}function jd(t){let e=[];for(let r of t)for(let n of r.split(/,(?=\s*[A-Za-z0-9_.-]+=)/)){let s=n.trim();if(!s)continue;let a=s.split(";"),i=a[0].indexOf("=");if(i===-1)continue;let o=a[0].slice(0,i).trim(),l=a[0].slice(i+1).trim(),d=a.slice(1).map(c=>c.trim()).filter(Boolean).join(" \xB7 ")||void 0;o&&e.push({name:o,value:sa(l),attributes:d});}return e}var Xe=class Xe{constructor(e,r,n){this.originals=new Map;this.apiCallWriter=null;this.statusMix={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0};this.callCounter=0;this.apiCallCount=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=e,this.assertionTracker=r??null,this.apiConfig=n??Xe.DEFAULT_API_CONFIG;try{this.apiCallWriter=new H("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(e){return e!=null&&typeof e=="object"?te.get(e)??null:this.primitiveCallIds.get(e)??null}intercept(){for(let r of Od){let n=this.context[r].bind(this.context);this.originals.set(r,n),this.context[r]=this.createWrapper(r,n);}let e=this.context.dispose.bind(this.context);this.originals.set("dispose",e),this.context.dispose=async r=>(this.disposed=true,e(r));}tallyStatus(e){if(e===null||e<=0){this.statusMix.error++;return}if(e>=500){this.statusMix["5xx"]++;return}if(e>=400){this.statusMix["4xx"]++;return}if(e>=300){this.statusMix["3xx"]++;return}if(e>=200){this.statusMix["2xx"]++;return}this.statusMix.error++;}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0,apiStatusMix:{...this.statusMix}}}flushLegacyAnnotations(e){}dispose(){for(let[e,r]of this.originals)this.context[e]=r;this.originals.clear(),this.apiCallWriter?.close(),this.callCounter=0,this.apiCallCount=0,this._lastCallId=null,this.primitiveCallIds.clear();}get isDisposed(){return this.disposed}getCapturedCallCount(){return this.apiCallCount}tagResponseMethods(e,r){let{primitiveCallIds:n}=this,s=e.headers.bind(e);e.headers=function(){let g=s();return te.set(g,r),g};let a=e.headersArray.bind(e);e.headersArray=function(){let g=a();return te.set(g,r),g};let i=e.json.bind(e);e.json=async function(){let g=await i();return g!=null&&typeof g=="object"&&te.set(g,r),g};let o=e.status.bind(e);e.status=function(){let g=o();return n.set(g,r),g};let l=e.statusText.bind(e);e.statusText=function(){let g=l();return n.set(g,r),g};let d=e.ok.bind(e);e.ok=function(){let g=d();return n.set(g,r),g};let c=e.text.bind(e);e.text=async function(){let g=await c();return n.set(g,r),g};let u=e.body.bind(e);e.body=async function(){let g=await u();return te.set(g,r),g};}createWrapper(e,r){return async(n,s)=>{if(!na(n,this.apiConfig.apiIncludeUrls,this.apiConfig.apiExcludeUrls))return r(n,s);let a=`api-call-${this.callCounter++}`,i=new Date().toISOString(),o=e==="fetch"?(s?.method??"GET").toUpperCase():e.toUpperCase(),l=Ud(s),d=perf_hooks.performance.now();this._lastCallId=a,this.assertionTracker&&this.assertionTracker.setCurrentCallId(a);let c;try{c=await r(n,s);}catch(u){let f=perf_hooks.performance.now();try{let g=this.apiConfig.captureRequestBody?Ye(l,this.apiConfig.redactBodyFields):null,p={id:a,timestamp:i,method:o,url:Sr(n),requestHeaders:null,requestBody:g,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((f-d)*100)/100,isBinary:!1,error:u instanceof Error?u.message:String(u)};this.apiCallWriter&&(this.apiCallWriter.append(p),this.apiCallCount++,this.tallyStatus(null));}catch{}throw u}try{let u=perf_hooks.performance.now(),f=c.headers(),g=f["content-type"]??null,p=g?!Hd(g):!1,h=null;this.apiConfig.captureRequestHeaders&&s?.headers&&(h=s.headers);let b=null;this.apiConfig.captureResponseHeaders&&(b=f);let v=this.apiConfig.captureRequestBody?l:null,m=null;if(this.apiConfig.captureResponseBody)try{p?m=(await c.body()).toString("base64"):m=await c.text();}catch{}let y=[],w=[];try{if(this.apiConfig.captureRequestHeaders&&(y=zd(s?.headers)),this.apiConfig.captureResponseHeaders){let _=c.headersArray().filter(S=>S.name.toLowerCase()==="set-cookie").map(S=>S.value);w=jd(_);}}catch{}h=Cr(h,this.apiConfig.redactHeaders),b=Cr(b,this.apiConfig.redactHeaders),v=Ye(v,this.apiConfig.redactBodyFields),m=Ye(m,this.apiConfig.redactBodyFields);let x={id:a,timestamp:i,method:o,url:Sr(c.url()),requestHeaders:h,requestBody:v,responseStatusCode:c.status(),responseStatusText:c.statusText(),responseHeaders:b,responseBody:m,requestCookies:y.length?y:null,responseCookies:w.length?w:null,responseTimeMs:Math.round((u-d)*100)/100,isBinary:p,error:null};this.apiCallWriter&&(this.apiCallWriter.append(x),this.apiCallCount++,this.tallyStatus(x.responseStatusCode));}catch{}try{c[wr]=a,this.tagResponseMethods(c,a);}catch{}return c}}};Xe.DEFAULT_API_CONFIG=Object.freeze({trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]});var de=Xe;var Gd=[".png",".jpg",".jpeg"],Kd=/A snapshot doesn't exist at /;function Jd(t){return t.wrote?t.existedBefore?"updated":"new":t.pass?"passed":"failed"}function Yd(t){return t.status==="failed"&&!t.hadBaseline}function aa(t){if(!t)return null;try{let e=fs$1.statSync(t);return {size:e.size,mtimeMs:e.mtimeMs}}catch{return null}}function Xd(t,e){if(!Ne(t))return null;try{return t.snapshotPath(e,{kind:"screenshot"})}catch{return null}}function Zd(t){let e=t.toLowerCase();return Gd.some(r=>e.endsWith(r))?t:`${t}.png`}function Qd(){try{return test.test.info()}catch{return null}}function ec(t,e,r){let n=a=>/^(.+)-(expected|actual|diff|previous)\.[A-Za-z0-9]+$/.exec(a)?.[1]??null,s=t.slice(e);if(r){for(let a of s)if(a.path===r&&/-expected\.[A-Za-z0-9]+$/.test(a.name))return n(a.name)}for(let a of s){let i=n(a.name);if(i)return i}return null}function tc(t,e){return e?path.basename(e,path.extname(e)||".png"):t.replace(/\.[A-Za-z0-9]+$/,"")}async function rc(t,e){if(e===null)return Le("Attaching the baseline of a passing comparison"),null;try{let r=path.extname(e)||".png",n=path.basename(e,r);return await t.attach(`${n}-expected${r}`,{path:e}),n}catch{return null}}async function nc(t,e){try{await t.attach(Ht,{body:Buffer.from(JSON.stringify([e])),contentType:"application/json"});}catch{}}async function Rr(t,e,r={}){let n={...r};delete n.tags;let s=Zd(e),a=Qd(),i=a?.attachments.length??0,o=a?.errors?.length??0,l=a?Xd(a,s):null,d=aa(l),c=true,u="";try{await test.expect(t).toHaveScreenshot(s,n);}catch(f){c=false,u=f instanceof Error?f.message:String(f);}if(a){let f=aa(l),g=l!==null?f!==null&&(d===null||d.size!==f.size||d.mtimeMs!==f.mtimeMs):(a.errors??[]).slice(o).some(v=>Kd.test(v.message??"")),p=Jd({pass:c,wrote:g,existedBefore:d!==null}),b=(p==="passed"||p==="updated"?await rc(a,l):ec(a.attachments,i,l))??(Yd({status:p,hadBaseline:d!==null})?tc(s,l):null);b&&await nc(a,{stem:b,name:e,status:p,...l?{committedPath:l}:{}});}return {pass:c,name:"toMatchVisualBaseline",message:()=>c?`Expected "${e}" to differ from its visual baseline, but it matched.`:u}}test.expect.extend({toMatchVisualBaseline:Rr});function ic(){try{return test.test.info()}catch{return null}}jn(Je(test.expect),ic);var oc="__testrelic_api_config",lc="__testrelic_config_trackApiCalls";function Ar(t){let e=t.annotations.find(n=>n.type===oc&&n.description!==void 0);if(e)try{return JSON.parse(e.description,dc)}catch{}let r=t.annotations.find(n=>n.type===lc&&n.description!==void 0);return r?{trackApiCalls:r.description!=="false",captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}:{trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}}function dc(t,e){if(typeof e=="object"&&e!==null&&e.__regexp===true&&typeof e.source=="string"){let{source:r,flags:n}=e;return new RegExp(r,n)}return e}var pa={page:async({page:t},e,r)=>{let n=new Ke(t);try{await n.init();}catch{}await e(t);try{let{navigations:s,networkRequestsFile:a,networkRequestsCount:i,consoleLogsFile:o,consoleLogsCount:l}=await n.getFileData(),d={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:a,networkRequestsCount:i,consoleLogsFile:o,consoleLogsCount:l,apiCallsFile:null,apiCallsCount:0};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:t},e,r)=>{let n=Ar(r);if(!n.trackApiCalls){await e(t);return}let s=new oe,a=new de(t,s,n);a.intercept(),le(s,a);try{await e(t);}finally{le(null,null);}try{let{apiCallsFile:i,apiCallsCount:o,apiStatusMix:l}=a.getFileData(),d=n.captureAssertions?s.getData():[],c={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:d,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:i,apiCallsCount:o,apiStatusMix:l};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(c)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};test.test.extend(pa);Je(test.expect);var gc={request:async({request:t},e,r)=>{let n=Ar(r);if(!n.trackApiCalls){await e(t);return}let s=new oe,a=new de(t,s,n);a.intercept(),le(s,a);let i=null;try{i=new H("api-console");}catch{}let o=0,l=process.stdout.write,d=process.stderr.write;process.stdout.write=function(c,...u){try{let f=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!f.startsWith("[testrelic]")&&!f.startsWith("\u2139 TestRelic")&&!f.startsWith("\u2713 TestRelic")&&!f.startsWith("\u26A0 TestRelic")&&i&&(i.append({level:"stdout",text:f.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),o++);}catch{}return l.apply(process.stdout,[c,...u])},process.stderr.write=function(c,...u){try{let f=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!f.startsWith("[testrelic]")&&!f.startsWith("\u26A0 TestRelic")&&i&&(i.append({level:"stderr",text:f.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),o++);}catch{}return d.apply(process.stderr,[c,...u])};try{await e(t);}finally{process.stdout.write=l,process.stderr.write=d,le(null,null);}try{i?.close();let{apiCallsFile:c,apiCallsCount:u,apiStatusMix:f}=a.getFileData(),g=n.captureAssertions?s.getData():[],p={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:g,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:o>0?i?.getPath()??null:null,consoleLogsCount:o,apiCallsFile:c,apiCallsCount:u,apiStatusMix:f};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(p)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};var fa="@testrelic/playwright-analytics";function mc(t){return Array.isArray(t)?t.some(e=>Array.isArray(e)&&typeof e[0]=="string"&&e[0]===fa):false}function vc(t,e){let n={video:"on",screenshot:"on",trace:"on",...t.use??{}},s;Array.isArray(t.reporter)?s=t.reporter:typeof t.reporter=="string"?s=[[t.reporter]]:s=[["list"]];let a=mc(s)?s:[...s,[fa,e??{}]];return test.defineConfig({...t,use:n,reporter:a})}var ga=false;function Og(t,e,r="manual_record"){if(!t||!t.annotations){ga||(ga=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
|
|
4419
|
-
`));return}let n={url:e,navigationType:r,timestamp:new Date().toISOString()};t.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}Object.defineProperty(exports,"ATTACHMENT_CONTENT_TYPE",{enumerable:true,get:function(){return core.ATTACHMENT_CONTENT_TYPE}});Object.defineProperty(exports,"ATTACHMENT_NAME",{enumerable:true,get:function(){return core.ATTACHMENT_NAME}});Object.defineProperty(exports,"PAYLOAD_VERSION",{enumerable:true,get:function(){return core.PAYLOAD_VERSION}});Object.defineProperty(exports,"isTestRelicDataPayload",{enumerable:true,get:function(){return core.isTestRelicDataPayload}});exports.SCHEMA_VERSION=
|
|
4412
|
+
`));}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let e=path.dirname(this.config.outputPath);this.streamingWriter=new ve(e);for(let r of this.collectedTests){let n=dt(r.filePath,r.titlePath,r.testId,r.retry),s=r.apiCallsFile&&r.apiCallsCount>0?$(r.apiCallsFile):void 0,a={id:n,...r.expectedStatus!=="passed"?{expectedStatus:r.expectedStatus}:{},navigations:r.navigations??[],apiAssertions:r.apiAssertions??[],actions:r.actions??[],artifacts:r.artifacts,failureDiagnostic:r.failure,hasNetworkFile:r.networkRequestsFile!==null,networkRequestsCount:r.networkRequestsCount,hasConsoleFile:r.consoleLogsFile!==null,consoleLogsCount:r.consoleLogsCount,hasApiCallsFile:r.apiCallsFile!==null,apiCallsCount:r.apiCallsCount,startedAt:r.startedAt};this.streamingWriter.writeTestDetail(n,a,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let i={id:n,title:r.titlePath[r.titlePath.length-1]??r.title,titlePath:r.titlePath,filePath:r.filePath,status:r.status,...r.expectedStatus!=="passed"?{expectedStatus:r.expectedStatus}:{},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(`
|
|
4413
|
+
`)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,actionCount:r.actions?.length??0,testType:r.testType,apiCallCount:r.apiCallsCount,...r.apiStatusMix?{apiStatusMix:r.apiStatusMix}:s?{apiStatusMix:Ed(s)}:{},assertionsPassed:rt(r.apiAssertions,"passed"),assertionsFailed:rt(r.apiAssertions,"failed"),...(()=>{let o=Qs(r.apiAssertions);return o?{firstFailedAssertion:o}:{}})(),isRetry:!1,retryGroupKey:ct(r.filePath,r.titlePath,r.testId)};switch(this.testIndex.push(i),this.summaryCounters.total++,r.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.upsertAggContribution(`${r.filePath}::${r.titlePath.join(" > ")}`,ta(r.retry,s,r.apiAssertions??[],r.navigations??[],r.networkRequestsCount,r.consoleLogsCount,r.actions??null));}this.collectedTests.length=0;}catch{}}buildTimeline(){let e=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls:null,apiAssertions:r.apiAssertions,testId:r.testId,filePath:r.filePath,suiteName:r.suiteName,testType:r.testType,isFlaky:r.isFlaky,retryStatus:r.retryStatus,expectedStatus:r.expectedStatus,actualStatus:r.actualStatus,artifacts:r.artifacts,networkRequests:null,actions:r.actions,consoleLogs:null}));return vs(e,{navigationTypes:this.config.navigationTypes})}readJsonlFile(e){if(!e)return null;let r=$(e);return r.length>0?r:null}toTestResult(e,r){let n=null,s=null,a=null;return r?.loadFiles&&(n=this.readJsonlFile(e.networkRequestsFile),s=this.readJsonlFile(e.consoleLogsFile),a=this.readJsonlFile(e.apiCallsFile)),{title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,retry:e.retry,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,visual:e.visual,networkRequests:n,apiCalls:a,apiAssertions:e.apiAssertions,actions:e.actions??null,consoleLogs:s}}buildCloudTestPayload(e){let r={title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retry:e.retry,retryCount:e.retryCount,retryStatus:e.retryStatus,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,visual:e.visual??[],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=We(e.apiAssertions)),e.consoleLogsFile&&(r.consoleLogs=$(e.consoleLogsFile)),e.networkRequestsFile&&(r.networkRequests=$(e.networkRequestsFile)),e.apiCallsFile){let n=$(e.apiCallsFile);r.apiCalls=Ve(n),(!r.networkRequests||r.networkRequests.length===0)&&(r.networkRequests=$e(n));}return r}writeReport(e){try{let r=JSON.stringify(e),n=this.config.outputPath,s=path.dirname(n);fs$1.mkdirSync(s,{recursive:!0});let a=n+".tmp";fs$1.writeFileSync(a,r,"utf-8"),fs$1.renameSync(a,n);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
|
|
4414
|
+
`);}}};var $d=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Wd(t){let e=t.toLowerCase();return $d.some(r=>e.includes(r))}var at=class t{constructor(e,r){this.page=e;this.records=[];this.listeners=[];this.navCounters=[];this.pendingRequests=new Map;this.networkWriter=null;this.consoleWriter=null;this.pendingBodyReads=[];this.requestIdCounter=0;this.networkRequestCount=0;this.consoleLogCount=0;this.includeNetworkStats=r?.includeNetworkStats??true,this.origGoto=e.goto.bind(e),this.origGoBack=e.goBack.bind(e),this.origGoForward=e.goForward.bind(e),this.origReload=e.reload.bind(e);try{this.includeNetworkStats&&(this.networkWriter=new V("network")),this.consoleWriter=new V("console");}catch{}this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async finalizeCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[,e]of this.pendingRequests)this.networkWriter&&(this.networkWriter.append({url:e.url,method:e.method,resourceType:e.resourceType,statusCode:0,responseTimeMs:Date.now()-e.startTimeMs,startedAt:e.startedAt,requestHeaders:e.headers,requestBody:e.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:e.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.networkRequestCount++);this.pendingRequests.clear(),this.networkWriter?.close(),this.consoleWriter?.close();}static mapConsoleType(e){switch(e){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getFileData(){this.assembleNetworkStats();let e=this.records.map(r=>({url:r.url,navigationType:r.navigationType,timestamp:r.timestamp,domContentLoadedAt:r.domContentLoadedAt,networkIdleAt:r.networkIdleAt,networkStats:r.networkStats}));return this.includeNetworkStats?await this.finalizeCapturedRequests():this.consoleWriter?.close(),{navigations:e,networkRequestsFile:this.networkWriter?.getCount()?this.networkWriter.getPath():null,networkRequestsCount:this.networkWriter?.getCount()??0,consoleLogsFile:this.consoleWriter?.getCount()?this.consoleWriter.getPath():null,consoleLogsCount:this.consoleWriter?.getCount()??0}}async flushLegacyAnnotations(e){}dispose(){let e=t.asPatchable(this.page);e.goto=this.origGoto,e.goBack=this.origGoBack,e.goForward=this.origGoForward,e.reload=this.origReload;for(let{event:r,handler:n}of this.listeners)this.page.off(r,n);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}getRecords(){return this.assembleNetworkStats(),this.records}static asPatchable(e){return e}interceptMethods(){let e=this.page,r=t.asPatchable(e);r.goto=async(n,s)=>(this.recordNavigation(n,"goto"),this.origGoto(n,s)),r.goBack=async n=>{let s=await this.origGoBack(n);return this.recordNavigation(e.url(),"back"),s},r.goForward=async n=>{let s=await this.origGoForward(n);return this.recordNavigation(e.url(),"forward"),s},r.reload=async n=>(this.recordNavigation(e.url(),"refresh"),this.origReload(n));}attachListeners(){let e=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",e),this.listeners.push({event:"domcontentloaded",handler:e});let r=s=>{try{let a=s;if(typeof a.parentFrame=="function"&&a.parentFrame()!==null)return;let i=a.url(),o=this.records[this.records.length-1];if(o&&Date.now()-new Date(o.timestamp).getTime()<50&&o.url===i)return;this.recordNavigation(i,"navigation");}catch{}};this.page.on("framenavigated",r),this.listeners.push({event:"framenavigated",handler:r});let n=s=>{try{let a=s,i=a.type(),o=a.text();if(i==="debug"&&o.startsWith("__testrelic_nav:")){try{let l=JSON.parse(o.slice(16));l.type&&l.url&&this.recordNavigation(l.url,l.type);}catch{}return}{let l=null;try{let c=a.location();c&&c.url&&(l=`${c.url}:${c.lineNumber}:${c.columnNumber}`);}catch{}let d=t.mapConsoleType(i);this.consoleWriter&&(this.consoleWriter.append({level:d,text:o,timestamp:new Date().toISOString(),location:l}),this.consoleLogCount++);}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=o=>{let l=this.records.length-1,d=this.counterForNav(l);d&&d.totalRequests++;try{let c=o,p=String(this.requestIdCounter++),u=c.postData()??null,f={url:c.url(),method:c.method(),resourceType:this.mapResourceType(c.resourceType()),headers:c.headers(),postData:u,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now(),navIndex:l};this.pendingRequests.set(p,f),o.__testrelic_id=p;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let a=o=>{try{let l=o,d=l.request().__testrelic_id,c=d?this.pendingRequests.get(d):void 0,p=this.counterForNav(c?c.navIndex:this.records.length-1);if(p){let v=l.status();v>=400&&(p.failedRequests++,p.failedRequestUrls.push(v+" "+l.url()));let y=l.headers()["content-length"];y&&(p.totalBytes+=parseInt(y,10)||0);let x=l.request().resourceType(),C=this.mapResourceType(x);p.byType[C]++;}if(!d||!c)return;this.pendingRequests.delete(d);let u=Date.now()-c.startTimeMs,f=l.headers(),g=f["content-type"]??null,h=parseInt(f["content-length"]??"0",10)||0,m=g?!Wd(g):!1,b=(async()=>{let v=null;if(!m)try{v=(await l.body()).toString("utf-8");}catch{}let y={url:c.url,method:c.method,resourceType:c.resourceType,statusCode:l.status(),responseTimeMs:u,startedAt:c.startedAt,requestHeaders:c.headers,requestBody:c.postData,responseBody:v,responseHeaders:f,contentType:g,responseSize:h,requestBodyTruncated:c.postDataTruncated,responseBodyTruncated:!1,isBinary:m,error:null};this.networkWriter&&(this.networkWriter.append(y),this.networkRequestCount++);})();this.pendingBodyReads.push(b);}catch{}};this.page.on("response",a),this.listeners.push({event:"response",handler:a});let i=o=>{let l=o.__testrelic_id,d=l?this.pendingRequests.get(l):void 0,c=this.counterForNav(d?d.navIndex:this.records.length-1);if(c){c.failedRequests++;try{let p=o;c.failedRequestUrls.push("ERR "+p.url());}catch{}}try{let p=o;if(!l||!d)return;this.pendingRequests.delete(l);let u={url:d.url,method:d.method,resourceType:d.resourceType,statusCode:0,responseTimeMs:Date.now()-d.startTimeMs,startedAt:d.startedAt,requestHeaders:d.headers,requestBody:d.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:d.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:p.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(u),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",i),this.listeners.push({event:"requestfailed",handler:i});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let e=history.pushState.bind(history),r=history.replaceState.bind(history);history.pushState=function(...n){e(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){r(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(e,r){this.records.push({url:e,navigationType:r,timestamp:new Date().toISOString()}),this.includeNetworkStats&&this.navCounters.push(this.createNetworkCounter());}createNetworkCounter(){return {totalRequests:0,failedRequests:0,failedRequestUrls:[],totalBytes:0,byType:{xhr:0,document:0,script:0,stylesheet:0,image:0,font:0,other:0}}}counterForNav(e){return e>=0?this.navCounters[e]:void 0}assembleNetworkStats(){if(this.includeNetworkStats)for(let e=0;e<this.records.length;e++){let r=this.navCounters[e];r&&(this.records[e].networkStats={totalRequests:r.totalRequests,failedRequests:r.failedRequests,failedRequestUrls:[...r.failedRequestUrls],totalBytes:r.totalBytes,byType:{...r.byType}});}}mapResourceType(e){switch(e){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};var Pr=Symbol.for("__testrelic_call_id"),Kd="__testrelic_api_assertions",ne=new WeakMap,de=class{constructor(){this.assertions=[];this.currentCallId=null;}recordAssertion(e){this.assertions.push(e);}getAssertions(){return this.assertions}setCurrentCallId(e){this.currentCallId=e;}getCurrentCallId(){return this.currentCallId}getData(){return [...this.assertions]}flushLegacyAnnotations(e){this.assertions.length!==0&&e.annotations.push({type:Kd,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}},aa=new Map;function Jd(t){let e=aa.get(t);if(e)return e;try{let r=t.startsWith("file://")?url.fileURLToPath(t):t,s=fs$1.readFileSync(r,"utf-8").split(`
|
|
4415
|
+
`);return aa.set(t,s),s}catch{return null}}var ia=(()=>{let t=new Error().stack;if(!t)return null;for(let e of t.split(`
|
|
4416
|
+
`)){let r=e.match(/at\s+(?:.*?\s+\()?(.+?):\d+:\d+\)?$/);if(!r||r[1].startsWith("node:"))continue;let n=Math.max(r[1].lastIndexOf("/"),r[1].lastIndexOf("\\"));return n>0?r[1].slice(0,n+1):null}return null})();function Yd(t){if(!t.startsWith("file:"))return t;try{return url.fileURLToPath(t)}catch{return t}}function Xd(){let e=new Error().stack;if(!e)return null;let r=e.split(`
|
|
4417
|
+
`);return oa(r,true)??oa(r,false)}function oa(t,e){for(let r of t){if(e&&ia!==null&&r.includes(ia)||r.includes("node_modules")||r.includes("node:internal")||r.includes(" at new Error")||r.includes(" at captureAssertionLocation")||r.includes(" at findFrame")||r.includes(" at expectWrapper")||r.includes(" at wrappedMatcher"))continue;let n=r.match(/at\s+(?:.*?\s+\()?(.+?):(\d+):(\d+)\)?$/);if(n)return {file:Yd(n[1]),line:parseInt(n[2],10),column:parseInt(n[3],10)}}return null}function Zd(t,e){if(!t)return "custom";let r=t.toLowerCase();return r.includes(".status()")&&!r.includes(".statustext()")?r.includes(".ok()")?"statusOk":"status":r.includes(".ok()")?"statusOk":r.includes(".headers()")||r.includes(".headersarray()")?"header":r.includes("tomatchobject")||r.includes("toequal")?"bodyMatch":r.includes("tocontain")||r.includes("tostringcontaining")?"bodyContains":r.includes(".json()")||r.includes(".text()")?"bodyField":"custom"}function Qd(t,e,r){let n=function(o,...l){let d=t(),c=e();if(!d||!c)return r(o,...l);let p=null;if(o!=null&&typeof o=="object"){let h=o[Pr];typeof h=="string"&&(p=h);}if(!p&&o!==null&&o!==void 0&&typeof o=="object"&&(p=ne.get(o)??null),p||(p=c.getCallIdForValue(o)),p||(p=d.getCurrentCallId()),!p)return r(o,...l);let u=Xd(),f;if(u){let h=Jd(u.file);h&&u.line>0&&u.line<=h.length&&(f=h[u.line-1].trim());}let g=r(o,...l);return ua(g,{tracker:d,callId:p,received:o,location:u??{file:"unknown",line:0},expression:f})},s=r,a=n;for(let i of Object.keys(s))a[i]=s[i];return n}var la=Symbol.for("testrelic.activeAssertionContext");function Mr(){let t=globalThis,e=t[la];return e||(e={tracker:null,apiTracker:null},t[la]=e),e}function ce(t,e){let r=Mr();r.tracker=t,r.apiTracker=e;}function it(t){return Qd(()=>Mr().tracker,()=>Mr().apiTracker,t)}function ua(t,e){return new Proxy(t,{get(r,n,s){let a=Reflect.get(r,n,s);return typeof a!="function"||typeof n=="symbol"?a:n==="not"?ua(a,e):function(...o){let l=o[0],d="passed",c=e.received,p=null;try{let u=a.apply(this??r,o);return u&&typeof u=="object"&&typeof u.then=="function"?u.then(()=>{Ir(e,n,l,c,"passed");},f=>{throw Ir(e,n,l,c,"failed"),f}):u}catch(u){if(d="failed",p=u,u instanceof Error&&u.message){let f=u.message.match(/Received:\s*(.+)/);f&&(c=f[1]);}throw u}finally{(p!==null||d==="passed")&&Ir(e,n,l,c,d);}}}})}function Ir(t,e,r,n,s){let a=Zd(t.expression,t.received),i={callId:t.callId,type:a,expected:da(r),actual:da(n),status:s,location:t.location,expression:t.expression};t.tracker.recordAssertion(i);}function da(t){if(t==null)return t;if(typeof t=="string")return ie(t);if(typeof t=="number"||typeof t=="boolean")return t;try{return JSON.stringify(t),t}catch{return String(t)}}var pa="[REDACTED]";function Lr(t,e){if(t===null||e.length===0)return t;let r=new Set(e.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(t))Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=r.has(s.toLowerCase())?pa:t[s]);return n}function ot(t,e){if(t===null||e.length===0)return t;let r;try{r=JSON.parse(t);}catch{return t}if(typeof r!="object"||r===null)return t;let n=new Set(e.map(a=>a.toLowerCase())),s=Er(r,n);return JSON.stringify(s)}function Er(t,e){if(Array.isArray(t))return t.map(r=>Er(r,e));if(typeof t=="object"&&t!==null){let r={};for(let n of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n];e.has(n.toLowerCase())?r[n]=pa:r[n]=Er(s,e);}return r}return t}var ec=new Set(["access_token","api_key","token","sig"]);function Nr(t){if(!t)return t;let e;try{e=new URL(t);}catch{return t}let r=false;for(let n of [...e.searchParams.keys()])ec.has(n.toLowerCase())&&(e.searchParams.delete(n),r=true);return r?e.toString():t}function ga(t,e,r){if(r.length>0){for(let n of r)if(fa(t,n))return false}if(e.length>0){for(let n of e)if(fa(t,n))return true;return false}return true}function fa(t,e){try{return e instanceof RegExp?e.test(t):tc(e).test(t)}catch{return process.stderr.write(`[testrelic] Invalid URL filter pattern: ${String(e)}
|
|
4418
|
+
`),false}}function tc(t){let e="",r=0;for(;r<t.length;){let n=t[r];n==="*"&&t[r+1]==="*"?(e+=".*",r+=2,t[r]==="/"&&r++):n==="*"?(e+="[^/]*",r++):n==="?"?(e+="[^/]",r++):".+^${}()|[]\\".includes(n)?(e+="\\"+n,r++):(e+=n,r++);}return new RegExp(e)}var rc=["get","post","put","patch","delete","head","fetch"],nc=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function sc(t){let e=t.toLowerCase();return nc.some(r=>e.includes(r))}function ac(t){if(!t)return null;if(t.data!==void 0&&t.data!==null){let e=t.data;return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString("base64"):JSON.stringify(e)}if(t.form!==void 0&&t.form!==null)return JSON.stringify(t.form);if(t.multipart!==void 0&&t.multipart!==null){let e=t.multipart,r={};for(let[n,s]of Object.entries(e))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?r[n]=String(s):s&&typeof s=="object"&&"name"in s?r[n]=`[file: ${s.name}]`:r[n]="[binary]";return JSON.stringify(r)}return null}function ha(t){return t?"\u2022\u2022\u2022\u2022":""}function ic(t){if(!t)return [];let e;for(let[n,s]of Object.entries(t))if(n.toLowerCase()==="cookie"){e=s;break}if(!e)return [];let r=[];for(let n of e.split(";")){let s=n.trim();if(!s)continue;let a=s.indexOf("="),i=a===-1?s:s.slice(0,a).trim(),o=a===-1?"":s.slice(a+1).trim();i&&r.push({name:i,value:ha(o)});}return r}function oc(t){let e=[];for(let r of t)for(let n of r.split(/,(?=\s*[A-Za-z0-9_.-]+=)/)){let s=n.trim();if(!s)continue;let a=s.split(";"),i=a[0].indexOf("=");if(i===-1)continue;let o=a[0].slice(0,i).trim(),l=a[0].slice(i+1).trim(),d=a.slice(1).map(c=>c.trim()).filter(Boolean).join(" \xB7 ")||void 0;o&&e.push({name:o,value:ha(l),attributes:d});}return e}var lt=class lt{constructor(e,r,n){this.originals=new Map;this.apiCallWriter=null;this.statusMix={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0};this.callCounter=0;this.apiCallCount=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=e,this.assertionTracker=r??null,this.apiConfig=n??lt.DEFAULT_API_CONFIG;try{this.apiCallWriter=new V("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(e){return e!=null&&typeof e=="object"?ne.get(e)??null:this.primitiveCallIds.get(e)??null}intercept(){for(let r of rc){let n=this.context[r].bind(this.context);this.originals.set(r,n),this.context[r]=this.createWrapper(r,n);}let e=this.context.dispose.bind(this.context);this.originals.set("dispose",e),this.context.dispose=async r=>(this.disposed=true,e(r));}tallyStatus(e){if(e===null||e<=0){this.statusMix.error++;return}if(e>=500){this.statusMix["5xx"]++;return}if(e>=400){this.statusMix["4xx"]++;return}if(e>=300){this.statusMix["3xx"]++;return}if(e>=200){this.statusMix["2xx"]++;return}this.statusMix.error++;}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0,apiStatusMix:{...this.statusMix}}}flushLegacyAnnotations(e){}dispose(){for(let[e,r]of this.originals)this.context[e]=r;this.originals.clear(),this.apiCallWriter?.close(),this.callCounter=0,this.apiCallCount=0,this._lastCallId=null,this.primitiveCallIds.clear();}get isDisposed(){return this.disposed}getCapturedCallCount(){return this.apiCallCount}tagResponseMethods(e,r){let{primitiveCallIds:n}=this,s=e.headers.bind(e);e.headers=function(){let f=s();return ne.set(f,r),f};let a=e.headersArray.bind(e);e.headersArray=function(){let f=a();return ne.set(f,r),f};let i=e.json.bind(e);e.json=async function(){let f=await i();return f!=null&&typeof f=="object"&&ne.set(f,r),f};let o=e.status.bind(e);e.status=function(){let f=o();return n.set(f,r),f};let l=e.statusText.bind(e);e.statusText=function(){let f=l();return n.set(f,r),f};let d=e.ok.bind(e);e.ok=function(){let f=d();return n.set(f,r),f};let c=e.text.bind(e);e.text=async function(){let f=await c();return n.set(f,r),f};let p=e.body.bind(e);e.body=async function(){let f=await p();return ne.set(f,r),f};}createWrapper(e,r){return async(n,s)=>{if(!ga(n,this.apiConfig.apiIncludeUrls,this.apiConfig.apiExcludeUrls))return r(n,s);let a=`api-call-${this.callCounter++}`,i=new Date().toISOString(),o=e==="fetch"?(s?.method??"GET").toUpperCase():e.toUpperCase(),l=ac(s),d=perf_hooks.performance.now();this._lastCallId=a,this.assertionTracker&&this.assertionTracker.setCurrentCallId(a);let c;try{c=await r(n,s);}catch(p){let u=perf_hooks.performance.now();try{let f=this.apiConfig.captureRequestBody?ot(l,this.apiConfig.redactBodyFields):null,g={id:a,timestamp:i,method:o,url:Nr(n),requestHeaders:null,requestBody:f,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((u-d)*100)/100,isBinary:!1,error:p instanceof Error?p.message:String(p)};this.apiCallWriter&&(this.apiCallWriter.append(g),this.apiCallCount++,this.tallyStatus(null));}catch{}throw p}try{let p=perf_hooks.performance.now(),u=c.headers(),f=u["content-type"]??null,g=f?!sc(f):!1,h=null;this.apiConfig.captureRequestHeaders&&s?.headers&&(h=s.headers);let m=null;this.apiConfig.captureResponseHeaders&&(m=u);let b=this.apiConfig.captureRequestBody?l:null,v=null;if(this.apiConfig.captureResponseBody)try{g?v=(await c.body()).toString("base64"):v=await c.text();}catch{}let y=[],x=[];try{if(this.apiConfig.captureRequestHeaders&&(y=ic(s?.headers)),this.apiConfig.captureResponseHeaders){let I=c.headersArray().filter(T=>T.name.toLowerCase()==="set-cookie").map(T=>T.value);x=oc(I);}}catch{}h=Lr(h,this.apiConfig.redactHeaders),m=Lr(m,this.apiConfig.redactHeaders),b=ot(b,this.apiConfig.redactBodyFields),v=ot(v,this.apiConfig.redactBodyFields);let C={id:a,timestamp:i,method:o,url:Nr(c.url()),requestHeaders:h,requestBody:b,responseStatusCode:c.status(),responseStatusText:c.statusText(),responseHeaders:m,responseBody:v,requestCookies:y.length?y:null,responseCookies:x.length?x:null,responseTimeMs:Math.round((p-d)*100)/100,isBinary:g,error:null};this.apiCallWriter&&(this.apiCallWriter.append(C),this.apiCallCount++,this.tallyStatus(C.responseStatusCode));}catch{}try{c[Pr]=a,this.tagResponseMethods(c,a);}catch{}return c}}};lt.DEFAULT_API_CONFIG=Object.freeze({trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]});var ue=lt;var uc=[".png",".jpg",".jpeg"],pc=/A snapshot doesn't exist at /;function fc(t){return t.wrote?t.existedBefore?"updated":"new":t.pass?"passed":"failed"}function gc(t){return t.status==="failed"&&!t.hadBaseline}function ma(t){if(!t)return null;try{let e=fs$1.statSync(t);return {size:e.size,mtimeMs:e.mtimeMs}}catch{return null}}function hc(t,e){if(!Be(t))return null;try{return t.snapshotPath(e,{kind:"screenshot"})}catch{return null}}function mc(t){let e=t.toLowerCase();return uc.some(r=>e.endsWith(r))?t:`${t}.png`}function vc(){try{return test.test.info()}catch{return null}}function yc(t,e,r){let n=a=>/^(.+)-(expected|actual|diff|previous)\.[A-Za-z0-9]+$/.exec(a)?.[1]??null,s=t.slice(e);if(r){for(let a of s)if(a.path===r&&/-expected\.[A-Za-z0-9]+$/.test(a.name))return n(a.name)}for(let a of s){let i=n(a.name);if(i)return i}return null}function bc(t,e){return e?path.basename(e,path.extname(e)||".png"):t.replace(/\.[A-Za-z0-9]+$/,"")}async function xc(t,e){if(e===null)return Oe("Attaching the baseline of a passing comparison"),null;try{let r=path.extname(e)||".png",n=path.basename(e,r);return await t.attach(`${n}-expected${r}`,{path:e}),n}catch{return null}}async function wc(t,e){try{await t.attach(Yt,{body:Buffer.from(JSON.stringify([e])),contentType:"application/json"});}catch{}}async function Fr(t,e,r={}){let n={...r};delete n.tags;let s=mc(e),a=vc(),i=a?.attachments.length??0,o=a?.errors?.length??0,l=a?hc(a,s):null,d=ma(l),c=true,p="";try{await test.expect(t).toHaveScreenshot(s,n);}catch(u){c=false,p=u instanceof Error?u.message:String(u);}if(a){let u=ma(l),f=l!==null?u!==null&&(d===null||d.size!==u.size||d.mtimeMs!==u.mtimeMs):(a.errors??[]).slice(o).some(b=>pc.test(b.message??"")),g=fc({pass:c,wrote:f,existedBefore:d!==null}),m=(g==="passed"||g==="updated"?await xc(a,l):yc(a.attachments,i,l))??(gc({status:g,hadBaseline:d!==null})?bc(s,l):null);m&&await wc(a,{stem:m,name:e,status:g,...l?{committedPath:l}:{}});}return {pass:c,name:"toMatchVisualBaseline",message:()=>c?`Expected "${e}" to differ from its visual baseline, but it matched.`:p}}test.expect.extend({toMatchVisualBaseline:Fr});function Tc(){try{return test.test.info()}catch{return null}}Zn(it(test.expect),Tc);var Sc="__testrelic_api_config",Rc="__testrelic_config_trackApiCalls";function Br(t){let e=t.annotations.find(n=>n.type===Sc&&n.description!==void 0);if(e)try{return JSON.parse(e.description,Ac)}catch{}let r=t.annotations.find(n=>n.type===Rc&&n.description!==void 0);return r?{trackApiCalls:r.description!=="false",captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}:{trackApiCalls:true,captureRequestHeaders:true,captureResponseHeaders:true,captureRequestBody:true,captureResponseBody:true,captureAssertions:true,redactHeaders:["authorization","cookie","set-cookie","x-api-key"],redactBodyFields:["password","secret","token","apiKey","api_key"],apiIncludeUrls:[],apiExcludeUrls:[]}}function Ac(t,e){if(typeof e=="object"&&e!==null&&e.__regexp===true&&typeof e.source=="string"){let{source:r,flags:n}=e;return new RegExp(r,n)}return e}var Ca={page:async({page:t},e,r)=>{let n=new at(t);try{await n.init();}catch{}await e(t);try{let{navigations:s,networkRequestsFile:a,networkRequestsCount:i,consoleLogsFile:o,consoleLogsCount:l}=await n.getFileData(),d={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:a,networkRequestsCount:i,consoleLogsFile:o,consoleLogsCount:l,apiCallsFile:null,apiCallsCount:0};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:t},e,r)=>{let n=Br(r);if(!n.trackApiCalls){await e(t);return}let s=new de,a=new ue(t,s,n);a.intercept(),ce(s,a);try{await e(t);}finally{ce(null,null);}try{let{apiCallsFile:i,apiCallsCount:o,apiStatusMix:l}=a.getFileData(),d=n.captureAssertions?s.getData():[],c={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:d,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:i,apiCallsCount:o,apiStatusMix:l};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(c)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();},_testrelicFixture:Ye};test.test.extend(Ca);it(test.expect);var Ec={request:async({request:t},e,r)=>{let n=Br(r);if(!n.trackApiCalls){await e(t);return}let s=new de,a=new ue(t,s,n);a.intercept(),ce(s,a);let i=null;try{i=new V("api-console");}catch{}let o=0,l=process.stdout.write,d=process.stderr.write;process.stdout.write=function(c,...p){try{let u=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!u.startsWith("[testrelic]")&&!u.startsWith("\u2139 TestRelic")&&!u.startsWith("\u2713 TestRelic")&&!u.startsWith("\u26A0 TestRelic")&&i&&(i.append({level:"stdout",text:u.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),o++);}catch{}return l.apply(process.stdout,[c,...p])},process.stderr.write=function(c,...p){try{let u=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!u.startsWith("[testrelic]")&&!u.startsWith("\u26A0 TestRelic")&&i&&(i.append({level:"stderr",text:u.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),o++);}catch{}return d.apply(process.stderr,[c,...p])};try{await e(t);}finally{process.stdout.write=l,process.stderr.write=d,ce(null,null);}try{i?.close();let{apiCallsFile:c,apiCallsCount:p,apiStatusMix:u}=a.getFileData(),f=n.captureAssertions?s.getData():[],g={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:f,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:o>0?i?.getPath()??null:null,consoleLogsCount:o,apiCallsFile:c,apiCallsCount:p,apiStatusMix:u};await r.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(g)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();},_testrelicFixture:Ye};var Ta="@testrelic/playwright-analytics";function Nc(t){return Array.isArray(t)?t.some(e=>Array.isArray(e)&&typeof e[0]=="string"&&e[0]===Ta):false}function Dc(t,e){let n={video:"on",screenshot:"on",trace:"on",...t.use??{}},s;Array.isArray(t.reporter)?s=t.reporter:typeof t.reporter=="string"?s=[[t.reporter]]:s=[["list"]];let a=Nc(s)?s:[...s,[Ta,e??{}]];return test.defineConfig({...t,use:n,reporter:a})}var Sa=false;function gh(t,e,r="manual_record"){if(!t||!t.annotations){Sa||(Sa=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
|
|
4419
|
+
`));return}let n={url:e,navigationType:r,timestamp:new Date().toISOString()};t.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}Object.defineProperty(exports,"ATTACHMENT_CONTENT_TYPE",{enumerable:true,get:function(){return core.ATTACHMENT_CONTENT_TYPE}});Object.defineProperty(exports,"ATTACHMENT_NAME",{enumerable:true,get:function(){return core.ATTACHMENT_NAME}});Object.defineProperty(exports,"PAYLOAD_VERSION",{enumerable:true,get:function(){return core.PAYLOAD_VERSION}});Object.defineProperty(exports,"isTestRelicDataPayload",{enumerable:true,get:function(){return core.isTestRelicDataPayload}});exports.SCHEMA_VERSION=Ae;exports.default=st;exports.defineConfig=Dc;exports.recordNavigation=gh;exports.testRelicApiFixture=Ec;exports.testRelicFixture=Ca;//# sourceMappingURL=index.cjs.map
|
|
4420
4420
|
//# sourceMappingURL=index.cjs.map
|