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

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.
@@ -1,5 +1,5 @@
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 O=path.join(os.tmpdir(),"testrelic-data"),y=class{constructor(t){this.count=0;this.closed=false;fs.mkdirSync(O,{recursive:true}),this.filePath=path.join(O,`${t}-${crypto.randomUUID().substring(0,8)}.jsonl`),this.fd=fs.openSync(this.filePath,"w");}append(t){if(this.closed)return;let e=JSON.stringify(t)+`
2
- `;fs.writeSync(this.fd,e),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 _=Symbol.for("__testrelic_call_id"),ot="__testrelic_api_assertions",m=new WeakMap,A=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:ot,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}},D=new Map;function it(r){let t=D.get(r);if(t)return t;try{let e=r.startsWith("file://")?url.fileURLToPath(r):r,s=fs.readFileSync(e,"utf-8").split(`
3
- `);return D.set(r,s),s}catch{return null}}function at(){let t=new Error().stack;if(!t)return null;let e=t.split(`
4
- `);for(let n of e){if(n.includes("/assertion-tracker.")||n.includes("/api-request-tracker.")||n.includes("node:internal")||n.includes(" at new Error")||n.includes(" at captureAssertionLocation")||n.includes(" at expectWrapper")||n.includes(" at wrappedMatcher"))continue;let s=n.match(/at\s+(?:.*?\s+\()?(.+?):(\d+):(\d+)\)?$/);if(s)return {file:s[1],line:parseInt(s[2],10),column:parseInt(s[3],10)}}return null}function lt(r,t){if(!r)return "custom";let e=r.toLowerCase();return e.includes(".status()")&&!e.includes(".statustext()")?e.includes(".ok()")?"statusOk":"status":e.includes(".ok()")?"statusOk":e.includes(".headers()")||e.includes(".headersarray()")?"header":e.includes("tomatchobject")||e.includes("toequal")?"bodyMatch":e.includes("tocontain")||e.includes("tostringcontaining")?"bodyContains":e.includes(".json()")||e.includes(".text()")?"bodyField":"custom"}function ut(r,t,e){let n=function(i,...p){let c=r(),u=t();if(!c||!u)return e(i,...p);let d=null;if(i!=null&&typeof i=="object"){let a=i[_];typeof a=="string"&&(d=a);}if(!d&&i!==null&&i!==void 0&&typeof i=="object"&&(d=m.get(i)??null),d||(d=u.getCallIdForValue(i)),d||(d=c.getCurrentCallId()),!d)return e(i,...p);let o=at(),g;if(o){let a=it(o.file);a&&o.line>0&&o.line<=a.length&&(g=a[o.line-1].trim());}let l=e(i,...p);return d?H(l,{tracker:c,callId:d,received:i,location:o??{file:"unknown",line:0},expression:g}):l};for(let s of Object.keys(e))n[s]=e[s];return n}var M=null,j=null;function v(r,t){M=r,j=t;}function N(r){return ut(()=>M,()=>j,r)}function H(r,t){return new Proxy(r,{get(e,n,s){let i=Reflect.get(e,n,s);return typeof i!="function"||typeof n=="symbol"?i:n==="not"?H(i,t):function(...c){let u=c[0],d="passed",o=t.received,g=null;try{let l=i.apply(this??e,c);return l&&typeof l=="object"&&typeof l.then=="function"?l.then(()=>{P(t,n,u,o,"passed");},a=>{throw P(t,n,u,o,"failed"),a}):l}catch(l){if(d="failed",g=l,l instanceof Error&&l.message){let a=l.message.match(/Received:\s*(.+)/);a&&(o=a[1]);}throw l}finally{(g!==null||d==="passed")&&P(t,n,u,o,d);}}}})}function P(r,t,e,n,s){let i=lt(r.expression,r.received),p={callId:r.callId,type:i,expected:W(e),actual:W(n),status:s,location:r.location,expression:r.expression};r.tracker.recordAssertion(p);}function W(r){if(r==null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;try{return JSON.stringify(r),r}catch{return String(r)}}var J="[REDACTED]";function B(r,t){if(r===null||t.length===0)return r;let e=new Set(t.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(r))Object.hasOwn(r,s)&&(n[s]=e.has(s.toLowerCase())?J:r[s]);return n}function q(r,t){if(r===null||t.length===0)return r;let e;try{e=JSON.parse(r);}catch{return r}if(typeof e!="object"||e===null)return r;let n=new Set(t),s=I(e,n);return JSON.stringify(s)}function I(r,t){if(Array.isArray(r))return r.map(e=>I(e,t));if(typeof r=="object"&&r!==null){let e={};for(let n of Object.keys(r)){if(!Object.hasOwn(r,n))continue;let s=r[n];t.has(n)?e[n]=J:e[n]=I(s,t);}return e}return r}function G(r,t,e){if(e.length>0){for(let n of e)if(U(r,n))return false}if(t.length>0){for(let n of t)if(U(r,n))return true;return false}return true}function U(r,t){try{return t instanceof RegExp?t.test(r):ct(t).test(r)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(t)}`),false}}function ct(r){let t="",e=0;for(;e<r.length;){let n=r[e];n==="*"&&r[e+1]==="*"?(t+=".*",e+=2,r[e]==="/"&&e++):n==="*"?(t+="[^/]*",e++):n==="?"?(t+="[^/]",e++):".+^${}()|[]\\".includes(n)?(t+="\\"+n,e++):(t+=n,e++);}return new RegExp(t)}var dt=["get","post","put","patch","delete","head","fetch"],pt=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function gt(r){let t=r.toLowerCase();return pt.some(e=>t.includes(e))}function ft(r){if(!r)return null;if(r.data!==void 0&&r.data!==null){let t=r.data;return typeof t=="string"?t:Buffer.isBuffer(t)?t.toString("base64"):JSON.stringify(t)}if(r.form!==void 0&&r.form!==null)return JSON.stringify(r.form);if(r.multipart!==void 0&&r.multipart!==null){let t=r.multipart,e={};for(let[n,s]of Object.entries(t))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?e[n]=String(s):s&&typeof s=="object"&&"name"in s?e[n]=`[file: ${s.name}]`:e[n]="[binary]";return JSON.stringify(e)}return null}var x=class x{constructor(t,e,n){this.originals=new Map;this.apiCallWriter=null;this.callCounter=0;this.apiCallCount=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=t,this.assertionTracker=e??null,this.apiConfig=n??x.DEFAULT_API_CONFIG;try{this.apiCallWriter=new y("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(t){return t!=null&&typeof t=="object"?m.get(t)??null:this.primitiveCallIds.get(t)??null}intercept(){for(let e of dt){let n=this.context[e].bind(this.context);this.originals.set(e,n),this.context[e]=this.createWrapper(e,n);}let t=this.context.dispose.bind(this.context);this.originals.set("dispose",t),this.context.dispose=async e=>(this.disposed=true,t(e));}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0}}flushLegacyAnnotations(t){}dispose(){for(let[t,e]of this.originals)this.context[t]=e;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,e){let n=this,s=t.headers.bind(t);t.headers=function(){let a=s();return m.set(a,e),a};let i=t.headersArray.bind(t);t.headersArray=function(){let a=i();return m.set(a,e),a};let p=t.json.bind(t);t.json=async function(){let a=await p();return a!=null&&typeof a=="object"&&m.set(a,e),a};let c=t.status.bind(t);t.status=function(){let a=c();return n.primitiveCallIds.set(a,e),a};let u=t.statusText.bind(t);t.statusText=function(){let a=u();return n.primitiveCallIds.set(a,e),a};let d=t.ok.bind(t);t.ok=function(){let a=d();return n.primitiveCallIds.set(a,e),a};let o=t.text.bind(t);t.text=async function(){let a=await o();return n.primitiveCallIds.set(a,e),a};let g=t.body.bind(t);t.body=async function(){let a=await g();return m.set(a,e),a};}createWrapper(t,e){let n=this;return async function(i,p){if(!G(i,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return e(i,p);let c=`api-call-${n.callCounter++}`,u=new Date().toISOString(),d=t==="fetch"?(p?.method??"GET").toUpperCase():t.toUpperCase(),o=ft(p),g=perf_hooks.performance.now();n._lastCallId=c,n.assertionTracker&&n.assertionTracker.setCurrentCallId(c);let l;try{l=await e(i,p);}catch(a){let C=perf_hooks.performance.now();try{let w=n.apiConfig.captureRequestBody?q(o,n.apiConfig.redactBodyFields):null,R={id:c,timestamp:u,method:d,url:i,requestHeaders:null,requestBody:w,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((C-g)*100)/100,isBinary:!1,error:a instanceof Error?a.message:String(a)};n.apiCallWriter&&(n.apiCallWriter.append(R),n.apiCallCount++);}catch{}throw a}try{let a=perf_hooks.performance.now(),C=l.headers(),w=C["content-type"]??null,R=w?!gt(w):!1,f=null;n.apiConfig.captureRequestHeaders&&p?.headers&&(f=p.headers);let h=null;n.apiConfig.captureResponseHeaders&&(h=C);let T=n.apiConfig.captureRequestBody?o:null,k=null;if(n.apiConfig.captureResponseBody)try{R?k=(await l.body()).toString("base64"):k=await l.text();}catch{}f=B(f,n.apiConfig.redactHeaders),h=B(h,n.apiConfig.redactHeaders),T=q(T,n.apiConfig.redactBodyFields),k=q(k,n.apiConfig.redactBodyFields);let K={id:c,timestamp:u,method:d,url:l.url(),requestHeaders:f,requestBody:T,responseStatusCode:l.status(),responseStatusText:l.statusText(),responseHeaders:h,responseBody:k,responseTimeMs:Math.round((a-g)*100)/100,isBinary:R,error:null};n.apiCallWriter&&(n.apiCallWriter.append(K),n.apiCallCount++);}catch{}try{l[_]=c,n.tagResponseMethods(l,c);}catch{}return l}}};x.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 b=x;var ht=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function yt(r){let t=r.toLowerCase();return ht.some(e=>t.includes(e))}var S=class r{constructor(t,e){this.page=t;this.records=[];this.listeners=[];this.currentNetworkCounter=null;this.pendingRequests=new Map;this.networkWriter=null;this.consoleWriter=null;this.pendingBodyReads=[];this.requestIdCounter=0;this.networkRequestCount=0;this.consoleLogCount=0;this.includeNetworkStats=e?.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 y("network")),this.consoleWriter=new y("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.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}});let t=this.records.map(e=>({url:e.url,navigationType:e.navigationType,timestamp:e.timestamp,domContentLoadedAt:e.domContentLoadedAt,networkIdleAt:e.networkIdleAt,networkStats:e.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(){this.page.goto=this.origGoto,this.page.goBack=this.origGoBack,this.page.goForward=this.origGoForward,this.page.reload=this.origReload;for(let{event:t,handler:e}of this.listeners)this.page.off(t,e);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}getRecords(){return this.records}interceptMethods(){let t=this,e=this.page;e.goto=async function(n,s){return t.recordNavigation(n,"goto"),t.origGoto(n,s)},e.goBack=async function(n){let s=await t.origGoBack(n);return t.recordNavigation(e.url(),"back"),s},e.goForward=async function(n){let s=await t.origGoForward(n);return t.recordNavigation(e.url(),"forward"),s},e.reload=async function(n){return t.recordNavigation(e.url(),"refresh"),t.origReload(n)};}attachListeners(){let t=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",t),this.listeners.push({event:"domcontentloaded",handler:t});let e=s=>{try{let i=s;if(typeof i.parentFrame=="function"&&i.parentFrame()!==null)return;let p=i.url(),c=this.records[this.records.length-1];if(c&&Date.now()-new Date(c.timestamp).getTime()<50&&c.url===p)return;this.recordNavigation(p,"navigation");}catch{}};this.page.on("framenavigated",e),this.listeners.push({event:"framenavigated",handler:e});let n=s=>{try{let i=s,p=i.type(),c=i.text();if(p==="debug"&&c.startsWith("__testrelic_nav:")){try{let u=JSON.parse(c.slice(16));u.type&&u.url&&this.recordNavigation(u.url,u.type);}catch{}return}{let u=null;try{let o=i.location();o&&o.url&&(u=`${o.url}:${o.lineNumber}:${o.columnNumber}`);}catch{}let d=r.mapConsoleType(p);this.consoleWriter&&(this.consoleWriter.append({level:d,text:c,timestamp:new Date().toISOString(),location:u}),this.consoleLogCount++);}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=c=>{this.currentNetworkCounter&&this.currentNetworkCounter.totalRequests++;try{let u=c,d=String(this.requestIdCounter++),o=u.postData()??null,g={url:u.url(),method:u.method(),resourceType:this.mapResourceType(u.resourceType()),headers:u.headers(),postData:o,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now()};this.pendingRequests.set(d,g),c.__testrelic_id=d;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let i=c=>{try{let u=c;if(this.currentNetworkCounter){let f=u.status();f>=400&&(this.currentNetworkCounter.failedRequests++,this.currentNetworkCounter.failedRequestUrls.push(f+" "+u.url()));let h=u.headers()["content-length"];h&&(this.currentNetworkCounter.totalBytes+=parseInt(h,10)||0);let T=u.request().resourceType(),k=this.mapResourceType(T);this.currentNetworkCounter.byType[k]++;}let d=u.request().__testrelic_id;if(!d)return;let o=this.pendingRequests.get(d);if(!o)return;this.pendingRequests.delete(d);let g=Date.now()-o.startTimeMs,l=u.headers(),a=l["content-type"]??null,C=parseInt(l["content-length"]??"0",10)||0,w=a?!yt(a):!1,R=(async()=>{let f=null;if(!w)try{f=(await u.body()).toString("utf-8");}catch{}let h={url:o.url,method:o.method,resourceType:o.resourceType,statusCode:u.status(),responseTimeMs:g,startedAt:o.startedAt,requestHeaders:o.headers,requestBody:o.postData,responseBody:f,responseHeaders:l,contentType:a,responseSize:C,requestBodyTruncated:o.postDataTruncated,responseBodyTruncated:!1,isBinary:w,error:null};this.networkWriter&&(this.networkWriter.append(h),this.networkRequestCount++);})();this.pendingBodyReads.push(R);}catch{}};this.page.on("response",i),this.listeners.push({event:"response",handler:i});let p=c=>{if(this.currentNetworkCounter){this.currentNetworkCounter.failedRequests++;try{let u=c;this.currentNetworkCounter.failedRequestUrls.push("ERR "+u.url());}catch{}}try{let u=c,d=u.__testrelic_id;if(!d)return;let o=this.pendingRequests.get(d);if(!o)return;this.pendingRequests.delete(d);let g={url:o.url,method:o.method,resourceType:o.resourceType,statusCode:0,responseTimeMs:Date.now()-o.startTimeMs,startedAt:o.startedAt,requestHeaders:o.headers,requestBody:o.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:o.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:u.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(g),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",p),this.listeners.push({event:"requestfailed",handler:p});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let t=history.pushState.bind(history),e=history.replaceState.bind(history);history.pushState=function(...n){t(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){e(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(t,e){this.includeNetworkStats&&this.currentNetworkCounter&&this.records.length>0&&(this.records[this.records.length-1].networkStats={totalRequests:this.currentNetworkCounter.totalRequests,failedRequests:this.currentNetworkCounter.failedRequests,failedRequestUrls:[...this.currentNetworkCounter.failedRequestUrls],totalBytes:this.currentNetworkCounter.totalBytes,byType:{...this.currentNetworkCounter.byType}}),this.records.push({url:t,navigationType:e,timestamp:new Date().toISOString()}),this.includeNetworkStats&&(this.currentNetworkCounter=this.createNetworkCounter());}createNetworkCounter(){return {totalRequests:0,failedRequests:0,failedRequestUrls:[],totalBytes:0,byType:{xhr:0,document:0,script:0,stylesheet:0,image:0,font:0,other:0}}}mapResourceType(t){switch(t){case "xhr":case "fetch":return "xhr";case "document":return "document";case "script":return "script";case "stylesheet":return "stylesheet";case "image":return "image";case "font":return "font";default:return "other"}}};N(test.expect);var mt="__testrelic_api_config",Ct="__testrelic_config_trackApiCalls";function F(r){let t=r.annotations.find(n=>n.type===mt&&n.description!==void 0);if(t)try{return JSON.parse(t.description,Rt)}catch{}let e=r.annotations.find(n=>n.type===Ct&&n.description!==void 0);return e?{trackApiCalls:e.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 Rt(r,t){if(typeof t=="object"&&t!==null&&t.__regexp===true&&typeof t.source=="string"){let{source:e,flags:n}=t;return new RegExp(e,n)}return t}var Tt={page:async({page:r},t,e)=>{let n=new S(r);try{await n.init();}catch{}await t(r);try{let{navigations:s,networkRequestsFile:i,networkRequestsCount:p,consoleLogsFile:c,consoleLogsCount:u}=await n.getFileData(),d={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:i,networkRequestsCount:p,consoleLogsFile:c,consoleLogsCount:u,apiCallsFile:null,apiCallsCount:0};await e.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:r},t,e)=>{let n=F(e);if(!n.trackApiCalls){await t(r);return}let s=new A,i=new b(r,s,n);i.intercept(),v(s,i);try{await t(r);}finally{v(null,null);}try{let{apiCallsFile:p,apiCallsCount:c}=i.getFileData(),u=n.captureAssertions?s.getData():[],d={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:u,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:p,apiCallsCount:c};await e.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(d)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}i.dispose(),s.dispose();}};test.test.extend(Tt);var ue=N(test.expect),ce={request:async({request:r},t,e)=>{let n=F(e);if(!n.trackApiCalls){await t(r);return}let s=new A,i=new b(r,s,n);i.intercept(),v(s,i);let p=null;try{p=new y("api-console");}catch{}let c=0,u=process.stdout.write,d=process.stderr.write;process.stdout.write=function(o,...g){try{let l=typeof o=="string"?o:Buffer.isBuffer(o)?o.toString("utf-8"):String(o);!l.startsWith("[testrelic]")&&!l.startsWith("\u2139 TestRelic")&&!l.startsWith("\u2713 TestRelic")&&!l.startsWith("\u26A0 TestRelic")&&p&&(p.append({level:"stdout",text:l.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),c++);}catch{}return u.apply(process.stdout,[o,...g])},process.stderr.write=function(o,...g){try{let l=typeof o=="string"?o:Buffer.isBuffer(o)?o.toString("utf-8"):String(o);!l.startsWith("[testrelic]")&&!l.startsWith("\u26A0 TestRelic")&&p&&(p.append({level:"stderr",text:l.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),c++);}catch{}return d.apply(process.stderr,[o,...g])};try{await t(r);}finally{process.stdout.write=u,process.stderr.write=d,v(null,null);}try{p?.close();let{apiCallsFile:o,apiCallsCount:g}=i.getFileData(),l=n.captureAssertions?s.getData():[],a={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:l,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:c>0?p?.getPath()??null:null,consoleLogsCount:c,apiCallsFile:o,apiCallsCount:g};await e.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(a)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}i.dispose(),s.dispose();}};exports.expect=ue;exports.testRelicApiFixture=ce;//# sourceMappingURL=api-fixture.cjs.map
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 E=path.join(os.tmpdir(),"testrelic-data"),h=class{constructor(t){this.count=0;this.closed=false;fs.mkdirSync(E,{recursive:true}),this.filePath=path.join(E,`${t}-${crypto.randomUUID().substring(0,8)}.jsonl`),this.fd=fs.openSync(this.filePath,"w");}append(t){if(this.closed)return;let e=JSON.stringify(t)+`
2
+ `;fs.writeSync(this.fd,e),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 _=Symbol.for("__testrelic_call_id"),ot="__testrelic_api_assertions",C=new WeakMap,A=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:ot,description:JSON.stringify(this.assertions)});}dispose(){this.assertions=[],this.currentCallId=null;}},W=new Map;function it(r){let t=W.get(r);if(t)return t;try{let e=r.startsWith("file://")?url.fileURLToPath(r):r,s=fs.readFileSync(e,"utf-8").split(`
3
+ `);return W.set(r,s),s}catch{return null}}function at(){let t=new Error().stack;if(!t)return null;let e=t.split(`
4
+ `);for(let n of e){if(n.includes("/assertion-tracker.")||n.includes("/api-request-tracker.")||n.includes("node:internal")||n.includes(" at new Error")||n.includes(" at captureAssertionLocation")||n.includes(" at expectWrapper")||n.includes(" at wrappedMatcher"))continue;let s=n.match(/at\s+(?:.*?\s+\()?(.+?):(\d+):(\d+)\)?$/);if(s)return {file:s[1],line:parseInt(s[2],10),column:parseInt(s[3],10)}}return null}function lt(r,t){if(!r)return "custom";let e=r.toLowerCase();return e.includes(".status()")&&!e.includes(".statustext()")?e.includes(".ok()")?"statusOk":"status":e.includes(".ok()")?"statusOk":e.includes(".headers()")||e.includes(".headersarray()")?"header":e.includes("tomatchobject")||e.includes("toequal")?"bodyMatch":e.includes("tocontain")||e.includes("tostringcontaining")?"bodyContains":e.includes(".json()")||e.includes(".text()")?"bodyField":"custom"}function ct(r,t,e){let n=function(a,...p){let d=r(),u=t();if(!d||!u)return e(a,...p);let c=null;if(a!=null&&typeof a=="object"){let i=a[_];typeof i=="string"&&(c=i);}if(!c&&a!==null&&a!==void 0&&typeof a=="object"&&(c=C.get(a)??null),c||(c=u.getCallIdForValue(a)),c||(c=d.getCurrentCallId()),!c)return e(a,...p);let o=at(),g;if(o){let i=it(o.file);i&&o.line>0&&o.line<=i.length&&(g=i[o.line-1].trim());}let l=e(a,...p);return c?J(l,{tracker:d,callId:c,received:a,location:o??{file:"unknown",line:0},expression:g}):l};for(let s of Object.keys(e))n[s]=e[s];return n}var j=null,H=null;function v(r,t){j=r,H=t;}function x(r){return ct(()=>j,()=>H,r)}function J(r,t){return new Proxy(r,{get(e,n,s){let a=Reflect.get(e,n,s);return typeof a!="function"||typeof n=="symbol"?a:n==="not"?J(a,t):function(...d){let u=d[0],c="passed",o=t.received,g=null;try{let l=a.apply(this??e,d);return l&&typeof l=="object"&&typeof l.then=="function"?l.then(()=>{I(t,n,u,o,"passed");},i=>{throw I(t,n,u,o,"failed"),i}):l}catch(l){if(c="failed",g=l,l instanceof Error&&l.message){let i=l.message.match(/Received:\s*(.+)/);i&&(o=i[1]);}throw l}finally{(g!==null||c==="passed")&&I(t,n,u,o,c);}}}})}function I(r,t,e,n,s){let a=lt(r.expression,r.received),p={callId:r.callId,type:a,expected:M(e),actual:M(n),status:s,location:r.location,expression:r.expression};r.tracker.recordAssertion(p);}function M(r){if(r==null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r;try{return JSON.stringify(r),r}catch{return String(r)}}var U="[REDACTED]";function B(r,t){if(r===null||t.length===0)return r;let e=new Set(t.map(s=>s.toLowerCase())),n={};for(let s of Object.keys(r))Object.hasOwn(r,s)&&(n[s]=e.has(s.toLowerCase())?U:r[s]);return n}function S(r,t){if(r===null||t.length===0)return r;let e;try{e=JSON.parse(r);}catch{return r}if(typeof e!="object"||e===null)return r;let n=new Set(t),s=L(e,n);return JSON.stringify(s)}function L(r,t){if(Array.isArray(r))return r.map(e=>L(e,t));if(typeof r=="object"&&r!==null){let e={};for(let n of Object.keys(r)){if(!Object.hasOwn(r,n))continue;let s=r[n];t.has(n)?e[n]=U:e[n]=L(s,t);}return e}return r}function $(r,t,e){if(e.length>0){for(let n of e)if(G(r,n))return false}if(t.length>0){for(let n of t)if(G(r,n))return true;return false}return true}function G(r,t){try{return t instanceof RegExp?t.test(r):ut(t).test(r)}catch{return console.warn(`[testrelic] Invalid URL filter pattern: ${String(t)}`),false}}function ut(r){let t="",e=0;for(;e<r.length;){let n=r[e];n==="*"&&r[e+1]==="*"?(t+=".*",e+=2,r[e]==="/"&&e++):n==="*"?(t+="[^/]*",e++):n==="?"?(t+="[^/]",e++):".+^${}()|[]\\".includes(n)?(t+="\\"+n,e++):(t+=n,e++);}return new RegExp(t)}var dt=["get","post","put","patch","delete","head","fetch"],pt=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function gt(r){let t=r.toLowerCase();return pt.some(e=>t.includes(e))}function ft(r){if(!r)return null;if(r.data!==void 0&&r.data!==null){let t=r.data;return typeof t=="string"?t:Buffer.isBuffer(t)?t.toString("base64"):JSON.stringify(t)}if(r.form!==void 0&&r.form!==null)return JSON.stringify(r.form);if(r.multipart!==void 0&&r.multipart!==null){let t=r.multipart,e={};for(let[n,s]of Object.entries(t))typeof s=="string"||typeof s=="number"||typeof s=="boolean"?e[n]=String(s):s&&typeof s=="object"&&"name"in s?e[n]=`[file: ${s.name}]`:e[n]="[binary]";return JSON.stringify(e)}return null}var q=class q{constructor(t,e,n){this.originals=new Map;this.apiCallWriter=null;this.callCounter=0;this.apiCallCount=0;this.disposed=false;this._lastCallId=null;this.primitiveCallIds=new Map;this.context=t,this.assertionTracker=e??null,this.apiConfig=n??q.DEFAULT_API_CONFIG;try{this.apiCallWriter=new h("api-calls");}catch{}}get lastCallId(){return this._lastCallId}getCallIdForValue(t){return t!=null&&typeof t=="object"?C.get(t)??null:this.primitiveCallIds.get(t)??null}intercept(){for(let e of dt){let n=this.context[e].bind(this.context);this.originals.set(e,n),this.context[e]=this.createWrapper(e,n);}let t=this.context.dispose.bind(this.context);this.originals.set("dispose",t),this.context.dispose=async e=>(this.disposed=true,t(e));}getFileData(){return this.apiCallWriter?.close(),{apiCallsFile:this.apiCallWriter?.getCount()?this.apiCallWriter.getPath():null,apiCallsCount:this.apiCallWriter?.getCount()??0}}flushLegacyAnnotations(t){}dispose(){for(let[t,e]of this.originals)this.context[t]=e;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,e){let n=this,s=t.headers.bind(t);t.headers=function(){let i=s();return C.set(i,e),i};let a=t.headersArray.bind(t);t.headersArray=function(){let i=a();return C.set(i,e),i};let p=t.json.bind(t);t.json=async function(){let i=await p();return i!=null&&typeof i=="object"&&C.set(i,e),i};let d=t.status.bind(t);t.status=function(){let i=d();return n.primitiveCallIds.set(i,e),i};let u=t.statusText.bind(t);t.statusText=function(){let i=u();return n.primitiveCallIds.set(i,e),i};let c=t.ok.bind(t);t.ok=function(){let i=c();return n.primitiveCallIds.set(i,e),i};let o=t.text.bind(t);t.text=async function(){let i=await o();return n.primitiveCallIds.set(i,e),i};let g=t.body.bind(t);t.body=async function(){let i=await g();return C.set(i,e),i};}createWrapper(t,e){let n=this;return async function(a,p){if(!$(a,n.apiConfig.apiIncludeUrls,n.apiConfig.apiExcludeUrls))return e(a,p);let d=`api-call-${n.callCounter++}`,u=new Date().toISOString(),c=t==="fetch"?(p?.method??"GET").toUpperCase():t.toUpperCase(),o=ft(p),g=perf_hooks.performance.now();n._lastCallId=d,n.assertionTracker&&n.assertionTracker.setCurrentCallId(d);let l;try{l=await e(a,p);}catch(i){let y=perf_hooks.performance.now();try{let R=n.apiConfig.captureRequestBody?S(o,n.apiConfig.redactBodyFields):null,m={id:d,timestamp:u,method:c,url:a,requestHeaders:null,requestBody:R,responseStatusCode:null,responseStatusText:null,responseHeaders:null,responseBody:null,responseTimeMs:Math.round((y-g)*100)/100,isBinary:!1,error:i instanceof Error?i.message:String(i)};n.apiCallWriter&&(n.apiCallWriter.append(m),n.apiCallCount++);}catch{}throw i}try{let i=perf_hooks.performance.now(),y=l.headers(),R=y["content-type"]??null,m=R?!gt(R):!1,T=null;n.apiConfig.captureRequestHeaders&&p?.headers&&(T=p.headers);let f=null;n.apiConfig.captureResponseHeaders&&(f=y);let w=n.apiConfig.captureRequestBody?o:null,k=null;if(n.apiConfig.captureResponseBody)try{m?k=(await l.body()).toString("base64"):k=await l.text();}catch{}T=B(T,n.apiConfig.redactHeaders),f=B(f,n.apiConfig.redactHeaders),w=S(w,n.apiConfig.redactBodyFields),k=S(k,n.apiConfig.redactBodyFields);let P={id:d,timestamp:u,method:c,url:l.url(),requestHeaders:T,requestBody:w,responseStatusCode:l.status(),responseStatusText:l.statusText(),responseHeaders:f,responseBody:k,responseTimeMs:Math.round((i-g)*100)/100,isBinary:m,error:null};n.apiCallWriter&&(n.apiCallWriter.append(P),n.apiCallCount++);}catch{}try{l[_]=d,n.tagResponseMethods(l,d);}catch{}return l}}};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 b=q;var ht=["text/","application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/graphql"];function yt(r){let t=r.toLowerCase();return ht.some(e=>t.includes(e))}var N=class r{constructor(t,e){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=e?.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 h("network")),this.consoleWriter=new h("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(e=>({url:e.url,navigationType:e.navigationType,timestamp:e.timestamp,domContentLoadedAt:e.domContentLoadedAt,networkIdleAt:e.networkIdleAt,networkStats:e.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(){this.page.goto=this.origGoto,this.page.goBack=this.origGoBack,this.page.goForward=this.origGoForward,this.page.reload=this.origReload;for(let{event:t,handler:e}of this.listeners)this.page.off(t,e);this.listeners=[],this.records=[],this.pendingRequests.clear(),this.pendingBodyReads=[],this.networkWriter?.close(),this.consoleWriter?.close();}getRecords(){return this.assembleNetworkStats(),this.records}interceptMethods(){let t=this,e=this.page;e.goto=async function(n,s){return t.recordNavigation(n,"goto"),t.origGoto(n,s)},e.goBack=async function(n){let s=await t.origGoBack(n);return t.recordNavigation(e.url(),"back"),s},e.goForward=async function(n){let s=await t.origGoForward(n);return t.recordNavigation(e.url(),"forward"),s},e.reload=async function(n){return t.recordNavigation(e.url(),"refresh"),t.origReload(n)};}attachListeners(){let t=()=>{this.lastDomContentLoaded=new Date().toISOString(),this.records.length>0&&(this.records[this.records.length-1].domContentLoadedAt=this.lastDomContentLoaded);};this.page.on("domcontentloaded",t),this.listeners.push({event:"domcontentloaded",handler:t});let e=s=>{try{let a=s;if(typeof a.parentFrame=="function"&&a.parentFrame()!==null)return;let p=a.url(),d=this.records[this.records.length-1];if(d&&Date.now()-new Date(d.timestamp).getTime()<50&&d.url===p)return;this.recordNavigation(p,"navigation");}catch{}};this.page.on("framenavigated",e),this.listeners.push({event:"framenavigated",handler:e});let n=s=>{try{let a=s,p=a.type(),d=a.text();if(p==="debug"&&d.startsWith("__testrelic_nav:")){try{let u=JSON.parse(d.slice(16));u.type&&u.url&&this.recordNavigation(u.url,u.type);}catch{}return}{let u=null;try{let o=a.location();o&&o.url&&(u=`${o.url}:${o.lineNumber}:${o.columnNumber}`);}catch{}let c=r.mapConsoleType(p);this.consoleWriter&&(this.consoleWriter.append({level:c,text:d,timestamp:new Date().toISOString(),location:u}),this.consoleLogCount++);}}catch{}};if(this.page.on("console",n),this.listeners.push({event:"console",handler:n}),this.includeNetworkStats){let s=d=>{let u=this.records.length-1,c=this.counterForNav(u);c&&c.totalRequests++;try{let o=d,g=String(this.requestIdCounter++),l=o.postData()??null,i={url:o.url(),method:o.method(),resourceType:this.mapResourceType(o.resourceType()),headers:o.headers(),postData:l,postDataTruncated:!1,startedAt:new Date().toISOString(),startTimeMs:Date.now(),navIndex:u};this.pendingRequests.set(g,i),d.__testrelic_id=g;}catch{}};this.page.on("request",s),this.listeners.push({event:"request",handler:s});let a=d=>{try{let u=d,c=u.request().__testrelic_id,o=c?this.pendingRequests.get(c):void 0,g=this.counterForNav(o?o.navIndex:this.records.length-1);if(g){let f=u.status();f>=400&&(g.failedRequests++,g.failedRequestUrls.push(f+" "+u.url()));let w=u.headers()["content-length"];w&&(g.totalBytes+=parseInt(w,10)||0);let k=u.request().resourceType(),P=this.mapResourceType(k);g.byType[P]++;}if(!c||!o)return;this.pendingRequests.delete(c);let l=Date.now()-o.startTimeMs,i=u.headers(),y=i["content-type"]??null,R=parseInt(i["content-length"]??"0",10)||0,m=y?!yt(y):!1,T=(async()=>{let f=null;if(!m)try{f=(await u.body()).toString("utf-8");}catch{}let w={url:o.url,method:o.method,resourceType:o.resourceType,statusCode:u.status(),responseTimeMs:l,startedAt:o.startedAt,requestHeaders:o.headers,requestBody:o.postData,responseBody:f,responseHeaders:i,contentType:y,responseSize:R,requestBodyTruncated:o.postDataTruncated,responseBodyTruncated:!1,isBinary:m,error:null};this.networkWriter&&(this.networkWriter.append(w),this.networkRequestCount++);})();this.pendingBodyReads.push(T);}catch{}};this.page.on("response",a),this.listeners.push({event:"response",handler:a});let p=d=>{let u=d.__testrelic_id,c=u?this.pendingRequests.get(u):void 0,o=this.counterForNav(c?c.navIndex:this.records.length-1);if(o){o.failedRequests++;try{let g=d;o.failedRequestUrls.push("ERR "+g.url());}catch{}}try{let g=d;if(!u||!c)return;this.pendingRequests.delete(u);let l={url:c.url,method:c.method,resourceType:c.resourceType,statusCode:0,responseTimeMs:Date.now()-c.startTimeMs,startedAt:c.startedAt,requestHeaders:c.headers,requestBody:c.postData,responseBody:null,responseHeaders:null,contentType:null,responseSize:0,requestBodyTruncated:c.postDataTruncated,responseBodyTruncated:!1,isBinary:!1,error:g.failure()?.errorText??"Unknown error"};this.networkWriter&&(this.networkWriter.append(l),this.networkRequestCount++);}catch{}};this.page.on("requestfailed",p),this.listeners.push({event:"requestfailed",handler:p});}}async injectSPADetection(){try{await this.page.addInitScript(()=>{let t=history.pushState.bind(history),e=history.replaceState.bind(history);history.pushState=function(...n){t(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_route",url:location.href}));},history.replaceState=function(...n){e(...n),console.debug("__testrelic_nav:"+JSON.stringify({type:"spa_replace",url:location.href}));},window.addEventListener("popstate",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"popstate",url:location.href}));}),window.addEventListener("hashchange",()=>{console.debug("__testrelic_nav:"+JSON.stringify({type:"hash_change",url:location.href}));});});}catch{}}recordNavigation(t,e){this.records.push({url:t,navigationType:e,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 e=this.navCounters[t];e&&(this.records[t].networkStats={totalRequests:e.totalRequests,failedRequests:e.failedRequests,failedRequestUrls:[...e.failedRequestUrls],totalBytes:e.totalBytes,byType:{...e.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"}}};x(test.expect);var mt="__testrelic_api_config",Ct="__testrelic_config_trackApiCalls";function O(r){let t=r.annotations.find(n=>n.type===mt&&n.description!==void 0);if(t)try{return JSON.parse(t.description,Rt)}catch{}let e=r.annotations.find(n=>n.type===Ct&&n.description!==void 0);return e?{trackApiCalls:e.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 Rt(r,t){if(typeof t=="object"&&t!==null&&t.__regexp===true&&typeof t.source=="string"){let{source:e,flags:n}=t;return new RegExp(e,n)}return t}var Tt={page:async({page:r},t,e)=>{let n=new N(r);try{await n.init();}catch{}await t(r);try{let{navigations:s,networkRequestsFile:a,networkRequestsCount:p,consoleLogsFile:d,consoleLogsCount:u}=await n.getFileData(),c={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:s,apiAssertions:[],networkRequestsFile:a,networkRequestsCount:p,consoleLogsFile:d,consoleLogsCount:u,apiCallsFile:null,apiCallsCount:0};await e.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(c)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}n.dispose();},request:async({request:r},t,e)=>{let n=O(e);if(!n.trackApiCalls){await t(r);return}let s=new A,a=new b(r,s,n);a.intercept(),v(s,a);try{await t(r);}finally{v(null,null);}try{let{apiCallsFile:p,apiCallsCount:d}=a.getFileData(),u=n.captureAssertions?s.getData():[],c={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:u,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:null,consoleLogsCount:0,apiCallsFile:p,apiCallsCount:d};await e.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(c)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};test.test.extend(Tt);var ce=x(test.expect),ue={request:async({request:r},t,e)=>{let n=O(e);if(!n.trackApiCalls){await t(r);return}let s=new A,a=new b(r,s,n);a.intercept(),v(s,a);let p=null;try{p=new h("api-console");}catch{}let d=0,u=process.stdout.write,c=process.stderr.write;process.stdout.write=function(o,...g){try{let l=typeof o=="string"?o:Buffer.isBuffer(o)?o.toString("utf-8"):String(o);!l.startsWith("[testrelic]")&&!l.startsWith("\u2139 TestRelic")&&!l.startsWith("\u2713 TestRelic")&&!l.startsWith("\u26A0 TestRelic")&&p&&(p.append({level:"stdout",text:l.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),d++);}catch{}return u.apply(process.stdout,[o,...g])},process.stderr.write=function(o,...g){try{let l=typeof o=="string"?o:Buffer.isBuffer(o)?o.toString("utf-8"):String(o);!l.startsWith("[testrelic]")&&!l.startsWith("\u26A0 TestRelic")&&p&&(p.append({level:"stderr",text:l.replace(/\n$/,""),timestamp:new Date().toISOString(),location:null}),d++);}catch{}return c.apply(process.stderr,[o,...g])};try{await t(r);}finally{process.stdout.write=u,process.stderr.write=c,v(null,null);}try{p?.close();let{apiCallsFile:o,apiCallsCount:g}=a.getFileData(),l=n.captureAssertions?s.getData():[],i={testRelicData:!0,version:core.PAYLOAD_VERSION,navigations:[],apiAssertions:l,networkRequestsFile:null,networkRequestsCount:0,consoleLogsFile:d>0?p?.getPath()??null:null,consoleLogsCount:d,apiCallsFile:o,apiCallsCount:g};await e.attach(core.ATTACHMENT_NAME,{body:Buffer.from(JSON.stringify(i)),contentType:core.ATTACHMENT_CONTENT_TYPE});}catch{}a.dispose(),s.dispose();}};exports.expect=ce;exports.testRelicApiFixture=ue;//# sourceMappingURL=api-fixture.cjs.map
5
5
  //# sourceMappingURL=api-fixture.cjs.map