@testrelic/playwright-analytics 2.9.0-next.66 → 2.9.0-next.68

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.
@@ -2575,7 +2575,7 @@ ${s}
2575
2575
  `);break;default:this.setLocalMode(`auth_error_${r??"unknown"}`),process.stderr.write(`\u26A0 TestRelic: Cloud authentication failed. Running in local mode.
2576
2576
  `);break}}async resolveRepoId(){if(!this.config||!this.authState.accessToken)return;let e=this.gitMetadata?.remoteUrl?Z(this.gitMetadata.remoteUrl):null,r=e?wr(e):this.config.projectName??Q(process.cwd()),a=e??this.config.projectName??Q(process.cwd()),s=this.readRepoCache(a);if(s){this.repoId=s.repoId;return}try{let n=await br(this.config.endpoint,this.authState.accessToken,a,r,this.config.timeout,this.gitMetadata?.branch);n&&(this.repoId=n.repoId,this.writeRepoCache(a,n.repoId,n.displayName));}catch{}!e&&!this.config.projectName&&!Je(process.cwd())&&process.stderr.write(`\u2139 TestRelic: No git remote or package.json detected. Set project.name in .testrelic for stable project identity.
2577
2577
  `);}readRepoCache(e){if(!this.config)return null;let r=join(this.config.queueDirectory,"..","cache","repo.json");try{if(!existsSync(r))return null;let a=readFileSync(r,"utf-8"),s=JSON.parse(a);if(s.gitId!==e||Date.now()-s.resolvedAt>Is)return null;let n=this.hashApiKey();return n&&s.apiKeyHash!==n?null:s}catch{return null}}writeRepoCache(e,r,a){if(!this.config)return;let s=join(this.config.queueDirectory,"..","cache"),n=join(s,"repo.json");try{mkdirSync(s,{recursive:!0});let o={repoId:r,gitId:e,displayName:a,resolvedAt:Date.now(),apiKeyHash:this.hashApiKey()??""},i=n+".tmp";writeFileSync(i,JSON.stringify(o,null,2),"utf-8"),renameSync(i,n);}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,a=this.config.endpoint;this.flushPromise=Promise.race([Cr(r,a,e),new Promise(s=>setTimeout(s,Ar))]).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 Ge(e))return;if(this.config?.apiKey){let a=await We(this.config.endpoint,this.config.apiKey,this.config.timeout);if(!Ke(a)){let s=a;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.
2578
- `),this.startBackgroundFlush();}}}catch{}},Ls);}};var Ms=new Set(["smoke","regression","nightly","ci"]);function ue(){let t=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(t&&Ms.has(t))return t}var Ps=1048576,pe=[1e3,3e3,9e3],fe=3,Fs=40*1048576,Ns=new Set(["e2e","mobile","unit"]);function et(t){if(t&&t.length>0&&t.every(s=>s.testType==="api")){let s=new Map;for(let i of t){let l=i.apiProtocol??"rest";s.set(l,(s.get(l)??0)+1);}let n="rest",o=0;for(let[i,l]of s)l>o&&(o=l,n=i);return {testType:"api",apiProtocol:n,metadata:{testType:"api",primaryProtocol:n}}}let e=new Map;for(let s of t??[])Ns.has(s.testType)&&e.set(s.testType,(e.get(s.testType)??0)+1);let r=null,a=0;for(let[s,n]of e)n>a&&(a=n,r=s);return {testType:r??"e2e"}}function tt(t,e,r,a,s,n){let o=n?.cloudPlatform?n.cloudPlatform:a?.provider&&a.provider!=="unknown"?a.provider:"local",i=ue(),l=et(s),d=l.testType==="api"?l:null,p=d&&s?s.map(h=>h.apiProtocol?h:{...h,apiProtocol:d.apiProtocol}):s,f={runId:t.testRunId,repoGitId:e,startedAt:t.startedAt,summary:t.summary,timeline:t.timeline,environment:o,...i?{runType:i}:{},...d?{testType:d.testType,apiProtocol:d.apiProtocol,metadata:d.metadata}:{testType:l.testType},...p&&p.length>0?{tests:p}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...a?.provider?{ciProvider:a.provider}:{},...a?.runUrl?{ciRunUrl:a.runUrl}:{},...n?.cloudPlatform?{cloudPlatform:n.cloudPlatform}:{},...n?.cloudBuildId?{cloudBuildId:n.cloudBuildId}:{},...n?.cloudSessionId?{cloudSessionId:n.cloudSessionId}:{}};if(f.tests&&f.tests.length>0){let h=JSON.stringify(f);if(Buffer.byteLength(h,"utf-8")>Fs){let c=f.tests.map(({consoleLogs:u,networkRequests:g,apiCalls:m,...b})=>b);return {...f,tests:c}}}return f}function Xe(t){return typeof t=="string"?Buffer.byteLength(t,"utf-8"):0}function rt(t){return Array.isArray(t)?t.map(e=>{let r=e.statusCode??e.responseStatusCode??null;return {...e.protocol!=null?{protocol:e.protocol}:{},method:e.method??null,url:e.url??null,statusCode:r,statusText:e.statusText??e.responseStatusText??null,ok:typeof r=="number"?r<400:e.ok??null,durationMs:e.durationMs??e.responseTimeMs??null,bytesIn:typeof e.bytesIn=="number"?e.bytesIn:Xe(e.responseBody),bytesOut:typeof e.bytesOut=="number"?e.bytesOut:Xe(e.requestBody),requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null}}):[]}function at(t){return Array.isArray(t)?t.map(e=>{let r=e.responseStatusCode??e.statusCode??0,a=e.timestamp??null;return {method:e.method??"GET",url:e.url??"",status:r,statusCode:r,type:"xhr",size:Xe(e.responseBody),duration:e.responseTimeMs??e.durationMs??0,responseTimeMs:e.responseTimeMs??e.durationMs??0,requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null,timestamp:a,startedAt:a}}):[]}function st(t){if(!Array.isArray(t))return [];let e=r=>{if(r==null)return String(r);if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}};return t.map(r=>{let a=r.status==="failed"?"failed":"passed",s=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,n=r.kind??r.type??"assertion",o=a==="failed"?`expected ${e(r.expected)}, received ${e(r.actual)}`:r.expected!==void 0?`expected ${e(r.expected)}`:null;return {kind:n,description:s??r.description??`${n} assertion`,status:a,detail:o}})}async function ge(t){return new Promise(e=>setTimeout(e,t))}function Ds(t){let e={};for(let[r,a]of Object.entries(t))a!=null&&(e[r]=a);return e}async function _r(t,e,r){for(let a=0;a<fe;a++)try{let s=await fetch(t,e);if(s.ok)return s;if(s.status===401&&r&&a===0){let n=await r();if(n){let o={...e,headers:{...e.headers,Authorization:`Bearer ${n}`}},i=await fetch(t,o);if(i.ok)return i}return null}if(s.status===429&&a<fe-1){let n=s.headers.get("Retry-After"),o=n?parseInt(n,10)*1e3:pe[a];!isNaN(o)&&o>0?await ge(o):await ge(pe[a]);continue}if(s.status>=500&&a<fe-1){await ge(pe[a]);continue}return s}catch{if(a<fe-1){await ge(pe[a]);continue}return null}return null}function Bs(t){let e=JSON.stringify(t),r={"Content-Type":"application/json"};if(Buffer.byteLength(e,"utf-8")>Ps){let a=gzipSync(Buffer.from(e,"utf-8"));return r["Content-Encoding"]="gzip",{body:a,headers:r}}return {body:e,headers:r}}async function Ir(t,e,r,a){let s=`${t}/runs`,{body:n,headers:o}=Bs(r);o.Authorization=`Bearer ${e}`;let i=await _r(s,{method:"POST",headers:o,body:n},a);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 Lr(t,e,r){let a=`${t}/runs/init`;try{let s=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(Ds(r))});return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function Mr(t,e,r,a){let s=`${t}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(a)}).catch(()=>{});}async function Er(t,e,r,a){let s=`${t}/runs/${r}/finalize`;return (await _r(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(a)}))?.ok??false}function nt(t,e,r,a){let s=`${t}/runs/${r}/finalize`,n=new Date,o={finishedAt:n.toISOString(),duration:n.getTime()-new Date(a).getTime(),summary:{}};fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}).catch(()=>{});}function Pr(t,e,r,a){let s=[],n=[],o=null,i=0,l=null,d=0,p=null,f=0,h=t.filter(g=>g.name===ATTACHMENT_NAME&&g.body),c=false;if(h.length>0)for(let g of h)try{let m=JSON.parse(g.body.toString());if(isTestRelicFilePayload(m)){s=s.concat(m.navigations),n=n.concat(m.apiAssertions),m.networkRequestsFile&&(o=m.networkRequestsFile,i+=m.networkRequestsCount),m.consoleLogsFile&&(l=m.consoleLogsFile,d+=m.consoleLogsCount),m.apiCallsFile&&(p=m.apiCallsFile,f+=m.apiCallsCount),c=!0;continue}if(isTestRelicDataPayload(m)){s=s.concat(m.navigations),Array.isArray(m.apiAssertions)&&(n=n.concat(m.apiAssertions)),i+=m.networkRequests?.length??0,f+=m.apiCalls?.length??0;let b=m.consoleLogs;Array.isArray(b)&&(d+=b.length),c=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
2578
+ `),this.startBackgroundFlush();}}}catch{}},Ls);}};var Ms=new Set(["smoke","regression","nightly","ci"]);function ue(){let t=process.env.TESTRELIC_RUN_TYPE?.trim().toLowerCase();if(t&&Ms.has(t))return t}var Ps=1048576,pe=[1e3,3e3,9e3],fe=3,Fs=40*1048576,Ns=new Set(["e2e","mobile","unit"]);function et(t){if(t&&t.length>0&&t.every(s=>s.testType==="api")){let s=new Map;for(let i of t){let l=i.apiProtocol??"rest";s.set(l,(s.get(l)??0)+1);}let n="rest",o=0;for(let[i,l]of s)l>o&&(o=l,n=i);return {testType:"api",apiProtocol:n,metadata:{testType:"api",primaryProtocol:n}}}let e=new Map;for(let s of t??[])Ns.has(s.testType)&&e.set(s.testType,(e.get(s.testType)??0)+1);let r=null,a=0;for(let[s,n]of e)n>a&&(a=n,r=s);return {testType:r??"e2e"}}function tt(t,e,r,a,s,n){let o=n?.cloudPlatform?n.cloudPlatform:a?.provider&&a.provider!=="unknown"?a.provider:"local",i=ue(),l=et(s),d=l.testType==="api"?l:null,p=d&&s?s.map(h=>h.apiProtocol?h:{...h,apiProtocol:d.apiProtocol}):s,f={runId:t.testRunId,repoGitId:e,startedAt:t.startedAt,summary:t.summary,timeline:t.timeline,environment:o,...i?{runType:i}:{},...d?{testType:d.testType,apiProtocol:d.apiProtocol,metadata:d.metadata}:{testType:l.testType},...p&&p.length>0?{tests:p}:{},...r?.branch?{branch:r.branch}:{},...r?.commitSha?{commit:r.commitSha}:{},...r?.commitMessage?{commitMessage:r.commitMessage}:{},...r?.commitAuthor?{commitAuthor:r.commitAuthor}:{},...t.completedAt?{finishedAt:t.completedAt}:{},...t.totalDuration?{duration:t.totalDuration}:{},...a?.provider?{ciProvider:a.provider}:{},...a?.runUrl?{ciRunUrl:a.runUrl}:{},...n?.cloudPlatform?{cloudPlatform:n.cloudPlatform}:{},...n?.cloudBuildId?{cloudBuildId:n.cloudBuildId}:{},...n?.cloudSessionId?{cloudSessionId:n.cloudSessionId}:{}};if(f.tests&&f.tests.length>0){let h=JSON.stringify(f);if(Buffer.byteLength(h,"utf-8")>Fs){let c=f.tests.map(({consoleLogs:u,networkRequests:g,apiCalls:m,...b})=>b);return {...f,tests:c}}}return f}function Xe(t){return typeof t=="string"?Buffer.byteLength(t,"utf-8"):0}function rt(t){return Array.isArray(t)?t.map(e=>{let r=e.statusCode??e.responseStatusCode??null;return {...e.protocol!=null?{protocol:e.protocol}:{},method:e.method??null,url:e.url??null,statusCode:r,statusText:e.statusText??e.responseStatusText??null,ok:typeof r=="number"?r<400:e.ok??null,durationMs:e.durationMs??e.responseTimeMs??null,bytesIn:typeof e.bytesIn=="number"?e.bytesIn:Xe(e.responseBody),bytesOut:typeof e.bytesOut=="number"?e.bytesOut:Xe(e.requestBody),requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null,requestCookies:e.requestCookies??null,responseCookies:e.responseCookies??null}}):[]}function at(t){return Array.isArray(t)?t.map(e=>{let r=e.responseStatusCode??e.statusCode??0,a=e.timestamp??null;return {method:e.method??"GET",url:e.url??"",status:r,statusCode:r,type:"xhr",size:Xe(e.responseBody),duration:e.responseTimeMs??e.durationMs??0,responseTimeMs:e.responseTimeMs??e.durationMs??0,requestHeaders:e.requestHeaders??null,responseHeaders:e.responseHeaders??null,requestBody:e.requestBody??null,responseBody:e.responseBody??null,timestamp:a,startedAt:a}}):[]}function st(t){if(!Array.isArray(t))return [];let e=r=>{if(r==null)return String(r);if(typeof r=="string")return r;try{return JSON.stringify(r)}catch{return String(r)}};return t.map(r=>{let a=r.status==="failed"?"failed":"passed",s=typeof r.expression=="string"&&r.expression.trim()?r.expression.trim():null,n=r.kind??r.type??"assertion",o=a==="failed"?`expected ${e(r.expected)}, received ${e(r.actual)}`:r.expected!==void 0?`expected ${e(r.expected)}`:null;return {kind:n,description:s??r.description??`${n} assertion`,status:a,detail:o}})}async function ge(t){return new Promise(e=>setTimeout(e,t))}function Ds(t){let e={};for(let[r,a]of Object.entries(t))a!=null&&(e[r]=a);return e}async function _r(t,e,r){for(let a=0;a<fe;a++)try{let s=await fetch(t,e);if(s.ok)return s;if(s.status===401&&r&&a===0){let n=await r();if(n){let o={...e,headers:{...e.headers,Authorization:`Bearer ${n}`}},i=await fetch(t,o);if(i.ok)return i}return null}if(s.status===429&&a<fe-1){let n=s.headers.get("Retry-After"),o=n?parseInt(n,10)*1e3:pe[a];!isNaN(o)&&o>0?await ge(o):await ge(pe[a]);continue}if(s.status>=500&&a<fe-1){await ge(pe[a]);continue}return s}catch{if(a<fe-1){await ge(pe[a]);continue}return null}return null}function Bs(t){let e=JSON.stringify(t),r={"Content-Type":"application/json"};if(Buffer.byteLength(e,"utf-8")>Ps){let a=gzipSync(Buffer.from(e,"utf-8"));return r["Content-Encoding"]="gzip",{body:a,headers:r}}return {body:e,headers:r}}async function Ir(t,e,r,a){let s=`${t}/runs`,{body:n,headers:o}=Bs(r);o.Authorization=`Bearer ${e}`;let i=await _r(s,{method:"POST",headers:o,body:n},a);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 Lr(t,e,r){let a=`${t}/runs/init`;try{let s=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(Ds(r))});return s.ok?{runId:(await s.json()).runId}:null}catch{return null}}function Mr(t,e,r,a){let s=`${t}/runs/${r}/tests`;fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(a)}).catch(()=>{});}async function Er(t,e,r,a){let s=`${t}/runs/${r}/finalize`;return (await _r(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(a)}))?.ok??false}function nt(t,e,r,a){let s=`${t}/runs/${r}/finalize`,n=new Date,o={finishedAt:n.toISOString(),duration:n.getTime()-new Date(a).getTime(),summary:{}};fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify(o)}).catch(()=>{});}function Pr(t,e,r,a){let s=[],n=[],o=null,i=0,l=null,d=0,p=null,f=0,h=t.filter(g=>g.name===ATTACHMENT_NAME&&g.body),c=false;if(h.length>0)for(let g of h)try{let m=JSON.parse(g.body.toString());if(isTestRelicFilePayload(m)){s=s.concat(m.navigations),n=n.concat(m.apiAssertions),m.networkRequestsFile&&(o=m.networkRequestsFile,i+=m.networkRequestsCount),m.consoleLogsFile&&(l=m.consoleLogsFile,d+=m.consoleLogsCount),m.apiCallsFile&&(p=m.apiCallsFile,f+=m.apiCallsCount),c=!0;continue}if(isTestRelicDataPayload(m)){s=s.concat(m.navigations),Array.isArray(m.apiAssertions)&&(n=n.concat(m.apiAssertions)),i+=m.networkRequests?.length??0,f+=m.apiCalls?.length??0;let b=m.consoleLogs;Array.isArray(b)&&(d+=b.length),c=!0;}}catch{process.stderr.write(`[testrelic] Warning: Corrupt attachment for test "${r}"
2579
2579
  `);}return c||(s=e.filter(g=>g.type==="lambdatest-navigation"&&g.description).map(g=>{try{return JSON.parse(g.description)}catch{return null}}).filter(g=>g!==null)),s.length===0&&i===0&&f===0&&!a&&!c&&process.stderr.write(`[testrelic] Warning: No data found for test "${r}". Make sure your tests import { test, expect } from '@testrelic/playwright-analytics/fixture' instead of '@playwright/test'. Without the TestRelic fixture, network logs, video sync, and timeline data cannot be captured.
2580
2580
  `),{navigations:s,apiAssertions:n,networkRequestsFile:o,networkRequestsCount:i,consoleLogsFile:l,consoleLogsCount:d,apiCallsFile:p,apiCallsCount:f}}function he(t=process.env){let e=Us(t.TESTRELIC_CLOUD_PLATFORM);if(e)return {cloudPlatform:e,cloudBuildId:t.TESTRELIC_CLOUD_BUILD_ID||void 0,cloudSessionId:t.TESTRELIC_CLOUD_SESSION_ID||void 0};if(t.BROWSERSTACK_USERNAME||t.BROWSERSTACK_ACCESS_KEY)return {cloudPlatform:"browserstack",cloudBuildId:t.BROWSERSTACK_BUILD_NAME||t.BROWSERSTACK_BUILD_ID||void 0,cloudSessionId:t.BROWSERSTACK_SESSION_ID||void 0};if(t.LT_USERNAME||t.LAMBDATEST_USERNAME||t.LT_ACCESS_KEY||t.LAMBDATEST_ACCESS_KEY)return {cloudPlatform:"lambdatest",cloudBuildId:t.LT_BUILD||t.LAMBDATEST_BUILD||void 0,cloudSessionId:t.LT_SESSION_ID||t.LAMBDATEST_SESSION_ID||void 0};let r=t.PLAYWRIGHT_WS_ENDPOINT;if(r){if(/cdp\.lambdatest\.com/i.test(r))return {cloudPlatform:"lambdatest"};if(/cdp\.browserstack\.com/i.test(r))return {cloudPlatform:"browserstack"}}return {}}function Us(t){if(!t)return;let e=t.toLowerCase().trim();if(e==="browserstack"||e==="bs")return "browserstack";if(e==="lambdatest"||e==="lt")return "lambdatest"}var Gs=5,me=[1e3,3e3,9e3],z=3,Ws={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".webm":"video/webm",".mp4":"video/mp4",".zip":"application/zip"},it=0,ot=[];async function Ks(){it>=Gs&&await new Promise(t=>ot.push(t)),it++;}function Js(){it--,ot.length>0&&ot.shift()();}async function ve(t){return new Promise(e=>setTimeout(e,t))}function Ys(t){let e=t.substring(t.lastIndexOf(".")).toLowerCase();return Ws[e]??"application/octet-stream"}function Zs(t){try{return statSync(t).size}catch{return 0}}async function Qs(t,e,r,a,s){let n=`${t}/artifacts/upload-url`,o=JSON.stringify({runId:r.runId,testId:r.testId,fileName:basename(r.filePath),contentType:s,type:r.type,sizeBytes:a});for(let i=0;i<z;i++)try{let l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:o});if(l.ok)return await l.json();if(l.status>=500&&i<z-1){await ve(me[i]);continue}return null}catch{if(i<z-1){await ve(me[i]);continue}return null}return null}async function Xs(t,e,r,a){for(let s=0;s<z;s++)try{let n=createReadStream(e),o=Readable.toWeb(n),i=await fetch(t,{method:"PUT",headers:{"Content-Type":r,"Content-Length":String(a)},body:o,duplex:"half"});if(i.ok)return !0;if(i.status>=500&&s<z-1){await ve(me[s]);continue}return !1}catch{if(s<z-1){await ve(me[s]);continue}return false}return false}async function en(t,e,r){let a=`${t}/artifacts/confirm`;try{return (await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({artifactId:r})})).ok}catch{return false}}async function tn(t,e,r,a){let s=Zs(r.filePath);if(s===0)return {success:false,storageKey:null,artifactId:null,error:"file_not_found_or_empty"};if(s>a*1024*1024)return {success:false,storageKey:null,artifactId:null,error:"file_too_large"};let n=Ys(r.filePath);await Ks();try{let o=await Qs(t,e,r,s,n);if(!o)return {success:!1,storageKey:null,artifactId:null,error:"upload_url_request_failed"};if(!await Xs(o.uploadUrl,r.filePath,n,s))return {success:!1,storageKey:o.storageKey,artifactId:o.artifactId,error:"presigned_put_failed"};let l=await en(t,e,o.artifactId);return {success:l,storageKey:o.storageKey,artifactId:o.artifactId,error:l?null:"confirm_failed"}}finally{Js();}}async function Fr(t,e,r,a){let s=new Map,n=r.map(async o=>{let i=await tn(t,e,o,a);s.set(o.filePath,i);});return await Promise.allSettled(n),s}function lt(t){let r=t.getGitMetadata()?.remoteUrl;return r?Z(r):t.getConfig()?.projectName??Q(process.cwd())}async function Dr(t,e,r,a,s){if(!t.isCloudMode()||e!=="realtime"&&e!=="both"||!await t.ensureValidToken())return null;let o=t.getGitMetadata(),i=P(),l=he(),d=ue();return (await Lr(t.getEndpoint(),t.getAccessToken(),{runId:r,repoGitId:lt(t),branch:o?.branch??null,commit:o?.commitSha??null,commitMessage:o?.commitMessage??null,commitAuthor:o?.commitAuthor??null,startedAt:a,totalTests:null,ciProvider:i?.provider??null,ciRunUrl:i?.runUrl??null,environment:s??l.cloudPlatform??null,cloudPlatform:l.cloudPlatform??null,cloudBuildId:l.cloudBuildId??null,cloudSessionId:l.cloudSessionId??null,...d?{runType:d}:{},testType:"e2e"}))?.runId??null}var rn=true,an=50;async function sn(t,e,r,a){let s=new Map;if(!(e?.uploadArtifacts??rn)||!await t.ensureValidToken())return s;let i=[],l=new Map;for(let c of a){if(c.artifacts.screenshot){let u=join(c.outputDir,c.artifacts.screenshot);i.push({filePath:u,runId:r,testId:c.testId,type:"screenshot"}),l.set(u,{testId:c.testId,field:"screenshot"});}if(c.artifacts.video){let u=join(c.outputDir,c.artifacts.video);i.push({filePath:u,runId:r,testId:c.testId,type:"video"}),l.set(u,{testId:c.testId,field:"video"});}}if(i.length===0)return s;let d=e?.artifactMaxSizeMb??an,p=await Fr(t.getEndpoint(),t.getAccessToken(),i,d),f=new Map;for(let[c,u]of p){if(!u.success||!u.storageKey)continue;let g=l.get(c);if(!g)continue;let m=f.get(g.testId)??{};g.field==="screenshot"&&(m.screenshotKey=u.storageKey),g.field==="video"&&(m.videoKey=u.storageKey),f.set(g.testId,m);}for(let c of a){let u=f.get(c.testId);s.set(c.testId,{...c.artifacts,...u?.screenshotKey?{screenshotKey:u.screenshotKey}:{},...u?.videoKey?{videoKey:u.videoKey}:{}});}let h=Array.from(p.values()).filter(c=>c.success).length;return h>0&&process.stderr.write(`\u2713 TestRelic: Uploaded ${h} artifact(s) to cloud storage.
2581
2581
  `),s}async function dt(t,e,r,a,s,n,o,i,l,d,p){try{if(t.isCloudMode()&&s&&(r==="realtime"||r==="both")){let h=await t.ensureValidToken(),c=t.getGitMetadata(),u=et(p),g={finishedAt:o,duration:i,summary:l,...c?.commitMessage?{commitMessage:c.commitMessage}:{},testType:u.testType,...u.testType==="api"?{apiProtocol:u.apiProtocol,metadata:u.metadata}:{}};if(h){if(!await Er(t.getEndpoint(),t.getAccessToken(),s,g)){let b=e?.queueDirectory??".testrelic/queue";X(b,a,"finalize","finalize_failed_after_retries",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",g,{"Content-Type":"application/json"});}}else {let m=e?.queueDirectory??".testrelic/queue";X(m,a,"finalize",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs/${s}/finalize`,"POST",g,{"Content-Type":"application/json"});}}let f=new Map;if(t.isCloudMode()&&d&&d.length>0&&(f=await sn(t,e,a,d)),t.isCloudMode()&&(!r||r==="batch"||r==="both"))if(await t.ensureValidToken()){let c=t.getGitMetadata(),u=P(),g=lt(t),m=nn(n,f),b=tt(m,g,c,u,p,he()),S=await Ir(t.getEndpoint(),t.getAccessToken(),b,async()=>await t.ensureValidToken()?t.getAccessToken():null);if(!S.success){let y=S,x=e?.queueDirectory??".testrelic/queue";X(x,a,"batch",y.reason,y.targetEndpoint,y.method,y.payload,{"Content-Type":"application/json"});}}else {let c=e?.queueDirectory??".testrelic/queue",u=t.getGitMetadata(),g=P(),m=lt(t),b=tt(n,m,u,g,void 0,he());X(c,a,"batch",t.getFailureReason()??"token_invalid",`${t.getEndpoint()}/runs`,"POST",b,{"Content-Type":"application/json"});}await t.dispose();}catch{try{await t.dispose();}catch{}}}function nn(t,e){if(e.size===0)return t;let r=t.timeline.map(a=>{let s=a.testId;if(!s)return a;let n=e.get(s);return n?{...a,...n.screenshotKey?{screenshotKey:n.screenshotKey}:{},...n.videoKey?{videoKey:n.videoKey}:{}}:a});return {...t,timeline:r}}function q(t){try{return readFileSync(t,"utf-8").split(`