@testrelic/playwright-analytics 2.3.8 → 2.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import {randomUUID,createHash}from'crypto';import {mkdirSync,openSync,writeSync,closeSync,unlinkSync,writeFileSync,renameSync,existsSync,readFileSync,appendFileSync,readdirSync,statSync,rmSync,createReadStream}from'fs';import {join,dirname,relative,extname,resolve,parse,basename}from'path';import {PAYLOAD_VERSION,ATTACHMENT_NAME,ATTACHMENT_CONTENT_TYPE,isValidConfig,createError,ErrorCode,isTestRelicFilePayload,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 {tmpdir}from'os';import {createInterface}from'readline';import {copyFile}from'fs/promises';import {gzipSync}from'zlib';import {test,defineConfig}from'@playwright/test';import {performance}from'perf_hooks';var Mr=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Fr=".testrelic-report";function ve(t,e,r,n){let s=`${t}|${e.join("|")}|${r}|${n}`;return createHash("sha256").update(s).digest("hex").substring(0,12)}var W=class{constructor(e){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=join(e,Fr),this.testsDir=join(this.reportDir,"tests"),mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(e,r,n){try{let s=join(this.testsDir,e);mkdirSync(s,{recursive:!0});let a=join(s,"meta.json"),o=a+".tmp",i=JSON.stringify(r);return writeFileSync(o,i,"utf-8"),renameSync(o,a),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),n?.networkRequestsFile&&this.moveFile(n.networkRequestsFile,join(s,"network.jsonl")),n?.consoleLogsFile&&this.moveFile(n.consoleLogsFile,join(s,"console.jsonl")),n?.apiCallsFile&&this.moveFile(n.apiCallsFile,join(s,"api-calls.jsonl")),!0}catch(s){let a=s instanceof Error?s.message:String(s);return this.writeErrors.push({testId:e,error:a,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${e}: ${a}
2
- `),false}}moveFile(e,r){try{renameSync(e,r);}catch{try{let{copyFileSync:n}=Mr("fs");n(e,r);try{unlinkSync(e);}catch{}}catch(n){process.stderr.write(`[testrelic] Failed to move file ${e} \u2192 ${r}: ${n instanceof Error?n.message:String(n)}
1
+ import {randomUUID,createHash}from'crypto';import {mkdirSync,openSync,writeSync,closeSync,unlinkSync,writeFileSync,renameSync,existsSync,readFileSync,appendFileSync,readdirSync,statSync,rmSync,createReadStream}from'fs';import {join,dirname,relative,extname,resolve,parse,basename}from'path';import {PAYLOAD_VERSION,ATTACHMENT_NAME,ATTACHMENT_CONTENT_TYPE,isValidConfig,createError,ErrorCode,isTestRelicFilePayload,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 {tmpdir}from'os';import {createInterface}from'readline';import {copyFile}from'fs/promises';import {gzipSync}from'zlib';import {test,defineConfig}from'@playwright/test';import {performance}from'perf_hooks';var Er=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Fr=".testrelic-report";function ve(t,e,r,n){let s=`${t}|${e.join("|")}|${r}|${n}`;return createHash("sha256").update(s).digest("hex").substring(0,12)}var W=class{constructor(e){this.writeErrors=[];this.totalBytesWritten=0;this.reportDir=join(e,Fr),this.testsDir=join(this.reportDir,"tests"),mkdirSync(this.testsDir,{recursive:true});}getReportDir(){return this.reportDir}getWriteErrors(){return this.writeErrors}writeTestDetail(e,r,n){try{let s=join(this.testsDir,e);mkdirSync(s,{recursive:!0});let a=join(s,"meta.json"),o=a+".tmp",i=JSON.stringify(r);return writeFileSync(o,i,"utf-8"),renameSync(o,a),this.totalBytesWritten+=Buffer.byteLength(i,"utf-8"),n?.networkRequestsFile&&this.moveFile(n.networkRequestsFile,join(s,"network.jsonl")),n?.consoleLogsFile&&this.moveFile(n.consoleLogsFile,join(s,"console.jsonl")),n?.apiCallsFile&&this.moveFile(n.apiCallsFile,join(s,"api-calls.jsonl")),!0}catch(s){let a=s instanceof Error?s.message:String(s);return this.writeErrors.push({testId:e,error:a,timestamp:new Date().toISOString()}),process.stderr.write(`[testrelic] Failed to write test detail for ${e}: ${a}
2
+ `),false}}moveFile(e,r){try{renameSync(e,r);}catch{try{let{copyFileSync:n}=Er("fs");n(e,r);try{unlinkSync(e);}catch{}}catch(n){process.stderr.write(`[testrelic] Failed to move file ${e} \u2192 ${r}: ${n instanceof Error?n.message:String(n)}
3
3
  `);}}}writeIndex(e){let r=join(this.reportDir,"index.json"),n=r+".tmp",s=JSON.stringify(e);writeFileSync(n,s,"utf-8"),renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeCompactIndex(e){let r=join(this.reportDir,"index-compact.json"),n=r+".tmp",s=e.map(({titlePath:o,project:i,...l})=>l),a=JSON.stringify(s);writeFileSync(n,a,"utf-8"),renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(a,"utf-8");}writeSummary(e){let r=join(this.reportDir,"summary.json"),n=r+".tmp",s=JSON.stringify(e);writeFileSync(n,s,"utf-8"),renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}writeManifest(e){let r=join(this.reportDir,"manifest.json"),n=r+".tmp",s=JSON.stringify(e);writeFileSync(n,s,"utf-8"),renameSync(n,r),this.totalBytesWritten+=Buffer.byteLength(s,"utf-8");}computeTotalSize(){return this.totalBytesWritten}dispose(){}};var zr=".testrelic",Vr=5,Wr=new Set(["__proto__","constructor","prototype"]),it=Object.freeze({apiKey:null,endpoint:"https://api.testrelic.com/api/v1",uploadStrategy:"batch",timeout:3e4,projectName:null,queueMaxAge:6048e5,queueDirectory:".testrelic/queue"}),Gr={s:1e3,m:60*1e3,h:3600*1e3,d:1440*60*1e3};function lt(t){let e=resolve(t);for(let r=0;r<=Vr;r++){let n=join(e,zr);if(existsSync(n))return n;let s=dirname(e);if(s===e)break;e=s;}return null}function dt(t){try{let e=readFileSync(t,"utf-8"),r=JSON.parse(e);return typeof r!="object"||r===null||Array.isArray(r)||!ct(r)?null:r}catch{return null}}function ct(t){for(let e of Object.keys(t)){if(Wr.has(e))return false;let r=t[e];if(typeof r=="object"&&r!==null&&!Array.isArray(r)&&!ct(r))return false}return true}function ut(t){let e=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(t);if(e)return process.env[e[1]]??null;let r=/^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(t);return r?process.env[r[1]]??null:t}function ye(t){let e=Object.create(null);for(let r of Object.keys(t)){let n=t[r];typeof n=="string"&&n.startsWith("$")?e[r]=ut(n):typeof n=="object"&&n!==null&&!Array.isArray(n)?e[r]=ye(n):e[r]=n;}return e}function ot(t){let e=/^(\d+)\s*([smhd])$/.exec(t.trim());if(!e)return null;let r=parseInt(e[1],10),n=e[2],s=Gr[n];return !s||r<=0?null:r*s}function pt(t,e){let r=Object.create(null);if(Object.assign(r,it),t){let l=t.cloud;l&&typeof l=="object"&&(typeof l.endpoint=="string"&&(r.endpoint=l.endpoint),typeof l.upload=="string"&&(r.uploadStrategy=l.upload),typeof l.timeout=="number"&&(r.timeout=l.timeout),typeof l.apiKey=="string"&&l.apiKey.length>0&&(r.apiKey=l.apiKey));let d=t.project;d&&typeof d=="object"&&typeof d.name=="string"&&(r.projectName=d.name);let c=t.queue;if(c&&typeof c=="object"){if(typeof c.maxAge=="string"){let p=ot(c.maxAge);p!==null&&(r.queueMaxAge=p);}typeof c.directory=="string"&&(r.queueDirectory=c.directory);}}if(e){if(typeof e.apiKey=="string"&&e.apiKey.length>0){let l=e.apiKey.startsWith("$")?ut(e.apiKey):e.apiKey;l&&(r.apiKey=l);}if(typeof e.endpoint=="string"&&(r.endpoint=e.endpoint),typeof e.upload=="string"&&(r.uploadStrategy=e.upload),typeof e.timeout=="number"&&(r.timeout=e.timeout),typeof e.projectName=="string"&&(r.projectName=e.projectName),typeof e.queueMaxAge=="string"){let l=ot(e.queueMaxAge);l!==null&&(r.queueMaxAge=l);}typeof e.queueDirectory=="string"&&(r.queueDirectory=e.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 o=process.env.TESTRELIC_CLOUD_TIMEOUT;if(o){let l=parseInt(o,10);!isNaN(l)&&l>=1e3&&l<=12e4&&(r.timeout=l);}let i=Object.freeze(r);return isValidCloudConfig(i)?i:it}var Zr=[/AKIA[A-Z0-9]{16}/g,/Bearer\s+[A-Za-z0-9\-._~+/]+=*/g,/-----BEGIN\s+(RSA\s+)?PRIVATE\sKEY-----[\s\S]*?-----END/g,/\/\/[^:]+:[^@]+@/g],Qr=["authorization","cookie","set-cookie","x-api-key"],Xr=["password","secret","token","apiKey","api_key"];function ft(t){let e=Object.create(null);return e.trackApiCalls=t?.trackApiCalls??true,e.captureRequestHeaders=t?.captureRequestHeaders??true,e.captureResponseHeaders=t?.captureResponseHeaders??true,e.captureRequestBody=t?.captureRequestBody??true,e.captureResponseBody=t?.captureResponseBody??true,e.captureAssertions=t?.captureAssertions??true,e.redactHeaders=t?.redactHeaders??[...Qr],e.redactBodyFields=t?.redactBodyFields??[...Xr],e.apiIncludeUrls=t?.apiIncludeUrls??[],e.apiExcludeUrls=t?.apiExcludeUrls??[],Object.freeze(e)}function gt(t){if(t!==void 0&&!isValidConfig(t))throw createError(ErrorCode.CONFIG_INVALID,"Invalid reporter configuration");let e=Object.create(null);e.outputPath=t?.outputPath??"./test-results/analytics-timeline.json",e.includeStackTrace=t?.includeStackTrace??false,e.includeCodeSnippets=t?.includeCodeSnippets??true,e.codeContextLines=t?.codeContextLines??3,e.includeNetworkStats=t?.includeNetworkStats??true,e.navigationTypes=t?.navigationTypes??null,e.redactPatterns=[...Zr,...t?.redactPatterns??[]],e.testRunId=t?.testRunId??null,e.metadata=t?.metadata??null;let r=e.outputPath;e.openReport=t?.openReport??true,e.htmlReportPath=t?.htmlReportPath??r.replace(/\.json$/,".html"),e.includeArtifacts=t?.includeArtifacts??true,e.trackApiCalls=t?.trackApiCalls??true,e.quiet=t?.quiet??false,e.includeActionSteps=t?.includeActionSteps??true,e.captureConsoleLogs=t?.captureConsoleLogs??true;let n=lt(process.cwd()),s=n?dt(n):null,a=s?ye(s):null,o=pt(a,t?.cloud);return e.cloud=o.apiKey?o:null,e.reportMode=t?.reportMode??"streaming",e.streamingThreshold=t?.streamingThreshold??0,Object.freeze(e)}var X="1.3.0";function ht(t,e,r){try{let s=readFileSync(t,"utf-8").split(`
4
4
  `);if(e<1||e>s.length)return null;let a=Math.max(1,e-r),o=Math.min(s.length,e+r),i=[];for(let l=a;l<=o;l++){let d=l===e?">":" ",c=String(l).padStart(String(o).length," ");i.push(`${d} ${c} | ${s[l-1]}`);}return i.join(`
5
5
  `)}catch{return null}}function mt(t){return e=>{let r=e;for(let n of t)if(typeof n=="string"){let s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");r=r.replace(new RegExp(s,"g"),"[REDACTED]");}else {let s=n.flags.includes("g")?n.flags:n.flags+"g",a=new RegExp(n.source,s);r=r.replace(a,"[REDACTED]");}return r}}function tn(t){return t.GITHUB_ACTIONS!=="true"?null:{provider:"github-actions",buildId:t.GITHUB_RUN_ID??null,commitSha:t.GITHUB_SHA??null,branch:t.GITHUB_REF_NAME??null,runUrl:t.GITHUB_SERVER_URL&&t.GITHUB_REPOSITORY&&t.GITHUB_RUN_ID?`${t.GITHUB_SERVER_URL}/${t.GITHUB_REPOSITORY}/actions/runs/${t.GITHUB_RUN_ID}`:null}}function rn(t){return t.GITLAB_CI!=="true"?null:{provider:"gitlab-ci",buildId:t.CI_PIPELINE_ID??null,commitSha:t.CI_COMMIT_SHA??null,branch:t.CI_COMMIT_BRANCH??t.CI_COMMIT_REF_NAME??null,runUrl:t.CI_PIPELINE_URL??null}}function nn(t){if(!t.JENKINS_URL)return null;let e=t.GIT_BRANCH??null;return e?.startsWith("origin/")&&(e=e.slice(7)),{provider:"jenkins",buildId:t.BUILD_ID??null,commitSha:t.GIT_COMMIT??null,branch:e,runUrl:t.BUILD_URL??null}}function sn(t){return t.CIRCLECI!=="true"?null:{provider:"circleci",buildId:t.CIRCLE_BUILD_NUM??null,commitSha:t.CIRCLE_SHA1??null,branch:t.CIRCLE_BRANCH??null,runUrl:t.CIRCLE_BUILD_URL??null}}function an(t){if(!t.BITBUCKET_PIPELINE_UUID)return null;let e=t.BITBUCKET_WORKSPACE&&t.BITBUCKET_REPO_SLUG&&t.BITBUCKET_PIPELINE_UUID?`https://bitbucket.org/${t.BITBUCKET_WORKSPACE}/${t.BITBUCKET_REPO_SLUG}/pipelines/results/${t.BITBUCKET_PIPELINE_UUID}`:null;return {provider:"bitbucket-pipelines",buildId:t.BITBUCKET_BUILD_NUMBER??null,commitSha:t.BITBUCKET_COMMIT??null,branch:t.BITBUCKET_BRANCH??null,runUrl:e}}var on=[tn,rn,nn,sn,an];function D(t){let e=process.env;for(let r of on){let n=r(e);if(n)return n}return null}var be=`
@@ -860,16 +860,18 @@ body{
860
860
  var hasApiCalls=t.apiCalls&&t.apiCalls.length>0;
861
861
  var hasActions=t.actions&&t.actions.length>0;
862
862
  var hasConsoleLogs=t.consoleLogs&&t.consoleLogs.length>0;
863
+ var hasNetworkReqs=t.networkRequests&&t.networkRequests.length>0;
863
864
  var hasVideo=!!(t.artifacts&&t.artifacts.video);
864
865
  /* Compute base time for video offset calculation (console/network) */
865
866
  var baseTime=0;
866
867
  if(hasVideo&&t.startedAt){baseTime=Date.parse(t.startedAt);}
867
868
  if(!baseTime&&hasVideo&&t.consoleLogs&&t.consoleLogs.length>0&&t.consoleLogs[0].timestamp){baseTime=Date.parse(t.consoleLogs[0].timestamp);}
868
- if(hasArt||hasSteps||hasApiCalls||hasActions||hasConsoleLogs){
869
+ if(hasArt||hasSteps||hasApiCalls||hasActions||hasConsoleLogs||hasNetworkReqs){
869
870
  h+='<div class="drawer-sections">';
870
871
  if(hasArt)h+='<div class="drawer-section">'+renderArtifactColumn(t.artifacts)+'</div>';
871
872
  if(hasActions)h+='<div class="drawer-section">'+renderActionsColumn(t.actions,hasVideo)+'</div>';
872
873
  if(hasSteps)h+='<div class="drawer-section">'+renderTimelineColumn(t.steps,t.networkRequests,t.consoleLogs,t.testType,hasVideo,baseTime)+'</div>';
874
+ if(!hasSteps&&hasNetworkReqs&&typeof renderNetworkDevtools==='function')h+='<div class="drawer-section">'+renderNetworkDevtools(t.networkRequests,t._testId)+'</div>';
873
875
  if(!hasSteps&&hasConsoleLogs)h+='<div class="drawer-section">'+renderConsoleColumn(t.consoleLogs,t.testType,hasVideo,baseTime)+'</div>';
874
876
  if(hasApiCalls)h+='<div class="drawer-section">'+renderApiCallsColumn(t.apiCalls)+'</div>';
875
877
  h+='</div>';
@@ -939,47 +941,44 @@ body{
939
941
  function loadHeavyData(testId,merged){
940
942
  var fetchData=window.__trFetchTestData;
941
943
  if(!fetchData)return;
944
+ var pending=0;
945
+ var loaded=0;
946
+ function onLoaded(){loaded++;if(loaded>=pending){renderDrawer(testId,merged);}}
942
947
  /* Load first page of network requests */
943
948
  if(merged._networkCount>0){
949
+ pending++;
944
950
  fetchData(testId,'network',1,100,function(err,result){
945
- if(err||!result)return;
946
- merged.networkRequests=result.items;
947
- merged._networkTotal=result.total;
948
- merged._networkPage=1;
949
- merged._networkPageSize=result.pageSize;
950
- /* Re-render network section if drawer still shows this test */
951
- var ndtEl=document.querySelector('.ndt[data-testid="'+testId+'"]');
952
- if(ndtEl&&typeof renderNetworkDevtools==='function'){
953
- ndtEl.outerHTML=renderNetworkDevtools(merged.networkRequests,merged._testId);
954
- }else{
955
- /* If no network section rendered yet, re-render drawer */
956
- renderDrawer(testId,merged);
951
+ if(!err&&result){
952
+ merged.networkRequests=result.items;
953
+ merged._networkTotal=result.total;
954
+ merged._networkPage=1;
955
+ merged._networkPageSize=result.pageSize;
957
956
  }
957
+ onLoaded();
958
958
  });
959
959
  }
960
960
  /* Load first page of console logs */
961
961
  if(merged._consoleCount>0){
962
+ pending++;
962
963
  fetchData(testId,'console',1,200,function(err,result){
963
- if(err||!result)return;
964
- merged.consoleLogs=result.items;
965
- merged._consoleTotal=result.total;
966
- merged._consolePage=1;
967
- /* Re-render if drawer still shows this test */
968
- var conEl=document.querySelector('.console-panel[data-testid="'+testId+'"]');
969
- if(conEl&&typeof renderConsolePanel==='function'){
970
- conEl.outerHTML=renderConsolePanel(merged.consoleLogs,merged._testId);
964
+ if(!err&&result){
965
+ merged.consoleLogs=result.items;
966
+ merged._consoleTotal=result.total;
967
+ merged._consolePage=1;
971
968
  }
969
+ onLoaded();
972
970
  });
973
971
  }
974
972
  /* Load first page of API calls */
975
973
  if(merged._apiCallsCount>0){
974
+ pending++;
976
975
  fetchData(testId,'api-calls',1,50,function(err,result){
977
- if(err||!result)return;
978
- merged.apiCalls=result.items;
979
- merged._apiCallsTotal=result.total;
980
- merged._apiCallsPage=1;
981
- /* Re-render drawer with API calls */
982
- renderDrawer(testId,merged);
976
+ if(!err&&result){
977
+ merged.apiCalls=result.items;
978
+ merged._apiCallsTotal=result.total;
979
+ merged._apiCallsPage=1;
980
+ }
981
+ onLoaded();
983
982
  });
984
983
  }
985
984
  }
@@ -2479,10 +2478,10 @@ ${o?`<script id="artifact-manifest-data" type="application/json">${o}</script>`:
2479
2478
  </body>
2480
2479
  </html>`}function Le(t){try{let e=process.platform,r;e==="darwin"?r=`open "${t}"`:e==="win32"?r=`start "" "${t}"`:r=`xdg-open "${t}"`,exec(r,n=>{n&&process.stderr.write(`[testrelic] Failed to open browser: ${n.message}
2481
2480
  `);});}catch{}}var yt=join(tmpdir(),"testrelic-data"),N=class{constructor(e){this.count=0;this.closed=false;mkdirSync(yt,{recursive:true}),this.filePath=join(yt,`${e}-${randomUUID().substring(0,8)}.jsonl`),this.fd=openSync(this.filePath,"w");}append(e){if(this.closed)return;let r=JSON.stringify(e)+`
2482
- `;writeSync(this.fd,r),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{closeSync(this.fd);}catch{}}}cleanup(){try{unlinkSync(this.filePath);}catch{}}};async function wt(t,e,r,n){let s=(e-1)*r,a=[],o=0,i=createInterface({input:createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let c of i)if(c.length!==0){if(o>=s&&a.length<r)try{a.push(JSON.parse(c));}catch{}if(o++,a.length>=r&&n!==void 0)break}let l=n??o,d=Math.max(1,Math.ceil(l/r));return {items:a,total:l,page:e,pageSize:r,totalPages:d}}var Ct=/^[a-f0-9]{12}$/,Ne=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Tt=500;function x(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function St(t){t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type");}function re(t){try{return existsSync(t)?JSON.parse(readFileSync(t,"utf-8")):null}catch{return null}}function ne(t){let e=0;try{let r=readdirSync(t,{withFileTypes:!0});for(let n of r){let s=join(t,n.name);n.isFile()?e+=statSync(s).size:n.isDirectory()&&(e+=ne(s));}}catch{}return e}function Rt(t,e,r,n){let s=re(join(r,"index.json"));x(e,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-n)/1e3)});}function At(t,e,r){let n=re(join(r,"summary.json"));if(!n){x(e,404,{error:"Summary not found"});return}x(e,200,n);}function _t(t,e,r){let n=re(join(r,"index.json"));if(!n){x(e,404,{error:"Test index not found"});return}let a=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,o=Math.max(1,parseInt(a.get("page")??"1",10)||1),i=Math.min(Tt,Math.max(1,parseInt(a.get("pageSize")??"100",10)||100)),l=a.get("status")?.split(",").filter(Boolean)??null,d=a.get("file")??null,c=a.get("search")?.toLowerCase()??null,p=a.get("tag")?.split(",").filter(Boolean)??null,f=a.get("sort")??"file",u=a.get("order")==="desc"?-1:1,g=n;l&&l.length>0&&(g=g.filter(w=>l.includes(w.status))),d&&(g=g.filter(w=>w.filePath===d||w.filePath.startsWith(d+"/"))),c&&(g=g.filter(w=>w.title.toLowerCase().includes(c)||w.filePath.toLowerCase().includes(c))),p&&p.length>0&&(g=g.filter(w=>p.some(y=>w.tags.includes(y)))),g=[...g].sort((w,y)=>{let T=0;switch(f){case "duration":T=w.duration-y.duration;break;case "status":T=w.status.localeCompare(y.status);break;case "title":T=w.title.localeCompare(y.title);break;default:T=w.filePath.localeCompare(y.filePath);break}return T*u});let h=g.length,m=Math.max(1,Math.ceil(h/i)),b=(o-1)*i,C=g.slice(b,b+i);x(e,200,{tests:C,pagination:{page:o,pageSize:i,totalItems:h,totalPages:m},filters:{status:l,file:d,search:c,tag:p}});}function It(t,e,r,n){if(!Ct.test(n)){x(e,400,{error:"Invalid test ID format"});return}let s=join(r,"tests",n,"meta.json"),a=join(r,"tests",`${n}.json`),o=existsSync(s)?s:existsSync(a)?a:null;if(!o){x(e,404,{error:`Test not found: ${n}`});return}try{let i=readFileSync(o,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(i);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}async function Lt(t,e,r,n,s){if(!Ct.test(n)){x(e,400,{error:"Invalid test ID format"});return}let o=join(r,"tests",n,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!existsSync(o)){x(e,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let l=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,d=Math.max(1,parseInt(l.get("page")??"1",10)||1),c=Math.min(Tt,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),p,f=join(r,"tests",n,"meta.json");if(existsSync(f))try{let g=JSON.parse(readFileSync(f,"utf-8"));switch(s){case "network":p=g.networkRequestsCount;break;case "console":p=g.consoleLogsCount;break;case "api-calls":p=g.apiCallsCount;break}}catch{}let u=await wt(o,d,c,p);x(e,200,u);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}function Nt(t,e,r){let n=re(join(r,"index.json"));if(!n){x(e,404,{error:"Test index not found"});return}let s=new Map;for(let o of n){if(o.isRetry)continue;let i=s.get(o.filePath);switch(i||(i={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},s.set(o.filePath,i)),i.total++,o.status){case "passed":i.passed++;break;case "failed":i.failed++;break;case "flaky":i.flaky++;break;case "skipped":i.skipped++;break;case "timedout":i.timedOut++;break}}let a=Array.from(s.entries()).map(([o,i])=>({filePath:o,...i})).sort((o,i)=>o.filePath.localeCompare(i.filePath));x(e,200,{files:a});}function Et(t,e,r){if(!existsSync(r)){x(e,200,{runs:[],totalSizeBytes:0});return}try{let n=[],s=0,a=readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!Ne.test(o.name))continue;let i=join(r,o.name),l=ne(i),d=readdirSync(i,{withFileTypes:!0}).filter(c=>c.isDirectory());n.push({folderName:o.name,totalSizeBytes:l,testCount:d.length}),s+=l;}n.sort((o,i)=>i.folderName.localeCompare(o.folderName)),x(e,200,{runs:n,totalSizeBytes:s});}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}function Mt(t,e,r){try{let n=0,s=0;if(existsSync(r)){let a=readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!Ne.test(o.name))continue;let i=join(r,o.name),l=ne(i);rmSync(i,{recursive:!0,force:!0}),s+=l,n++;}}x(e,200,{deletedCount:n,freedBytes:s});}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}function Pt(t,e,r,n){if(!Ne.test(n)){x(e,400,{error:"Invalid folder name"});return}let s=join(r,n);try{if(!statSync(s).isDirectory()){x(e,404,{error:"Not found"});return}}catch{x(e,404,{error:"Not found"});return}try{let a=ne(s);rmSync(s,{recursive:!0,force:!0}),x(e,200,{deleted:n,freedBytes:a});}catch(a){x(e,500,{error:a instanceof Error?a.message:String(a)});}}function Dt(t,e,r){x(e,200,{status:"shutting_down"}),r.close();}function Ee(t,e,r){if(!existsSync(r)){x(e,404,{error:"File not found"});return}try{let n=readFileSync(r),s=extname(r).toLowerCase(),a=wn[s]??"application/octet-stream";e.writeHead(200,{"Content-Type":a}),e.end(n);}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}var wn={".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 Tn=9323,Sn=10,Rn=1800*1e3;function G(t,e){return new Promise((r,n)=>{let s=e?.port??Tn,a=Date.now(),o,i=0,l=existsSync(join(t,"artifacts"))?join(t,"artifacts"):existsSync(join(t,"..","artifacts"))?join(t,"..","artifacts"):join(t,"artifacts");function d(){clearTimeout(o),o=setTimeout(()=>{p.close();},Rn);}let c=e?.htmlPath??null;if(!c){let u=dirname(t);try{let g=readdirSync(u).find(h=>h.endsWith(".html"));g&&(c=join(u,g));}catch{}}let p=createServer((u,g)=>{if(d(),St(g),u.method==="OPTIONS"){g.writeHead(204),g.end();return}let h;try{h=new URL(u.url??"/",`http://${u.headers.host??"localhost"}`).pathname;}catch{x(g,400,{error:"Invalid URL"});return}if(u.method==="GET"&&(h==="/"||h==="/index.html")){if(c&&existsSync(c)){Ee(u,g,c);return}x(g,404,{error:"HTML report not found"});return}if(u.method==="GET"&&h==="/api/health"){Rt(u,g,t,a);return}if(u.method==="GET"&&h==="/api/summary"){At(u,g,t);return}if(u.method==="GET"&&h==="/api/tests"){_t(u,g,t);return}if(u.method==="GET"&&h==="/api/files"){Nt(u,g,t);return}let m=h.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(u.method==="GET"&&m){Lt(u,g,t,m[1],m[2]);return}let b=h.match(/^\/api\/tests\/([a-f0-9]+)$/);if(u.method==="GET"&&b){It(u,g,t,b[1]);return}if(u.method==="GET"&&h==="/api/artifacts"){Et(u,g,l);return}if(u.method==="DELETE"&&h==="/api/artifacts"){Mt(u,g,l);return}let C=h.match(/^\/api\/artifacts\/(.+)$/);if(u.method==="DELETE"&&C){Pt(u,g,l,decodeURIComponent(C[1]));return}if(u.method==="GET"&&h.startsWith("/artifacts/")){let w=decodeURIComponent(h.slice(11));if(w.includes("..")||w.includes("\0")){x(g,400,{error:"Invalid path"});return}Ee(u,g,join(l,w));return}if(u.method==="POST"&&h==="/api/shutdown"){Dt(u,g,p);return}x(g,404,{error:"Not found"});});function f(u){let g=h=>{h.code==="EADDRINUSE"&&i<Sn?(i++,f(u+1)):n(h);};p.once("error",g),p.listen(u,"127.0.0.1",()=>{p.removeListener("error",g);let h=p.address();if(!h||typeof h=="string"){n(new Error("Failed to get server address"));return}d(),r({port:h.port,dispose:()=>new Promise(m=>{clearTimeout(o),p.close(()=>m());})});});}f(s);})}async function Ft(t){let e=await G(t);return {port:e.port,dispose:e.dispose}}function In(t,e,r){let n=JSON.stringify(t),s=r?JSON.stringify(r):null;return vt(n,e,s)}async function Pe(t,e,r){try{let n=null,s=null,a=e.reportMode==="streaming"||e.reportMode==="auto"&&t.timeline.length===0&&t.summary.total>=e.streamingThreshold,o,i=e.htmlReportPath,l=dirname(i);mkdirSync(l,{recursive:!0});let d="",c="[]",p=null;if(a){d=JSON.stringify(t.summary);let u=dirname(e.outputPath),g=join(u,".testrelic-report");try{let h=join(g,"index-compact.json"),m=join(g,"index.json");existsSync(h)?c=readFileSync(h,"utf-8"):existsSync(m)&&(c=readFileSync(m,"utf-8"));}catch{}p=r?JSON.stringify(r):null,o=Ie(d,c,null,p);}else o=In(t,null,r);let f=i+".tmp";if(writeFileSync(f,o,"utf-8"),renameSync(f,i),a){if(t.ci===null){let u=dirname(e.outputPath),g=join(u,".testrelic-report"),h=resolve(i);try{if(await Nn(),n=await En(g),!n){s=await G(g,{htmlPath:h}),n=s.port;let m=setInterval(()=>{},6e4),b=()=>{clearInterval(m),s?.dispose();};process.on("SIGINT",b),process.on("SIGTERM",b),setTimeout(b,1800*1e3).unref();}if(n){process.stderr.write(`
2481
+ `;writeSync(this.fd,r),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{closeSync(this.fd);}catch{}}}cleanup(){try{unlinkSync(this.filePath);}catch{}}};async function wt(t,e,r,n){let s=(e-1)*r,a=[],o=0,i=createInterface({input:createReadStream(t,{encoding:"utf-8"}),crlfDelay:1/0});for await(let c of i)if(c.length!==0){if(o>=s&&a.length<r)try{a.push(JSON.parse(c));}catch{}if(o++,a.length>=r&&n!==void 0)break}let l=n??o,d=Math.max(1,Math.ceil(l/r));return {items:a,total:l,page:e,pageSize:r,totalPages:d}}var Ct=/^[a-f0-9]{12}$/,Ne=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Tt=500;function x(t,e,r){t.writeHead(e,{"Content-Type":"application/json"}),t.end(JSON.stringify(r));}function St(t){t.setHeader("Access-Control-Allow-Origin","*"),t.setHeader("Access-Control-Allow-Methods","GET, DELETE, OPTIONS"),t.setHeader("Access-Control-Allow-Headers","Content-Type");}function re(t){try{return existsSync(t)?JSON.parse(readFileSync(t,"utf-8")):null}catch{return null}}function ne(t){let e=0;try{let r=readdirSync(t,{withFileTypes:!0});for(let n of r){let s=join(t,n.name);n.isFile()?e+=statSync(s).size:n.isDirectory()&&(e+=ne(s));}}catch{}return e}function Rt(t,e,r,n){let s=re(join(r,"index.json"));x(e,200,{status:"ok",reportMode:"streaming",testCount:s?.length??0,uptime:Math.floor((Date.now()-n)/1e3)});}function At(t,e,r){let n=re(join(r,"summary.json"));if(!n){x(e,404,{error:"Summary not found"});return}x(e,200,n);}function _t(t,e,r){let n=re(join(r,"index.json"));if(!n){x(e,404,{error:"Test index not found"});return}let a=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,o=Math.max(1,parseInt(a.get("page")??"1",10)||1),i=Math.min(Tt,Math.max(1,parseInt(a.get("pageSize")??"100",10)||100)),l=a.get("status")?.split(",").filter(Boolean)??null,d=a.get("file")??null,c=a.get("search")?.toLowerCase()??null,p=a.get("tag")?.split(",").filter(Boolean)??null,f=a.get("sort")??"file",u=a.get("order")==="desc"?-1:1,g=n;l&&l.length>0&&(g=g.filter(w=>l.includes(w.status))),d&&(g=g.filter(w=>w.filePath===d||w.filePath.startsWith(d+"/"))),c&&(g=g.filter(w=>w.title.toLowerCase().includes(c)||w.filePath.toLowerCase().includes(c))),p&&p.length>0&&(g=g.filter(w=>p.some(y=>w.tags.includes(y)))),g=[...g].sort((w,y)=>{let T=0;switch(f){case "duration":T=w.duration-y.duration;break;case "status":T=w.status.localeCompare(y.status);break;case "title":T=w.title.localeCompare(y.title);break;default:T=w.filePath.localeCompare(y.filePath);break}return T*u});let h=g.length,m=Math.max(1,Math.ceil(h/i)),b=(o-1)*i,C=g.slice(b,b+i);x(e,200,{tests:C,pagination:{page:o,pageSize:i,totalItems:h,totalPages:m},filters:{status:l,file:d,search:c,tag:p}});}function It(t,e,r,n){if(!Ct.test(n)){x(e,400,{error:"Invalid test ID format"});return}let s=join(r,"tests",n,"meta.json"),a=join(r,"tests",`${n}.json`),o=existsSync(s)?s:existsSync(a)?a:null;if(!o){x(e,404,{error:`Test not found: ${n}`});return}try{let i=readFileSync(o,"utf-8");e.writeHead(200,{"Content-Type":"application/json"}),e.end(i);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}async function Lt(t,e,r,n,s){if(!Ct.test(n)){x(e,400,{error:"Invalid test ID format"});return}let o=join(r,"tests",n,{network:"network.jsonl",console:"console.jsonl","api-calls":"api-calls.jsonl"}[s]);if(!existsSync(o)){x(e,200,{items:[],total:0,page:1,pageSize:50,totalPages:0});return}try{let l=new URL(t.url??"/",`http://${t.headers.host}`).searchParams,d=Math.max(1,parseInt(l.get("page")??"1",10)||1),c=Math.min(Tt,Math.max(1,parseInt(l.get("pageSize")??"50",10)||50)),p,f=join(r,"tests",n,"meta.json");if(existsSync(f))try{let g=JSON.parse(readFileSync(f,"utf-8"));switch(s){case "network":p=g.networkRequestsCount;break;case "console":p=g.consoleLogsCount;break;case "api-calls":p=g.apiCallsCount;break}}catch{}let u=await wt(o,d,c,p);x(e,200,u);}catch(i){x(e,500,{error:i instanceof Error?i.message:String(i)});}}function Nt(t,e,r){let n=re(join(r,"index.json"));if(!n){x(e,404,{error:"Test index not found"});return}let s=new Map;for(let o of n){if(o.isRetry)continue;let i=s.get(o.filePath);switch(i||(i={total:0,passed:0,failed:0,flaky:0,skipped:0,timedOut:0},s.set(o.filePath,i)),i.total++,o.status){case "passed":i.passed++;break;case "failed":i.failed++;break;case "flaky":i.flaky++;break;case "skipped":i.skipped++;break;case "timedout":i.timedOut++;break}}let a=Array.from(s.entries()).map(([o,i])=>({filePath:o,...i})).sort((o,i)=>o.filePath.localeCompare(i.filePath));x(e,200,{files:a});}function Mt(t,e,r){if(!existsSync(r)){x(e,200,{runs:[],totalSizeBytes:0});return}try{let n=[],s=0,a=readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!Ne.test(o.name))continue;let i=join(r,o.name),l=ne(i),d=readdirSync(i,{withFileTypes:!0}).filter(c=>c.isDirectory());n.push({folderName:o.name,totalSizeBytes:l,testCount:d.length}),s+=l;}n.sort((o,i)=>i.folderName.localeCompare(o.folderName)),x(e,200,{runs:n,totalSizeBytes:s});}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}function Et(t,e,r){try{let n=0,s=0;if(existsSync(r)){let a=readdirSync(r,{withFileTypes:!0});for(let o of a){if(!o.isDirectory()||!Ne.test(o.name))continue;let i=join(r,o.name),l=ne(i);rmSync(i,{recursive:!0,force:!0}),s+=l,n++;}}x(e,200,{deletedCount:n,freedBytes:s});}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}function Pt(t,e,r,n){if(!Ne.test(n)){x(e,400,{error:"Invalid folder name"});return}let s=join(r,n);try{if(!statSync(s).isDirectory()){x(e,404,{error:"Not found"});return}}catch{x(e,404,{error:"Not found"});return}try{let a=ne(s);rmSync(s,{recursive:!0,force:!0}),x(e,200,{deleted:n,freedBytes:a});}catch(a){x(e,500,{error:a instanceof Error?a.message:String(a)});}}function Dt(t,e,r){x(e,200,{status:"shutting_down"}),r.close();}function Me(t,e,r){if(!existsSync(r)){x(e,404,{error:"File not found"});return}try{let n=readFileSync(r),s=extname(r).toLowerCase(),a=wn[s]??"application/octet-stream";e.writeHead(200,{"Content-Type":a}),e.end(n);}catch(n){x(e,500,{error:n instanceof Error?n.message:String(n)});}}var wn={".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 Tn=9323,Sn=10,Rn=1800*1e3;function G(t,e){return new Promise((r,n)=>{let s=e?.port??Tn,a=Date.now(),o,i=0,l=existsSync(join(t,"artifacts"))?join(t,"artifacts"):existsSync(join(t,"..","artifacts"))?join(t,"..","artifacts"):join(t,"artifacts");function d(){clearTimeout(o),o=setTimeout(()=>{p.close();},Rn);}let c=e?.htmlPath??null;if(!c){let u=dirname(t);try{let g=readdirSync(u).find(h=>h.endsWith(".html"));g&&(c=join(u,g));}catch{}}let p=createServer((u,g)=>{if(d(),St(g),u.method==="OPTIONS"){g.writeHead(204),g.end();return}let h;try{h=new URL(u.url??"/",`http://${u.headers.host??"localhost"}`).pathname;}catch{x(g,400,{error:"Invalid URL"});return}if(u.method==="GET"&&(h==="/"||h==="/index.html")){if(c&&existsSync(c)){Me(u,g,c);return}x(g,404,{error:"HTML report not found"});return}if(u.method==="GET"&&h==="/api/health"){Rt(u,g,t,a);return}if(u.method==="GET"&&h==="/api/summary"){At(u,g,t);return}if(u.method==="GET"&&h==="/api/tests"){_t(u,g,t);return}if(u.method==="GET"&&h==="/api/files"){Nt(u,g,t);return}let m=h.match(/^\/api\/tests\/([a-f0-9]+)\/(network|console|api-calls)$/);if(u.method==="GET"&&m){Lt(u,g,t,m[1],m[2]);return}let b=h.match(/^\/api\/tests\/([a-f0-9]+)$/);if(u.method==="GET"&&b){It(u,g,t,b[1]);return}if(u.method==="GET"&&h==="/api/artifacts"){Mt(u,g,l);return}if(u.method==="DELETE"&&h==="/api/artifacts"){Et(u,g,l);return}let C=h.match(/^\/api\/artifacts\/(.+)$/);if(u.method==="DELETE"&&C){Pt(u,g,l,decodeURIComponent(C[1]));return}if(u.method==="GET"&&h.startsWith("/artifacts/")){let w=decodeURIComponent(h.slice(11));if(w.includes("..")||w.includes("\0")){x(g,400,{error:"Invalid path"});return}Me(u,g,join(l,w));return}if(u.method==="POST"&&h==="/api/shutdown"){Dt(u,g,p);return}x(g,404,{error:"Not found"});});function f(u){let g=h=>{h.code==="EADDRINUSE"&&i<Sn?(i++,f(u+1)):n(h);};p.once("error",g),p.listen(u,"127.0.0.1",()=>{p.removeListener("error",g);let h=p.address();if(!h||typeof h=="string"){n(new Error("Failed to get server address"));return}d(),r({port:h.port,dispose:()=>new Promise(m=>{clearTimeout(o),p.close(()=>m());})});});}f(s);})}async function Ft(t){let e=await G(t);return {port:e.port,dispose:e.dispose}}function In(t,e,r){let n=JSON.stringify(t),s=r?JSON.stringify(r):null;return vt(n,e,s)}async function Pe(t,e,r){try{let n=null,s=null,a=e.reportMode==="streaming"||e.reportMode==="auto"&&t.timeline.length===0&&t.summary.total>=e.streamingThreshold,o,i=e.htmlReportPath,l=dirname(i);mkdirSync(l,{recursive:!0});let d="",c="[]",p=null;if(a){d=JSON.stringify(t.summary);let u=dirname(e.outputPath),g=join(u,".testrelic-report");try{let h=join(g,"index-compact.json"),m=join(g,"index.json");existsSync(h)?c=readFileSync(h,"utf-8"):existsSync(m)&&(c=readFileSync(m,"utf-8"));}catch{}p=r?JSON.stringify(r):null,o=Ie(d,c,null,p);}else o=In(t,null,r);let f=i+".tmp";if(writeFileSync(f,o,"utf-8"),renameSync(f,i),a){if(t.ci===null){let u=dirname(e.outputPath),g=join(u,".testrelic-report"),h=resolve(i);try{if(await Nn(),n=await Mn(g),!n){s=await G(g,{htmlPath:h}),n=s.port;let m=setInterval(()=>{},6e4),b=()=>{clearInterval(m),s?.dispose();};process.on("SIGINT",b),process.on("SIGTERM",b),setTimeout(b,1800*1e3).unref();}if(n){process.stderr.write(`
2483
2482
  Report server: http://127.0.0.1:${n}
2484
2483
  `);try{let m=Ie(d,c,n,p),b=i+".tmp";writeFileSync(b,m,"utf-8"),renameSync(b,i);}catch{}}}catch{}}}else if(e.openReport&&t.ci===null&&e.includeArtifacts){let u=dirname(e.outputPath),g=join(u,"artifacts");if(existsSync(g))try{let h=await Ft(g);n=h.port,process.on("exit",()=>{h.dispose();});}catch{}}if(e.openReport&&t.ci===null)if(a&&n)Le(`http://127.0.0.1:${n}`);else {let u=resolve(i);Le(u);}}catch(n){process.stderr.write(`[testrelic] Failed to write HTML report: ${n instanceof Error?n.message:String(n)}
2485
- `);}}var ie=9323,Ut=10;async function Ln(){for(let t=ie;t<ie+Ut;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${t}/api/health`,{signal:e.signal});if(clearTimeout(r),n.ok)return t}catch{}return null}async function Nn(){for(let t=ie;t<ie+Ut;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),1e3);await fetch(`http://127.0.0.1:${t}/api/shutdown`,{method:"POST",signal:e.signal}),clearTimeout(r);}catch{}await new Promise(t=>setTimeout(t,300));}async function En(t){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 G(t);return process.on("exit",()=>{n?.dispose();}),n.port}return new Promise(n=>{let s=spawn(process.execPath,[r,"serve",t],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),a="",o=false,i=setTimeout(()=>{o||(o=true,s.stderr?.removeAllListeners(),Ln().then(n));},5e3);s.stderr?.on("data",l=>{a+=l.toString();let d=a.match(/127\.0\.0\.1:(\d+)/);d&&!o&&(o=true,clearTimeout(i),s.stderr?.removeAllListeners(),s.unref(),n(Number(d[1])));}),s.on("error",()=>{o||(o=true,clearTimeout(i),n(null));}),s.on("exit",()=>{o||(o=true,clearTimeout(i),n(null));}),s.unref();})}var Dn=20,De=0,Fe=[];async function jt(t,e){De>=Dn&&await new Promise(r=>Fe.push(r)),De++;try{return await copyFile(t,e),!0}catch{return false}finally{De--,Fe.length>0&&Fe.shift()();}}var K=[];async function zt(){K.length!==0&&(await Promise.allSettled(K),K.length=0);}function Vt(t){let e=new Date,r=a=>String(a).padStart(2,"0"),n=`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())}T${r(e.getHours())}-${r(e.getMinutes())}-${r(e.getSeconds())}`;if(!existsSync(join(t,n)))return n;let s=1;for(;existsSync(join(t,`${n}-${s}`));)s++;return `${n}-${s}`}function Fn(t){let e=t.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return e.length>100&&(e=e.substring(0,100).replace(/-+$/,"")),e||"unnamed-test"}function Wt(t,e,r,n,s){let a=t.find(f=>f.name==="screenshot"&&f.path),o=t.find(f=>f.name==="video"&&f.path);if(!a&&!o)return null;let i=Fn(e);r>0&&(i+=`--retry-${r}`);let l=s?["artifacts",s,i]:["artifacts",i],d=join(n,...l),c=l,p={};try{mkdirSync(d,{recursive:!0});}catch{return null}if(a?.path&&existsSync(a.path)){let u=`screenshot${extname(a.path)||".png"}`,g=join(d,u);K.push(jt(a.path,g).then(()=>{})),p.screenshot=`${c.join("/")}/${u}`;}if(o?.path&&existsSync(o.path)){let u=`video${extname(o.path)||".webm"}`,g=join(d,u);K.push(jt(o.path,g).then(()=>{})),p.video=`${c.join("/")}/${u}`;}return !p.screenshot&&!p.video?null:p}var qn=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Hn="1.0";function Un(t){let e=extname(t).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(e)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(e)?"video":"other"}function Gt(t,e,r){let n=[];try{let s=readdirSync(t,{withFileTypes:!0});for(let a of s){if(!a.isFile())continue;let o=join(t,a.name),i=statSync(o);n.push({name:a.name,type:Un(a.name),relativePath:`artifacts/${e}/${r}/${a.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:n}}function $n(t,e){let r=join(t,e),n=[],s=0;try{let o=readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let l=Gt(join(r,i.name),e,i.name);n.push(l);for(let d of l.files)s+=d.sizeBytes;}}catch{}let a=e.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return n.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:e,timestamp:a,totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}}function Jt(t,e){let r=join(t,"artifacts"),n=[],s=[],a=0;try{let i=readdirSync(r,{withFileTypes:!0});for(let l of i)if(l.isDirectory())if(qn.test(l.name)){let d=$n(r,l.name);n.push({...d,isCurrentRun:l.name===e});}else {let d=Gt(join(r,l.name),l.name,l.name);s.push(d);for(let c of d.files)a+=c.sizeBytes;}}catch{}n.sort((i,l)=>l.timestamp.localeCompare(i.timestamp)),s.length>0&&(s.sort((i,l)=>i.testName.localeCompare(l.testName)),n.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:a,testCount:s.length,tests:s,isCurrentRun:false}));let o=n.reduce((i,l)=>i+l.totalSizeBytes,0);return {schemaVersion:Hn,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:n,serverPort:null}}function Gn(t){let e=t,{root:r}=parse(e);for(;e!==r;){if(existsSync(join(e,".git")))return e;e=join(e,"..");}return null}function Yt(t){try{let e=Gn(t);if(!e)return;let r=join(e,".gitignore"),n=relative(e,t).replace(/\\/g,"/"),s=n.endsWith("/")?n:`${n}/`;if(existsSync(r)&&readFileSync(r,"utf-8").split(`
2484
+ `);}}var ie=9323,Ut=10;async function Ln(){for(let t=ie;t<ie+Ut;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),500),n=await fetch(`http://127.0.0.1:${t}/api/health`,{signal:e.signal});if(clearTimeout(r),n.ok)return t}catch{}return null}async function Nn(){for(let t=ie;t<ie+Ut;t++)try{let e=new AbortController,r=setTimeout(()=>e.abort(),1e3);await fetch(`http://127.0.0.1:${t}/api/shutdown`,{method:"POST",signal:e.signal}),clearTimeout(r);}catch{}await new Promise(t=>setTimeout(t,300));}async function Mn(t){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 G(t);return process.on("exit",()=>{n?.dispose();}),n.port}return new Promise(n=>{let s=spawn(process.execPath,[r,"serve",t],{detached:true,stdio:["ignore","ignore","pipe"],env:{...process.env}}),a="",o=false,i=setTimeout(()=>{o||(o=true,s.stderr?.removeAllListeners(),Ln().then(n));},5e3);s.stderr?.on("data",l=>{a+=l.toString();let d=a.match(/127\.0\.0\.1:(\d+)/);d&&!o&&(o=true,clearTimeout(i),s.stderr?.removeAllListeners(),s.unref(),n(Number(d[1])));}),s.on("error",()=>{o||(o=true,clearTimeout(i),n(null));}),s.on("exit",()=>{o||(o=true,clearTimeout(i),n(null));}),s.unref();})}var Dn=20,De=0,Fe=[];async function jt(t,e){De>=Dn&&await new Promise(r=>Fe.push(r)),De++;try{return await copyFile(t,e),!0}catch{return false}finally{De--,Fe.length>0&&Fe.shift()();}}var K=[];async function zt(){K.length!==0&&(await Promise.allSettled(K),K.length=0);}function Vt(t){let e=new Date,r=a=>String(a).padStart(2,"0"),n=`${e.getFullYear()}-${r(e.getMonth()+1)}-${r(e.getDate())}T${r(e.getHours())}-${r(e.getMinutes())}-${r(e.getSeconds())}`;if(!existsSync(join(t,n)))return n;let s=1;for(;existsSync(join(t,`${n}-${s}`));)s++;return `${n}-${s}`}function Fn(t){let e=t.replace(/[^a-zA-Z0-9\-_ ]/g,"-").replace(/\s+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"");return e.length>100&&(e=e.substring(0,100).replace(/-+$/,"")),e||"unnamed-test"}function Wt(t,e,r,n,s){let a=t.find(f=>f.name==="screenshot"&&f.path),o=t.find(f=>f.name==="video"&&f.path);if(!a&&!o)return null;let i=Fn(e);r>0&&(i+=`--retry-${r}`);let l=s?["artifacts",s,i]:["artifacts",i],d=join(n,...l),c=l,p={};try{mkdirSync(d,{recursive:!0});}catch{return null}if(a?.path&&existsSync(a.path)){let u=`screenshot${extname(a.path)||".png"}`,g=join(d,u);K.push(jt(a.path,g).then(()=>{})),p.screenshot=`${c.join("/")}/${u}`;}if(o?.path&&existsSync(o.path)){let u=`video${extname(o.path)||".webm"}`,g=join(d,u);K.push(jt(o.path,g).then(()=>{})),p.video=`${c.join("/")}/${u}`;}return !p.screenshot&&!p.video?null:p}var qn=/^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/,Hn="1.0";function Un(t){let e=extname(t).toLowerCase();return [".png",".jpg",".jpeg",".gif",".bmp",".webp"].includes(e)?"screenshot":[".webm",".mp4",".avi",".mov"].includes(e)?"video":"other"}function Gt(t,e,r){let n=[];try{let s=readdirSync(t,{withFileTypes:!0});for(let a of s){if(!a.isFile())continue;let o=join(t,a.name),i=statSync(o);n.push({name:a.name,type:Un(a.name),relativePath:`artifacts/${e}/${r}/${a.name}`,sizeBytes:i.size});}}catch{}return {testName:r,files:n}}function $n(t,e){let r=join(t,e),n=[],s=0;try{let o=readdirSync(r,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let l=Gt(join(r,i.name),e,i.name);n.push(l);for(let d of l.files)s+=d.sizeBytes;}}catch{}let a=e.replace(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/,"$1T$2:$3:$4").replace(/-\d+$/,"");return n.sort((o,i)=>o.testName.localeCompare(i.testName)),{folderName:e,timestamp:a,totalSizeBytes:s,testCount:n.length,tests:n,isCurrentRun:false}}function Jt(t,e){let r=join(t,"artifacts"),n=[],s=[],a=0;try{let i=readdirSync(r,{withFileTypes:!0});for(let l of i)if(l.isDirectory())if(qn.test(l.name)){let d=$n(r,l.name);n.push({...d,isCurrentRun:l.name===e});}else {let d=Gt(join(r,l.name),l.name,l.name);s.push(d);for(let c of d.files)a+=c.sizeBytes;}}catch{}n.sort((i,l)=>l.timestamp.localeCompare(i.timestamp)),s.length>0&&(s.sort((i,l)=>i.testName.localeCompare(l.testName)),n.push({folderName:"__legacy__",timestamp:"1970-01-01T00:00:00",totalSizeBytes:a,testCount:s.length,tests:s,isCurrentRun:false}));let o=n.reduce((i,l)=>i+l.totalSizeBytes,0);return {schemaVersion:Hn,generatedAt:new Date().toISOString(),artifactBaseDir:"artifacts",totalSizeBytes:o,runs:n,serverPort:null}}function Gn(t){let e=t,{root:r}=parse(e);for(;e!==r;){if(existsSync(join(e,".git")))return e;e=join(e,"..");}return null}function Yt(t){try{let e=Gn(t);if(!e)return;let r=join(e,".gitignore"),n=relative(e,t).replace(/\\/g,"/"),s=n.endsWith("/")?n:`${n}/`;if(existsSync(r)&&readFileSync(r,"utf-8").split(`
2486
2485
  `).map(l=>l.trim()).some(l=>l===s||l===n))return;let a=`
2487
2486
  # TestRelic test artifacts
2488
2487
  ${s}
@@ -2510,7 +2509,7 @@ ${s}
2510
2509
  `);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
2511
2510
  `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?Z(this.gitMetadata.remoteUrl):null,r=e?lr(e):this.config.projectName??Q(process.cwd()),n=e??this.config.projectName??Q(process.cwd()),s=this.readRepoCache(n);if(s){this.repoId=s.repoId;return}try{let a=await ir(this.config.endpoint,this.authState.accessToken,n,r,this.config.timeout,this.gitMetadata?.branch);a&&(this.repoId=a.repoId,this.writeRepoCache(n,a.repoId,a.displayName));}catch{}!e&&!this.config.projectName&&!Ve(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
2512
2511
  `);}readRepoCache(e){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!==e||Date.now()-s.resolvedAt>_s)return null;let a=this.hashApiKey();return a&&s.apiKeyHash!==a?null:s}catch{return null}}writeRepoCache(e,r,n){if(!this.config)return;let s=join(this.config.queueDirectory,"..","cache"),a=join(s,"repo.json");try{mkdirSync(s,{recursive:!0});let o={repoId:r,gitId:e,displayName:n,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=a+".tmp";writeFileSync(i,JSON.stringify(o,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 e=this.authState.accessToken,r=this.config.queueDirectory,n=this.config.endpoint;this.flushPromise=Promise.race([pr(r,n,e),new Promise(s=>setTimeout(s,gr))]).catch(()=>{});}startHealthCheck(){if(!this.config)return;let e=this.config.endpoint;this.healthCheckTimer=setInterval(async()=>{if(!this.isCloudMode()&&!(!this.failureReason||!["cloud_unreachable","auth_timeout","network_error"].includes(this.failureReason)))try{if(!await $e(e))return;if(this.config?.apiKey){let n=await je(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!ze(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.
2513
- `),this.startBackgroundFlush();}}}catch{}},Is);}};var Ns=1048576,ce=[1e3,3e3,9e3],ue=3;function Ye(t,e,r,n){return {runId:t.testRunId,repoGitId:e,startedAt:t.startedAt,summary:t.summary,timeline:t.timeline,...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...n?.provider?{ciProvider:n.provider}:{},...n?.runUrl?{ciRunUrl:n.runUrl}:{}}}async function pe(t){return new Promise(e=>setTimeout(e,t))}function Es(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}async function Ms(t,e,r){for(let n=0;n<ue;n++)try{let s=await fetch(t,e);if(s.ok)return s;if(s.status===401&&r&&n===0){let a=await r();if(a){let o={...e,headers:{...e.headers,Authorization:`Bearer ${a}`}},i=await fetch(t,o);if(i.ok)return i}return null}if(s.status===429&&n<ue-1){let a=s.headers.get("Retry-After"),o=a?parseInt(a,10)*1e3:ce[n];!isNaN(o)&&o>0?await pe(o):await pe(ce[n]);continue}if(s.status>=500&&n<ue-1){await pe(ce[n]);continue}return s}catch{if(n<ue-1){await pe(ce[n]);continue}return null}return null}function Ps(t){let e=JSON.stringify(t),r={"Content-Type":"application/json"};if(Buffer.byteLength(e,"utf-8")>Ns){let n=gzipSync(Buffer.from(e,"utf-8"));return r["Content-Encoding"]="gzip",{body:n,headers:r}}return {body:e,headers:r}}async function hr(t,e,r,n){let s=`${t}/runs`,{body:a,headers:o}=Ps(r);o.Authorization=`Bearer ${e}`;let i=await Ms(s,{method:"POST",headers:o,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 mr(t,e,r){let n=`${t}/runs/init`;try{let s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(Es(r))});return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function vr(t,e,r,n){let s=`${t}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}).catch(()=>{});}async function yr(t,e,r,n){let s=`${t}/runs/${r}/finalize`;try{return (await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)})).ok}catch{return false}}function br(t,e,r,n){let s=[],a=[],o=null,i=0,l=null,d=0,c=null,p=0,f=t.filter(h=>h.name===ATTACHMENT_NAME&&h.body),u=false;if(f.length>0)for(let h of f)try{let m=JSON.parse(h.body.toString());if(isTestRelicFilePayload(m)){s=s.concat(m.navigations),a=a.concat(m.apiAssertions),m.networkRequestsFile&&(o=m.networkRequestsFile,i+=m.networkRequestsCount),m.consoleLogsFile&&(l=m.consoleLogsFile,d+=m.consoleLogsCount),m.apiCallsFile&&(c=m.apiCallsFile,p+=m.apiCallsCount),u=!0;continue}if(isTestRelicDataPayload(m)){s=s.concat(m.navigations),Array.isArray(m.apiAssertions)&&(a=a.concat(m.apiAssertions)),i+=m.networkRequests?.length??0,p+=m.apiCalls?.length??0;let b=m.consoleLogs;Array.isArray(b)&&(d+=b.length),u=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
2512
+ `),this.startBackgroundFlush();}}}catch{}},Is);}};var Ns=1048576,ce=[1e3,3e3,9e3],ue=3;function Ye(t,e,r,n){return {runId:t.testRunId,repoGitId:e,startedAt:t.startedAt,summary:t.summary,timeline:t.timeline,...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...n?.provider?{ciProvider:n.provider}:{},...n?.runUrl?{ciRunUrl:n.runUrl}:{}}}async function pe(t){return new Promise(e=>setTimeout(e,t))}function Ms(t){let e={};for(let[r,n]of Object.entries(t))n!=null&&(e[r]=n);return e}async function Es(t,e,r){for(let n=0;n<ue;n++)try{let s=await fetch(t,e);if(s.ok)return s;if(s.status===401&&r&&n===0){let a=await r();if(a){let o={...e,headers:{...e.headers,Authorization:`Bearer ${a}`}},i=await fetch(t,o);if(i.ok)return i}return null}if(s.status===429&&n<ue-1){let a=s.headers.get("Retry-After"),o=a?parseInt(a,10)*1e3:ce[n];!isNaN(o)&&o>0?await pe(o):await pe(ce[n]);continue}if(s.status>=500&&n<ue-1){await pe(ce[n]);continue}return s}catch{if(n<ue-1){await pe(ce[n]);continue}return null}return null}function Ps(t){let e=JSON.stringify(t),r={"Content-Type":"application/json"};if(Buffer.byteLength(e,"utf-8")>Ns){let n=gzipSync(Buffer.from(e,"utf-8"));return r["Content-Encoding"]="gzip",{body:n,headers:r}}return {body:e,headers:r}}async function hr(t,e,r,n){let s=`${t}/runs`,{body:a,headers:o}=Ps(r);o.Authorization=`Bearer ${e}`;let i=await Es(s,{method:"POST",headers:o,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 mr(t,e,r){let n=`${t}/runs/init`;try{let s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(Ms(r))});return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function vr(t,e,r,n){let s=`${t}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)}).catch(()=>{});}async function yr(t,e,r,n){let s=`${t}/runs/${r}/finalize`;try{return (await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(n)})).ok}catch{return false}}function br(t,e,r,n){let s=[],a=[],o=null,i=0,l=null,d=0,c=null,p=0,f=t.filter(h=>h.name===ATTACHMENT_NAME&&h.body),u=false;if(f.length>0)for(let h of f)try{let m=JSON.parse(h.body.toString());if(isTestRelicFilePayload(m)){s=s.concat(m.navigations),a=a.concat(m.apiAssertions),m.networkRequestsFile&&(o=m.networkRequestsFile,i+=m.networkRequestsCount),m.consoleLogsFile&&(l=m.consoleLogsFile,d+=m.consoleLogsCount),m.apiCallsFile&&(c=m.apiCallsFile,p+=m.apiCallsCount),u=!0;continue}if(isTestRelicDataPayload(m)){s=s.concat(m.navigations),Array.isArray(m.apiAssertions)&&(a=a.concat(m.apiAssertions)),i+=m.networkRequests?.length??0,p+=m.apiCalls?.length??0;let b=m.consoleLogs;Array.isArray(b)&&(d+=b.length),u=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
2514
2513
  `);}return u||(s=e.filter(h=>h.type==="lambdatest-navigation"&&h.description).map(h=>{try{return JSON.parse(h.description)}catch{return null}}).filter(h=>h!==null)),s.length===0&&i===0&&p===0&&!n&&!u&&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.
2515
2514
  `),{navigations:s,apiAssertions:a,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:l,consoleLogsCount:d,apiCallsFile:c,apiCallsCount:p}}function Ze(t){let r=t.getGitMetadata()?.remoteUrl;return r?Z(r):t.getConfig()?.projectName??Q(process.cwd())}async function wr(t,e,r,n){if(!t.isCloudMode()||e!=="realtime"&&e!=="both"||!await t.ensureValidToken())return null;let a=t.getGitMetadata(),o=D();return (await mr(t.getEndpoint(),t.getAccessToken(),{runId:r,repoGitId:Ze(t),branch:a?.branch??null,commit:a?.commitSha??null,startedAt:n,totalTests:null,ciProvider:o?.provider??null,ciRunUrl:o?.runUrl??null}))?.runId??null}async function Qe(t,e,r,n,s,a,o,i,l){try{if(t.isCloudMode()&&s&&(r==="realtime"||r==="both")&&await t.ensureValidToken()&&await yr(t.getEndpoint(),t.getAccessToken(),s,{finishedAt:o,duration:i,summary:l}),t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await t.ensureValidToken()){let c=t.getGitMetadata(),p=D(),f=Ze(t),u=Ye(a,f,c,p),g=await hr(t.getEndpoint(),t.getAccessToken(),u,async()=>await t.ensureValidToken()?t.getAccessToken():null);if(!g.success){let h=g,m=e?.queueDirectory??".testrelic/queue";Ge(m,n,"batch",h.reason,h.targetEndpoint,h.method,h.payload,{"Content-Type":"application/json"});}}else {let c=e?.queueDirectory??".testrelic/queue",p=t.getGitMetadata(),f=D(),u=Ze(t),g=Ye(a,u,p,f);Ge(c,n,"batch",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs`,"POST",g,{"Content-Type":"application/json"});}await t.dispose();}catch{try{await t.dispose();}catch{}}}function et(t){switch(t){case "passed":return "passed";case "failed":return "failed";case "timedOut":return "timedout";case "skipped":return "skipped";case "interrupted":return "failed";default:return "failed"}}function $s(t,e,r){let n=`${t}::${e}::${r}`;return createHash("sha256").update(n).digest("hex").substring(0,16)}function js(t){return t.length<=4?"":t[t.length-2]}function zs(t){let e=t.findIndex(r=>r.status==="passed");return e>0?`passed on retry ${e}`:null}function Vs(t,e){let r=["e2e","api","unit"];for(let s of r)if(t.some(a=>a===`@${s}`||a===s))return s;let n=e.replace(/\\/g,"/");for(let s of r)if(n.includes(`/${s}/`))return s;return "unknown"}var Ws="__testrelic_api_config";function Gs(t){return JSON.stringify(t,(e,r)=>r instanceof RegExp?{__regexp:true,source:r.source,flags:r.flags}:r)}var fe=class{constructor(e){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=gt(e),this.apiConfig=ft(e);}async onBegin(e,r){try{if(this.rootDir=e.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)
2516
2515
  `),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 o={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(o);}catch{}this.streamingWriter.dispose();}};process.on("SIGTERM",a),process.on("SIGINT",a);}if(this.config.includeArtifacts){let s=dirname(this.config.outputPath);this.runTimestamp=Vt(join(s,"artifacts"));try{Yt(join(s,"artifacts"));}catch{}}try{this.cloudClient=new de(this.config.cloud),await this.cloudClient.initialize(),this.cloudRunId=await wr(this.cloudClient,this.config.cloud?.uploadStrategy,this.testRunId,this.startedAt);}catch{this.cloudClient?.switchToLocalMode("init_error");}}catch{}}onTestBegin(e,r){try{e.annotations.push({type:Ws,description:Gs(this.apiConfig)});}catch{}}onTestEnd(e,r){try{let n=r,s=e.outcome(),a;s==="flaky"?a="flaky":s==="skipped"?a="skipped":a=et(n.status);let o=n.startTime.toISOString(),i=new Date(n.startTime.getTime()+n.duration).toISOString(),l=e.tags?[...e.tags]:e.annotations.filter(S=>S.type==="tag").map(S=>S.description??""),d=br(n.attachments,e.annotations,e.title,a==="skipped");(d.navigations.length>0||d.networkRequestsCount>0||d.apiCallsCount>0)&&(this.fixtureDataReceived=!0);let c=null;if(a==="failed"||a==="flaky"){let R=(a==="flaky"?e.results.find(P=>P.status!=="passed")?.errors??[]:n.errors)[0];if(R){let P=mt(this.config.redactPatterns),j=R.location?.line??null,z=null;this.config.includeCodeSnippets&&j!==null&&R.location?.file&&(z=ht(R.location.file,j,this.config.codeContextLines),z&&(z=P(z))),c={message:P(R.message??"Unknown error"),line:j,code:z,stack:this.config.includeStackTrace&&R.stack?P(R.stack):null};}}let p=e.titlePath().filter(Boolean),f=relative(this.rootDir||".",e.location.file),u=js(p),g=p.join(" > "),h=f,m=$s(h,u,g),b=Vs(l,h),C=s==="flaky",w=zs(e.results),y=et(e.expectedStatus),T=et(n.status),v=null;if(this.config.includeArtifacts&&a!=="skipped"&&n.attachments){let S=dirname(this.config.outputPath),R=p[p.length-1]??e.title;v=Wt(n.attachments,R,n.retry,S,this.runTimestamp||void 0);}let k=this.config.includeActionSteps&&n.steps?tr(n.steps,n.startTime):null,A={titlePath:p,title:g,status:a,duration:n.duration,startedAt:o,completedAt:i,retryCount:e.results.length-1,retry:n.retry,tags:l,failure:c,specFile:f,navigations:d.navigations,testId:m,filePath:h,suiteName:u,testType:b,isFlaky:C,retryStatus:w,expectedStatus:y,actualStatus:T,artifacts:v,apiAssertions:d.apiAssertions,actions:k,networkRequestsFile:d.networkRequestsFile,networkRequestsCount:d.networkRequestsCount,consoleLogsFile:d.consoleLogsFile,consoleLogsCount:d.consoleLogsCount,apiCallsFile:d.apiCallsFile,apiCallsCount:d.apiCallsCount};if(this.activeReportMode==="streaming"&&this.streamingWriter){let S=ve(h,p,e.id??"",n.retry),R=n.retry===e.results.length-1,P={id:S,navigations:d.navigations,apiAssertions:d.apiAssertions,actions:k??[],artifacts:v,failureDiagnostic:c,hasNetworkFile:d.networkRequestsFile!==null,networkRequestsCount:d.networkRequestsCount,hasConsoleFile:d.consoleLogsFile!==null,consoleLogsCount:d.consoleLogsCount,hasApiCallsFile:d.apiCallsFile!==null,apiCallsCount:d.apiCallsCount,startedAt:o};this.streamingWriter.writeTestDetail(S,P,{networkRequestsFile:d.networkRequestsFile,consoleLogsFile:d.consoleLogsFile,apiCallsFile:d.apiCallsFile});let j={id:S,title:p[p.length-1]??e.title,titlePath:p,filePath:h,status:a,duration:n.duration,project:p[1]??"",retryIndex:n.retry,tags:l,hasNetworkData:d.networkRequestsCount>0,hasConsoleData:d.consoleLogsCount>0,hasArtifacts:v!==null,hasActionSteps:(k?.length??0)>0,errorMessage:c?.message?.split(`
@@ -2530,6 +2529,6 @@ ${s}
2530
2529
  `),this.switchToStreamingMode()):n>.8&&process.stderr.write(`[testrelic] WARNING: Memory pressure detected (${Math.round(r)} MB used).
2531
2530
  `);}catch{}}switchToStreamingMode(){try{if(this.activeReportMode==="streaming")return;this.activeReportMode="streaming";let e=dirname(this.config.outputPath);this.streamingWriter=new W(e);for(let r of this.collectedTests){let n=ve(r.filePath,r.titlePath,r.testId,r.retry),s={id:n,navigations:r.navigations??[],apiAssertions:r.apiAssertions??[],actions:r.actions??[],artifacts:r.artifacts,failureDiagnostic:r.failure,hasNetworkFile:r.networkRequestsFile!==null,networkRequestsCount:r.networkRequestsCount,hasConsoleFile:r.consoleLogsFile!==null,consoleLogsCount:r.consoleLogsCount,hasApiCallsFile:r.apiCallsFile!==null,apiCallsCount:r.apiCallsCount,startedAt:r.startedAt};this.streamingWriter.writeTestDetail(n,s,{networkRequestsFile:r.networkRequestsFile,consoleLogsFile:r.consoleLogsFile,apiCallsFile:r.apiCallsFile});let 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.networkRequestsCount>0,hasConsoleData:r.consoleLogsCount>0,hasArtifacts:r.artifacts!==null,hasActionSteps:(r.actions?.length??0)>0,errorMessage:r.failure?.message?.split(`
2532
2531
  `)[0]??null,networkCount:r.networkRequestsCount,consoleCount:r.consoleLogsCount,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.apiCallsCount,this.summaryCounters.totalAssertions+=r.apiAssertions?.length??0,this.summaryCounters.totalNavigations+=r.navigations?.length??0,this.summaryCounters.totalNetworkRequests+=r.networkRequestsCount,this.summaryCounters.totalConsoleLogs+=r.consoleLogsCount,this.summaryCounters.totalActionSteps+=r.actions?.length??0;}this.collectedTests.length=0;}catch{}}buildTimeline(){let e=this.collectedTests.map(r=>({titlePath:r.titlePath,title:r.title,status:r.status,duration:r.duration,startedAt:r.startedAt,completedAt:r.completedAt,retryCount:r.retryCount,retry:r.retry,tags:r.tags,failure:r.failure,specFile:r.specFile,navigations:r.navigations,apiCalls:null,apiAssertions:r.apiAssertions,testId:r.testId,filePath:r.filePath,suiteName:r.suiteName,testType:r.testType,isFlaky:r.isFlaky,retryStatus:r.retryStatus,expectedStatus:r.expectedStatus,actualStatus:r.actualStatus,artifacts:r.artifacts,networkRequests:null,actions:r.actions,consoleLogs:null}));return Xt(e,{navigationTypes:this.config.navigationTypes})}toTestResult(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:null,apiCalls:null,apiAssertions:e.apiAssertions,actions:e.actions??null,consoleLogs:null}}writeReport(e){try{let r=JSON.stringify(e),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)}
2533
- `);}}};var Qs=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Xs(t){let e=t.toLowerCase();return Qs.some(r=>e.includes(r))}var ge=class t{constructor(e,r){this.page=e;this.records=[];this.listeners=[];this.currentNetworkCounter=null;this.pendingRequests=new Map;this.networkWriter=null;this.consoleWriter=null;this.pendingBodyReads=[];this.requestIdCounter=0;this.networkRequestCount=0;this.consoleLogCount=0;this.includeNetworkStats=r?.includeNetworkStats??true,this.origGoto=e.goto.bind(e),this.origGoBack=e.goBack.bind(e),this.origGoForward=e.goForward.bind(e),this.origReload=e.reload.bind(e);try{this.includeNetworkStats&&(this.networkWriter=new N("network")),this.consoleWriter=new N("console");}catch{}this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async finalizeCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[,e]of this.pendingRequests)this.networkWriter&&(this.networkWriter.append({url:e.url,method:e.method,resourceType:e.resourceType,statusCode:0,responseTimeMs:Date.now()-e.startTimeMs,startedAt:e.startedAt,requestHeaders:e.headers,requestBody:e.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:e.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.networkRequestCount++);this.pendingRequests.clear(),this.networkWriter?.close(),this.consoleWriter?.close();}static mapConsoleType(e){switch(e){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getFileData(){this.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 e=this.records.map(r=>({url:r.url,navigationType:r.navigationType,timestamp:r.timestamp,domContentLoadedAt:r.domContentLoadedAt,networkIdleAt:r.networkIdleAt,networkStats:r.networkStats}));return this.includeNetworkStats?await this.finalizeCapturedRequests():this.consoleWriter?.close(),{navigations:e,networkRequestsFile:this.networkWriter?.getCount()?this.networkWriter.getPath():null,networkRequestsCount:this.networkWriter?.getCount()??0,consoleLogsFile:this.consoleWriter?.getCount()?this.consoleWriter.getPath():null,consoleLogsCount:this.consoleWriter?.getCount()??0}}async flushLegacyAnnotations(e){}dispose(){this.page.goto=this.origGoto,this.page.goBack=this.origGoBack,this.page.goForward=this.origGoForward,this.page.reload=this.origReload;for(let{event:e,handler:r}of this.listeners)this.page.off(e,r);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}getRecords(){return this.records}interceptMethods(){let e=this,r=this.page;r.goto=async function(n,s){return e.recordNavigation(n,"goto"),e.origGoto(n,s)},r.goBack=async function(n){let s=await e.origGoBack(n);return e.recordNavigation(r.url(),"back"),s},r.goForward=async function(n){let s=await e.origGoForward(n);return e.recordNavigation(r.url(),"forward"),s},r.reload=async function(n){return e.recordNavigation(r.url(),"refresh"),e.origReload(n)};}attachListeners(){let e=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",e),this.listeners.push({event:"domcontentloaded",handler:e});let r=s=>{try{let a=s;if(typeof a.parentFrame=="function"&&a.parentFrame()!==null)return;let o=a.url(),i=this.records[this.records.length-1];if(i&&Date.now()-new Date(i.timestamp).getTime()<50&&i.url===o)return;this.recordNavigation(o,"navigation");}catch{}};this.page.on("framenavigated",r),this.listeners.push({event:"framenavigated",handler:r});let n=s=>{try{let a=s,o=a.type(),i=a.text();if(o==="debug"&&i.startsWith("__testrelic_nav:")){try{let l=JSON.parse(i.slice(16));l.type&&l.url&&this.recordNavigation(l.url,l.type);}catch{}return}{let l=null;try{let c=a.location();c&&c.url&&(l=`${c.url}:${c.lineNumber}:${c.columnNumber}`);}catch{}let d=t.mapConsoleType(o);this.consoleWriter&&(this.consoleWriter.append({level:d,text:i,timestamp:new Date().toISOString(),location:l}),this.consoleLogCount++);}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=i=>{this.currentNetworkCounter&&this.currentNetworkCounter.totalRequests++;try{let l=i,d=String(this.requestIdCounter++),c=l.postData()??null,p={url:l.url(),method:l.method(),resourceType:this.mapResourceType(l.resourceType()),headers:l.headers(),postData:c,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now()};this.pendingRequests.set(d,p),i.__testrelic_id=d;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let a=i=>{try{let l=i;if(this.currentNetworkCounter){let b=l.status();b>=400&&(this.currentNetworkCounter.failedRequests++,this.currentNetworkCounter.failedRequestUrls.push(b+" "+l.url()));let C=l.headers()["content-length"];C&&(this.currentNetworkCounter.totalBytes+=parseInt(C,10)||0);let w=l.request().resourceType(),y=this.mapResourceType(w);this.currentNetworkCounter.byType[y]++;}let d=l.request().__testrelic_id;if(!d)return;let c=this.pendingRequests.get(d);if(!c)return;this.pendingRequests.delete(d);let p=Date.now()-c.startTimeMs,f=l.headers(),u=f["content-type"]??null,g=parseInt(f["content-length"]??"0",10)||0,h=u?!Xs(u):!1,m=(async()=>{let b=null;if(!h)try{b=(await l.body()).toString("utf-8");}catch{}let C={url:c.url,method:c.method,resourceType:c.resourceType,statusCode:l.status(),responseTimeMs:p,startedAt:c.startedAt,requestHeaders:c.headers,requestBody:c.postData,responseBody:b,responseHeaders:f,contentType:u,responseSize:g,requestBodyTruncated:c.postDataTruncated,responseBodyTruncated:!1,isBinary:h,error:null};this.networkWriter&&(this.networkWriter.append(C),this.networkRequestCount++);})();this.pendingBodyReads.push(m);}catch{}};this.page.on("response",a),this.listeners.push({event:"response",handler:a});let o=i=>{if(this.currentNetworkCounter){this.currentNetworkCounter.failedRequests++;try{let l=i;this.currentNetworkCounter.failedRequestUrls.push("ERR "+l.url());}catch{}}try{let l=i,d=l.__testrelic_id;if(!d)return;let c=this.pendingRequests.get(d);if(!c)return;this.pendingRequests.delete(d);let p={url:c.url,method:c.method,resourceType:c.resourceType,statusCode:0,responseTimeMs:Date.now()-c.startTimeMs,startedAt:c.startedAt,requestHeaders:c.headers,requestBody:c.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:c.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:l.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(p),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",o),this.listeners.push({event:"requestfailed",handler:o});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let e=history.pushState.bind(history),r=history.replaceState.bind(history);history.pushState=function(...n){e(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){r(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(e,r){this.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:e,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(e){switch(e){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};var Cr=Symbol.for("__testrelic_call_id"),ea="__testrelic_api_assertions",U=new WeakMap,H=class{constructor(){this.assertions=[];this.currentCallId=null;}recordAssertion(e){this.assertions.push(e);}getAssertions(){return this.assertions}setCurrentCallId(e){this.currentCallId=e;}getCurrentCallId(){return this.currentCallId}getData(){return [...this.assertions]}flushLegacyAnnotations(e){this.assertions.length!==0&&e.annotations.push({type:ea,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}};var Tr="[REDACTED]";function rt(t,e){if(t===null||e.length===0)return t;let r=new Set(e.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(t))Object.hasOwn(t,s)&&(n[s]=r.has(s.toLowerCase())?Tr:t[s]);return n}function he(t,e){if(t===null||e.length===0)return t;let r;try{r=JSON.parse(t);}catch{return t}if(typeof r!="object"||r===null)return t;let n=new Set(e),s=tt(r,n);return JSON.stringify(s)}function tt(t,e){if(Array.isArray(t))return t.map(r=>tt(r,e));if(typeof t=="object"&&t!==null){let r={};for(let n of Object.keys(t)){if(!Object.hasOwn(t,n))continue;let s=t[n];e.has(n)?r[n]=Tr:r[n]=tt(s,e);}return r}return t}function Rr(t,e,r){if(r.length>0){for(let n of r)if(Sr(t,n))return false}if(e.length>0){for(let n of e)if(Sr(t,n))return true;return false}return true}function Sr(t,e){try{return e instanceof RegExp?e.test(t):ta(e).test(t)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(e)}`),false}}function ta(t){let e="",r=0;for(;r<t.length;){let n=t[r];n==="*"&&t[r+1]==="*"?(e+=".*",r+=2,t[r]==="/"&&r++):n==="*"?(e+="[^/]*",r++):n==="?"?(e+="[^/]",r++):".+^${}()|[]\\".includes(n)?(e+="\\"+n,r++):(e+=n,r++);}return new RegExp(e)}var ra=["get","post","put","patch","delete","head","fetch"],na=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function sa(t){let e=t.toLowerCase();return na.some(r=>e.includes(r))}function aa(t){if(!t)return null;if(t.data!==void 0&&t.data!==null){let e=t.data;return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString("base64"):JSON.stringify(e)}if(t.form!==void 0&&t.form!==null)return JSON.stringify(t.form);if(t.multipart!==void 0&&t.multipart!==null){let e=t.multipart,r={};for(let[n,s]of Object.entries(e))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?r[n]=String(s):s&&typeof s=="object"&&"name"in s?r[n]=`[file: ${s.name}]`:r[n]="[binary]";return JSON.stringify(r)}return null}var me=class me{constructor(e,r,n){this.originals=new Map;this.apiCallWriter=null;this.callCounter=0;this.apiCallCount=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=e,this.assertionTracker=r??null,this.apiConfig=n??me.DEFAULT_API_CONFIG;try{this.apiCallWriter=new N("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(e){return e!=null&&typeof e=="object"?U.get(e)??null:this.primitiveCallIds.get(e)??null}intercept(){for(let r of ra){let n=this.context[r].bind(this.context);this.originals.set(r,n),this.context[r]=this.createWrapper(r,n);}let e=this.context.dispose.bind(this.context);this.originals.set("dispose",e),this.context.dispose=async r=>(this.disposed=true,e(r));}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0}}flushLegacyAnnotations(e){}dispose(){for(let[e,r]of this.originals)this.context[e]=r;this.originals.clear(),this.apiCallWriter?.close(),this.callCounter=0,this.apiCallCount=0,this._lastCallId=null,this.primitiveCallIds.clear();}get isDisposed(){return this.disposed}getCapturedCallCount(){return this.apiCallCount}tagResponseMethods(e,r){let n=this,s=e.headers.bind(e);e.headers=function(){let u=s();return U.set(u,r),u};let a=e.headersArray.bind(e);e.headersArray=function(){let u=a();return U.set(u,r),u};let o=e.json.bind(e);e.json=async function(){let u=await o();return u!=null&&typeof u=="object"&&U.set(u,r),u};let i=e.status.bind(e);e.status=function(){let u=i();return n.primitiveCallIds.set(u,r),u};let l=e.statusText.bind(e);e.statusText=function(){let u=l();return n.primitiveCallIds.set(u,r),u};let d=e.ok.bind(e);e.ok=function(){let u=d();return n.primitiveCallIds.set(u,r),u};let c=e.text.bind(e);e.text=async function(){let u=await c();return n.primitiveCallIds.set(u,r),u};let p=e.body.bind(e);e.body=async function(){let u=await p();return U.set(u,r),u};}createWrapper(e,r){let n=this;return async function(a,o){if(!Rr(a,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return r(a,o);let i=`api-call-${n.callCounter++}`,l=new Date().toISOString(),d=e==="fetch"?(o?.method??"GET").toUpperCase():e.toUpperCase(),c=aa(o),p=performance.now();n._lastCallId=i,n.assertionTracker&&n.assertionTracker.setCurrentCallId(i);let f;try{f=await r(a,o);}catch(u){let g=performance.now();try{let h=n.apiConfig.captureRequestBody?he(c,n.apiConfig.redactBodyFields):null,m={id:i,timestamp:l,method:d,url:a,requestHeaders:null,requestBody:h,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((g-p)*100)/100,isBinary:!1,error:u instanceof Error?u.message:String(u)};n.apiCallWriter&&(n.apiCallWriter.append(m),n.apiCallCount++);}catch{}throw u}try{let u=performance.now(),g=f.headers(),h=g["content-type"]??null,m=h?!sa(h):!1,b=null;n.apiConfig.captureRequestHeaders&&o?.headers&&(b=o.headers);let C=null;n.apiConfig.captureResponseHeaders&&(C=g);let w=n.apiConfig.captureRequestBody?c:null,y=null;if(n.apiConfig.captureResponseBody)try{m?y=(await f.body()).toString("base64"):y=await f.text();}catch{}b=rt(b,n.apiConfig.redactHeaders),C=rt(C,n.apiConfig.redactHeaders),w=he(w,n.apiConfig.redactBodyFields),y=he(y,n.apiConfig.redactBodyFields);let T={id:i,timestamp:l,method:d,url:f.url(),requestHeaders:b,requestBody:w,responseStatusCode:f.status(),responseStatusText:f.statusText(),responseHeaders:C,responseBody:y,responseTimeMs:Math.round((u-p)*100)/100,isBinary:m,error:null};n.apiCallWriter&&(n.apiCallWriter.append(T),n.apiCallCount++);}catch{}try{f[Cr]=i,n.tagResponseMethods(f,i);}catch{}return f}}};me.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 $=me;var oa="__testrelic_api_config",la="__testrelic_config_trackApiCalls";function st(t){let e=t.annotations.find(n=>n.type===oa&&n.description!==void 0);if(e)try{return JSON.parse(e.description,da)}catch{}let r=t.annotations.find(n=>n.type===la&&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 da(t,e){if(typeof e=="object"&&e!==null&&e.__regexp===true&&typeof e.source=="string"){let{source:r,flags:n}=e;return new RegExp(r,n)}return e}var Lr={page:async({page:t},e,r)=>{let n=new ge(t);try{await n.init();}catch{}await e(t);try{let{navigations:s,networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:l}=await n.getFileData(),d={testRelicData:!0,version:PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:l,apiCallsFile:null,apiCallsCount:0};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:t},e,r)=>{let n=st(r);if(!n.trackApiCalls){await e(t);return}let s=new H,a=new $(t,s,n);a.intercept(),await e(t);try{let{apiCallsFile:o,apiCallsCount:i}=a.getFileData(),l=n.captureAssertions?s.getData():[],d={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],apiAssertions:l,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:o,apiCallsCount:i};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};test.extend(Lr);var fa={request:async({request:t},e,r)=>{let n=st(r);if(!n.trackApiCalls){await e(t);return}let s=new H,a=new $(t,s,n);a.intercept();let o=null;try{o=new N("api-console");}catch{}let i=0,l=process.stdout.write,d=process.stderr.write;process.stdout.write=function(c,...p){try{let f=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!f.startsWith("[testrelic]")&&!f.startsWith("\u2139 TestRelic")&&!f.startsWith("\u2713 TestRelic")&&!f.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stdout",text:f.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return l.apply(process.stdout,[c,...p])},process.stderr.write=function(c,...p){try{let f=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!f.startsWith("[testrelic]")&&!f.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stderr",text:f.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return d.apply(process.stderr,[c,...p])};try{await e(t);}finally{process.stdout.write=l,process.stderr.write=d;}try{o?.close();let{apiCallsFile:c,apiCallsCount:p}=a.getFileData(),f=n.captureAssertions?s.getData():[],u={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],apiAssertions:f,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:i>0?o?.getPath()??null:null,consoleLogsCount:i,apiCallsFile:c,apiCallsCount:p};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(u)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};var Nr="@testrelic/playwright-analytics";function ha(t){return Array.isArray(t)?t.some(e=>Array.isArray(e)&&typeof e[0]=="string"&&e[0]===Nr):false}function ma(t,e){let n={video:"on",screenshot:"on",trace:"on",...t.use??{}},s;Array.isArray(t.reporter)?s=t.reporter:typeof t.reporter=="string"?s=[[t.reporter]]:s=[["list"]];let a=ha(s)?s:[...s,[Nr,e??{}]];return defineConfig({...t,use:n,reporter:a})}var Er=false;function hl(t,e,r="manual_record"){if(!t||!t.annotations){Er||(Er=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
2532
+ `);}}};var Qs=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Xs(t){let e=t.toLowerCase();return Qs.some(r=>e.includes(r))}var ge=class t{constructor(e,r){this.page=e;this.records=[];this.listeners=[];this.currentNetworkCounter=null;this.pendingRequests=new Map;this.networkWriter=null;this.consoleWriter=null;this.pendingBodyReads=[];this.requestIdCounter=0;this.networkRequestCount=0;this.consoleLogCount=0;this.includeNetworkStats=r?.includeNetworkStats??true,this.origGoto=e.goto.bind(e),this.origGoBack=e.goBack.bind(e),this.origGoForward=e.goForward.bind(e),this.origReload=e.reload.bind(e);try{this.includeNetworkStats&&(this.networkWriter=new N("network")),this.consoleWriter=new N("console");}catch{}this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async finalizeCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[,e]of this.pendingRequests)this.networkWriter&&(this.networkWriter.append({url:e.url,method:e.method,resourceType:e.resourceType,statusCode:0,responseTimeMs:Date.now()-e.startTimeMs,startedAt:e.startedAt,requestHeaders:e.headers,requestBody:e.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:e.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.networkRequestCount++);this.pendingRequests.clear(),this.networkWriter?.close(),this.consoleWriter?.close();}static mapConsoleType(e){switch(e){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getFileData(){this.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 e=this.records.map(r=>({url:r.url,navigationType:r.navigationType,timestamp:r.timestamp,domContentLoadedAt:r.domContentLoadedAt,networkIdleAt:r.networkIdleAt,networkStats:r.networkStats}));return this.includeNetworkStats?await this.finalizeCapturedRequests():this.consoleWriter?.close(),{navigations:e,networkRequestsFile:this.networkWriter?.getCount()?this.networkWriter.getPath():null,networkRequestsCount:this.networkWriter?.getCount()??0,consoleLogsFile:this.consoleWriter?.getCount()?this.consoleWriter.getPath():null,consoleLogsCount:this.consoleWriter?.getCount()??0}}async flushLegacyAnnotations(e){}dispose(){this.page.goto=this.origGoto,this.page.goBack=this.origGoBack,this.page.goForward=this.origGoForward,this.page.reload=this.origReload;for(let{event:e,handler:r}of this.listeners)this.page.off(e,r);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}getRecords(){return this.records}interceptMethods(){let e=this,r=this.page;r.goto=async function(n,s){return e.recordNavigation(n,"goto"),e.origGoto(n,s)},r.goBack=async function(n){let s=await e.origGoBack(n);return e.recordNavigation(r.url(),"back"),s},r.goForward=async function(n){let s=await e.origGoForward(n);return e.recordNavigation(r.url(),"forward"),s},r.reload=async function(n){return e.recordNavigation(r.url(),"refresh"),e.origReload(n)};}attachListeners(){let e=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",e),this.listeners.push({event:"domcontentloaded",handler:e});let r=s=>{try{let a=s;if(typeof a.parentFrame=="function"&&a.parentFrame()!==null)return;let o=a.url(),i=this.records[this.records.length-1];if(i&&Date.now()-new Date(i.timestamp).getTime()<50&&i.url===o)return;this.recordNavigation(o,"navigation");}catch{}};this.page.on("framenavigated",r),this.listeners.push({event:"framenavigated",handler:r});let n=s=>{try{let a=s,o=a.type(),i=a.text();if(o==="debug"&&i.startsWith("__testrelic_nav:")){try{let l=JSON.parse(i.slice(16));l.type&&l.url&&this.recordNavigation(l.url,l.type);}catch{}return}{let l=null;try{let c=a.location();c&&c.url&&(l=`${c.url}:${c.lineNumber}:${c.columnNumber}`);}catch{}let d=t.mapConsoleType(o);this.consoleWriter&&(this.consoleWriter.append({level:d,text:i,timestamp:new Date().toISOString(),location:l}),this.consoleLogCount++);}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=i=>{this.currentNetworkCounter&&this.currentNetworkCounter.totalRequests++;try{let l=i,d=String(this.requestIdCounter++),c=l.postData()??null,p={url:l.url(),method:l.method(),resourceType:this.mapResourceType(l.resourceType()),headers:l.headers(),postData:c,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now()};this.pendingRequests.set(d,p),i.__testrelic_id=d;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let a=i=>{try{let l=i;if(this.currentNetworkCounter){let b=l.status();b>=400&&(this.currentNetworkCounter.failedRequests++,this.currentNetworkCounter.failedRequestUrls.push(b+" "+l.url()));let C=l.headers()["content-length"];C&&(this.currentNetworkCounter.totalBytes+=parseInt(C,10)||0);let w=l.request().resourceType(),y=this.mapResourceType(w);this.currentNetworkCounter.byType[y]++;}let d=l.request().__testrelic_id;if(!d)return;let c=this.pendingRequests.get(d);if(!c)return;this.pendingRequests.delete(d);let p=Date.now()-c.startTimeMs,f=l.headers(),u=f["content-type"]??null,g=parseInt(f["content-length"]??"0",10)||0,h=u?!Xs(u):!1,m=(async()=>{let b=null;if(!h)try{b=(await l.body()).toString("utf-8");}catch{}let C={url:c.url,method:c.method,resourceType:c.resourceType,statusCode:l.status(),responseTimeMs:p,startedAt:c.startedAt,requestHeaders:c.headers,requestBody:c.postData,responseBody:b,responseHeaders:f,contentType:u,responseSize:g,requestBodyTruncated:c.postDataTruncated,responseBodyTruncated:!1,isBinary:h,error:null};this.networkWriter&&(this.networkWriter.append(C),this.networkRequestCount++);})();this.pendingBodyReads.push(m);}catch{}};this.page.on("response",a),this.listeners.push({event:"response",handler:a});let o=i=>{if(this.currentNetworkCounter){this.currentNetworkCounter.failedRequests++;try{let l=i;this.currentNetworkCounter.failedRequestUrls.push("ERR "+l.url());}catch{}}try{let l=i,d=l.__testrelic_id;if(!d)return;let c=this.pendingRequests.get(d);if(!c)return;this.pendingRequests.delete(d);let p={url:c.url,method:c.method,resourceType:c.resourceType,statusCode:0,responseTimeMs:Date.now()-c.startTimeMs,startedAt:c.startedAt,requestHeaders:c.headers,requestBody:c.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:c.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:l.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(p),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",o),this.listeners.push({event:"requestfailed",handler:o});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let e=history.pushState.bind(history),r=history.replaceState.bind(history);history.pushState=function(...n){e(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){r(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(e,r){this.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:e,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(e){switch(e){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};var Cr=Symbol.for("__testrelic_call_id"),ea="__testrelic_api_assertions",U=new WeakMap,H=class{constructor(){this.assertions=[];this.currentCallId=null;}recordAssertion(e){this.assertions.push(e);}getAssertions(){return this.assertions}setCurrentCallId(e){this.currentCallId=e;}getCurrentCallId(){return this.currentCallId}getData(){return [...this.assertions]}flushLegacyAnnotations(e){this.assertions.length!==0&&e.annotations.push({type:ea,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}};var Tr="[REDACTED]";function rt(t,e){if(t===null||e.length===0)return t;let r=new Set(e.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(t))Object.hasOwn(t,s)&&(n[s]=r.has(s.toLowerCase())?Tr:t[s]);return n}function he(t,e){if(t===null||e.length===0)return t;let r;try{r=JSON.parse(t);}catch{return t}if(typeof r!="object"||r===null)return t;let n=new Set(e),s=tt(r,n);return JSON.stringify(s)}function tt(t,e){if(Array.isArray(t))return t.map(r=>tt(r,e));if(typeof t=="object"&&t!==null){let r={};for(let n of Object.keys(t)){if(!Object.hasOwn(t,n))continue;let s=t[n];e.has(n)?r[n]=Tr:r[n]=tt(s,e);}return r}return t}function Rr(t,e,r){if(r.length>0){for(let n of r)if(Sr(t,n))return false}if(e.length>0){for(let n of e)if(Sr(t,n))return true;return false}return true}function Sr(t,e){try{return e instanceof RegExp?e.test(t):ta(e).test(t)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(e)}`),false}}function ta(t){let e="",r=0;for(;r<t.length;){let n=t[r];n==="*"&&t[r+1]==="*"?(e+=".*",r+=2,t[r]==="/"&&r++):n==="*"?(e+="[^/]*",r++):n==="?"?(e+="[^/]",r++):".+^${}()|[]\\".includes(n)?(e+="\\"+n,r++):(e+=n,r++);}return new RegExp(e)}var ra=["get","post","put","patch","delete","head","fetch"],na=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function sa(t){let e=t.toLowerCase();return na.some(r=>e.includes(r))}function aa(t){if(!t)return null;if(t.data!==void 0&&t.data!==null){let e=t.data;return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString("base64"):JSON.stringify(e)}if(t.form!==void 0&&t.form!==null)return JSON.stringify(t.form);if(t.multipart!==void 0&&t.multipart!==null){let e=t.multipart,r={};for(let[n,s]of Object.entries(e))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?r[n]=String(s):s&&typeof s=="object"&&"name"in s?r[n]=`[file: ${s.name}]`:r[n]="[binary]";return JSON.stringify(r)}return null}var me=class me{constructor(e,r,n){this.originals=new Map;this.apiCallWriter=null;this.callCounter=0;this.apiCallCount=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=e,this.assertionTracker=r??null,this.apiConfig=n??me.DEFAULT_API_CONFIG;try{this.apiCallWriter=new N("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(e){return e!=null&&typeof e=="object"?U.get(e)??null:this.primitiveCallIds.get(e)??null}intercept(){for(let r of ra){let n=this.context[r].bind(this.context);this.originals.set(r,n),this.context[r]=this.createWrapper(r,n);}let e=this.context.dispose.bind(this.context);this.originals.set("dispose",e),this.context.dispose=async r=>(this.disposed=true,e(r));}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0}}flushLegacyAnnotations(e){}dispose(){for(let[e,r]of this.originals)this.context[e]=r;this.originals.clear(),this.apiCallWriter?.close(),this.callCounter=0,this.apiCallCount=0,this._lastCallId=null,this.primitiveCallIds.clear();}get isDisposed(){return this.disposed}getCapturedCallCount(){return this.apiCallCount}tagResponseMethods(e,r){let n=this,s=e.headers.bind(e);e.headers=function(){let u=s();return U.set(u,r),u};let a=e.headersArray.bind(e);e.headersArray=function(){let u=a();return U.set(u,r),u};let o=e.json.bind(e);e.json=async function(){let u=await o();return u!=null&&typeof u=="object"&&U.set(u,r),u};let i=e.status.bind(e);e.status=function(){let u=i();return n.primitiveCallIds.set(u,r),u};let l=e.statusText.bind(e);e.statusText=function(){let u=l();return n.primitiveCallIds.set(u,r),u};let d=e.ok.bind(e);e.ok=function(){let u=d();return n.primitiveCallIds.set(u,r),u};let c=e.text.bind(e);e.text=async function(){let u=await c();return n.primitiveCallIds.set(u,r),u};let p=e.body.bind(e);e.body=async function(){let u=await p();return U.set(u,r),u};}createWrapper(e,r){let n=this;return async function(a,o){if(!Rr(a,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return r(a,o);let i=`api-call-${n.callCounter++}`,l=new Date().toISOString(),d=e==="fetch"?(o?.method??"GET").toUpperCase():e.toUpperCase(),c=aa(o),p=performance.now();n._lastCallId=i,n.assertionTracker&&n.assertionTracker.setCurrentCallId(i);let f;try{f=await r(a,o);}catch(u){let g=performance.now();try{let h=n.apiConfig.captureRequestBody?he(c,n.apiConfig.redactBodyFields):null,m={id:i,timestamp:l,method:d,url:a,requestHeaders:null,requestBody:h,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((g-p)*100)/100,isBinary:!1,error:u instanceof Error?u.message:String(u)};n.apiCallWriter&&(n.apiCallWriter.append(m),n.apiCallCount++);}catch{}throw u}try{let u=performance.now(),g=f.headers(),h=g["content-type"]??null,m=h?!sa(h):!1,b=null;n.apiConfig.captureRequestHeaders&&o?.headers&&(b=o.headers);let C=null;n.apiConfig.captureResponseHeaders&&(C=g);let w=n.apiConfig.captureRequestBody?c:null,y=null;if(n.apiConfig.captureResponseBody)try{m?y=(await f.body()).toString("base64"):y=await f.text();}catch{}b=rt(b,n.apiConfig.redactHeaders),C=rt(C,n.apiConfig.redactHeaders),w=he(w,n.apiConfig.redactBodyFields),y=he(y,n.apiConfig.redactBodyFields);let T={id:i,timestamp:l,method:d,url:f.url(),requestHeaders:b,requestBody:w,responseStatusCode:f.status(),responseStatusText:f.statusText(),responseHeaders:C,responseBody:y,responseTimeMs:Math.round((u-p)*100)/100,isBinary:m,error:null};n.apiCallWriter&&(n.apiCallWriter.append(T),n.apiCallCount++);}catch{}try{f[Cr]=i,n.tagResponseMethods(f,i);}catch{}return f}}};me.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 $=me;var oa="__testrelic_api_config",la="__testrelic_config_trackApiCalls";function st(t){let e=t.annotations.find(n=>n.type===oa&&n.description!==void 0);if(e)try{return JSON.parse(e.description,da)}catch{}let r=t.annotations.find(n=>n.type===la&&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 da(t,e){if(typeof e=="object"&&e!==null&&e.__regexp===true&&typeof e.source=="string"){let{source:r,flags:n}=e;return new RegExp(r,n)}return e}var Lr={page:async({page:t},e,r)=>{let n=new ge(t);try{await n.init();}catch{}await e(t);try{let{navigations:s,networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:l}=await n.getFileData(),d={testRelicData:!0,version:PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:a,networkRequestsCount:o,consoleLogsFile:i,consoleLogsCount:l,apiCallsFile:null,apiCallsCount:0};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:t},e,r)=>{let n=st(r);if(!n.trackApiCalls){await e(t);return}let s=new H,a=new $(t,s,n);a.intercept(),await e(t);try{let{apiCallsFile:o,apiCallsCount:i}=a.getFileData(),l=n.captureAssertions?s.getData():[],d={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],apiAssertions:l,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:o,apiCallsCount:i};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};test.extend(Lr);var fa={request:async({request:t},e,r)=>{let n=st(r);if(!n.trackApiCalls){await e(t);return}let s=new H,a=new $(t,s,n);a.intercept();let o=null;try{o=new N("api-console");}catch{}let i=0,l=process.stdout.write,d=process.stderr.write;process.stdout.write=function(c,...p){try{let f=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!f.startsWith("[testrelic]")&&!f.startsWith("\u2139 TestRelic")&&!f.startsWith("\u2713 TestRelic")&&!f.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stdout",text:f.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return l.apply(process.stdout,[c,...p])},process.stderr.write=function(c,...p){try{let f=typeof c=="string"?c:Buffer.isBuffer(c)?c.toString("utf-8"):String(c);!f.startsWith("[testrelic]")&&!f.startsWith("\u26A0 TestRelic")&&o&&(o.append({level:"stderr",text:f.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),i++);}catch{}return d.apply(process.stderr,[c,...p])};try{await e(t);}finally{process.stdout.write=l,process.stderr.write=d;}try{o?.close();let{apiCallsFile:c,apiCallsCount:p}=a.getFileData(),f=n.captureAssertions?s.getData():[],u={testRelicData:!0,version:PAYLOAD_VERSION,navigations:[],apiAssertions:f,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:i>0?o?.getPath()??null:null,consoleLogsCount:i,apiCallsFile:c,apiCallsCount:p};await r.attach(ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(u)),contentType:ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};var Nr="@testrelic/playwright-analytics";function ha(t){return Array.isArray(t)?t.some(e=>Array.isArray(e)&&typeof e[0]=="string"&&e[0]===Nr):false}function ma(t,e){let n={video:"on",screenshot:"on",trace:"on",...t.use??{}},s;Array.isArray(t.reporter)?s=t.reporter:typeof t.reporter=="string"?s=[[t.reporter]]:s=[["list"]];let a=ha(s)?s:[...s,[Nr,e??{}]];return defineConfig({...t,use:n,reporter:a})}var Mr=false;function hl(t,e,r="manual_record"){if(!t||!t.annotations){Mr||(Mr=true,process.stderr.write(`[testrelic] recordNavigation: reporter not active, navigation not recorded
2534
2533
  `));return}let n={url:e,navigationType:r,timestamp:new Date().toISOString()};t.annotations.push({type:"lambdatest-navigation",description:JSON.stringify(n)});}export{X as SCHEMA_VERSION,fe as default,ma as defineConfig,hl as recordNavigation,fa as testRelicApiFixture,Lr as testRelicFixture};//# sourceMappingURL=index.js.map
2535
2534
  //# sourceMappingURL=index.js.map