@testrelic/playwright-analytics 2.16.1-next.138 → 2.16.1-next.142
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 +5 -5
- package/dist/api-fixture.cjs.map +1 -1
- package/dist/api-fixture.js +5 -5
- package/dist/api-fixture.js.map +1 -1
- package/dist/cli.cjs +4 -0
- package/dist/fixture.cjs +6 -6
- package/dist/fixture.cjs.map +1 -1
- package/dist/fixture.js +6 -6
- package/dist/fixture.js.map +1 -1
- package/dist/index.cjs +86 -86
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +86 -86
- package/dist/index.js.map +1 -1
- package/dist/merge.cjs +1 -1
- package/dist/merge.cjs.map +1 -1
- package/dist/merge.js +1 -1
- package/dist/merge.js.map +1 -1
- package/dist/reporter-entry.cjs +50 -50
- package/dist/reporter-entry.cjs.map +1 -1
- package/dist/reporter-entry.d.cts +7 -0
- package/dist/reporter-entry.d.ts +7 -0
- package/dist/reporter-entry.js +50 -50
- package/dist/reporter-entry.js.map +1 -1
- package/dist/visual.cjs +2 -2
- package/dist/visual.cjs.map +1 -1
- package/dist/visual.d.cts +1 -0
- package/dist/visual.d.ts +1 -0
- package/dist/visual.js +2 -2
- package/dist/visual.js.map +1 -1
- package/package.json +2 -2
package/dist/cli.cjs
CHANGED
|
@@ -713,6 +713,10 @@ async function mergeReports(files, options) {
|
|
|
713
713
|
}
|
|
714
714
|
}
|
|
715
715
|
}
|
|
716
|
+
const srcArtifacts = (0, import_node_path.join)((0, import_node_path.dirname)(sr.dir), "artifacts");
|
|
717
|
+
if ((0, import_node_fs.existsSync)(srcArtifacts)) {
|
|
718
|
+
(0, import_node_fs.cpSync)(srcArtifacts, (0, import_node_path.join)(outputDir, "artifacts"), { recursive: true });
|
|
719
|
+
}
|
|
716
720
|
for (const entry of sr.index) {
|
|
717
721
|
if (!seenTestIds.has(entry.id)) {
|
|
718
722
|
seenTestIds.add(entry.id);
|
package/dist/fixture.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
'use strict';var test=require('@playwright/test'),fs=require('fs'),path=require('path'),os=require('os'),crypto=require('crypto');require('readline');var perf_hooks=require('perf_hooks'),url=require('url'),core=require('@testrelic/core');var
|
|
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
|
|
4
|
-
`)){let n=
|
|
5
|
-
`);return he(n,true)??he(n,false)}function he(t,e){for(let n of t){if(e&&ge!==null&&n.includes(ge)||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:Ze(r[1]),line:parseInt(r[2],10),column:parseInt(r[3],10)}}return null}function et(t,e){if(!t)return "custom";let n=t.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 tt(t,e,n){let r=function(a,...c){let f=t(),d=e();if(!f||!d)return n(a,...c);let u=null;if(a!=null&&typeof a=="object"){let h=a[U];typeof h=="string"&&(u=h);}if(!u&&a!==null&&a!==void 0&&typeof a=="object"&&(u=D.get(a)??null),u||(u=d.getCallIdForValue(a)),u||(u=f.getCurrentCallId()),!u)return n(a,...c);let i=Qe(),p;if(i){let h=Ke(i.file);h&&i.line>0&&i.line<=h.length&&(p=h[i.line-1].trim());}let g=n(a,...c);return u?be(g,{tracker:f,callId:u,received:a,location:i??{file:"unknown",line:0},expression:p}):g},o=n,s=r;for(let l of Object.keys(o))s[l]=o[l];return r}var me=Symbol.for("testrelic.activeAssertionContext");function V(){let t=globalThis,e=t[me];return e||(e={tracker:null,apiTracker:null},t[me]=e),e}function z(t,e){let n=V();n.tracker=t,n.apiTracker=e;}function ke(t){return tt(()=>V().tracker,()=>V().apiTracker,t)}function be(t,e){return new Proxy(t,{get(n,r,o){let s=Reflect.get(n,r,o);return typeof s!="function"||typeof r=="symbol"?s:r==="not"?be(s,e):function(...a){let c=a[0],f="passed",d=e.received,u=null;try{let i=s.apply(this??n,a);return i&&typeof i=="object"&&typeof i.then=="function"?i.then(()=>{W(e,r,c,d,"passed");},p=>{throw W(e,r,c,d,"failed"),p}):i}catch(i){if(f="failed",u=i,i instanceof Error&&i.message){let p=i.message.match(/Received:\s*(.+)/);p&&(d=p[1]);}throw i}finally{(u!==null||f==="passed")&&W(e,r,c,d,f);}}}})}function W(t,e,n,r,o){let s=et(t.expression,t.received),l={callId:t.callId,type:s,expected:ye(n),actual:ye(r),status:o,location:t.location,expression:t.expression};t.tracker.recordAssertion(l);}function ye(t){if(t==null)return t;if(typeof t=="string")return pe(t);if(typeof t=="number"||typeof t=="boolean")return t;try{return JSON.stringify(t),t}catch{return String(t)}}var xe="[REDACTED]";function J(t,e){if(t===null||e.length===0)return t;let n=new Set(e.map(o=>o.toLowerCase())),r={};for(let o of Object.keys(t))Object.prototype.hasOwnProperty.call(t,o)&&(r[o]=n.has(o.toLowerCase())?xe:t[o]);return r}function E(t,e){if(t===null||e.length===0)return t;let n;try{n=JSON.parse(t);}catch{return t}if(typeof n!="object"||n===null)return t;let r=new Set(e.map(s=>s.toLowerCase())),o=G(n,r);return JSON.stringify(o)}function G(t,e){if(Array.isArray(t))return t.map(n=>G(n,e));if(typeof t=="object"&&t!==null){let n={};for(let r of Object.keys(t)){if(!Object.prototype.hasOwnProperty.call(t,r))continue;let o=t[r];e.has(r.toLowerCase())?n[r]=xe:n[r]=G(o,e);}return n}return t}var nt=new Set(["access_token","api_key","token","sig"]);function $(t){if(!t)return t;let e;try{e=new URL(t);}catch{return t}let n=false;for(let r of [...e.searchParams.keys()])nt.has(r.toLowerCase())&&(e.searchParams.delete(r),n=true);return n?e.toString():t}function Re(t,e,n){if(n.length>0){for(let r of n)if(Ce(t,r))return false}if(e.length>0){for(let r of e)if(Ce(t,r))return true;return false}return true}function Ce(t,e){try{return e instanceof RegExp?e.test(t):rt(e).test(t)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(e)}`),false}}function rt(t){let e="",n=0;for(;n<t.length;){let r=t[n];r==="*"&&t[n+1]==="*"?(e+=".*",n+=2,t[n]==="/"&&n++):r==="*"?(e+="[^/]*",n++):r==="?"?(e+="[^/]",n++):".+^${}()|[]\\".includes(r)?(e+="\\"+r,n++):(e+=r,n++);}return new RegExp(e)}var ot=["get","post","put","patch","delete","head","fetch"],st=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function it(t){let e=t.toLowerCase();return st.some(n=>e.includes(n))}function at(t){if(!t)return null;if(t.data!==void 0&&t.data!==null){let e=t.data;return typeof e=="string"?e:Buffer.isBuffer(e)?e.toString("base64"):JSON.stringify(e)}if(t.form!==void 0&&t.form!==null)return JSON.stringify(t.form);if(t.multipart!==void 0&&t.multipart!==null){let e=t.multipart,n={};for(let[r,o]of Object.entries(e))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 Se(t){return t?"\u2022\u2022\u2022\u2022":""}function ut(t){if(!t)return [];let e;for(let[r,o]of Object.entries(t))if(r.toLowerCase()==="cookie"){e=o;break}if(!e)return [];let n=[];for(let r of e.split(";")){let o=r.trim();if(!o)continue;let s=o.indexOf("="),l=s===-1?o:o.slice(0,s).trim(),a=s===-1?"":o.slice(s+1).trim();l&&n.push({name:l,value:Se(a)});}return n}function ct(t){let e=[];for(let n of t)for(let r of n.split(/,(?=\s*[A-Za-z0-9_.\-]+=)/)){let o=r.trim();if(!o)continue;let s=o.split(";"),l=s[0].indexOf("=");if(l===-1)continue;let a=s[0].slice(0,l).trim(),c=s[0].slice(l+1).trim(),f=s.slice(1).map(d=>d.trim()).filter(Boolean).join(" \xB7 ")||void 0;a&&e.push({name:a,value:Se(c),attributes:f});}return e}var L=class L{constructor(e,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=e,this.assertionTracker=n??null,this.apiConfig=r??L.DEFAULT_API_CONFIG;try{this.apiCallWriter=new N("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(e){return e!=null&&typeof e=="object"?D.get(e)??null:this.primitiveCallIds.get(e)??null}intercept(){for(let n of ot){let r=this.context[n].bind(this.context);this.originals.set(n,r),this.context[n]=this.createWrapper(n,r);}let e=this.context.dispose.bind(this.context);this.originals.set("dispose",e),this.context.dispose=async n=>(this.disposed=true,e(n));}tallyStatus(e){if(e===null||e<=0){this.statusMix.error++;return}if(e>=500){this.statusMix["5xx"]++;return}if(e>=400){this.statusMix["4xx"]++;return}if(e>=300){this.statusMix["3xx"]++;return}if(e>=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(e){}dispose(){for(let[e,n]of this.originals)this.context[e]=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(e,n){let r=this,o=e.headers.bind(e);e.headers=function(){let p=o();return D.set(p,n),p};let s=e.headersArray.bind(e);e.headersArray=function(){let p=s();return D.set(p,n),p};let l=e.json.bind(e);e.json=async function(){let p=await l();return p!=null&&typeof p=="object"&&D.set(p,n),p};let a=e.status.bind(e);e.status=function(){let p=a();return r.primitiveCallIds.set(p,n),p};let c=e.statusText.bind(e);e.statusText=function(){let p=c();return r.primitiveCallIds.set(p,n),p};let f=e.ok.bind(e);e.ok=function(){let p=f();return r.primitiveCallIds.set(p,n),p};let d=e.text.bind(e);e.text=async function(){let p=await d();return r.primitiveCallIds.set(p,n),p};let u=e.body.bind(e);e.body=async function(){let p=await u();return D.set(p,n),p};}createWrapper(e,n){let r=this;return async function(s,l){if(!Re(s,r.apiConfig.apiIncludeUrls,r.apiConfig.apiExcludeUrls))return n(s,l);let a=`api-call-${r.callCounter++}`,c=new Date().toISOString(),f=e==="fetch"?(l?.method??"GET").toUpperCase():e.toUpperCase(),d=at(l),u=perf_hooks.performance.now();r._lastCallId=a,r.assertionTracker&&r.assertionTracker.setCurrentCallId(a);let i;try{i=await n(s,l);}catch(p){let g=perf_hooks.performance.now();try{let h=r.apiConfig.captureRequestBody?E(d,r.apiConfig.redactBodyFields):null,w={id:a,timestamp:c,method:f,url:$(s),requestHeaders:null,requestBody:h,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((g-u)*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(),h=g["content-type"]??null,w=h?!it(h):!1,k=null;r.apiConfig.captureRequestHeaders&&l?.headers&&(k=l.headers);let x=null;r.apiConfig.captureResponseHeaders&&(x=g);let R=r.apiConfig.captureRequestBody?d:null,A=null;if(r.apiConfig.captureResponseBody)try{w?A=(await i.body()).toString("base64"):A=await i.text();}catch{}let v=[],P=[];try{if(r.apiConfig.captureRequestHeaders&&(v=ut(l?.headers)),r.apiConfig.captureResponseHeaders){let m=i.headersArray().filter(b=>b.name.toLowerCase()==="set-cookie").map(b=>b.value);P=ct(m);}}catch{}k=J(k,r.apiConfig.redactHeaders),x=J(x,r.apiConfig.redactHeaders),R=E(R,r.apiConfig.redactBodyFields),A=E(A,r.apiConfig.redactBodyFields);let y={id:a,timestamp:c,method:f,url:$(i.url()),requestHeaders:k,requestBody:R,responseStatusCode:i.status(),responseStatusText:i.statusText(),responseHeaders:x,responseBody:A,requestCookies:v.length?v:null,responseCookies:P.length?P:null,responseTimeMs:Math.round((p-u)*100)/100,isBinary:w,error:null};r.apiCallWriter&&(r.apiCallWriter.append(y),r.apiCallCount++,r.tallyStatus(y.responseStatusCode));}catch{}try{i[U]=a,r.tagResponseMethods(i,a);}catch{}return i}}};L.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 O=L;Buffer.from([137,80,78,71,13,10,26,10]);var lt=/Expected an image (\d+)px by (\d+)px, received (\d+)px by (\d+)px/;function Y(t){return t?lt.test(t):false}function Te(t){let{styleProps:e,defaults:n,inherited:r,maxNodes:o,maxText:s,maskBoxes:l,viewportBox:a,fullPage:c}=t,f={};for(let y=0;y<r.length;y++)f[r[y]]=true;let d=window.scrollX||window.pageXOffset||0,u=window.scrollY||window.pageYOffset||0,i=[],p=0,g=[];for(let y=0;y<l.length;y++){let m=l[y];g.push([m[0]+d,m[1]+u,m[2],m[3]]);}function h(y,m,b,T){for(let C=0;C<g.length;C++){let S=g[C];if(y<S[0]+S[2]&&y+b>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 b=m.children,T=0;for(let C=0;C<b.length;C++){let S=b[C];if(S===y)break;S.tagName===y.tagName&&T++;}return T}function k(y){let m="",b=y.childNodes;for(let T=0;T<b.length;T++){let C=b[T];C.nodeType===3&&(m+=C.nodeValue??"");}return m=m.replace(/\s+/g," ").trim(),m.length>s?m.slice(0,s):m}function x(y,m){let b;for(let T=0;T<e.length;T++){let C=e[T],S=y.getPropertyValue(C);if(S){if(f[C]){if(m&&m.getPropertyValue(C)===S)continue}else if(n[C]===S)continue;b||(b={}),b[C]=S;}}return b}let R=[{el:document.body,parentPath:"",parentComputed:null}];for(;R.length>0;){let y=R.pop(),m=y.el,b=window.getComputedStyle(m);if(b.display==="none")continue;let T=m.tagName.toLowerCase(),C=m.id?"#"+m.id:y.parentPath?y.parentPath+">"+T+"["+w(m)+"]":T,S=m.children;for(let H=S.length-1;H>=0;H--)R.push({el:S[H],parentPath:C,parentComputed:b});if(b.visibility==="hidden")continue;let M=m.getBoundingClientRect();if(M.width<=0||M.height<=0)continue;if(i.length>=o){p++;continue}let re=Math.round(M.left+d),oe=Math.round(M.top+u),se=Math.round(M.width),ie=Math.round(M.height),_={p:C,t:T,r:[re,oe,se,ie]};m.id&&(_.i=m.id);let ae=m.getAttribute("class");ae&&(_.c=ae.replace(/\s+/g," ").trim());let ue=k(m);ue&&(_.x=ue);let ce=x(b,y.parentComputed);ce&&(_.s=ce),h(re,oe,se,ie)&&(_.m=1),i.push(_);}let A=Math.max(document.documentElement.scrollWidth,window.innerWidth),v=Math.max(document.documentElement.scrollHeight,window.innerHeight),P;return a?P=[Math.round(a[0]+d),Math.round(a[1]+u),Math.round(a[2]),Math.round(a[3])]:c?P=[0,0,A,v]:P=[Math.round(d),Math.round(u),window.innerWidth,window.innerHeight],{version:"1.0",url:location.href,viewport:{width:window.innerWidth,height:window.innerHeight},content:{width:A,height:v},captureBox:P,nodes:i,truncatedNodes:p}}var mt=["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"],yt={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"},wt=["color","font-family","font-size","font-weight","line-height","letter-spacing","text-align","text-transform"],kt=1024*1024,bt=1500,xt=200;async function Ct(t){let e=[];for(let n of t)try{let r=await n.boundingBox();r&&e.push([r.x,r.y,r.width,r.height]);}catch{}return e}async function Ae(t){let e=t.config??{};try{let n=t.maskLocators?.length?await Ct(t.maskLocators):[],r=null;if(t.bounded){let s=await t.bounded.boundingBox();s&&(r=[s.x,s.y,s.width,s.height]);}let o={styleProps:mt,defaults:yt,inherited:wt,maxNodes:e.maxNodes??bt,maxText:e.maxText??xt,maskBoxes:n,viewportBox:r,fullPage:t.fullPage===!0};return await t.target.evaluate(Te,o)}catch{return null}}function ve(t,e=kt){let n=JSON.stringify(t);if(Buffer.byteLength(n,"utf-8")<=e)return {json:n,truncatedBytes:false};let r=t.nodes.slice(),o=0;for(;r.length>0&&Buffer.byteLength(n,"utf-8")>e;){let s=Math.max(1,Math.floor(r.length*.1));r.splice(-s,s),o+=s,n=JSON.stringify({...t,nodes:r,truncatedNodes:t.truncatedNodes+o});}return {json:n,truncatedBytes:true}}function Pe(t){return t.replace(/\.[A-Za-z0-9]+$/,"")+".dom.json"}function Ne(t){try{if(!fs.existsSync(t))return null;let e=JSON.parse(fs.readFileSync(t,"utf-8"));return Rt(e)?e:null}catch{return null}}function De(t,e){try{return fs.mkdirSync(path.dirname(t),{recursive:!0}),fs.writeFileSync(t,e,"utf-8"),!0}catch{return false}}function Rt(t){if(typeof t!="object"||t===null)return false;let e=t;return typeof e.version=="string"&&Array.isArray(e.nodes)&&Array.isArray(e.captureBox)&&e.captureBox.length===4}var St=new Set(["moved","resized"]);function q(t){return t.some(e=>!St.has(e))}function K(t){let e=t.t;if(t.i&&(e+="#"+t.i),t.c){let n=t.c.split(" ").filter(Boolean).slice(0,3);n.length>0&&(e+="."+n.join("."));}return e}function Tt(t,e){let n=[],r=Math.abs(t.r[0]-e.r[0]),o=Math.abs(t.r[1]-e.r[1]),s=Math.abs(t.r[2]-e.r[2]),l=Math.abs(t.r[3]-e.r[3]);return (r>1||o>1)&&n.push("moved"),(s>1||l>1)&&n.push("resized"),n}function At(t,e){let n=t.s??{},r=e.s??{},o=new Set([...Object.keys(n),...Object.keys(r)]),s=[];for(let l of o){let a=n[l],c=r[l];a!==c&&s.push({prop:l,from:a??"(initial)",to:c??"(initial)"});}return s.sort((l,a)=>l.prop.localeCompare(a.prop)),s}function Me(t){return t.i?"i:"+t.t+"#"+t.i:t.c?"c:"+t.t+"."+t.c:null}function vt(t,e){let n=new Map;for(let u of t)n.set(u.p,u);let r=[],o=[],s=new Set;for(let u of e){let i=n.get(u.p);if(i&&i.t!==u.t){o.push(u);continue}i&&!s.has(i)?(s.add(i),r.push({before:i,after:u})):o.push(u);}let l=t.filter(u=>!s.has(u)),a=new Map;for(let u of l){let i=Me(u);if(!i)continue;let p=a.get(i);p?p.push(u):a.set(i,[u]);}let c=[],f=new Set;for(let u of o){let i=Me(u),g=(i?a.get(i):void 0)?.find(h=>!f.has(h));g?(f.add(g),r.push({before:g,after:u})):c.push(u);}let d=l.filter(u=>!f.has(u));return {pairs:r,removed:d,added:c}}function Pt(t,e){let n=[];return (t.i??"")!==(e.i??"")&&n.push({prop:"id",from:t.i??"(none)",to:e.i??"(none)"}),(t.c??"")!==(e.c??"")&&n.push({prop:"class",from:t.c??"(none)",to:e.c??"(none)"}),n}function Z(t,e){let n=(e[2]??0)*(e[3]??0);return n<=0?0:Math.min(1,t.r[2]*t.r[3]/n)}function _e(t,e,n={}){let r=n.maxChanges??50,o=n.includeText!==false,s=n.includeStyles!==false,l=t.nodes.filter(g=>g.m!==1),a=e.nodes.filter(g=>g.m!==1),{pairs:c,removed:f,added:d}=vt(l,a),u=[];for(let{before:g,after:h}of c){let w=Tt(g,h),k=s?At(g,h):[];k.length>0&&w.push("restyled");let x=Pt(g,h);x.length>0&&w.push("attrs");let R=o&&(g.x??"")!==(h.x??"");if(R&&w.push("text"),w.length===0)continue;let A=Z(h,e.captureBox);u.push({score:A,change:{path:h.p,label:K(h),kinds:w,rect:h.r,baselineRect:g.r,areaPct:A,...x.length>0?{attrs:x}:{},...k.length>0?{styles:k}:{},...R?{text:{from:g.x??"",to:h.x??""}}:{}}});}for(let g of d){let h=Z(g,e.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,t.captureBox);u.push({score:h,change:{path:g.p,label:K(g),kinds:["removed"],baselineRect:g.r,areaPct:h}});}let i=u.filter(g=>q(g.change.kinds)).length;return u.sort((g,h)=>{if(i>0){let w=q(g.change.kinds)?1:0,k=q(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,...i>0&&!q(g.change.kinds)?{consequence:true}:{}})),total:u.length,rootCauses:i}}var Nt="__testrelic_snapshot_path_probe__.png",Be=Symbol.for("testrelic.snapshotPathWarned");function Dt(){let t=globalThis,e=t[Be];return e||(e={warned:false},t[Be]=e),e}function F(t){try{let e=t.snapshotPath(Nt,{kind:"screenshot"});return typeof e=="string"&&!e.includes("[object Object]")}catch{return false}}function j(t){let e=Dt();e.warned||(e.warned=true,process.stderr.write(`[testrelic] ${t} 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
|
|
1
|
+
'use strict';var test=require('@playwright/test'),fs=require('fs'),path=require('path'),os=require('os'),crypto=require('crypto');require('readline');var perf_hooks=require('perf_hooks'),url=require('url'),core=require('@testrelic/core');var ct=path.join(os.tmpdir(),"testrelic-data"),N=class{constructor(t){this.count=0;this.closed=false;fs.mkdirSync(ct,{recursive:true}),this.filePath=path.join(ct,`${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 Gt=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function Jt(e){let t=e.toLowerCase();return Gt.some(n=>t.includes(n))}var B=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 N("network")),this.consoleWriter=new N("console");}catch{}this.interceptMethods(),this.attachListeners();}async init(){await this.injectSPADetection();}async finalizeCapturedRequests(){await Promise.allSettled(this.pendingBodyReads),this.pendingBodyReads=[];for(let[,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 l=o.url(),a=this.records[this.records.length-1];if(a&&Date.now()-new Date(a.timestamp).getTime()<50&&a.url===l)return;this.recordNavigation(l,"navigation");}catch{}};this.page.on("framenavigated",n),this.listeners.push({event:"framenavigated",handler:n});let r=s=>{try{let o=s,l=o.type(),a=o.text();if(l==="debug"&&a.startsWith("__testrelic_nav:")){try{let c=JSON.parse(a.slice(16));c.type&&c.url&&this.recordNavigation(c.url,c.type);}catch{}return}{let c=null;try{let p=o.location();p&&p.url&&(c=`${p.url}:${p.lineNumber}:${p.columnNumber}`);}catch{}let f=e.mapConsoleType(l);this.consoleWriter&&(this.consoleWriter.append({level:f,text:a,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 s=a=>{let c=this.records.length-1,f=this.counterForNav(c);f&&f.totalRequests++;try{let p=a,u=String(this.requestIdCounter++),i=p.postData()??null,d={url:p.url(),method:p.method(),resourceType:this.mapResourceType(p.resourceType()),headers:p.headers(),postData:i,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now(),navIndex:c};this.pendingRequests.set(u,d),a.__testrelic_id=u;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let o=a=>{try{let c=a,f=c.request().__testrelic_id,p=f?this.pendingRequests.get(f):void 0,u=this.counterForNav(p?p.navIndex:this.records.length-1);if(u){let x=c.status();x>=400&&(u.failedRequests++,u.failedRequestUrls.push(x+" "+c.url()));let R=c.headers()["content-length"];R&&(u.totalBytes+=parseInt(R,10)||0);let A=c.request().resourceType(),v=this.mapResourceType(A);u.byType[v]++;}if(!f||!p)return;this.pendingRequests.delete(f);let i=Date.now()-p.startTimeMs,d=c.headers(),g=d["content-type"]??null,h=parseInt(d["content-length"]??"0",10)||0,w=g?!Jt(g):!1,k=(async()=>{let x=null;if(!w)try{x=(await c.body()).toString("utf-8");}catch{}let R={url:p.url,method:p.method,resourceType:p.resourceType,statusCode:c.status(),responseTimeMs:i,startedAt:p.startedAt,requestHeaders:p.headers,requestBody:p.postData,responseBody:x,responseHeaders:d,contentType:g,responseSize:h,requestBodyTruncated:p.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 l=a=>{let c=a.__testrelic_id,f=c?this.pendingRequests.get(c):void 0,p=this.counterForNav(f?f.navIndex:this.records.length-1);if(p){p.failedRequests++;try{let u=a;p.failedRequestUrls.push("ERR "+u.url());}catch{}}try{let u=a;if(!c||!f)return;this.pendingRequests.delete(c);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:u.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(i),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",l),this.listeners.push({event:"requestfailed",handler:l});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let t=history.pushState.bind(history),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"}}};var $t=new RegExp("[\x1B\x9B][[\\]()#;?]*(?:\\d{1,4}(?:;\\d{0,4})*)?[0-9A-PR-TZcf-nqry=><]","g");function dt(e){return !e||e.indexOf("\x1B")===-1&&e.indexOf("\x9B")===-1?e:e.replace($t,"")}var U=Symbol.for("__testrelic_call_id"),Yt="__testrelic_api_assertions",D=new WeakMap,I=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:Yt,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}},pt=new Map;function Kt(e){let t=pt.get(e);if(t)return t;try{let n=e.startsWith("file://")?url.fileURLToPath(e):e,s=fs.readFileSync(n,"utf-8").split(`
|
|
3
|
+
`);return pt.set(e,s),s}catch{return null}}var ft=(()=>{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 Zt(e){if(!e.startsWith("file:"))return e;try{return url.fileURLToPath(e)}catch{return e}}function Qt(){let t=new Error().stack;if(!t)return null;let n=t.split(`
|
|
5
|
+
`);return gt(n,true)??gt(n,false)}function gt(e,t){for(let n of e){if(t&&ft!==null&&n.includes(ft)||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:Zt(r[1]),line:parseInt(r[2],10),column:parseInt(r[3],10)}}return null}function te(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 ee(e,t,n){let r=function(a,...c){let f=e(),p=t();if(!f||!p)return n(a,...c);let u=null;if(a!=null&&typeof a=="object"){let h=a[U];typeof h=="string"&&(u=h);}if(!u&&a!==null&&a!==void 0&&typeof a=="object"&&(u=D.get(a)??null),u||(u=p.getCallIdForValue(a)),u||(u=f.getCurrentCallId()),!u)return n(a,...c);let i=Qt(),d;if(i){let h=Kt(i.file);h&&i.line>0&&i.line<=h.length&&(d=h[i.line-1].trim());}let g=n(a,...c);return u?kt(g,{tracker:f,callId:u,received:a,location:i??{file:"unknown",line:0},expression:d}):g},s=n,o=r;for(let l of Object.keys(s))o[l]=s[l];return r}var ht=Symbol.for("testrelic.activeAssertionContext");function V(){let e=globalThis,t=e[ht];return t||(t={tracker:null,apiTracker:null},e[ht]=t),t}function z(e,t){let n=V();n.tracker=e,n.apiTracker=t;}function wt(e){return ee(()=>V().tracker,()=>V().apiTracker,e)}function kt(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"?kt(o,t):function(...a){let c=a[0],f="passed",p=t.received,u=null;try{let i=o.apply(this??n,a);return i&&typeof i=="object"&&typeof i.then=="function"?i.then(()=>{W(t,r,c,p,"passed");},d=>{throw W(t,r,c,p,"failed"),d}):i}catch(i){if(f="failed",u=i,i instanceof Error&&i.message){let d=i.message.match(/Received:\s*(.+)/);d&&(p=d[1]);}throw i}finally{(u!==null||f==="passed")&&W(t,r,c,p,f);}}}})}function W(e,t,n,r,s){let o=te(e.expression,e.received),l={callId:e.callId,type:o,expected:mt(n),actual:mt(r),status:s,location:e.location,expression:e.expression};e.tracker.recordAssertion(l);}function mt(e){if(e==null)return e;if(typeof e=="string")return dt(e);if(typeof e=="number"||typeof e=="boolean")return e;try{return JSON.stringify(e),e}catch{return String(e)}}var bt="[REDACTED]";function J(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())?bt:e[s]);return r}function E(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]=bt:n[r]=G(s,t);}return n}return e}var ne=new Set(["access_token","api_key","token","sig"]);function $(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()])ne.has(r.toLowerCase())&&(t.searchParams.delete(r),n=true);return n?t.toString():e}function Ct(e,t,n){if(n.length>0){for(let r of n)if(xt(e,r))return false}if(t.length>0){for(let r of t)if(xt(e,r))return true;return false}return true}function xt(e,t){try{return t instanceof RegExp?t.test(e):re(t).test(e)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(t)}`),false}}function re(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 oe=["get","post","put","patch","delete","head","fetch"],se=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function ie(e){let t=e.toLowerCase();return se.some(n=>t.includes(n))}function ae(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 Rt(e){return e?"\u2022\u2022\u2022\u2022":""}function ue(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("="),l=o===-1?s:s.slice(0,o).trim(),a=o===-1?"":s.slice(o+1).trim();l&&n.push({name:l,value:Rt(a)});}return n}function ce(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(";"),l=o[0].indexOf("=");if(l===-1)continue;let a=o[0].slice(0,l).trim(),c=o[0].slice(l+1).trim(),f=o.slice(1).map(p=>p.trim()).filter(Boolean).join(" \xB7 ")||void 0;a&&t.push({name:a,value:Rt(c),attributes:f});}return t}var L=class L{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??L.DEFAULT_API_CONFIG;try{this.apiCallWriter=new N("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 oe){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 d=s();return D.set(d,n),d};let o=t.headersArray.bind(t);t.headersArray=function(){let d=o();return D.set(d,n),d};let l=t.json.bind(t);t.json=async function(){let d=await l();return d!=null&&typeof d=="object"&&D.set(d,n),d};let a=t.status.bind(t);t.status=function(){let d=a();return r.primitiveCallIds.set(d,n),d};let c=t.statusText.bind(t);t.statusText=function(){let d=c();return r.primitiveCallIds.set(d,n),d};let f=t.ok.bind(t);t.ok=function(){let d=f();return r.primitiveCallIds.set(d,n),d};let p=t.text.bind(t);t.text=async function(){let d=await p();return r.primitiveCallIds.set(d,n),d};let u=t.body.bind(t);t.body=async function(){let d=await u();return D.set(d,n),d};}createWrapper(t,n){let r=this;return async function(o,l){if(!Ct(o,r.apiConfig.apiIncludeUrls,r.apiConfig.apiExcludeUrls))return n(o,l);let a=`api-call-${r.callCounter++}`,c=new Date().toISOString(),f=t==="fetch"?(l?.method??"GET").toUpperCase():t.toUpperCase(),p=ae(l),u=perf_hooks.performance.now();r._lastCallId=a,r.assertionTracker&&r.assertionTracker.setCurrentCallId(a);let i;try{i=await n(o,l);}catch(d){let g=perf_hooks.performance.now();try{let h=r.apiConfig.captureRequestBody?E(p,r.apiConfig.redactBodyFields):null,w={id:a,timestamp:c,method:f,url:$(o),requestHeaders:null,requestBody:h,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((g-u)*100)/100,isBinary:!1,error:d instanceof Error?d.message:String(d)};r.apiCallWriter&&(r.apiCallWriter.append(w),r.apiCallCount++,r.tallyStatus(null));}catch{}throw d}try{let d=perf_hooks.performance.now(),g=i.headers(),h=g["content-type"]??null,w=h?!ie(h):!1,k=null;r.apiConfig.captureRequestHeaders&&l?.headers&&(k=l.headers);let x=null;r.apiConfig.captureResponseHeaders&&(x=g);let R=r.apiConfig.captureRequestBody?p:null,A=null;if(r.apiConfig.captureResponseBody)try{w?A=(await i.body()).toString("base64"):A=await i.text();}catch{}let v=[],P=[];try{if(r.apiConfig.captureRequestHeaders&&(v=ue(l?.headers)),r.apiConfig.captureResponseHeaders){let m=i.headersArray().filter(b=>b.name.toLowerCase()==="set-cookie").map(b=>b.value);P=ce(m);}}catch{}k=J(k,r.apiConfig.redactHeaders),x=J(x,r.apiConfig.redactHeaders),R=E(R,r.apiConfig.redactBodyFields),A=E(A,r.apiConfig.redactBodyFields);let y={id:a,timestamp:c,method:f,url:$(i.url()),requestHeaders:k,requestBody:R,responseStatusCode:i.status(),responseStatusText:i.statusText(),responseHeaders:x,responseBody:A,requestCookies:v.length?v:null,responseCookies:P.length?P:null,responseTimeMs:Math.round((d-u)*100)/100,isBinary:w,error:null};r.apiCallWriter&&(r.apiCallWriter.append(y),r.apiCallCount++,r.tallyStatus(y.responseStatusCode));}catch{}try{i[U]=a,r.tagResponseMethods(i,a);}catch{}return i}}};L.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 O=L;Buffer.from([137,80,78,71,13,10,26,10]);function St(e){let{styleProps:t,defaults:n,inherited:r,maxNodes:s,maxText:o,maskBoxes:l,viewportBox:a,fullPage:c}=e,f={};for(let y=0;y<r.length;y++)f[r[y]]=true;let p=window.scrollX||window.pageXOffset||0,u=window.scrollY||window.pageYOffset||0,i=[],d=0,g=[];for(let y=0;y<l.length;y++){let m=l[y];g.push([m[0]+p,m[1]+u,m[2],m[3]]);}function h(y,m,b,T){for(let C=0;C<g.length;C++){let S=g[C];if(y<S[0]+S[2]&&y+b>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 b=m.children,T=0;for(let C=0;C<b.length;C++){let S=b[C];if(S===y)break;S.tagName===y.tagName&&T++;}return T}function k(y){let m="",b=y.childNodes;for(let T=0;T<b.length;T++){let C=b[T];C.nodeType===3&&(m+=C.nodeValue??"");}return m=m.replace(/\s+/g," ").trim(),m.length>o?m.slice(0,o):m}function x(y,m){let b;for(let T=0;T<t.length;T++){let C=t[T],S=y.getPropertyValue(C);if(S){if(f[C]){if(m&&m.getPropertyValue(C)===S)continue}else if(n[C]===S)continue;b||(b={}),b[C]=S;}}return b}let R=[{el:document.body,parentPath:"",parentComputed:null}];for(;R.length>0;){let y=R.pop(),m=y.el,b=window.getComputedStyle(m);if(b.display==="none")continue;let T=m.tagName.toLowerCase(),C=m.id?"#"+m.id:y.parentPath?y.parentPath+">"+T+"["+w(m)+"]":T,S=m.children;for(let H=S.length-1;H>=0;H--)R.push({el:S[H],parentPath:C,parentComputed:b});if(b.visibility==="hidden")continue;let M=m.getBoundingClientRect();if(M.width<=0||M.height<=0)continue;if(i.length>=s){d++;continue}let nt=Math.round(M.left+p),rt=Math.round(M.top+u),ot=Math.round(M.width),st=Math.round(M.height),_={p:C,t:T,r:[nt,rt,ot,st]};m.id&&(_.i=m.id);let it=m.getAttribute("class");it&&(_.c=it.replace(/\s+/g," ").trim());let at=k(m);at&&(_.x=at);let ut=x(b,y.parentComputed);ut&&(_.s=ut),h(nt,rt,ot,st)&&(_.m=1),i.push(_);}let A=Math.max(document.documentElement.scrollWidth,window.innerWidth),v=Math.max(document.documentElement.scrollHeight,window.innerHeight),P;return a?P=[Math.round(a[0]+p),Math.round(a[1]+u),Math.round(a[2]),Math.round(a[3])]:c?P=[0,0,A,v]:P=[Math.round(p),Math.round(u),window.innerWidth,window.innerHeight],{version:"1.0",url:location.href,viewport:{width:window.innerWidth,height:window.innerHeight},content:{width:A,height:v},captureBox:P,nodes:i,truncatedNodes:d}}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"],me={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"},ye=["color","font-family","font-size","font-weight","line-height","letter-spacing","text-align","text-transform"],we=1024*1024,ke=1500,be=200;async function xe(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 Tt(e){let t=e.config??{};try{let n=e.maskLocators?.length?await xe(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:me,inherited:ye,maxNodes:t.maxNodes??ke,maxText:t.maxText??be,maskBoxes:n,viewportBox:r,fullPage:e.fullPage===!0};return await e.target.evaluate(St,s)}catch{return null}}function At(e,t=we){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 vt(e){return e.replace(/\.[A-Za-z0-9]+$/,"")+".dom.json"}function Pt(e){try{if(!fs.existsSync(e))return null;let t=JSON.parse(fs.readFileSync(e,"utf-8"));return Ce(t)?t:null}catch{return null}}function Nt(e,t){try{return fs.mkdirSync(path.dirname(e),{recursive:!0}),fs.writeFileSync(e,t,"utf-8"),!0}catch{return false}}function Ce(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 Re=new Set(["moved","resized"]);function q(e){return e.some(t=>!Re.has(t))}function Y(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]),l=Math.abs(e.r[3]-t.r[3]);return (r>1||s>1)&&n.push("moved"),(o>1||l>1)&&n.push("resized"),n}function Te(e,t){let n=e.s??{},r=t.s??{},s=new Set([...Object.keys(n),...Object.keys(r)]),o=[];for(let l of s){let a=n[l],c=r[l];a!==c&&o.push({prop:l,from:a??"(initial)",to:c??"(initial)"});}return o.sort((l,a)=>l.prop.localeCompare(a.prop)),o}function Dt(e){return e.i?"i:"+e.t+"#"+e.i:e.c?"c:"+e.t+"."+e.c:null}function Ae(e,t){let n=new Map;for(let u of e)n.set(u.p,u);let r=[],s=[],o=new Set;for(let u of t){let i=n.get(u.p);if(i&&i.t!==u.t){s.push(u);continue}i&&!o.has(i)?(o.add(i),r.push({before:i,after:u})):s.push(u);}let l=e.filter(u=>!o.has(u)),a=new Map;for(let u of l){let i=Dt(u);if(!i)continue;let d=a.get(i);d?d.push(u):a.set(i,[u]);}let c=[],f=new Set;for(let u of s){let i=Dt(u),g=(i?a.get(i):void 0)?.find(h=>!f.has(h));g?(f.add(g),r.push({before:g,after:u})):c.push(u);}let p=l.filter(u=>!f.has(u));return {pairs:r,removed:p,added:c}}function ve(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 K(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 Mt(e,t,n={}){let r=n.maxChanges??50,s=n.includeText!==false,o=n.includeStyles!==false,l=e.nodes.filter(g=>g.m!==1),a=t.nodes.filter(g=>g.m!==1),{pairs:c,removed:f,added:p}=Ae(l,a),u=[];for(let{before:g,after:h}of c){let w=Se(g,h),k=o?Te(g,h):[];k.length>0&&w.push("restyled");let x=ve(g,h);x.length>0&&w.push("attrs");let R=s&&(g.x??"")!==(h.x??"");if(R&&w.push("text"),w.length===0)continue;let A=K(h,t.captureBox);u.push({score:A,change:{path:h.p,label:Y(h),kinds:w,rect:h.r,baselineRect:g.r,areaPct:A,...x.length>0?{attrs:x}:{},...k.length>0?{styles:k}:{},...R?{text:{from:g.x??"",to:h.x??""}}:{}}});}for(let g of p){let h=K(g,t.captureBox);u.push({score:h,change:{path:g.p,label:Y(g),kinds:["added"],rect:g.r,areaPct:h}});}for(let g of f){let h=K(g,e.captureBox);u.push({score:h,change:{path:g.p,label:Y(g),kinds:["removed"],baselineRect:g.r,areaPct:h}});}let i=u.filter(g=>q(g.change.kinds)).length;return u.sort((g,h)=>{if(i>0){let w=q(g.change.kinds)?1:0,k=q(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,...i>0&&!q(g.change.kinds)?{consequence:true}:{}})),total:u.length,rootCauses:i}}var Pe="__testrelic_snapshot_path_probe__.png",_t=Symbol.for("testrelic.snapshotPathWarned");function Ne(){let e=globalThis,t=e[_t];return t||(t={warned:false},e[_t]=t),t}function F(e){try{let t=e.snapshotPath(Pe,{kind:"screenshot"});return typeof t=="string"&&!t.includes("[object Object]")}catch{return false}}function j(e){let t=Ne();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 Bt="testrelic-visual-dom",Ie=new Set(["toHaveScreenshot","toMatchVisualBaseline"]);function It(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.boundingBox=="function"&&typeof t.page=="function"}function Ee(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.evaluate=="function"&&typeof t.screenshot=="function"}function Oe(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 Le(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 Fe(e){return /\.(png|jpg|jpeg)$/i.test(e)?e:`${e}.png`}var je=/^(.+)-(expected|actual|diff|previous)\.[A-Za-z0-9]+$/;function He(e,t,n){let r=e.attachments;for(let s=t;s<r.length;s++){let o=je.exec(r[s]?.name??"");if(o)return o[1]}return n}async function We(e){let t=Le(e.args),n=It(e.received)?e.received:null,r=n?n.page():e.received;return Tt({target:r,bounded:n,maskLocators:qe(t),fullPage:t.fullPage===true})}function Ve(e){let t=e.config?.updateSnapshots;return t==="all"||t==="changed"}async function Ue(e,t){let n=Oe(e.args);if(!n)return;if(!F(e.testInfo)){j("DOM comparison");return}let r=e.testInfo.snapshotPath(Fe(n),{kind:"screenshot"}),s=vt(r),o=He(e.testInfo,e.attachedBefore,path.basename(r,path.extname(r))),l=At(t),c=Ve(e.testInfo)?null:Pt(s);if(!c){Nt(s,l.json);return}let{changes:f,total:p,rootCauses:u}=Mt(c,t),i;try{i=e.testInfo.outputPath(`${o}.actual.dom.json`),fs.writeFileSync(i,l.json,"utf-8");}catch{i=void 0;}let d={stem:o,changes:f,total:p,rootCauses:u,truncated:l.truncatedBytes||t.truncatedNodes>0,captureBox:t.captureBox,...fs.existsSync(s)?{baselineDomPath:s}:{},...i?{actualDomPath:i}:{}};await e.testInfo.attach(Bt,{body:Buffer.from(JSON.stringify([d])),contentType:"application/json"});}function Et(e,t){let n=function(l,...a){let c=e(l,...a);return !(It(l)||Ee(l))||typeof c!="object"||c===null?c:new Proxy(c,{get(p,u,i){let d=Reflect.get(p,u,i);if(typeof u!="string"||!Ie.has(u)||typeof d!="function")return d;let g=d;return async function(...w){let k=t(),x=null,R=k?.attachments.length??0;if(k)try{x=await We({received:l,args:w,testInfo:k,attachedBefore:R});}catch{}try{return await g.apply(p,w)}finally{if(k&&x)try{await Ue({received:l,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 Ot="testrelic-visual";var Ye=[".png",".jpg",".jpeg"],Ke=/A snapshot doesn't exist at /;function Ze(e){return e.wrote?e.existedBefore?"updated":"new":e.pass?"passed":"failed"}function Lt(e){if(!e)return null;try{let t=fs.statSync(e);return {size:t.size,mtimeMs:t.mtimeMs}}catch{return null}}function Qe(e,t){if(!F(e))return null;try{return e.snapshotPath(t,{kind:"screenshot"})}catch{return null}}function tn(e){let t=e.toLowerCase();return Ye.some(n=>t.endsWith(n))?e:`${e}.png`}function en(){try{return test.test.info()}catch{return null}}function nn(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 l=r(o.name);if(l)return l}return null}async function rn(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 on(e,t){try{await e.attach(Ot,{body:Buffer.from(JSON.stringify([t])),contentType:"application/json"});}catch{}}async function Z(e,t,n={}){let r={...n};delete r.tags;let s=tn(t),o=en(),l=o?.attachments.length??0,a=o?.errors?.length??0,c=o?Qe(o,s):null,f=Lt(c),p=true,u="";try{await test.expect(e).toHaveScreenshot(s,r);}catch(i){p=false,u=i instanceof Error?i.message:String(i);}if(o){let i=Lt(c),d=c!==null?i!==null&&(f===null||f.size!==i.size||f.mtimeMs!==i.mtimeMs):(o.errors??[]).slice(a).some(w=>Ke.test(w.message??"")),g=Ze({pass:p,wrote:d,existedBefore:f!==null}),h=g==="passed"||g==="updated"?await rn(o,c):nn(o.attachments,l,c);h&&await on(o,{stem:h,name:t,status:g,...c?{committedPath:c}:{}});}return {pass:p,name:"toMatchVisualBaseline",message:()=>p?`Expected "${t}" to differ from its visual baseline, but it matched.`:u}}test.expect.extend({toMatchVisualBaseline:Z});function un(){try{return test.test.info()}catch{return null}}var xr=Et(wt(test.expect),un),cn="__testrelic_api_config",ln="__testrelic_config_trackApiCalls";function dn(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===ln&&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 B(e);try{await r.init();}catch{}await t(e);try{let{navigations:s,networkRequestsFile:o,networkRequestsCount:l,consoleLogsFile:a,consoleLogsCount:c}=await r.getFileData(),f={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:o,networkRequestsCount:l,consoleLogsFile:a,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=dn(n);if(!r.trackApiCalls){await t(e);return}let s=new I,o=new O(e,s,r);o.intercept(),z(s,o);try{await t(e);}finally{z(null,null);}try{let{apiCallsFile:l,apiCallsCount:a,apiStatusMix:c}=o.getFileData(),f=r.captureAssertions?s.getData():[],p={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:f,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:l,apiCallsCount:a,apiStatusMix:c};await n.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(p)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}o.dispose(),s.dispose();}};async function Cr(e,t){let n=new B(e);try{await n.init();}catch{}return async()=>{try{let{navigations:r,networkRequestsFile:s,networkRequestsCount:o,consoleLogsFile:l,consoleLogsCount:a}=await n.getFileData(),c={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:r,apiAssertions:[],networkRequestsFile:s,networkRequestsCount:o,consoleLogsFile:l,consoleLogsCount:a,apiCallsFile:null,apiCallsCount:0};await t.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(c)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();}}var Rr=test.test.extend(fn);exports.expect=xr;exports.readApiConfig=dn;exports.test=Rr;exports.testRelicFixture=fn;exports.trackPage=Cr;//# sourceMappingURL=fixture.cjs.map
|
|
7
7
|
//# sourceMappingURL=fixture.cjs.map
|