@testrelic/playwright-analytics 2.16.2 → 2.16.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api-fixture.cjs +6 -5
- package/dist/api-fixture.cjs.map +1 -1
- package/dist/api-fixture.js +6 -5
- package/dist/api-fixture.js.map +1 -1
- package/dist/fixture.cjs +7 -6
- package/dist/fixture.cjs.map +1 -1
- package/dist/fixture.js +7 -6
- package/dist/fixture.js.map +1 -1
- package/dist/index.cjs +57 -52
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +57 -52
- package/dist/index.js.map +1 -1
- package/dist/reporter-entry.cjs +44 -40
- package/dist/reporter-entry.cjs.map +1 -1
- package/dist/reporter-entry.js +44 -40
- package/dist/reporter-entry.js.map +1 -1
- package/dist/visual.cjs +2 -2
- package/dist/visual.cjs.map +1 -1
- package/dist/visual.js +2 -2
- package/dist/visual.js.map +1 -1
- package/package.json +2 -2
package/dist/api-fixture.cjs
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
'use strict';var test=require('@playwright/test'),perf_hooks=require('perf_hooks'),fs=require('fs'),path=require('path'),os=require('os'),crypto=require('crypto');require('readline');var url=require('url'),core=require('@testrelic/core');var ut=path.join(os.tmpdir(),"testrelic-data"),v=class{constructor(t){this.count=0;this.closed=false;fs.mkdirSync(ut,{recursive:true}),this.filePath=path.join(ut,`${t}-${crypto.randomUUID().substring(0,8)}.jsonl`),this.fd=fs.openSync(this.filePath,"w");}append(t){if(this.closed)return;let n=JSON.stringify(t)+`
|
|
2
|
-
`;fs.writeSync(this.fd,n),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{fs.closeSync(this.fd);}catch{}}}cleanup(){try{fs.unlinkSync(this.filePath);}catch{}}};var
|
|
3
|
-
`);return dt.set(e,
|
|
4
|
-
`)){let n=t.match(/at\s+(?:.*?\s+\()?(.+?):\d+:\d+\)?$/);if(!n||n[1].startsWith("node:"))continue;let r=Math.max(n[1].lastIndexOf("/"),n[1].lastIndexOf("\\"));return r>0?n[1].slice(0,r+1):null}return null})();function
|
|
5
|
-
`);return ft(n,true)??ft(n,false)}function ft(e,t){for(let n of e){if(t&&pt!==null&&n.includes(pt)||n.includes("node_modules")||n.includes("node:internal")||n.includes(" at new Error")||n.includes(" at captureAssertionLocation")||n.includes(" at findFrame")||n.includes(" at expectWrapper")||n.includes(" at wrappedMatcher"))continue;let r=n.match(/at\s+(?:.*?\s+\()?(.+?):(\d+):(\d+)\)?$/);if(r)return {file:Kt(r[1]),line:parseInt(r[2],10),column:parseInt(r[3],10)}}return null}function Qt(e,t){if(!e)return "custom";let n=e.toLowerCase();return n.includes(".status()")&&!n.includes(".statustext()")?n.includes(".ok()")?"statusOk":"status":n.includes(".ok()")?"statusOk":n.includes(".headers()")||n.includes(".headersarray()")?"header":n.includes("tomatchobject")||n.includes("toequal")?"bodyMatch":n.includes("tocontain")||n.includes("tostringcontaining")?"bodyContains":n.includes(".json()")||n.includes(".text()")?"bodyField":"custom"}function te(e,t,n){let r=function(l,...d){let f=e(),u=t();if(!f||!u)return n(l,...d);let a=null;if(l!=null&&typeof l=="object"){let m=l[J];typeof m=="string"&&(a=m);}if(!a&&l!==null&&l!==void 0&&typeof l=="object"&&(a=D.get(l)??null),a||(a=u.getCallIdForValue(l)),a||(a=f.getCurrentCallId()),!a)return n(l,...d);let i=Zt(),p;if(i){let m=Xt(i.file);m&&i.line>0&&i.line<=m.length&&(p=m[i.line-1].trim());}let g=n(l,...d);return a?yt(g,{tracker:f,callId:a,received:l,location:i??{file:"unknown",line:0},expression:p}):g},s=n,o=r;for(let c of Object.keys(s))o[c]=s[c];return r}var gt=Symbol.for("testrelic.activeAssertionContext");function z(){let e=globalThis,t=e[gt];return t||(t={tracker:null,apiTracker:null},e[gt]=t),t}function E(e,t){let n=z();n.tracker=e,n.apiTracker=t;}function O(e){return te(()=>z().tracker,()=>z().apiTracker,e)}function yt(e,t){return new Proxy(e,{get(n,r,s){let o=Reflect.get(n,r,s);return typeof o!="function"||typeof r=="symbol"?o:r==="not"?yt(o,t):function(...l){let d=l[0],f="passed",u=t.received,a=null;try{let i=o.apply(this??n,l);return i&&typeof i=="object"&&typeof i.then=="function"?i.then(()=>{U(t,r,d,u,"passed");},p=>{throw U(t,r,d,u,"failed"),p}):i}catch(i){if(f="failed",a=i,i instanceof Error&&i.message){let p=i.message.match(/Received:\s*(.+)/);p&&(u=p[1]);}throw i}finally{(a!==null||f==="passed")&&U(t,r,d,u,f);}}}})}function U(e,t,n,r,s){let o=Qt(e.expression,e.received),c={callId:e.callId,type:o,expected:mt(n),actual:mt(r),status:s,location:e.location,expression:e.expression};e.tracker.recordAssertion(c);}function mt(e){if(e==null)return e;if(typeof e=="string")return ct(e);if(typeof e=="number"||typeof e=="boolean")return e;try{return JSON.stringify(e),e}catch{return String(e)}}var wt="[REDACTED]";function $(e,t){if(e===null||t.length===0)return e;let n=new Set(t.map(s=>s.toLowerCase())),r={};for(let s of Object.keys(e))Object.prototype.hasOwnProperty.call(e,s)&&(r[s]=n.has(s.toLowerCase())?wt:e[s]);return r}function L(e,t){if(e===null||t.length===0)return e;let n;try{n=JSON.parse(e);}catch{return e}if(typeof n!="object"||n===null)return e;let r=new Set(t.map(o=>o.toLowerCase())),s=G(n,r);return JSON.stringify(s)}function G(e,t){if(Array.isArray(e))return e.map(n=>G(n,t));if(typeof e=="object"&&e!==null){let n={};for(let r of Object.keys(e)){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let s=e[r];t.has(r.toLowerCase())?n[r]=wt:n[r]=G(s,t);}return n}return e}var ee=new Set(["access_token","api_key","token","sig"]);function Y(e){if(!e)return e;let t;try{t=new URL(e);}catch{return e}let n=false;for(let r of [...t.searchParams.keys()])ee.has(r.toLowerCase())&&(t.searchParams.delete(r),n=true);return n?t.toString():e}function bt(e,t,n){if(n.length>0){for(let r of n)if(kt(e,r))return false}if(t.length>0){for(let r of t)if(kt(e,r))return true;return false}return true}function kt(e,t){try{return t instanceof RegExp?t.test(e):ne(t).test(e)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(t)}`),false}}function ne(e){let t="",n=0;for(;n<e.length;){let r=e[n];r==="*"&&e[n+1]==="*"?(t+=".*",n+=2,e[n]==="/"&&n++):r==="*"?(t+="[^/]*",n++):r==="?"?(t+="[^/]",n++):".+^${}()|[]\\".includes(r)?(t+="\\"+r,n++):(t+=r,n++);}return new RegExp(t)}var re=["get","post","put","patch","delete","head","fetch"],oe=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function se(e){let t=e.toLowerCase();return oe.some(n=>t.includes(n))}function ie(e){if(!e)return null;if(e.data!==void 0&&e.data!==null){let t=e.data;return typeof t=="string"?t:Buffer.isBuffer(t)?t.toString("base64"):JSON.stringify(t)}if(e.form!==void 0&&e.form!==null)return JSON.stringify(e.form);if(e.multipart!==void 0&&e.multipart!==null){let t=e.multipart,n={};for(let[r,s]of Object.entries(t))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?n[r]=String(s):s&&typeof s=="object"&&"name"in s?n[r]=`[file: ${s.name}]`:n[r]="[binary]";return JSON.stringify(n)}return null}function xt(e){return e?"\u2022\u2022\u2022\u2022":""}function ae(e){if(!e)return [];let t;for(let[r,s]of Object.entries(e))if(r.toLowerCase()==="cookie"){t=s;break}if(!t)return [];let n=[];for(let r of t.split(";")){let s=r.trim();if(!s)continue;let o=s.indexOf("="),c=o===-1?s:s.slice(0,o).trim(),l=o===-1?"":s.slice(o+1).trim();c&&n.push({name:c,value:xt(l)});}return n}function ue(e){let t=[];for(let n of e)for(let r of n.split(/,(?=\s*[A-Za-z0-9_.\-]+=)/)){let s=r.trim();if(!s)continue;let o=s.split(";"),c=o[0].indexOf("=");if(c===-1)continue;let l=o[0].slice(0,c).trim(),d=o[0].slice(c+1).trim(),f=o.slice(1).map(u=>u.trim()).filter(Boolean).join(" \xB7 ")||void 0;l&&t.push({name:l,value:xt(d),attributes:f});}return t}var F=class F{constructor(t,n,r){this.originals=new Map;this.apiCallWriter=null;this.statusMix={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0};this.callCounter=0;this.apiCallCount=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=t,this.assertionTracker=n??null,this.apiConfig=r??F.DEFAULT_API_CONFIG;try{this.apiCallWriter=new v("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(t){return t!=null&&typeof t=="object"?D.get(t)??null:this.primitiveCallIds.get(t)??null}intercept(){for(let n of re){let r=this.context[n].bind(this.context);this.originals.set(n,r),this.context[n]=this.createWrapper(n,r);}let t=this.context.dispose.bind(this.context);this.originals.set("dispose",t),this.context.dispose=async n=>(this.disposed=true,t(n));}tallyStatus(t){if(t===null||t<=0){this.statusMix.error++;return}if(t>=500){this.statusMix["5xx"]++;return}if(t>=400){this.statusMix["4xx"]++;return}if(t>=300){this.statusMix["3xx"]++;return}if(t>=200){this.statusMix["2xx"]++;return}this.statusMix.error++;}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0,apiStatusMix:{...this.statusMix}}}flushLegacyAnnotations(t){}dispose(){for(let[t,n]of this.originals)this.context[t]=n;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(t,n){let r=this,s=t.headers.bind(t);t.headers=function(){let p=s();return D.set(p,n),p};let o=t.headersArray.bind(t);t.headersArray=function(){let p=o();return D.set(p,n),p};let c=t.json.bind(t);t.json=async function(){let p=await c();return p!=null&&typeof p=="object"&&D.set(p,n),p};let l=t.status.bind(t);t.status=function(){let p=l();return r.primitiveCallIds.set(p,n),p};let d=t.statusText.bind(t);t.statusText=function(){let p=d();return r.primitiveCallIds.set(p,n),p};let f=t.ok.bind(t);t.ok=function(){let p=f();return r.primitiveCallIds.set(p,n),p};let u=t.text.bind(t);t.text=async function(){let p=await u();return r.primitiveCallIds.set(p,n),p};let a=t.body.bind(t);t.body=async function(){let p=await a();return D.set(p,n),p};}createWrapper(t,n){let r=this;return async function(o,c){if(!bt(o,r.apiConfig.apiIncludeUrls,r.apiConfig.apiExcludeUrls))return n(o,c);let l=`api-call-${r.callCounter++}`,d=new Date().toISOString(),f=t==="fetch"?(c?.method??"GET").toUpperCase():t.toUpperCase(),u=ie(c),a=perf_hooks.performance.now();r._lastCallId=l,r.assertionTracker&&r.assertionTracker.setCurrentCallId(l);let i;try{i=await n(o,c);}catch(p){let g=perf_hooks.performance.now();try{let m=r.apiConfig.captureRequestBody?L(u,r.apiConfig.redactBodyFields):null,w={id:l,timestamp:d,method:f,url:Y(o),requestHeaders:null,requestBody:m,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((g-a)*100)/100,isBinary:!1,error:p instanceof Error?p.message:String(p)};r.apiCallWriter&&(r.apiCallWriter.append(w),r.apiCallCount++,r.tallyStatus(null));}catch{}throw p}try{let p=perf_hooks.performance.now(),g=i.headers(),m=g["content-type"]??null,w=m?!se(m):!1,k=null;r.apiConfig.captureRequestHeaders&&c?.headers&&(k=c.headers);let x=null;r.apiConfig.captureResponseHeaders&&(x=g);let R=r.apiConfig.captureRequestBody?u:null,A=null;if(r.apiConfig.captureResponseBody)try{w?A=(await i.body()).toString("base64"):A=await i.text();}catch{}let P=[],N=[];try{if(r.apiConfig.captureRequestHeaders&&(P=ae(c?.headers)),r.apiConfig.captureResponseHeaders){let h=i.headersArray().filter(b=>b.name.toLowerCase()==="set-cookie").map(b=>b.value);N=ue(h);}}catch{}k=$(k,r.apiConfig.redactHeaders),x=$(x,r.apiConfig.redactHeaders),R=L(R,r.apiConfig.redactBodyFields),A=L(A,r.apiConfig.redactBodyFields);let y={id:l,timestamp:d,method:f,url:Y(i.url()),requestHeaders:k,requestBody:R,responseStatusCode:i.status(),responseStatusText:i.statusText(),responseHeaders:x,responseBody:A,requestCookies:P.length?P:null,responseCookies:N.length?N:null,responseTimeMs:Math.round((p-a)*100)/100,isBinary:w,error:null};r.apiCallWriter&&(r.apiCallWriter.append(y),r.apiCallCount++,r.tallyStatus(y.responseStatusCode));}catch{}try{i[J]=l,r.tagResponseMethods(i,l);}catch{}return i}}};F.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 I=F;var le=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function ce(e){let t=e.toLowerCase();return le.some(n=>t.includes(n))}var q=class e{constructor(t,n){this.page=t;this.records=[];this.listeners=[];this.navCounters=[];this.pendingRequests=new Map;this.networkWriter=null;this.consoleWriter=null;this.pendingBodyReads=[];this.requestIdCounter=0;this.networkRequestCount=0;this.consoleLogCount=0;this.includeNetworkStats=n?.includeNetworkStats??true,this.origGoto=t.goto.bind(t),this.origGoBack=t.goBack.bind(t),this.origGoForward=t.goForward.bind(t),this.origReload=t.reload.bind(t);try{this.includeNetworkStats&&(this.networkWriter=new v("network")),this.consoleWriter=new v("console");}catch{}this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async finalizeCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[,t]of this.pendingRequests)this.networkWriter&&(this.networkWriter.append({url:t.url,method:t.method,resourceType:t.resourceType,statusCode:0,responseTimeMs:Date.now()-t.startTimeMs,startedAt:t.startedAt,requestHeaders:t.headers,requestBody:t.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:t.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.networkRequestCount++);this.pendingRequests.clear(),this.networkWriter?.close(),this.consoleWriter?.close();}static mapConsoleType(t){switch(t){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getFileData(){this.assembleNetworkStats();let t=this.records.map(n=>({url:n.url,navigationType:n.navigationType,timestamp:n.timestamp,domContentLoadedAt:n.domContentLoadedAt,networkIdleAt:n.networkIdleAt,networkStats:n.networkStats}));return this.includeNetworkStats?await this.finalizeCapturedRequests():this.consoleWriter?.close(),{navigations:t,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(t){}dispose(){let t=e.asPatchable(this.page);t.goto=this.origGoto,t.goBack=this.origGoBack,t.goForward=this.origGoForward,t.reload=this.origReload;for(let{event:n,handler:r}of this.listeners)this.page.off(n,r);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}getRecords(){return this.assembleNetworkStats(),this.records}static asPatchable(t){return t}interceptMethods(){let t=this,n=this.page,r=e.asPatchable(n);r.goto=async function(s,o){return t.recordNavigation(s,"goto"),t.origGoto(s,o)},r.goBack=async function(s){let o=await t.origGoBack(s);return t.recordNavigation(n.url(),"back"),o},r.goForward=async function(s){let o=await t.origGoForward(s);return t.recordNavigation(n.url(),"forward"),o},r.reload=async function(s){return t.recordNavigation(n.url(),"refresh"),t.origReload(s)};}attachListeners(){let t=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",t),this.listeners.push({event:"domcontentloaded",handler:t});let n=s=>{try{let o=s;if(typeof o.parentFrame=="function"&&o.parentFrame()!==null)return;let c=o.url(),l=this.records[this.records.length-1];if(l&&Date.now()-new Date(l.timestamp).getTime()<50&&l.url===c)return;this.recordNavigation(c,"navigation");}catch{}};this.page.on("framenavigated",n),this.listeners.push({event:"framenavigated",handler:n});let r=s=>{try{let o=s,c=o.type(),l=o.text();if(c==="debug"&&l.startsWith("__testrelic_nav:")){try{let d=JSON.parse(l.slice(16));d.type&&d.url&&this.recordNavigation(d.url,d.type);}catch{}return}{let d=null;try{let u=o.location();u&&u.url&&(d=`${u.url}:${u.lineNumber}:${u.columnNumber}`);}catch{}let f=e.mapConsoleType(c);this.consoleWriter&&(this.consoleWriter.append({level:f,text:l,timestamp:new Date().toISOString(),location:d}),this.consoleLogCount++);}}catch{}};if(this.page.on("console",r),this.listeners.push({event:"console",handler:r}),this.includeNetworkStats){let s=l=>{let d=this.records.length-1,f=this.counterForNav(d);f&&f.totalRequests++;try{let u=l,a=String(this.requestIdCounter++),i=u.postData()??null,p={url:u.url(),method:u.method(),resourceType:this.mapResourceType(u.resourceType()),headers:u.headers(),postData:i,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now(),navIndex:d};this.pendingRequests.set(a,p),l.__testrelic_id=a;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let o=l=>{try{let d=l,f=d.request().__testrelic_id,u=f?this.pendingRequests.get(f):void 0,a=this.counterForNav(u?u.navIndex:this.records.length-1);if(a){let x=d.status();x>=400&&(a.failedRequests++,a.failedRequestUrls.push(x+" "+d.url()));let R=d.headers()["content-length"];R&&(a.totalBytes+=parseInt(R,10)||0);let A=d.request().resourceType(),P=this.mapResourceType(A);a.byType[P]++;}if(!f||!u)return;this.pendingRequests.delete(f);let i=Date.now()-u.startTimeMs,p=d.headers(),g=p["content-type"]??null,m=parseInt(p["content-length"]??"0",10)||0,w=g?!ce(g):!1,k=(async()=>{let x=null;if(!w)try{x=(await d.body()).toString("utf-8");}catch{}let R={url:u.url,method:u.method,resourceType:u.resourceType,statusCode:d.status(),responseTimeMs:i,startedAt:u.startedAt,requestHeaders:u.headers,requestBody:u.postData,responseBody:x,responseHeaders:p,contentType:g,responseSize:m,requestBodyTruncated:u.postDataTruncated,responseBodyTruncated:!1,isBinary:w,error:null};this.networkWriter&&(this.networkWriter.append(R),this.networkRequestCount++);})();this.pendingBodyReads.push(k);}catch{}};this.page.on("response",o),this.listeners.push({event:"response",handler:o});let c=l=>{let d=l.__testrelic_id,f=d?this.pendingRequests.get(d):void 0,u=this.counterForNav(f?f.navIndex:this.records.length-1);if(u){u.failedRequests++;try{let a=l;u.failedRequestUrls.push("ERR "+a.url());}catch{}}try{let a=l;if(!d||!f)return;this.pendingRequests.delete(d);let i={url:f.url,method:f.method,resourceType:f.resourceType,statusCode:0,responseTimeMs:Date.now()-f.startTimeMs,startedAt:f.startedAt,requestHeaders:f.headers,requestBody:f.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:f.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:a.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(i),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",c),this.listeners.push({event:"requestfailed",handler:c});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let t=history.pushState.bind(history),n=history.replaceState.bind(history);history.pushState=function(...r){t(...r),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...r){n(...r),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(t,n){this.records.push({url:t,navigationType:n,timestamp:new Date().toISOString()}),this.includeNetworkStats&&this.navCounters.push(this.createNetworkCounter());}createNetworkCounter(){return {totalRequests:0,failedRequests:0,failedRequestUrls:[],totalBytes:0,byType:{xhr:0,document:0,script:0,stylesheet:0,image:0,font:0,other:0}}}counterForNav(t){return t>=0?this.navCounters[t]:void 0}assembleNetworkStats(){if(this.includeNetworkStats)for(let t=0;t<this.records.length;t++){let n=this.navCounters[t];n&&(this.records[t].networkStats={totalRequests:n.totalRequests,failedRequests:n.failedRequests,failedRequestUrls:[...n.failedRequestUrls],totalBytes:n.totalBytes,byType:{...n.byType}});}}mapResourceType(t){switch(t){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};Buffer.from([137,80,78,71,13,10,26,10]);function Ct(e){let{styleProps:t,defaults:n,inherited:r,maxNodes:s,maxText:o,maskBoxes:c,viewportBox:l,fullPage:d}=e,f={};for(let y=0;y<r.length;y++)f[r[y]]=true;let u=window.scrollX||window.pageXOffset||0,a=window.scrollY||window.pageYOffset||0,i=[],p=0,g=[];for(let y=0;y<c.length;y++){let h=c[y];g.push([h[0]+u,h[1]+a,h[2],h[3]]);}function m(y,h,b,S){for(let C=0;C<g.length;C++){let T=g[C];if(y<T[0]+T[2]&&y+b>T[0]&&h<T[1]+T[3]&&h+S>T[1])return true}return false}function w(y){let h=y.parentElement;if(!h)return 0;let b=h.children,S=0;for(let C=0;C<b.length;C++){let T=b[C];if(T===y)break;T.tagName===y.tagName&&S++;}return S}function k(y){let h="",b=y.childNodes;for(let S=0;S<b.length;S++){let C=b[S];C.nodeType===3&&(h+=C.nodeValue??"");}return h=h.replace(/\s+/g," ").trim(),h.length>o?h.slice(0,o):h}function x(y,h){let b;for(let S=0;S<t.length;S++){let C=t[S],T=y.getPropertyValue(C);if(T){if(f[C]){if(h&&h.getPropertyValue(C)===T)continue}else if(n[C]===T)continue;b||(b={}),b[C]=T;}}return b}let R=[{el:document.body,parentPath:"",parentComputed:null}];for(;R.length>0;){let y=R.pop(),h=y.el,b=window.getComputedStyle(h);if(b.display==="none")continue;let S=h.tagName.toLowerCase(),C=h.id?"#"+h.id:y.parentPath?y.parentPath+">"+S+"["+w(h)+"]":S,T=h.children;for(let V=T.length-1;V>=0;V--)R.push({el:T[V],parentPath:C,parentComputed:b});if(b.visibility==="hidden")continue;let M=h.getBoundingClientRect();if(M.width<=0||M.height<=0)continue;if(i.length>=s){p++;continue}let et=Math.round(M.left+u),nt=Math.round(M.top+a),rt=Math.round(M.width),ot=Math.round(M.height),_={p:C,t:S,r:[et,nt,rt,ot]};h.id&&(_.i=h.id);let st=h.getAttribute("class");st&&(_.c=st.replace(/\s+/g," ").trim());let it=k(h);it&&(_.x=it);let at=x(b,y.parentComputed);at&&(_.s=at),m(et,nt,rt,ot)&&(_.m=1),i.push(_);}let A=Math.max(document.documentElement.scrollWidth,window.innerWidth),P=Math.max(document.documentElement.scrollHeight,window.innerHeight),N;return l?N=[Math.round(l[0]+u),Math.round(l[1]+a),Math.round(l[2]),Math.round(l[3])]:d?N=[0,0,A,P]:N=[Math.round(u),Math.round(a),window.innerWidth,window.innerHeight],{version:"1.0",url:location.href,viewport:{width:window.innerWidth,height:window.innerHeight},content:{width:A,height:P},captureBox:N,nodes:i,truncatedNodes:p}}var he=["display","position","color","background-color","background-image","border-top-width","border-right-width","border-bottom-width","border-left-width","border-color","border-style","border-radius","box-shadow","opacity","transform","margin-top","margin-right","margin-bottom","margin-left","padding-top","padding-right","padding-bottom","padding-left","font-family","font-size","font-weight","line-height","letter-spacing","text-align","text-decoration-line","text-transform","flex-direction","justify-content","align-items","gap","z-index","overflow"],ye={position:"static","background-color":"rgba(0, 0, 0, 0)","background-image":"none","border-top-width":"0px","border-right-width":"0px","border-bottom-width":"0px","border-left-width":"0px","border-style":"none","border-radius":"0px","box-shadow":"none",opacity:"1",transform:"none","margin-top":"0px","margin-right":"0px","margin-bottom":"0px","margin-left":"0px","padding-top":"0px","padding-right":"0px","padding-bottom":"0px","padding-left":"0px","text-decoration-line":"none","flex-direction":"row","justify-content":"normal","align-items":"normal",gap:"normal","z-index":"auto",overflow:"visible"},we=["color","font-family","font-size","font-weight","line-height","letter-spacing","text-align","text-transform"],ke=1024*1024,be=1500,xe=200;async function Ce(e){let t=[];for(let n of e)try{let r=await n.boundingBox();r&&t.push([r.x,r.y,r.width,r.height]);}catch{}return t}async function Rt(e){let t=e.config??{};try{let n=e.maskLocators?.length?await Ce(e.maskLocators):[],r=null;if(e.bounded){let o=await e.bounded.boundingBox();o&&(r=[o.x,o.y,o.width,o.height]);}let s={styleProps:he,defaults:ye,inherited:we,maxNodes:t.maxNodes??be,maxText:t.maxText??xe,maskBoxes:n,viewportBox:r,fullPage:e.fullPage===!0};return await e.target.evaluate(Ct,s)}catch{return null}}function Tt(e,t=ke){let n=JSON.stringify(e);if(Buffer.byteLength(n,"utf-8")<=t)return {json:n,truncatedBytes:false};let r=e.nodes.slice(),s=0;for(;r.length>0&&Buffer.byteLength(n,"utf-8")>t;){let o=Math.max(1,Math.floor(r.length*.1));r.splice(-o,o),s+=o,n=JSON.stringify({...e,nodes:r,truncatedNodes:e.truncatedNodes+s});}return {json:n,truncatedBytes:true}}function St(e){return e.replace(/\.[A-Za-z0-9]+$/,"")+".dom.json"}function At(e){try{if(!fs.existsSync(e))return null;let t=JSON.parse(fs.readFileSync(e,"utf-8"));return Re(t)?t:null}catch{return null}}function vt(e,t){try{return fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,t,"utf-8"),!0}catch{return false}}function Re(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.version=="string"&&Array.isArray(t.nodes)&&Array.isArray(t.captureBox)&&t.captureBox.length===4}var Te=new Set(["moved","resized"]);function W(e){return e.some(t=>!Te.has(t))}function K(e){let t=e.t;if(e.i&&(t+="#"+e.i),e.c){let n=e.c.split(" ").filter(Boolean).slice(0,3);n.length>0&&(t+="."+n.join("."));}return t}function Se(e,t){let n=[],r=Math.abs(e.r[0]-t.r[0]),s=Math.abs(e.r[1]-t.r[1]),o=Math.abs(e.r[2]-t.r[2]),c=Math.abs(e.r[3]-t.r[3]);return (r>1||s>1)&&n.push("moved"),(o>1||c>1)&&n.push("resized"),n}function Ae(e,t){let n=e.s??{},r=t.s??{},s=new Set([...Object.keys(n),...Object.keys(r)]),o=[];for(let c of s){let l=n[c],d=r[c];l!==d&&o.push({prop:c,from:l??"(initial)",to:d??"(initial)"});}return o.sort((c,l)=>c.prop.localeCompare(l.prop)),o}function Pt(e){return e.i?"i:"+e.t+"#"+e.i:e.c?"c:"+e.t+"."+e.c:null}function ve(e,t){let n=new Map;for(let a of e)n.set(a.p,a);let r=[],s=[],o=new Set;for(let a of t){let i=n.get(a.p);if(i&&i.t!==a.t){s.push(a);continue}i&&!o.has(i)?(o.add(i),r.push({before:i,after:a})):s.push(a);}let c=e.filter(a=>!o.has(a)),l=new Map;for(let a of c){let i=Pt(a);if(!i)continue;let p=l.get(i);p?p.push(a):l.set(i,[a]);}let d=[],f=new Set;for(let a of s){let i=Pt(a),g=(i?l.get(i):void 0)?.find(m=>!f.has(m));g?(f.add(g),r.push({before:g,after:a})):d.push(a);}let u=c.filter(a=>!f.has(a));return {pairs:r,removed:u,added:d}}function Pe(e,t){let n=[];return (e.i??"")!==(t.i??"")&&n.push({prop:"id",from:e.i??"(none)",to:t.i??"(none)"}),(e.c??"")!==(t.c??"")&&n.push({prop:"class",from:e.c??"(none)",to:t.c??"(none)"}),n}function Z(e,t){let n=(t[2]??0)*(t[3]??0);return n<=0?0:Math.min(1,e.r[2]*e.r[3]/n)}function Nt(e,t,n={}){let r=n.maxChanges??50,s=n.includeText!==false,o=n.includeStyles!==false,c=e.nodes.filter(g=>g.m!==1),l=t.nodes.filter(g=>g.m!==1),{pairs:d,removed:f,added:u}=ve(c,l),a=[];for(let{before:g,after:m}of d){let w=Se(g,m),k=o?Ae(g,m):[];k.length>0&&w.push("restyled");let x=Pe(g,m);x.length>0&&w.push("attrs");let R=s&&(g.x??"")!==(m.x??"");if(R&&w.push("text"),w.length===0)continue;let A=Z(m,t.captureBox);a.push({score:A,change:{path:m.p,label:K(m),kinds:w,rect:m.r,baselineRect:g.r,areaPct:A,...x.length>0?{attrs:x}:{},...k.length>0?{styles:k}:{},...R?{text:{from:g.x??"",to:m.x??""}}:{}}});}for(let g of u){let m=Z(g,t.captureBox);a.push({score:m,change:{path:g.p,label:K(g),kinds:["added"],rect:g.r,areaPct:m}});}for(let g of f){let m=Z(g,e.captureBox);a.push({score:m,change:{path:g.p,label:K(g),kinds:["removed"],baselineRect:g.r,areaPct:m}});}let i=a.filter(g=>W(g.change.kinds)).length;return a.sort((g,m)=>{if(i>0){let w=W(g.change.kinds)?1:0,k=W(m.change.kinds)?1:0;if(w!==k)return k-w}return m.score-g.score}),{changes:a.slice(0,r).map((g,m)=>({rank:m+1,...g.change,...i>0&&!W(g.change.kinds)?{consequence:true}:{}})),total:a.length,rootCauses:i}}var Ne="__testrelic_snapshot_path_probe__.png",Dt=Symbol.for("testrelic.snapshotPathWarned");function De(){let e=globalThis,t=e[Dt];return t||(t={warned:false},e[Dt]=t),t}function H(e){try{let t=e.snapshotPath(Ne,{kind:"screenshot"});return typeof t=="string"&&!t.includes("[object Object]")}catch{return false}}function j(e){let t=De();t.warned||(t.warned=true,process.stderr.write(`[testrelic] ${e} needs Playwright >= 1.51 for testInfo.snapshotPath(name, { kind }); this project's Playwright resolves that call the older way. Everything else in the reporter is unaffected \u2014 upgrade Playwright to enable it.
|
|
6
|
-
`));}var Mt="testrelic-visual-dom",Ie=new Set(["toHaveScreenshot","toMatchVisualBaseline"]);function _t(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.boundingBox=="function"&&typeof t.page=="function"}function Oe(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.evaluate=="function"&&typeof t.screenshot=="function"}function Le(e){let t=e[0];if(typeof t=="string")return t;if(Array.isArray(t))return t.join("/");if(typeof t=="object"&&t!==null){let n=t.name;if(typeof n=="string")return n}return null}function Fe(e){for(let t of e)if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t;return {}}function qe(e){let t=e.mask;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&typeof n.boundingBox=="function"):[]}function We(e){return /\.(png|jpg|jpeg)$/i.test(e)?e:`${e}.png`}var He=/^(.+)-(expected|actual|diff|previous)\.[A-Za-z0-9]+$/;function je(e,t,n){let r=e.attachments;for(let s=t;s<r.length;s++){let o=He.exec(r[s]?.name??"");if(o)return o[1]}return n}async function Ve(e){let t=Fe(e.args),n=_t(e.received)?e.received:null,r=n?n.page():e.received;return Rt({target:r,bounded:n,maskLocators:qe(t),fullPage:t.fullPage===true})}function Ue(e){let t=e.config?.updateSnapshots;return t==="all"||t==="changed"}async function ze(e,t){let n=Le(e.args);if(!n)return;if(!H(e.testInfo)){j("DOM comparison");return}let r=e.testInfo.snapshotPath(We(n),{kind:"screenshot"}),s=St(r),o=je(e.testInfo,e.attachedBefore,path.basename(r,path.extname(r))),c=Tt(t),d=Ue(e.testInfo)?null:At(s);if(!d){vt(s,c.json);return}let{changes:f,total:u,rootCauses:a}=Nt(d,t),i;try{i=e.testInfo.outputPath(`${o}.actual.dom.json`),fs.writeFileSync(i,c.json,"utf-8");}catch{i=void 0;}let p={stem:o,changes:f,total:u,rootCauses:a,truncated:c.truncatedBytes||t.truncatedNodes>0,captureBox:t.captureBox,...fs.existsSync(s)?{baselineDomPath:s}:{},...i?{actualDomPath:i}:{}};await e.testInfo.attach(Mt,{body:Buffer.from(JSON.stringify([p])),contentType:"application/json"});}function Bt(e,t){let n=function(c,...l){let d=e(c,...l);return !(_t(c)||Oe(c))||typeof d!="object"||d===null?d:new Proxy(d,{get(u,a,i){let p=Reflect.get(u,a,i);if(typeof a!="string"||!Ie.has(a)||typeof p!="function")return p;let g=p;return async function(...w){let k=t(),x=null,R=k?.attachments.length??0;if(k)try{x=await Ve({received:c,args:w,testInfo:k,attachedBefore:R});}catch{}try{return await g.apply(u,w)}finally{if(k&&x)try{await ze({received:c,args:w,testInfo:k,attachedBefore:R},x);}catch{}}}}})},r=e,s=n;for(let o of Object.keys(r))s[o]=r[o];return n}var Et="testrelic-visual";var Ke=[".png",".jpg",".jpeg"],Ze=/A snapshot doesn't exist at /;function Qe(e){return e.wrote?e.existedBefore?"updated":"new":e.pass?"passed":"failed"}function It(e){if(!e)return null;try{let t=fs.statSync(e);return {size:t.size,mtimeMs:t.mtimeMs}}catch{return null}}function tn(e,t){if(!H(e))return null;try{return e.snapshotPath(t,{kind:"screenshot"})}catch{return null}}function en(e){let t=e.toLowerCase();return Ke.some(n=>t.endsWith(n))?e:`${e}.png`}function nn(){try{return test.test.info()}catch{return null}}function rn(e,t,n){let r=o=>/^(.+)-(expected|actual|diff|previous)\.[A-Za-z0-9]+$/.exec(o)?.[1]??null,s=e.slice(t);if(n){for(let o of s)if(o.path===n&&/-expected\.[A-Za-z0-9]+$/.test(o.name))return r(o.name)}for(let o of s){let c=r(o.name);if(c)return c}return null}async function on(e,t){if(t===null)return j("Attaching the baseline of a passing comparison"),null;try{let n=path.extname(t)||".png",r=path.basename(t,n);return await e.attach(`${r}-expected${n}`,{path:t}),r}catch{return null}}async function sn(e,t){try{await e.attach(Et,{body:Buffer.from(JSON.stringify([t])),contentType:"application/json"});}catch{}}async function Q(e,t,n={}){let r={...n};delete r.tags;let s=en(t),o=nn(),c=o?.attachments.length??0,l=o?.errors?.length??0,d=o?tn(o,s):null,f=It(d),u=true,a="";try{await test.expect(e).toHaveScreenshot(s,r);}catch(i){u=false,a=i instanceof Error?i.message:String(i);}if(o){let i=It(d),p=d!==null?i!==null&&(f===null||f.size!==i.size||f.mtimeMs!==i.mtimeMs):(o.errors??[]).slice(l).some(w=>Ze.test(w.message??"")),g=Qe({pass:u,wrote:p,existedBefore:f!==null}),m=g==="passed"||g==="updated"?await on(o,d):rn(o.attachments,c,d);m&&await sn(o,{stem:m,name:t,status:g,...d?{committedPath:d}:{}});}return {pass:u,name:"toMatchVisualBaseline",message:()=>u?`Expected "${t}" to differ from its visual baseline, but it matched.`:a}}test.expect.extend({toMatchVisualBaseline:Q});function ln(){try{return test.test.info()}catch{return null}}Bt(O(test.expect),ln);var cn="__testrelic_api_config",dn="__testrelic_config_trackApiCalls";function tt(e){let t=e.annotations.find(r=>r.type===cn&&r.description!==void 0);if(t)try{return JSON.parse(t.description,pn)}catch{}let n=e.annotations.find(r=>r.type===dn&&r.description!==void 0);return n?{trackApiCalls:n.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 pn(e,t){if(typeof t=="object"&&t!==null&&t.__regexp===true&&typeof t.source=="string"){let{source:n,flags:r}=t;return new RegExp(n,r)}return t}var fn={page:async({page:e},t,n)=>{let r=new q(e);try{await r.init();}catch{}await t(e);try{let{navigations:s,networkRequestsFile:o,networkRequestsCount:c,consoleLogsFile:l,consoleLogsCount:d}=await r.getFileData(),f={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:o,networkRequestsCount:c,consoleLogsFile:l,consoleLogsCount:d,apiCallsFile:null,apiCallsCount:0};await n.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(f)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}r.dispose();},request:async({request:e},t,n)=>{let r=tt(n);if(!r.trackApiCalls){await t(e);return}let s=new B,o=new I(e,s,r);o.intercept(),E(s,o);try{await t(e);}finally{E(null,null);}try{let{apiCallsFile:c,apiCallsCount:l,apiStatusMix:d}=o.getFileData(),f=r.captureAssertions?s.getData():[],u={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:f,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:c,apiCallsCount:l,apiStatusMix:d};await n.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(u)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}o.dispose(),s.dispose();}};test.test.extend(fn);var Er=O(test.expect),Ir={request:async({request:e},t,n)=>{let r=tt(n);if(!r.trackApiCalls){await t(e);return}let s=new B,o=new I(e,s,r);o.intercept(),E(s,o);let c=null;try{c=new v("api-console");}catch{}let l=0,d=process.stdout.write,f=process.stderr.write;process.stdout.write=function(u,...a){try{let i=typeof u=="string"?u:Buffer.isBuffer(u)?u.toString("utf-8"):String(u);!i.startsWith("[testrelic]")&&!i.startsWith("\u2139 TestRelic")&&!i.startsWith("\u2713 TestRelic")&&!i.startsWith("\u26A0 TestRelic")&&c&&(c.append({level:"stdout",text:i.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),l++);}catch{}return d.apply(process.stdout,[u,...a])},process.stderr.write=function(u,...a){try{let i=typeof u=="string"?u:Buffer.isBuffer(u)?u.toString("utf-8"):String(u);!i.startsWith("[testrelic]")&&!i.startsWith("\u26A0 TestRelic")&&c&&(c.append({level:"stderr",text:i.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),l++);}catch{}return f.apply(process.stderr,[u,...a])};try{await t(e);}finally{process.stdout.write=d,process.stderr.write=f,E(null,null);}try{c?.close();let{apiCallsFile:u,apiCallsCount:a,apiStatusMix:i}=o.getFileData(),p=r.captureAssertions?s.getData():[],g={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:p,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:l>0?c?.getPath()??null:null,consoleLogsCount:l,apiCallsFile:u,apiCallsCount:a,apiStatusMix:i};await n.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(g)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}o.dispose(),s.dispose();}};exports.expect=Er;exports.testRelicApiFixture=Ir;//# sourceMappingURL=api-fixture.cjs.map
|
|
2
|
+
`;fs.writeSync(this.fd,n),this.count++;}getPath(){return this.filePath}getCount(){return this.count}close(){if(!this.closed){this.closed=true;try{fs.closeSync(this.fd);}catch{}}}cleanup(){try{fs.unlinkSync(this.filePath);}catch{}}};var Xt=new RegExp("[\x1B\x9B][[\\]()#;?]*(?:\\d{1,4}(?:;\\d{0,4})*)?[0-9A-PR-TZcf-nqry=><]","g");function ct(e){return !e||e.indexOf("\x1B")===-1&&e.indexOf("\x9B")===-1?e:e.replace(Xt,"")}var J=Symbol.for("__testrelic_call_id"),Kt="__testrelic_api_assertions",D=new WeakMap,_=class{constructor(){this.assertions=[];this.currentCallId=null;}recordAssertion(t){this.assertions.push(t);}getAssertions(){return this.assertions}setCurrentCallId(t){this.currentCallId=t;}getCurrentCallId(){return this.currentCallId}getData(){return [...this.assertions]}flushLegacyAnnotations(t){this.assertions.length!==0&&t.annotations.push({type:Kt,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}},dt=new Map;function Zt(e){let t=dt.get(e);if(t)return t;try{let n=e.startsWith("file://")?url.fileURLToPath(e):e,o=fs.readFileSync(n,"utf-8").split(`
|
|
3
|
+
`);return dt.set(e,o),o}catch{return null}}var pt=(()=>{let e=new Error().stack;if(!e)return null;for(let t of e.split(`
|
|
4
|
+
`)){let n=t.match(/at\s+(?:.*?\s+\()?(.+?):\d+:\d+\)?$/);if(!n||n[1].startsWith("node:"))continue;let r=Math.max(n[1].lastIndexOf("/"),n[1].lastIndexOf("\\"));return r>0?n[1].slice(0,r+1):null}return null})();function Qt(e){if(!e.startsWith("file:"))return e;try{return url.fileURLToPath(e)}catch{return e}}function te(){let t=new Error().stack;if(!t)return null;let n=t.split(`
|
|
5
|
+
`);return ft(n,true)??ft(n,false)}function ft(e,t){for(let n of e){if(t&&pt!==null&&n.includes(pt)||n.includes("node_modules")||n.includes("node:internal")||n.includes(" at new Error")||n.includes(" at captureAssertionLocation")||n.includes(" at findFrame")||n.includes(" at expectWrapper")||n.includes(" at wrappedMatcher"))continue;let r=n.match(/at\s+(?:.*?\s+\()?(.+?):(\d+):(\d+)\)?$/);if(r)return {file:Qt(r[1]),line:parseInt(r[2],10),column:parseInt(r[3],10)}}return null}function ee(e,t){if(!e)return "custom";let n=e.toLowerCase();return n.includes(".status()")&&!n.includes(".statustext()")?n.includes(".ok()")?"statusOk":"status":n.includes(".ok()")?"statusOk":n.includes(".headers()")||n.includes(".headersarray()")?"header":n.includes("tomatchobject")||n.includes("toequal")?"bodyMatch":n.includes("tocontain")||n.includes("tostringcontaining")?"bodyContains":n.includes(".json()")||n.includes(".text()")?"bodyField":"custom"}function ne(e,t,n){let r=function(l,...c){let f=e(),i=t();if(!f||!i)return n(l,...c);let u=null;if(l!=null&&typeof l=="object"){let h=l[J];typeof h=="string"&&(u=h);}if(!u&&l!==null&&l!==void 0&&typeof l=="object"&&(u=D.get(l)??null),u||(u=i.getCallIdForValue(l)),u||(u=f.getCurrentCallId()),!u)return n(l,...c);let a=te(),p;if(a){let h=Zt(a.file);h&&a.line>0&&a.line<=h.length&&(p=h[a.line-1].trim());}let g=n(l,...c);return u?yt(g,{tracker:f,callId:u,received:l,location:a??{file:"unknown",line:0},expression:p}):g},o=n,s=r;for(let d of Object.keys(o))s[d]=o[d];return r}var gt=Symbol.for("testrelic.activeAssertionContext");function z(){let e=globalThis,t=e[gt];return t||(t={tracker:null,apiTracker:null},e[gt]=t),t}function E(e,t){let n=z();n.tracker=e,n.apiTracker=t;}function O(e){return ne(()=>z().tracker,()=>z().apiTracker,e)}function yt(e,t){return new Proxy(e,{get(n,r,o){let s=Reflect.get(n,r,o);return typeof s!="function"||typeof r=="symbol"?s:r==="not"?yt(s,t):function(...l){let c=l[0],f="passed",i=t.received,u=null;try{let a=s.apply(this??n,l);return a&&typeof a=="object"&&typeof a.then=="function"?a.then(()=>{U(t,r,c,i,"passed");},p=>{throw U(t,r,c,i,"failed"),p}):a}catch(a){if(f="failed",u=a,a instanceof Error&&a.message){let p=a.message.match(/Received:\s*(.+)/);p&&(i=p[1]);}throw a}finally{(u!==null||f==="passed")&&U(t,r,c,i,f);}}}})}function U(e,t,n,r,o){let s=ee(e.expression,e.received),d={callId:e.callId,type:s,expected:ht(n),actual:ht(r),status:o,location:e.location,expression:e.expression};e.tracker.recordAssertion(d);}function ht(e){if(e==null)return e;if(typeof e=="string")return ct(e);if(typeof e=="number"||typeof e=="boolean")return e;try{return JSON.stringify(e),e}catch{return String(e)}}var wt="[REDACTED]";function $(e,t){if(e===null||t.length===0)return e;let n=new Set(t.map(o=>o.toLowerCase())),r={};for(let o of Object.keys(e))Object.prototype.hasOwnProperty.call(e,o)&&(r[o]=n.has(o.toLowerCase())?wt:e[o]);return r}function L(e,t){if(e===null||t.length===0)return e;let n;try{n=JSON.parse(e);}catch{return e}if(typeof n!="object"||n===null)return e;let r=new Set(t.map(s=>s.toLowerCase())),o=G(n,r);return JSON.stringify(o)}function G(e,t){if(Array.isArray(e))return e.map(n=>G(n,t));if(typeof e=="object"&&e!==null){let n={};for(let r of Object.keys(e)){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let o=e[r];t.has(r.toLowerCase())?n[r]=wt:n[r]=G(o,t);}return n}return e}var re=new Set(["access_token","api_key","token","sig"]);function X(e){if(!e)return e;let t;try{t=new URL(e);}catch{return e}let n=false;for(let r of [...t.searchParams.keys()])re.has(r.toLowerCase())&&(t.searchParams.delete(r),n=true);return n?t.toString():e}function bt(e,t,n){if(n.length>0){for(let r of n)if(kt(e,r))return false}if(t.length>0){for(let r of t)if(kt(e,r))return true;return false}return true}function kt(e,t){try{return t instanceof RegExp?t.test(e):oe(t).test(e)}catch{return process.stderr.write(`[testrelic] Invalid URL filter pattern: ${String(t)}
|
|
6
|
+
`),false}}function oe(e){let t="",n=0;for(;n<e.length;){let r=e[n];r==="*"&&e[n+1]==="*"?(t+=".*",n+=2,e[n]==="/"&&n++):r==="*"?(t+="[^/]*",n++):r==="?"?(t+="[^/]",n++):".+^${}()|[]\\".includes(r)?(t+="\\"+r,n++):(t+=r,n++);}return new RegExp(t)}var se=["get","post","put","patch","delete","head","fetch"],ie=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function ae(e){let t=e.toLowerCase();return ie.some(n=>t.includes(n))}function ue(e){if(!e)return null;if(e.data!==void 0&&e.data!==null){let t=e.data;return typeof t=="string"?t:Buffer.isBuffer(t)?t.toString("base64"):JSON.stringify(t)}if(e.form!==void 0&&e.form!==null)return JSON.stringify(e.form);if(e.multipart!==void 0&&e.multipart!==null){let t=e.multipart,n={};for(let[r,o]of Object.entries(t))typeof o=="string"||typeof o=="number"||typeof o=="boolean"?n[r]=String(o):o&&typeof o=="object"&&"name"in o?n[r]=`[file: ${o.name}]`:n[r]="[binary]";return JSON.stringify(n)}return null}function xt(e){return e?"\u2022\u2022\u2022\u2022":""}function le(e){if(!e)return [];let t;for(let[r,o]of Object.entries(e))if(r.toLowerCase()==="cookie"){t=o;break}if(!t)return [];let n=[];for(let r of t.split(";")){let o=r.trim();if(!o)continue;let s=o.indexOf("="),d=s===-1?o:o.slice(0,s).trim(),l=s===-1?"":o.slice(s+1).trim();d&&n.push({name:d,value:xt(l)});}return n}function ce(e){let t=[];for(let n of e)for(let r of n.split(/,(?=\s*[A-Za-z0-9_.-]+=)/)){let o=r.trim();if(!o)continue;let s=o.split(";"),d=s[0].indexOf("=");if(d===-1)continue;let l=s[0].slice(0,d).trim(),c=s[0].slice(d+1).trim(),f=s.slice(1).map(i=>i.trim()).filter(Boolean).join(" \xB7 ")||void 0;l&&t.push({name:l,value:xt(c),attributes:f});}return t}var q=class q{constructor(t,n,r){this.originals=new Map;this.apiCallWriter=null;this.statusMix={"2xx":0,"3xx":0,"4xx":0,"5xx":0,error:0};this.callCounter=0;this.apiCallCount=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=t,this.assertionTracker=n??null,this.apiConfig=r??q.DEFAULT_API_CONFIG;try{this.apiCallWriter=new v("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(t){return t!=null&&typeof t=="object"?D.get(t)??null:this.primitiveCallIds.get(t)??null}intercept(){for(let n of se){let r=this.context[n].bind(this.context);this.originals.set(n,r),this.context[n]=this.createWrapper(n,r);}let t=this.context.dispose.bind(this.context);this.originals.set("dispose",t),this.context.dispose=async n=>(this.disposed=true,t(n));}tallyStatus(t){if(t===null||t<=0){this.statusMix.error++;return}if(t>=500){this.statusMix["5xx"]++;return}if(t>=400){this.statusMix["4xx"]++;return}if(t>=300){this.statusMix["3xx"]++;return}if(t>=200){this.statusMix["2xx"]++;return}this.statusMix.error++;}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0,apiStatusMix:{...this.statusMix}}}flushLegacyAnnotations(t){}dispose(){for(let[t,n]of this.originals)this.context[t]=n;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(t,n){let{primitiveCallIds:r}=this,o=t.headers.bind(t);t.headers=function(){let p=o();return D.set(p,n),p};let s=t.headersArray.bind(t);t.headersArray=function(){let p=s();return D.set(p,n),p};let d=t.json.bind(t);t.json=async function(){let p=await d();return p!=null&&typeof p=="object"&&D.set(p,n),p};let l=t.status.bind(t);t.status=function(){let p=l();return r.set(p,n),p};let c=t.statusText.bind(t);t.statusText=function(){let p=c();return r.set(p,n),p};let f=t.ok.bind(t);t.ok=function(){let p=f();return r.set(p,n),p};let i=t.text.bind(t);t.text=async function(){let p=await i();return r.set(p,n),p};let u=t.body.bind(t);t.body=async function(){let p=await u();return D.set(p,n),p};}createWrapper(t,n){return async(r,o)=>{if(!bt(r,this.apiConfig.apiIncludeUrls,this.apiConfig.apiExcludeUrls))return n(r,o);let s=`api-call-${this.callCounter++}`,d=new Date().toISOString(),l=t==="fetch"?(o?.method??"GET").toUpperCase():t.toUpperCase(),c=ue(o),f=perf_hooks.performance.now();this._lastCallId=s,this.assertionTracker&&this.assertionTracker.setCurrentCallId(s);let i;try{i=await n(r,o);}catch(u){let a=perf_hooks.performance.now();try{let p=this.apiConfig.captureRequestBody?L(c,this.apiConfig.redactBodyFields):null,g={id:s,timestamp:d,method:l,url:X(r),requestHeaders:null,requestBody:p,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((a-f)*100)/100,isBinary:!1,error:u instanceof Error?u.message:String(u)};this.apiCallWriter&&(this.apiCallWriter.append(g),this.apiCallCount++,this.tallyStatus(null));}catch{}throw u}try{let u=perf_hooks.performance.now(),a=i.headers(),p=a["content-type"]??null,g=p?!ae(p):!1,h=null;this.apiConfig.captureRequestHeaders&&o?.headers&&(h=o.headers);let w=null;this.apiConfig.captureResponseHeaders&&(w=a);let k=this.apiConfig.captureRequestBody?c:null,b=null;if(this.apiConfig.captureResponseBody)try{g?b=(await i.body()).toString("base64"):b=await i.text();}catch{}let C=[],A=[];try{if(this.apiConfig.captureRequestHeaders&&(C=le(o?.headers)),this.apiConfig.captureResponseHeaders){let N=i.headersArray().filter(y=>y.name.toLowerCase()==="set-cookie").map(y=>y.value);A=ce(N);}}catch{}h=$(h,this.apiConfig.redactHeaders),w=$(w,this.apiConfig.redactHeaders),k=L(k,this.apiConfig.redactBodyFields),b=L(b,this.apiConfig.redactBodyFields);let P={id:s,timestamp:d,method:l,url:X(i.url()),requestHeaders:h,requestBody:k,responseStatusCode:i.status(),responseStatusText:i.statusText(),responseHeaders:w,responseBody:b,requestCookies:C.length?C:null,responseCookies:A.length?A:null,responseTimeMs:Math.round((u-f)*100)/100,isBinary:g,error:null};this.apiCallWriter&&(this.apiCallWriter.append(P),this.apiCallCount++,this.tallyStatus(P.responseStatusCode));}catch{}try{i[J]=s,this.tagResponseMethods(i,s);}catch{}return i}}};q.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 I=q;var de=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function pe(e){let t=e.toLowerCase();return de.some(n=>t.includes(n))}var F=class e{constructor(t,n){this.page=t;this.records=[];this.listeners=[];this.navCounters=[];this.pendingRequests=new Map;this.networkWriter=null;this.consoleWriter=null;this.pendingBodyReads=[];this.requestIdCounter=0;this.networkRequestCount=0;this.consoleLogCount=0;this.includeNetworkStats=n?.includeNetworkStats??true,this.origGoto=t.goto.bind(t),this.origGoBack=t.goBack.bind(t),this.origGoForward=t.goForward.bind(t),this.origReload=t.reload.bind(t);try{this.includeNetworkStats&&(this.networkWriter=new v("network")),this.consoleWriter=new v("console");}catch{}this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async finalizeCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[,t]of this.pendingRequests)this.networkWriter&&(this.networkWriter.append({url:t.url,method:t.method,resourceType:t.resourceType,statusCode:0,responseTimeMs:Date.now()-t.startTimeMs,startedAt:t.startedAt,requestHeaders:t.headers,requestBody:t.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:t.postDataTruncated,responseBodyTruncated:false,isBinary:false,error:"incomplete"}),this.networkRequestCount++);this.pendingRequests.clear(),this.networkWriter?.close(),this.consoleWriter?.close();}static mapConsoleType(t){switch(t){case "log":return "log";case "warning":return "warn";case "error":return "error";case "info":return "info";case "debug":return "debug";default:return "log"}}async getFileData(){this.assembleNetworkStats();let t=this.records.map(n=>({url:n.url,navigationType:n.navigationType,timestamp:n.timestamp,domContentLoadedAt:n.domContentLoadedAt,networkIdleAt:n.networkIdleAt,networkStats:n.networkStats}));return this.includeNetworkStats?await this.finalizeCapturedRequests():this.consoleWriter?.close(),{navigations:t,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(t){}dispose(){let t=e.asPatchable(this.page);t.goto=this.origGoto,t.goBack=this.origGoBack,t.goForward=this.origGoForward,t.reload=this.origReload;for(let{event:n,handler:r}of this.listeners)this.page.off(n,r);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}getRecords(){return this.assembleNetworkStats(),this.records}static asPatchable(t){return t}interceptMethods(){let t=this.page,n=e.asPatchable(t);n.goto=async(r,o)=>(this.recordNavigation(r,"goto"),this.origGoto(r,o)),n.goBack=async r=>{let o=await this.origGoBack(r);return this.recordNavigation(t.url(),"back"),o},n.goForward=async r=>{let o=await this.origGoForward(r);return this.recordNavigation(t.url(),"forward"),o},n.reload=async r=>(this.recordNavigation(t.url(),"refresh"),this.origReload(r));}attachListeners(){let t=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",t),this.listeners.push({event:"domcontentloaded",handler:t});let n=o=>{try{let s=o;if(typeof s.parentFrame=="function"&&s.parentFrame()!==null)return;let d=s.url(),l=this.records[this.records.length-1];if(l&&Date.now()-new Date(l.timestamp).getTime()<50&&l.url===d)return;this.recordNavigation(d,"navigation");}catch{}};this.page.on("framenavigated",n),this.listeners.push({event:"framenavigated",handler:n});let r=o=>{try{let s=o,d=s.type(),l=s.text();if(d==="debug"&&l.startsWith("__testrelic_nav:")){try{let c=JSON.parse(l.slice(16));c.type&&c.url&&this.recordNavigation(c.url,c.type);}catch{}return}{let c=null;try{let i=s.location();i&&i.url&&(c=`${i.url}:${i.lineNumber}:${i.columnNumber}`);}catch{}let f=e.mapConsoleType(d);this.consoleWriter&&(this.consoleWriter.append({level:f,text:l,timestamp:new Date().toISOString(),location:c}),this.consoleLogCount++);}}catch{}};if(this.page.on("console",r),this.listeners.push({event:"console",handler:r}),this.includeNetworkStats){let o=l=>{let c=this.records.length-1,f=this.counterForNav(c);f&&f.totalRequests++;try{let i=l,u=String(this.requestIdCounter++),a=i.postData()??null,p={url:i.url(),method:i.method(),resourceType:this.mapResourceType(i.resourceType()),headers:i.headers(),postData:a,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now(),navIndex:c};this.pendingRequests.set(u,p),l.__testrelic_id=u;}catch{}};this.page.on("request",o),this.listeners.push({event:"request",handler:o});let s=l=>{try{let c=l,f=c.request().__testrelic_id,i=f?this.pendingRequests.get(f):void 0,u=this.counterForNav(i?i.navIndex:this.records.length-1);if(u){let b=c.status();b>=400&&(u.failedRequests++,u.failedRequestUrls.push(b+" "+c.url()));let C=c.headers()["content-length"];C&&(u.totalBytes+=parseInt(C,10)||0);let A=c.request().resourceType(),P=this.mapResourceType(A);u.byType[P]++;}if(!f||!i)return;this.pendingRequests.delete(f);let a=Date.now()-i.startTimeMs,p=c.headers(),g=p["content-type"]??null,h=parseInt(p["content-length"]??"0",10)||0,w=g?!pe(g):!1,k=(async()=>{let b=null;if(!w)try{b=(await c.body()).toString("utf-8");}catch{}let C={url:i.url,method:i.method,resourceType:i.resourceType,statusCode:c.status(),responseTimeMs:a,startedAt:i.startedAt,requestHeaders:i.headers,requestBody:i.postData,responseBody:b,responseHeaders:p,contentType:g,responseSize:h,requestBodyTruncated:i.postDataTruncated,responseBodyTruncated:!1,isBinary:w,error:null};this.networkWriter&&(this.networkWriter.append(C),this.networkRequestCount++);})();this.pendingBodyReads.push(k);}catch{}};this.page.on("response",s),this.listeners.push({event:"response",handler:s});let d=l=>{let c=l.__testrelic_id,f=c?this.pendingRequests.get(c):void 0,i=this.counterForNav(f?f.navIndex:this.records.length-1);if(i){i.failedRequests++;try{let u=l;i.failedRequestUrls.push("ERR "+u.url());}catch{}}try{let u=l;if(!c||!f)return;this.pendingRequests.delete(c);let a={url:f.url,method:f.method,resourceType:f.resourceType,statusCode:0,responseTimeMs:Date.now()-f.startTimeMs,startedAt:f.startedAt,requestHeaders:f.headers,requestBody:f.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:f.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:u.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(a),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",d),this.listeners.push({event:"requestfailed",handler:d});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let t=history.pushState.bind(history),n=history.replaceState.bind(history);history.pushState=function(...r){t(...r),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...r){n(...r),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(t,n){this.records.push({url:t,navigationType:n,timestamp:new Date().toISOString()}),this.includeNetworkStats&&this.navCounters.push(this.createNetworkCounter());}createNetworkCounter(){return {totalRequests:0,failedRequests:0,failedRequestUrls:[],totalBytes:0,byType:{xhr:0,document:0,script:0,stylesheet:0,image:0,font:0,other:0}}}counterForNav(t){return t>=0?this.navCounters[t]:void 0}assembleNetworkStats(){if(this.includeNetworkStats)for(let t=0;t<this.records.length;t++){let n=this.navCounters[t];n&&(this.records[t].networkStats={totalRequests:n.totalRequests,failedRequests:n.failedRequests,failedRequestUrls:[...n.failedRequestUrls],totalBytes:n.totalBytes,byType:{...n.byType}});}}mapResourceType(t){switch(t){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};Buffer.from([137,80,78,71,13,10,26,10]);function Ct(e){let{styleProps:t,defaults:n,inherited:r,maxNodes:o,maxText:s,maskBoxes:d,viewportBox:l,fullPage:c}=e,f={};for(let y=0;y<r.length;y++)f[r[y]]=true;let i=window.scrollX||window.pageXOffset||0,u=window.scrollY||window.pageYOffset||0,a=[],p=0,g=[];for(let y=0;y<d.length;y++){let m=d[y];g.push([m[0]+i,m[1]+u,m[2],m[3]]);}function h(y,m,R,T){for(let x=0;x<g.length;x++){let S=g[x];if(y<S[0]+S[2]&&y+R>S[0]&&m<S[1]+S[3]&&m+T>S[1])return true}return false}function w(y){let m=y.parentElement;if(!m)return 0;let R=m.children,T=0;for(let x=0;x<R.length;x++){let S=R[x];if(S===y)break;S.tagName===y.tagName&&T++;}return T}function k(y){let m="",R=y.childNodes;for(let T=0;T<R.length;T++){let x=R[T];x.nodeType===3&&(m+=x.nodeValue??"");}return m=m.replace(/\s+/g," ").trim(),m.length>s?m.slice(0,s):m}function b(y,m){let R;for(let T=0;T<t.length;T++){let x=t[T],S=y.getPropertyValue(x);if(S){if(f[x]){if(m&&m.getPropertyValue(x)===S)continue}else if(n[x]===S)continue;R||(R={}),R[x]=S;}}return R}let C=[{el:document.body,parentPath:"",parentComputed:null}];for(;C.length>0;){let y=C.pop(),m=y.el,R=window.getComputedStyle(m);if(R.display==="none")continue;let T=m.tagName.toLowerCase(),x=m.id?"#"+m.id:y.parentPath?y.parentPath+">"+T+"["+w(m)+"]":T,S=m.children;for(let V=S.length-1;V>=0;V--)C.push({el:S[V],parentPath:x,parentComputed:R});if(R.visibility==="hidden")continue;let M=m.getBoundingClientRect();if(M.width<=0||M.height<=0)continue;if(a.length>=o){p++;continue}let et=Math.round(M.left+i),nt=Math.round(M.top+u),rt=Math.round(M.width),ot=Math.round(M.height),B={p:x,t:T,r:[et,nt,rt,ot]};m.id&&(B.i=m.id);let st=m.getAttribute("class");st&&(B.c=st.replace(/\s+/g," ").trim());let it=k(m);it&&(B.x=it);let at=b(R,y.parentComputed);at&&(B.s=at),h(et,nt,rt,ot)&&(B.m=1),a.push(B);}let A=Math.max(document.documentElement.scrollWidth,window.innerWidth),P=Math.max(document.documentElement.scrollHeight,window.innerHeight),N;return l?N=[Math.round(l[0]+i),Math.round(l[1]+u),Math.round(l[2]),Math.round(l[3])]:c?N=[0,0,A,P]:N=[Math.round(i),Math.round(u),window.innerWidth,window.innerHeight],{version:"1.0",url:location.href,viewport:{width:window.innerWidth,height:window.innerHeight},content:{width:A,height:P},captureBox:N,nodes:a,truncatedNodes:p}}var we=["display","position","color","background-color","background-image","border-top-width","border-right-width","border-bottom-width","border-left-width","border-color","border-style","border-radius","box-shadow","opacity","transform","margin-top","margin-right","margin-bottom","margin-left","padding-top","padding-right","padding-bottom","padding-left","font-family","font-size","font-weight","line-height","letter-spacing","text-align","text-decoration-line","text-transform","flex-direction","justify-content","align-items","gap","z-index","overflow"],ke={position:"static","background-color":"rgba(0, 0, 0, 0)","background-image":"none","border-top-width":"0px","border-right-width":"0px","border-bottom-width":"0px","border-left-width":"0px","border-style":"none","border-radius":"0px","box-shadow":"none",opacity:"1",transform:"none","margin-top":"0px","margin-right":"0px","margin-bottom":"0px","margin-left":"0px","padding-top":"0px","padding-right":"0px","padding-bottom":"0px","padding-left":"0px","text-decoration-line":"none","flex-direction":"row","justify-content":"normal","align-items":"normal",gap:"normal","z-index":"auto",overflow:"visible"},be=["color","font-family","font-size","font-weight","line-height","letter-spacing","text-align","text-transform"],xe=1024*1024,Ce=1500,Re=200;async function Se(e){let t=[];for(let n of e)try{let r=await n.boundingBox();r&&t.push([r.x,r.y,r.width,r.height]);}catch{}return t}async function Rt(e){let t=e.config??{};try{let n=e.maskLocators?.length?await Se(e.maskLocators):[],r=null;if(e.bounded){let s=await e.bounded.boundingBox();s&&(r=[s.x,s.y,s.width,s.height]);}let o={styleProps:we,defaults:ke,inherited:be,maxNodes:t.maxNodes??Ce,maxText:t.maxText??Re,maskBoxes:n,viewportBox:r,fullPage:e.fullPage===!0};return await e.target.evaluate(Ct,o)}catch{return null}}function St(e,t=xe){let n=JSON.stringify(e);if(Buffer.byteLength(n,"utf-8")<=t)return {json:n,truncatedBytes:false};let r=e.nodes.slice(),o=0;for(;r.length>0&&Buffer.byteLength(n,"utf-8")>t;){let s=Math.max(1,Math.floor(r.length*.1));r.splice(-s,s),o+=s,n=JSON.stringify({...e,nodes:r,truncatedNodes:e.truncatedNodes+o});}return {json:n,truncatedBytes:true}}function Tt(e){return e.replace(/\.[A-Za-z0-9]+$/,"")+".dom.json"}function At(e){try{if(!fs.existsSync(e))return null;let t=JSON.parse(fs.readFileSync(e,"utf-8"));return Te(t)?t:null}catch{return null}}function vt(e,t){try{return fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,t,"utf-8"),!0}catch{return false}}function Te(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.version=="string"&&Array.isArray(t.nodes)&&Array.isArray(t.captureBox)&&t.captureBox.length===4}var Ae=new Set(["moved","resized"]);function W(e){return e.some(t=>!Ae.has(t))}function K(e){let t=e.t;if(e.i&&(t+="#"+e.i),e.c){let n=e.c.split(" ").filter(Boolean).slice(0,3);n.length>0&&(t+="."+n.join("."));}return t}function ve(e,t){let n=[],r=Math.abs(e.r[0]-t.r[0]),o=Math.abs(e.r[1]-t.r[1]),s=Math.abs(e.r[2]-t.r[2]),d=Math.abs(e.r[3]-t.r[3]);return (r>1||o>1)&&n.push("moved"),(s>1||d>1)&&n.push("resized"),n}function Pe(e,t){let n=e.s??{},r=t.s??{},o=new Set([...Object.keys(n),...Object.keys(r)]),s=[];for(let d of o){let l=n[d],c=r[d];l!==c&&s.push({prop:d,from:l??"(initial)",to:c??"(initial)"});}return s.sort((d,l)=>d.prop.localeCompare(l.prop)),s}function Pt(e){return e.i?"i:"+e.t+"#"+e.i:e.c?"c:"+e.t+"."+e.c:null}function Ne(e,t){let n=new Map;for(let u of e)n.set(u.p,u);let r=[],o=[],s=new Set;for(let u of t){let a=n.get(u.p);if(a&&a.t!==u.t){o.push(u);continue}a&&!s.has(a)?(s.add(a),r.push({before:a,after:u})):o.push(u);}let d=e.filter(u=>!s.has(u)),l=new Map;for(let u of d){let a=Pt(u);if(!a)continue;let p=l.get(a);p?p.push(u):l.set(a,[u]);}let c=[],f=new Set;for(let u of o){let a=Pt(u),g=(a?l.get(a):void 0)?.find(h=>!f.has(h));g?(f.add(g),r.push({before:g,after:u})):c.push(u);}let i=d.filter(u=>!f.has(u));return {pairs:r,removed:i,added:c}}function De(e,t){let n=[];return (e.i??"")!==(t.i??"")&&n.push({prop:"id",from:e.i??"(none)",to:t.i??"(none)"}),(e.c??"")!==(t.c??"")&&n.push({prop:"class",from:e.c??"(none)",to:t.c??"(none)"}),n}function Z(e,t){let n=(t[2]??0)*(t[3]??0);return n<=0?0:Math.min(1,e.r[2]*e.r[3]/n)}function Nt(e,t,n={}){let r=n.maxChanges??50,o=n.includeText!==false,s=n.includeStyles!==false,d=e.nodes.filter(g=>g.m!==1),l=t.nodes.filter(g=>g.m!==1),{pairs:c,removed:f,added:i}=Ne(d,l),u=[];for(let{before:g,after:h}of c){let w=ve(g,h),k=s?Pe(g,h):[];k.length>0&&w.push("restyled");let b=De(g,h);b.length>0&&w.push("attrs");let C=o&&(g.x??"")!==(h.x??"");if(C&&w.push("text"),w.length===0)continue;let A=Z(h,t.captureBox);u.push({score:A,change:{path:h.p,label:K(h),kinds:w,rect:h.r,baselineRect:g.r,areaPct:A,...b.length>0?{attrs:b}:{},...k.length>0?{styles:k}:{},...C?{text:{from:g.x??"",to:h.x??""}}:{}}});}for(let g of i){let h=Z(g,t.captureBox);u.push({score:h,change:{path:g.p,label:K(g),kinds:["added"],rect:g.r,areaPct:h}});}for(let g of f){let h=Z(g,e.captureBox);u.push({score:h,change:{path:g.p,label:K(g),kinds:["removed"],baselineRect:g.r,areaPct:h}});}let a=u.filter(g=>W(g.change.kinds)).length;return u.sort((g,h)=>{if(a>0){let w=W(g.change.kinds)?1:0,k=W(h.change.kinds)?1:0;if(w!==k)return k-w}return h.score-g.score}),{changes:u.slice(0,r).map((g,h)=>({rank:h+1,...g.change,...a>0&&!W(g.change.kinds)?{consequence:true}:{}})),total:u.length,rootCauses:a}}var Me="__testrelic_snapshot_path_probe__.png",Dt=Symbol.for("testrelic.snapshotPathWarned");function Be(){let e=globalThis,t=e[Dt];return t||(t={warned:false},e[Dt]=t),t}function H(e){try{let t=e.snapshotPath(Me,{kind:"screenshot"});return typeof t=="string"&&!t.includes("[object Object]")}catch{return false}}function j(e){let t=Be();t.warned||(t.warned=true,process.stderr.write(`[testrelic] ${e} needs Playwright >= 1.51 for testInfo.snapshotPath(name, { kind }); this project's Playwright resolves that call the older way. Everything else in the reporter is unaffected \u2014 upgrade Playwright to enable it.
|
|
7
|
+
`));}var Mt="testrelic-visual-dom",Le=new Set(["toHaveScreenshot","toMatchVisualBaseline"]);function Bt(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.boundingBox=="function"&&typeof t.page=="function"}function qe(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.evaluate=="function"&&typeof t.screenshot=="function"}function Fe(e){let t=e[0];if(typeof t=="string")return t;if(Array.isArray(t))return t.join("/");if(typeof t=="object"&&t!==null){let n=t.name;if(typeof n=="string")return n}return null}function We(e){for(let t of e)if(typeof t=="object"&&t!==null&&!Array.isArray(t))return t;return {}}function He(e){let t=e.mask;return Array.isArray(t)?t.filter(n=>typeof n=="object"&&n!==null&&typeof n.boundingBox=="function"):[]}function je(e){return /\.(png|jpg|jpeg)$/i.test(e)?e:`${e}.png`}var Ve=/^(.+)-(expected|actual|diff|previous)\.[A-Za-z0-9]+$/;function Ue(e,t,n){let r=e.attachments;for(let o=t;o<r.length;o++){let s=Ve.exec(r[o]?.name??"");if(s)return s[1]}return n}async function ze(e){let t=We(e.args),n=Bt(e.received)?e.received:null,r=n?n.page():e.received;return Rt({target:r,bounded:n,maskLocators:He(t),fullPage:t.fullPage===true})}function Je(e){let t=e.config?.updateSnapshots;return t==="all"||t==="changed"}async function Ge(e,t){let n=Fe(e.args);if(!n)return;if(!H(e.testInfo)){j("DOM comparison");return}let r=e.testInfo.snapshotPath(je(n),{kind:"screenshot"}),o=Tt(r),s=Ue(e.testInfo,e.attachedBefore,path.basename(r,path.extname(r))),d=St(t),c=Je(e.testInfo)?null:At(o);if(!c){vt(o,d.json);return}let{changes:f,total:i,rootCauses:u}=Nt(c,t),a;try{a=e.testInfo.outputPath(`${s}.actual.dom.json`),fs.writeFileSync(a,d.json,"utf-8");}catch{a=void 0;}let p={stem:s,changes:f,total:i,rootCauses:u,truncated:d.truncatedBytes||t.truncatedNodes>0,captureBox:t.captureBox,...fs.existsSync(o)?{baselineDomPath:o}:{},...a?{actualDomPath:a}:{}};await e.testInfo.attach(Mt,{body:Buffer.from(JSON.stringify([p])),contentType:"application/json"});}function _t(e,t){let n=function(d,...l){let c=e(d,...l);return !(Bt(d)||qe(d))||typeof c!="object"||c===null?c:new Proxy(c,{get(i,u,a){let p=Reflect.get(i,u,a);if(typeof u!="string"||!Le.has(u)||typeof p!="function")return p;let g=p;return async function(...w){let k=t(),b=null,C=k?.attachments.length??0;if(k)try{b=await ze({received:d,args:w,testInfo:k,attachedBefore:C});}catch{}try{return await g.apply(i,w)}finally{if(k&&b)try{await Ge({received:d,args:w,testInfo:k,attachedBefore:C},b);}catch{}}}}})},r=e,o=n;for(let s of Object.keys(r))o[s]=r[s];return n}var Et="testrelic-visual";var Ke=[".png",".jpg",".jpeg"],Ze=/A snapshot doesn't exist at /;function Qe(e){return e.wrote?e.existedBefore?"updated":"new":e.pass?"passed":"failed"}function tn(e){return e.status==="failed"&&!e.hadBaseline}function It(e){if(!e)return null;try{let t=fs.statSync(e);return {size:t.size,mtimeMs:t.mtimeMs}}catch{return null}}function en(e,t){if(!H(e))return null;try{return e.snapshotPath(t,{kind:"screenshot"})}catch{return null}}function nn(e){let t=e.toLowerCase();return Ke.some(n=>t.endsWith(n))?e:`${e}.png`}function rn(){try{return test.test.info()}catch{return null}}function on(e,t,n){let r=s=>/^(.+)-(expected|actual|diff|previous)\.[A-Za-z0-9]+$/.exec(s)?.[1]??null,o=e.slice(t);if(n){for(let s of o)if(s.path===n&&/-expected\.[A-Za-z0-9]+$/.test(s.name))return r(s.name)}for(let s of o){let d=r(s.name);if(d)return d}return null}function sn(e,t){return t?path.basename(t,path.extname(t)||".png"):e.replace(/\.[A-Za-z0-9]+$/,"")}async function an(e,t){if(t===null)return j("Attaching the baseline of a passing comparison"),null;try{let n=path.extname(t)||".png",r=path.basename(t,n);return await e.attach(`${r}-expected${n}`,{path:t}),r}catch{return null}}async function un(e,t){try{await e.attach(Et,{body:Buffer.from(JSON.stringify([t])),contentType:"application/json"});}catch{}}async function Q(e,t,n={}){let r={...n};delete r.tags;let o=nn(t),s=rn(),d=s?.attachments.length??0,l=s?.errors?.length??0,c=s?en(s,o):null,f=It(c),i=true,u="";try{await test.expect(e).toHaveScreenshot(o,r);}catch(a){i=false,u=a instanceof Error?a.message:String(a);}if(s){let a=It(c),p=c!==null?a!==null&&(f===null||f.size!==a.size||f.mtimeMs!==a.mtimeMs):(s.errors??[]).slice(l).some(k=>Ze.test(k.message??"")),g=Qe({pass:i,wrote:p,existedBefore:f!==null}),w=(g==="passed"||g==="updated"?await an(s,c):on(s.attachments,d,c))??(tn({status:g,hadBaseline:f!==null})?sn(o,c):null);w&&await un(s,{stem:w,name:t,status:g,...c?{committedPath:c}:{}});}return {pass:i,name:"toMatchVisualBaseline",message:()=>i?`Expected "${t}" to differ from its visual baseline, but it matched.`:u}}test.expect.extend({toMatchVisualBaseline:Q});function dn(){try{return test.test.info()}catch{return null}}_t(O(test.expect),dn);var pn="__testrelic_api_config",fn="__testrelic_config_trackApiCalls";function tt(e){let t=e.annotations.find(r=>r.type===pn&&r.description!==void 0);if(t)try{return JSON.parse(t.description,gn)}catch{}let n=e.annotations.find(r=>r.type===fn&&r.description!==void 0);return n?{trackApiCalls:n.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 gn(e,t){if(typeof t=="object"&&t!==null&&t.__regexp===true&&typeof t.source=="string"){let{source:n,flags:r}=t;return new RegExp(n,r)}return t}var hn={page:async({page:e},t,n)=>{let r=new F(e);try{await r.init();}catch{}await t(e);try{let{navigations:o,networkRequestsFile:s,networkRequestsCount:d,consoleLogsFile:l,consoleLogsCount:c}=await r.getFileData(),f={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:o,apiAssertions:[],networkRequestsFile:s,networkRequestsCount:d,consoleLogsFile:l,consoleLogsCount:c,apiCallsFile:null,apiCallsCount:0};await n.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(f)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}r.dispose();},request:async({request:e},t,n)=>{let r=tt(n);if(!r.trackApiCalls){await t(e);return}let o=new _,s=new I(e,o,r);s.intercept(),E(o,s);try{await t(e);}finally{E(null,null);}try{let{apiCallsFile:d,apiCallsCount:l,apiStatusMix:c}=s.getFileData(),f=r.captureAssertions?o.getData():[],i={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:f,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:d,apiCallsCount:l,apiStatusMix:c};await n.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(i)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}s.dispose(),o.dispose();}};test.test.extend(hn);var Or=O(test.expect),Lr={request:async({request:e},t,n)=>{let r=tt(n);if(!r.trackApiCalls){await t(e);return}let o=new _,s=new I(e,o,r);s.intercept(),E(o,s);let d=null;try{d=new v("api-console");}catch{}let l=0,c=process.stdout.write,f=process.stderr.write;process.stdout.write=function(i,...u){try{let a=typeof i=="string"?i:Buffer.isBuffer(i)?i.toString("utf-8"):String(i);!a.startsWith("[testrelic]")&&!a.startsWith("\u2139 TestRelic")&&!a.startsWith("\u2713 TestRelic")&&!a.startsWith("\u26A0 TestRelic")&&d&&(d.append({level:"stdout",text:a.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),l++);}catch{}return c.apply(process.stdout,[i,...u])},process.stderr.write=function(i,...u){try{let a=typeof i=="string"?i:Buffer.isBuffer(i)?i.toString("utf-8"):String(i);!a.startsWith("[testrelic]")&&!a.startsWith("\u26A0 TestRelic")&&d&&(d.append({level:"stderr",text:a.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),l++);}catch{}return f.apply(process.stderr,[i,...u])};try{await t(e);}finally{process.stdout.write=c,process.stderr.write=f,E(null,null);}try{d?.close();let{apiCallsFile:i,apiCallsCount:u,apiStatusMix:a}=s.getFileData(),p=r.captureAssertions?o.getData():[],g={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:p,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:l>0?d?.getPath()??null:null,consoleLogsCount:l,apiCallsFile:i,apiCallsCount:u,apiStatusMix:a};await n.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(g)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}s.dispose(),o.dispose();}};exports.expect=Or;exports.testRelicApiFixture=Lr;//# sourceMappingURL=api-fixture.cjs.map
|
|
7
8
|
//# sourceMappingURL=api-fixture.cjs.map
|