@testrelic/playwright-analytics 2.2.4 → 2.2.6
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/README.md +107 -3
- package/dist/api-fixture.cjs +1 -1
- package/dist/api-fixture.cjs.map +1 -1
- package/dist/api-fixture.js +1 -1
- package/dist/api-fixture.js.map +1 -1
- package/dist/fixture.cjs +1 -1
- package/dist/fixture.cjs.map +1 -1
- package/dist/fixture.js +1 -1
- package/dist/fixture.js.map +1 -1
- package/dist/index.cjs +146 -45
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +31 -2
- package/dist/index.d.ts +31 -2
- package/dist/index.js +146 -45
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {randomUUID,createHash}from'crypto';import {mkdirSync,writeFileSync,renameSync,existsSync,readFileSync,copyFileSync,readdirSync,unlinkSync,statSync}from'fs';import {relative,dirname,join,extname,resolve,basename}from'path';import {PAYLOAD_VERSION,ATTACHMENT_NAME,ATTACHMENT_CONTENT_TYPE,isValidConfig,createError,ErrorCode,isTestRelicDataPayload,isValidEndpointUrl,isValidCloudConfig,isValidQueueEntry}from'@testrelic/core';export{ATTACHMENT_CONTENT_TYPE,ATTACHMENT_NAME,PAYLOAD_VERSION,isTestRelicDataPayload}from'@testrelic/core';import {exec,execSync}from'child_process';import {gzipSync}from'zlib';import {test}from'@playwright/test';import {performance}from'perf_hooks';var
|
|
2
|
-
`);if(t<1||t>
|
|
3
|
-
`)}catch{return null}}function
|
|
1
|
+
import {randomUUID,createHash}from'crypto';import {mkdirSync,writeFileSync,renameSync,existsSync,readFileSync,copyFileSync,readdirSync,unlinkSync,statSync}from'fs';import {relative,dirname,join,extname,resolve,basename}from'path';import {PAYLOAD_VERSION,ATTACHMENT_NAME,ATTACHMENT_CONTENT_TYPE,isValidConfig,createError,ErrorCode,isTestRelicDataPayload,isValidEndpointUrl,isValidCloudConfig,isValidQueueEntry}from'@testrelic/core';export{ATTACHMENT_CONTENT_TYPE,ATTACHMENT_NAME,PAYLOAD_VERSION,isTestRelicDataPayload}from'@testrelic/core';import {exec,execSync}from'child_process';import {gzipSync}from'zlib';import {test,defineConfig}from'@playwright/test';import {performance}from'perf_hooks';var Me=".testrelic",Pe=5,De=new Set(["__proto__","constructor","prototype"]),mt=Object.freeze({apiKey:null,endpoint:"https://api.testrelic.com/api/v1",uploadStrategy:"batch",timeout:3e4,projectName:null,queueMaxAge:6048e5,queueDirectory:".testrelic/queue"}),Oe={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function bt(e){let t=resolve(e);for(let r=0;r<=Pe;r++){let n=join(t,Me);if(existsSync(n))return n;let s=dirname(t);if(s===t)break;t=s;}return null}function vt(e){try{let t=readFileSync(e,"utf-8"),r=JSON.parse(t);return typeof r!="object"||r===null||Array.isArray(r)||!wt(r)?null:r}catch{return null}}function wt(e){for(let t of Object.keys(e)){if(De.has(t))return false;let r=e[t];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!wt(r))return false}return true}function xt(e){let t=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(e);if(t)return process.env[t[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(e);return r?process.env[r[1]]??null:e}function K(e){let t=Object.create(null);for(let r of Object.keys(e)){let n=e[r];typeof n=="string"&&n.startsWith("$")?t[r]=xt(n):typeof n=="object"&&n!==null&&!Array.isArray(n)?t[r]=K(n):t[r]=n;}return t}function yt(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let r=parseInt(t[1],10),n=t[2],s=Oe[n];return !s||r<=0?null:r*s}function kt(e,t){let r=Object.create(null);if(Object.assign(r,mt),e){let i=e.cloud;i&&typeof i=="object"&&(typeof i.endpoint=="string"&&(r.endpoint=i.endpoint),typeof i.upload=="string"&&(r.uploadStrategy=i.upload),typeof i.timeout=="number"&&(r.timeout=i.timeout),typeof i.apiKey=="string"&&i.apiKey.length>0&&(r.apiKey=i.apiKey));let c=e.project;c&&typeof c=="object"&&typeof c.name=="string"&&(r.projectName=c.name);let d=e.queue;if(d&&typeof d=="object"){if(typeof d.maxAge=="string"){let u=yt(d.maxAge);u!==null&&(r.queueMaxAge=u);}typeof d.directory=="string"&&(r.queueDirectory=d.directory);}}if(t){if(typeof t.apiKey=="string"&&t.apiKey.length>0){let i=t.apiKey.startsWith("$")?xt(t.apiKey):t.apiKey;i&&(r.apiKey=i);}if(typeof t.endpoint=="string"&&(r.endpoint=t.endpoint),typeof t.upload=="string"&&(r.uploadStrategy=t.upload),typeof t.timeout=="number"&&(r.timeout=t.timeout),typeof t.projectName=="string"&&(r.projectName=t.projectName),typeof t.queueMaxAge=="string"){let i=yt(t.queueMaxAge);i!==null&&(r.queueMaxAge=i);}typeof t.queueDirectory=="string"&&(r.queueDirectory=t.queueDirectory);}let n=process.env.TESTRELIC_API_KEY;n&&n.length>0&&(r.apiKey=n);let s=process.env.TESTRELIC_CLOUD_ENDPOINT;s&&isValidEndpointUrl(s)&&(r.endpoint=s);let a=process.env.TESTRELIC_UPLOAD_STRATEGY;a&&["batch","realtime","both"].includes(a)&&(r.uploadStrategy=a);let l=process.env.TESTRELIC_CLOUD_TIMEOUT;if(l){let i=parseInt(l,10);!isNaN(i)&&i>=1e3&&i<=12e4&&(r.timeout=i);}let o=Object.freeze(r);return isValidCloudConfig(o)?o:mt}var ze=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],je=["authorization","cookie","set-cookie","x-api-key"],$e=["password","secret","token","apiKey","api_key"];function Ct(e){let t=Object.create(null);return t.trackApiCalls=e?.trackApiCalls??true,t.captureRequestHeaders=e?.captureRequestHeaders??true,t.captureResponseHeaders=e?.captureResponseHeaders??true,t.captureRequestBody=e?.captureRequestBody??true,t.captureResponseBody=e?.captureResponseBody??true,t.captureAssertions=e?.captureAssertions??true,t.redactHeaders=e?.redactHeaders??[...je],t.redactBodyFields=e?.redactBodyFields??[...$e],t.apiIncludeUrls=e?.apiIncludeUrls??[],t.apiExcludeUrls=e?.apiExcludeUrls??[],Object.freeze(t)}function Tt(e){if(e!==void 0&&!isValidConfig(e))throw createError(ErrorCode.CONFIG_INVALID,"Invalid reporter configuration");let t=Object.create(null);t.outputPath=e?.outputPath??"./test-results/analytics-timeline.json",t.includeStackTrace=e?.includeStackTrace??false,t.includeCodeSnippets=e?.includeCodeSnippets??true,t.codeContextLines=e?.codeContextLines??3,t.includeNetworkStats=e?.includeNetworkStats??true,t.navigationTypes=e?.navigationTypes??null,t.redactPatterns=[...ze,...e?.redactPatterns??[]],t.testRunId=e?.testRunId??null,t.metadata=e?.metadata??null;let r=t.outputPath;t.openReport=e?.openReport??true,t.htmlReportPath=e?.htmlReportPath??r.replace(/\.json$/,".html"),t.includeArtifacts=e?.includeArtifacts??true,t.trackApiCalls=e?.trackApiCalls??true,t.quiet=e?.quiet??false,t.includeActionSteps=e?.includeActionSteps??true,t.captureConsoleLogs=e?.captureConsoleLogs??true;let n=bt(process.cwd()),s=n?vt(n):null,a=s?K(s):null,l=kt(a,e?.cloud);return t.cloud=l.apiKey?l:null,Object.freeze(t)}var W="1.3.0";function Rt(e,t,r){try{let s=readFileSync(e,"utf-8").split(`
|
|
2
|
+
`);if(t<1||t>s.length)return null;let a=Math.max(1,t-r),l=Math.min(s.length,t+r),o=[];for(let i=a;i<=l;i++){let c=i===t?">":" ",d=String(i).padStart(String(l).length," ");o.push(`${c} ${d} | ${s[i-1]}`);}return o.join(`
|
|
3
|
+
`)}catch{return null}}function St(e){return t=>{let r=t;for(let n of e)if(typeof n=="string"){let s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(s,"g"),"[REDACTED]");}else {let s=n.flags.includes("g")?n.flags:n.flags+"g",a=new RegExp(n.source,s);r=r.replace(a,"[REDACTED]");}return r}}function Ve(e){return e.GITHUB_ACTIONS!=="true"?null:{provider:"github-actions",buildId:e.GITHUB_RUN_ID??null,commitSha:e.GITHUB_SHA??null,branch:e.GITHUB_REF_NAME??null,runUrl:e.GITHUB_SERVER_URL&&e.GITHUB_REPOSITORY&&e.GITHUB_RUN_ID?`${e.GITHUB_SERVER_URL}/${e.GITHUB_REPOSITORY}/actions/runs/${e.GITHUB_RUN_ID}`:null}}function Je(e){return e.GITLAB_CI!=="true"?null:{provider:"gitlab-ci",buildId:e.CI_PIPELINE_ID??null,commitSha:e.CI_COMMIT_SHA??null,branch:e.CI_COMMIT_BRANCH??e.CI_COMMIT_REF_NAME??null,runUrl:e.CI_PIPELINE_URL??null}}function Ke(e){if(!e.JENKINS_URL)return null;let t=e.GIT_BRANCH??null;return t?.startsWith("origin/")&&(t=t.slice(7)),{provider:"jenkins",buildId:e.BUILD_ID??null,commitSha:e.GIT_COMMIT??null,branch:t,runUrl:e.BUILD_URL??null}}function We(e){return e.CIRCLECI!=="true"?null:{provider:"circleci",buildId:e.CIRCLE_BUILD_NUM??null,commitSha:e.CIRCLE_SHA1??null,branch:e.CIRCLE_BRANCH??null,runUrl:e.CIRCLE_BUILD_URL??null}}function Ye(e){if(!e.BITBUCKET_PIPELINE_UUID)return null;let t=e.BITBUCKET_WORKSPACE&&e.BITBUCKET_REPO_SLUG&&e.BITBUCKET_PIPELINE_UUID?`https://bitbucket.org/${e.BITBUCKET_WORKSPACE}/${e.BITBUCKET_REPO_SLUG}/pipelines/results/${e.BITBUCKET_PIPELINE_UUID}`:null;return {provider:"bitbucket-pipelines",buildId:e.BITBUCKET_BUILD_NUMBER??null,commitSha:e.BITBUCKET_COMMIT??null,branch:e.BITBUCKET_BRANCH??null,runUrl:t}}var Ze=[Ve,Je,Ke,We,Ye];function A(e){let t=process.env;for(let r of Ze){let n=r(t);if(n)return n}return null}var At=`
|
|
4
4
|
/* Theme Variables */
|
|
5
5
|
:root,[data-theme="dark"]{
|
|
6
6
|
--bg:#0f1117;--bg-1:#161b22;--bg-2:#1c2128;--bg-3:#21262d;--bg-code:#13111c;
|
|
@@ -461,6 +461,27 @@ body{
|
|
|
461
461
|
.action-step.seeking{animation:trSeekFlash .4s ease-out}
|
|
462
462
|
@keyframes trSeekFlash{0%{background:rgba(3,183,156,0.15)}100%{background:transparent}}
|
|
463
463
|
|
|
464
|
+
/* \u2500\u2500 Console/Logs Panel \u2500\u2500 */
|
|
465
|
+
.console-panel{border:1px solid var(--bd);border-radius:8px;overflow:hidden}
|
|
466
|
+
.console-header{font-size:11px;font-weight:700;color:var(--fg-1);text-transform:uppercase;letter-spacing:.06em;display:flex;align-items:center;gap:6px;padding:10px 12px 8px;border-bottom:1px solid var(--bd)}
|
|
467
|
+
.console-header svg{opacity:.6}
|
|
468
|
+
.console-count{font-weight:400;color:var(--fg-2);font-size:10px}
|
|
469
|
+
.console-error-count{color:#f87171;font-weight:500;font-size:10px;text-transform:none;letter-spacing:0}
|
|
470
|
+
.console-warn-count{color:#fbbf24;font-weight:500;font-size:10px;text-transform:none;letter-spacing:0}
|
|
471
|
+
.console-toolbar{display:flex;gap:4px;padding:6px 12px;border-bottom:1px solid var(--bd);flex-wrap:wrap}
|
|
472
|
+
.console-filter-btn{font-size:10px;padding:2px 8px;border-radius:4px;border:1px solid var(--bd);background:transparent;color:var(--fg-2);cursor:pointer;transition:all .15s;font-family:inherit}
|
|
473
|
+
.console-filter-btn.active{background:var(--bg-3);color:var(--fg-1);border-color:var(--fg-2)}
|
|
474
|
+
.console-filter-btn:hover{background:var(--hvr)}
|
|
475
|
+
.console-list{max-height:400px;overflow-y:auto;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px}
|
|
476
|
+
.console-entry{display:flex;align-items:baseline;gap:8px;padding:3px 12px;border-bottom:1px solid color-mix(in srgb,var(--bd) 50%,transparent)}
|
|
477
|
+
.console-entry:hover{background:var(--hvr)}
|
|
478
|
+
.console-level-badge{font-weight:600;font-size:9px;min-width:32px;text-transform:uppercase;letter-spacing:.03em}
|
|
479
|
+
.console-time{color:var(--fg-2);font-size:10px;white-space:nowrap;min-width:65px}
|
|
480
|
+
.console-text{flex:1;word-break:break-word;white-space:pre-wrap;color:var(--fg)}
|
|
481
|
+
.console-loc{color:var(--fg-2);font-size:10px;white-space:nowrap;margin-left:auto;max-width:180px;overflow:hidden;text-overflow:ellipsis}
|
|
482
|
+
.console-level-error,.console-level-stderr{background:rgba(248,113,113,0.06)}
|
|
483
|
+
.console-level-warn{background:rgba(251,191,36,0.06)}
|
|
484
|
+
|
|
464
485
|
/* \u2500\u2500 Lightbox \u2500\u2500 */
|
|
465
486
|
.lightbox-overlay{position:fixed;inset:0;background:var(--lb-bg);z-index:1000;display:flex;align-items:center;justify-content:center;cursor:zoom-out;animation:trFadeIn .15s}
|
|
466
487
|
.lightbox-overlay img{max-width:92vw;max-height:92vh;border-radius:8px;box-shadow:0 8px 40px var(--lb-shadow)}
|
|
@@ -500,15 +521,15 @@ body{
|
|
|
500
521
|
print-color-adjust:exact;-webkit-print-color-adjust:exact;
|
|
501
522
|
}
|
|
502
523
|
}
|
|
503
|
-
`;var
|
|
524
|
+
`;var It=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 196 247" fill="none">
|
|
504
525
|
<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)"/>
|
|
505
526
|
<defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
|
|
506
527
|
<stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
|
|
507
|
-
</linearGradient></defs></svg>`,
|
|
528
|
+
</linearGradient></defs></svg>`,_t=`<svg width="32" height="40" viewBox="0 0 196 247" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
508
529
|
<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)"/>
|
|
509
530
|
<defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
|
|
510
531
|
<stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
|
|
511
|
-
</linearGradient></defs></svg>`;var
|
|
532
|
+
</linearGradient></defs></svg>`;var Lt=`
|
|
512
533
|
/* \u2500\u2500 Utilities \u2500\u2500 */
|
|
513
534
|
function esc(s){if(!s)return '';return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,''')}
|
|
514
535
|
function stripAnsi(s){return s?s.replace(/\\u001b\\[[0-9;]*m/g,'').replace(/\\x1b\\[[0-9;]*m/g,''):''}
|
|
@@ -530,7 +551,7 @@ body{
|
|
|
530
551
|
tags:t.tags,failure:t.failure,filePath:t.filePath,suiteName:t.suiteName,
|
|
531
552
|
testType:t.testType,isFlaky:t.isFlaky,retryStatus:t.retryStatus,
|
|
532
553
|
expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,
|
|
533
|
-
artifacts:t.artifacts,networkRequests:t.networkRequests||[],steps:[],apiCalls:[],actions:t.actions||[]
|
|
554
|
+
artifacts:t.artifacts,networkRequests:t.networkRequests||[],steps:[],apiCalls:[],actions:t.actions||[],consoleLogs:t.consoleLogs||[]
|
|
534
555
|
};
|
|
535
556
|
}
|
|
536
557
|
if(entry.type==='api_call'){
|
|
@@ -542,7 +563,7 @@ body{
|
|
|
542
563
|
}else{
|
|
543
564
|
testMap[t.testId].steps.push({
|
|
544
565
|
url:entry.url,navigationType:entry.navigationType,
|
|
545
|
-
visitedAt:entry.visitedAt,duration:entry.duration,specFile:entry.specFile,
|
|
566
|
+
visitedAt:entry.visitedAt||entry.timestamp,duration:entry.duration||entry.durationOnUrl||0,specFile:entry.specFile,
|
|
546
567
|
domContentLoadedAt:entry.domContentLoadedAt,networkIdleAt:entry.networkIdleAt,
|
|
547
568
|
networkStats:entry.networkStats
|
|
548
569
|
});
|
|
@@ -684,12 +705,14 @@ body{
|
|
|
684
705
|
var hasSteps=t.steps&&t.steps.length>0;
|
|
685
706
|
var hasApiCalls=t.apiCalls&&t.apiCalls.length>0;
|
|
686
707
|
var hasActions=t.actions&&t.actions.length>0;
|
|
708
|
+
var hasConsoleLogs=t.consoleLogs&&t.consoleLogs.length>0;
|
|
687
709
|
var hasVideo=!!(t.artifacts&&t.artifacts.video);
|
|
688
|
-
if(hasArt||hasSteps||hasApiCalls||hasActions){
|
|
710
|
+
if(hasArt||hasSteps||hasApiCalls||hasActions||hasConsoleLogs){
|
|
689
711
|
h+='<div class="drawer-sections">';
|
|
690
712
|
if(hasArt)h+='<div class="drawer-section">'+renderArtifactColumn(t.artifacts)+'</div>';
|
|
691
713
|
if(hasActions)h+='<div class="drawer-section">'+renderActionsColumn(t.actions,hasVideo)+'</div>';
|
|
692
|
-
if(hasSteps)h+='<div class="drawer-section">'+renderTimelineColumn(t.steps,t.networkRequests)+'</div>';
|
|
714
|
+
if(hasSteps)h+='<div class="drawer-section">'+renderTimelineColumn(t.steps,t.networkRequests,t.consoleLogs,t.testType)+'</div>';
|
|
715
|
+
if(!hasSteps&&hasConsoleLogs)h+='<div class="drawer-section">'+renderConsoleColumn(t.consoleLogs,t.testType)+'</div>';
|
|
693
716
|
if(hasApiCalls)h+='<div class="drawer-section">'+renderApiCallsColumn(t.apiCalls)+'</div>';
|
|
694
717
|
h+='</div>';
|
|
695
718
|
}
|
|
@@ -891,14 +914,17 @@ body{
|
|
|
891
914
|
h+='</div></div>';return h;
|
|
892
915
|
}
|
|
893
916
|
|
|
894
|
-
function renderTimelineColumn(steps,networkRequests){
|
|
917
|
+
function renderTimelineColumn(steps,networkRequests,consoleLogs,testType){
|
|
895
918
|
if(!steps||steps.length===0)return '<div class="artifact-empty">No navigation data</div>';
|
|
896
919
|
var hasReqs=networkRequests&&networkRequests.length>0;
|
|
920
|
+
var hasCLogs=consoleLogs&&consoleLogs.length>0;
|
|
897
921
|
var h='<div class="seg-ctrl" data-seg-group="right-panel">';
|
|
898
922
|
h+='<button class="seg-btn active" data-seg="timeline"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg>Timeline ('+steps.length+')</button>';
|
|
923
|
+
if(hasCLogs)h+='<button class="seg-btn" data-seg="console"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/></svg>Console ('+consoleLogs.length+')</button>';
|
|
899
924
|
h+='<button class="seg-btn" data-seg="network"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>Network'+(hasReqs?' ('+networkRequests.length+')':'')+'</button>';
|
|
900
925
|
h+='</div>';
|
|
901
926
|
h+='<div class="seg-pane active" data-seg-pane="timeline">'+renderNavTimeline(steps)+'</div>';
|
|
927
|
+
if(hasCLogs)h+='<div class="seg-pane" data-seg-pane="console">'+renderConsoleColumn(consoleLogs,testType)+'</div>';
|
|
902
928
|
h+='<div class="seg-pane" data-seg-pane="network">'+renderNetworkDevTools(networkRequests)+'</div>';
|
|
903
929
|
return h;
|
|
904
930
|
}
|
|
@@ -1188,7 +1214,7 @@ function _updateCard(cls,val){
|
|
|
1188
1214
|
var el=document.querySelector('.'+cls+' .s-count');
|
|
1189
1215
|
if(el)el.textContent=''+val;
|
|
1190
1216
|
}
|
|
1191
|
-
`;var
|
|
1217
|
+
`;var qt=`
|
|
1192
1218
|
/* \u2500\u2500 Event Delegation \u2500\u2500 */
|
|
1193
1219
|
document.addEventListener('click',function(e){
|
|
1194
1220
|
var target=e.target;
|
|
@@ -1288,6 +1314,27 @@ function _updateCard(cls,val){
|
|
|
1288
1314
|
return;
|
|
1289
1315
|
}
|
|
1290
1316
|
|
|
1317
|
+
/* Console log level filter */
|
|
1318
|
+
var consoleFilterBtn=target.closest('.console-filter-btn');
|
|
1319
|
+
if(consoleFilterBtn){
|
|
1320
|
+
var toolbar=consoleFilterBtn.closest('.console-toolbar');
|
|
1321
|
+
if(toolbar){
|
|
1322
|
+
var btns=toolbar.querySelectorAll('.console-filter-btn');
|
|
1323
|
+
for(var bi=0;bi<btns.length;bi++)btns[bi].classList.remove('active');
|
|
1324
|
+
consoleFilterBtn.classList.add('active');
|
|
1325
|
+
var filterLevel=consoleFilterBtn.getAttribute('data-console-filter');
|
|
1326
|
+
var list=consoleFilterBtn.closest('.console-panel').querySelector('.console-list');
|
|
1327
|
+
if(list){
|
|
1328
|
+
var entries=list.querySelectorAll('.console-entry');
|
|
1329
|
+
for(var ei=0;ei<entries.length;ei++){
|
|
1330
|
+
if(filterLevel==='all'){entries[ei].style.display='';}
|
|
1331
|
+
else{entries[ei].style.display=entries[ei].getAttribute('data-console-level')===filterLevel?'':'none';}
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
return;
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1291
1338
|
/* Action step click \u2192 seek video + highlight */
|
|
1292
1339
|
var actionStep=target.closest('.action-step.seekable');
|
|
1293
1340
|
if(actionStep){
|
|
@@ -1415,7 +1462,7 @@ function _updateCard(cls,val){
|
|
|
1415
1462
|
var d=document.getElementById('filter-drawer');if(d)d.classList.remove('open');
|
|
1416
1463
|
var b=document.getElementById('filter-drawer-backdrop');if(b)b.classList.remove('open');
|
|
1417
1464
|
}
|
|
1418
|
-
`;var
|
|
1465
|
+
`;var Bt=`
|
|
1419
1466
|
/* \u2500\u2500 Category badge helpers \u2500\u2500 */
|
|
1420
1467
|
function actionBadgeClass(cat){
|
|
1421
1468
|
if(cat==='assertion')return 'action-badge-assertion';
|
|
@@ -1461,14 +1508,61 @@ function _updateCard(cls,val){
|
|
|
1461
1508
|
h+='</div>';
|
|
1462
1509
|
return h;
|
|
1463
1510
|
}
|
|
1464
|
-
`;var
|
|
1511
|
+
`;var Mt=`
|
|
1512
|
+
/* \u2500\u2500 Console Log Level Colors & Labels \u2500\u2500 */
|
|
1513
|
+
var LOG_COLORS={log:'#9ca3af',warn:'#fbbf24',error:'#f87171',info:'#60a5fa',debug:'#a78bfa',stdout:'#9ca3af',stderr:'#f87171'};
|
|
1514
|
+
var LOG_LABELS={log:'LOG',warn:'WARN',error:'ERR',info:'INFO',debug:'DBG',stdout:'OUT',stderr:'ERR'};
|
|
1515
|
+
|
|
1516
|
+
function renderConsoleLogEntry(entry){
|
|
1517
|
+
var h='<div class="console-entry console-level-'+esc(entry.level)+'" data-console-level="'+esc(entry.level)+'">';
|
|
1518
|
+
h+='<span class="console-level-badge" style="color:'+LOG_COLORS[entry.level]+'">'+LOG_LABELS[entry.level]+'</span>';
|
|
1519
|
+
h+='<span class="console-time">'+fmtDate(entry.timestamp).split(', ').pop()+'</span>';
|
|
1520
|
+
h+='<span class="console-text">'+esc(stripAnsi(entry.text))+'</span>';
|
|
1521
|
+
if(entry.location){var short=entry.location.split('/').pop()||entry.location;h+='<span class="console-loc" title="'+esc(entry.location)+'">'+esc(short)+'</span>';}
|
|
1522
|
+
h+='</div>';
|
|
1523
|
+
return h;
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1526
|
+
function renderConsoleColumn(logs,testType){
|
|
1527
|
+
if(!logs||logs.length===0)return '';
|
|
1528
|
+
var isApi=testType==='api';
|
|
1529
|
+
var label=isApi?'Terminal Logs':'Console';
|
|
1530
|
+
|
|
1531
|
+
var counts={};
|
|
1532
|
+
for(var i=0;i<logs.length;i++){var l=logs[i].level;counts[l]=(counts[l]||0)+1;}
|
|
1533
|
+
|
|
1534
|
+
var h='<div class="console-panel">';
|
|
1535
|
+
h+='<div class="console-header">';
|
|
1536
|
+
h+='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/></svg>';
|
|
1537
|
+
h+=' '+label+' <span class="console-count">'+logs.length+'</span>';
|
|
1538
|
+
if(counts.error||counts.stderr){var ec=(counts.error||0)+(counts.stderr||0);h+=' <span class="console-error-count">'+ec+' error'+(ec>1?'s':'')+'</span>';}
|
|
1539
|
+
if(counts.warn)h+=' <span class="console-warn-count">'+counts.warn+' warning'+(counts.warn>1?'s':'')+'</span>';
|
|
1540
|
+
h+='</div>';
|
|
1541
|
+
|
|
1542
|
+
h+='<div class="console-toolbar">';
|
|
1543
|
+
h+='<button class="console-filter-btn active" data-console-filter="all">All</button>';
|
|
1544
|
+
var levels=isApi?['stdout','stderr']:['log','info','warn','error','debug'];
|
|
1545
|
+
for(var li=0;li<levels.length;li++){
|
|
1546
|
+
var lv=levels[li];
|
|
1547
|
+
if(counts[lv])h+='<button class="console-filter-btn" data-console-filter="'+lv+'">'+LOG_LABELS[lv]+' <span style="opacity:.6">'+counts[lv]+'</span></button>';
|
|
1548
|
+
}
|
|
1549
|
+
h+='</div>';
|
|
1550
|
+
|
|
1551
|
+
h+='<div class="console-list">';
|
|
1552
|
+
for(var i=0;i<logs.length;i++){h+=renderConsoleLogEntry(logs[i]);}
|
|
1553
|
+
h+='</div>';
|
|
1554
|
+
h+='</div>';
|
|
1555
|
+
return h;
|
|
1556
|
+
}
|
|
1557
|
+
`;var Qe=`
|
|
1465
1558
|
(function(){
|
|
1466
1559
|
var data=JSON.parse(document.getElementById('report-data').textContent);
|
|
1467
|
-
${
|
|
1468
|
-
${
|
|
1560
|
+
${Lt}
|
|
1561
|
+
${Bt}
|
|
1562
|
+
${Mt}
|
|
1469
1563
|
${Nt}
|
|
1470
1564
|
${Et}
|
|
1471
|
-
${
|
|
1565
|
+
${qt}
|
|
1472
1566
|
applyTheme();
|
|
1473
1567
|
renderRunMeta();
|
|
1474
1568
|
renderSummary();
|
|
@@ -1483,15 +1577,15 @@ function _updateCard(cls,val){
|
|
|
1483
1577
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
1484
1578
|
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: blob: 'self'; media-src blob: 'self';">
|
|
1485
1579
|
<title>TestRelic AI Analytics Report</title>
|
|
1486
|
-
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(
|
|
1487
|
-
<style>${
|
|
1580
|
+
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(It).toString("base64")}">
|
|
1581
|
+
<style>${At}</style>
|
|
1488
1582
|
<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>
|
|
1489
1583
|
</head>
|
|
1490
1584
|
<body>
|
|
1491
1585
|
<div class="wrap">
|
|
1492
1586
|
<div class="top-bar">
|
|
1493
1587
|
<div class="brand">
|
|
1494
|
-
${
|
|
1588
|
+
${_t}
|
|
1495
1589
|
<div class="brand-text">
|
|
1496
1590
|
<span class="brand-title">TestRelic AI</span>
|
|
1497
1591
|
<span class="brand-sub">Analytics Report</span>
|
|
@@ -1526,37 +1620,44 @@ function _updateCard(cls,val){
|
|
|
1526
1620
|
<div class="filter-drawer-body" id="filter-drawer-body"></div>
|
|
1527
1621
|
</aside>
|
|
1528
1622
|
<script id="report-data" type="application/json">${t}</script>
|
|
1529
|
-
<script>${
|
|
1623
|
+
<script>${Qe}</script>
|
|
1530
1624
|
</body>
|
|
1531
|
-
</html>`}function
|
|
1532
|
-
`);});}catch{}}function
|
|
1533
|
-
`);}}function
|
|
1534
|
-
`}function
|
|
1535
|
-
`,
|
|
1536
|
-
`,l=T(""),
|
|
1537
|
-
`,process.stderr.write(
|
|
1538
|
-
`)[0]?.trim();return n?
|
|
1625
|
+
</html>`}function Dt(e){try{let t=process.platform,r;t==="darwin"?r=`open "${e}"`:t==="win32"?r=`start "" "${e}"`:r=`xdg-open "${e}"`,exec(r,n=>{n&&process.stderr.write(`[testrelic] Failed to open browser: ${n.message}
|
|
1626
|
+
`);});}catch{}}function ar(e){let t=JSON.stringify(e);return Pt(t)}function Ot(e,t){try{let r=ar(e),n=t.htmlReportPath,s=dirname(n);mkdirSync(s,{recursive:!0});let a=n+".tmp";if(writeFileSync(a,r,"utf-8"),renameSync(a,n),t.openReport&&e.ci===null){let l=resolve(n);Dt(l);}}catch(r){process.stderr.write(`[testrelic] Failed to write HTML report: ${r instanceof Error?r.message:String(r)}
|
|
1627
|
+
`);}}function ir(e){let t=e.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return t.length>100&&(t=t.substring(0,100).replace(/-+$/,"")),t||"unnamed-test"}function zt(e,t,r,n){let s=e.find(c=>c.name==="screenshot"&&c.path),a=e.find(c=>c.name==="video"&&c.path);if(!s&&!a)return null;let l=ir(t);r>0&&(l+=`--retry-${r}`);let o=join(n,"artifacts",l),i={};try{mkdirSync(o,{recursive:!0});}catch{return null}if(s?.path)try{if(existsSync(s.path)){let d=`screenshot${extname(s.path)||".png"}`;copyFileSync(s.path,join(o,d)),i.screenshot=`artifacts/${l}/${d}`;}}catch{}if(a?.path)try{if(existsSync(a.path)){let d=`video${extname(a.path)||".webm"}`;copyFileSync(a.path,join(o,d)),i.video=`artifacts/${l}/${d}`;}}catch{}return !i.screenshot&&!i.video?null:i}function Gt(e,t){let r=[];for(let n of e){let s=lr(n),a=dr(n),l=cr(n,s,a,t),o=pr(n,s,a);if(l.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(...l,...o);}return r.sort(ur),gr(r,e),r.map((n,s)=>n.type==="navigation"?{...{index:s,type:"navigation",url:n.url,timestamp:n.timestamp,durationOnUrl:n.durationOnUrl??0,navigationType:n.navigationType,domContentLoadedAt:n.domContentLoadedAt??null,networkIdleAt:n.networkIdleAt??null,networkStats:n.networkStats??null,specFile:n.specFile,test:n.test},tests:n.tests}:{...{index:s,type:"api_call",callId:n.callId,method:n.method,url:n.url,timestamp:n.timestamp,responseTime:n.responseTime??null,request:n.request,response:n.response??null,...n.error?{error:n.error}:{},assertions:n.assertions??[],specFile:n.specFile,test:n.test},tests:n.tests})}function lr(e){return {title:e.title,fullTitle:e.titlePath,status:e.status,duration:e.duration,retries:e.retryCount,retry:e.retry,tags:e.tags,failure:e.failure}}function dr(e){return {title:e.title,status:e.status,duration:e.duration,startedAt:e.startedAt,completedAt:e.completedAt,retryCount:e.retryCount,tags:e.tags,failure:e.failure,testId:e.testId,filePath:e.filePath,suiteName:e.suiteName,testType:e.testType,isFlaky:e.isFlaky,retryStatus:e.retryStatus,expectedStatus:e.expectedStatus,actualStatus:e.actualStatus,artifacts:e.artifacts,networkRequests:e.networkRequests,apiCalls:e.apiCalls,apiAssertions:e.apiAssertions,actions:e.actions,consoleLogs:e.consoleLogs}}function cr(e,t,r,n){let s=[];for(let a of e.navigations)n.navigationTypes!==null&&!n.navigationTypes.includes(a.navigationType)||s.push({type:"navigation",url:a.url,timestamp:a.timestamp,durationOnUrl:0,navigationType:a.navigationType,domContentLoadedAt:a.domContentLoadedAt??null,networkIdleAt:a.networkIdleAt??null,networkStats:a.networkStats??null,specFile:e.specFile,test:t,tests:[r],_testTitle:e.title});return s}function pr(e,t,r){if(!e.apiCalls||e.apiCalls.length===0)return [];let n=e.apiAssertions??[];return e.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}:{}})),l=null;return s.responseStatusCode!==null&&s.responseStatusText!==null&&(l={statusCode:s.responseStatusCode,statusText:s.responseStatusText,headers:s.responseHeaders,body:$t(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:$t(s.requestBody)},response:l,...s.error?{error:s.error}:{},assertions:a,specFile:e.specFile,test:t,tests:[r],_testTitle:e.title}})}function ur(e,t){let r=new Date(e.timestamp).getTime(),n=new Date(t.timestamp).getTime();if(r!==n)return r-n;let s={navigation:0,api_call:1},a=s[e.type],l=s[t.type];return a!==l?a-l:e.type==="api_call"&&t.type==="api_call"&&e.callId&&t.callId?jt(e.callId)-jt(t.callId):0}function jt(e){let t=e.match(/(\d+)$/);return t?parseInt(t[1],10):0}function gr(e,t){for(let r=0;r<e.length;r++){let n=e[r];if(n.type!=="navigation")continue;let s=new Date(n.timestamp).getTime(),a=null;for(let l=r+1;l<e.length;l++)if(e[l]._testTitle===n._testTitle){a=new Date(e[l].timestamp).getTime();break}if(a!==null)n.durationOnUrl=Math.max(0,a-s);else {let l=t.find(o=>o.title===n._testTitle);if(l){let o=new Date(l.completedAt).getTime();n.durationOnUrl=Math.max(0,o-s);}}}}function $t(e){if(e==null)return null;try{return JSON.parse(e)}catch{return e}}function Z(e,t){let r=e.length,n=Math.min(Math.ceil(t/100*r)-1,r-1);return e[Math.max(0,n)]}function fr(e){try{let t=new URL(e);return t.origin+t.pathname}catch{return e}}function hr(e){return e==null?"error":e>=200&&e<300?"2xx":e>=300&&e<400?"3xx":e>=400&&e<500?"4xx":e>=500&&e<600?"5xx":"error"}function Vt(e,t){let r=0,n=0,s=0,a=0,l=0;for(let h of e)switch(h.status){case "passed":r++;break;case "failed":n++;break;case "flaky":s++;break;case "skipped":a++;break;case "timedout":l++;break}let o=[];for(let h of e)h.apiCalls&&o.push(...h.apiCalls);let i=o.length,c=new Set,d={},u={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},g=[];for(let h of o)c.add(fr(h.url)),d[h.method]=(d[h.method]??0)+1,u[hr(h.responseStatusCode)]+=1,g.push(h.responseTimeMs);let p=null;if(g.length>0){let h=[...g].sort((E,q)=>E-q),k=h.reduce((E,q)=>E+q,0);p={avg:Math.round(k/h.length),min:h[0],max:h[h.length-1],p50:Z(h,50),p95:Z(h,95),p99:Z(h,99)};}let m=0,f=0,v=0;for(let h of e)if(h.apiAssertions)for(let k of h.apiAssertions)m++,k.status==="passed"?f++:v++;let y=0,b=new Set;for(let h of e){y+=h.navigations.length;for(let k of h.navigations)b.add(k.url);}let w=0,x={};function S(h){for(let k of h)w++,x[k.category]=(x[k.category]??0)+1,k.children.length>0&&S(k.children);}for(let h of e)h.actions&&S(h.actions);return {total:e.length,passed:r,failed:n,flaky:s,skipped:a,timedout:l,totalApiCalls:i,uniqueApiUrls:c.size,apiCallsByMethod:d,apiCallsByStatusRange:u,apiResponseTime:p,totalAssertions:m,passedAssertions:f,failedAssertions:v,totalNavigations:y,uniqueNavigationUrls:b.size,totalTimelineSteps:t,totalActionSteps:w,actionStepsByCategory:x}}function mr(e){let t=56-e.length;return t>0?e+" ".repeat(t):e}function T(e){return `\u2502 ${mr(e)} \u2502
|
|
1628
|
+
`}function Jt(e,t,r,n){if(n||e.total===0)return;let s=`\u250C${"\u2500".repeat(58)}\u2510
|
|
1629
|
+
`,a=`\u2514${"\u2500".repeat(58)}\u2518
|
|
1630
|
+
`,l=T(""),o=s;o+=T("TestRelic AI - Playwright Test Report"),o+=l;let i=[];if(e.passed>0&&i.push(`${e.passed} \u2713`),e.failed>0&&i.push(`${e.failed} \u2717`),e.flaky>0&&i.push(`${e.flaky} \u26A0`),e.skipped>0&&i.push(`${e.skipped} skipped`),e.timedout>0&&i.push(`${e.timedout} timedout`),o+=T(`Tests: ${e.total} total (${i.join(" ")})`),e.totalNavigations>0&&(o+=T(`Navigations: ${e.totalNavigations} visits across ${e.uniqueNavigationUrls} unique URLs`)),e.totalApiCalls>0){o+=T(`API Calls: ${e.totalApiCalls} calls across ${e.uniqueApiUrls} unique endpoints`);let c=Object.entries(e.apiCallsByMethod).filter(([,u])=>u>0).map(([u,g])=>`${u}: ${g}`);c.length>0&&(o+=T(` ${c.join(" ")}`));let d=Object.entries(e.apiCallsByStatusRange).filter(([,u])=>u>0).map(([u,g])=>`${u}: ${g}`);d.length>0&&(o+=T(` ${d.join(" ")}`)),e.apiResponseTime&&(o+=T(` Avg response: ${e.apiResponseTime.avg}ms P95: ${e.apiResponseTime.p95}ms`));}if(e.totalAssertions>0&&(o+=T(`Assertions: ${e.totalAssertions} total (${e.passedAssertions} \u2713 ${e.failedAssertions} \u2717)`)),e.totalActionSteps>0){let c=[],d=e.actionStepsByCategory;d.ui_action&&c.push(`${d.ui_action} UI`),d.assertion&&c.push(`${d.assertion} assertions`),d.custom_step&&c.push(`${d.custom_step} custom`);let u=c.length>0?` (${c.join(" ")})`:"";o+=T(`Actions: ${e.totalActionSteps} steps${u}`);}o+=T(`Report: ${r}`),o+=T(`Data: ${t}`),o+=a,o+=`For more information visit us at https://docs.testrelic.ai
|
|
1631
|
+
`,process.stderr.write(o);}var yr=new Set(["pw:api","expect","test.step"]);function br(e){return e==="expect"?"assertion":e==="test.step"?"custom_step":"ui_action"}function Q(e,t,r){if(yr.has(e.category)){let n=[];for(let a of e.steps)Q(a,t,n);let s=e.startTime.getTime()-t.getTime();r.push({title:e.title,category:br(e.category),timestamp:e.startTime.toISOString(),duration:e.duration,videoOffset:s>=0?s/1e3:null,status:e.error?"failed":"passed",error:e.error?.message??null,children:n});}else for(let n of e.steps)Q(n,t,r);}function Kt(e,t){let r=[];for(let n of e)Q(n,t,r);return r}var xr=new Set(["localhost","127.0.0.1","0.0.0.0"]);function Yt(e){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&xr.has(t.hostname)))throw createError(ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${t.protocol}//${t.hostname}`)}var kr=3e3;async function X(e){let t=new AbortController,r=setTimeout(()=>t.abort(),kr);try{return (await fetch(`${e}/health`,{method:"GET",signal:t.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function Zt(e){return new Promise(t=>setTimeout(t,e))}async function Wt(e){try{let r=(await e.json()).error;if(r&&typeof r.message=="string"){let n=r.details;if(Array.isArray(n)&&n.length>0){let s=n.map(a=>`${a.field}: ${a.message}`).join(", ");return `${r.message} (${s})`}return r.message}}catch{}return `HTTP ${e.status}`}async function tt(e,t,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:n.signal});if(a.ok){let 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"),i=o?parseInt(o,10)*1e3:5e3;if(!isNaN(i)&&i>0){await Zt(i);let c=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:n.signal});if(c.ok){let d=await c.json();return {accessToken:d.accessToken,refreshToken:d.refreshToken,expiresIn:d.expiresIn,orgId:d.orgId,orgName:d.orgName,userId:d.userId,userName:d.userName}}}return {code:"rate_limited",message:"Rate limited during token exchange.",statusCode:429}}return a.status===400?{code:"validation_error",message:await Wt(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 Wt(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 et(e){return "code"in e&&typeof e.code=="string"&&["invalid_key","expired_key","validation_error","rate_limited","server_error","network_error","timeout"].includes(e.code)}async function Qt(e,t,r){let n=new AbortController,s=setTimeout(()=>n.abort(),r);try{let a=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:n.signal});if(a.status===429){let o=a.headers.get("Retry-After"),i=o?parseInt(o,10)*1e3:5e3;!isNaN(i)&&i>0&&(await Zt(i),a=await fetch(`${e}/sdk/auth/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refreshToken:t}),signal:n.signal}));}if(!a.ok)return null;let l=await a.json();return {accessToken:l.accessToken,refreshToken:l.refreshToken,expiresIn:l.expiresIn}}catch{return null}finally{clearTimeout(s);}}async function Xt(e,t,r,n,s,a){let l=new AbortController,o=setTimeout(()=>l.abort(),s);try{let i={gitId:r,displayName:n};a&&(i.branch=a);let c=await fetch(`${e}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(i),signal:l.signal});if(!c.ok)return null;let d=await c.json();return {repoId:d.repoId,displayName:d.displayName}}catch{return null}finally{clearTimeout(o);}}var Ar=5e3;function I(e,t){try{return execSync(e,{cwd:t,timeout:Ar,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function te(e){let t=I("git rev-parse --abbrev-ref HEAD",e),r=I("git rev-parse --short HEAD",e),n=I("git log -1 --pretty=%s",e),s=Ir(e),a=s?P(s):null;return {branch:t,commitSha:r,commitMessage:n,remoteUrl:a}}function Ir(e){let t=I("git remote get-url origin",e);if(t)return t;let r=I("git remote",e);if(!r)return null;let n=r.split(`
|
|
1632
|
+
`)[0]?.trim();return n?I(`git remote get-url ${n}`,e):null}function P(e){let t=e.trim();return t=t.replace(/^[a-z+]+:\/\//,""),t=t.replace(/^[^@]+@/,""),t=t.replace(/:(?!\d)/,"/"),t=t.replace(/\.git$/,""),t=t.replace(/\/+$/,""),t=t.replace(/^[^@/]+@/,""),t.toLowerCase()}function ee(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function rt(e){try{let t=readFileSync(join(e,"package.json"),"utf-8"),r=JSON.parse(t);return typeof r.name=="string"&&r.name.length>0?r.name:null}catch{return null}}function D(e){let t=rt(e);return t||`local/${basename(e)}`}var Br="1.0.0",re=10;function st(e,t,r,n,s,a,l,o){try{mkdirSync(e,{recursive:!0});let i=Date.now(),c=`${i}-${t}-${r}.json`,d=join(e,c),u={version:Br,queuedAt:new Date(i).toISOString(),reason:n,retryCount:0,targetEndpoint:s,method:a,payload:l,headers:o},g=d+".tmp";writeFileSync(g,JSON.stringify(u,null,2),"utf-8"),renameSync(g,d);}catch(i){i.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
|
|
1539
1633
|
`):process.stderr.write(`\u26A0 TestRelic: Unable to queue upload data.
|
|
1540
|
-
`);}}async function
|
|
1541
|
-
`),unlinkSync(
|
|
1542
|
-
`);return}try{if(
|
|
1634
|
+
`);}}async function ae(e,t,r){let n;try{n=readdirSync(e).filter(a=>a.endsWith(".json")&&!a.endsWith(".tmp")).sort();}catch{return}if(n.length===0)return;let s=[];for(let a=0;a<n.length;a+=re)s.push(n.slice(a,a+re));for(let a of s)for(let l of a){let o=join(e,l);try{if(!statSync(o).isFile())continue;let c=readFileSync(o,"utf-8"),d=JSON.parse(c);if(!isValidQueueEntry(d)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${l}
|
|
1635
|
+
`),unlinkSync(o);continue}let u=d;if((await fetch(u.targetEndpoint,{method:u.method,headers:{...u.headers,Authorization:`Bearer ${r}`},body:JSON.stringify(u.payload)})).ok)unlinkSync(o);else return}catch{return}}}function oe(e,t){try{let r=readdirSync(e).filter(s=>s.endsWith(".json")&&!s.endsWith(".tmp")),n=Date.now();for(let s of r){let a=join(e,s);try{let l=readFileSync(a,"utf-8"),i=JSON.parse(l).queuedAt;if(typeof i=="string"){let c=new Date(i).getTime();n-c>t&&unlinkSync(a);}}catch{try{unlinkSync(a);}catch{}}}}catch{}}var Ur=3e5,zr=864e5,jr=6e4,ie=3e4,ot="https://app.testrelic.com/settings/api-keys",F=class{constructor(t){this.gitMetadata=null;this.repoId=null;this.failureReason=null;this.flushPromise=null;this.healthCheckTimer=null;this.config=t,this.authState={mode:"pending",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null};}async initialize(){if(!this.config||!this.config.apiKey){this.setLocalMode("no_api_key"),process.stderr.write(`\u2139 TestRelic: No API key configured. Running in local mode.
|
|
1636
|
+
`);return}try{if(Yt(this.config.endpoint),this.gitMetadata=te(),!await X(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.
|
|
1543
1637
|
`);return}let r=await tt(this.config.endpoint,this.config.apiKey,this.config.timeout);if(et(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})
|
|
1544
|
-
`),await this.
|
|
1545
|
-
`);}}getMode(){return this.authState.mode}isCloudMode(){return this.authState.mode==="cloud"}isLocalMode(){return this.authState.mode==="local"}getAccessToken(){return this.authState.accessToken}
|
|
1546
|
-
`));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,new Promise(t=>setTimeout(t,
|
|
1547
|
-
\u2192 Manage keys: ${
|
|
1638
|
+
`),await this.resolveRepoId(),this.config.queueDirectory&&(oe(this.config.queueDirectory,this.config.queueMaxAge),this.startBackgroundFlush()),this.startHealthCheck();}catch{this.setLocalMode("unexpected_error"),process.stderr.write(`\u26A0 TestRelic: Unexpected error during cloud initialization. Running in local mode.
|
|
1639
|
+
`);}}getMode(){return this.authState.mode}isCloudMode(){return this.authState.mode==="cloud"}isLocalMode(){return this.authState.mode==="local"}getAccessToken(){return this.authState.accessToken}getRepoId(){return this.repoId}getGitMetadata(){return this.gitMetadata}getConfig(){return this.config}getFailureReason(){return this.failureReason}getEndpoint(){return this.config?.endpoint??"https://api.testrelic.com/api/v1"}async ensureValidToken(){if(!this.isCloudMode()||!this.authState.accessToken)return false;let t=this.authState.expiresAt??0;if(Date.now()+Ur<t)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await Qt(this.config.endpoint,this.authState.refreshToken,this.config.timeout);return r?(this.authState.accessToken=r.accessToken,this.authState.refreshToken=r.refreshToken,this.authState.expiresAt=Date.now()+r.expiresIn*1e3,!0):(this.switchToLocalMode("token_refresh_failed"),!1)}catch{return this.switchToLocalMode("token_refresh_error"),false}}switchToLocalMode(t){this.authState.mode!=="local"&&(this.authState.mode="local",this.failureReason=t,process.stderr.write(`\u26A0 TestRelic: Switched to local mode (${t}).
|
|
1640
|
+
`));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,new Promise(t=>setTimeout(t,ie))]);}catch{}this.flushPromise=null;}this.authState={mode:"local",accessToken:null,refreshToken:null,expiresAt:null,orgId:null,orgName:null,userId:null,userName:null},this.repoId=null,this.gitMetadata=null;}setLocalMode(t){this.authState.mode="local",this.failureReason=t;}handleAuthError(t,r){switch(t){case "invalid_key":this.setLocalMode("invalid_api_key"),process.stderr.write(`\u26A0 TestRelic: API key is invalid or revoked. Running in local mode.
|
|
1641
|
+
\u2192 Manage keys: ${ot}
|
|
1548
1642
|
`);break;case "expired_key":this.setLocalMode("expired_api_key"),process.stderr.write(`\u26A0 TestRelic: API key has expired. Running in local mode.
|
|
1549
|
-
\u2192 Generate a new key: ${
|
|
1643
|
+
\u2192 Generate a new key: ${ot}
|
|
1550
1644
|
`);break;case "validation_error":this.setLocalMode("validation_error"),process.stderr.write(`\u26A0 TestRelic: API key format invalid. Running in local mode.
|
|
1551
|
-
\u2192 Manage keys: ${
|
|
1645
|
+
\u2192 Manage keys: ${ot}
|
|
1552
1646
|
`);break;case "rate_limited":this.setLocalMode("rate_limited"),process.stderr.write(`\u26A0 TestRelic: Rate limited during authentication. Running in local mode.
|
|
1553
1647
|
`);break;case "timeout":this.setLocalMode("auth_timeout"),process.stderr.write(`\u26A0 TestRelic: Authentication timed out. Running in local mode.
|
|
1554
1648
|
`);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
|
|
1555
|
-
`);break}}async
|
|
1556
|
-
`);}
|
|
1557
|
-
`),this.startBackgroundFlush();}}}catch{}},
|
|
1558
|
-
`);}if(!
|
|
1559
|
-
`),{navigations:
|
|
1560
|
-
`);}}};var un=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function pn(e){let t=e.toLowerCase();return un.some(r=>t.includes(r))}function fe(e,t){let r=new TextEncoder().encode(e);return r.length<=t?{text:e,truncated:false}:{text:new TextDecoder().decode(r.slice(0,t)),truncated:true}}var $=class{constructor(t,r){this.page=t;this.records=[];this.listeners=[];this.currentNetworkCounter=null;this.pendingRequests=new Map;this.capturedRequests=[];this.pendingBodyReads=[];this.requestIdCounter=0;this.requestCaptureCount=0;this.includeNetworkStats=r?.includeNetworkStats??true,this.origGoto=t.goto.bind(t),this.origGoBack=t.goBack.bind(t),this.origGoForward=t.goForward.bind(t),this.origReload=t.reload.bind(t),this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async getCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[t,r]of this.pendingRequests)this.capturedRequests.push({url:r.url,method:r.method,resourceType:r.resourceType,statusCode:0,responseTimeMs:Date.now()-r.startTimeMs,startedAt:r.startedAt,requestHeaders:r.headers,requestBody:r.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:r.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.pendingRequests.delete(t);return [...this.capturedRequests].sort((t,r)=>t.startedAt.localeCompare(r.startedAt))}async getData(){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}});let t=this.records.map(n=>({url:n.url,navigationType:n.navigationType,timestamp:n.timestamp,domContentLoadedAt:n.domContentLoadedAt,networkIdleAt:n.networkIdleAt,networkStats:n.networkStats})),r=this.includeNetworkStats?await this.getCapturedRequests():[];return {navigations:t,networkRequests:r}}async flushLegacyAnnotations(t){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}});for(let r of this.records){let n={url:r.url,navigationType:r.navigationType,timestamp:r.timestamp,domContentLoadedAt:r.domContentLoadedAt,networkIdleAt:r.networkIdleAt,networkStats:r.networkStats};t.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}if(this.includeNetworkStats){let r=await this.getCapturedRequests();r.length>0&&t.annotations.push({type:"__testrelic_network_requests",description:JSON.stringify(r)});}}dispose(){this.page.goto=this.origGoto,this.page.goBack=this.origGoBack,this.page.goForward=this.origGoForward,this.page.reload=this.origReload;for(let{event:t,handler:r}of this.listeners)this.page.off(t,r);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.capturedRequests=[],this.pendingBodyReads=[],this.requestCaptureCount=0;}getRecords(){return this.records}interceptMethods(){let t=this,r=this.page;r.goto=async function(n,a){return t.recordNavigation(n,"goto"),t.origGoto(n,a)},r.goBack=async function(n){let a=await t.origGoBack(n);return t.recordNavigation(r.url(),"back"),a},r.goForward=async function(n){let a=await t.origGoForward(n);return t.recordNavigation(r.url(),"forward"),a},r.reload=async function(n){return t.recordNavigation(r.url(),"refresh"),t.origReload(n)};}attachListeners(){let t=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",t),this.listeners.push({event:"domcontentloaded",handler:t});let r=a=>{try{let s=a;if(typeof s.parentFrame=="function"&&s.parentFrame()!==null)return;let l=s.url(),i=this.records[this.records.length-1];if(i&&Date.now()-new Date(i.timestamp).getTime()<50&&i.url===l)return;this.recordNavigation(l,"navigation");}catch{}};this.page.on("framenavigated",r),this.listeners.push({event:"framenavigated",handler:r});let n=a=>{try{let s=a;if(s.type()!=="debug")return;let l=s.text();if(!l.startsWith("__testrelic_nav:"))return;let i=JSON.parse(l.slice(16));i.type&&i.url&&this.recordNavigation(i.url,i.type);}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let a=i=>{if(this.currentNetworkCounter&&this.currentNetworkCounter.totalRequests++,!(this.requestCaptureCount>=500)){this.requestCaptureCount++;try{let o=i,c=String(this.requestIdCounter++),d=o.postData()??null,g=!1;if(d!==null){let p=fe(d,10240);d=p.text,g=p.truncated;}let u={url:o.url(),method:o.method(),resourceType:this.mapResourceType(o.resourceType()),headers:o.headers(),postData:d,postDataTruncated:g,startedAt:new Date().toISOString(),startTimeMs:Date.now()};this.pendingRequests.set(c,u),i.__testrelic_id=c;}catch{}}};this.page.on("request",a),this.listeners.push({event:"request",handler:a});let s=i=>{try{let o=i;if(this.currentNetworkCounter){let b=o.status();b>=400&&(this.currentNetworkCounter.failedRequests++,this.currentNetworkCounter.failedRequestUrls.push(b+" "+o.url()));let y=o.headers()["content-length"];y&&(this.currentNetworkCounter.totalBytes+=parseInt(y,10)||0);let x=o.request().resourceType(),w=this.mapResourceType(x);this.currentNetworkCounter.byType[w]++;}let c=o.request().__testrelic_id;if(!c)return;let d=this.pendingRequests.get(c);if(!d)return;this.pendingRequests.delete(c);let g=Date.now()-d.startTimeMs,u=o.headers(),p=u["content-type"]??null,f=parseInt(u["content-length"]??"0",10)||0,m=p?!pn(p):!1,v=(async()=>{let b=null,y=!1;if(!m)try{let S=(await o.body()).toString("utf-8"),h=fe(S,10240);b=h.text,y=h.truncated;}catch{}let x={url:d.url,method:d.method,resourceType:d.resourceType,statusCode:o.status(),responseTimeMs:g,startedAt:d.startedAt,requestHeaders:d.headers,requestBody:d.postData,responseBody:b,responseHeaders:u,contentType:p,responseSize:f,requestBodyTruncated:d.postDataTruncated,responseBodyTruncated:y,isBinary:m,error:null};this.capturedRequests.push(x);})();this.pendingBodyReads.push(v);}catch{}};this.page.on("response",s),this.listeners.push({event:"response",handler:s});let l=i=>{if(this.currentNetworkCounter){this.currentNetworkCounter.failedRequests++;try{let o=i;this.currentNetworkCounter.failedRequestUrls.push("ERR "+o.url());}catch{}}try{let o=i,c=o.__testrelic_id;if(!c)return;let d=this.pendingRequests.get(c);if(!d)return;this.pendingRequests.delete(c);let g={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:o.failure()?.errorText??"Unknown error"};this.capturedRequests.push(g);}catch{}};this.page.on("requestfailed",l),this.listeners.push({event:"requestfailed",handler:l});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let t=history.pushState.bind(history),r=history.replaceState.bind(history);history.pushState=function(...n){t(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){r(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(t,r){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}}),this.records.push({url:t,navigationType:r,timestamp:new Date().toISOString()}),this.includeNetworkStats&&(this.currentNetworkCounter=this.createNetworkCounter());}createNetworkCounter(){return {totalRequests:0,failedRequests:0,failedRequestUrls:[],totalBytes:0,byType:{xhr:0,document:0,script:0,stylesheet:0,image:0,font:0,other:0}}}mapResourceType(t){switch(t){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};var he=Symbol.for("__testrelic_call_id"),gn="__testrelic_api_assertions",E=new WeakMap,N=class{constructor(){this.assertions=[];this.currentCallId=null;}recordAssertion(t){this.assertions.push(t);}getAssertions(){return this.assertions}setCurrentCallId(t){this.currentCallId=t;}getCurrentCallId(){return this.currentCallId}getData(){return [...this.assertions]}flushLegacyAnnotations(t){this.assertions.length!==0&&t.annotations.push({type:gn,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}};var me="[REDACTED]";function ut(e,t){if(e===null||t.length===0)return e;let r=new Set(t.map(a=>a.toLowerCase())),n={};for(let a of Object.keys(e))Object.hasOwn(e,a)&&(n[a]=r.has(a.toLowerCase())?me:e[a]);return n}function G(e,t){if(e===null||t.length===0)return e;let r;try{r=JSON.parse(e);}catch{return e}if(typeof r!="object"||r===null)return e;let n=new Set(t),a=ct(r,n);return JSON.stringify(a)}function ct(e,t){if(Array.isArray(e))return e.map(r=>ct(r,t));if(typeof e=="object"&&e!==null){let r={};for(let n of Object.keys(e)){if(!Object.hasOwn(e,n))continue;let a=e[n];t.has(n)?r[n]=me:r[n]=ct(a,t);}return r}return e}function be(e,t,r){if(r.length>0){for(let n of r)if(ye(e,n))return false}if(t.length>0){for(let n of t)if(ye(e,n))return true;return false}return true}function ye(e,t){try{return t instanceof RegExp?t.test(e):fn(t).test(e)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(t)}`),false}}function fn(e){let t="",r=0;for(;r<e.length;){let n=e[r];n==="*"&&e[r+1]==="*"?(t+=".*",r+=2,e[r]==="/"&&r++):n==="*"?(t+="[^/]*",r++):n==="?"?(t+="[^/]",r++):".+^${}()|[]\\".includes(n)?(t+="\\"+n,r++):(t+=n,r++);}return new RegExp(t)}var hn=["get","post","put","patch","delete","head","fetch"],mn=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"],yn="__testrelic_api_calls";function bn(e){let t=e.toLowerCase();return mn.some(r=>t.includes(r))}function vn(e){if(!e)return null;if(e.data!==void 0&&e.data!==null){let t=e.data;return typeof t=="string"?t:Buffer.isBuffer(t)?t.toString("base64"):JSON.stringify(t)}if(e.form!==void 0&&e.form!==null)return JSON.stringify(e.form);if(e.multipart!==void 0&&e.multipart!==null){let t=e.multipart,r={};for(let[n,a]of Object.entries(t))typeof a=="string"||typeof a=="number"||typeof a=="boolean"?r[n]=String(a):a&&typeof a=="object"&&"name"in a?r[n]=`[file: ${a.name}]`:r[n]="[binary]";return JSON.stringify(r)}return null}var V=class V{constructor(t,r,n){this.originals=new Map;this.capturedCalls=[];this.callCounter=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=t,this.assertionTracker=r??null,this.apiConfig=n??V.DEFAULT_API_CONFIG;}get lastCallId(){return this._lastCallId}getCallIdForValue(t){return t!=null&&typeof t=="object"?E.get(t)??null:this.primitiveCallIds.get(t)??null}intercept(){for(let r of hn){let n=this.context[r].bind(this.context);this.originals.set(r,n),this.context[r]=this.createWrapper(r,n);}let t=this.context.dispose.bind(this.context);this.originals.set("dispose",t),this.context.dispose=async r=>(this.disposed=true,t(r));}getData(){return [...this.capturedCalls]}flushLegacyAnnotations(t){this.capturedCalls.length!==0&&t.annotations.push({type:yn,description:JSON.stringify(this.capturedCalls)});}dispose(){for(let[t,r]of this.originals)this.context[t]=r;this.originals.clear(),this.capturedCalls=[],this.callCounter=0,this._lastCallId=null,this.primitiveCallIds.clear();}get isDisposed(){return this.disposed}getCapturedCalls(){return this.capturedCalls}tagResponseMethods(t,r){let n=this,a=t.headers.bind(t);t.headers=function(){let p=a();return E.set(p,r),p};let s=t.headersArray.bind(t);t.headersArray=function(){let p=s();return E.set(p,r),p};let l=t.json.bind(t);t.json=async function(){let p=await l();return p!=null&&typeof p=="object"&&E.set(p,r),p};let i=t.status.bind(t);t.status=function(){let p=i();return n.primitiveCallIds.set(p,r),p};let o=t.statusText.bind(t);t.statusText=function(){let p=o();return n.primitiveCallIds.set(p,r),p};let c=t.ok.bind(t);t.ok=function(){let p=c();return n.primitiveCallIds.set(p,r),p};let d=t.text.bind(t);t.text=async function(){let p=await d();return n.primitiveCallIds.set(p,r),p};let g=t.body.bind(t);t.body=async function(){let p=await g();return E.set(p,r),p};}createWrapper(t,r){let n=this;return async function(s,l){if(!be(s,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return r(s,l);let i=`api-call-${n.callCounter++}`,o=new Date().toISOString(),c=t==="fetch"?(l?.method??"GET").toUpperCase():t.toUpperCase(),d=vn(l),g=performance.now();n._lastCallId=i,n.assertionTracker&&n.assertionTracker.setCurrentCallId(i);let u;try{u=await r(s,l);}catch(p){let f=performance.now();try{let m=n.apiConfig.captureRequestBody?G(d,n.apiConfig.redactBodyFields):null,v={id:i,timestamp:o,method:c,url:s,requestHeaders:null,requestBody:m,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((f-g)*100)/100,isBinary:!1,error:p instanceof Error?p.message:String(p)};n.capturedCalls.push(v);}catch{}throw p}try{let p=performance.now(),f=u.headers(),m=f["content-type"]??null,v=m?!bn(m):!1,b=null;n.apiConfig.captureRequestHeaders&&l?.headers&&(b=l.headers);let y=null;n.apiConfig.captureResponseHeaders&&(y=f);let x=n.apiConfig.captureRequestBody?d:null,w=null;if(n.apiConfig.captureResponseBody)try{v?w=(await u.body()).toString("base64"):w=await u.text();}catch{}b=ut(b,n.apiConfig.redactHeaders),y=ut(y,n.apiConfig.redactHeaders),x=G(x,n.apiConfig.redactBodyFields),w=G(w,n.apiConfig.redactBodyFields);let S={id:i,timestamp:o,method:c,url:u.url(),requestHeaders:b,requestBody:x,responseStatusCode:u.status(),responseStatusText:u.statusText(),responseHeaders:y,responseBody:w,responseTimeMs:Math.round((p-g)*100)/100,isBinary:v,error:null};n.capturedCalls.push(S);}catch{}try{u[he]=i,n.tagResponseMethods(u,i);}catch{}return u}}};V.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 L=V;var xn="__testrelic_api_config",kn="__testrelic_config_trackApiCalls";function gt(e){let t=e.annotations.find(n=>n.type===xn&&n.description!==void 0);if(t)try{return JSON.parse(t.description,Cn)}catch{}let r=e.annotations.find(n=>n.type===kn&&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 Cn(e,t){if(typeof t=="object"&&t!==null&&t.__regexp===true&&typeof t.source=="string"){let{source:r,flags:n}=t;return new RegExp(r,n)}return t}var ke={page:async({page:e},t,r)=>{let n=new $(e);try{await n.init();}catch{}await t(e);try{let{navigations:a,networkRequests:s}=await n.getData(),l={testRelicData:!0,version:PAYLOAD_VERSION,navigations:a,networkRequests:s,apiCalls:[],apiAssertions:[]};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(l)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{await n.flushLegacyAnnotations(r);}catch{}n.dispose();},request:async({request:e},t,r)=>{let n=gt(r);if(!n.trackApiCalls){await t(e);return}let a=new N,s=new L(e,a,n);s.intercept(),await t(e);try{let l=s.getData(),i=n.captureAssertions?a.getData():[],o={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],networkRequests:[],apiCalls:l,apiAssertions:i};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(o)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{s.flushLegacyAnnotations(r);}catch{}try{a.flushLegacyAnnotations(r);}catch{}s.dispose(),a.dispose();}};test.extend(ke);var An={request:async({request:e},t,r)=>{let n=gt(r);if(!n.trackApiCalls){await t(e);return}let a=new N,s=new L(e,a,n);s.intercept(),await t(e);try{let l=s.getData(),i=n.captureAssertions?a.getData():[],o={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],networkRequests:[],apiCalls:l,apiAssertions:i};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(o)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{s.flushLegacyAnnotations(r);}catch{}try{a.flushLegacyAnnotations(r);}catch{}s.dispose(),a.dispose();}};var Ce=false;function Ms(e,t,r="manual_record"){if(!e||!e.annotations){Ce||(Ce=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
|
|
1561
|
-
|
|
1649
|
+
`);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let t=this.gitMetadata?.remoteUrl?P(this.gitMetadata.remoteUrl):null,r=t?ee(t):this.config.projectName??D(process.cwd()),n=t??this.config.projectName??D(process.cwd()),s=this.readRepoCache(n);if(s){this.repoId=s.repoId;return}try{let a=await Xt(this.config.endpoint,this.authState.accessToken,n,r,this.config.timeout,this.gitMetadata?.branch);a&&(this.repoId=a.repoId,this.writeRepoCache(n,a.repoId,a.displayName));}catch{}!t&&!this.config.projectName&&!rt(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
|
|
1650
|
+
`);}readRepoCache(t){if(!this.config)return null;let r=join(this.config.queueDirectory,"..","cache","repo.json");try{if(!existsSync(r))return null;let n=readFileSync(r,"utf-8"),s=JSON.parse(n);if(s.gitId!==t||Date.now()-s.resolvedAt>zr)return null;let a=this.hashApiKey();return a&&s.apiKeyHash!==a?null:s}catch{return null}}writeRepoCache(t,r,n){if(!this.config)return;let s=join(this.config.queueDirectory,"..","cache"),a=join(s,"repo.json");try{mkdirSync(s,{recursive:!0});let l={repoId:r,gitId:t,displayName:n,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},o=a+".tmp";writeFileSync(o,JSON.stringify(l,null,2),"utf-8"),renameSync(o,a);}catch{}}hashApiKey(){return this.config?.apiKey?createHash("sha256").update(this.config.apiKey).digest("hex").substring(0,16):null}startBackgroundFlush(){if(!this.config||!this.authState.accessToken)return;let t=this.authState.accessToken,r=this.config.queueDirectory,n=this.config.endpoint;this.flushPromise=Promise.race([ae(r,n,t),new Promise(s=>setTimeout(s,ie))]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let t=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await X(t))return;if(this.config?.apiKey){let n=await tt(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!et(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.
|
|
1651
|
+
`),this.startBackgroundFlush();}}}catch{}},jr);}};var Gr=1048576,H=[1e3,3e3,9e3],U=3;function it(e,t,r,n){return {runId:e.testRunId,repoGitId:t,startedAt:e.startedAt,summary:e.summary,timeline:e.timeline,...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...e.completedAt?{finishedAt:e.completedAt}:{},...e.totalDuration?{duration:e.totalDuration}:{},...n?.provider?{ciProvider:n.provider}:{},...n?.runUrl?{ciRunUrl:n.runUrl}:{}}}async function z(e){return new Promise(t=>setTimeout(t,e))}function Vr(e){let t={};for(let[r,n]of Object.entries(e))n!=null&&(t[r]=n);return t}async function Jr(e,t,r){for(let n=0;n<U;n++)try{let s=await fetch(e,t);if(s.ok)return s;if(s.status===401&&r&&n===0){let a=await r();if(a){let l={...t,headers:{...t.headers,Authorization:`Bearer ${a}`}},o=await fetch(e,l);if(o.ok)return o}return null}if(s.status===429&&n<U-1){let a=s.headers.get("Retry-After"),l=a?parseInt(a,10)*1e3:H[n];!isNaN(l)&&l>0?await z(l):await z(H[n]);continue}if(s.status>=500&&n<U-1){await z(H[n]);continue}return s}catch{if(n<U-1){await z(H[n]);continue}return null}return null}function Kr(e){let t=JSON.stringify(e),r={"Content-Type":"application/json"};if(Buffer.byteLength(t,"utf-8")>Gr){let n=gzipSync(Buffer.from(t,"utf-8"));return r["Content-Encoding"]="gzip",{body:n,headers:r}}return {body:t,headers:r}}async function le(e,t,r,n){let s=`${e}/runs`,{body:a,headers:l}=Kr(r);l.Authorization=`Bearer ${t}`;let o=await Jr(s,{method:"POST",headers:l,body:a},n);return o?.ok?{success:true,statusCode:o.status,error:null}:o?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:o?`Upload failed with status ${o.status}`:"Upload failed after retries",statusCode:o?.status??null,payload:r,targetEndpoint:s,method:"POST"}}async function de(e,t,r){let n=`${e}/runs/init`;try{let s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(Vr(r))});return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function ce(e,t,r,n){let s=`${e}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)}).catch(()=>{});}async function pe(e,t,r,n){let s=`${e}/runs/${r}/finalize`;try{return (await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(n)})).ok}catch{return false}}function ue(e,t,r,n){let s=[],a=null,l=null,o=null,i=null,c=e.filter(g=>g.name===ATTACHMENT_NAME&&g.body),d=false;if(c.length>0)for(let g of c)try{let p=JSON.parse(g.body.toString());if(isTestRelicDataPayload(p)){s=s.concat(p.navigations),p.networkRequests.length>0&&(a=(a??[]).concat(p.networkRequests)),p.apiCalls.length>0&&(l=(l??[]).concat(p.apiCalls)),p.apiAssertions.length>0&&(o=(o??[]).concat(p.apiAssertions));let m=p.consoleLogs;Array.isArray(m)&&m.length>0&&(i=(i??[]).concat(m)),d=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}", falling back to annotations
|
|
1652
|
+
`);}if(!d){s=t.filter(f=>f.type==="lambdatest-navigation"&&f.description).map(f=>{try{return JSON.parse(f.description)}catch{return null}}).filter(f=>f!==null);let g=t.find(f=>f.type==="__testrelic_network_requests"&&f.description);if(g)try{a=JSON.parse(g.description);}catch{}let p=t.find(f=>f.type==="__testrelic_api_calls"&&f.description);if(p)try{l=JSON.parse(p.description);}catch{}let m=t.find(f=>f.type==="__testrelic_api_assertions"&&f.description);if(m)try{o=JSON.parse(m.description);}catch{}}return s.length===0&&!a&&!l&&!o&&!i&&!n&&process.stderr.write(`[testrelic] Warning: No data found for test "${r}". Make sure your tests import { test, expect } from '@testrelic/playwright-analytics/fixture' instead of '@playwright/test'. Without the TestRelic fixture, network logs, video sync, and timeline data cannot be captured.
|
|
1653
|
+
`),{navigations:s,networkRequests:a,apiCalls:l,apiAssertions:o,consoleLogs:i}}function lt(e){let r=e.getGitMetadata()?.remoteUrl;return r?P(r):e.getConfig()?.projectName??D(process.cwd())}async function ge(e,t,r,n){if(!e.isCloudMode()||t!=="realtime"&&t!=="both"||!await e.ensureValidToken())return null;let a=e.getGitMetadata(),l=A();return (await de(e.getEndpoint(),e.getAccessToken(),{runId:r,repoGitId:lt(e),branch:a?.branch??null,commit:a?.commitSha??null,startedAt:n,totalTests:null,ciProvider:l?.provider??null,ciRunUrl:l?.runUrl??null}))?.runId??null}async function fe(e,t,r,n,s,a,l,o,i){try{if(e.isCloudMode()&&s&&(r==="realtime"||r==="both")&&await e.ensureValidToken()&&await pe(e.getEndpoint(),e.getAccessToken(),s,{finishedAt:l,duration:o,summary:i}),e.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await e.ensureValidToken()){let d=e.getGitMetadata(),u=A(),g=lt(e),p=it(a,g,d,u),m=await le(e.getEndpoint(),e.getAccessToken(),p,async()=>await e.ensureValidToken()?e.getAccessToken():null);if(!m.success){let f=m,v=t?.queueDirectory??".testrelic/queue";st(v,n,"batch",f.reason,f.targetEndpoint,f.method,f.payload,{"Content-Type":"application/json"});}}else {let d=t?.queueDirectory??".testrelic/queue",u=e.getGitMetadata(),g=A(),p=lt(e),m=it(a,p,u,g);st(d,n,"batch",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs`,"POST",m,{"Content-Type":"application/json"});}await e.dispose();}catch{try{await e.dispose();}catch{}}}function dt(e){switch(e){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function nn(e,t,r){let n=`${e}::${t}::${r}`;return createHash("sha256").update(n).digest("hex").substring(0,16)}function sn(e){return e.length<=4?"":e[e.length-2]}function an(e){let t=e.findIndex(r=>r.status==="passed");return t>0?`passed on retry ${t}`:null}function on(e,t){let r=["e2e","api","unit"];for(let n of r)if(e.some(s=>s===`@${n}`||s===n))return n;for(let n of r)if(t.includes(`/${n}/`))return n;return "unknown"}var ln="__testrelic_api_config";function dn(e){return JSON.stringify(e,(t,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var j=class{constructor(t){this.rootDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.cloudClient=null;this.cloudRunId=null;this.config=Tt(t),this.apiConfig=Ct(t);}async onBegin(t,r){try{this.rootDir=t.rootDir,this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??randomUUID();try{this.cloudClient=new F(this.config.cloud),await this.cloudClient.initialize(),this.cloudRunId=await ge(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt);}catch{this.cloudClient?.switchToLocalMode("init_error");}}catch{}}onTestBegin(t,r){try{t.annotations.push({type:ln,description:dn(this.apiConfig)});}catch{}}onTestEnd(t,r){try{let n=r,s=t.outcome(),a;s==="flaky"?a="flaky":s==="skipped"?a="skipped":a=dt(n.status);let l=n.startTime.toISOString(),o=new Date(n.startTime.getTime()+n.duration).toISOString(),i=t.tags?[...t.tags]:t.annotations.filter(R=>R.type==="tag").map(R=>R.description??""),{navigations:c,networkRequests:d,apiCalls:u,apiAssertions:g,consoleLogs:p}=ue(n.attachments,t.annotations,t.title,a==="skipped");(c.length>0||d||u)&&(this.fixtureDataReceived=!0);let m=null;if(a==="failed"||a==="flaky"){let C=(a==="flaky"?t.results.find(B=>B.status!=="passed")?.errors??[]:n.errors)[0];if(C){let B=St(this.config.redactPatterns),J=C.location?.line??null,M=null;this.config.includeCodeSnippets&&J!==null&&C.location?.file&&(M=Rt(C.location.file,J,this.config.codeContextLines),M&&(M=B(M))),m={message:B(C.message??"Unknown error"),line:J,code:M,stack:this.config.includeStackTrace&&C.stack?B(C.stack):null};}}let f=t.titlePath().filter(Boolean),v=relative(this.rootDir||".",t.location.file),y=sn(f),b=f.join(" > "),w=v,x=nn(w,y,b),S=on(i,w),h=s==="flaky",k=an(t.results),E=dt(t.expectedStatus),q=dt(n.status),ft=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments){let R=dirname(this.config.outputPath),C=f[f.length-1]??t.title;ft=zt(n.attachments,C,n.retry,R);}let Ae=this.config.includeActionSteps&&n.steps?Kt(n.steps,n.startTime):null,ht={titlePath:f,title:b,status:a,duration:n.duration,startedAt:l,completedAt:o,retryCount:t.results.length-1,retry:n.retry,tags:i,failure:m,specFile:v,navigations:c,testId:x,filePath:w,suiteName:y,testType:S,isFlaky:h,retryStatus:k,expectedStatus:E,actualStatus:q,artifacts:ft,networkRequests:d,apiCalls:u,apiAssertions:g,actions:Ae,consoleLogs:p};this.collectedTests.push(ht);try{let R=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(R==="realtime"||R==="both")){let C=this.cloudClient.getAccessToken();C&&ce(this.cloudClient.getEndpoint(),C,this.cloudRunId,this.toTestResult(ht));}}catch{}}catch{}}async onEnd(t){try{let r=new Date().toISOString(),n=new Date(this.startedAt).getTime(),a=new Date(r).getTime()-n,l=this.buildTimeline(),o=Vt(this.collectedTests,l.length),i={schemaVersion:W,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:a,summary:o,ci:A(),metadata:this.config.metadata,timeline:l,shardRunIds:null};!this.fixtureDataReceived&&this.collectedTests.some(c=>c.status!=="skipped")&&process.stderr.write(`
|
|
1654
|
+
\u26A0 TestRelic: No fixture data received from any test.
|
|
1655
|
+
To enable network logs, video sync, and timeline tracking, import the TestRelic fixture:
|
|
1656
|
+
import { test, expect } from '@testrelic/playwright-analytics/fixture';
|
|
1657
|
+
instead of:
|
|
1658
|
+
import { test, expect } from '@playwright/test';
|
|
1659
|
+
|
|
1660
|
+
`),this.writeReport(i),Ot(i,this.config),Jt(o,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient&&await fe(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,i,r,a,o);}catch{}}printsToStdio(){return false}buildTimeline(){let t=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls:r.apiCalls,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:r.networkRequests,actions:r.actions,consoleLogs:r.consoleLogs}));return Gt(t,{navigationTypes:this.config.navigationTypes})}toTestResult(t){return {title:t.title,status:t.status,duration:t.duration,startedAt:t.startedAt,completedAt:t.completedAt,retryCount:t.retryCount,tags:t.tags,failure:t.failure,testId:t.testId,filePath:t.filePath,suiteName:t.suiteName,testType:t.testType,isFlaky:t.isFlaky,retryStatus:t.retryStatus,expectedStatus:t.expectedStatus,actualStatus:t.actualStatus,artifacts:t.artifacts,networkRequests:t.networkRequests,apiCalls:t.apiCalls,apiAssertions:t.apiAssertions,actions:t.actions??null,consoleLogs:t.consoleLogs??null}}writeReport(t){try{let r=JSON.stringify(t,null,2),n=this.config.outputPath,s=dirname(n);mkdirSync(s,{recursive:!0});let a=n+".tmp";writeFileSync(a,r,"utf-8"),renameSync(a,n);}catch(r){process.stderr.write(`[testrelic] Failed to write report: ${r instanceof Error?r.message:String(r)}
|
|
1661
|
+
`);}}};var fn=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function hn(e){let t=e.toLowerCase();return fn.some(r=>t.includes(r))}function me(e,t){let r=new TextEncoder().encode(e);return r.length<=t?{text:e,truncated:false}:{text:new TextDecoder().decode(r.slice(0,t)),truncated:true}}var $=class e{constructor(t,r){this.page=t;this.records=[];this.listeners=[];this.currentNetworkCounter=null;this.pendingRequests=new Map;this.capturedRequests=[];this.pendingBodyReads=[];this.requestIdCounter=0;this.requestCaptureCount=0;this.consoleLogs=[];this.includeNetworkStats=r?.includeNetworkStats??true,this.origGoto=t.goto.bind(t),this.origGoBack=t.goBack.bind(t),this.origGoForward=t.goForward.bind(t),this.origReload=t.reload.bind(t),this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async getCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[t,r]of this.pendingRequests)this.capturedRequests.push({url:r.url,method:r.method,resourceType:r.resourceType,statusCode:0,responseTimeMs:Date.now()-r.startTimeMs,startedAt:r.startedAt,requestHeaders:r.headers,requestBody:r.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:r.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.pendingRequests.delete(t);return [...this.capturedRequests].sort((t,r)=>t.startedAt.localeCompare(r.startedAt))}static mapConsoleType(t){switch(t){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getData(){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}});let t=this.records.map(n=>({url:n.url,navigationType:n.navigationType,timestamp:n.timestamp,domContentLoadedAt:n.domContentLoadedAt,networkIdleAt:n.networkIdleAt,networkStats:n.networkStats})),r=this.includeNetworkStats?await this.getCapturedRequests():[];return {navigations:t,networkRequests:r,consoleLogs:[...this.consoleLogs]}}async flushLegacyAnnotations(t){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}});for(let r of this.records){let n={url:r.url,navigationType:r.navigationType,timestamp:r.timestamp,domContentLoadedAt:r.domContentLoadedAt,networkIdleAt:r.networkIdleAt,networkStats:r.networkStats};t.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}if(this.includeNetworkStats){let r=await this.getCapturedRequests();r.length>0&&t.annotations.push({type:"__testrelic_network_requests",description:JSON.stringify(r)});}}dispose(){this.page.goto=this.origGoto,this.page.goBack=this.origGoBack,this.page.goForward=this.origGoForward,this.page.reload=this.origReload;for(let{event:t,handler:r}of this.listeners)this.page.off(t,r);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.capturedRequests=[],this.pendingBodyReads=[],this.requestCaptureCount=0;}getRecords(){return this.records}interceptMethods(){let t=this,r=this.page;r.goto=async function(n,s){return t.recordNavigation(n,"goto"),t.origGoto(n,s)},r.goBack=async function(n){let s=await t.origGoBack(n);return t.recordNavigation(r.url(),"back"),s},r.goForward=async function(n){let s=await t.origGoForward(n);return t.recordNavigation(r.url(),"forward"),s},r.reload=async function(n){return t.recordNavigation(r.url(),"refresh"),t.origReload(n)};}attachListeners(){let t=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",t),this.listeners.push({event:"domcontentloaded",handler:t});let r=s=>{try{let a=s;if(typeof a.parentFrame=="function"&&a.parentFrame()!==null)return;let l=a.url(),o=this.records[this.records.length-1];if(o&&Date.now()-new Date(o.timestamp).getTime()<50&&o.url===l)return;this.recordNavigation(l,"navigation");}catch{}};this.page.on("framenavigated",r),this.listeners.push({event:"framenavigated",handler:r});let n=s=>{try{let a=s,l=a.type(),o=a.text();if(l==="debug"&&o.startsWith("__testrelic_nav:")){try{let i=JSON.parse(o.slice(16));i.type&&i.url&&this.recordNavigation(i.url,i.type);}catch{}return}{let i=null;try{let d=a.location();d&&d.url&&(i=`${d.url}:${d.lineNumber}:${d.columnNumber}`);}catch{}let c=e.mapConsoleType(l);this.consoleLogs.push({level:c,text:o,timestamp:new Date().toISOString(),location:i});}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=o=>{if(this.currentNetworkCounter&&this.currentNetworkCounter.totalRequests++,!(this.requestCaptureCount>=500)){this.requestCaptureCount++;try{let i=o,c=String(this.requestIdCounter++),d=i.postData()??null,u=!1;if(d!==null){let p=me(d,10240);d=p.text,u=p.truncated;}let g={url:i.url(),method:i.method(),resourceType:this.mapResourceType(i.resourceType()),headers:i.headers(),postData:d,postDataTruncated:u,startedAt:new Date().toISOString(),startTimeMs:Date.now()};this.pendingRequests.set(c,g),o.__testrelic_id=c;}catch{}}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let a=o=>{try{let i=o;if(this.currentNetworkCounter){let y=i.status();y>=400&&(this.currentNetworkCounter.failedRequests++,this.currentNetworkCounter.failedRequestUrls.push(y+" "+i.url()));let b=i.headers()["content-length"];b&&(this.currentNetworkCounter.totalBytes+=parseInt(b,10)||0);let w=i.request().resourceType(),x=this.mapResourceType(w);this.currentNetworkCounter.byType[x]++;}let c=i.request().__testrelic_id;if(!c)return;let d=this.pendingRequests.get(c);if(!d)return;this.pendingRequests.delete(c);let u=Date.now()-d.startTimeMs,g=i.headers(),p=g["content-type"]??null,m=parseInt(g["content-length"]??"0",10)||0,f=p?!hn(p):!1,v=(async()=>{let y=null,b=!1;if(!f)try{let S=(await i.body()).toString("utf-8"),h=me(S,10240);y=h.text,b=h.truncated;}catch{}let w={url:d.url,method:d.method,resourceType:d.resourceType,statusCode:i.status(),responseTimeMs:u,startedAt:d.startedAt,requestHeaders:d.headers,requestBody:d.postData,responseBody:y,responseHeaders:g,contentType:p,responseSize:m,requestBodyTruncated:d.postDataTruncated,responseBodyTruncated:b,isBinary:f,error:null};this.capturedRequests.push(w);})();this.pendingBodyReads.push(v);}catch{}};this.page.on("response",a),this.listeners.push({event:"response",handler:a});let l=o=>{if(this.currentNetworkCounter){this.currentNetworkCounter.failedRequests++;try{let i=o;this.currentNetworkCounter.failedRequestUrls.push("ERR "+i.url());}catch{}}try{let i=o,c=i.__testrelic_id;if(!c)return;let d=this.pendingRequests.get(c);if(!d)return;this.pendingRequests.delete(c);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:i.failure()?.errorText??"Unknown error"};this.capturedRequests.push(u);}catch{}};this.page.on("requestfailed",l),this.listeners.push({event:"requestfailed",handler:l});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let t=history.pushState.bind(history),r=history.replaceState.bind(history);history.pushState=function(...n){t(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){r(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(t,r){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}}),this.records.push({url:t,navigationType:r,timestamp:new Date().toISOString()}),this.includeNetworkStats&&(this.currentNetworkCounter=this.createNetworkCounter());}createNetworkCounter(){return {totalRequests:0,failedRequests:0,failedRequestUrls:[],totalBytes:0,byType:{xhr:0,document:0,script:0,stylesheet:0,image:0,font:0,other:0}}}mapResourceType(t){switch(t){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};var ye=Symbol.for("__testrelic_call_id"),mn="__testrelic_api_assertions",L=new WeakMap,_=class{constructor(){this.assertions=[];this.currentCallId=null;}recordAssertion(t){this.assertions.push(t);}getAssertions(){return this.assertions}setCurrentCallId(t){this.currentCallId=t;}getCurrentCallId(){return this.currentCallId}getData(){return [...this.assertions]}flushLegacyAnnotations(t){this.assertions.length!==0&&t.annotations.push({type:mn,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}};var be="[REDACTED]";function pt(e,t){if(e===null||t.length===0)return e;let r=new Set(t.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(e))Object.hasOwn(e,s)&&(n[s]=r.has(s.toLowerCase())?be:e[s]);return n}function G(e,t){if(e===null||t.length===0)return e;let r;try{r=JSON.parse(e);}catch{return e}if(typeof r!="object"||r===null)return e;let n=new Set(t),s=ct(r,n);return JSON.stringify(s)}function ct(e,t){if(Array.isArray(e))return e.map(r=>ct(r,t));if(typeof e=="object"&&e!==null){let r={};for(let n of Object.keys(e)){if(!Object.hasOwn(e,n))continue;let s=e[n];t.has(n)?r[n]=be:r[n]=ct(s,t);}return r}return e}function we(e,t,r){if(r.length>0){for(let n of r)if(ve(e,n))return false}if(t.length>0){for(let n of t)if(ve(e,n))return true;return false}return true}function ve(e,t){try{return t instanceof RegExp?t.test(e):yn(t).test(e)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(t)}`),false}}function yn(e){let t="",r=0;for(;r<e.length;){let n=e[r];n==="*"&&e[r+1]==="*"?(t+=".*",r+=2,e[r]==="/"&&r++):n==="*"?(t+="[^/]*",r++):n==="?"?(t+="[^/]",r++):".+^${}()|[]\\".includes(n)?(t+="\\"+n,r++):(t+=n,r++);}return new RegExp(t)}var bn=["get","post","put","patch","delete","head","fetch"],vn=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"],wn="__testrelic_api_calls";function xn(e){let t=e.toLowerCase();return vn.some(r=>t.includes(r))}function kn(e){if(!e)return null;if(e.data!==void 0&&e.data!==null){let t=e.data;return typeof t=="string"?t:Buffer.isBuffer(t)?t.toString("base64"):JSON.stringify(t)}if(e.form!==void 0&&e.form!==null)return JSON.stringify(e.form);if(e.multipart!==void 0&&e.multipart!==null){let t=e.multipart,r={};for(let[n,s]of Object.entries(t))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?r[n]=String(s):s&&typeof s=="object"&&"name"in s?r[n]=`[file: ${s.name}]`:r[n]="[binary]";return JSON.stringify(r)}return null}var V=class V{constructor(t,r,n){this.originals=new Map;this.capturedCalls=[];this.callCounter=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=t,this.assertionTracker=r??null,this.apiConfig=n??V.DEFAULT_API_CONFIG;}get lastCallId(){return this._lastCallId}getCallIdForValue(t){return t!=null&&typeof t=="object"?L.get(t)??null:this.primitiveCallIds.get(t)??null}intercept(){for(let r of bn){let n=this.context[r].bind(this.context);this.originals.set(r,n),this.context[r]=this.createWrapper(r,n);}let t=this.context.dispose.bind(this.context);this.originals.set("dispose",t),this.context.dispose=async r=>(this.disposed=true,t(r));}getData(){return [...this.capturedCalls]}flushLegacyAnnotations(t){this.capturedCalls.length!==0&&t.annotations.push({type:wn,description:JSON.stringify(this.capturedCalls)});}dispose(){for(let[t,r]of this.originals)this.context[t]=r;this.originals.clear(),this.capturedCalls=[],this.callCounter=0,this._lastCallId=null,this.primitiveCallIds.clear();}get isDisposed(){return this.disposed}getCapturedCalls(){return this.capturedCalls}tagResponseMethods(t,r){let n=this,s=t.headers.bind(t);t.headers=function(){let p=s();return L.set(p,r),p};let a=t.headersArray.bind(t);t.headersArray=function(){let p=a();return L.set(p,r),p};let l=t.json.bind(t);t.json=async function(){let p=await l();return p!=null&&typeof p=="object"&&L.set(p,r),p};let o=t.status.bind(t);t.status=function(){let p=o();return n.primitiveCallIds.set(p,r),p};let i=t.statusText.bind(t);t.statusText=function(){let p=i();return n.primitiveCallIds.set(p,r),p};let c=t.ok.bind(t);t.ok=function(){let p=c();return n.primitiveCallIds.set(p,r),p};let d=t.text.bind(t);t.text=async function(){let p=await d();return n.primitiveCallIds.set(p,r),p};let u=t.body.bind(t);t.body=async function(){let p=await u();return L.set(p,r),p};}createWrapper(t,r){let n=this;return async function(a,l){if(!we(a,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return r(a,l);let o=`api-call-${n.callCounter++}`,i=new Date().toISOString(),c=t==="fetch"?(l?.method??"GET").toUpperCase():t.toUpperCase(),d=kn(l),u=performance.now();n._lastCallId=o,n.assertionTracker&&n.assertionTracker.setCurrentCallId(o);let g;try{g=await r(a,l);}catch(p){let m=performance.now();try{let f=n.apiConfig.captureRequestBody?G(d,n.apiConfig.redactBodyFields):null,v={id:o,timestamp:i,method:c,url:a,requestHeaders:null,requestBody:f,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((m-u)*100)/100,isBinary:!1,error:p instanceof Error?p.message:String(p)};n.capturedCalls.push(v);}catch{}throw p}try{let p=performance.now(),m=g.headers(),f=m["content-type"]??null,v=f?!xn(f):!1,y=null;n.apiConfig.captureRequestHeaders&&l?.headers&&(y=l.headers);let b=null;n.apiConfig.captureResponseHeaders&&(b=m);let w=n.apiConfig.captureRequestBody?d:null,x=null;if(n.apiConfig.captureResponseBody)try{v?x=(await g.body()).toString("base64"):x=await g.text();}catch{}y=pt(y,n.apiConfig.redactHeaders),b=pt(b,n.apiConfig.redactHeaders),w=G(w,n.apiConfig.redactBodyFields),x=G(x,n.apiConfig.redactBodyFields);let S={id:o,timestamp:i,method:c,url:g.url(),requestHeaders:y,requestBody:w,responseStatusCode:g.status(),responseStatusText:g.statusText(),responseHeaders:b,responseBody:x,responseTimeMs:Math.round((p-u)*100)/100,isBinary:v,error:null};n.capturedCalls.push(S);}catch{}try{g[ye]=o,n.tagResponseMethods(g,o);}catch{}return g}}};V.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 N=V;var Tn="__testrelic_api_config",Rn="__testrelic_config_trackApiCalls";function gt(e){let t=e.annotations.find(n=>n.type===Tn&&n.description!==void 0);if(t)try{return JSON.parse(t.description,Sn)}catch{}let r=e.annotations.find(n=>n.type===Rn&&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 Sn(e,t){if(typeof t=="object"&&t!==null&&t.__regexp===true&&typeof t.source=="string"){let{source:r,flags:n}=t;return new RegExp(r,n)}return t}var Te={page:async({page:e},t,r)=>{let n=new $(e);try{await n.init();}catch{}await t(e);try{let{navigations:s,networkRequests:a,consoleLogs:l}=await n.getData(),o={testRelicData:!0,version:PAYLOAD_VERSION,navigations:s,networkRequests:a,apiCalls:[],apiAssertions:[],consoleLogs:l};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(o)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{await n.flushLegacyAnnotations(r);}catch{}n.dispose();},request:async({request:e},t,r)=>{let n=gt(r);if(!n.trackApiCalls){await t(e);return}let s=new _,a=new N(e,s,n);a.intercept(),await t(e);try{let l=a.getData(),o=n.captureAssertions?s.getData():[],i={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],networkRequests:[],apiCalls:l,apiAssertions:o,consoleLogs:[]};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(i)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{a.flushLegacyAnnotations(r);}catch{}try{s.flushLegacyAnnotations(r);}catch{}a.dispose(),s.dispose();}};test.extend(Te);var Ln={request:async({request:e},t,r)=>{let n=gt(r);if(!n.trackApiCalls){await t(e);return}let s=new _,a=new N(e,s,n);a.intercept();let l=[],o=process.stdout.write,i=process.stderr.write;process.stdout.write=function(c,...d){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")&&l.push({level:"stdout",text:u.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null});}catch{}return o.apply(process.stdout,[c,...d])},process.stderr.write=function(c,...d){try{let u=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!u.startsWith("[testrelic]")&&!u.startsWith("\u26A0 TestRelic")&&l.push({level:"stderr",text:u.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null});}catch{}return i.apply(process.stderr,[c,...d])};try{await t(e);}finally{process.stdout.write=o,process.stderr.write=i;}try{let c=a.getData(),d=n.captureAssertions?s.getData():[],u={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],networkRequests:[],apiCalls:c,apiAssertions:d,consoleLogs:l};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(u)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{a.flushLegacyAnnotations(r);}catch{}try{s.flushLegacyAnnotations(r);}catch{}a.dispose(),s.dispose();}};var Re="@testrelic/playwright-analytics";function En(e){return Array.isArray(e)?e.some(t=>Array.isArray(t)&&typeof t[0]=="string"&&t[0]===Re):false}function qn(e,t){let n={video:"on",screenshot:"on",trace:"on",...e.use??{}},s;Array.isArray(e.reporter)?s=e.reporter:typeof e.reporter=="string"?s=[[e.reporter]]:s=[["list"]];let a=En(s)?s:[...s,[Re,t??{}]];return defineConfig({...e,use:n,reporter:a})}var Se=false;function Ga(e,t,r="manual_record"){if(!e||!e.annotations){Se||(Se=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
|
|
1662
|
+
`));return}let n={url:t,navigationType:r,timestamp:new Date().toISOString()};e.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}export{W as SCHEMA_VERSION,j as default,qn as defineConfig,Ga as recordNavigation,Ln as testRelicApiFixture,Te as testRelicFixture};//# sourceMappingURL=index.js.map
|
|
1562
1663
|
//# sourceMappingURL=index.js.map
|