@testrelic/playwright-analytics 2.2.7 → 2.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.cjs +621 -30
- package/dist/index.cjs +666 -334
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +12 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +666 -334
- package/dist/index.js.map +1 -1
- package/dist/merge.cjs +1 -1
- package/dist/merge.cjs.map +1 -1
- package/dist/merge.js +1 -1
- package/dist/merge.js.map +1 -1
- package/package.json +13 -13
package/dist/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {randomUUID,createHash}from'crypto';import {writeFileSync,renameSync,mkdirSync,existsSync,readFileSync,appendFileSync,
|
|
2
|
-
`)
|
|
3
|
-
`)
|
|
1
|
+
import {randomUUID,createHash}from'crypto';import {writeFileSync,renameSync,mkdirSync,existsSync,readFileSync,appendFileSync,readdirSync,unlinkSync,statSync,rmSync}from'fs';import {dirname,join,relative,extname,resolve,parse,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 {spawn,exec,execSync}from'child_process';import {createServer}from'http';import {copyFile}from'fs/promises';import {gzipSync}from'zlib';import {test,defineConfig}from'@playwright/test';import {performance}from'perf_hooks';var Ir=".testrelic-report";function bt(e,t,r,n){let s=`${e}|${t.join("|")}|${r}|${n}`;return createHash("sha256").update(s).digest("hex").substring(0,12)}var W=class{constructor(t){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=join(t,Ir),this.testsDir=join(this.reportDir,"tests"),mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(t,r){try{let n=join(this.testsDir,`${t}.json`),s=n+".tmp",a=JSON.stringify(r);return writeFileSync(s,a,"utf-8"),renameSync(s,n),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8"),!0}catch(n){let s=n instanceof Error?n.message:String(n);return this.writeErrors.push({testId:t,error:s,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${t}: ${s}
|
|
2
|
+
`),false}}writeIndex(t){let r=join(this.reportDir,"index.json"),n=r+".tmp",s=JSON.stringify(t);writeFileSync(n,s,"utf-8"),renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeCompactIndex(t){let r=join(this.reportDir,"index-compact.json"),n=r+".tmp",s=t.map(({titlePath:l,project:i,...o})=>o),a=JSON.stringify(s);writeFileSync(n,a,"utf-8"),renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}writeSummary(t){let r=join(this.reportDir,"summary.json"),n=r+".tmp",s=JSON.stringify(t);writeFileSync(n,s,"utf-8"),renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeManifest(t){let r=join(this.reportDir,"manifest.json"),n=r+".tmp",s=JSON.stringify(t);writeFileSync(n,s,"utf-8"),renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var Or=".testrelic",qr=5,Fr=new Set(["__proto__","constructor","prototype"]),oe=Object.freeze({apiKey:null,endpoint:"https://api.testrelic.com/api/v1",uploadStrategy:"batch",timeout:3e4,projectName:null,queueMaxAge:6048e5,queueDirectory:".testrelic/queue"}),Hr={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function de(e){let t=resolve(e);for(let r=0;r<=qr;r++){let n=join(t,Or);if(existsSync(n))return n;let s=dirname(t);if(s===t)break;t=s;}return null}function ce(e){try{let t=readFileSync(e,"utf-8"),r=JSON.parse(t);return typeof r!="object"||r===null||Array.isArray(r)||!pe(r)?null:r}catch{return null}}function pe(e){for(let t of Object.keys(e)){if(Fr.has(t))return false;let r=e[t];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!pe(r))return false}return true}function ue(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 wt(e){let t=Object.create(null);for(let r of Object.keys(e)){let n=e[r];typeof n=="string"&&n.startsWith("$")?t[r]=ue(n):typeof n=="object"&&n!==null&&!Array.isArray(n)?t[r]=wt(n):t[r]=n;}return t}function le(e){let t=/^(\d+)\s*([smhd])$/.exec(e.trim());if(!t)return null;let r=parseInt(t[1],10),n=t[2],s=Hr[n];return !s||r<=0?null:r*s}function fe(e,t){let r=Object.create(null);if(Object.assign(r,oe),e){let o=e.cloud;o&&typeof o=="object"&&(typeof o.endpoint=="string"&&(r.endpoint=o.endpoint),typeof o.upload=="string"&&(r.uploadStrategy=o.upload),typeof o.timeout=="number"&&(r.timeout=o.timeout),typeof o.apiKey=="string"&&o.apiKey.length>0&&(r.apiKey=o.apiKey));let p=e.project;p&&typeof p=="object"&&typeof p.name=="string"&&(r.projectName=p.name);let d=e.queue;if(d&&typeof d=="object"){if(typeof d.maxAge=="string"){let u=le(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 o=t.apiKey.startsWith("$")?ue(t.apiKey):t.apiKey;o&&(r.apiKey=o);}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 o=le(t.queueMaxAge);o!==null&&(r.queueMaxAge=o);}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 o=parseInt(l,10);!isNaN(o)&&o>=1e3&&o<=12e4&&(r.timeout=o);}let i=Object.freeze(r);return isValidCloudConfig(i)?i:oe}var jr=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],Vr=["authorization","cookie","set-cookie","x-api-key"],Gr=["password","secret","token","apiKey","api_key"];function ge(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??[...Vr],t.redactBodyFields=e?.redactBodyFields??[...Gr],t.apiIncludeUrls=e?.apiIncludeUrls??[],t.apiExcludeUrls=e?.apiExcludeUrls??[],Object.freeze(t)}function he(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=[...jr,...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=de(process.cwd()),s=n?ce(n):null,a=s?wt(s):null,l=fe(a,e?.cloud);return t.cloud=l.apiKey?l:null,t.reportMode=e?.reportMode??"streaming",t.streamingThreshold=e?.streamingThreshold??0,Object.freeze(t)}var rt="1.3.0";function me(e,t,r){try{let s=readFileSync(e,"utf-8").split(`
|
|
3
|
+
`);if(t<1||t>s.length)return null;let a=Math.max(1,t-r),l=Math.min(s.length,t+r),i=[];for(let o=a;o<=l;o++){let p=o===t?">":" ",d=String(o).padStart(String(l).length," ");i.push(`${p} ${d} | ${s[o-1]}`);}return i.join(`
|
|
4
|
+
`)}catch{return null}}function ve(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 Jr(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 Kr(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 Yr(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 Zr(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 Qr(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 Xr=[Jr,Kr,Yr,Zr,Qr];function M(e){let t=process.env;for(let r of Xr){let n=r(t);if(n)return n}return null}var xt=`
|
|
4
5
|
/* Theme Variables */
|
|
5
6
|
:root,[data-theme="dark"]{
|
|
6
7
|
--bg:#0f1117;--bg-1:#161b22;--bg-2:#1c2128;--bg-3:#21262d;--bg-code:#13111c;
|
|
@@ -289,6 +290,9 @@ body{
|
|
|
289
290
|
/* \u2500\u2500 Failure Panel \u2500\u2500 */
|
|
290
291
|
.failure-panel{margin-bottom:20px;border:1px solid rgba(239,68,68,0.2);border-radius:10px;overflow:hidden;background:var(--bg-2)}
|
|
291
292
|
.failure-panel-header{display:flex;align-items:center;gap:8px;padding:10px 14px;background:rgba(239,68,68,0.08);font-size:12px;font-weight:600;color:#ef4444}
|
|
293
|
+
.copy-prompt-btn{margin-left:auto;display:inline-flex;align-items:center;gap:5px;padding:4px 10px;font-size:11px;font-weight:500;font-family:inherit;color:var(--fg-1);background:var(--bg-3);border:1px solid var(--bd);border-radius:6px;cursor:pointer;transition:all .15s;white-space:nowrap}
|
|
294
|
+
.copy-prompt-btn:hover{background:var(--bg-2);color:var(--fg);border-color:var(--bd-m)}
|
|
295
|
+
.copy-prompt-btn.copied{color:#34d399;border-color:rgba(52,211,153,0.3);background:rgba(52,211,153,0.08)}
|
|
292
296
|
.failure-message{padding:12px 14px;background:var(--bg-code);color:var(--fg-err);font-size:12px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap;word-break:break-word;line-height:1.6;overflow-x:auto}
|
|
293
297
|
.code-snippet{background:var(--bg-code);font-size:12px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;overflow-x:auto;border-top:1px solid var(--bd-s)}
|
|
294
298
|
.code-line{display:flex;padding:0 14px;line-height:1.8}
|
|
@@ -381,21 +385,26 @@ body{
|
|
|
381
385
|
|
|
382
386
|
/* \u2500\u2500 Network DevTools Panel \u2500\u2500 */
|
|
383
387
|
.ndt{border:1px solid var(--bd);border-radius:10px;overflow:hidden;background:var(--bg-1)}
|
|
384
|
-
.ndt
|
|
388
|
+
.ndt{border:1px solid var(--bd);border-radius:8px;overflow:hidden;background:var(--bg-1)}
|
|
389
|
+
.ndt-toolbar{display:flex;align-items:center;gap:4px;padding:4px 8px;background:var(--bg-2);border-bottom:1px solid var(--bd);flex-wrap:wrap}
|
|
385
390
|
.ndt-filter{display:flex;gap:2px;flex-wrap:wrap}
|
|
386
391
|
.ndt-filter-btn{font-size:10px;padding:2px 8px;border-radius:4px;border:1px solid transparent;background:none;color:var(--fg-2);cursor:pointer;font-weight:500;transition:all .15s}
|
|
387
392
|
.ndt-filter-btn:hover{background:var(--hvr);color:var(--fg-1)}
|
|
388
393
|
.ndt-filter-btn.active{background:var(--bg-3);color:var(--fg);border-color:var(--bd-m);font-weight:600}
|
|
389
|
-
.ndt-search{flex:1;min-width:100px;max-width:220px;font-size:10px;padding:3px 8px;border-radius:4px;border:1px solid var(--bd);background:var(--bg);color:var(--fg);outline:none;font-family:
|
|
394
|
+
.ndt-search{flex:1;min-width:100px;max-width:220px;font-size:10px;padding:3px 8px;border-radius:4px;border:1px solid var(--bd);background:var(--bg);color:var(--fg);outline:none;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
|
|
390
395
|
.ndt-search:focus{border-color:rgba(3,183,156,0.4)}
|
|
391
396
|
.ndt-count{font-size:10px;color:var(--fg-2);margin-left:auto;white-space:nowrap}
|
|
392
|
-
.ndt-list{max-height:600px;overflow-y:auto}
|
|
397
|
+
.ndt-list{max-height:600px;overflow-y:auto;background:var(--bg)}
|
|
393
398
|
.ndt-list::-webkit-scrollbar{width:5px}.ndt-list::-webkit-scrollbar-thumb{background:var(--scroll-thumb);border-radius:4px}
|
|
394
|
-
.ndt-row{display:grid;grid-template-columns:42px 50px 1fr 52px 56px 56px;align-items:center;gap:4px;padding:
|
|
399
|
+
.ndt-row{display:grid;grid-template-columns:42px 50px 1fr 52px 56px 56px;align-items:center;gap:4px;padding:4px 10px;border-bottom:1px solid var(--bd-xs);cursor:pointer;font-size:11px;transition:background .1s}
|
|
395
400
|
.ndt-row:hover{background:var(--hvr)}
|
|
396
401
|
.ndt-row.ndt-row--open{background:var(--bg-2)}
|
|
397
402
|
.ndt-row.ndt-row--fail{background:rgba(239,68,68,0.04)}
|
|
398
403
|
.ndt-row.ndt-row--fail:hover{background:rgba(239,68,68,0.08)}
|
|
404
|
+
.ndt-row.seekable{cursor:pointer}
|
|
405
|
+
.ndt-row--active{background:rgba(3,183,156,0.1) !important;border-left:3px solid #03b79c}
|
|
406
|
+
.ndt-row--active .ndt-url{color:#2dd4a8}
|
|
407
|
+
.ndt-offset{color:#03b79c !important;font-weight:600}
|
|
399
408
|
.ndt-status{font-weight:700;font-size:10px;padding:1px 5px;border-radius:3px;text-align:center;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
|
|
400
409
|
.ndt-status--2xx{background:rgba(34,197,94,0.12);color:#22c55e}
|
|
401
410
|
.ndt-status--3xx{background:rgba(59,130,246,0.12);color:#60a5fa}
|
|
@@ -462,23 +471,29 @@ body{
|
|
|
462
471
|
@keyframes trSeekFlash{0%{background:rgba(3,183,156,0.15)}100%{background:transparent}}
|
|
463
472
|
|
|
464
473
|
/* \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:
|
|
474
|
+
.console-panel{border:1px solid var(--bd);border-radius:8px;overflow:hidden;background:var(--bg-1)}
|
|
475
|
+
.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:8px 12px;border-bottom:1px solid var(--bd);background:var(--bg-2)}
|
|
467
476
|
.console-header svg{opacity:.6}
|
|
468
477
|
.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:
|
|
472
|
-
.console-filter-btn{font-size:10px;padding:2px 8px;border-radius:4px;border:1px solid
|
|
473
|
-
.console-filter-btn.active{background:var(--bg-3);color:var(--fg-1);border-color:var(--
|
|
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-
|
|
478
|
+
.console-error-count{color:#f87171;font-weight:500;font-size:10px;text-transform:none;letter-spacing:0;background:rgba(248,113,113,0.1);padding:1px 6px;border-radius:3px}
|
|
479
|
+
.console-warn-count{color:#fbbf24;font-weight:500;font-size:10px;text-transform:none;letter-spacing:0;background:rgba(251,191,36,0.1);padding:1px 6px;border-radius:3px}
|
|
480
|
+
.console-toolbar{display:flex;gap:3px;padding:4px 8px;border-bottom:1px solid var(--bd);flex-wrap:wrap;background:var(--bg-2)}
|
|
481
|
+
.console-filter-btn{font-size:10px;padding:2px 8px;border-radius:4px;border:1px solid transparent;background:transparent;color:var(--fg-2);cursor:pointer;transition:all .15s;font-family:inherit}
|
|
482
|
+
.console-filter-btn.active{background:var(--bg-3);color:var(--fg-1);border-color:var(--bd-m);font-weight:600}
|
|
483
|
+
.console-filter-btn:hover{background:var(--hvr);color:var(--fg-1)}
|
|
484
|
+
.console-list{max-height:400px;overflow-y:auto;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11px;background:var(--bg)}
|
|
485
|
+
.console-list::-webkit-scrollbar{width:5px}.console-list::-webkit-scrollbar-thumb{background:var(--scroll-thumb);border-radius:4px}
|
|
486
|
+
.console-entry{display:flex;align-items:baseline;gap:6px;padding:2px 10px;border-bottom:1px solid var(--bd-xs);line-height:20px}
|
|
477
487
|
.console-entry:hover{background:var(--hvr)}
|
|
478
488
|
.console-level-badge{font-weight:600;font-size:9px;min-width:32px;text-transform:uppercase;letter-spacing:.03em}
|
|
479
489
|
.console-time{color:var(--fg-2);font-size:10px;white-space:nowrap;min-width:65px}
|
|
480
490
|
.console-text{flex:1;word-break:break-word;white-space:pre-wrap;color:var(--fg)}
|
|
481
491
|
.console-loc{color:var(--fg-2);font-size:10px;white-space:nowrap;margin-left:auto;max-width:180px;overflow:hidden;text-overflow:ellipsis}
|
|
492
|
+
.console-entry.seekable{cursor:pointer}
|
|
493
|
+
.console-entry.seekable:hover{background:rgba(3,183,156,0.06)}
|
|
494
|
+
.console-active{background:rgba(3,183,156,0.12) !important;border-left:3px solid #03b79c}
|
|
495
|
+
.console-active .console-text{color:#2dd4a8}
|
|
496
|
+
.console-offset{color:#03b79c;font-size:9px;font-weight:600;min-width:42px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
|
|
482
497
|
.console-level-error,.console-level-stderr{background:rgba(248,113,113,0.06)}
|
|
483
498
|
.console-level-warn{background:rgba(251,191,36,0.06)}
|
|
484
499
|
|
|
@@ -511,42 +526,6 @@ body{
|
|
|
511
526
|
.detail-duration{font-size:20px}
|
|
512
527
|
}
|
|
513
528
|
|
|
514
|
-
/* \u2500\u2500 Test Artifacts Section \u2500\u2500 */
|
|
515
|
-
#artifact-section{margin-top:32px;margin-bottom:32px}
|
|
516
|
-
.as-header{display:flex;align-items:center;gap:10px;margin-bottom:14px}
|
|
517
|
-
.as-title{font-size:14px;font-weight:700;color:var(--fg)}
|
|
518
|
-
.as-total{font-size:11px;color:var(--fg-2);margin-left:auto}
|
|
519
|
-
.as-empty{text-align:center;padding:32px 20px;color:var(--fg-2);font-size:12px;font-style:italic;border:1px dashed var(--bd-m);border-radius:10px}
|
|
520
|
-
.as-runs{border:1px solid var(--bd);border-radius:10px;overflow:hidden;background:var(--bg-1)}
|
|
521
|
-
.as-run{border-bottom:1px solid var(--bd-s)}
|
|
522
|
-
.as-run:last-child{border-bottom:none}
|
|
523
|
-
.as-run-row{display:flex;align-items:center;gap:8px;padding:10px 14px;cursor:pointer;transition:background .1s}
|
|
524
|
-
.as-run-row:hover{background:var(--hvr)}
|
|
525
|
-
.as-run-arrow{font-size:9px;color:var(--fg-2);transition:transform .15s;display:inline-block;flex-shrink:0}
|
|
526
|
-
.as-run.expanded .as-run-arrow{transform:rotate(90deg)}
|
|
527
|
-
.as-run-label{font-size:12px;font-weight:500;color:var(--fg)}
|
|
528
|
-
.as-current-tag{font-size:9px;font-weight:600;padding:1px 6px;border-radius:4px;background:rgba(3,183,156,0.12);color:#2dd4a8;margin-left:4px}
|
|
529
|
-
.as-run-meta{font-size:11px;color:var(--fg-2);margin-left:auto;white-space:nowrap}
|
|
530
|
-
.as-run-legacy .as-run-label{font-style:italic;color:var(--fg-2)}
|
|
531
|
-
.as-run-detail{padding:0 14px 14px;background:var(--bg-2);border-top:1px solid var(--bd-s)}
|
|
532
|
-
.as-no-tests{padding:12px;text-align:center;font-size:11px;color:var(--fg-2);font-style:italic}
|
|
533
|
-
.as-test{padding:8px 0;border-bottom:1px solid var(--bd-xs)}
|
|
534
|
-
.as-test:last-child{border-bottom:none}
|
|
535
|
-
.as-test-name{font-size:11px;font-weight:600;color:var(--fg-1);margin-bottom:6px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
|
|
536
|
-
.as-test-files{display:flex;flex-wrap:wrap;gap:10px}
|
|
537
|
-
.as-file{display:flex;flex-direction:column;gap:4px;max-width:200px}
|
|
538
|
-
.as-thumb{max-width:180px;max-height:120px;border-radius:6px;cursor:pointer;border:1px solid var(--bd);transition:border-color .15s;object-fit:contain}
|
|
539
|
-
.as-thumb:hover{border-color:#03b79c}
|
|
540
|
-
.as-video-wrap{border-radius:6px;overflow:hidden;border:1px solid var(--bd);background:#000;max-width:180px}
|
|
541
|
-
.as-video-wrap video{width:100%;display:block;max-height:120px}
|
|
542
|
-
.as-file-info{font-size:9px;color:var(--fg-2)}
|
|
543
|
-
.as-file-icon{margin-right:4px}
|
|
544
|
-
.as-loading{text-align:center;padding:24px;color:var(--fg-2);font-size:12px}
|
|
545
|
-
.as-delete-btn{font-size:10px;padding:3px 10px;border-radius:4px;border:1px solid rgba(239,68,68,0.3);background:rgba(239,68,68,0.08);color:#ef4444;cursor:pointer;font-weight:500;transition:all .15s;flex-shrink:0}
|
|
546
|
-
.as-delete-btn:hover{background:rgba(239,68,68,0.15);border-color:rgba(239,68,68,0.5)}
|
|
547
|
-
.as-delete-all-btn{font-size:10px;padding:3px 12px;border-radius:4px;border:1px solid rgba(239,68,68,0.3);background:rgba(239,68,68,0.08);color:#ef4444;cursor:pointer;font-weight:600;transition:all .15s}
|
|
548
|
-
.as-delete-all-btn:hover{background:rgba(239,68,68,0.15);border-color:rgba(239,68,68,0.5)}
|
|
549
|
-
|
|
550
529
|
/* \u2500\u2500 Print \u2500\u2500 */
|
|
551
530
|
@media print{
|
|
552
531
|
body{background:#fff;color:#000}
|
|
@@ -571,15 +550,23 @@ body{
|
|
|
571
550
|
::-webkit-scrollbar-corner{background:transparent}
|
|
572
551
|
/* Virtual grid sentinel */
|
|
573
552
|
.vg-sentinel{height:1px}
|
|
574
|
-
|
|
553
|
+
/* \u2500\u2500 Streaming: detail loading / error states \u2500\u2500 */
|
|
554
|
+
.detail-loading{display:flex;flex-direction:column;align-items:center;justify-content:center;padding:48px 20px;gap:14px}
|
|
555
|
+
.detail-loading .loading-spinner{width:28px;height:28px;border:3px solid var(--bd-l);border-top-color:var(--fg-1);border-radius:50%;animation:spin .8s linear infinite}
|
|
556
|
+
.detail-loading .loading-text{font-size:12px;color:var(--fg-2)}
|
|
557
|
+
.detail-error{padding:32px 20px;text-align:center;color:var(--fg-2);font-size:13px;line-height:1.7}
|
|
558
|
+
.detail-error .failure-message{margin-bottom:16px;padding:12px;background:rgba(239,68,68,0.06);border:1px solid rgba(239,68,68,0.15);border-radius:8px;font-size:12px;color:#f87171;text-align:left;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap;word-break:break-word}
|
|
559
|
+
.detail-error code{font-size:11px;padding:2px 6px;background:var(--bg-2);border-radius:4px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
|
|
560
|
+
.server-offline-banner{padding:8px 14px;background:rgba(251,191,36,0.08);border:1px solid rgba(251,191,36,0.2);border-radius:6px;font-size:11px;color:#fbbf24;text-align:center;margin-bottom:12px}
|
|
561
|
+
`;var kt=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 196 247" fill="none">
|
|
575
562
|
<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)"/>
|
|
576
563
|
<defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
|
|
577
564
|
<stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
|
|
578
|
-
</linearGradient></defs></svg>`,
|
|
565
|
+
</linearGradient></defs></svg>`,Tt=`<svg width="32" height="40" viewBox="0 0 196 247" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
579
566
|
<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)"/>
|
|
580
567
|
<defs><linearGradient id="paint0_linear_55_11" x1="98" y1="0.000244141" x2="98" y2="247" gradientUnits="userSpaceOnUse">
|
|
581
568
|
<stop stop-color="#03B79C"/><stop offset="0.504808" stop-color="#4EDAA4"/><stop offset="0.865285" stop-color="#84F3AA"/>
|
|
582
|
-
</linearGradient></defs></svg>`;var
|
|
569
|
+
</linearGradient></defs></svg>`;var Ct=`
|
|
583
570
|
/* \u2500\u2500 Utilities \u2500\u2500 */
|
|
584
571
|
function esc(s){if(!s)return '';return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,''')}
|
|
585
572
|
function stripAnsi(s){return s?s.replace(/\\u001b\\[[0-9;]*m/g,'').replace(/\\x1b\\[[0-9;]*m/g,''):''}
|
|
@@ -627,6 +614,49 @@ body{
|
|
|
627
614
|
return a.startedAt<b.startedAt?-1:1;
|
|
628
615
|
});
|
|
629
616
|
|
|
617
|
+
/* \u2500\u2500 Streaming mode: build tests from compact index \u2500\u2500 */
|
|
618
|
+
if(data.reportMode==='streaming'&&data.index&&data.index.length>0){
|
|
619
|
+
tests=[];testMap={};
|
|
620
|
+
for(var xi=0;xi<data.index.length;xi++){
|
|
621
|
+
var ix=data.index[xi];
|
|
622
|
+
if(ix.isRetry)continue;
|
|
623
|
+
var st={
|
|
624
|
+
testId:ix.id,title:ix.title,status:ix.status,duration:ix.duration,
|
|
625
|
+
filePath:ix.filePath,tags:ix.tags||[],isFlaky:ix.status==='flaky',
|
|
626
|
+
testType:'e2e',retryCount:0,suiteName:'',
|
|
627
|
+
startedAt:'',completedAt:'',
|
|
628
|
+
networkRequests:[],steps:[],apiCalls:[],actions:[],consoleLogs:[],
|
|
629
|
+
artifacts:null,failure:null,retryStatus:null,expectedStatus:null,actualStatus:null,
|
|
630
|
+
hasNetworkData:ix.hasNetworkData,hasConsoleData:ix.hasConsoleData,
|
|
631
|
+
hasActionSteps:ix.hasActionSteps,hasArtifacts:ix.hasArtifacts,
|
|
632
|
+
errorMessage:ix.errorMessage,networkCount:ix.networkCount||0,
|
|
633
|
+
consoleCount:ix.consoleCount||0,actionCount:ix.actionCount||0
|
|
634
|
+
};
|
|
635
|
+
testMap[st.testId]=st;
|
|
636
|
+
tests.push(st);
|
|
637
|
+
}
|
|
638
|
+
tests.sort(function(a,b){
|
|
639
|
+
if(a.filePath!==b.filePath)return a.filePath<b.filePath?-1:1;
|
|
640
|
+
return 0;
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/* \u2500\u2500 Streaming detail cache (LRU, max 50 entries) \u2500\u2500 */
|
|
645
|
+
var _detailCache={};
|
|
646
|
+
var _detailCacheKeys=[];
|
|
647
|
+
var _detailCacheMax=50;
|
|
648
|
+
function cacheDetail(testId,data){
|
|
649
|
+
if(_detailCache[testId]){
|
|
650
|
+
var ki=_detailCacheKeys.indexOf(testId);
|
|
651
|
+
if(ki>-1)_detailCacheKeys.splice(ki,1);
|
|
652
|
+
}else if(_detailCacheKeys.length>=_detailCacheMax){
|
|
653
|
+
var evict=_detailCacheKeys.shift();
|
|
654
|
+
delete _detailCache[evict];
|
|
655
|
+
}
|
|
656
|
+
_detailCache[testId]=data;
|
|
657
|
+
_detailCacheKeys.push(testId);
|
|
658
|
+
}
|
|
659
|
+
|
|
630
660
|
/* \u2500\u2500 State \u2500\u2500 */
|
|
631
661
|
var searchQuery='';
|
|
632
662
|
|
|
@@ -800,8 +830,8 @@ body{
|
|
|
800
830
|
}
|
|
801
831
|
|
|
802
832
|
/* \u2500\u2500 Render: Drawer Content \u2500\u2500 */
|
|
803
|
-
function renderDrawer(testId){
|
|
804
|
-
var t=testMap[testId];
|
|
833
|
+
function renderDrawer(testId,detail){
|
|
834
|
+
var t=detail||testMap[testId];
|
|
805
835
|
if(!t){drawerBodyEl.innerHTML='';return;}
|
|
806
836
|
var h='<div class="test-detail">';
|
|
807
837
|
|
|
@@ -820,7 +850,7 @@ body{
|
|
|
820
850
|
h+='</div><div class="detail-duration">'+fmtDur(t.duration)+'</div></div></div>';
|
|
821
851
|
|
|
822
852
|
/* \u2500\u2500 Failure panel (full width) \u2500\u2500 */
|
|
823
|
-
if((t.status==='failed'||t.status==='flaky')&&t.failure)h+=renderFailure(t.failure);
|
|
853
|
+
if((t.status==='failed'||t.status==='flaky')&&t.failure)h+=renderFailure(t.failure,t.filePath,t.title,t.tags);
|
|
824
854
|
else if(t.status==='failed'&&!t.failure)h+='<div style="margin-bottom:20px;padding:14px;background:var(--bg-2);border:1px solid var(--bd);border-radius:10px;font-size:12px;color:var(--fg-2);font-style:italic">No diagnostic information available</div>';
|
|
825
855
|
|
|
826
856
|
/* \u2500\u2500 Stacked sections: 1) Artifacts 2) Timeline / Network 3) API Calls \u2500\u2500 */
|
|
@@ -830,12 +860,16 @@ body{
|
|
|
830
860
|
var hasActions=t.actions&&t.actions.length>0;
|
|
831
861
|
var hasConsoleLogs=t.consoleLogs&&t.consoleLogs.length>0;
|
|
832
862
|
var hasVideo=!!(t.artifacts&&t.artifacts.video);
|
|
863
|
+
/* Compute base time for video offset calculation (console/network) */
|
|
864
|
+
var baseTime=0;
|
|
865
|
+
if(hasVideo&&t.startedAt){baseTime=Date.parse(t.startedAt);}
|
|
866
|
+
if(!baseTime&&hasVideo&&t.consoleLogs&&t.consoleLogs.length>0&&t.consoleLogs[0].timestamp){baseTime=Date.parse(t.consoleLogs[0].timestamp);}
|
|
833
867
|
if(hasArt||hasSteps||hasApiCalls||hasActions||hasConsoleLogs){
|
|
834
868
|
h+='<div class="drawer-sections">';
|
|
835
869
|
if(hasArt)h+='<div class="drawer-section">'+renderArtifactColumn(t.artifacts)+'</div>';
|
|
836
870
|
if(hasActions)h+='<div class="drawer-section">'+renderActionsColumn(t.actions,hasVideo)+'</div>';
|
|
837
|
-
if(hasSteps)h+='<div class="drawer-section">'+renderTimelineColumn(t.steps,t.networkRequests,t.consoleLogs,t.testType)+'</div>';
|
|
838
|
-
if(!hasSteps&&hasConsoleLogs)h+='<div class="drawer-section">'+renderConsoleColumn(t.consoleLogs,t.testType)+'</div>';
|
|
871
|
+
if(hasSteps)h+='<div class="drawer-section">'+renderTimelineColumn(t.steps,t.networkRequests,t.consoleLogs,t.testType,hasVideo,baseTime)+'</div>';
|
|
872
|
+
if(!hasSteps&&hasConsoleLogs)h+='<div class="drawer-section">'+renderConsoleColumn(t.consoleLogs,t.testType,hasVideo,baseTime)+'</div>';
|
|
839
873
|
if(hasApiCalls)h+='<div class="drawer-section">'+renderApiCallsColumn(t.apiCalls)+'</div>';
|
|
840
874
|
h+='</div>';
|
|
841
875
|
}
|
|
@@ -849,6 +883,43 @@ body{
|
|
|
849
883
|
|
|
850
884
|
/* \u2500\u2500 Drawer open / close \u2500\u2500 */
|
|
851
885
|
function openDrawer(testId){
|
|
886
|
+
if(data.reportMode==='streaming'){
|
|
887
|
+
drawerEl.classList.add('open');
|
|
888
|
+
drawerBackdropEl.classList.add('open');
|
|
889
|
+
document.body.style.overflow='hidden';
|
|
890
|
+
if(_detailCache[testId]){renderDrawer(testId,_detailCache[testId]);return;}
|
|
891
|
+
drawerBodyEl.innerHTML='<div class="detail-loading"><div class="loading-spinner"></div><div class="loading-text">Loading test details...</div></div>';
|
|
892
|
+
if(window.__trStreamingFetchDetail){
|
|
893
|
+
window.__trStreamingFetchDetail(testId,function(err,detail){
|
|
894
|
+
if(err){
|
|
895
|
+
var t=testMap[testId];
|
|
896
|
+
var emsg=t&&t.errorMessage?'<div class="failure-message">'+esc(t.errorMessage)+'</div>':'';
|
|
897
|
+
drawerBodyEl.innerHTML='<div class="detail-error">'+emsg+'<p>Server unavailable — run <code>npx testrelic serve <path></code> to view full details</p></div>';
|
|
898
|
+
return;
|
|
899
|
+
}
|
|
900
|
+
/* Merge index entry (title, status, duration, tags, etc.) with server detail (network, console, actions, etc.) */
|
|
901
|
+
var idx=testMap[testId]||{};
|
|
902
|
+
var merged={};
|
|
903
|
+
var k;for(k in idx){if(idx.hasOwnProperty(k))merged[k]=idx[k];}
|
|
904
|
+
merged.networkRequests=detail.networkRequests||[];
|
|
905
|
+
merged.consoleLogs=detail.consoleLogs||[];
|
|
906
|
+
merged.actions=detail.actions||[];
|
|
907
|
+
merged.apiCalls=detail.apiCalls||[];
|
|
908
|
+
merged.apiAssertions=detail.apiAssertions||[];
|
|
909
|
+
merged.artifacts=detail.artifacts||null;
|
|
910
|
+
merged.failure=detail.failureDiagnostic||detail.failure||null;
|
|
911
|
+
merged.steps=detail.navigations||[];
|
|
912
|
+
if(detail.startedAt)merged.startedAt=detail.startedAt;
|
|
913
|
+
cacheDetail(testId,merged);
|
|
914
|
+
renderDrawer(testId,merged);
|
|
915
|
+
});
|
|
916
|
+
}else{
|
|
917
|
+
var t=testMap[testId];
|
|
918
|
+
var emsg=t&&t.errorMessage?'<div class="failure-message">'+esc(t.errorMessage)+'</div>':'';
|
|
919
|
+
drawerBodyEl.innerHTML='<div class="detail-error">'+emsg+'<p>Server unavailable — run <code>npx testrelic serve <path></code> to view full details</p></div>';
|
|
920
|
+
}
|
|
921
|
+
return;
|
|
922
|
+
}
|
|
852
923
|
renderDrawer(testId);
|
|
853
924
|
drawerEl.classList.add('open');
|
|
854
925
|
drawerBackdropEl.classList.add('open');
|
|
@@ -869,7 +940,7 @@ body{
|
|
|
869
940
|
clearTimeout(_searchTimer);
|
|
870
941
|
_searchTimer=setTimeout(function(){searchQuery=q;applyFilters();},150);
|
|
871
942
|
}
|
|
872
|
-
`;var
|
|
943
|
+
`;var St=`
|
|
873
944
|
/* \u2500\u2500 Network Visualization Helpers \u2500\u2500 */
|
|
874
945
|
var RES_COLORS={xhr:'#60a5fa',document:'#818cf8',script:'#fbbf24',stylesheet:'#a78bfa',image:'#34d399',font:'#f472b6',other:'#6b7280'};
|
|
875
946
|
var RES_LABELS={xhr:'XHR',document:'Doc',script:'JS',stylesheet:'CSS',image:'Img',font:'Font',other:'Other'};
|
|
@@ -1004,9 +1075,18 @@ body{
|
|
|
1004
1075
|
}
|
|
1005
1076
|
|
|
1006
1077
|
var NDT_ROW_H=32;
|
|
1078
|
+
var NDT_DETAIL_H=280;
|
|
1007
1079
|
var NDT_VBUF=30;
|
|
1008
1080
|
|
|
1009
|
-
function
|
|
1081
|
+
function ndtVideoOffset(req,baseTime){
|
|
1082
|
+
if(!baseTime||!req.startedAt)return -1;
|
|
1083
|
+
var t=Date.parse(req.startedAt);
|
|
1084
|
+
if(isNaN(t))return -1;
|
|
1085
|
+
var off=(t-baseTime)/1000;
|
|
1086
|
+
return off>=0?off:-1;
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
function renderNetworkDevTools(reqs,hasVideo,baseTime){
|
|
1010
1090
|
if(!reqs||reqs.length===0)return '<div class="artifact-empty">No network requests captured</div>';
|
|
1011
1091
|
var uid='ndt-'+Math.random().toString(36).substr(2,6);
|
|
1012
1092
|
var h='<div class="ndt" id="'+uid+'">';
|
|
@@ -1031,6 +1111,12 @@ body{
|
|
|
1031
1111
|
h+='<div class="ndt-vspacer" style="height:'+(reqs.length*NDT_ROW_H)+'px;position:relative"></div>';
|
|
1032
1112
|
h+='</div></div>';
|
|
1033
1113
|
|
|
1114
|
+
/* Pre-compute video offsets */
|
|
1115
|
+
var ndtVideoOffsets=[];
|
|
1116
|
+
if(hasVideo&&baseTime){
|
|
1117
|
+
for(var noi=0;noi<reqs.length;noi++){ndtVideoOffsets.push(ndtVideoOffset(reqs[noi],baseTime));}
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1034
1120
|
/* Store reqs data for virtual rendering */
|
|
1035
1121
|
setTimeout(function(){
|
|
1036
1122
|
var el=document.getElementById(uid);if(!el)return;
|
|
@@ -1039,31 +1125,95 @@ body{
|
|
|
1039
1125
|
var allReqs=reqs;
|
|
1040
1126
|
var filteredIdxs=null;
|
|
1041
1127
|
var openIdx=-1;
|
|
1128
|
+
var openTab='general';
|
|
1129
|
+
var highlightIdx=-1;
|
|
1042
1130
|
|
|
1043
1131
|
function getVisible(){return filteredIdxs||allReqs.map(function(_,i){return i});}
|
|
1044
1132
|
|
|
1133
|
+
var lastDetailH=NDT_DETAIL_H;
|
|
1134
|
+
var NDT_TABS=['general','req-headers','req-body','res-headers','res-body'];
|
|
1135
|
+
|
|
1136
|
+
function renderDetailWithTab(r,ri,activeTab){
|
|
1137
|
+
var html=renderNdtDetail(r,ri);
|
|
1138
|
+
/* Replace the default active tab/pane with the tracked one */
|
|
1139
|
+
if(activeTab&&activeTab!=='general'){
|
|
1140
|
+
/* Remove default active from general tab button and pane */
|
|
1141
|
+
html=html.replace('data-ndt-tab="general" data-ndt-target','data-ndt-tab="general" data-ndt-target');
|
|
1142
|
+
/* Swap active classes: remove from general, add to activeTab */
|
|
1143
|
+
var parts=html;
|
|
1144
|
+
/* Tabs: remove active from all, add to target */
|
|
1145
|
+
for(var t=0;t<NDT_TABS.length;t++){
|
|
1146
|
+
var tn=NDT_TABS[t];
|
|
1147
|
+
var isAct=tn===activeTab;
|
|
1148
|
+
parts=parts.replace(new RegExp('class="ndt-detail-tab'+(tn==='general'?' active':'')+'" data-ndt-tab="'+tn+'"'),'class="ndt-detail-tab'+(isAct?' active':'')+'" data-ndt-tab="'+tn+'"');
|
|
1149
|
+
}
|
|
1150
|
+
/* Panes: remove active from all, add to target */
|
|
1151
|
+
for(var p=0;p<NDT_TABS.length;p++){
|
|
1152
|
+
var pn=NDT_TABS[p];
|
|
1153
|
+
var isPAct=pn===activeTab;
|
|
1154
|
+
parts=parts.replace(new RegExp('class="ndt-detail-pane'+(pn==='general'?' active':'')+'" data-ndt-pane="'+pn+'"'),'class="ndt-detail-pane'+(isPAct?' active':'')+'" data-ndt-pane="'+pn+'"');
|
|
1155
|
+
}
|
|
1156
|
+
html=parts;
|
|
1157
|
+
}
|
|
1158
|
+
return html.replace('class="ndt-detail"','class="ndt-detail show"');
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1045
1161
|
function paint(){
|
|
1046
1162
|
var vis=getVisible();
|
|
1047
|
-
|
|
1163
|
+
/* Find the visual index of the open row (if any) */
|
|
1164
|
+
var openVi=-1;
|
|
1165
|
+
if(openIdx>=0){for(var oi=0;oi<vis.length;oi++){if(vis[oi]===openIdx){openVi=oi;break;}}}
|
|
1166
|
+
var detailExtra=openVi>=0?lastDetailH:0;
|
|
1167
|
+
var totalH=vis.length*NDT_ROW_H+detailExtra;
|
|
1168
|
+
spacer.style.height=totalH+'px';
|
|
1048
1169
|
var st=list.scrollTop;var vh=list.clientHeight;
|
|
1049
1170
|
var startRow=Math.max(0,Math.floor(st/NDT_ROW_H)-NDT_VBUF);
|
|
1050
|
-
var endRow=Math.min(vis.length,Math.ceil((st+vh)/NDT_ROW_H)+NDT_VBUF);
|
|
1171
|
+
var endRow=Math.min(vis.length,Math.ceil((st+vh+detailExtra)/NDT_ROW_H)+NDT_VBUF);
|
|
1051
1172
|
var out='';
|
|
1052
1173
|
for(var vi=startRow;vi<endRow;vi++){
|
|
1053
1174
|
var ri=vis[vi];var r=allReqs[ri];
|
|
1054
1175
|
var isFail=r.statusCode>=400||r.statusCode===0;
|
|
1055
1176
|
var isOpen=ri===openIdx;
|
|
1056
|
-
|
|
1177
|
+
var isActive=ri===highlightIdx;
|
|
1178
|
+
var off=ndtVideoOffsets[ri];
|
|
1179
|
+
var seekable=off>=0;
|
|
1180
|
+
/* Rows after the open row shift down by the detail panel height */
|
|
1181
|
+
var rowTop=vi*NDT_ROW_H+(openVi>=0&&vi>openVi?lastDetailH:0);
|
|
1182
|
+
out+='<div class="ndt-row'+(isFail?' ndt-row--fail':'')+(isOpen?' ndt-row--open':'')+(seekable?' seekable':'')+(isActive?' ndt-row--active':'')+'" data-ndt-idx="'+ri+'" data-ndt-type="'+esc(r.resourceType)+'" data-ndt-url="'+esc(r.url.toLowerCase())+'"'+(seekable?' data-offset="'+off.toFixed(2)+'"':'')+' style="position:absolute;top:'+rowTop+'px;left:0;right:0;height:'+NDT_ROW_H+'px">';
|
|
1057
1183
|
out+='<span class="ndt-status '+ndtStatusClass(r.statusCode)+'">'+r.statusCode+'</span>';
|
|
1058
1184
|
out+='<span class="ndt-method">'+esc(r.method)+'</span>';
|
|
1059
1185
|
out+='<span class="ndt-url" title="'+esc(r.url)+'">'+esc(urlPath(r.url))+'</span>';
|
|
1060
1186
|
out+='<span class="ndt-type">'+esc(RES_LABELS[r.resourceType]||r.resourceType)+'</span>';
|
|
1061
1187
|
out+='<span class="ndt-size">'+fmtBytes(r.responseSize||0)+'</span>';
|
|
1062
|
-
out+='<span class="ndt-time">'+
|
|
1188
|
+
if(seekable){out+='<span class="ndt-time ndt-offset">'+off.toFixed(1)+'s</span>';}
|
|
1189
|
+
else{out+='<span class="ndt-time">'+fmtDur(r.responseTimeMs)+'</span>';}
|
|
1063
1190
|
out+='</div>';
|
|
1064
|
-
if(isOpen){out+=
|
|
1191
|
+
if(isOpen){out+='<div style="position:absolute;top:'+(rowTop+NDT_ROW_H)+'px;left:0;right:0;z-index:1" class="ndt-detail-wrap">'+renderDetailWithTab(r,ri,openTab)+'</div>';}
|
|
1065
1192
|
}
|
|
1066
1193
|
spacer.innerHTML=out;
|
|
1194
|
+
/* Measure actual detail height and adjust layout without full repaint */
|
|
1195
|
+
if(openVi>=0){
|
|
1196
|
+
var detailWrap=spacer.querySelector('.ndt-detail-wrap');
|
|
1197
|
+
if(detailWrap){
|
|
1198
|
+
var measuredH=detailWrap.offsetHeight;
|
|
1199
|
+
if(measuredH>0&&Math.abs(measuredH-lastDetailH)>2){
|
|
1200
|
+
lastDetailH=measuredH;
|
|
1201
|
+
/* Update spacer height and row positions without re-rendering */
|
|
1202
|
+
var newTotalH=vis.length*NDT_ROW_H+lastDetailH;
|
|
1203
|
+
spacer.style.height=newTotalH+'px';
|
|
1204
|
+
var rows=spacer.querySelectorAll('.ndt-row');
|
|
1205
|
+
for(var rr=0;rr<rows.length;rr++){
|
|
1206
|
+
var rrIdx=parseInt(rows[rr].getAttribute('data-ndt-idx'),10);
|
|
1207
|
+
/* Find visual index for this row */
|
|
1208
|
+
for(var rv=startRow;rv<endRow;rv++){if(vis[rv]===rrIdx){
|
|
1209
|
+
if(rv>openVi){rows[rr].style.top=(rv*NDT_ROW_H+lastDetailH)+'px';}
|
|
1210
|
+
break;
|
|
1211
|
+
}}
|
|
1212
|
+
}
|
|
1213
|
+
detailWrap.style.top=((openVi*NDT_ROW_H)+NDT_ROW_H)+'px';
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1067
1217
|
var countEl=el.querySelector('.ndt-count');
|
|
1068
1218
|
if(countEl)countEl.textContent=vis.length+(vis.length!==allReqs.length?' / '+allReqs.length:'')+' requests';
|
|
1069
1219
|
}
|
|
@@ -1073,9 +1223,54 @@ body{
|
|
|
1073
1223
|
|
|
1074
1224
|
/* Click handler for rows */
|
|
1075
1225
|
list.addEventListener('click',function(e){
|
|
1226
|
+
var tab=e.target.closest('.ndt-detail-tab');
|
|
1227
|
+
if(tab){
|
|
1228
|
+
/* Handle tab switch within detail panel \u2014 DOM-only, no repaint */
|
|
1229
|
+
e.stopPropagation();
|
|
1230
|
+
var tgt=tab.getAttribute('data-ndt-target');
|
|
1231
|
+
var pane=tab.getAttribute('data-ndt-tab');
|
|
1232
|
+
openTab=pane;
|
|
1233
|
+
var det=document.getElementById(tgt);
|
|
1234
|
+
if(det){
|
|
1235
|
+
var tabs=det.querySelectorAll('.ndt-detail-tab');
|
|
1236
|
+
for(var ti=0;ti<tabs.length;ti++)tabs[ti].classList.remove('active');
|
|
1237
|
+
tab.classList.add('active');
|
|
1238
|
+
var panes=det.querySelectorAll('.ndt-detail-pane');
|
|
1239
|
+
for(var pi=0;pi<panes.length;pi++)panes[pi].classList.remove('active');
|
|
1240
|
+
var tp=det.querySelector('[data-ndt-pane="'+pane+'"]');
|
|
1241
|
+
if(tp)tp.classList.add('active');
|
|
1242
|
+
/* Re-measure after tab switch since pane height may differ */
|
|
1243
|
+
requestAnimationFrame(function(){
|
|
1244
|
+
var detailWrap=spacer.querySelector('.ndt-detail-wrap');
|
|
1245
|
+
if(detailWrap){
|
|
1246
|
+
var mh=detailWrap.offsetHeight;
|
|
1247
|
+
if(mh>0&&Math.abs(mh-lastDetailH)>2){
|
|
1248
|
+
lastDetailH=mh;
|
|
1249
|
+
/* Adjust layout without full repaint to preserve tab state */
|
|
1250
|
+
var vis=getVisible();
|
|
1251
|
+
var ovi=-1;
|
|
1252
|
+
for(var oi=0;oi<vis.length;oi++){if(vis[oi]===openIdx){ovi=oi;break;}}
|
|
1253
|
+
spacer.style.height=(vis.length*NDT_ROW_H+lastDetailH)+'px';
|
|
1254
|
+
var rows=spacer.querySelectorAll('.ndt-row');
|
|
1255
|
+
for(var rr=0;rr<rows.length;rr++){
|
|
1256
|
+
var rrIdx=parseInt(rows[rr].getAttribute('data-ndt-idx'),10);
|
|
1257
|
+
for(var rv=0;rv<vis.length;rv++){if(vis[rv]===rrIdx){
|
|
1258
|
+
if(rv>ovi){rows[rr].style.top=(rv*NDT_ROW_H+lastDetailH)+'px';}
|
|
1259
|
+
break;
|
|
1260
|
+
}}
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
});
|
|
1265
|
+
}
|
|
1266
|
+
return;
|
|
1267
|
+
}
|
|
1076
1268
|
var row=e.target.closest('.ndt-row');if(!row)return;
|
|
1269
|
+
e.stopPropagation();
|
|
1077
1270
|
var idx=parseInt(row.getAttribute('data-ndt-idx'),10);
|
|
1078
1271
|
openIdx=openIdx===idx?-1:idx;
|
|
1272
|
+
openTab='general';
|
|
1273
|
+
lastDetailH=NDT_DETAIL_H;
|
|
1079
1274
|
paint();
|
|
1080
1275
|
});
|
|
1081
1276
|
|
|
@@ -1097,12 +1292,35 @@ body{
|
|
|
1097
1292
|
paint();
|
|
1098
1293
|
};
|
|
1099
1294
|
|
|
1295
|
+
/* Video sync: scroll to matching request by time */
|
|
1296
|
+
if(ndtVideoOffsets.length){
|
|
1297
|
+
el.__videoSync=function(seconds){
|
|
1298
|
+
var vis=getVisible();
|
|
1299
|
+
var matchVi=-1;
|
|
1300
|
+
for(var i=vis.length-1;i>=0;i--){
|
|
1301
|
+
if(ndtVideoOffsets[vis[i]]>=0&&ndtVideoOffsets[vis[i]]<=seconds){matchVi=i;break;}
|
|
1302
|
+
}
|
|
1303
|
+
if(matchVi<0){highlightIdx=-1;paint();return;}
|
|
1304
|
+
var newHL=vis[matchVi];
|
|
1305
|
+
if(newHL===highlightIdx)return;
|
|
1306
|
+
highlightIdx=newHL;
|
|
1307
|
+
var syncOpenVi=-1;
|
|
1308
|
+
if(openIdx>=0){var svis=getVisible();for(var si=0;si<svis.length;si++){if(svis[si]===openIdx){syncOpenVi=si;break;}}}
|
|
1309
|
+
var rowTop=matchVi*NDT_ROW_H+(syncOpenVi>=0&&matchVi>syncOpenVi?lastDetailH:0);
|
|
1310
|
+
var vh=list.clientHeight;
|
|
1311
|
+
if(rowTop<list.scrollTop||rowTop>list.scrollTop+vh-NDT_ROW_H){
|
|
1312
|
+
list.scrollTop=rowTop-vh/2;
|
|
1313
|
+
}
|
|
1314
|
+
paint();
|
|
1315
|
+
};
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1100
1318
|
paint();
|
|
1101
1319
|
},0);
|
|
1102
1320
|
return h;
|
|
1103
1321
|
}
|
|
1104
1322
|
|
|
1105
|
-
function renderTimelineColumn(steps,networkRequests,consoleLogs,testType){
|
|
1323
|
+
function renderTimelineColumn(steps,networkRequests,consoleLogs,testType,hasVideo,baseTime){
|
|
1106
1324
|
if(!steps||steps.length===0)return '<div class="artifact-empty">No navigation data</div>';
|
|
1107
1325
|
var hasReqs=networkRequests&&networkRequests.length>0;
|
|
1108
1326
|
var hasCLogs=consoleLogs&&consoleLogs.length>0;
|
|
@@ -1112,20 +1330,71 @@ body{
|
|
|
1112
1330
|
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>';
|
|
1113
1331
|
h+='</div>';
|
|
1114
1332
|
h+='<div class="seg-pane active" data-seg-pane="timeline">'+renderNavTimeline(steps)+'</div>';
|
|
1115
|
-
if(hasCLogs)h+='<div class="seg-pane" data-seg-pane="console">'+renderConsoleColumn(consoleLogs,testType)+'</div>';
|
|
1116
|
-
h+='<div class="seg-pane" data-seg-pane="network">'+renderNetworkDevTools(networkRequests)+'</div>';
|
|
1333
|
+
if(hasCLogs)h+='<div class="seg-pane" data-seg-pane="console">'+renderConsoleColumn(consoleLogs,testType,hasVideo,baseTime)+'</div>';
|
|
1334
|
+
h+='<div class="seg-pane" data-seg-pane="network">'+renderNetworkDevTools(networkRequests,hasVideo,baseTime)+'</div>';
|
|
1117
1335
|
return h;
|
|
1118
1336
|
}
|
|
1119
1337
|
|
|
1120
|
-
function renderFailure(failure){
|
|
1338
|
+
function renderFailure(failure,filePath,testName,tags){
|
|
1121
1339
|
if(!failure)return '';
|
|
1122
1340
|
var sid='s-'+Math.random().toString(36).substr(2,8);
|
|
1123
|
-
var
|
|
1341
|
+
var cpid='cp-'+Math.random().toString(36).substr(2,8);
|
|
1342
|
+
var h='<div class="failure-panel"><div class="failure-panel-header"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M15 9l-6 6M9 9l6 6"/></svg>Failure Details<button class="copy-prompt-btn" id="'+cpid+'"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>Copy Prompt</button></div>';
|
|
1124
1343
|
h+='<div class="failure-message">'+esc(stripAnsi(failure.message))+'</div>';
|
|
1125
1344
|
if(failure.code)h+=renderCodeSnippet(failure.code);
|
|
1126
1345
|
if(failure.line!==null&&failure.line!==undefined)h+='<div class="line-marker">Line '+failure.line+'</div>';
|
|
1127
1346
|
if(failure.stack){h+='<button class="stack-toggle-btn" data-stack="'+sid+'">Show stack trace</button><div class="stack-trace" id="'+sid+'">'+esc(stripAnsi(failure.stack))+'</div>';}
|
|
1128
|
-
h+='</div>';
|
|
1347
|
+
h+='</div>';
|
|
1348
|
+
/* Wire up Copy Prompt button after render */
|
|
1349
|
+
setTimeout(function(){
|
|
1350
|
+
var btn=document.getElementById(cpid);
|
|
1351
|
+
if(!btn)return;
|
|
1352
|
+
btn.addEventListener('click',function(e){
|
|
1353
|
+
e.stopPropagation();
|
|
1354
|
+
var nl=String.fromCharCode(10);
|
|
1355
|
+
var ticks=String.fromCharCode(96,96,96);
|
|
1356
|
+
var msg=failure.message?stripAnsi(failure.message):'Unknown error';
|
|
1357
|
+
var tname=testName||'Unknown test';
|
|
1358
|
+
var tline=(failure.line!==null&&failure.line!==undefined)?String(failure.line):'unknown';
|
|
1359
|
+
var ttags=(tags&&tags.length>0)?tags.join(', '):'none';
|
|
1360
|
+
var fp=filePath||'unknown';
|
|
1361
|
+
/* Escape regex special chars in test name for --grep */
|
|
1362
|
+
function escGrep(s){return s.replace(/[.*+?^]/g,'\\\\$&').replace(/[()]/g,'\\\\$&');}
|
|
1363
|
+
var tnameEsc=escGrep(tname);
|
|
1364
|
+
var p='You are a Playwright test repair agent. A test in this codebase has failed. Your job is to fix the code and verify the fix passes.'+nl+nl;
|
|
1365
|
+
p+='## Failed Test'+nl+nl;
|
|
1366
|
+
p+='- **File:** '+fp+nl;
|
|
1367
|
+
p+='- **Test Name:** '+tname+nl;
|
|
1368
|
+
p+='- **Line:** '+tline+nl;
|
|
1369
|
+
p+='- **Tags:** '+ttags+nl+nl;
|
|
1370
|
+
p+='## Error'+nl+nl;
|
|
1371
|
+
p+=msg+nl+nl;
|
|
1372
|
+
if(failure.code){
|
|
1373
|
+
p+='## Failing Code'+nl+nl;
|
|
1374
|
+
p+=ticks+'typescript'+nl+stripAnsi(failure.code)+nl+ticks+nl+nl;
|
|
1375
|
+
}
|
|
1376
|
+
if(failure.stack){
|
|
1377
|
+
p+='## Stack Trace'+nl+nl;
|
|
1378
|
+
p+=ticks+nl+stripAnsi(failure.stack)+nl+ticks+nl+nl;
|
|
1379
|
+
}
|
|
1380
|
+
p+='## Your Task'+nl+nl;
|
|
1381
|
+
p+='1. Analyze the error and identify the root cause'+nl;
|
|
1382
|
+
p+='2. Edit '+ticks+fp+ticks+' to fix the failing assertion or logic '+String.fromCharCode(8212)+' do not delete the test'+nl;
|
|
1383
|
+
p+='3. Run the specific test to verify the fix: '+ticks+'npx playwright test '+fp+' --grep "'+tnameEsc+'" --reporter=line'+ticks+nl;
|
|
1384
|
+
p+='4. If the test passes, run the full file to confirm no regressions: '+ticks+'npx playwright test '+fp+' --reporter=line'+ticks+nl;
|
|
1385
|
+
p+='5. Stop only when the test exits with status '+ticks+'passed'+ticks+nl+nl;
|
|
1386
|
+
p+='## Constraints'+nl+nl;
|
|
1387
|
+
p+='- Only modify '+ticks+fp+ticks+nl;
|
|
1388
|
+
p+='- Do not alter shared fixtures, helpers, or '+ticks+'playwright.config.ts'+ticks+nl;
|
|
1389
|
+
p+='- Do not skip or remove the test'+nl;
|
|
1390
|
+
navigator.clipboard.writeText(p).then(function(){
|
|
1391
|
+
btn.innerHTML='<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 6L9 17l-5-5"/></svg>Copied!';
|
|
1392
|
+
btn.classList.add('copied');
|
|
1393
|
+
setTimeout(function(){btn.innerHTML='<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1"/></svg>Copy Prompt';btn.classList.remove('copied');},2000);
|
|
1394
|
+
});
|
|
1395
|
+
});
|
|
1396
|
+
},0);
|
|
1397
|
+
return h;
|
|
1129
1398
|
}
|
|
1130
1399
|
|
|
1131
1400
|
/* \u2500\u2500 Network DevTools Filter Logic \u2500\u2500 */
|
|
@@ -1238,7 +1507,7 @@ body{
|
|
|
1238
1507
|
var countEl=ndt.querySelector('.ndt-count');
|
|
1239
1508
|
if(countEl)countEl.textContent=visible+' / '+rows.length+' requests';
|
|
1240
1509
|
}
|
|
1241
|
-
`;var
|
|
1510
|
+
`;var Rt=`
|
|
1242
1511
|
var _filterState={status:{},type:{},specFile:{}};
|
|
1243
1512
|
var _totalTests=0;
|
|
1244
1513
|
var _originalSummary=null;
|
|
@@ -1409,7 +1678,7 @@ function _updateCard(cls,val){
|
|
|
1409
1678
|
var el=document.querySelector('.'+cls+' .s-count');
|
|
1410
1679
|
if(el)el.textContent=''+val;
|
|
1411
1680
|
}
|
|
1412
|
-
`;var
|
|
1681
|
+
`;var At=`
|
|
1413
1682
|
/* \u2500\u2500 Event Delegation \u2500\u2500 */
|
|
1414
1683
|
document.addEventListener('click',function(e){
|
|
1415
1684
|
var target=e.target;
|
|
@@ -1553,37 +1822,6 @@ function _updateCard(cls,val){
|
|
|
1553
1822
|
return;
|
|
1554
1823
|
}
|
|
1555
1824
|
|
|
1556
|
-
/* Artifact section: run row toggle */
|
|
1557
|
-
var artToggle=target.closest('[data-artifact-toggle]');
|
|
1558
|
-
if(artToggle){
|
|
1559
|
-
var idx=artToggle.getAttribute('data-artifact-toggle');
|
|
1560
|
-
var detail=document.getElementById('as-run-detail-'+idx);
|
|
1561
|
-
var runEl=artToggle.closest('.as-run');
|
|
1562
|
-
if(detail){
|
|
1563
|
-
var isOpen=detail.style.display!=='none';
|
|
1564
|
-
detail.style.display=isOpen?'none':'block';
|
|
1565
|
-
if(runEl)runEl.classList.toggle('expanded',!isOpen);
|
|
1566
|
-
}
|
|
1567
|
-
return;
|
|
1568
|
-
}
|
|
1569
|
-
|
|
1570
|
-
/* Artifact section: delete single run */
|
|
1571
|
-
var deleteBtn=target.closest('[data-artifact-action="delete"]');
|
|
1572
|
-
if(deleteBtn){
|
|
1573
|
-
e.stopPropagation();
|
|
1574
|
-
var folder=deleteBtn.getAttribute('data-run-folder');
|
|
1575
|
-
var isCurrent=deleteBtn.getAttribute('data-is-current')==='true';
|
|
1576
|
-
if(folder&&typeof deleteArtifactRun==='function')deleteArtifactRun(folder,isCurrent);
|
|
1577
|
-
return;
|
|
1578
|
-
}
|
|
1579
|
-
|
|
1580
|
-
/* Artifact section: delete all */
|
|
1581
|
-
var deleteAllBtn=target.closest('[data-artifact-action="delete-all"]');
|
|
1582
|
-
if(deleteAllBtn){
|
|
1583
|
-
if(typeof deleteAllArtifacts==='function')deleteAllArtifacts();
|
|
1584
|
-
return;
|
|
1585
|
-
}
|
|
1586
|
-
|
|
1587
1825
|
/* Stack trace toggle */
|
|
1588
1826
|
if(target.classList.contains('stack-toggle-btn')){var se=document.getElementById(target.getAttribute('data-stack'));if(se){var sv=se.classList.toggle('show');target.textContent=sv?'Hide stack trace':'Show stack trace';}return;}
|
|
1589
1827
|
|
|
@@ -1641,42 +1879,58 @@ function _updateCard(cls,val){
|
|
|
1641
1879
|
var b=document.querySelector('.lightbox-close');if(b)b.remove();
|
|
1642
1880
|
}
|
|
1643
1881
|
|
|
1644
|
-
/* \u2500\u2500 Video \u2194
|
|
1882
|
+
/* \u2500\u2500 Video \u2194 All Panels Sync \u2500\u2500 */
|
|
1645
1883
|
var _videoSyncCleanup=null;
|
|
1646
1884
|
function syncActionsWithVideo(){
|
|
1647
1885
|
/* Clean up previous listener */
|
|
1648
1886
|
if(_videoSyncCleanup){_videoSyncCleanup();_videoSyncCleanup=null;}
|
|
1649
1887
|
var video=document.querySelector('.drawer-body video');
|
|
1650
1888
|
if(!video)return;
|
|
1889
|
+
|
|
1890
|
+
/* Action steps sync */
|
|
1651
1891
|
var steps=document.querySelectorAll('.action-step.seekable');
|
|
1652
|
-
if(!steps.length)return;
|
|
1653
|
-
/* Build sorted offset list from DOM */
|
|
1654
1892
|
var offsets=[];
|
|
1655
1893
|
for(var i=0;i<steps.length;i++){
|
|
1656
1894
|
var o=parseFloat(steps[i].getAttribute('data-offset'));
|
|
1657
1895
|
if(!isNaN(o))offsets.push({el:steps[i],offset:o});
|
|
1658
1896
|
}
|
|
1659
|
-
if(!offsets.length)return;
|
|
1660
1897
|
offsets.sort(function(a,b){return a.offset-b.offset;});
|
|
1898
|
+
|
|
1899
|
+
/* Collect console and network panels with video sync */
|
|
1900
|
+
var consolePanels=document.querySelectorAll('.console-panel');
|
|
1901
|
+
var ndtPanels=document.querySelectorAll('.ndt');
|
|
1902
|
+
|
|
1661
1903
|
var lastActive=null;
|
|
1662
1904
|
function onTimeUpdate(){
|
|
1663
1905
|
var ct=video.currentTime;
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1906
|
+
|
|
1907
|
+
/* Sync action steps */
|
|
1908
|
+
if(offsets.length){
|
|
1909
|
+
var match=null;
|
|
1910
|
+
for(var i=offsets.length-1;i>=0;i--){
|
|
1911
|
+
if(offsets[i].offset<=ct){match=offsets[i].el;break;}
|
|
1912
|
+
}
|
|
1913
|
+
if(match!==lastActive){
|
|
1914
|
+
if(lastActive)lastActive.classList.remove('action-active');
|
|
1915
|
+
if(match){
|
|
1916
|
+
match.classList.add('action-active');
|
|
1917
|
+
match.scrollIntoView({block:'nearest',behavior:'smooth'});
|
|
1918
|
+
}
|
|
1919
|
+
lastActive=match;
|
|
1920
|
+
}
|
|
1668
1921
|
}
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1922
|
+
|
|
1923
|
+
/* Sync console panels */
|
|
1924
|
+
for(var ci=0;ci<consolePanels.length;ci++){
|
|
1925
|
+
if(consolePanels[ci].__videoSync)consolePanels[ci].__videoSync(ct);
|
|
1926
|
+
}
|
|
1927
|
+
|
|
1928
|
+
/* Sync network panels */
|
|
1929
|
+
for(var ni=0;ni<ndtPanels.length;ni++){
|
|
1930
|
+
if(ndtPanels[ni].__videoSync)ndtPanels[ni].__videoSync(ct);
|
|
1675
1931
|
}
|
|
1676
|
-
lastActive=match;
|
|
1677
1932
|
}
|
|
1678
1933
|
video.addEventListener('timeupdate',onTimeUpdate);
|
|
1679
|
-
/* Also sync on seek */
|
|
1680
1934
|
video.addEventListener('seeked',onTimeUpdate);
|
|
1681
1935
|
_videoSyncCleanup=function(){
|
|
1682
1936
|
video.removeEventListener('timeupdate',onTimeUpdate);
|
|
@@ -1694,7 +1948,7 @@ function _updateCard(cls,val){
|
|
|
1694
1948
|
var d=document.getElementById('filter-drawer');if(d)d.classList.remove('open');
|
|
1695
1949
|
var b=document.getElementById('filter-drawer-backdrop');if(b)b.classList.remove('open');
|
|
1696
1950
|
}
|
|
1697
|
-
`;var
|
|
1951
|
+
`;var _t=`
|
|
1698
1952
|
/* \u2500\u2500 Category badge helpers \u2500\u2500 */
|
|
1699
1953
|
function actionBadgeClass(cat){
|
|
1700
1954
|
if(cat==='assertion')return 'action-badge-assertion';
|
|
@@ -1740,15 +1994,26 @@ function _updateCard(cls,val){
|
|
|
1740
1994
|
h+='</div>';
|
|
1741
1995
|
return h;
|
|
1742
1996
|
}
|
|
1743
|
-
`;var
|
|
1997
|
+
`;var It=`
|
|
1744
1998
|
/* \u2500\u2500 Console Log Level Colors & Labels \u2500\u2500 */
|
|
1745
1999
|
var LOG_COLORS={log:'#9ca3af',warn:'#fbbf24',error:'#f87171',info:'#60a5fa',debug:'#a78bfa',stdout:'#9ca3af',stderr:'#f87171'};
|
|
1746
2000
|
var LOG_LABELS={log:'LOG',warn:'WARN',error:'ERR',info:'INFO',debug:'DBG',stdout:'OUT',stderr:'ERR'};
|
|
1747
2001
|
|
|
1748
|
-
function
|
|
1749
|
-
|
|
2002
|
+
function consoleVideoOffset(entry,baseTime){
|
|
2003
|
+
if(!baseTime||!entry.timestamp)return -1;
|
|
2004
|
+
var t=Date.parse(entry.timestamp);
|
|
2005
|
+
if(isNaN(t))return -1;
|
|
2006
|
+
var off=(t-baseTime)/1000;
|
|
2007
|
+
return off>=0?off:-1;
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
function renderConsoleLogEntry(entry,hasVideo,baseTime){
|
|
2011
|
+
var off=hasVideo?consoleVideoOffset(entry,baseTime):-1;
|
|
2012
|
+
var seekable=off>=0;
|
|
2013
|
+
var h='<div class="console-entry console-level-'+esc(entry.level)+(seekable?' seekable':'')+'" data-console-level="'+esc(entry.level)+'"'+(seekable?' data-offset="'+off.toFixed(2)+'"':'')+'>';
|
|
1750
2014
|
h+='<span class="console-level-badge" style="color:'+LOG_COLORS[entry.level]+'">'+LOG_LABELS[entry.level]+'</span>';
|
|
1751
|
-
h+='<span class="console-
|
|
2015
|
+
if(seekable){h+='<span class="console-offset">'+off.toFixed(1)+'s</span>';}
|
|
2016
|
+
else{h+='<span class="console-time">'+fmtDate(entry.timestamp).split(', ').pop()+'</span>';}
|
|
1752
2017
|
h+='<span class="console-text">'+esc(stripAnsi(entry.text))+'</span>';
|
|
1753
2018
|
if(entry.location){var short=entry.location.split('/').pop()||entry.location;h+='<span class="console-loc" title="'+esc(entry.location)+'">'+esc(short)+'</span>';}
|
|
1754
2019
|
h+='</div>';
|
|
@@ -1758,7 +2023,7 @@ function _updateCard(cls,val){
|
|
|
1758
2023
|
var CON_ROW_H=24;
|
|
1759
2024
|
var CON_VBUF=40;
|
|
1760
2025
|
|
|
1761
|
-
function renderConsoleColumn(logs,testType){
|
|
2026
|
+
function renderConsoleColumn(logs,testType,hasVideo,baseTime){
|
|
1762
2027
|
if(!logs||logs.length===0)return '';
|
|
1763
2028
|
var isApi=testType==='api';
|
|
1764
2029
|
var label=isApi?'Terminal Logs':'Console';
|
|
@@ -1784,6 +2049,12 @@ function _updateCard(cls,val){
|
|
|
1784
2049
|
}
|
|
1785
2050
|
h+='</div>';
|
|
1786
2051
|
|
|
2052
|
+
/* Pre-compute video offsets for all entries */
|
|
2053
|
+
var videoOffsets=[];
|
|
2054
|
+
if(hasVideo&&baseTime){
|
|
2055
|
+
for(var oi=0;oi<logs.length;oi++){videoOffsets.push(consoleVideoOffset(logs[oi],baseTime));}
|
|
2056
|
+
}
|
|
2057
|
+
|
|
1787
2058
|
/* Use virtualization for large log lists */
|
|
1788
2059
|
if(logs.length>200){
|
|
1789
2060
|
h+='<div class="console-list console-vlist" style="overflow-y:auto;max-height:400px;position:relative">';
|
|
@@ -1797,6 +2068,7 @@ function _updateCard(cls,val){
|
|
|
1797
2068
|
var spacer=list.querySelector('.console-vspacer');
|
|
1798
2069
|
var allLogs=logs;
|
|
1799
2070
|
var filteredIdxs=null;
|
|
2071
|
+
var highlightIdx=-1;
|
|
1800
2072
|
|
|
1801
2073
|
function getVis(){return filteredIdxs||allLogs.map(function(_,i){return i});}
|
|
1802
2074
|
|
|
@@ -1808,10 +2080,14 @@ function _updateCard(cls,val){
|
|
|
1808
2080
|
var s1=Math.min(vis.length,Math.ceil((st+vh)/CON_ROW_H)+CON_VBUF);
|
|
1809
2081
|
var out='';
|
|
1810
2082
|
for(var vi=s0;vi<s1;vi++){
|
|
1811
|
-
var
|
|
1812
|
-
|
|
2083
|
+
var ri=vis[vi];var entry=allLogs[ri];
|
|
2084
|
+
var off=videoOffsets[ri];
|
|
2085
|
+
var seekable=off>=0;
|
|
2086
|
+
var isActive=ri===highlightIdx;
|
|
2087
|
+
out+='<div class="console-entry console-level-'+esc(entry.level)+(seekable?' seekable':'')+(isActive?' console-active':'')+'" data-console-level="'+esc(entry.level)+'"'+(seekable?' data-offset="'+off.toFixed(2)+'"':'')+' data-vidx="'+ri+'" style="position:absolute;top:'+(vi*CON_ROW_H)+'px;left:0;right:0;height:'+CON_ROW_H+'px">';
|
|
1813
2088
|
out+='<span class="console-level-badge" style="color:'+LOG_COLORS[entry.level]+'">'+LOG_LABELS[entry.level]+'</span>';
|
|
1814
|
-
out+='<span class="console-
|
|
2089
|
+
if(seekable){out+='<span class="console-offset">'+off.toFixed(1)+'s</span>';}
|
|
2090
|
+
else{out+='<span class="console-time">'+fmtDate(entry.timestamp).split(', ').pop()+'</span>';}
|
|
1815
2091
|
out+='<span class="console-text">'+esc(stripAnsi(entry.text))+'</span>';
|
|
1816
2092
|
if(entry.location){var short=entry.location.split('/').pop()||entry.location;out+='<span class="console-loc" title="'+esc(entry.location)+'">'+esc(short)+'</span>';}
|
|
1817
2093
|
out+='</div>';
|
|
@@ -1822,6 +2098,16 @@ function _updateCard(cls,val){
|
|
|
1822
2098
|
var rafP=false;
|
|
1823
2099
|
list.addEventListener('scroll',function(){if(!rafP){rafP=true;requestAnimationFrame(function(){rafP=false;paint();})}},{passive:true});
|
|
1824
2100
|
|
|
2101
|
+
/* Click-to-seek for virtual entries */
|
|
2102
|
+
list.addEventListener('click',function(e){
|
|
2103
|
+
var entry=e.target.closest('.console-entry.seekable');
|
|
2104
|
+
if(!entry)return;
|
|
2105
|
+
var off=parseFloat(entry.getAttribute('data-offset'));
|
|
2106
|
+
if(isNaN(off))return;
|
|
2107
|
+
var video=document.querySelector('.drawer-body video');
|
|
2108
|
+
if(video){video.currentTime=off;video.play();}
|
|
2109
|
+
});
|
|
2110
|
+
|
|
1825
2111
|
/* Store filter handler */
|
|
1826
2112
|
panel.__conFilter=function(level){
|
|
1827
2113
|
if(!level||level==='all'){filteredIdxs=null;}
|
|
@@ -1829,21 +2115,74 @@ function _updateCard(cls,val){
|
|
|
1829
2115
|
list.scrollTop=0;paint();
|
|
1830
2116
|
};
|
|
1831
2117
|
|
|
2118
|
+
/* Video sync: scroll to matching entry by time */
|
|
2119
|
+
panel.__videoSync=function(seconds){
|
|
2120
|
+
if(!videoOffsets.length)return;
|
|
2121
|
+
var vis=getVis();
|
|
2122
|
+
var matchVi=-1;
|
|
2123
|
+
for(var i=vis.length-1;i>=0;i--){
|
|
2124
|
+
if(videoOffsets[vis[i]]>=0&&videoOffsets[vis[i]]<=seconds){matchVi=i;break;}
|
|
2125
|
+
}
|
|
2126
|
+
if(matchVi<0){highlightIdx=-1;paint();return;}
|
|
2127
|
+
var newHL=vis[matchVi];
|
|
2128
|
+
if(newHL===highlightIdx)return;
|
|
2129
|
+
highlightIdx=newHL;
|
|
2130
|
+
/* Scroll to row */
|
|
2131
|
+
var rowTop=matchVi*CON_ROW_H;
|
|
2132
|
+
var vh=list.clientHeight;
|
|
2133
|
+
if(rowTop<list.scrollTop||rowTop>list.scrollTop+vh-CON_ROW_H){
|
|
2134
|
+
list.scrollTop=rowTop-vh/2;
|
|
2135
|
+
}
|
|
2136
|
+
paint();
|
|
2137
|
+
};
|
|
2138
|
+
|
|
1832
2139
|
paint();
|
|
1833
2140
|
},0);
|
|
1834
2141
|
}else{
|
|
1835
2142
|
h+='<div class="console-list">';
|
|
1836
|
-
for(var i=0;i<logs.length;i++){h+=renderConsoleLogEntry(logs[i]);}
|
|
2143
|
+
for(var i=0;i<logs.length;i++){h+=renderConsoleLogEntry(logs[i],hasVideo,baseTime);}
|
|
1837
2144
|
h+='</div>';
|
|
1838
2145
|
h+='</div>';
|
|
2146
|
+
|
|
2147
|
+
/* Wire up click-to-seek for non-virtual entries */
|
|
2148
|
+
if(hasVideo&&baseTime){
|
|
2149
|
+
setTimeout(function(){
|
|
2150
|
+
var panel=document.getElementById(uid);if(!panel)return;
|
|
2151
|
+
panel.addEventListener('click',function(e){
|
|
2152
|
+
var entry=e.target.closest('.console-entry.seekable');
|
|
2153
|
+
if(!entry)return;
|
|
2154
|
+
var off=parseFloat(entry.getAttribute('data-offset'));
|
|
2155
|
+
if(isNaN(off))return;
|
|
2156
|
+
var video=document.querySelector('.drawer-body video');
|
|
2157
|
+
if(video){video.currentTime=off;video.play();}
|
|
2158
|
+
});
|
|
2159
|
+
/* Video sync for non-virtual */
|
|
2160
|
+
var entries=panel.querySelectorAll('.console-entry.seekable');
|
|
2161
|
+
var offsets=[];
|
|
2162
|
+
for(var i=0;i<entries.length;i++){
|
|
2163
|
+
var off=parseFloat(entries[i].getAttribute('data-offset'));
|
|
2164
|
+
if(!isNaN(off))offsets.push({el:entries[i],offset:off});
|
|
2165
|
+
}
|
|
2166
|
+
if(offsets.length){
|
|
2167
|
+
var lastHL=null;
|
|
2168
|
+
panel.__videoSync=function(seconds){
|
|
2169
|
+
var match=null;
|
|
2170
|
+
for(var i=offsets.length-1;i>=0;i--){
|
|
2171
|
+
if(offsets[i].offset<=seconds){match=offsets[i].el;break;}
|
|
2172
|
+
}
|
|
2173
|
+
if(match===lastHL)return;
|
|
2174
|
+
if(lastHL)lastHL.classList.remove('console-active');
|
|
2175
|
+
if(match){match.classList.add('console-active');match.scrollIntoView({block:'nearest',behavior:'smooth'});}
|
|
2176
|
+
lastHL=match;
|
|
2177
|
+
};
|
|
2178
|
+
}
|
|
2179
|
+
},0);
|
|
2180
|
+
}
|
|
1839
2181
|
}
|
|
1840
2182
|
return h;
|
|
1841
2183
|
}
|
|
1842
|
-
`;var
|
|
1843
|
-
/* \u2500\u2500
|
|
1844
|
-
var _artifactManifest=null;
|
|
1845
|
-
var _artifactServerPort=null;
|
|
1846
|
-
|
|
2184
|
+
`;var Lt=`
|
|
2185
|
+
/* \u2500\u2500 Artifact Utilities \u2500\u2500 */
|
|
1847
2186
|
function formatBytes(bytes){
|
|
1848
2187
|
if(bytes===0)return '0 B';
|
|
1849
2188
|
var k=1024;var sizes=['B','KB','MB','GB'];
|
|
@@ -1851,186 +2190,168 @@ function _updateCard(cls,val){
|
|
|
1851
2190
|
if(i>=sizes.length)i=sizes.length-1;
|
|
1852
2191
|
return parseFloat((bytes/Math.pow(k,i)).toFixed(1))+' '+sizes[i];
|
|
1853
2192
|
}
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
}
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
2193
|
+
`;var tn=`
|
|
2194
|
+
(function(){
|
|
2195
|
+
var data=JSON.parse(document.getElementById('report-data').textContent);
|
|
2196
|
+
${Ct}
|
|
2197
|
+
${_t}
|
|
2198
|
+
${It}
|
|
2199
|
+
${St}
|
|
2200
|
+
${Rt}
|
|
2201
|
+
${Lt}
|
|
2202
|
+
${At}
|
|
2203
|
+
applyTheme();
|
|
2204
|
+
renderRunMeta();
|
|
2205
|
+
renderSummary();
|
|
2206
|
+
initFilters();
|
|
2207
|
+
renderFilterBar();
|
|
2208
|
+
renderTestGrid();
|
|
2209
|
+
var _lo=document.getElementById('loading-overlay');if(_lo)_lo.remove();
|
|
2210
|
+
})();`;function ye(e,t,r){let n=e.replace(/<\//g,"<\\/"),s=r?r.replace(/<\//g,"<\\/"):null;return `<!-- TestRelic AI Analytics Report \u2014 self-contained, no external dependencies -->
|
|
2211
|
+
<!DOCTYPE html>
|
|
2212
|
+
<html lang="en" data-theme="">
|
|
2213
|
+
<head>
|
|
2214
|
+
<meta charset="UTF-8">
|
|
2215
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
2216
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: blob: 'self'; media-src blob: 'self'; connect-src 'self' http://127.0.0.1:*;">
|
|
2217
|
+
<title>TestRelic AI Analytics Report</title>
|
|
2218
|
+
${""}
|
|
2219
|
+
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(kt).toString("base64")}">
|
|
2220
|
+
<style>${xt}</style>
|
|
2221
|
+
<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>
|
|
2222
|
+
</head>
|
|
2223
|
+
<body>
|
|
2224
|
+
<div class="wrap">
|
|
2225
|
+
<div class="top-bar">
|
|
2226
|
+
<div class="brand">
|
|
2227
|
+
${Tt}
|
|
2228
|
+
<div class="brand-text">
|
|
2229
|
+
<span class="brand-title">TestRelic AI</span>
|
|
2230
|
+
<span class="brand-sub">Analytics Report</span>
|
|
2231
|
+
</div>
|
|
2232
|
+
</div>
|
|
2233
|
+
<div class="run-meta" id="run-meta"></div>
|
|
2234
|
+
<div class="theme-toggle" id="theme-toggle">
|
|
2235
|
+
<button class="theme-btn" data-theme-val="system" title="System"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></svg></button>
|
|
2236
|
+
<button class="theme-btn" data-theme-val="light" title="Light"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg></button>
|
|
2237
|
+
<button class="theme-btn" data-theme-val="dark" title="Dark"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/></svg></button>
|
|
2238
|
+
</div>
|
|
2239
|
+
<a class="cta-btn" href="https://testrelic.ai" target="_blank" rel="noopener noreferrer"><svg class="cta-icon" viewBox="0 0 16 16" fill="none"><path d="M8 1l1.545 4.955L14.5 7.5l-4.955 1.545L8 14l-1.545-4.955L1.5 7.5l4.955-1.545L8 1z" fill="currentColor"/></svg>Advanced Insights with AI<span class="cta-sep">\u2013</span><strong>Get Started</strong><svg class="cta-arrow" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M2.5 6h7M6.5 3l3 3-3 3"/></svg></a>
|
|
2240
|
+
</div>
|
|
2241
|
+
<div id="summary-strip" class="summary-strip"></div>
|
|
2242
|
+
<div id="filter-bar" class="filter-bar"></div>
|
|
2243
|
+
<div id="test-grid"></div>
|
|
2244
|
+
</div>
|
|
2245
|
+
<div class="loading-overlay" id="loading-overlay"><div class="loading-spinner"></div><div class="loading-text">Loading report...</div></div>
|
|
2246
|
+
<div class="drawer-backdrop" id="drawer-backdrop"></div>
|
|
2247
|
+
<aside class="drawer" id="drawer">
|
|
2248
|
+
<div class="drawer-bar">
|
|
2249
|
+
<span class="drawer-bar-title">Test Details</span>
|
|
2250
|
+
<button class="drawer-close" id="drawer-close">×</button>
|
|
2251
|
+
</div>
|
|
2252
|
+
<div class="drawer-body" id="drawer-body"></div>
|
|
2253
|
+
</aside>
|
|
2254
|
+
<div class="filter-drawer-backdrop" id="filter-drawer-backdrop"></div>
|
|
2255
|
+
<aside class="filter-drawer" id="filter-drawer">
|
|
2256
|
+
<div class="filter-drawer-bar">
|
|
2257
|
+
<span class="filter-drawer-title">Filters</span>
|
|
2258
|
+
<button class="filter-drawer-close" id="filter-drawer-close">×</button>
|
|
2259
|
+
</div>
|
|
2260
|
+
<div class="filter-drawer-body" id="filter-drawer-body"></div>
|
|
2261
|
+
</aside>
|
|
2262
|
+
<script id="report-data" type="application/json">${n}</script>
|
|
2263
|
+
${s?`<script id="artifact-manifest-data" type="application/json">${s}</script>`:""}
|
|
2264
|
+
<script>${tn}</script>
|
|
2265
|
+
</body>
|
|
2266
|
+
</html>`}function be(e,t,r,n){let s=e.replace(/<\//g,"<\\/"),a=t.replace(/<\//g,"<\\/"),l=n?n.replace(/<\//g,"<\\/"):null,i=`{
|
|
2267
|
+
"schemaVersion":"2.0",
|
|
2268
|
+
"reportMode":"streaming",
|
|
2269
|
+
"serverPort":${"null"},
|
|
2270
|
+
"summary":${s},
|
|
2271
|
+
"index":${a},
|
|
2272
|
+
"timeline":[],
|
|
2273
|
+
"testRunId":"",
|
|
2274
|
+
"startedAt":"",
|
|
2275
|
+
"completedAt":"",
|
|
2276
|
+
"totalDuration":0,
|
|
2277
|
+
"ci":null,
|
|
2278
|
+
"metadata":null,
|
|
2279
|
+
"shardRunIds":null
|
|
2280
|
+
}`,o=`
|
|
2281
|
+
(function(){
|
|
2282
|
+
var data=JSON.parse(document.getElementById('report-data').textContent);
|
|
2283
|
+
var _serverPort=data.serverPort||null;
|
|
2284
|
+
var _serverAvailable=false;
|
|
2285
|
+
var _detailCache={};
|
|
2286
|
+
var _detailCacheKeysS=[];
|
|
2287
|
+
var _detailCacheMaxS=50;
|
|
2288
|
+
var _testIndex=data.index||[];
|
|
2289
|
+
|
|
2290
|
+
/* Resolve the API base URL: if served from http, use same origin; otherwise use explicit port */
|
|
2291
|
+
function getApiBase(){
|
|
2292
|
+
if(window.location.protocol==='http:'||window.location.protocol==='https:'){
|
|
2293
|
+
return window.location.origin;
|
|
1897
2294
|
}
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
fetch('artifact-manifest.json').then(function(r){
|
|
1901
|
-
if(!r.ok)throw new Error('HTTP '+r.status);
|
|
1902
|
-
return r.json();
|
|
1903
|
-
}).then(function(m){
|
|
1904
|
-
_artifactManifest=m;
|
|
1905
|
-
renderArtifactContent(section,m);
|
|
1906
|
-
}).catch(function(){
|
|
1907
|
-
/* No manifest embedded and fetch failed \u2014 hide section entirely */
|
|
1908
|
-
section.style.display='none';
|
|
1909
|
-
});
|
|
2295
|
+
if(_serverPort){return 'http://127.0.0.1:'+_serverPort;}
|
|
2296
|
+
return null;
|
|
1910
2297
|
}
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
}
|
|
1919
|
-
html+='</div>';
|
|
1920
|
-
|
|
1921
|
-
if(runs.length===0){
|
|
1922
|
-
html+='<div class="as-empty">No artifact runs found.</div>';
|
|
1923
|
-
}else{
|
|
1924
|
-
html+='<div class="as-runs">';
|
|
1925
|
-
for(var i=0;i<runs.length;i++){
|
|
1926
|
-
var run=runs[i];
|
|
1927
|
-
var isLegacy=run.folderName==='__legacy__';
|
|
1928
|
-
var label=isLegacy?'Legacy (pre-timestamp)':formatTimestamp(run.timestamp);
|
|
1929
|
-
var currentTag=run.isCurrentRun?' <span class="as-current-tag">Current</span>':'';
|
|
1930
|
-
var legacyClass=isLegacy?' as-run-legacy':'';
|
|
1931
|
-
html+='<div class="as-run'+legacyClass+'" data-run-folder="'+run.folderName+'">';
|
|
1932
|
-
html+='<div class="as-run-row" data-artifact-toggle="'+i+'">';
|
|
1933
|
-
html+='<span class="as-run-arrow">▶</span>';
|
|
1934
|
-
html+='<span class="as-run-label">'+label+currentTag+'</span>';
|
|
1935
|
-
html+='<span class="as-run-meta">'+run.testCount+' test'+(run.testCount!==1?'s':'')+' · '+formatBytes(run.totalSizeBytes)+'</span>';
|
|
1936
|
-
if(hasServer&&!isLegacy){
|
|
1937
|
-
html+='<button class="as-delete-btn" data-artifact-action="delete" data-run-folder="'+run.folderName+'"'+(run.isCurrentRun?' data-is-current="true"':'')+'>Delete</button>';
|
|
1938
|
-
}
|
|
1939
|
-
html+='</div>';
|
|
1940
|
-
html+='<div class="as-run-detail" id="as-run-detail-'+i+'" style="display:none;">';
|
|
1941
|
-
var tests=run.tests||[];
|
|
1942
|
-
if(tests.length===0){
|
|
1943
|
-
html+='<div class="as-no-tests">No test artifacts in this run.</div>';
|
|
1944
|
-
}else{
|
|
1945
|
-
for(var t=0;t<tests.length;t++){
|
|
1946
|
-
var test=tests[t];
|
|
1947
|
-
html+='<div class="as-test">';
|
|
1948
|
-
html+='<div class="as-test-name">'+test.testName+'</div>';
|
|
1949
|
-
html+='<div class="as-test-files">';
|
|
1950
|
-
for(var f=0;f<test.files.length;f++){
|
|
1951
|
-
var file=test.files[f];
|
|
1952
|
-
if(file.type==='screenshot'){
|
|
1953
|
-
html+='<div class="as-file"><img class="as-thumb artifact-col-img" src="'+file.relativePath+'" alt="'+file.name+'" loading="lazy"><span class="as-file-info">'+file.name+' ('+formatBytes(file.sizeBytes)+')</span></div>';
|
|
1954
|
-
}else if(file.type==='video'){
|
|
1955
|
-
html+='<div class="as-file"><div class="as-video-wrap"><video src="'+file.relativePath+'" controls preload="metadata"></video></div><span class="as-file-info">'+file.name+' ('+formatBytes(file.sizeBytes)+')</span></div>';
|
|
1956
|
-
}else{
|
|
1957
|
-
html+='<div class="as-file"><span class="as-file-icon">📄</span><a href="'+file.relativePath+'" target="_blank">'+file.name+'</a> ('+formatBytes(file.sizeBytes)+')</div>';
|
|
1958
|
-
}
|
|
1959
|
-
}
|
|
1960
|
-
html+='</div></div>';
|
|
1961
|
-
}
|
|
1962
|
-
}
|
|
1963
|
-
html+='</div></div>';
|
|
1964
|
-
}
|
|
1965
|
-
html+='</div>';
|
|
1966
|
-
}
|
|
1967
|
-
section.innerHTML=html;
|
|
2298
|
+
var _apiBase=getApiBase();
|
|
2299
|
+
|
|
2300
|
+
/* Check server availability */
|
|
2301
|
+
function checkServer(cb){
|
|
2302
|
+
if(!_apiBase){cb(false);return;}
|
|
2303
|
+
fetch(_apiBase+'/api/health',{method:'GET'}).then(function(r){
|
|
2304
|
+
_serverAvailable=r.ok;cb(r.ok);
|
|
2305
|
+
}).catch(function(){_serverAvailable=false;cb(false);});
|
|
1968
2306
|
}
|
|
1969
2307
|
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
if(
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
_artifactManifest={schemaVersion:'1.0',generatedAt:new Date().toISOString(),artifactBaseDir:'artifacts',totalSizeBytes:data.totalSizeBytes||0,runs:data.runs||[],serverPort:_artifactServerPort};
|
|
1979
|
-
renderArtifactContent(section,_artifactManifest);
|
|
1980
|
-
}).catch(function(){
|
|
1981
|
-
section.innerHTML='<div class="as-header"><span class="as-title">Test Artifacts</span></div><div class="as-empty">Failed to refresh artifact data.</div>';
|
|
1982
|
-
});
|
|
1983
|
-
}else{
|
|
1984
|
-
renderArtifactSection();
|
|
2308
|
+
/* Bounded detail cache (LRU, max 50 entries) */
|
|
2309
|
+
function sCacheDetail(testId,d){
|
|
2310
|
+
if(_detailCache[testId]){
|
|
2311
|
+
var ki=_detailCacheKeysS.indexOf(testId);
|
|
2312
|
+
if(ki>-1)_detailCacheKeysS.splice(ki,1);
|
|
2313
|
+
}else if(_detailCacheKeysS.length>=_detailCacheMaxS){
|
|
2314
|
+
var evict=_detailCacheKeysS.shift();
|
|
2315
|
+
delete _detailCache[evict];
|
|
1985
2316
|
}
|
|
2317
|
+
_detailCache[testId]=d;
|
|
2318
|
+
_detailCacheKeysS.push(testId);
|
|
1986
2319
|
}
|
|
1987
2320
|
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
if(
|
|
1991
|
-
if(!
|
|
1992
|
-
|
|
1993
|
-
fetch('http://127.0.0.1:'+_artifactServerPort+'/api/artifacts/'+encodeURIComponent(folderName),{method:'DELETE'}).then(function(r){
|
|
2321
|
+
/* Fetch test detail from server */
|
|
2322
|
+
function fetchTestDetail(testId,cb){
|
|
2323
|
+
if(_detailCache[testId]){cb(null,_detailCache[testId]);return;}
|
|
2324
|
+
if(!_serverAvailable||!_apiBase){cb('Server unavailable');return;}
|
|
2325
|
+
fetch(_apiBase+'/api/tests/'+testId).then(function(r){
|
|
1994
2326
|
if(!r.ok)throw new Error('HTTP '+r.status);
|
|
1995
2327
|
return r.json();
|
|
1996
|
-
}).then(function(){
|
|
1997
|
-
|
|
1998
|
-
}).catch(function(
|
|
1999
|
-
alert('Failed to delete: '+err.message);
|
|
2000
|
-
});
|
|
2328
|
+
}).then(function(d){
|
|
2329
|
+
sCacheDetail(testId,d);cb(null,d);
|
|
2330
|
+
}).catch(function(e){cb(e.message||'Failed to fetch');});
|
|
2001
2331
|
}
|
|
2002
2332
|
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
}
|
|
2015
|
-
|
|
2016
|
-
(function(){
|
|
2017
|
-
var data=JSON.parse(document.getElementById('report-data').textContent);
|
|
2018
|
-
${Ut}
|
|
2019
|
-
${Gt}
|
|
2020
|
-
${Vt}
|
|
2021
|
-
${zt}
|
|
2022
|
-
${jt}
|
|
2023
|
-
${Jt}
|
|
2024
|
-
${$t}
|
|
2333
|
+
/* Make fetchTestDetail and index available globally for other modules */
|
|
2334
|
+
window.__trStreamingFetchDetail=fetchTestDetail;
|
|
2335
|
+
window.__trTestIndex=_testIndex;
|
|
2336
|
+
window.__trServerPort=_serverPort;
|
|
2337
|
+
window.__trIsStreaming=true;
|
|
2338
|
+
|
|
2339
|
+
${Ct}
|
|
2340
|
+
${_t}
|
|
2341
|
+
${It}
|
|
2342
|
+
${St}
|
|
2343
|
+
${Rt}
|
|
2344
|
+
${Lt}
|
|
2345
|
+
${At}
|
|
2025
2346
|
applyTheme();
|
|
2026
2347
|
renderRunMeta();
|
|
2027
2348
|
renderSummary();
|
|
2028
2349
|
initFilters();
|
|
2029
2350
|
renderFilterBar();
|
|
2030
2351
|
renderTestGrid();
|
|
2031
|
-
|
|
2352
|
+
checkServer(function(ok){});
|
|
2032
2353
|
var _lo=document.getElementById('loading-overlay');if(_lo)_lo.remove();
|
|
2033
|
-
})();`;
|
|
2354
|
+
})();`;return `<!-- TestRelic AI Analytics Report \u2014 streaming mode -->
|
|
2034
2355
|
<!DOCTYPE html>
|
|
2035
2356
|
<html lang="en" data-theme="">
|
|
2036
2357
|
<head>
|
|
@@ -2038,16 +2359,17 @@ function _updateCard(cls,val){
|
|
|
2038
2359
|
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
2039
2360
|
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; img-src data: blob: 'self'; media-src blob: 'self'; connect-src 'self' http://127.0.0.1:*;">
|
|
2040
2361
|
<title>TestRelic AI Analytics Report</title>
|
|
2041
|
-
${
|
|
2042
|
-
|
|
2043
|
-
<
|
|
2362
|
+
${""}
|
|
2363
|
+
${""}
|
|
2364
|
+
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml;base64,${Buffer.from(kt).toString("base64")}">
|
|
2365
|
+
<style>${xt}</style>
|
|
2044
2366
|
<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>
|
|
2045
2367
|
</head>
|
|
2046
2368
|
<body>
|
|
2047
2369
|
<div class="wrap">
|
|
2048
2370
|
<div class="top-bar">
|
|
2049
2371
|
<div class="brand">
|
|
2050
|
-
${
|
|
2372
|
+
${Tt}
|
|
2051
2373
|
<div class="brand-text">
|
|
2052
2374
|
<span class="brand-title">TestRelic AI</span>
|
|
2053
2375
|
<span class="brand-sub">Analytics Report</span>
|
|
@@ -2064,7 +2386,6 @@ ${t?`<meta name="artifact-server-port" content="${t}">`:""}
|
|
|
2064
2386
|
<div id="summary-strip" class="summary-strip"></div>
|
|
2065
2387
|
<div id="filter-bar" class="filter-bar"></div>
|
|
2066
2388
|
<div id="test-grid"></div>
|
|
2067
|
-
<div id="artifact-section"></div>
|
|
2068
2389
|
</div>
|
|
2069
2390
|
<div class="loading-overlay" id="loading-overlay"><div class="loading-spinner"></div><div class="loading-text">Loading report...</div></div>
|
|
2070
2391
|
<div class="drawer-backdrop" id="drawer-backdrop"></div>
|
|
@@ -2083,50 +2404,61 @@ ${t?`<meta name="artifact-server-port" content="${t}">`:""}
|
|
|
2083
2404
|
</div>
|
|
2084
2405
|
<div class="filter-drawer-body" id="filter-drawer-body"></div>
|
|
2085
2406
|
</aside>
|
|
2086
|
-
<script id="report-data" type="application/json">${
|
|
2087
|
-
${
|
|
2088
|
-
<script>${
|
|
2407
|
+
<script id="report-data" type="application/json">${i}</script>
|
|
2408
|
+
${l?`<script id="artifact-manifest-data" type="application/json">${l}</script>`:""}
|
|
2409
|
+
<script>${o}</script>
|
|
2089
2410
|
</body>
|
|
2090
|
-
</html>`}function
|
|
2091
|
-
`);});}catch{}}var
|
|
2092
|
-
|
|
2411
|
+
</html>`}function Nt(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}
|
|
2412
|
+
`);});}catch{}}var nn=/^[a-f0-9]{12}$/,Mt=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,sn=500;function w(e,t,r){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(r));}function ke(e){e.setHeader("Access-Control-Allow-Origin","*"),e.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),e.setHeader("Access-Control-Allow-Headers","Content-Type");}function st(e){try{return existsSync(e)?JSON.parse(readFileSync(e,"utf-8")):null}catch{return null}}function at(e){let t=0;try{let r=readdirSync(e,{withFileTypes:!0});for(let n of r){let s=join(e,n.name);n.isFile()?t+=statSync(s).size:n.isDirectory()&&(t+=at(s));}}catch{}return t}function Te(e,t,r,n){let s=st(join(r,"index.json"));w(t,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-n)/1e3)});}function Ce(e,t,r){let n=st(join(r,"summary.json"));if(!n){w(t,404,{error:"Summary not found"});return}w(t,200,n);}function Se(e,t,r){let n=st(join(r,"index.json"));if(!n){w(t,404,{error:"Test index not found"});return}let a=new URL(e.url??"/",`http://${e.headers.host}`).searchParams,l=Math.max(1,parseInt(a.get("page")??"1",10)||1),i=Math.min(sn,Math.max(1,parseInt(a.get("pageSize")??"100",10)||100)),o=a.get("status")?.split(",").filter(Boolean)??null,p=a.get("file")??null,d=a.get("search")?.toLowerCase()??null,u=a.get("tag")?.split(",").filter(Boolean)??null,f=a.get("sort")??"file",c=a.get("order")==="desc"?-1:1,g=n;o&&o.length>0&&(g=g.filter(y=>o.includes(y.status))),p&&(g=g.filter(y=>y.filePath===p||y.filePath.startsWith(p+"/"))),d&&(g=g.filter(y=>y.title.toLowerCase().includes(d)||y.filePath.toLowerCase().includes(d))),u&&u.length>0&&(g=g.filter(y=>u.some(m=>y.tags.includes(m)))),g=[...g].sort((y,m)=>{let C=0;switch(f){case "duration":C=y.duration-m.duration;break;case "status":C=y.status.localeCompare(m.status);break;case "title":C=y.title.localeCompare(m.title);break;default:C=y.filePath.localeCompare(m.filePath);break}return C*c});let h=g.length,b=Math.max(1,Math.ceil(h/i)),x=(l-1)*i,k=g.slice(x,x+i);w(t,200,{tests:k,pagination:{page:l,pageSize:i,totalItems:h,totalPages:b},filters:{status:o,file:p,search:d,tag:u}});}function Re(e,t,r,n){if(!nn.test(n)){w(t,400,{error:"Invalid test ID format"});return}let s=join(r,"tests",`${n}.json`);if(!existsSync(s)){w(t,404,{error:`Test not found: ${n}`});return}try{let a=readFileSync(s,"utf-8");t.writeHead(200,{"Content-Type":"application/json"}),t.end(a);}catch(a){w(t,500,{error:a instanceof Error?a.message:String(a)});}}function Ae(e,t,r){let n=st(join(r,"index.json"));if(!n){w(t,404,{error:"Test index not found"});return}let s=new Map;for(let l of n){if(l.isRetry)continue;let i=s.get(l.filePath);switch(i||(i={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},s.set(l.filePath,i)),i.total++,l.status){case "passed":i.passed++;break;case "failed":i.failed++;break;case "flaky":i.flaky++;break;case "skipped":i.skipped++;break;case "timedout":i.timedOut++;break}}let a=Array.from(s.entries()).map(([l,i])=>({filePath:l,...i})).sort((l,i)=>l.filePath.localeCompare(i.filePath));w(t,200,{files:a});}function _e(e,t,r){if(!existsSync(r)){w(t,200,{runs:[],totalSizeBytes:0});return}try{let n=[],s=0,a=readdirSync(r,{withFileTypes:!0});for(let l of a){if(!l.isDirectory()||!Mt.test(l.name))continue;let i=join(r,l.name),o=at(i),p=readdirSync(i,{withFileTypes:!0}).filter(d=>d.isDirectory());n.push({folderName:l.name,totalSizeBytes:o,testCount:p.length}),s+=o;}n.sort((l,i)=>i.folderName.localeCompare(l.folderName)),w(t,200,{runs:n,totalSizeBytes:s});}catch(n){w(t,500,{error:n instanceof Error?n.message:String(n)});}}function Ie(e,t,r){try{let n=0,s=0;if(existsSync(r)){let a=readdirSync(r,{withFileTypes:!0});for(let l of a){if(!l.isDirectory()||!Mt.test(l.name))continue;let i=join(r,l.name),o=at(i);rmSync(i,{recursive:!0,force:!0}),s+=o,n++;}}w(t,200,{deletedCount:n,freedBytes:s});}catch(n){w(t,500,{error:n instanceof Error?n.message:String(n)});}}function Le(e,t,r,n){if(!Mt.test(n)){w(t,400,{error:"Invalid folder name"});return}let s=join(r,n);try{if(!statSync(s).isDirectory()){w(t,404,{error:"Not found"});return}}catch{w(t,404,{error:"Not found"});return}try{let a=at(s);rmSync(s,{recursive:!0,force:!0}),w(t,200,{deleted:n,freedBytes:a});}catch(a){w(t,500,{error:a instanceof Error?a.message:String(a)});}}function Ne(e,t,r){w(t,200,{status:"shutting_down"}),r.close();}function Pt(e,t,r){if(!existsSync(r)){w(t,404,{error:"File not found"});return}try{let n=readFileSync(r),s=extname(r).toLowerCase(),a=an[s]??"application/octet-stream";t.writeHead(200,{"Content-Type":a}),t.end(n);}catch(n){w(t,500,{error:n instanceof Error?n.message:String(n)});}}var an={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".json":"application/json",".html":"text/html",".css":"text/css",".js":"text/javascript",".svg":"image/svg+xml"};var cn=9323,pn=10,un=1800*1e3;function K(e,t){return new Promise((r,n)=>{let s=t?.port??cn,a=Date.now(),l,i=0,o=existsSync(join(e,"artifacts"))?join(e,"artifacts"):existsSync(join(e,"..","artifacts"))?join(e,"..","artifacts"):join(e,"artifacts");function p(){clearTimeout(l),l=setTimeout(()=>{u.close();},un);}let d=t?.htmlPath??null;if(!d){let c=dirname(e);try{let g=readdirSync(c).find(h=>h.endsWith(".html"));g&&(d=join(c,g));}catch{}}let u=createServer((c,g)=>{if(p(),ke(g),c.method==="OPTIONS"){g.writeHead(204),g.end();return}let h;try{h=new URL(c.url??"/",`http://${c.headers.host??"localhost"}`).pathname;}catch{w(g,400,{error:"Invalid URL"});return}if(c.method==="GET"&&(h==="/"||h==="/index.html")){if(d&&existsSync(d)){Pt(c,g,d);return}w(g,404,{error:"HTML report not found"});return}if(c.method==="GET"&&h==="/api/health"){Te(c,g,e,a);return}if(c.method==="GET"&&h==="/api/summary"){Ce(c,g,e);return}if(c.method==="GET"&&h==="/api/tests"){Se(c,g,e);return}if(c.method==="GET"&&h==="/api/files"){Ae(c,g,e);return}let b=h.match(/^\/api\/tests\/([a-f0-9]+)$/);if(c.method==="GET"&&b){Re(c,g,e,b[1]);return}if(c.method==="GET"&&h==="/api/artifacts"){_e(c,g,o);return}if(c.method==="DELETE"&&h==="/api/artifacts"){Ie(c,g,o);return}let x=h.match(/^\/api\/artifacts\/(.+)$/);if(c.method==="DELETE"&&x){Le(c,g,o,decodeURIComponent(x[1]));return}if(c.method==="GET"&&h.startsWith("/artifacts/")){let k=decodeURIComponent(h.slice(11));if(k.includes("..")||k.includes("\0")){w(g,400,{error:"Invalid path"});return}Pt(c,g,join(o,k));return}if(c.method==="POST"&&h==="/api/shutdown"){Ne(c,g,u);return}w(g,404,{error:"Not found"});});function f(c){let g=h=>{h.code==="EADDRINUSE"&&i<pn?(i++,f(c+1)):n(h);};u.once("error",g),u.listen(c,"127.0.0.1",()=>{u.removeListener("error",g);let h=u.address();if(!h||typeof h=="string"){n(new Error("Failed to get server address"));return}p(),r({port:h.port,dispose:()=>new Promise(b=>{clearTimeout(l),u.close(()=>b());})});});}f(s);})}async function Ee(e){let t=await K(e);return {port:t.port,dispose:t.dispose}}function vn(e,t,r){let n=JSON.stringify(e),s=r?JSON.stringify(r):null;return ye(n,t,s)}async function Bt(e,t,r){try{let n=null,s=null,a=t.reportMode==="streaming"||t.reportMode==="auto"&&e.timeline.length===0&&e.summary.total>=t.streamingThreshold,l,i=t.htmlReportPath,o=dirname(i);if(mkdirSync(o,{recursive:!0}),a){let d=JSON.stringify(e.summary),u=dirname(t.outputPath),f=join(u,".testrelic-report"),c="[]";try{let h=join(f,"index-compact.json"),b=join(f,"index.json");existsSync(h)?c=readFileSync(h,"utf-8"):existsSync(b)&&(c=readFileSync(b,"utf-8"));}catch{}let g=r?JSON.stringify(r):null;l=be(d,c,null,g);}else l=vn(e,null,r);let p=i+".tmp";if(writeFileSync(p,l,"utf-8"),renameSync(p,i),a){if(e.ci===null){let d=dirname(t.outputPath),u=join(d,".testrelic-report"),f=resolve(i);try{if(await bn(),n=await wn(u),!n){s=await K(u,{htmlPath:f}),n=s.port;let c=setInterval(()=>{},6e4),g=()=>{clearInterval(c),s?.dispose();};process.on("SIGINT",g),process.on("SIGTERM",g),setTimeout(g,1800*1e3).unref();}n&&process.stderr.write(`
|
|
2413
|
+
Report server: http://127.0.0.1:${n}
|
|
2414
|
+
`);}catch{}}}else if(t.openReport&&e.ci===null&&t.includeArtifacts){let d=dirname(t.outputPath),u=join(d,"artifacts");if(existsSync(u))try{let f=await Ee(u);n=f.port,process.on("exit",()=>{f.dispose();});}catch{}}if(t.openReport&&e.ci===null)if(a&&n)Nt(`http://127.0.0.1:${n}`);else {let d=resolve(i);Nt(d);}}catch(n){process.stderr.write(`[testrelic] Failed to write HTML report: ${n instanceof Error?n.message:String(n)}
|
|
2415
|
+
`);}}var lt=9323,De=10;async function yn(){for(let e=lt;e<lt+De;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),500),n=await fetch(`http://127.0.0.1:${e}/api/health`,{signal:t.signal});if(clearTimeout(r),n.ok)return e}catch{}return null}async function bn(){for(let e=lt;e<lt+De;e++)try{let t=new AbortController,r=setTimeout(()=>t.abort(),1e3);await fetch(`http://127.0.0.1:${e}/api/shutdown`,{method:"POST",signal:t.signal}),clearTimeout(r);}catch{}await new Promise(e=>setTimeout(e,300));}async function wn(e){let r=[join(__dirname,"cli.cjs"),join(__dirname,"cli.js"),join(__dirname,"..","dist","cli.cjs"),join(__dirname,"..","dist","cli.js")].find(n=>existsSync(n));if(!r){let n=await K(e);return process.on("exit",()=>{n?.dispose();}),n.port}return new Promise(n=>{let s=spawn(process.execPath,[r,"serve",e],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),a="",l=false,i=setTimeout(()=>{l||(l=true,s.stderr?.removeAllListeners(),yn().then(n));},5e3);s.stderr?.on("data",o=>{a+=o.toString();let p=a.match(/127\.0\.0\.1:(\d+)/);p&&!l&&(l=true,clearTimeout(i),s.stderr?.removeAllListeners(),s.unref(),n(Number(p[1])));}),s.on("error",()=>{l||(l=true,clearTimeout(i),n(null));}),s.on("exit",()=>{l||(l=true,clearTimeout(i),n(null));}),s.unref();})}var Tn=20,Ot=0,qt=[];async function Oe(e,t){Ot>=Tn&&await new Promise(r=>qt.push(r)),Ot++;try{return await copyFile(e,t),!0}catch{return false}finally{Ot--,qt.length>0&&qt.shift()();}}var Z=[];async function qe(){Z.length!==0&&(await Promise.allSettled(Z),Z.length=0);}function Fe(e){let t=new Date,r=a=>String(a).padStart(2,"0"),n=`${t.getFullYear()}-${r(t.getMonth()+1)}-${r(t.getDate())}T${r(t.getHours())}-${r(t.getMinutes())}-${r(t.getSeconds())}`;if(!existsSync(join(e,n)))return n;let s=1;for(;existsSync(join(e,`${n}-${s}`));)s++;return `${n}-${s}`}function Cn(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 He(e,t,r,n,s){let a=e.find(f=>f.name==="screenshot"&&f.path),l=e.find(f=>f.name==="video"&&f.path);if(!a&&!l)return null;let i=Cn(t);r>0&&(i+=`--retry-${r}`);let o=s?["artifacts",s,i]:["artifacts",i],p=join(n,...o),d=o,u={};try{mkdirSync(p,{recursive:!0});}catch{return null}if(a?.path&&existsSync(a.path)){let c=`screenshot${extname(a.path)||".png"}`,g=join(p,c);Z.push(Oe(a.path,g).then(()=>{})),u.screenshot=`${d.join("/")}/${c}`;}if(l?.path&&existsSync(l.path)){let c=`video${extname(l.path)||".webm"}`,g=join(p,c);Z.push(Oe(l.path,g).then(()=>{})),u.video=`${d.join("/")}/${c}`;}return !u.screenshot&&!u.video?null:u}var An=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,_n="1.0";function In(e){let t=extname(e).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(t)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(t)?"video":"other"}function Ue(e,t,r){let n=[];try{let s=readdirSync(e,{withFileTypes:!0});for(let a of s){if(!a.isFile())continue;let l=join(e,a.name),i=statSync(l);n.push({name:a.name,type:In(a.name),relativePath:`artifacts/${t}/${r}/${a.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:n}}function Ln(e,t){let r=join(e,t),n=[],s=0;try{let l=readdirSync(r,{withFileTypes:!0});for(let i of l){if(!i.isDirectory())continue;let o=Ue(join(r,i.name),t,i.name);n.push(o);for(let p of o.files)s+=p.sizeBytes;}}catch{}let a=t.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return n.sort((l,i)=>l.testName.localeCompare(i.testName)),{folderName:t,timestamp:a,totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}}function $e(e,t){let r=join(e,"artifacts"),n=[],s=[],a=0;try{let i=readdirSync(r,{withFileTypes:!0});for(let o of i)if(o.isDirectory())if(An.test(o.name)){let p=Ln(r,o.name);n.push({...p,isCurrentRun:o.name===t});}else {let p=Ue(join(r,o.name),o.name,o.name);s.push(p);for(let d of p.files)a+=d.sizeBytes;}}catch{}n.sort((i,o)=>o.timestamp.localeCompare(i.timestamp)),s.length>0&&(s.sort((i,o)=>i.testName.localeCompare(o.testName)),n.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:a,testCount:s.length,tests:s,isCurrentRun:false}));let l=n.reduce((i,o)=>i+o.totalSizeBytes,0);return {schemaVersion:_n,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:l,runs:n,serverPort:null}}function Dn(e){let t=e,{root:r}=parse(t);for(;t!==r;){if(existsSync(join(t,".git")))return t;t=join(t,"..");}return null}function je(e){try{let t=Dn(e);if(!t)return;let r=join(t,".gitignore"),n=relative(t,e).replace(/\\/g,"/"),s=n.endsWith("/")?n:`${n}/`;if(existsSync(r)&&readFileSync(r,"utf-8").split(`
|
|
2093
2416
|
`).map(o=>o.trim()).some(o=>o===s||o===n))return;let a=`
|
|
2094
2417
|
# TestRelic test artifacts
|
|
2095
2418
|
${s}
|
|
2096
|
-
`;appendFileSync(r,a,"utf-8");}catch{}}function
|
|
2097
|
-
`}function
|
|
2419
|
+
`;appendFileSync(r,a,"utf-8");}catch{}}function We(e,t){let r=[];for(let n of e){let s=Bn(n),a=On(n),l=qn(n,s,a,t),i=Fn(n,s,a);if(l.length===0&&i.length===0){r.push({type:"navigation",url:"about:blank",timestamp:n.startedAt,durationOnUrl:n.duration,navigationType:"dummy",domContentLoadedAt:null,networkIdleAt:null,networkStats:null,specFile:n.specFile,test:s,tests:[a],_testTitle:n.title});continue}r.push(...l,...i);}return r.sort(Hn),Un(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 Bn(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 On(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 qn(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 Fn(e,t,r){if(!e.apiCalls||e.apiCalls.length===0)return [];let n=e.apiAssertions??[];return e.apiCalls.map(s=>{let a=n.filter(i=>i.callId===s.id).map(i=>({type:i.type,expected:i.expected,actual:i.actual,status:i.status,location:i.location,...i.expression!==void 0?{expression:i.expression}:{}})),l=null;return s.responseStatusCode!==null&&s.responseStatusText!==null&&(l={statusCode:s.responseStatusCode,statusText:s.responseStatusText,headers:s.responseHeaders,body:Ge(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:Ge(s.requestBody)},response:l,...s.error?{error:s.error}:{},assertions:a,specFile:e.specFile,test:t,tests:[r],_testTitle:e.title}})}function Hn(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?Ve(e.callId)-Ve(t.callId):0}function Ve(e){let t=e.match(/(\d+)$/);return t?parseInt(t[1],10):0}function Un(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(i=>i.title===n._testTitle);if(l){let i=new Date(l.completedAt).getTime();n.durationOnUrl=Math.max(0,i-s);}}}}function Ge(e){if(e==null)return null;try{return JSON.parse(e)}catch{return e}}function Ut(e,t){let r=e.length,n=Math.min(Math.ceil(t/100*r)-1,r-1);return e[Math.max(0,n)]}function $n(e){try{let t=new URL(e);return t.origin+t.pathname}catch{return e}}function zn(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 Je(e,t){let r=0,n=0,s=0,a=0,l=0;for(let v of e)switch(v.status){case "passed":r++;break;case "failed":n++;break;case "flaky":s++;break;case "skipped":a++;break;case "timedout":l++;break}let i=[];for(let v of e)v.apiCalls&&i.push(...v.apiCalls);let o=i.length,p=new Set,d={},u={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},f=[];for(let v of i)p.add($n(v.url)),d[v.method]=(d[v.method]??0)+1,u[zn(v.responseStatusCode)]+=1,f.push(v.responseTimeMs);let c=null;if(f.length>0){let v=[...f].sort((H,U)=>H-U),T=v.reduce((H,U)=>H+U,0);c={avg:Math.round(T/v.length),min:v[0],max:v[v.length-1],p50:Ut(v,50),p95:Ut(v,95),p99:Ut(v,99)};}let g=0,h=0,b=0;for(let v of e)if(v.apiAssertions)for(let T of v.apiAssertions)g++,T.status==="passed"?h++:b++;let x=0,k=new Set;for(let v of e){x+=v.navigations.length;for(let T of v.navigations)k.add(T.url);}let y=0,m={};function C(v){for(let T of v)y++,m[T.category]=(m[T.category]??0)+1,T.children.length>0&&C(T.children);}for(let v of e)v.actions&&C(v.actions);return {total:e.length,passed:r,failed:n,flaky:s,skipped:a,timedout:l,totalApiCalls:o,uniqueApiUrls:p.size,apiCallsByMethod:d,apiCallsByStatusRange:u,apiResponseTime:c,totalAssertions:g,passedAssertions:h,failedAssertions:b,totalNavigations:x,uniqueNavigationUrls:k.size,totalTimelineSteps:t,totalActionSteps:y,actionStepsByCategory:m}}function jn(e){let t=56-e.length;return t>0?e+" ".repeat(t):e}function A(e){return `\u2502 ${jn(e)} \u2502
|
|
2420
|
+
`}function $t(e,t,r,n){if(n||e.total===0)return;let s=`\u250C${"\u2500".repeat(58)}\u2510
|
|
2098
2421
|
`,a=`\u2514${"\u2500".repeat(58)}\u2518
|
|
2099
|
-
`,l=
|
|
2100
|
-
`,process.stderr.write(i);}var
|
|
2101
|
-
`)[0]?.trim();return n?
|
|
2422
|
+
`,l=A(""),i=s;i+=A("TestRelic AI - Playwright Test Report"),i+=l;let o=[];if(e.passed>0&&o.push(`${e.passed} \u2713`),e.failed>0&&o.push(`${e.failed} \u2717`),e.flaky>0&&o.push(`${e.flaky} \u26A0`),e.skipped>0&&o.push(`${e.skipped} skipped`),e.timedout>0&&o.push(`${e.timedout} timedout`),i+=A(`Tests: ${e.total} total (${o.join(" ")})`),e.totalNavigations>0&&(i+=A(`Navigations: ${e.totalNavigations} visits across ${e.uniqueNavigationUrls} unique URLs`)),e.totalApiCalls>0){i+=A(`API Calls: ${e.totalApiCalls} calls across ${e.uniqueApiUrls} unique endpoints`);let p=Object.entries(e.apiCallsByMethod).filter(([,u])=>u>0).map(([u,f])=>`${u}: ${f}`);p.length>0&&(i+=A(` ${p.join(" ")}`));let d=Object.entries(e.apiCallsByStatusRange).filter(([,u])=>u>0).map(([u,f])=>`${u}: ${f}`);d.length>0&&(i+=A(` ${d.join(" ")}`)),e.apiResponseTime&&(i+=A(` Avg response: ${e.apiResponseTime.avg}ms P95: ${e.apiResponseTime.p95}ms`));}if(e.totalAssertions>0&&(i+=A(`Assertions: ${e.totalAssertions} total (${e.passedAssertions} \u2713 ${e.failedAssertions} \u2717)`)),e.totalActionSteps>0){let p=[],d=e.actionStepsByCategory;d.ui_action&&p.push(`${d.ui_action} UI`),d.assertion&&p.push(`${d.assertion} assertions`),d.custom_step&&p.push(`${d.custom_step} custom`);let u=p.length>0?` (${p.join(" ")})`:"";i+=A(`Actions: ${e.totalActionSteps} steps${u}`);}i+=A(`Report: ${r}`),i+=A(`Data: ${t}`),i+=a,i+=`For more information visit us at https://docs.testrelic.ai
|
|
2423
|
+
`,process.stderr.write(i);}var Vn=new Set(["pw:api","expect","test.step"]);function Gn(e){return e==="expect"?"assertion":e==="test.step"?"custom_step":"ui_action"}function zt(e,t,r){if(Vn.has(e.category)){let n=[];for(let a of e.steps)zt(a,t,n);let s=e.startTime.getTime()-t.getTime();r.push({title:e.title,category:Gn(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)zt(n,t,r);}function Ke(e,t){let r=[];for(let n of e)zt(n,t,r);return r}var Kn=new Set(["localhost","127.0.0.1","0.0.0.0"]);function Ze(e){let t=new URL(e);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&Kn.has(t.hostname)))throw createError(ErrorCode.CLOUD_CONFIG_INVALID,`HTTPS is required for cloud communication. Got: ${t.protocol}//${t.hostname}`)}var Yn=3e3;async function jt(e){let t=new AbortController,r=setTimeout(()=>t.abort(),Yn);try{return (await fetch(`${e}/health`,{method:"GET",signal:t.signal})).ok}catch{return false}finally{clearTimeout(r);}}async function Qe(e){return new Promise(t=>setTimeout(t,e))}async function Ye(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 Vt(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 i=await a.json();return {accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,orgId:i.orgId,orgName:i.orgName,userId:i.userId,userName:i.userName}}if(a.status===429){let i=a.headers.get("Retry-After"),o=i?parseInt(i,10)*1e3:5e3;if(!isNaN(o)&&o>0){await Qe(o);let p=await fetch(`${e}/sdk/auth/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t}),signal:n.signal});if(p.ok){let d=await p.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 Ye(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 Ye(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 Gt(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 Xe(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 i=a.headers.get("Retry-After"),o=i?parseInt(i,10)*1e3:5e3;!isNaN(o)&&o>0&&(await Qe(o),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 tr(e,t,r,n,s,a){let l=new AbortController,i=setTimeout(()=>l.abort(),s);try{let o={gitId:r,displayName:n};a&&(o.branch=a);let p=await fetch(`${e}/repos/resolve`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(o),signal:l.signal});if(!p.ok)return null;let d=await p.json();return {repoId:d.repoId,displayName:d.displayName}}catch{return null}finally{clearTimeout(i);}}var es=5e3;function D(e,t){try{return execSync(e,{cwd:t,timeout:es,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()||null}catch{return null}}function er(e){let t=D("git rev-parse --abbrev-ref HEAD",e),r=D("git rev-parse --short HEAD",e),n=D("git log -1 --pretty=%s",e),s=rs(e),a=s?X(s):null;return {branch:t,commitSha:r,commitMessage:n,remoteUrl:a}}function rs(e){let t=D("git remote get-url origin",e);if(t)return t;let r=D("git remote",e);if(!r)return null;let n=r.split(`
|
|
2424
|
+
`)[0]?.trim();return n?D(`git remote get-url ${n}`,e):null}function X(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 rr(e){let t=e.split("/").filter(Boolean);return t[t.length-1]??e}function Wt(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 tt(e){let t=Wt(e);return t||`local/${basename(e)}`}var ls="1.0.0",nr=10;function Kt(e,t,r,n,s,a,l,i){try{mkdirSync(e,{recursive:!0});let o=Date.now(),p=`${o}-${t}-${r}.json`,d=join(e,p),u={version:ls,queuedAt:new Date(o).toISOString(),reason:n,retryCount:0,targetEndpoint:s,method:a,payload:l,headers:i},f=d+".tmp";writeFileSync(f,JSON.stringify(u,null,2),"utf-8"),renameSync(f,d);}catch(o){o.code==="ENOSPC"?process.stderr.write(`\u26A0 TestRelic: Disk full \u2014 unable to queue upload data.
|
|
2102
2425
|
`):process.stderr.write(`\u26A0 TestRelic: Unable to queue upload data.
|
|
2103
|
-
`);}}async function
|
|
2104
|
-
`),unlinkSync(i);continue}let
|
|
2105
|
-
`);return}try{if(
|
|
2106
|
-
`);return}let r=await
|
|
2107
|
-
`),await this.resolveRepoId(),this.config.queueDirectory&&(
|
|
2108
|
-
`);}}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()+
|
|
2109
|
-
`));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,new Promise(t=>setTimeout(t,
|
|
2110
|
-
\u2192 Manage keys: ${
|
|
2426
|
+
`);}}async function ir(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+=nr)s.push(n.slice(a,a+nr));for(let a of s)for(let l of a){let i=join(e,l);try{if(!statSync(i).isFile())continue;let p=readFileSync(i,"utf-8"),d=JSON.parse(p);if(!isValidQueueEntry(d)){process.stderr.write(`\u26A0 TestRelic: Corrupted queue file deleted: ${l}
|
|
2427
|
+
`),unlinkSync(i);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(i);else return}catch{return}}}function or(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"),o=JSON.parse(l).queuedAt;if(typeof o=="string"){let p=new Date(o).getTime();n-p>t&&unlinkSync(a);}}catch{try{unlinkSync(a);}catch{}}}}catch{}}var hs=3e5,ms=864e5,vs=6e4,lr=3e4,Zt="https://app.testrelic.com/settings/api-keys",pt=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.
|
|
2428
|
+
`);return}try{if(Ze(this.config.endpoint),this.gitMetadata=er(),!await jt(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.
|
|
2429
|
+
`);return}let r=await Vt(this.config.endpoint,this.config.apiKey,this.config.timeout);if(Gt(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})
|
|
2430
|
+
`),await this.resolveRepoId(),this.config.queueDirectory&&(or(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.
|
|
2431
|
+
`);}}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()+hs<t)return true;if(!this.config||!this.authState.refreshToken)return this.switchToLocalMode("token_expired_no_refresh"),false;try{let r=await Xe(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}).
|
|
2432
|
+
`));}async dispose(){if(this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null),this.flushPromise){try{await Promise.race([this.flushPromise,new Promise(t=>setTimeout(t,lr))]);}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.
|
|
2433
|
+
\u2192 Manage keys: ${Zt}
|
|
2111
2434
|
`);break;case "expired_key":this.setLocalMode("expired_api_key"),process.stderr.write(`\u26A0 TestRelic: API key has expired. Running in local mode.
|
|
2112
|
-
\u2192 Generate a new key: ${
|
|
2435
|
+
\u2192 Generate a new key: ${Zt}
|
|
2113
2436
|
`);break;case "validation_error":this.setLocalMode("validation_error"),process.stderr.write(`\u26A0 TestRelic: API key format invalid. Running in local mode.
|
|
2114
|
-
\u2192 Manage keys: ${
|
|
2437
|
+
\u2192 Manage keys: ${Zt}
|
|
2115
2438
|
`);break;case "rate_limited":this.setLocalMode("rate_limited"),process.stderr.write(`\u26A0 TestRelic: Rate limited during authentication. Running in local mode.
|
|
2116
2439
|
`);break;case "timeout":this.setLocalMode("auth_timeout"),process.stderr.write(`\u26A0 TestRelic: Authentication timed out. Running in local mode.
|
|
2117
2440
|
`);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
|
|
2118
|
-
`);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let t=this.gitMetadata?.remoteUrl?
|
|
2119
|
-
`);}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>
|
|
2120
|
-
`),this.startBackgroundFlush();}}}catch{}},
|
|
2121
|
-
`);}if(!d){s=t.filter(
|
|
2122
|
-
`),{navigations:s,networkRequests:a,apiCalls:l,apiAssertions:i,consoleLogs:o}}function
|
|
2441
|
+
`);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let t=this.gitMetadata?.remoteUrl?X(this.gitMetadata.remoteUrl):null,r=t?rr(t):this.config.projectName??tt(process.cwd()),n=t??this.config.projectName??tt(process.cwd()),s=this.readRepoCache(n);if(s){this.repoId=s.repoId;return}try{let a=await tr(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&&!Wt(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
|
|
2442
|
+
`);}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>ms)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()??""},i=a+".tmp";writeFileSync(i,JSON.stringify(l,null,2),"utf-8"),renameSync(i,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([ir(r,n,t),new Promise(s=>setTimeout(s,lr))]).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 jt(t))return;if(this.config?.apiKey){let n=await Vt(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!Gt(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.
|
|
2443
|
+
`),this.startBackgroundFlush();}}}catch{}},vs);}};var bs=1048576,ut=[1e3,3e3,9e3],ft=3;function Qt(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 gt(e){return new Promise(t=>setTimeout(t,e))}function ws(e){let t={};for(let[r,n]of Object.entries(e))n!=null&&(t[r]=n);return t}async function xs(e,t,r){for(let n=0;n<ft;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}`}},i=await fetch(e,l);if(i.ok)return i}return null}if(s.status===429&&n<ft-1){let a=s.headers.get("Retry-After"),l=a?parseInt(a,10)*1e3:ut[n];!isNaN(l)&&l>0?await gt(l):await gt(ut[n]);continue}if(s.status>=500&&n<ft-1){await gt(ut[n]);continue}return s}catch{if(n<ft-1){await gt(ut[n]);continue}return null}return null}function ks(e){let t=JSON.stringify(e),r={"Content-Type":"application/json"};if(Buffer.byteLength(t,"utf-8")>bs){let n=gzipSync(Buffer.from(t,"utf-8"));return r["Content-Encoding"]="gzip",{body:n,headers:r}}return {body:t,headers:r}}async function dr(e,t,r,n){let s=`${e}/runs`,{body:a,headers:l}=ks(r);l.Authorization=`Bearer ${t}`;let i=await xs(s,{method:"POST",headers:l,body:a},n);return i?.ok?{success:true,statusCode:i.status,error:null}:i?.status===409?{success:true,statusCode:409,error:null}:{success:false,reason:i?`Upload failed with status ${i.status}`:"Upload failed after retries",statusCode:i?.status??null,payload:r,targetEndpoint:s,method:"POST"}}async function cr(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(ws(r))});return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function pr(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 ur(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 fr(e,t,r,n){let s=[],a=null,l=null,i=null,o=null,p=e.filter(f=>f.name===ATTACHMENT_NAME&&f.body),d=false;if(p.length>0)for(let f of p)try{let c=JSON.parse(f.body.toString());if(isTestRelicDataPayload(c)){s=s.concat(c.navigations),c.networkRequests.length>0&&(a=(a??[]).concat(c.networkRequests)),c.apiCalls.length>0&&(l=(l??[]).concat(c.apiCalls)),c.apiAssertions.length>0&&(i=(i??[]).concat(c.apiAssertions));let g=c.consoleLogs;Array.isArray(g)&&g.length>0&&(o=(o??[]).concat(g)),d=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}", falling back to annotations
|
|
2444
|
+
`);}if(!d){s=t.filter(h=>h.type==="lambdatest-navigation"&&h.description).map(h=>{try{return JSON.parse(h.description)}catch{return null}}).filter(h=>h!==null);let f=t.find(h=>h.type==="__testrelic_network_requests"&&h.description);if(f)try{a=JSON.parse(f.description);}catch{}let c=t.find(h=>h.type==="__testrelic_api_calls"&&h.description);if(c)try{l=JSON.parse(c.description);}catch{}let g=t.find(h=>h.type==="__testrelic_api_assertions"&&h.description);if(g)try{i=JSON.parse(g.description);}catch{}}return s.length===0&&!a&&!l&&!i&&!o&&!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.
|
|
2445
|
+
`),{navigations:s,networkRequests:a,apiCalls:l,apiAssertions:i,consoleLogs:o}}function Xt(e){let r=e.getGitMetadata()?.remoteUrl;return r?X(r):e.getConfig()?.projectName??tt(process.cwd())}async function gr(e,t,r,n){if(!e.isCloudMode()||t!=="realtime"&&t!=="both"||!await e.ensureValidToken())return null;let a=e.getGitMetadata(),l=M();return (await cr(e.getEndpoint(),e.getAccessToken(),{runId:r,repoGitId:Xt(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 te(e,t,r,n,s,a,l,i,o){try{if(e.isCloudMode()&&s&&(r==="realtime"||r==="both")&&await e.ensureValidToken()&&await ur(e.getEndpoint(),e.getAccessToken(),s,{finishedAt:l,duration:i,summary:o}),e.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await e.ensureValidToken()){let d=e.getGitMetadata(),u=M(),f=Xt(e),c=Qt(a,f,d,u),g=await dr(e.getEndpoint(),e.getAccessToken(),c,async()=>await e.ensureValidToken()?e.getAccessToken():null);if(!g.success){let h=g,b=t?.queueDirectory??".testrelic/queue";Kt(b,n,"batch",h.reason,h.targetEndpoint,h.method,h.payload,{"Content-Type":"application/json"});}}else {let d=t?.queueDirectory??".testrelic/queue",u=e.getGitMetadata(),f=M(),c=Xt(e),g=Qt(a,c,u,f);Kt(d,n,"batch",e.getFailureReason()??"token_invalid",`${e.getEndpoint()}/runs`,"POST",g,{"Content-Type":"application/json"});}await e.dispose();}catch{try{await e.dispose();}catch{}}}function re(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 Is(e,t,r){let n=`${e}::${t}::${r}`;return createHash("sha256").update(n).digest("hex").substring(0,16)}function Ls(e){return e.length<=4?"":e[e.length-2]}function Ns(e){let t=e.findIndex(r=>r.status==="passed");return t>0?`passed on retry ${t}`:null}function Es(e,t){let r=["e2e","api","unit"];for(let s of r)if(e.some(a=>a===`@${s}`||a===s))return s;let n=t.replace(/\\/g,"/");for(let s of r)if(n.includes(`/${s}/`))return s;return "unknown"}var Ms="__testrelic_api_config";function Ps(e){return JSON.stringify(e,(t,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var ht=class{constructor(t){this.rootDir="";this.startedAt="";this.testRunId="";this.collectedTests=[];this.fixtureDataReceived=false;this.testCount=0;this.cloudClient=null;this.cloudRunId=null;this.runTimestamp="";this.activeReportMode="embedded";this.streamingWriter=null;this.testIndex=[];this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:0,totalAssertions:0,totalNavigations:0,totalNetworkRequests:0,totalConsoleLogs:0,totalActionSteps:0};this.config=he(t),this.apiConfig=ge(t);}async onBegin(t,r){try{if(this.rootDir=t.rootDir,this.startedAt=new Date().toISOString(),this.testRunId=this.config.testRunId??randomUUID(),this.config.reportMode==="auto"){let s=r.allTests().length;this.activeReportMode=s>=this.config.streamingThreshold?"streaming":"embedded";}else this.activeReportMode=this.config.reportMode;let n=r.allTests().length;if(process.stderr.write(`[testrelic] Report mode: ${this.activeReportMode} (${n} tests)
|
|
2446
|
+
`),this.activeReportMode==="streaming"){let s=dirname(this.config.outputPath);this.streamingWriter=new W(s);let a=()=>{if(this.streamingWriter){try{this.streamingWriter.writeIndex(this.testIndex);let l={testRunId:this.testRunId??"",startedAt:this.startedAt,completedAt:new Date().toISOString(),totalDuration:Date.now()-new Date(this.startedAt).getTime(),...this.summaryCounters,metadata:null,reportMode:"streaming",files:[],enrichedSummary:null,validation:null,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(l);}catch{}this.streamingWriter.dispose();}};process.on("SIGTERM",a),process.on("SIGINT",a);}if(this.config.includeArtifacts){let s=dirname(this.config.outputPath);this.runTimestamp=Fe(join(s,"artifacts"));try{je(join(s,"artifacts"));}catch{}}try{this.cloudClient=new pt(this.config.cloud),await this.cloudClient.initialize(),this.cloudRunId=await gr(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:Ms,description:Ps(this.apiConfig)});}catch{}}onTestEnd(t,r){try{let n=r,s=t.outcome(),a;s==="flaky"?a="flaky":s==="skipped"?a="skipped":a=re(n.status);let l=n.startTime.toISOString(),i=new Date(n.startTime.getTime()+n.duration).toISOString(),o=t.tags?[...t.tags]:t.annotations.filter(R=>R.type==="tag").map(R=>R.description??""),{navigations:p,networkRequests:d,apiCalls:u,apiAssertions:f,consoleLogs:c}=fr(n.attachments,t.annotations,t.title,a==="skipped");(p.length>0||d||u)&&(this.fixtureDataReceived=!0);let g=null;if(a==="failed"||a==="flaky"){let S=(a==="flaky"?t.results.find(N=>N.status!=="passed")?.errors??[]:n.errors)[0];if(S){let N=ve(this.config.redactPatterns),z=S.location?.line??null,j=null;this.config.includeCodeSnippets&&z!==null&&S.location?.file&&(j=me(S.location.file,z,this.config.codeContextLines),j&&(j=N(j))),g={message:N(S.message??"Unknown error"),line:z,code:j,stack:this.config.includeStackTrace&&S.stack?N(S.stack):null};}}let h=t.titlePath().filter(Boolean),b=relative(this.rootDir||".",t.location.file),x=Ls(h),k=h.join(" > "),y=b,m=Is(y,x,k),C=Es(o,y),v=s==="flaky",T=Ns(t.results),H=re(t.expectedStatus),U=re(n.status),et=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments){let R=dirname(this.config.outputPath),S=h[h.length-1]??t.title;et=He(n.attachments,S,n.retry,R,this.runTimestamp||void 0);}let $=this.config.includeActionSteps&&n.steps?Ke(n.steps,n.startTime):null,_={titlePath:h,title:k,status:a,duration:n.duration,startedAt:l,completedAt:i,retryCount:t.results.length-1,retry:n.retry,tags:o,failure:g,specFile:b,navigations:p,testId:m,filePath:y,suiteName:x,testType:C,isFlaky:v,retryStatus:T,expectedStatus:H,actualStatus:U,artifacts:et,networkRequests:d,apiCalls:u,apiAssertions:f,actions:$,consoleLogs:c};if(this.activeReportMode==="streaming"&&this.streamingWriter){let R=bt(y,h,t.id??"",n.retry),S=n.retry===t.results.length-1,N={id:R,navigations:p??[],networkRequests:d??[],apiCalls:u??[],apiAssertions:f??[],consoleLogs:c??[],actions:$??[],artifacts:et,failureDiagnostic:g};this.streamingWriter.writeTestDetail(R,N);let z={id:R,title:h[h.length-1]??t.title,titlePath:h,filePath:y,status:a,duration:n.duration,project:h[1]??"",retryIndex:n.retry,tags:o,hasNetworkData:(d?.length??0)>0,hasConsoleData:(c?.length??0)>0,hasArtifacts:et!==null,hasActionSteps:($?.length??0)>0,errorMessage:g?.message?.split(`
|
|
2447
|
+
`)[0]??null,networkCount:d?.length??0,consoleCount:c?.length??0,actionCount:$?.length??0,isRetry:!S};if(this.testIndex.push(z),S)switch(this.summaryCounters.total++,a){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.summaryCounters.totalApiCalls+=u?.length??0,this.summaryCounters.totalAssertions+=f?.length??0,this.summaryCounters.totalNavigations+=p?.length??0,this.summaryCounters.totalNetworkRequests+=d?.length??0,this.summaryCounters.totalConsoleLogs+=c?.length??0,this.summaryCounters.totalActionSteps+=$?.length??0,_.networkRequests=null,_.consoleLogs=null,_.actions=null,_.apiCalls=null,_.apiAssertions=null,_.navigations=[],_.artifacts=null,_.failure=null;}this.activeReportMode!=="streaming"&&this.collectedTests.push(_),this.testCount++,this.checkMemoryPressure();try{let R=this.config.cloud?.uploadStrategy;if(this.cloudClient?.isCloudMode()&&this.cloudRunId&&(R==="realtime"||R==="both")){let S=this.cloudClient.getAccessToken();S&&pr(this.cloudClient.getEndpoint(),S,this.cloudRunId,this.toTestResult(_));}}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.activeReportMode==="streaming"?this.testIndex.some(o=>o.status!=="skipped"):this.collectedTests.some(o=>o.status!=="skipped");!this.fixtureDataReceived&&l&&process.stderr.write(`
|
|
2123
2448
|
\u26A0 TestRelic: No fixture data received from any test.
|
|
2124
2449
|
To enable network logs, video sync, and timeline tracking, import the TestRelic fixture:
|
|
2125
2450
|
import { test, expect } from '@testrelic/playwright-analytics/fixture';
|
|
2126
2451
|
instead of:
|
|
2127
2452
|
import { test, expect } from '@playwright/test';
|
|
2128
2453
|
|
|
2129
|
-
`);let
|
|
2130
|
-
`);}}};var Jn=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Kn(e){let t=e.toLowerCase();return Jn.some(r=>t.includes(r))}var Q=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.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=[];}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(),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=s=>{try{let a=s,l=a.type(),i=a.text();if(l==="debug"&&i.startsWith("__testrelic_nav:")){try{let o=JSON.parse(i.slice(16));o.type&&o.url&&this.recordNavigation(o.url,o.type);}catch{}return}{let o=null;try{let d=a.location();d&&d.url&&(o=`${d.url}:${d.lineNumber}:${d.columnNumber}`);}catch{}let c=e.mapConsoleType(l);this.consoleLogs.push({level:c,text:i,timestamp:new Date().toISOString(),location:o});}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=i=>{this.currentNetworkCounter&&this.currentNetworkCounter.totalRequests++;try{let o=i,c=String(this.requestIdCounter++),d=o.postData()??null,p={url:o.url(),method:o.method(),resourceType:this.mapResourceType(o.resourceType()),headers:o.headers(),postData:d,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now()};this.pendingRequests.set(c,p),i.__testrelic_id=c;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let a=i=>{try{let o=i;if(this.currentNetworkCounter){let y=o.status();y>=400&&(this.currentNetworkCounter.failedRequests++,this.currentNetworkCounter.failedRequestUrls.push(y+" "+o.url()));let b=o.headers()["content-length"];b&&(this.currentNetworkCounter.totalBytes+=parseInt(b,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 p=Date.now()-d.startTimeMs,f=o.headers(),u=f["content-type"]??null,h=parseInt(f["content-length"]??"0",10)||0,g=u?!Kn(u):!1,v=(async()=>{let y=null;if(!g)try{y=(await o.body()).toString("utf-8");}catch{}let b={url:d.url,method:d.method,resourceType:d.resourceType,statusCode:o.status(),responseTimeMs:p,startedAt:d.startedAt,requestHeaders:d.headers,requestBody:d.postData,responseBody:y,responseHeaders:f,contentType:u,responseSize:h,requestBodyTruncated:d.postDataTruncated,responseBodyTruncated:!1,isBinary:g,error:null};this.capturedRequests.push(b);})();this.pendingBodyReads.push(v);}catch{}};this.page.on("response",a),this.listeners.push({event:"response",handler:a});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 p={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(p);}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 De=Symbol.for("__testrelic_call_id"),Wn="__testrelic_api_assertions",L=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:Wn,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}};var Oe="[REDACTED]";function kt(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())?Oe:e[s]);return n}function X(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=wt(r,n);return JSON.stringify(s)}function wt(e,t){if(Array.isArray(e))return e.map(r=>wt(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]=Oe:r[n]=wt(s,t);}return r}return e}function He(e,t,r){if(r.length>0){for(let n of r)if(Fe(e,n))return false}if(t.length>0){for(let n of t)if(Fe(e,n))return true;return false}return true}function Fe(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 Zn=["get","post","put","patch","delete","head","fetch"],Qn=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"],Xn="__testrelic_api_calls";function ts(e){let t=e.toLowerCase();return Qn.some(r=>t.includes(r))}function es(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 tt=class tt{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??tt.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 Zn){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:Xn,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 u=s();return L.set(u,r),u};let a=t.headersArray.bind(t);t.headersArray=function(){let u=a();return L.set(u,r),u};let l=t.json.bind(t);t.json=async function(){let u=await l();return u!=null&&typeof u=="object"&&L.set(u,r),u};let i=t.status.bind(t);t.status=function(){let u=i();return n.primitiveCallIds.set(u,r),u};let o=t.statusText.bind(t);t.statusText=function(){let u=o();return n.primitiveCallIds.set(u,r),u};let c=t.ok.bind(t);t.ok=function(){let u=c();return n.primitiveCallIds.set(u,r),u};let d=t.text.bind(t);t.text=async function(){let u=await d();return n.primitiveCallIds.set(u,r),u};let p=t.body.bind(t);t.body=async function(){let u=await p();return L.set(u,r),u};}createWrapper(t,r){let n=this;return async function(a,l){if(!He(a,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return r(a,l);let i=`api-call-${n.callCounter++}`,o=new Date().toISOString(),c=t==="fetch"?(l?.method??"GET").toUpperCase():t.toUpperCase(),d=es(l),p=performance.now();n._lastCallId=i,n.assertionTracker&&n.assertionTracker.setCurrentCallId(i);let f;try{f=await r(a,l);}catch(u){let h=performance.now();try{let g=n.apiConfig.captureRequestBody?X(d,n.apiConfig.redactBodyFields):null,v={id:i,timestamp:o,method:c,url:a,requestHeaders:null,requestBody:g,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((h-p)*100)/100,isBinary:!1,error:u instanceof Error?u.message:String(u)};n.capturedCalls.push(v);}catch{}throw u}try{let u=performance.now(),h=f.headers(),g=h["content-type"]??null,v=g?!ts(g):!1,y=null;n.apiConfig.captureRequestHeaders&&l?.headers&&(y=l.headers);let b=null;n.apiConfig.captureResponseHeaders&&(b=h);let x=n.apiConfig.captureRequestBody?d:null,w=null;if(n.apiConfig.captureResponseBody)try{v?w=(await f.body()).toString("base64"):w=await f.text();}catch{}y=kt(y,n.apiConfig.redactHeaders),b=kt(b,n.apiConfig.redactHeaders),x=X(x,n.apiConfig.redactBodyFields),w=X(w,n.apiConfig.redactBodyFields);let A={id:i,timestamp:o,method:c,url:f.url(),requestHeaders:y,requestBody:x,responseStatusCode:f.status(),responseStatusText:f.statusText(),responseHeaders:b,responseBody:w,responseTimeMs:Math.round((u-p)*100)/100,isBinary:v,error:null};n.capturedCalls.push(A);}catch{}try{f[De]=i,n.tagResponseMethods(f,i);}catch{}return f}}};tt.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 E=tt;var ns="__testrelic_api_config",ss="__testrelic_config_trackApiCalls";function Ct(e){let t=e.annotations.find(n=>n.type===ns&&n.description!==void 0);if(t)try{return JSON.parse(t.description,as)}catch{}let r=e.annotations.find(n=>n.type===ss&&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 as(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 $e={page:async({page:e},t,r)=>{let n=new Q(e);try{await n.init();}catch{}await t(e);try{let{navigations:s,networkRequests:a,consoleLogs:l}=await n.getData(),i={testRelicData:!0,version:PAYLOAD_VERSION,navigations:s,networkRequests:a,apiCalls:[],apiAssertions:[],consoleLogs:l};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(i)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{await n.flushLegacyAnnotations(r);}catch{}n.dispose();},request:async({request:e},t,r)=>{let n=Ct(r);if(!n.trackApiCalls){await t(e);return}let s=new N,a=new E(e,s,n);a.intercept(),await t(e);try{let l=a.getData(),i=n.captureAssertions?s.getData():[],o={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],networkRequests:[],apiCalls:l,apiAssertions:i,consoleLogs:[]};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(o)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{a.flushLegacyAnnotations(r);}catch{}try{s.flushLegacyAnnotations(r);}catch{}a.dispose(),s.dispose();}};test.extend($e);var ds={request:async({request:e},t,r)=>{let n=Ct(r);if(!n.trackApiCalls){await t(e);return}let s=new N,a=new E(e,s,n);a.intercept();let l=[],i=process.stdout.write,o=process.stderr.write;process.stdout.write=function(c,...d){try{let p=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!p.startsWith("[testrelic]")&&!p.startsWith("\u2139 TestRelic")&&!p.startsWith("\u2713 TestRelic")&&!p.startsWith("\u26A0 TestRelic")&&l.push({level:"stdout",text:p.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null});}catch{}return i.apply(process.stdout,[c,...d])},process.stderr.write=function(c,...d){try{let p=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!p.startsWith("[testrelic]")&&!p.startsWith("\u26A0 TestRelic")&&l.push({level:"stderr",text:p.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null});}catch{}return o.apply(process.stderr,[c,...d])};try{await t(e);}finally{process.stdout.write=i,process.stderr.write=o;}try{let c=a.getData(),d=n.captureAssertions?s.getData():[],p={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],networkRequests:[],apiCalls:c,apiAssertions:d,consoleLogs:l};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(p)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{a.flushLegacyAnnotations(r);}catch{}try{s.flushLegacyAnnotations(r);}catch{}a.dispose(),s.dispose();}};var Ge="@testrelic/playwright-analytics";function ps(e){return Array.isArray(e)?e.some(t=>Array.isArray(t)&&typeof t[0]=="string"&&t[0]===Ge):false}function us(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=ps(s)?s:[...s,[Ge,t??{}]];return defineConfig({...e,use:n,reporter:a})}var Ve=false;function Fi(e,t,r="manual_record"){if(!e||!e.annotations){Ve||(Ve=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
|
|
2131
|
-
|
|
2454
|
+
`),await qe();let i=null;if(this.config.includeArtifacts&&this.runTimestamp)try{let o=dirname(this.config.outputPath);i=$e(o,this.runTimestamp);let p=join(o,"artifact-manifest.json"),d=JSON.stringify(i),u=p+".tmp";writeFileSync(u,d,"utf-8"),renameSync(u,p);}catch{}if(this.activeReportMode==="streaming"&&this.streamingWriter)await this.finalizeStreamingReport(r,a,t,i);else {let o=this.buildTimeline(),p=new Map;for(let c of this.collectedTests){let g=p.get(c.testId);(!g||c.retry>g.retry)&&p.set(c.testId,c);}let d=Array.from(p.values()),u=Je(d,o.length),f={schemaVersion:rt,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:r,totalDuration:a,summary:u,ci:M(),metadata:this.config.metadata,timeline:o,shardRunIds:null};this.writeReport(f),await Bt(f,this.config,i),$t(u,this.config.outputPath,this.config.htmlReportPath,this.config.quiet),this.cloudClient&&await te(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,f,r,a,u);}}catch{}}async finalizeStreamingReport(t,r,n,s){if(!this.streamingWriter)return;let{totalApiCalls:a,totalAssertions:l,totalNavigations:i,totalNetworkRequests:o,totalConsoleLogs:p,totalActionSteps:d}=this.summaryCounters;this.summaryCounters={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0,interrupted:0,totalApiCalls:a,totalAssertions:l,totalNavigations:i,totalNetworkRequests:o,totalConsoleLogs:p,totalActionSteps:d};let u=new Map,f=new Map;for(let m of this.testIndex){let C=`${m.filePath}::${m.titlePath.join(" > ")}`,v=u.get(C);(v===void 0||m.retryIndex>v)&&u.set(C,m.retryIndex);}let c=0;for(let m of this.testIndex){let C=`${m.filePath}::${m.titlePath.join(" > ")}`,v=u.get(C);if(m.isRetry=m.retryIndex<v,m.isRetry)continue;switch(c++,this.summaryCounters.total++,m.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}let T=f.get(m.filePath);switch(T||(T={filePath:m.filePath,total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},f.set(m.filePath,T)),T.total++,m.status){case "passed":T.passed++;break;case "failed":T.failed++;break;case "flaky":T.flaky++;break;case "skipped":T.skipped++;break;case "timedout":T.timedOut++;break}}let g=Array.from(f.values());this.streamingWriter.writeIndex(this.testIndex),this.streamingWriter.writeCompactIndex(this.testIndex);let h={reporterTotal:this.summaryCounters.total,indexTotal:c,playwrightStatus:n.status,isValid:this.summaryCounters.total===c};h.isValid||process.stderr.write(`[testrelic] WARNING: Summary count mismatch \u2014 reporter: ${h.reporterTotal}, index: ${h.indexTotal}
|
|
2455
|
+
`);let b={total:this.summaryCounters.total,passed:this.summaryCounters.passed,failed:this.summaryCounters.failed,flaky:this.summaryCounters.flaky,skipped:this.summaryCounters.skipped,timedout:this.summaryCounters.timedOut,totalApiCalls:this.summaryCounters.totalApiCalls,uniqueApiUrls:0,apiCallsByMethod:{},apiCallsByStatusRange:{"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0},apiResponseTime:null,totalAssertions:this.summaryCounters.totalAssertions,passedAssertions:0,failedAssertions:0,totalNavigations:this.summaryCounters.totalNavigations,uniqueNavigationUrls:0,totalTimelineSteps:this.testIndex.length,totalActionSteps:this.summaryCounters.totalActionSteps,actionStepsByCategory:{}},x={testRunId:this.testRunId,startedAt:this.startedAt,completedAt:t,totalDuration:r,...this.summaryCounters,metadata:this.config.metadata,reportMode:"streaming",files:g,enrichedSummary:b,validation:h,writeErrors:this.streamingWriter.getWriteErrors()};this.streamingWriter.writeSummary(x);let k={schemaVersion:"2.0",generatedAt:new Date().toISOString(),reportMode:"streaming",summaryFile:"summary.json",indexFile:"index.json",testsDir:"tests",artifactsDir:"artifacts",testCount:this.testIndex.length,totalSizeBytes:this.streamingWriter.computeTotalSize()};this.streamingWriter.writeManifest(k),await Bt(this.buildStreamingReport(x,b,t,r),this.config,s),$t(b,this.config.outputPath,this.config.htmlReportPath,this.config.quiet);let y=this.streamingWriter.getReportDir();if(process.stderr.write(`[testrelic] Streaming report written to ${y}
|
|
2456
|
+
[testrelic] ${this.testIndex.length} test detail files on disk
|
|
2457
|
+
`),this.streamingWriter.getWriteErrors().length>0&&process.stderr.write(`[testrelic] WARNING: ${this.streamingWriter.getWriteErrors().length} write error(s) during streaming
|
|
2458
|
+
`),this.streamingWriter.dispose(),this.cloudClient){let m=this.buildStreamingReport(x,b,t,r);await te(this.cloudClient,this.config.cloud,this.config.cloud?.uploadStrategy,this.testRunId,this.cloudRunId,m,t,r,b);}this.testIndex.length=0,this.collectedTests.length=0,this.streamingWriter=null,this.cloudClient=null;}buildStreamingReport(t,r,n,s){return {schemaVersion:rt,testRunId:this.testRunId,startedAt:this.startedAt,completedAt:n,totalDuration:s,summary:r,ci:M(),metadata:this.config.metadata,timeline:[],shardRunIds:null}}printsToStdio(){return false}checkMemoryPressure(){try{let t=process.memoryUsage(),r=t.heapUsed/1024/1024;if(r<200)return;let n=t.heapUsed/t.heapTotal;n>.9&&this.activeReportMode==="embedded"?(process.stderr.write(`[testrelic] WARNING: High memory (${Math.round(r)} MB). Auto-switching to streaming mode.
|
|
2459
|
+
`),this.switchToStreamingMode()):n>.8&&process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
|
|
2460
|
+
`);}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let t=dirname(this.config.outputPath);this.streamingWriter=new W(t);for(let r of this.collectedTests){let n=bt(r.filePath,r.titlePath,r.testId,r.retry),s={id:n,navigations:r.navigations??[],networkRequests:r.networkRequests??[],apiCalls:r.apiCalls??[],apiAssertions:r.apiAssertions??[],consoleLogs:r.consoleLogs??[],actions:r.actions??[],artifacts:r.artifacts,failureDiagnostic:r.failure};this.streamingWriter.writeTestDetail(n,s);let a={id:n,title:r.titlePath[r.titlePath.length-1]??r.title,titlePath:r.titlePath,filePath:r.filePath,status:r.status,duration:r.duration,project:r.titlePath[1]??"",retryIndex:r.retry,tags:r.tags,hasNetworkData:(r.networkRequests?.length??0)>0,hasConsoleData:(r.consoleLogs?.length??0)>0,hasArtifacts:r.artifacts!==null,hasActionSteps:(r.actions?.length??0)>0,errorMessage:r.failure?.message?.split(`
|
|
2461
|
+
`)[0]??null,networkCount:r.networkRequests?.length??0,consoleCount:r.consoleLogs?.length??0,actionCount:r.actions?.length??0,isRetry:!1};switch(this.testIndex.push(a),this.summaryCounters.total++,r.status){case "passed":this.summaryCounters.passed++;break;case "failed":this.summaryCounters.failed++;break;case "flaky":this.summaryCounters.flaky++;break;case "skipped":this.summaryCounters.skipped++;break;case "timedout":this.summaryCounters.timedOut++;break;default:this.summaryCounters.interrupted++;break}this.summaryCounters.totalApiCalls+=r.apiCalls?.length??0,this.summaryCounters.totalAssertions+=r.apiAssertions?.length??0,this.summaryCounters.totalNavigations+=r.navigations?.length??0,this.summaryCounters.totalNetworkRequests+=r.networkRequests?.length??0,this.summaryCounters.totalConsoleLogs+=r.consoleLogs?.length??0,this.summaryCounters.totalActionSteps+=r.actions?.length??0;}this.collectedTests.length=0;}catch{}}buildTimeline(){let t=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls: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 We(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),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)}
|
|
2462
|
+
`);}}};var Fs=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Hs(e){let t=e.toLowerCase();return Fs.some(r=>t.includes(r))}var mt=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.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=[];}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(),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=s=>{try{let a=s,l=a.type(),i=a.text();if(l==="debug"&&i.startsWith("__testrelic_nav:")){try{let o=JSON.parse(i.slice(16));o.type&&o.url&&this.recordNavigation(o.url,o.type);}catch{}return}{let o=null;try{let d=a.location();d&&d.url&&(o=`${d.url}:${d.lineNumber}:${d.columnNumber}`);}catch{}let p=e.mapConsoleType(l);this.consoleLogs.push({level:p,text:i,timestamp:new Date().toISOString(),location:o});}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=i=>{this.currentNetworkCounter&&this.currentNetworkCounter.totalRequests++;try{let o=i,p=String(this.requestIdCounter++),d=o.postData()??null,u={url:o.url(),method:o.method(),resourceType:this.mapResourceType(o.resourceType()),headers:o.headers(),postData:d,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now()};this.pendingRequests.set(p,u),i.__testrelic_id=p;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let a=i=>{try{let o=i;if(this.currentNetworkCounter){let x=o.status();x>=400&&(this.currentNetworkCounter.failedRequests++,this.currentNetworkCounter.failedRequestUrls.push(x+" "+o.url()));let k=o.headers()["content-length"];k&&(this.currentNetworkCounter.totalBytes+=parseInt(k,10)||0);let y=o.request().resourceType(),m=this.mapResourceType(y);this.currentNetworkCounter.byType[m]++;}let p=o.request().__testrelic_id;if(!p)return;let d=this.pendingRequests.get(p);if(!d)return;this.pendingRequests.delete(p);let u=Date.now()-d.startTimeMs,f=o.headers(),c=f["content-type"]??null,g=parseInt(f["content-length"]??"0",10)||0,h=c?!Hs(c):!1,b=(async()=>{let x=null;if(!h)try{x=(await o.body()).toString("utf-8");}catch{}let k={url:d.url,method:d.method,resourceType:d.resourceType,statusCode:o.status(),responseTimeMs:u,startedAt:d.startedAt,requestHeaders:d.headers,requestBody:d.postData,responseBody:x,responseHeaders:f,contentType:c,responseSize:g,requestBodyTruncated:d.postDataTruncated,responseBodyTruncated:!1,isBinary:h,error:null};this.capturedRequests.push(k);})();this.pendingBodyReads.push(b);}catch{}};this.page.on("response",a),this.listeners.push({event:"response",handler:a});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,p=o.__testrelic_id;if(!p)return;let d=this.pendingRequests.get(p);if(!d)return;this.pendingRequests.delete(p);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:o.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 vr=Symbol.for("__testrelic_call_id"),Us="__testrelic_api_assertions",q=new WeakMap,O=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:Us,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}};var yr="[REDACTED]";function se(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())?yr:e[s]);return n}function vt(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=ne(r,n);return JSON.stringify(s)}function ne(e,t){if(Array.isArray(e))return e.map(r=>ne(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]=yr:r[n]=ne(s,t);}return r}return e}function wr(e,t,r){if(r.length>0){for(let n of r)if(br(e,n))return false}if(t.length>0){for(let n of t)if(br(e,n))return true;return false}return true}function br(e,t){try{return t instanceof RegExp?t.test(e):$s(t).test(e)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(t)}`),false}}function $s(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 zs=["get","post","put","patch","delete","head","fetch"],js=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"],Vs="__testrelic_api_calls";function Gs(e){let t=e.toLowerCase();return js.some(r=>t.includes(r))}function Ws(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 yt=class yt{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??yt.DEFAULT_API_CONFIG;}get lastCallId(){return this._lastCallId}getCallIdForValue(t){return t!=null&&typeof t=="object"?q.get(t)??null:this.primitiveCallIds.get(t)??null}intercept(){for(let r of zs){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:Vs,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 c=s();return q.set(c,r),c};let a=t.headersArray.bind(t);t.headersArray=function(){let c=a();return q.set(c,r),c};let l=t.json.bind(t);t.json=async function(){let c=await l();return c!=null&&typeof c=="object"&&q.set(c,r),c};let i=t.status.bind(t);t.status=function(){let c=i();return n.primitiveCallIds.set(c,r),c};let o=t.statusText.bind(t);t.statusText=function(){let c=o();return n.primitiveCallIds.set(c,r),c};let p=t.ok.bind(t);t.ok=function(){let c=p();return n.primitiveCallIds.set(c,r),c};let d=t.text.bind(t);t.text=async function(){let c=await d();return n.primitiveCallIds.set(c,r),c};let u=t.body.bind(t);t.body=async function(){let c=await u();return q.set(c,r),c};}createWrapper(t,r){let n=this;return async function(a,l){if(!wr(a,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return r(a,l);let i=`api-call-${n.callCounter++}`,o=new Date().toISOString(),p=t==="fetch"?(l?.method??"GET").toUpperCase():t.toUpperCase(),d=Ws(l),u=performance.now();n._lastCallId=i,n.assertionTracker&&n.assertionTracker.setCurrentCallId(i);let f;try{f=await r(a,l);}catch(c){let g=performance.now();try{let h=n.apiConfig.captureRequestBody?vt(d,n.apiConfig.redactBodyFields):null,b={id:i,timestamp:o,method:p,url:a,requestHeaders:null,requestBody:h,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((g-u)*100)/100,isBinary:!1,error:c instanceof Error?c.message:String(c)};n.capturedCalls.push(b);}catch{}throw c}try{let c=performance.now(),g=f.headers(),h=g["content-type"]??null,b=h?!Gs(h):!1,x=null;n.apiConfig.captureRequestHeaders&&l?.headers&&(x=l.headers);let k=null;n.apiConfig.captureResponseHeaders&&(k=g);let y=n.apiConfig.captureRequestBody?d:null,m=null;if(n.apiConfig.captureResponseBody)try{b?m=(await f.body()).toString("base64"):m=await f.text();}catch{}x=se(x,n.apiConfig.redactHeaders),k=se(k,n.apiConfig.redactHeaders),y=vt(y,n.apiConfig.redactBodyFields),m=vt(m,n.apiConfig.redactBodyFields);let C={id:i,timestamp:o,method:p,url:f.url(),requestHeaders:x,requestBody:y,responseStatusCode:f.status(),responseStatusText:f.statusText(),responseHeaders:k,responseBody:m,responseTimeMs:Math.round((c-u)*100)/100,isBinary:b,error:null};n.capturedCalls.push(C);}catch{}try{f[vr]=i,n.tagResponseMethods(f,i);}catch{}return f}}};yt.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 F=yt;var Ks="__testrelic_api_config",Ys="__testrelic_config_trackApiCalls";function ie(e){let t=e.annotations.find(n=>n.type===Ks&&n.description!==void 0);if(t)try{return JSON.parse(t.description,Zs)}catch{}let r=e.annotations.find(n=>n.type===Ys&&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 Zs(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 Cr={page:async({page:e},t,r)=>{let n=new mt(e);try{await n.init();}catch{}await t(e);try{let{navigations:s,networkRequests:a,consoleLogs:l}=await n.getData(),i={testRelicData:!0,version:PAYLOAD_VERSION,navigations:s,networkRequests:a,apiCalls:[],apiAssertions:[],consoleLogs:l};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(i)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{await n.flushLegacyAnnotations(r);}catch{}n.dispose();},request:async({request:e},t,r)=>{let n=ie(r);if(!n.trackApiCalls){await t(e);return}let s=new O,a=new F(e,s,n);a.intercept(),await t(e);try{let l=a.getData(),i=n.captureAssertions?s.getData():[],o={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],networkRequests:[],apiCalls:l,apiAssertions:i,consoleLogs:[]};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(o)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}try{a.flushLegacyAnnotations(r);}catch{}try{s.flushLegacyAnnotations(r);}catch{}a.dispose(),s.dispose();}};test.extend(Cr);var ea={request:async({request:e},t,r)=>{let n=ie(r);if(!n.trackApiCalls){await t(e);return}let s=new O,a=new F(e,s,n);a.intercept();let l=[],i=process.stdout.write,o=process.stderr.write;process.stdout.write=function(p,...d){try{let u=typeof p=="string"?p:Buffer.isBuffer(p)?p.toString("utf-8"):String(p);!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 i.apply(process.stdout,[p,...d])},process.stderr.write=function(p,...d){try{let u=typeof p=="string"?p:Buffer.isBuffer(p)?p.toString("utf-8"):String(p);!u.startsWith("[testrelic]")&&!u.startsWith("\u26A0 TestRelic")&&l.push({level:"stderr",text:u.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null});}catch{}return o.apply(process.stderr,[p,...d])};try{await t(e);}finally{process.stdout.write=i,process.stderr.write=o;}try{let p=a.getData(),d=n.captureAssertions?s.getData():[],u={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],networkRequests:[],apiCalls:p,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 Sr="@testrelic/playwright-analytics";function na(e){return Array.isArray(e)?e.some(t=>Array.isArray(t)&&typeof t[0]=="string"&&t[0]===Sr):false}function sa(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=na(s)?s:[...s,[Sr,t??{}]];return defineConfig({...e,use:n,reporter:a})}var Rr=false;function Go(e,t,r="manual_record"){if(!e||!e.annotations){Rr||(Rr=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
|
|
2463
|
+
`));return}let n={url:t,navigationType:r,timestamp:new Date().toISOString()};e.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}export{rt as SCHEMA_VERSION,ht as default,sa as defineConfig,Go as recordNavigation,ea as testRelicApiFixture,Cr as testRelicFixture};//# sourceMappingURL=index.js.map
|
|
2132
2464
|
//# sourceMappingURL=index.js.map
|