@arvoretech/bug-jar 0.7.2 → 0.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -19
- package/dist/index.global.js +1 -1
- package/dist/index.js +9 -9
- package/dist/index.mjs +8 -8
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
"use strict";var W=Object.create;var v=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var V=Object.getPrototypeOf,Y=Object.prototype.hasOwnProperty;var Z=(
|
|
2
|
-
`);for(let
|
|
1
|
+
"use strict";var W=Object.create;var v=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var K=Object.getOwnPropertyNames;var V=Object.getPrototypeOf,Y=Object.prototype.hasOwnProperty;var Z=(o,e)=>{for(var t in e)v(o,t,{get:e[t],enumerable:!0})},M=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of K(e))!Y.call(o,r)&&r!==t&&v(o,r,{get:()=>e[r],enumerable:!(n=G(e,r))||n.enumerable});return o};var Q=(o,e,t)=>(t=o!=null?W(V(o)):{},M(e||!o||!o.__esModule?v(t,"default",{value:o,enumerable:!0}):t,o)),ee=o=>M(v({},"__esModule",{value:!0}),o);var ge={};Z(ge,{BugJar:()=>m,default:()=>me,exportAsZip:()=>$,generateSummary:()=>P,init:()=>X});module.exports=ee(ge);function h(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function I(o,e=1e4){try{let t=new WeakSet,n=JSON.stringify(o,(r,s)=>{if(typeof s=="object"&&s!==null){if(t.has(s))return"[Circular]";t.add(s)}return s instanceof Error?{message:s.message,stack:s.stack,name:s.name}:typeof s=="function"?"[Function]":s instanceof HTMLElement?f(s):s});return n&&n.length>e?n.slice(0,e)+"...[truncated]":n||""}catch{return"[Unserializable]"}}function f(o){if(!o||!(o instanceof Element))return"unknown";let e=o.tagName.toLowerCase(),t=o.id?`#${o.id}`:"",n=o.className&&typeof o.className=="string"?`.${o.className.trim().split(/\s+/).join(".")}`:"",r=o.textContent?.trim().slice(0,30)||"",s=r?` "${r}"`:"";return`${e}${t}${n}${s}`}function d(o,e){if(!o||typeof o!="object")return o;if(Array.isArray(o))return o.map(n=>d(n,e));let t={};for(let[n,r]of Object.entries(o))e.some(a=>n.toLowerCase().includes(a.toLowerCase()))?t[n]="[REDACTED]":typeof r=="object"&&r!==null?t[n]=d(r,e):t[n]=r;return t}var l=class{constructor(e){this.buffer=[];this.maxSize=e}push(e){this.buffer.length>=this.maxSize&&this.buffer.shift(),this.buffer.push(e)}getAll(){return[...this.buffer]}clear(){this.buffer=[]}get length(){return this.buffer.length}};var w=class{constructor(e){this.originalFetch=null;this.originalXhrOpen=null;this.originalXhrSend=null;this.originalXhrSetRequestHeader=null;this.originalSendBeacon=null;this.config=e,this.buffer=new l(e.maxNetworkEntries)}start(){this.interceptFetch(),this.interceptXHR(),this.interceptBeacon()}stop(){this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null),this.originalXhrOpen&&this.originalXhrSend&&(XMLHttpRequest.prototype.open=this.originalXhrOpen,XMLHttpRequest.prototype.send=this.originalXhrSend,this.originalXhrOpen=null,this.originalXhrSend=null),this.originalXhrSetRequestHeader&&(XMLHttpRequest.prototype.setRequestHeader=this.originalXhrSetRequestHeader,this.originalXhrSetRequestHeader=null),this.originalSendBeacon&&(Navigator.prototype.sendBeacon=this.originalSendBeacon,this.originalSendBeacon=null)}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}addIgnoreUrl(e){this.config.ignoreUrls||(this.config.ignoreUrls=[]),this.config.ignoreUrls.includes(e)||this.config.ignoreUrls.push(e)}getRawFetch(){return this.originalFetch??window.fetch.bind(window)}shouldIgnore(e){let t=this.config.ignoreUrls;return!t||t.length===0?!1:t.some(n=>e.includes(n))}resolveUrl(e){return typeof e=="string"?e:e instanceof URL?e.href:e.url}interceptFetch(){this.originalFetch=window.fetch.bind(window);let e=this;window.fetch=async function(t,n){if(e.shouldIgnore(e.resolveUrl(t)))return e.originalFetch(t,n);let r=performance.now(),s={id:h(),timestamp:Date.now(),method:(n?.method||"GET").toUpperCase(),url:typeof t=="string"?t:t instanceof URL?t.href:t.url,requestHeaders:e.extractHeaders(n?.headers),requestBody:e.safeParseBody(n?.body),status:null,statusText:"",responseHeaders:{},responseBody:null,responseSize:null,duration:null,type:"fetch",error:null,initiator:e.getInitiator()};try{let a=await e.originalFetch(t,n);s.status=a.status,s.statusText=a.statusText,s.responseHeaders=e.extractResponseHeaders(a.headers),s.duration=performance.now()-r;let c=a.clone();try{let i=await c.text();s.responseSize=i.length,s.responseBody=e.safeParseJson(i)}catch{s.responseBody="[Unable to read response]"}return s.requestBody=d(s.requestBody,e.config.sensitiveFields),s.responseBody=d(s.responseBody,e.config.sensitiveFields),e.buffer.push(s),a}catch(a){throw s.duration=performance.now()-r,s.error=a instanceof Error?a.message:String(a),e.buffer.push(s),a}}}interceptXHR(){this.originalXhrOpen=XMLHttpRequest.prototype.open,this.originalXhrSend=XMLHttpRequest.prototype.send,this.originalXhrSetRequestHeader=XMLHttpRequest.prototype.setRequestHeader;let e=this;XMLHttpRequest.prototype.open=function(t,n){return this.__bugjar_method=t,this.__bugjar_url=typeof n=="string"?n:n.href,this.__bugjar_headers={},e.originalXhrOpen.apply(this,arguments)},XMLHttpRequest.prototype.setRequestHeader=function(t,n){return this.__bugjar_headers&&(this.__bugjar_headers[t]=n),e.originalXhrSetRequestHeader.apply(this,arguments)},XMLHttpRequest.prototype.send=function(t){if(e.shouldIgnore(this.__bugjar_url||""))return e.originalXhrSend.apply(this,arguments);let n=performance.now(),r={id:h(),timestamp:Date.now(),method:(this.__bugjar_method||"GET").toUpperCase(),url:this.__bugjar_url||"",requestHeaders:this.__bugjar_headers||{},requestBody:e.safeParseBody(t),status:null,statusText:"",responseHeaders:{},responseBody:null,responseSize:null,duration:null,type:"xhr",error:null,initiator:e.getInitiator()};return this.addEventListener("load",function(){r.status=this.status,r.statusText=this.statusText,r.responseHeaders=e.parseXhrHeaders(this.getAllResponseHeaders()),r.duration=performance.now()-n;let s=e.readXhrResponse(this);r.responseSize=s.size,r.responseBody=s.body,r.requestBody=d(r.requestBody,e.config.sensitiveFields),r.responseBody=d(r.responseBody,e.config.sensitiveFields),e.buffer.push(r)}),this.addEventListener("error",function(){r.duration=performance.now()-n,r.error="Network error",e.buffer.push(r)}),this.addEventListener("timeout",function(){r.duration=performance.now()-n,r.error="Request timeout",e.buffer.push(r)}),e.originalXhrSend.apply(this,arguments)}}interceptBeacon(){if(!navigator.sendBeacon)return;this.originalSendBeacon=navigator.sendBeacon.bind(navigator);let e=this;Navigator.prototype.sendBeacon=function(t,n){let r=typeof t=="string"?t:t.href;if(e.shouldIgnore(r))return e.originalSendBeacon(t,n);let s={id:h(),timestamp:Date.now(),method:"POST",url:r,requestHeaders:{},requestBody:e.safeParseBody(n),status:null,statusText:"",responseHeaders:{},responseBody:null,responseSize:null,duration:null,type:"beacon",error:null,initiator:"sendBeacon"};return s.requestBody=d(s.requestBody,e.config.sensitiveFields),e.buffer.push(s),e.originalSendBeacon(t,n)}}extractHeaders(e){let t={};return e&&(e instanceof Headers?e.forEach((n,r)=>{t[r]=n}):Array.isArray(e)?e.forEach(([n,r])=>{t[n]=r}):Object.assign(t,e)),t}extractResponseHeaders(e){let t={};return e.forEach((n,r)=>{t[r]=n}),t}parseXhrHeaders(e){let t={};return e&&e.trim().split(/[\r\n]+/).forEach(n=>{let r=n.split(": "),s=r.shift();s&&(t[s]=r.join(": "))}),t}safeParseBody(e){if(!e)return null;if(typeof e=="string")return this.safeParseJson(e);if(e instanceof FormData){let t={};return e.forEach((n,r)=>{t[r]=n instanceof File?`[File: ${n.name}]`:n}),t}return e instanceof URLSearchParams?Object.fromEntries(e.entries()):e instanceof Blob?`[Blob: ${e.size} bytes]`:e instanceof ArrayBuffer?`[ArrayBuffer: ${e.byteLength} bytes]`:String(e)}readXhrResponse(e){try{let t=e.responseType;if(t===""||t==="text"){let r=e.responseText;return{size:r?.length||null,body:this.safeParseJson(r)}}let n=e.response;if(n==null)return{size:null,body:null};if(t==="json"){let r=JSON.stringify(n);return{size:r?.length||null,body:this.safeParseJson(r)}}return n instanceof Blob?{size:n.size,body:`[Blob: ${n.size} bytes]`}:n instanceof ArrayBuffer?{size:n.byteLength,body:`[ArrayBuffer: ${n.byteLength} bytes]`}:{size:null,body:`[${t}]`}}catch{return{size:null,body:"[Unable to read response]"}}}safeParseJson(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.length>5e3?e.slice(0,5e3)+"...[truncated]":e}}getInitiator(){try{let e=new Error().stack;if(!e)return null;let t=e.split(`
|
|
2
|
+
`);for(let n of t)if(!n.includes("bug-jar")&&n.includes("at "))return n.trim().slice(0,200);return null}catch{return null}}};var b=class{constructor(e){this.originals={};this.levels=["log","warn","error","info","debug"];this.buffer=new l(e.maxConsoleEntries)}start(){for(let e of this.levels){this.originals[e]=console[e].bind(console);let t=this;console[e]=(...n)=>{t.capture(e,n),t.originals[e](...n)}}}stop(){for(let e of this.levels)this.originals[e]&&(console[e]=this.originals[e]);this.originals={}}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}capture(e,t){let n={timestamp:Date.now(),level:e,args:t.map(r=>typeof r=="string"||typeof r=="number"||typeof r=="boolean"?r:JSON.parse(I(r))),stack:e==="error"||e==="warn"?this.getStack():null};this.buffer.push(n)}getStack(){try{return new Error().stack?.split(`
|
|
3
3
|
`).slice(4).join(`
|
|
4
|
-
`)||null}catch{return null}}};var S=class{constructor(e){this.errorHandler=null;this.rejectionHandler=null;this.resourceErrorHandler=null;this.buffer=new l(e.maxErrors)}start(){this.errorHandler=e=>{this.buffer.push({timestamp:Date.now(),message:e.message||"Unknown error",stack:e.error?.stack||null,filename:e.filename||null,lineno:e.lineno||null,colno:e.colno||null,type:"uncaught",context:this.getContext(e.error)})},this.rejectionHandler=e=>{let t=e.reason;this.buffer.push({timestamp:Date.now(),message:t instanceof Error?t.message:String(t),stack:t instanceof Error&&t.stack||null,filename:null,lineno:null,colno:null,type:"unhandledrejection",context:t instanceof Error?this.getContext(t):null})},this.resourceErrorHandler=e=>{let t=e.target;!t||!(t instanceof HTMLElement)||(t.tagName==="SCRIPT"||t.tagName==="LINK"||t.tagName==="IMG")&&this.buffer.push({timestamp:Date.now(),message:`Failed to load ${t.tagName.toLowerCase()}: ${t.src||t.href||"unknown"}`,stack:null,filename:t.src||t.href||null,lineno:null,colno:null,type:"resource",context:null})},window.addEventListener("error",this.errorHandler),window.addEventListener("unhandledrejection",this.rejectionHandler),window.addEventListener("error",this.resourceErrorHandler,!0)}stop(){this.errorHandler&&(window.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null),this.resourceErrorHandler&&(window.removeEventListener("error",this.resourceErrorHandler,!0),this.resourceErrorHandler=null)}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}getContext(e){if(!e)return null;try{let t=e.stack;if(!t)return null;let
|
|
4
|
+
`)||null}catch{return null}}};var S=class{constructor(e){this.errorHandler=null;this.rejectionHandler=null;this.resourceErrorHandler=null;this.buffer=new l(e.maxErrors)}start(){this.errorHandler=e=>{this.buffer.push({timestamp:Date.now(),message:e.message||"Unknown error",stack:e.error?.stack||null,filename:e.filename||null,lineno:e.lineno||null,colno:e.colno||null,type:"uncaught",context:this.getContext(e.error)})},this.rejectionHandler=e=>{let t=e.reason;this.buffer.push({timestamp:Date.now(),message:t instanceof Error?t.message:String(t),stack:t instanceof Error&&t.stack||null,filename:null,lineno:null,colno:null,type:"unhandledrejection",context:t instanceof Error?this.getContext(t):null})},this.resourceErrorHandler=e=>{let t=e.target;!t||!(t instanceof HTMLElement)||(t.tagName==="SCRIPT"||t.tagName==="LINK"||t.tagName==="IMG")&&this.buffer.push({timestamp:Date.now(),message:`Failed to load ${t.tagName.toLowerCase()}: ${t.src||t.href||"unknown"}`,stack:null,filename:t.src||t.href||null,lineno:null,colno:null,type:"resource",context:null})},window.addEventListener("error",this.errorHandler),window.addEventListener("unhandledrejection",this.rejectionHandler),window.addEventListener("error",this.resourceErrorHandler,!0)}stop(){this.errorHandler&&(window.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null),this.resourceErrorHandler&&(window.removeEventListener("error",this.resourceErrorHandler,!0),this.resourceErrorHandler=null)}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}getContext(e){if(!e)return null;try{let t=e.stack;if(!t)return null;let n=t.match(/at\s+(.+?)\s+\(/);return n?n[1]:null}catch{return null}}};var E=class{constructor(e){this.listeners=[];this.buffer=new l(e.maxUserActions)}start(){this.addListener("click",r=>{let s=r.target;this.buffer.push({timestamp:Date.now(),type:"click",target:f(s),metadata:{x:r.clientX,y:r.clientY,button:r.button}})},!0),this.addListener("input",r=>{let s=r.target,a=s.type==="password"||s.type==="hidden"||s.name?.toLowerCase().includes("password")||s.name?.toLowerCase().includes("token")||s.name?.toLowerCase().includes("secret");this.buffer.push({timestamp:Date.now(),type:"input",target:f(s),value:a?"[REDACTED]":s.value?.slice(0,50)||"",metadata:{inputType:s.type,name:s.name}})},!0),this.addListener("scroll",this.throttle(()=>{this.buffer.push({timestamp:Date.now(),type:"scroll",target:"window",metadata:{scrollX:window.scrollX,scrollY:window.scrollY,scrollHeight:document.documentElement.scrollHeight}})},500)),this.addListener("resize",this.throttle(()=>{this.buffer.push({timestamp:Date.now(),type:"resize",target:"window",metadata:{width:window.innerWidth,height:window.innerHeight}})},500)),this.addListener("visibilitychange",()=>{this.buffer.push({timestamp:Date.now(),type:"visibility",target:"document",value:document.visibilityState})}),this.addListener("copy",r=>{this.buffer.push({timestamp:Date.now(),type:"copy",target:f(r.target)})}),this.addListener("paste",r=>{this.buffer.push({timestamp:Date.now(),type:"paste",target:f(r.target)})});let e=history.pushState.bind(history),t=history.replaceState.bind(history),n=this;history.pushState=function(...r){return n.buffer.push({timestamp:Date.now(),type:"navigation",target:String(r[2]||window.location.href),metadata:{method:"pushState"}}),e(...r)},history.replaceState=function(...r){return n.buffer.push({timestamp:Date.now(),type:"navigation",target:String(r[2]||window.location.href),metadata:{method:"replaceState"}}),t(...r)},this.addListener("popstate",()=>{this.buffer.push({timestamp:Date.now(),type:"navigation",target:window.location.href,metadata:{method:"popstate"}})})}stop(){for(let{event:e,handler:t,options:n}of this.listeners)(e==="visibilitychange"?document:window).removeEventListener(e,t,n);this.listeners=[]}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}addListener(e,t,n){(e==="visibilitychange"?document:window).addEventListener(e,t,n),this.listeners.push({event:e,handler:t,options:n})}throttle(e,t){let n=0;return()=>{let r=Date.now();r-n>=t&&(n=r,e())}}};var k=class{collect(){return{userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language,languages:[...navigator.languages],timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timezoneOffset:new Date().getTimezoneOffset(),screenWidth:screen.width,screenHeight:screen.height,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,devicePixelRatio:window.devicePixelRatio,colorDepth:screen.colorDepth,cookiesEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack,online:navigator.onLine,hardwareConcurrency:navigator.hardwareConcurrency||0,maxTouchPoints:navigator.maxTouchPoints||0,vendor:navigator.vendor,connection:this.getConnection(),memory:this.getMemory()}}getConnection(){let e=navigator.connection;return e?{effectiveType:e.effectiveType||"unknown",downlink:e.downlink||0,rtt:e.rtt||0,saveData:e.saveData||!1}:null}getMemory(){let e=performance.memory;return e?{jsHeapSizeLimit:e.jsHeapSizeLimit,totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}:null}};var U=class{constructor(){this.lcp=null;this.fid=null;this.cls=null;this.observers=[]}start(){this.observeLCP(),this.observeFID(),this.observeCLS()}stop(){for(let e of this.observers)e.disconnect();this.observers=[]}collect(){let e=performance.getEntriesByType("navigation")[0],t=performance.getEntriesByType("paint"),n=performance.getEntriesByType("resource"),r=t.find(a=>a.name==="first-paint"),s=t.find(a=>a.name==="first-contentful-paint");return{navigationTiming:e?{redirectTime:e.redirectEnd-e.redirectStart,dnsTime:e.domainLookupEnd-e.domainLookupStart,tcpTime:e.connectEnd-e.connectStart,tlsTime:e.secureConnectionStart>0?e.connectEnd-e.secureConnectionStart:0,ttfb:e.responseStart-e.requestStart,downloadTime:e.responseEnd-e.responseStart,domParsing:e.domInteractive-e.responseEnd,domContentLoaded:e.domContentLoadedEventEnd-e.domContentLoadedEventStart,loadEvent:e.loadEventEnd-e.loadEventStart,totalTime:e.loadEventEnd-e.startTime}:{},resourceCount:n.length,totalTransferSize:n.reduce((a,c)=>a+(c.transferSize||0),0),domContentLoaded:e?e.domContentLoadedEventEnd-e.startTime:null,loadComplete:e?e.loadEventEnd-e.startTime:null,firstPaint:r?r.startTime:null,firstContentfulPaint:s?s.startTime:null,largestContentfulPaint:this.lcp,firstInputDelay:this.fid,cumulativeLayoutShift:this.cls,timeToInteractive:null}}observeLCP(){try{let e=new PerformanceObserver(t=>{let n=t.getEntries();n.length>0&&(this.lcp=n[n.length-1].startTime)});e.observe({type:"largest-contentful-paint",buffered:!0}),this.observers.push(e)}catch{}}observeFID(){try{let e=new PerformanceObserver(t=>{let n=t.getEntries();n.length>0&&(this.fid=n[0].processingStart-n[0].startTime)});e.observe({type:"first-input",buffered:!0}),this.observers.push(e)}catch{}}observeCLS(){try{let e=0,t=new PerformanceObserver(n=>{for(let r of n.getEntries())r.hadRecentInput||(e+=r.value);this.cls=e});t.observe({type:"layout-shift",buffered:!0}),this.observers.push(t)}catch{}}};var C=class{constructor(e){this.config=e}collect(){return{localStorage:this.config.captureLocalStorage?this.collectStorage(localStorage):{},sessionStorage:this.config.captureSessionStorage?this.collectStorage(sessionStorage):{},cookies:this.config.captureCookies?this.collectCookies():[]}}collectStorage(e){let t={};try{for(let n=0;n<e.length;n++){let r=e.key(n);if(!r)continue;if(this.config.sensitiveFields.some(a=>r.toLowerCase().includes(a.toLowerCase())))t[r]="[REDACTED]";else{let a=e.getItem(r)||"";t[r]=a.length>500?a.slice(0,500)+"...[truncated]":a}}}catch{}return t}collectCookies(){try{return document.cookie.split(";").map(e=>e.trim().split("=")[0]).filter(Boolean)}catch{return[]}}};var R=class{async capture(){try{let e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return null;let n=window.innerWidth,r=window.innerHeight,s=Math.min(window.devicePixelRatio,2);e.width=n*s,e.height=r*s,t.scale(s,s);let a=this.domToSvg(n,r);return a?new Promise(c=>{let i=new Image;i.onload=()=>{t.drawImage(i,0,0);try{let u=e.toDataURL("image/png",.8);c(u)}catch{c(null)}},i.onerror=()=>c(null),i.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(a)}`,setTimeout(()=>c(null),3e3)}):null}catch{return null}}domToSvg(e,t){try{let n=document.documentElement.cloneNode(!0);n.querySelectorAll("script").forEach(a=>a.remove());let s=new XMLSerializer().serializeToString(n);return`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}">
|
|
5
5
|
<foreignObject width="100%" height="100%">
|
|
6
|
-
${
|
|
6
|
+
${s}
|
|
7
7
|
</foreignObject>
|
|
8
|
-
</svg>`}catch{return null}}captureHtml(){try{let e=document.documentElement.cloneNode(!0);return e.querySelectorAll("script").forEach(
|
|
8
|
+
</svg>`}catch{return null}}captureHtml(){try{let e=document.documentElement.cloneNode(!0);return e.querySelectorAll("script").forEach(r=>r.remove()),e.querySelectorAll('input[type="password"], input[name*="token"], input[name*="secret"]').forEach(r=>r.value="[REDACTED]"),e.outerHTML.slice(0,5e5)}catch{return null}}};var x=class{collect(){let e={},t=!1,n=window.posthog;if(n?.getFeatureFlag)try{let c=n.getAllFlags?.()||n.getFeatureFlags?.()||{};e.posthog=c,t=!0}catch{}let r=window.ldclient;if(r?.allFlags)try{e.launchdarkly=r.allFlags(),t=!0}catch{}let s=window.statsig;if(s?.getExperiment||s?.checkGate)try{e.statsig={detected:!0},t=!0}catch{}let a=window.unleash;if(a?.getAllToggles)try{e.unleash=a.getAllToggles(),t=!0}catch{}return t?e:null}};var T=class{constructor(){this.mediaRecorder=null;this.chunks=[];this.stream=null;this.recording=!1;this.onChunk=null}get isRecording(){return this.recording}setChunkHandler(e){this.onChunk=e}async start(){if(!this.recording)try{this.stream=await navigator.mediaDevices.getDisplayMedia({video:{frameRate:15},audio:!1,preferCurrentTab:!0}),this.chunks=[],this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:this.getSupportedMimeType(),videoBitsPerSecond:1e6}),this.mediaRecorder.ondataavailable=e=>{e.data.size>0&&(this.chunks.push(e.data),this.onChunk&&e.data.arrayBuffer().then(t=>this.onChunk?.(new Uint8Array(t),!1)).catch(()=>{}))},this.mediaRecorder.onstop=()=>{this.recording=!1,this.stopTracks()},this.stream.getVideoTracks()[0].onended=()=>{this.stop()},this.mediaRecorder.start(1e3),this.recording=!0}catch{this.recording=!1,this.stream=null,this.mediaRecorder=null}}stop(){return new Promise(e=>{if(!this.mediaRecorder||!this.recording){e(null);return}this.mediaRecorder.onstop=()=>{this.recording=!1,this.stopTracks();let t=new Blob(this.chunks,{type:this.getSupportedMimeType()});this.chunks=[],e(t)},this.mediaRecorder.stop()})}stopTracks(){this.stream&&(this.stream.getTracks().forEach(e=>e.stop()),this.stream=null)}getSupportedMimeType(){let e=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"];for(let t of e)if(MediaRecorder.isTypeSupported(t))return t;return"video/webm"}};var A=class{constructor(){this.container=null}mount(){this.container||(this.container=document.createElement("div"),this.container.id="bug-jar-session-border",this.container.setAttribute("aria-hidden","true"),this.container.innerHTML=`
|
|
9
9
|
<div class="bug-jar-session-border-glow"></div>
|
|
10
10
|
<div class="bug-jar-session-pill">
|
|
11
11
|
<span class="bug-jar-session-pill-dot"></span>
|
|
@@ -80,7 +80,7 @@
|
|
|
80
80
|
.bug-jar-session-border-glow { animation: none; }
|
|
81
81
|
.bug-jar-session-pill-dot { animation: none; }
|
|
82
82
|
}
|
|
83
|
-
`,document.head.appendChild(e)}};function j(){if(typeof window>"u")return null;try{return new URLSearchParams(window.location.search).get("debug")}catch{return null}}async function _(
|
|
84
|
-
`)}function oe(
|
|
85
|
-
`);this.dataUploader.pushChunk(a,t)};this.dataInterval=setInterval(()=>e(!1),5e3)}registerFlushHandlers(){let e=()=>{this.finalizePage()};window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e()})}async finalizePage(){if(this.finalized||!this.debugSession)return;this.finalized=!0,this.dataInterval&&(clearInterval(this.dataInterval),this.dataInterval=null);let e={pageId:this.pageId,timestamp:Date.now(),url:window.location.href,final:!0,network:this.network.getEntries().filter(
|
|
86
|
-
`);this.dataUploader?.pushChunk(t,!0),await this.screenRecorder.stop(),await Promise.allSettled([this.dataUploader?.flush()??Promise.resolve(),this.videoUploader?.flush()??Promise.resolve()])}async runSpeedtest(e,t,
|
|
83
|
+
`,document.head.appendChild(e)}};function j(){if(typeof window>"u")return null;try{return new URLSearchParams(window.location.search).get("debug")}catch{return null}}async function _(o,e,t=fetch){let n=`${o.replace(/\/$/,"")}/${encodeURIComponent(e)}`,r=await t(n,{method:"GET",credentials:"include"});if(!r.ok){let s=new Error(`Failed to load debug session (${r.status})`);throw s.status=r.status,s}return await r.json()}function q(o,e=fetch){let t=o.replace(/\/$/,"");return async n=>{let r=`${t}/${encodeURIComponent(n.token)}/chunk-url`,s=await e(r,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({pageId:n.pageId,stream:n.stream,seq:n.seq})});if(!s.ok)throw new Error(`Failed to get chunk URL (${s.status})`);return await s.json()}}async function O(o,e,t,n,r=fetch){let a=`${o.replace(/\/$/,"")}/${encodeURIComponent(e)}/meta`;await r(a,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",keepalive:!0,body:JSON.stringify({pageId:t,meta:n})})}async function te(){let o=await import("libsodium-wrappers"),e=o.default??o;return await e.ready,e}function ne(o){let e=atob(o),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}var re=[66,74,83,49],L=class{constructor(){this.sodium=null;this.state=null;this.headerEnvelope=null}async init(e){let t=await te();this.sodium=t;let n=ne(e),r=t.crypto_secretstream_xchacha20poly1305_keygen(),s=t.crypto_box_seal(r,n),{state:a,header:c}=t.crypto_secretstream_xchacha20poly1305_init_push(r);this.state=a;let i=new Uint8Array(re),u=new Uint8Array([1]),p=new Uint8Array(4);new DataView(p.buffer).setUint32(0,s.length,!0);let g=se([i,u,p,s,c]);return this.headerEnvelope=g,g}get header(){if(!this.headerEnvelope)throw new Error("StreamEncryptor not initialized");return this.headerEnvelope}encryptChunk(e,t=!1){if(!this.sodium||!this.state)throw new Error("StreamEncryptor not initialized");let n=t?this.sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL:this.sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;return this.sodium.crypto_secretstream_xchacha20poly1305_push(this.state,e,null,n)}};function se(o){let e=o.reduce((r,s)=>r+s.length,0),t=new Uint8Array(e),n=0;for(let r of o)t.set(r,n),n+=r.length;return t}var y=class{constructor(e,t,n,r,s,a=fetch){this.token=e;this.pageId=t;this.stream=n;this.publicKey=r;this.fetchChunkUrl=s;this.rawFetch=a;this.encryptor=new L;this.seq=0;this.initialized=!1;this.queue=Promise.resolve()}async ensureInit(){if(this.initialized)return;this.initialized=!0;let e=await this.encryptor.init(this.publicKey);await this.putChunk(e)}pushChunk(e,t=!1){this.queue=this.queue.then(async()=>{await this.ensureInit();let n=this.encryptor.encryptChunk(e,t);await this.putChunk(n)})}async flush(){await this.queue}async putChunk(e){let{uploadUrl:t}=await this.fetchChunkUrl({token:this.token,pageId:this.pageId,stream:this.stream,seq:this.seq});this.seq+=1,await this.rawFetch(t,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:e})}};var B=class{constructor(e,t,n=fetch){this.baseUrl=e;this.token=t;this.rawFetch=n}async run(){let e=performance.now(),t={ranAt:Date.now(),latencyMs:null,jitterMs:null,downloadMbps:null,uploadMbps:null,durationMs:0};try{let n=await this.measureLatency();t.latencyMs=n.min,t.jitterMs=n.jitter}catch{}try{t.downloadMbps=await this.measureDownload()}catch{}try{t.uploadMbps=await this.measureUpload()}catch{}return t.durationMs=Math.round(performance.now()-e),t}url(e){return`${this.baseUrl.replace(/\/$/,"")}/${encodeURIComponent(this.token)}/${e}`}async measureLatency(){let e=[];for(let s=0;s<5;s++){let a=performance.now();await this.rawFetch(this.url(`speedtest/ping?n=${s}`),{cache:"no-store"}),e.push(performance.now()-a)}let t=Math.min(...e),n=e.reduce((s,a)=>s+a,0)/e.length,r=e.reduce((s,a)=>s+Math.abs(a-n),0)/e.length;return{min:Math.round(t),jitter:Math.round(r)}}async measureDownload(){let e=Math.floor(2097152),t=performance.now(),n=Array.from({length:4},(c,i)=>this.rawFetch(this.url(`speedtest/download?bytes=${e}&s=${i}`),{cache:"no-store"}).then(u=>u.arrayBuffer())),r=await Promise.all(n),s=(performance.now()-t)/1e3,a=r.reduce((c,i)=>c+i.byteLength,0);return this.toMbps(a,s)}async measureUpload(){let e=new Uint8Array(4194304);crypto.getRandomValues(e.subarray(0,Math.min(65536,4194304)));let t=performance.now();await this.rawFetch(this.url("speedtest/upload"),{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:e});let n=(performance.now()-t)/1e3;return this.toMbps(4194304,n)}toMbps(e,t){return t<=0?0:Math.round(e*8/t/1e6*100)/100}};var D="bug-jar-session";function z(){if(typeof window>"u"||typeof document>"u")return;let o=window.location.hostname;if(/^[0-9.]+$/.test(o)||o==="localhost")return;let e=o.split(".");if(e.length<2)return;let t="bug-jar-domain-probe";for(let n=e.length-2;n>=0;n--){let r=`.${e.slice(n).join(".")}`;document.cookie=`${t}=1; Path=/; Domain=${r}; SameSite=Lax`;let s=document.cookie.includes(`${t}=1`);if(document.cookie=`${t}=; Path=/; Domain=${r}; Expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax`,s)return r}}function N(){if(typeof document>"u")return null;let o=document.cookie.split("; ").find(t=>t.startsWith(`${D}=`));if(!o)return null;let e=o.slice(D.length+1);return e?decodeURIComponent(e):null}function H(o,e){if(typeof document>"u")return;let t=z(),n=new Date(e).toUTCString(),r=window.location.protocol==="https:"?"; Secure":"",s=t?`; Domain=${t}`:"";document.cookie=`${D}=${encodeURIComponent(o)}; Path=/; Expires=${n}; SameSite=Lax${s}${r}`}function F(){if(typeof document>"u")return;let o=z(),e=o?`; Domain=${o}`:"";document.cookie=`${D}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax${e}`}function P(o){let e=[];e.push(`Bug Report: ${o.id}`),e.push(`URL: ${o.url}`),e.push(`Time: ${new Date(o.timestamp).toISOString()}`),e.push(`User Description: "${o.userDescription}"`),e.push(""),e.push("## Environment"),e.push(`Browser: ${oe(o.environment.userAgent)}`),e.push(`Viewport: ${o.environment.viewportWidth}x${o.environment.viewportHeight}`),e.push(`Connection: ${o.environment.connection?.effectiveType||"unknown"}`),e.push(`Online: ${o.environment.online}`),e.push(""),e.push("## Network Activity");let t=o.network.length,n=o.network.filter(i=>i.error||i.status&&i.status>=400),r=o.network.filter(i=>i.duration&&i.duration>3e3);if(e.push(`Total requests: ${t}`),n.length>0){e.push(`Failed requests (${n.length}):`);for(let i of n)e.push(` - ${i.method} ${i.url} \u2192 ${i.error||`HTTP ${i.status}`}`)}if(r.length>0){e.push(`Slow requests >3s (${r.length}):`);for(let i of r)e.push(` - ${i.method} ${i.url} (${Math.round(i.duration)}ms)`)}if(e.push(""),e.push("## Errors"),o.errors.length===0)e.push("No errors captured.");else{e.push(`Total errors: ${o.errors.length}`);for(let i of o.errors)e.push(` - [${i.type}] ${i.message}`),i.filename&&e.push(` at ${i.filename}:${i.lineno}:${i.colno}`)}e.push(""),e.push("## Console");let s={log:0,warn:0,error:0,info:0,debug:0};for(let i of o.console)s[i.level]++;e.push(`Logs: ${s.log}, Warnings: ${s.warn}, Errors: ${s.error}, Info: ${s.info}, Debug: ${s.debug}`);let a=o.console.filter(i=>i.level==="error");if(a.length>0){e.push("Console errors:");for(let i of a)e.push(` - ${i.args.map(u=>typeof u=="string"?u:JSON.stringify(u)).join(" ")}`)}e.push(""),e.push("## User Actions"),e.push(`Total actions: ${o.userActions.length}`);let c={};for(let i of o.userActions)c[i.type]=(c[i.type]||0)+1;for(let[i,u]of Object.entries(c))e.push(` - ${i}: ${u}`);if(o.userActions.length>0){let i=o.userActions[0].timestamp,p=((o.userActions[o.userActions.length-1].timestamp-i)/1e3).toFixed(1);e.push(`Session duration: ${p}s`)}if(e.push(""),o.performance){e.push("## Performance");let i=o.performance;i.largestContentfulPaint&&e.push(`LCP: ${Math.round(i.largestContentfulPaint)}ms`),i.firstInputDelay&&e.push(`FID: ${Math.round(i.firstInputDelay)}ms`),i.cumulativeLayoutShift!==null&&e.push(`CLS: ${i.cumulativeLayoutShift?.toFixed(3)}`),i.loadComplete&&e.push(`Page Load: ${Math.round(i.loadComplete)}ms`),e.push(`Resources: ${i.resourceCount} (${ie(i.totalTransferSize)})`)}return e.join(`
|
|
84
|
+
`)}function oe(o){return o.includes("Chrome/")?`Chrome ${o.match(/Chrome\/(\d+)/)?.[1]||""}`:o.includes("Firefox/")?`Firefox ${o.match(/Firefox\/(\d+)/)?.[1]||""}`:o.includes("Safari/")&&!o.includes("Chrome")?`Safari ${o.match(/Version\/(\d+)/)?.[1]||""}`:o.slice(0,50)}function ie(o){return o<1024?`${o}B`:o<1024*1024?`${(o/1024).toFixed(1)}KB`:`${(o/(1024*1024)).toFixed(1)}MB`}async function $(o,e){let t=[],n=JSON.stringify(o,null,2);t.push({name:"report.json",content:new TextEncoder().encode(n)});let r=P(o);if(t.push({name:"summary.md",content:new TextEncoder().encode(r)}),o.screenshot){let s=ae(o.screenshot);s&&t.push({name:"screenshot.png",content:s})}if(e){let s=new Uint8Array(await e.arrayBuffer());t.push({name:"recording.webm",content:s})}return ce(t)}function ae(o){try{let e=o.split(",")[1];if(!e)return null;let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}catch{return null}}function ce(o){let e=[],t=[],n=0;for(let i of o){let u=new TextEncoder().encode(i.name),p=pe(i.content),g=ue(u,i.content.length,p);e.push(g),e.push(u),e.push(i.content);let J=le(u,i.content.length,p,n);t.push(J),t.push(u),n+=g.length+u.length+i.content.length}let r=n,s=0;for(let i of t)s+=i.length;let a=de(o.length,s,r),c=[...e,...t,a].map(i=>i.buffer);return new Blob(c,{type:"application/zip"})}function ue(o,e,t){let n=new Uint8Array(30),r=new DataView(n.buffer);return r.setUint32(0,67324752,!0),r.setUint16(4,20,!0),r.setUint16(6,0,!0),r.setUint16(8,0,!0),r.setUint16(10,0,!0),r.setUint16(12,0,!0),r.setUint32(14,t,!0),r.setUint32(18,e,!0),r.setUint32(22,e,!0),r.setUint16(26,o.length,!0),r.setUint16(28,0,!0),n}function le(o,e,t,n){let r=new Uint8Array(46),s=new DataView(r.buffer);return s.setUint32(0,33639248,!0),s.setUint16(4,20,!0),s.setUint16(6,20,!0),s.setUint16(8,0,!0),s.setUint16(10,0,!0),s.setUint16(12,0,!0),s.setUint16(14,0,!0),s.setUint32(16,t,!0),s.setUint32(20,e,!0),s.setUint32(24,e,!0),s.setUint16(28,o.length,!0),s.setUint16(30,0,!0),s.setUint16(32,0,!0),s.setUint16(34,0,!0),s.setUint16(36,0,!0),s.setUint32(38,0,!0),s.setUint32(42,n,!0),r}function de(o,e,t){let n=new Uint8Array(22),r=new DataView(n.buffer);return r.setUint32(0,101010256,!0),r.setUint16(4,0,!0),r.setUint16(6,0,!0),r.setUint16(8,o,!0),r.setUint16(10,o,!0),r.setUint32(12,e,!0),r.setUint32(16,t,!0),r.setUint16(20,0,!0),n}function pe(o){let e=4294967295;for(let t=0;t<o.length;t++){e^=o[t];for(let n=0;n<8;n++)e=e>>>1^(e&1?3988292384:0)}return(e^4294967295)>>>0}var he="0.7.2",fe={maxNetworkEntries:100,maxConsoleEntries:200,maxUserActions:150,maxErrors:50,captureScreenshot:!0,captureHtmlSnapshot:!0,captureCookies:!0,captureLocalStorage:!0,captureSessionStorage:!0,capturePerformance:!0,captureWebVitals:!0,captureMemory:!0,captureConnectivity:!0,sensitiveFields:["password","token","secret","authorization","cookie","session","credit_card","cvv","ssn","cpf"],endpoint:void 0,onCapture:void 0,debugToken:void 0,debugSessionEndpoint:void 0},m=class{constructor(e={}){this.sessionBorder=null;this.debugSession=null;this.dataUploader=null;this.videoUploader=null;this.pageId=h();this.dataInterval=null;this.lastFlushTs=0;this.finalized=!1;this.started=!1;this.config={...fe,...e},this.network=new w(this.config),this.console=new b(this.config),this.errors=new S(this.config),this.userActions=new E(this.config),this.environment=new k,this.performance=new U,this.storage=new C(this.config),this.screenshot=new R,this.featureFlags=new x,this.screenRecorder=new T}start(){if(this.started)return;this.started=!0,this.network.start(),this.console.start(),this.errors.start(),this.userActions.start(),this.config.captureWebVitals&&this.performance.start();let e=this.config.debugToken??j(),t=e??N();e&&H(e,Date.now()+1440*60*1e3),t&&this.startDebugSession(t)}stop(){this.started&&(this.started=!1,this.network.stop(),this.console.stop(),this.errors.stop(),this.userActions.stop(),this.performance.stop(),this.sessionBorder?.unmount())}async startRecording(){await this.screenRecorder.start()}get isRecording(){return this.screenRecorder.isRecording}async capture(e=""){let t={id:h(),timestamp:Date.now(),url:window.location.href,title:document.title,userDescription:e,environment:this.environment.collect(),network:this.network.getEntries(),console:this.console.getEntries(),errors:this.errors.getEntries(),userActions:this.userActions.getEntries(),performance:this.config.capturePerformance?this.performance.collect():null,storage:this.storage.collect(),screenshot:this.config.captureScreenshot?await this.screenshot.capture():null,htmlSnapshot:this.config.captureHtmlSnapshot?this.screenshot.captureHtml():null,featureFlags:this.featureFlags.collect(),metadata:{},version:he};return this.config.onCapture&&this.config.onCapture(t),t}async captureAndExport(e=""){let t=await this.screenRecorder.stop(),n=await this.capture(e);if(this.config.endpoint)if(t){let r=new FormData;r.append("report",JSON.stringify(n)),r.append("video",t,"recording.webm"),await fetch(this.config.endpoint,{method:"POST",body:r})}else await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});else{let r=await $(n,t),s=URL.createObjectURL(r),a=document.createElement("a");a.href=s,a.download=`bug-report-${n.id}.zip`,a.click(),URL.revokeObjectURL(s)}return n}getReport(){return this.capture()}async startDebugSession(e){if(!this.config.debugSessionEndpoint)return;let t=this.config.debugSessionEndpoint,n=()=>{this.sessionBorder=new A,this.sessionBorder.mount()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",n):n();try{let r=this.network.getRawFetch();this.debugSession=await _(t,e,r),H(this.debugSession.token,this.debugSession.expiresAt);let s=q(t,r);this.dataUploader=new y(this.debugSession.token,this.pageId,"data",this.debugSession.publicKey,s,r),this.videoUploader=new y(this.debugSession.token,this.pageId,"video",this.debugSession.publicKey,s,r),this.runSpeedtest(t,this.debugSession.token,r),this.startDataStreaming(),this.registerFlushHandlers(),this.screenRecorder.setChunkHandler(a=>{this.videoUploader?.pushChunk(a)}),this.screenRecorder.start()}catch(r){this.sessionBorder?.unmount();let s=r?.status;(s===401||s===403||s===404)&&F()}}startDataStreaming(){let e=t=>{if(!this.dataUploader)return;let n=this.lastFlushTs,r=Date.now(),s={pageId:this.pageId,timestamp:r,url:window.location.href,network:this.network.getEntries().filter(c=>c.timestamp>n),console:this.console.getEntries().filter(c=>c.timestamp>n),errors:this.errors.getEntries().filter(c=>c.timestamp>n),userActions:this.userActions.getEntries().filter(c=>c.timestamp>n)};this.lastFlushTs=r;let a=new TextEncoder().encode(JSON.stringify(s)+`
|
|
85
|
+
`);this.dataUploader.pushChunk(a,t)};this.dataInterval=setInterval(()=>e(!1),5e3)}registerFlushHandlers(){let e=()=>{this.finalizePage()};window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e()})}async finalizePage(){if(this.finalized||!this.debugSession)return;this.finalized=!0,this.dataInterval&&(clearInterval(this.dataInterval),this.dataInterval=null);let e={pageId:this.pageId,timestamp:Date.now(),url:window.location.href,final:!0,network:this.network.getEntries().filter(n=>n.timestamp>this.lastFlushTs),console:this.console.getEntries().filter(n=>n.timestamp>this.lastFlushTs),errors:this.errors.getEntries().filter(n=>n.timestamp>this.lastFlushTs),userActions:this.userActions.getEntries().filter(n=>n.timestamp>this.lastFlushTs),storage:this.storage.collect(),featureFlags:this.featureFlags.collect(),screenshot:this.config.captureScreenshot?await this.screenshot.capture():null},t=new TextEncoder().encode(JSON.stringify(e)+`
|
|
86
|
+
`);this.dataUploader?.pushChunk(t,!0),await this.screenRecorder.stop(),await Promise.allSettled([this.dataUploader?.flush()??Promise.resolve(),this.videoUploader?.flush()??Promise.resolve()])}async runSpeedtest(e,t,n){let r=null;try{r=await new B(e,t,n).run()}catch{}await O(e,t,this.pageId,{url:window.location.href,title:document.title,startedAt:Date.now(),environment:this.environment.collect(),speedtest:r},n)}endDebugSession(){F(),this.sessionBorder?.unmount(),this.finalizePage()}};function X(o={}){let e=new m(o);return e.start(),e}typeof window<"u"&&(window.BugJar={BugJar:m,init:X});var me=m;0&&(module.exports={BugJar,exportAsZip,generateSummary,init});
|
package/dist/index.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
function h(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function F(o,e=1e4){try{let t=new WeakSet,
|
|
2
|
-
`);for(let
|
|
1
|
+
function h(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function F(o,e=1e4){try{let t=new WeakSet,n=JSON.stringify(o,(r,s)=>{if(typeof s=="object"&&s!==null){if(t.has(s))return"[Circular]";t.add(s)}return s instanceof Error?{message:s.message,stack:s.stack,name:s.name}:typeof s=="function"?"[Function]":s instanceof HTMLElement?f(s):s});return n&&n.length>e?n.slice(0,e)+"...[truncated]":n||""}catch{return"[Unserializable]"}}function f(o){if(!o||!(o instanceof Element))return"unknown";let e=o.tagName.toLowerCase(),t=o.id?`#${o.id}`:"",n=o.className&&typeof o.className=="string"?`.${o.className.trim().split(/\s+/).join(".")}`:"",r=o.textContent?.trim().slice(0,30)||"",s=r?` "${r}"`:"";return`${e}${t}${n}${s}`}function d(o,e){if(!o||typeof o!="object")return o;if(Array.isArray(o))return o.map(n=>d(n,e));let t={};for(let[n,r]of Object.entries(o))e.some(a=>n.toLowerCase().includes(a.toLowerCase()))?t[n]="[REDACTED]":typeof r=="object"&&r!==null?t[n]=d(r,e):t[n]=r;return t}var l=class{constructor(e){this.buffer=[];this.maxSize=e}push(e){this.buffer.length>=this.maxSize&&this.buffer.shift(),this.buffer.push(e)}getAll(){return[...this.buffer]}clear(){this.buffer=[]}get length(){return this.buffer.length}};var v=class{constructor(e){this.originalFetch=null;this.originalXhrOpen=null;this.originalXhrSend=null;this.originalXhrSetRequestHeader=null;this.originalSendBeacon=null;this.config=e,this.buffer=new l(e.maxNetworkEntries)}start(){this.interceptFetch(),this.interceptXHR(),this.interceptBeacon()}stop(){this.originalFetch&&(window.fetch=this.originalFetch,this.originalFetch=null),this.originalXhrOpen&&this.originalXhrSend&&(XMLHttpRequest.prototype.open=this.originalXhrOpen,XMLHttpRequest.prototype.send=this.originalXhrSend,this.originalXhrOpen=null,this.originalXhrSend=null),this.originalXhrSetRequestHeader&&(XMLHttpRequest.prototype.setRequestHeader=this.originalXhrSetRequestHeader,this.originalXhrSetRequestHeader=null),this.originalSendBeacon&&(Navigator.prototype.sendBeacon=this.originalSendBeacon,this.originalSendBeacon=null)}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}addIgnoreUrl(e){this.config.ignoreUrls||(this.config.ignoreUrls=[]),this.config.ignoreUrls.includes(e)||this.config.ignoreUrls.push(e)}getRawFetch(){return this.originalFetch??window.fetch.bind(window)}shouldIgnore(e){let t=this.config.ignoreUrls;return!t||t.length===0?!1:t.some(n=>e.includes(n))}resolveUrl(e){return typeof e=="string"?e:e instanceof URL?e.href:e.url}interceptFetch(){this.originalFetch=window.fetch.bind(window);let e=this;window.fetch=async function(t,n){if(e.shouldIgnore(e.resolveUrl(t)))return e.originalFetch(t,n);let r=performance.now(),s={id:h(),timestamp:Date.now(),method:(n?.method||"GET").toUpperCase(),url:typeof t=="string"?t:t instanceof URL?t.href:t.url,requestHeaders:e.extractHeaders(n?.headers),requestBody:e.safeParseBody(n?.body),status:null,statusText:"",responseHeaders:{},responseBody:null,responseSize:null,duration:null,type:"fetch",error:null,initiator:e.getInitiator()};try{let a=await e.originalFetch(t,n);s.status=a.status,s.statusText=a.statusText,s.responseHeaders=e.extractResponseHeaders(a.headers),s.duration=performance.now()-r;let c=a.clone();try{let i=await c.text();s.responseSize=i.length,s.responseBody=e.safeParseJson(i)}catch{s.responseBody="[Unable to read response]"}return s.requestBody=d(s.requestBody,e.config.sensitiveFields),s.responseBody=d(s.responseBody,e.config.sensitiveFields),e.buffer.push(s),a}catch(a){throw s.duration=performance.now()-r,s.error=a instanceof Error?a.message:String(a),e.buffer.push(s),a}}}interceptXHR(){this.originalXhrOpen=XMLHttpRequest.prototype.open,this.originalXhrSend=XMLHttpRequest.prototype.send,this.originalXhrSetRequestHeader=XMLHttpRequest.prototype.setRequestHeader;let e=this;XMLHttpRequest.prototype.open=function(t,n){return this.__bugjar_method=t,this.__bugjar_url=typeof n=="string"?n:n.href,this.__bugjar_headers={},e.originalXhrOpen.apply(this,arguments)},XMLHttpRequest.prototype.setRequestHeader=function(t,n){return this.__bugjar_headers&&(this.__bugjar_headers[t]=n),e.originalXhrSetRequestHeader.apply(this,arguments)},XMLHttpRequest.prototype.send=function(t){if(e.shouldIgnore(this.__bugjar_url||""))return e.originalXhrSend.apply(this,arguments);let n=performance.now(),r={id:h(),timestamp:Date.now(),method:(this.__bugjar_method||"GET").toUpperCase(),url:this.__bugjar_url||"",requestHeaders:this.__bugjar_headers||{},requestBody:e.safeParseBody(t),status:null,statusText:"",responseHeaders:{},responseBody:null,responseSize:null,duration:null,type:"xhr",error:null,initiator:e.getInitiator()};return this.addEventListener("load",function(){r.status=this.status,r.statusText=this.statusText,r.responseHeaders=e.parseXhrHeaders(this.getAllResponseHeaders()),r.duration=performance.now()-n;let s=e.readXhrResponse(this);r.responseSize=s.size,r.responseBody=s.body,r.requestBody=d(r.requestBody,e.config.sensitiveFields),r.responseBody=d(r.responseBody,e.config.sensitiveFields),e.buffer.push(r)}),this.addEventListener("error",function(){r.duration=performance.now()-n,r.error="Network error",e.buffer.push(r)}),this.addEventListener("timeout",function(){r.duration=performance.now()-n,r.error="Request timeout",e.buffer.push(r)}),e.originalXhrSend.apply(this,arguments)}}interceptBeacon(){if(!navigator.sendBeacon)return;this.originalSendBeacon=navigator.sendBeacon.bind(navigator);let e=this;Navigator.prototype.sendBeacon=function(t,n){let r=typeof t=="string"?t:t.href;if(e.shouldIgnore(r))return e.originalSendBeacon(t,n);let s={id:h(),timestamp:Date.now(),method:"POST",url:r,requestHeaders:{},requestBody:e.safeParseBody(n),status:null,statusText:"",responseHeaders:{},responseBody:null,responseSize:null,duration:null,type:"beacon",error:null,initiator:"sendBeacon"};return s.requestBody=d(s.requestBody,e.config.sensitiveFields),e.buffer.push(s),e.originalSendBeacon(t,n)}}extractHeaders(e){let t={};return e&&(e instanceof Headers?e.forEach((n,r)=>{t[r]=n}):Array.isArray(e)?e.forEach(([n,r])=>{t[n]=r}):Object.assign(t,e)),t}extractResponseHeaders(e){let t={};return e.forEach((n,r)=>{t[r]=n}),t}parseXhrHeaders(e){let t={};return e&&e.trim().split(/[\r\n]+/).forEach(n=>{let r=n.split(": "),s=r.shift();s&&(t[s]=r.join(": "))}),t}safeParseBody(e){if(!e)return null;if(typeof e=="string")return this.safeParseJson(e);if(e instanceof FormData){let t={};return e.forEach((n,r)=>{t[r]=n instanceof File?`[File: ${n.name}]`:n}),t}return e instanceof URLSearchParams?Object.fromEntries(e.entries()):e instanceof Blob?`[Blob: ${e.size} bytes]`:e instanceof ArrayBuffer?`[ArrayBuffer: ${e.byteLength} bytes]`:String(e)}readXhrResponse(e){try{let t=e.responseType;if(t===""||t==="text"){let r=e.responseText;return{size:r?.length||null,body:this.safeParseJson(r)}}let n=e.response;if(n==null)return{size:null,body:null};if(t==="json"){let r=JSON.stringify(n);return{size:r?.length||null,body:this.safeParseJson(r)}}return n instanceof Blob?{size:n.size,body:`[Blob: ${n.size} bytes]`}:n instanceof ArrayBuffer?{size:n.byteLength,body:`[ArrayBuffer: ${n.byteLength} bytes]`}:{size:null,body:`[${t}]`}}catch{return{size:null,body:"[Unable to read response]"}}}safeParseJson(e){if(!e)return null;try{return JSON.parse(e)}catch{return e.length>5e3?e.slice(0,5e3)+"...[truncated]":e}}getInitiator(){try{let e=new Error().stack;if(!e)return null;let t=e.split(`
|
|
2
|
+
`);for(let n of t)if(!n.includes("bug-jar")&&n.includes("at "))return n.trim().slice(0,200);return null}catch{return null}}};var w=class{constructor(e){this.originals={};this.levels=["log","warn","error","info","debug"];this.buffer=new l(e.maxConsoleEntries)}start(){for(let e of this.levels){this.originals[e]=console[e].bind(console);let t=this;console[e]=(...n)=>{t.capture(e,n),t.originals[e](...n)}}}stop(){for(let e of this.levels)this.originals[e]&&(console[e]=this.originals[e]);this.originals={}}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}capture(e,t){let n={timestamp:Date.now(),level:e,args:t.map(r=>typeof r=="string"||typeof r=="number"||typeof r=="boolean"?r:JSON.parse(F(r))),stack:e==="error"||e==="warn"?this.getStack():null};this.buffer.push(n)}getStack(){try{return new Error().stack?.split(`
|
|
3
3
|
`).slice(4).join(`
|
|
4
|
-
`)||null}catch{return null}}};var b=class{constructor(e){this.errorHandler=null;this.rejectionHandler=null;this.resourceErrorHandler=null;this.buffer=new l(e.maxErrors)}start(){this.errorHandler=e=>{this.buffer.push({timestamp:Date.now(),message:e.message||"Unknown error",stack:e.error?.stack||null,filename:e.filename||null,lineno:e.lineno||null,colno:e.colno||null,type:"uncaught",context:this.getContext(e.error)})},this.rejectionHandler=e=>{let t=e.reason;this.buffer.push({timestamp:Date.now(),message:t instanceof Error?t.message:String(t),stack:t instanceof Error&&t.stack||null,filename:null,lineno:null,colno:null,type:"unhandledrejection",context:t instanceof Error?this.getContext(t):null})},this.resourceErrorHandler=e=>{let t=e.target;!t||!(t instanceof HTMLElement)||(t.tagName==="SCRIPT"||t.tagName==="LINK"||t.tagName==="IMG")&&this.buffer.push({timestamp:Date.now(),message:`Failed to load ${t.tagName.toLowerCase()}: ${t.src||t.href||"unknown"}`,stack:null,filename:t.src||t.href||null,lineno:null,colno:null,type:"resource",context:null})},window.addEventListener("error",this.errorHandler),window.addEventListener("unhandledrejection",this.rejectionHandler),window.addEventListener("error",this.resourceErrorHandler,!0)}stop(){this.errorHandler&&(window.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null),this.resourceErrorHandler&&(window.removeEventListener("error",this.resourceErrorHandler,!0),this.resourceErrorHandler=null)}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}getContext(e){if(!e)return null;try{let t=e.stack;if(!t)return null;let
|
|
4
|
+
`)||null}catch{return null}}};var b=class{constructor(e){this.errorHandler=null;this.rejectionHandler=null;this.resourceErrorHandler=null;this.buffer=new l(e.maxErrors)}start(){this.errorHandler=e=>{this.buffer.push({timestamp:Date.now(),message:e.message||"Unknown error",stack:e.error?.stack||null,filename:e.filename||null,lineno:e.lineno||null,colno:e.colno||null,type:"uncaught",context:this.getContext(e.error)})},this.rejectionHandler=e=>{let t=e.reason;this.buffer.push({timestamp:Date.now(),message:t instanceof Error?t.message:String(t),stack:t instanceof Error&&t.stack||null,filename:null,lineno:null,colno:null,type:"unhandledrejection",context:t instanceof Error?this.getContext(t):null})},this.resourceErrorHandler=e=>{let t=e.target;!t||!(t instanceof HTMLElement)||(t.tagName==="SCRIPT"||t.tagName==="LINK"||t.tagName==="IMG")&&this.buffer.push({timestamp:Date.now(),message:`Failed to load ${t.tagName.toLowerCase()}: ${t.src||t.href||"unknown"}`,stack:null,filename:t.src||t.href||null,lineno:null,colno:null,type:"resource",context:null})},window.addEventListener("error",this.errorHandler),window.addEventListener("unhandledrejection",this.rejectionHandler),window.addEventListener("error",this.resourceErrorHandler,!0)}stop(){this.errorHandler&&(window.removeEventListener("error",this.errorHandler),this.errorHandler=null),this.rejectionHandler&&(window.removeEventListener("unhandledrejection",this.rejectionHandler),this.rejectionHandler=null),this.resourceErrorHandler&&(window.removeEventListener("error",this.resourceErrorHandler,!0),this.resourceErrorHandler=null)}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}getContext(e){if(!e)return null;try{let t=e.stack;if(!t)return null;let n=t.match(/at\s+(.+?)\s+\(/);return n?n[1]:null}catch{return null}}};var S=class{constructor(e){this.listeners=[];this.buffer=new l(e.maxUserActions)}start(){this.addListener("click",r=>{let s=r.target;this.buffer.push({timestamp:Date.now(),type:"click",target:f(s),metadata:{x:r.clientX,y:r.clientY,button:r.button}})},!0),this.addListener("input",r=>{let s=r.target,a=s.type==="password"||s.type==="hidden"||s.name?.toLowerCase().includes("password")||s.name?.toLowerCase().includes("token")||s.name?.toLowerCase().includes("secret");this.buffer.push({timestamp:Date.now(),type:"input",target:f(s),value:a?"[REDACTED]":s.value?.slice(0,50)||"",metadata:{inputType:s.type,name:s.name}})},!0),this.addListener("scroll",this.throttle(()=>{this.buffer.push({timestamp:Date.now(),type:"scroll",target:"window",metadata:{scrollX:window.scrollX,scrollY:window.scrollY,scrollHeight:document.documentElement.scrollHeight}})},500)),this.addListener("resize",this.throttle(()=>{this.buffer.push({timestamp:Date.now(),type:"resize",target:"window",metadata:{width:window.innerWidth,height:window.innerHeight}})},500)),this.addListener("visibilitychange",()=>{this.buffer.push({timestamp:Date.now(),type:"visibility",target:"document",value:document.visibilityState})}),this.addListener("copy",r=>{this.buffer.push({timestamp:Date.now(),type:"copy",target:f(r.target)})}),this.addListener("paste",r=>{this.buffer.push({timestamp:Date.now(),type:"paste",target:f(r.target)})});let e=history.pushState.bind(history),t=history.replaceState.bind(history),n=this;history.pushState=function(...r){return n.buffer.push({timestamp:Date.now(),type:"navigation",target:String(r[2]||window.location.href),metadata:{method:"pushState"}}),e(...r)},history.replaceState=function(...r){return n.buffer.push({timestamp:Date.now(),type:"navigation",target:String(r[2]||window.location.href),metadata:{method:"replaceState"}}),t(...r)},this.addListener("popstate",()=>{this.buffer.push({timestamp:Date.now(),type:"navigation",target:window.location.href,metadata:{method:"popstate"}})})}stop(){for(let{event:e,handler:t,options:n}of this.listeners)(e==="visibilitychange"?document:window).removeEventListener(e,t,n);this.listeners=[]}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}addListener(e,t,n){(e==="visibilitychange"?document:window).addEventListener(e,t,n),this.listeners.push({event:e,handler:t,options:n})}throttle(e,t){let n=0;return()=>{let r=Date.now();r-n>=t&&(n=r,e())}}};var E=class{collect(){return{userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language,languages:[...navigator.languages],timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timezoneOffset:new Date().getTimezoneOffset(),screenWidth:screen.width,screenHeight:screen.height,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,devicePixelRatio:window.devicePixelRatio,colorDepth:screen.colorDepth,cookiesEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack,online:navigator.onLine,hardwareConcurrency:navigator.hardwareConcurrency||0,maxTouchPoints:navigator.maxTouchPoints||0,vendor:navigator.vendor,connection:this.getConnection(),memory:this.getMemory()}}getConnection(){let e=navigator.connection;return e?{effectiveType:e.effectiveType||"unknown",downlink:e.downlink||0,rtt:e.rtt||0,saveData:e.saveData||!1}:null}getMemory(){let e=performance.memory;return e?{jsHeapSizeLimit:e.jsHeapSizeLimit,totalJSHeapSize:e.totalJSHeapSize,usedJSHeapSize:e.usedJSHeapSize}:null}};var k=class{constructor(){this.lcp=null;this.fid=null;this.cls=null;this.observers=[]}start(){this.observeLCP(),this.observeFID(),this.observeCLS()}stop(){for(let e of this.observers)e.disconnect();this.observers=[]}collect(){let e=performance.getEntriesByType("navigation")[0],t=performance.getEntriesByType("paint"),n=performance.getEntriesByType("resource"),r=t.find(a=>a.name==="first-paint"),s=t.find(a=>a.name==="first-contentful-paint");return{navigationTiming:e?{redirectTime:e.redirectEnd-e.redirectStart,dnsTime:e.domainLookupEnd-e.domainLookupStart,tcpTime:e.connectEnd-e.connectStart,tlsTime:e.secureConnectionStart>0?e.connectEnd-e.secureConnectionStart:0,ttfb:e.responseStart-e.requestStart,downloadTime:e.responseEnd-e.responseStart,domParsing:e.domInteractive-e.responseEnd,domContentLoaded:e.domContentLoadedEventEnd-e.domContentLoadedEventStart,loadEvent:e.loadEventEnd-e.loadEventStart,totalTime:e.loadEventEnd-e.startTime}:{},resourceCount:n.length,totalTransferSize:n.reduce((a,c)=>a+(c.transferSize||0),0),domContentLoaded:e?e.domContentLoadedEventEnd-e.startTime:null,loadComplete:e?e.loadEventEnd-e.startTime:null,firstPaint:r?r.startTime:null,firstContentfulPaint:s?s.startTime:null,largestContentfulPaint:this.lcp,firstInputDelay:this.fid,cumulativeLayoutShift:this.cls,timeToInteractive:null}}observeLCP(){try{let e=new PerformanceObserver(t=>{let n=t.getEntries();n.length>0&&(this.lcp=n[n.length-1].startTime)});e.observe({type:"largest-contentful-paint",buffered:!0}),this.observers.push(e)}catch{}}observeFID(){try{let e=new PerformanceObserver(t=>{let n=t.getEntries();n.length>0&&(this.fid=n[0].processingStart-n[0].startTime)});e.observe({type:"first-input",buffered:!0}),this.observers.push(e)}catch{}}observeCLS(){try{let e=0,t=new PerformanceObserver(n=>{for(let r of n.getEntries())r.hadRecentInput||(e+=r.value);this.cls=e});t.observe({type:"layout-shift",buffered:!0}),this.observers.push(t)}catch{}}};var U=class{constructor(e){this.config=e}collect(){return{localStorage:this.config.captureLocalStorage?this.collectStorage(localStorage):{},sessionStorage:this.config.captureSessionStorage?this.collectStorage(sessionStorage):{},cookies:this.config.captureCookies?this.collectCookies():[]}}collectStorage(e){let t={};try{for(let n=0;n<e.length;n++){let r=e.key(n);if(!r)continue;if(this.config.sensitiveFields.some(a=>r.toLowerCase().includes(a.toLowerCase())))t[r]="[REDACTED]";else{let a=e.getItem(r)||"";t[r]=a.length>500?a.slice(0,500)+"...[truncated]":a}}}catch{}return t}collectCookies(){try{return document.cookie.split(";").map(e=>e.trim().split("=")[0]).filter(Boolean)}catch{return[]}}};var C=class{async capture(){try{let e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return null;let n=window.innerWidth,r=window.innerHeight,s=Math.min(window.devicePixelRatio,2);e.width=n*s,e.height=r*s,t.scale(s,s);let a=this.domToSvg(n,r);return a?new Promise(c=>{let i=new Image;i.onload=()=>{t.drawImage(i,0,0);try{let u=e.toDataURL("image/png",.8);c(u)}catch{c(null)}},i.onerror=()=>c(null),i.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(a)}`,setTimeout(()=>c(null),3e3)}):null}catch{return null}}domToSvg(e,t){try{let n=document.documentElement.cloneNode(!0);n.querySelectorAll("script").forEach(a=>a.remove());let s=new XMLSerializer().serializeToString(n);return`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}">
|
|
5
5
|
<foreignObject width="100%" height="100%">
|
|
6
6
|
${s}
|
|
7
7
|
</foreignObject>
|
|
8
|
-
</svg>`}catch{return null}}captureHtml(){try{let e=document.documentElement.cloneNode(!0);return e.querySelectorAll("script").forEach(
|
|
8
|
+
</svg>`}catch{return null}}captureHtml(){try{let e=document.documentElement.cloneNode(!0);return e.querySelectorAll("script").forEach(r=>r.remove()),e.querySelectorAll('input[type="password"], input[name*="token"], input[name*="secret"]').forEach(r=>r.value="[REDACTED]"),e.outerHTML.slice(0,5e5)}catch{return null}}};var R=class{collect(){let e={},t=!1,n=window.posthog;if(n?.getFeatureFlag)try{let c=n.getAllFlags?.()||n.getFeatureFlags?.()||{};e.posthog=c,t=!0}catch{}let r=window.ldclient;if(r?.allFlags)try{e.launchdarkly=r.allFlags(),t=!0}catch{}let s=window.statsig;if(s?.getExperiment||s?.checkGate)try{e.statsig={detected:!0},t=!0}catch{}let a=window.unleash;if(a?.getAllToggles)try{e.unleash=a.getAllToggles(),t=!0}catch{}return t?e:null}};var x=class{constructor(){this.mediaRecorder=null;this.chunks=[];this.stream=null;this.recording=!1;this.onChunk=null}get isRecording(){return this.recording}setChunkHandler(e){this.onChunk=e}async start(){if(!this.recording)try{this.stream=await navigator.mediaDevices.getDisplayMedia({video:{frameRate:15},audio:!1,preferCurrentTab:!0}),this.chunks=[],this.mediaRecorder=new MediaRecorder(this.stream,{mimeType:this.getSupportedMimeType(),videoBitsPerSecond:1e6}),this.mediaRecorder.ondataavailable=e=>{e.data.size>0&&(this.chunks.push(e.data),this.onChunk&&e.data.arrayBuffer().then(t=>this.onChunk?.(new Uint8Array(t),!1)).catch(()=>{}))},this.mediaRecorder.onstop=()=>{this.recording=!1,this.stopTracks()},this.stream.getVideoTracks()[0].onended=()=>{this.stop()},this.mediaRecorder.start(1e3),this.recording=!0}catch{this.recording=!1,this.stream=null,this.mediaRecorder=null}}stop(){return new Promise(e=>{if(!this.mediaRecorder||!this.recording){e(null);return}this.mediaRecorder.onstop=()=>{this.recording=!1,this.stopTracks();let t=new Blob(this.chunks,{type:this.getSupportedMimeType()});this.chunks=[],e(t)},this.mediaRecorder.stop()})}stopTracks(){this.stream&&(this.stream.getTracks().forEach(e=>e.stop()),this.stream=null)}getSupportedMimeType(){let e=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"];for(let t of e)if(MediaRecorder.isTypeSupported(t))return t;return"video/webm"}};var T=class{constructor(){this.container=null}mount(){this.container||(this.container=document.createElement("div"),this.container.id="bug-jar-session-border",this.container.setAttribute("aria-hidden","true"),this.container.innerHTML=`
|
|
9
9
|
<div class="bug-jar-session-border-glow"></div>
|
|
10
10
|
<div class="bug-jar-session-pill">
|
|
11
11
|
<span class="bug-jar-session-pill-dot"></span>
|
|
@@ -80,7 +80,7 @@ function h(){return`${Date.now().toString(36)}-${Math.random().toString(36).slic
|
|
|
80
80
|
.bug-jar-session-border-glow { animation: none; }
|
|
81
81
|
.bug-jar-session-pill-dot { animation: none; }
|
|
82
82
|
}
|
|
83
|
-
`,document.head.appendChild(e)}};function M(){if(typeof window>"u")return null;try{return new URLSearchParams(window.location.search).get("debug")}catch{return null}}async function I(o,e,t=fetch){let
|
|
84
|
-
`)}function G(o){return o.includes("Chrome/")?`Chrome ${o.match(/Chrome\/(\d+)/)?.[1]||""}`:o.includes("Firefox/")?`Firefox ${o.match(/Firefox\/(\d+)/)?.[1]||""}`:o.includes("Safari/")&&!o.includes("Chrome")?`Safari ${o.match(/Version\/(\d+)/)?.[1]||""}`:o.slice(0,50)}function K(o){return o<1024?`${o}B`:o<1024*1024?`${(o/1024).toFixed(1)}KB`:`${(o/(1024*1024)).toFixed(1)}MB`}async function H(o,e){let t=[],
|
|
85
|
-
`);this.dataUploader.pushChunk(a,t)};this.dataInterval=setInterval(()=>e(!1),5e3)}registerFlushHandlers(){let e=()=>{this.finalizePage()};window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e()})}async finalizePage(){if(this.finalized||!this.debugSession)return;this.finalized=!0,this.dataInterval&&(clearInterval(this.dataInterval),this.dataInterval=null);let e={pageId:this.pageId,timestamp:Date.now(),url:window.location.href,final:!0,network:this.network.getEntries().filter(
|
|
86
|
-
`);this.dataUploader?.pushChunk(t,!0),await this.screenRecorder.stop(),await Promise.allSettled([this.dataUploader?.flush()??Promise.resolve(),this.videoUploader?.flush()??Promise.resolve()])}async runSpeedtest(e,t,
|
|
83
|
+
`,document.head.appendChild(e)}};function M(){if(typeof window>"u")return null;try{return new URLSearchParams(window.location.search).get("debug")}catch{return null}}async function I(o,e,t=fetch){let n=`${o.replace(/\/$/,"")}/${encodeURIComponent(e)}`,r=await t(n,{method:"GET",credentials:"include"});if(!r.ok){let s=new Error(`Failed to load debug session (${r.status})`);throw s.status=r.status,s}return await r.json()}function j(o,e=fetch){let t=o.replace(/\/$/,"");return async n=>{let r=`${t}/${encodeURIComponent(n.token)}/chunk-url`,s=await e(r,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({pageId:n.pageId,stream:n.stream,seq:n.seq})});if(!s.ok)throw new Error(`Failed to get chunk URL (${s.status})`);return await s.json()}}async function _(o,e,t,n,r=fetch){let a=`${o.replace(/\/$/,"")}/${encodeURIComponent(e)}/meta`;await r(a,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",keepalive:!0,body:JSON.stringify({pageId:t,meta:n})})}async function N(){let o=await import("libsodium-wrappers"),e=o.default??o;return await e.ready,e}function X(o){let e=atob(o),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}var J=[66,74,83,49],A=class{constructor(){this.sodium=null;this.state=null;this.headerEnvelope=null}async init(e){let t=await N();this.sodium=t;let n=X(e),r=t.crypto_secretstream_xchacha20poly1305_keygen(),s=t.crypto_box_seal(r,n),{state:a,header:c}=t.crypto_secretstream_xchacha20poly1305_init_push(r);this.state=a;let i=new Uint8Array(J),u=new Uint8Array([1]),p=new Uint8Array(4);new DataView(p.buffer).setUint32(0,s.length,!0);let m=W([i,u,p,s,c]);return this.headerEnvelope=m,m}get header(){if(!this.headerEnvelope)throw new Error("StreamEncryptor not initialized");return this.headerEnvelope}encryptChunk(e,t=!1){if(!this.sodium||!this.state)throw new Error("StreamEncryptor not initialized");let n=t?this.sodium.crypto_secretstream_xchacha20poly1305_TAG_FINAL:this.sodium.crypto_secretstream_xchacha20poly1305_TAG_MESSAGE;return this.sodium.crypto_secretstream_xchacha20poly1305_push(this.state,e,null,n)}};function W(o){let e=o.reduce((r,s)=>r+s.length,0),t=new Uint8Array(e),n=0;for(let r of o)t.set(r,n),n+=r.length;return t}var g=class{constructor(e,t,n,r,s,a=fetch){this.token=e;this.pageId=t;this.stream=n;this.publicKey=r;this.fetchChunkUrl=s;this.rawFetch=a;this.encryptor=new A;this.seq=0;this.initialized=!1;this.queue=Promise.resolve()}async ensureInit(){if(this.initialized)return;this.initialized=!0;let e=await this.encryptor.init(this.publicKey);await this.putChunk(e)}pushChunk(e,t=!1){this.queue=this.queue.then(async()=>{await this.ensureInit();let n=this.encryptor.encryptChunk(e,t);await this.putChunk(n)})}async flush(){await this.queue}async putChunk(e){let{uploadUrl:t}=await this.fetchChunkUrl({token:this.token,pageId:this.pageId,stream:this.stream,seq:this.seq});this.seq+=1,await this.rawFetch(t,{method:"PUT",headers:{"Content-Type":"application/octet-stream"},body:e})}};var L=class{constructor(e,t,n=fetch){this.baseUrl=e;this.token=t;this.rawFetch=n}async run(){let e=performance.now(),t={ranAt:Date.now(),latencyMs:null,jitterMs:null,downloadMbps:null,uploadMbps:null,durationMs:0};try{let n=await this.measureLatency();t.latencyMs=n.min,t.jitterMs=n.jitter}catch{}try{t.downloadMbps=await this.measureDownload()}catch{}try{t.uploadMbps=await this.measureUpload()}catch{}return t.durationMs=Math.round(performance.now()-e),t}url(e){return`${this.baseUrl.replace(/\/$/,"")}/${encodeURIComponent(this.token)}/${e}`}async measureLatency(){let e=[];for(let s=0;s<5;s++){let a=performance.now();await this.rawFetch(this.url(`speedtest/ping?n=${s}`),{cache:"no-store"}),e.push(performance.now()-a)}let t=Math.min(...e),n=e.reduce((s,a)=>s+a,0)/e.length,r=e.reduce((s,a)=>s+Math.abs(a-n),0)/e.length;return{min:Math.round(t),jitter:Math.round(r)}}async measureDownload(){let e=Math.floor(2097152),t=performance.now(),n=Array.from({length:4},(c,i)=>this.rawFetch(this.url(`speedtest/download?bytes=${e}&s=${i}`),{cache:"no-store"}).then(u=>u.arrayBuffer())),r=await Promise.all(n),s=(performance.now()-t)/1e3,a=r.reduce((c,i)=>c+i.byteLength,0);return this.toMbps(a,s)}async measureUpload(){let e=new Uint8Array(4194304);crypto.getRandomValues(e.subarray(0,Math.min(65536,4194304)));let t=performance.now();await this.rawFetch(this.url("speedtest/upload"),{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:e});let n=(performance.now()-t)/1e3;return this.toMbps(4194304,n)}toMbps(e,t){return t<=0?0:Math.round(e*8/t/1e6*100)/100}};var B="bug-jar-session";function q(){if(typeof window>"u"||typeof document>"u")return;let o=window.location.hostname;if(/^[0-9.]+$/.test(o)||o==="localhost")return;let e=o.split(".");if(e.length<2)return;let t="bug-jar-domain-probe";for(let n=e.length-2;n>=0;n--){let r=`.${e.slice(n).join(".")}`;document.cookie=`${t}=1; Path=/; Domain=${r}; SameSite=Lax`;let s=document.cookie.includes(`${t}=1`);if(document.cookie=`${t}=; Path=/; Domain=${r}; Expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax`,s)return r}}function O(){if(typeof document>"u")return null;let o=document.cookie.split("; ").find(t=>t.startsWith(`${B}=`));if(!o)return null;let e=o.slice(B.length+1);return e?decodeURIComponent(e):null}function D(o,e){if(typeof document>"u")return;let t=q(),n=new Date(e).toUTCString(),r=window.location.protocol==="https:"?"; Secure":"",s=t?`; Domain=${t}`:"";document.cookie=`${B}=${encodeURIComponent(o)}; Path=/; Expires=${n}; SameSite=Lax${s}${r}`}function P(){if(typeof document>"u")return;let o=q(),e=o?`; Domain=${o}`:"";document.cookie=`${B}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=Lax${e}`}function $(o){let e=[];e.push(`Bug Report: ${o.id}`),e.push(`URL: ${o.url}`),e.push(`Time: ${new Date(o.timestamp).toISOString()}`),e.push(`User Description: "${o.userDescription}"`),e.push(""),e.push("## Environment"),e.push(`Browser: ${G(o.environment.userAgent)}`),e.push(`Viewport: ${o.environment.viewportWidth}x${o.environment.viewportHeight}`),e.push(`Connection: ${o.environment.connection?.effectiveType||"unknown"}`),e.push(`Online: ${o.environment.online}`),e.push(""),e.push("## Network Activity");let t=o.network.length,n=o.network.filter(i=>i.error||i.status&&i.status>=400),r=o.network.filter(i=>i.duration&&i.duration>3e3);if(e.push(`Total requests: ${t}`),n.length>0){e.push(`Failed requests (${n.length}):`);for(let i of n)e.push(` - ${i.method} ${i.url} \u2192 ${i.error||`HTTP ${i.status}`}`)}if(r.length>0){e.push(`Slow requests >3s (${r.length}):`);for(let i of r)e.push(` - ${i.method} ${i.url} (${Math.round(i.duration)}ms)`)}if(e.push(""),e.push("## Errors"),o.errors.length===0)e.push("No errors captured.");else{e.push(`Total errors: ${o.errors.length}`);for(let i of o.errors)e.push(` - [${i.type}] ${i.message}`),i.filename&&e.push(` at ${i.filename}:${i.lineno}:${i.colno}`)}e.push(""),e.push("## Console");let s={log:0,warn:0,error:0,info:0,debug:0};for(let i of o.console)s[i.level]++;e.push(`Logs: ${s.log}, Warnings: ${s.warn}, Errors: ${s.error}, Info: ${s.info}, Debug: ${s.debug}`);let a=o.console.filter(i=>i.level==="error");if(a.length>0){e.push("Console errors:");for(let i of a)e.push(` - ${i.args.map(u=>typeof u=="string"?u:JSON.stringify(u)).join(" ")}`)}e.push(""),e.push("## User Actions"),e.push(`Total actions: ${o.userActions.length}`);let c={};for(let i of o.userActions)c[i.type]=(c[i.type]||0)+1;for(let[i,u]of Object.entries(c))e.push(` - ${i}: ${u}`);if(o.userActions.length>0){let i=o.userActions[0].timestamp,p=((o.userActions[o.userActions.length-1].timestamp-i)/1e3).toFixed(1);e.push(`Session duration: ${p}s`)}if(e.push(""),o.performance){e.push("## Performance");let i=o.performance;i.largestContentfulPaint&&e.push(`LCP: ${Math.round(i.largestContentfulPaint)}ms`),i.firstInputDelay&&e.push(`FID: ${Math.round(i.firstInputDelay)}ms`),i.cumulativeLayoutShift!==null&&e.push(`CLS: ${i.cumulativeLayoutShift?.toFixed(3)}`),i.loadComplete&&e.push(`Page Load: ${Math.round(i.loadComplete)}ms`),e.push(`Resources: ${i.resourceCount} (${K(i.totalTransferSize)})`)}return e.join(`
|
|
84
|
+
`)}function G(o){return o.includes("Chrome/")?`Chrome ${o.match(/Chrome\/(\d+)/)?.[1]||""}`:o.includes("Firefox/")?`Firefox ${o.match(/Firefox\/(\d+)/)?.[1]||""}`:o.includes("Safari/")&&!o.includes("Chrome")?`Safari ${o.match(/Version\/(\d+)/)?.[1]||""}`:o.slice(0,50)}function K(o){return o<1024?`${o}B`:o<1024*1024?`${(o/1024).toFixed(1)}KB`:`${(o/(1024*1024)).toFixed(1)}MB`}async function H(o,e){let t=[],n=JSON.stringify(o,null,2);t.push({name:"report.json",content:new TextEncoder().encode(n)});let r=$(o);if(t.push({name:"summary.md",content:new TextEncoder().encode(r)}),o.screenshot){let s=V(o.screenshot);s&&t.push({name:"screenshot.png",content:s})}if(e){let s=new Uint8Array(await e.arrayBuffer());t.push({name:"recording.webm",content:s})}return Y(t)}function V(o){try{let e=o.split(",")[1];if(!e)return null;let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}catch{return null}}function Y(o){let e=[],t=[],n=0;for(let i of o){let u=new TextEncoder().encode(i.name),p=te(i.content),m=Z(u,i.content.length,p);e.push(m),e.push(u),e.push(i.content);let z=Q(u,i.content.length,p,n);t.push(z),t.push(u),n+=m.length+u.length+i.content.length}let r=n,s=0;for(let i of t)s+=i.length;let a=ee(o.length,s,r),c=[...e,...t,a].map(i=>i.buffer);return new Blob(c,{type:"application/zip"})}function Z(o,e,t){let n=new Uint8Array(30),r=new DataView(n.buffer);return r.setUint32(0,67324752,!0),r.setUint16(4,20,!0),r.setUint16(6,0,!0),r.setUint16(8,0,!0),r.setUint16(10,0,!0),r.setUint16(12,0,!0),r.setUint32(14,t,!0),r.setUint32(18,e,!0),r.setUint32(22,e,!0),r.setUint16(26,o.length,!0),r.setUint16(28,0,!0),n}function Q(o,e,t,n){let r=new Uint8Array(46),s=new DataView(r.buffer);return s.setUint32(0,33639248,!0),s.setUint16(4,20,!0),s.setUint16(6,20,!0),s.setUint16(8,0,!0),s.setUint16(10,0,!0),s.setUint16(12,0,!0),s.setUint16(14,0,!0),s.setUint32(16,t,!0),s.setUint32(20,e,!0),s.setUint32(24,e,!0),s.setUint16(28,o.length,!0),s.setUint16(30,0,!0),s.setUint16(32,0,!0),s.setUint16(34,0,!0),s.setUint16(36,0,!0),s.setUint32(38,0,!0),s.setUint32(42,n,!0),r}function ee(o,e,t){let n=new Uint8Array(22),r=new DataView(n.buffer);return r.setUint32(0,101010256,!0),r.setUint16(4,0,!0),r.setUint16(6,0,!0),r.setUint16(8,o,!0),r.setUint16(10,o,!0),r.setUint32(12,e,!0),r.setUint32(16,t,!0),r.setUint16(20,0,!0),n}function te(o){let e=4294967295;for(let t=0;t<o.length;t++){e^=o[t];for(let n=0;n<8;n++)e=e>>>1^(e&1?3988292384:0)}return(e^4294967295)>>>0}var ne="0.7.2",re={maxNetworkEntries:100,maxConsoleEntries:200,maxUserActions:150,maxErrors:50,captureScreenshot:!0,captureHtmlSnapshot:!0,captureCookies:!0,captureLocalStorage:!0,captureSessionStorage:!0,capturePerformance:!0,captureWebVitals:!0,captureMemory:!0,captureConnectivity:!0,sensitiveFields:["password","token","secret","authorization","cookie","session","credit_card","cvv","ssn","cpf"],endpoint:void 0,onCapture:void 0,debugToken:void 0,debugSessionEndpoint:void 0},y=class{constructor(e={}){this.sessionBorder=null;this.debugSession=null;this.dataUploader=null;this.videoUploader=null;this.pageId=h();this.dataInterval=null;this.lastFlushTs=0;this.finalized=!1;this.started=!1;this.config={...re,...e},this.network=new v(this.config),this.console=new w(this.config),this.errors=new b(this.config),this.userActions=new S(this.config),this.environment=new E,this.performance=new k,this.storage=new U(this.config),this.screenshot=new C,this.featureFlags=new R,this.screenRecorder=new x}start(){if(this.started)return;this.started=!0,this.network.start(),this.console.start(),this.errors.start(),this.userActions.start(),this.config.captureWebVitals&&this.performance.start();let e=this.config.debugToken??M(),t=e??O();e&&D(e,Date.now()+1440*60*1e3),t&&this.startDebugSession(t)}stop(){this.started&&(this.started=!1,this.network.stop(),this.console.stop(),this.errors.stop(),this.userActions.stop(),this.performance.stop(),this.sessionBorder?.unmount())}async startRecording(){await this.screenRecorder.start()}get isRecording(){return this.screenRecorder.isRecording}async capture(e=""){let t={id:h(),timestamp:Date.now(),url:window.location.href,title:document.title,userDescription:e,environment:this.environment.collect(),network:this.network.getEntries(),console:this.console.getEntries(),errors:this.errors.getEntries(),userActions:this.userActions.getEntries(),performance:this.config.capturePerformance?this.performance.collect():null,storage:this.storage.collect(),screenshot:this.config.captureScreenshot?await this.screenshot.capture():null,htmlSnapshot:this.config.captureHtmlSnapshot?this.screenshot.captureHtml():null,featureFlags:this.featureFlags.collect(),metadata:{},version:ne};return this.config.onCapture&&this.config.onCapture(t),t}async captureAndExport(e=""){let t=await this.screenRecorder.stop(),n=await this.capture(e);if(this.config.endpoint)if(t){let r=new FormData;r.append("report",JSON.stringify(n)),r.append("video",t,"recording.webm"),await fetch(this.config.endpoint,{method:"POST",body:r})}else await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});else{let r=await H(n,t),s=URL.createObjectURL(r),a=document.createElement("a");a.href=s,a.download=`bug-report-${n.id}.zip`,a.click(),URL.revokeObjectURL(s)}return n}getReport(){return this.capture()}async startDebugSession(e){if(!this.config.debugSessionEndpoint)return;let t=this.config.debugSessionEndpoint,n=()=>{this.sessionBorder=new T,this.sessionBorder.mount()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",n):n();try{let r=this.network.getRawFetch();this.debugSession=await I(t,e,r),D(this.debugSession.token,this.debugSession.expiresAt);let s=j(t,r);this.dataUploader=new g(this.debugSession.token,this.pageId,"data",this.debugSession.publicKey,s,r),this.videoUploader=new g(this.debugSession.token,this.pageId,"video",this.debugSession.publicKey,s,r),this.runSpeedtest(t,this.debugSession.token,r),this.startDataStreaming(),this.registerFlushHandlers(),this.screenRecorder.setChunkHandler(a=>{this.videoUploader?.pushChunk(a)}),this.screenRecorder.start()}catch(r){this.sessionBorder?.unmount();let s=r?.status;(s===401||s===403||s===404)&&P()}}startDataStreaming(){let e=t=>{if(!this.dataUploader)return;let n=this.lastFlushTs,r=Date.now(),s={pageId:this.pageId,timestamp:r,url:window.location.href,network:this.network.getEntries().filter(c=>c.timestamp>n),console:this.console.getEntries().filter(c=>c.timestamp>n),errors:this.errors.getEntries().filter(c=>c.timestamp>n),userActions:this.userActions.getEntries().filter(c=>c.timestamp>n)};this.lastFlushTs=r;let a=new TextEncoder().encode(JSON.stringify(s)+`
|
|
85
|
+
`);this.dataUploader.pushChunk(a,t)};this.dataInterval=setInterval(()=>e(!1),5e3)}registerFlushHandlers(){let e=()=>{this.finalizePage()};window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&e()})}async finalizePage(){if(this.finalized||!this.debugSession)return;this.finalized=!0,this.dataInterval&&(clearInterval(this.dataInterval),this.dataInterval=null);let e={pageId:this.pageId,timestamp:Date.now(),url:window.location.href,final:!0,network:this.network.getEntries().filter(n=>n.timestamp>this.lastFlushTs),console:this.console.getEntries().filter(n=>n.timestamp>this.lastFlushTs),errors:this.errors.getEntries().filter(n=>n.timestamp>this.lastFlushTs),userActions:this.userActions.getEntries().filter(n=>n.timestamp>this.lastFlushTs),storage:this.storage.collect(),featureFlags:this.featureFlags.collect(),screenshot:this.config.captureScreenshot?await this.screenshot.capture():null},t=new TextEncoder().encode(JSON.stringify(e)+`
|
|
86
|
+
`);this.dataUploader?.pushChunk(t,!0),await this.screenRecorder.stop(),await Promise.allSettled([this.dataUploader?.flush()??Promise.resolve(),this.videoUploader?.flush()??Promise.resolve()])}async runSpeedtest(e,t,n){let r=null;try{r=await new L(e,t,n).run()}catch{}await _(e,t,this.pageId,{url:window.location.href,title:document.title,startedAt:Date.now(),environment:this.environment.collect(),speedtest:r},n)}endDebugSession(){P(),this.sessionBorder?.unmount(),this.finalizePage()}};function se(o={}){let e=new y(o);return e.start(),e}typeof window<"u"&&(window.BugJar={BugJar:y,init:se});var We=y;export{y as BugJar,We as default,H as exportAsZip,$ as generateSummary,se as init};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@arvoretech/bug-jar",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.3",
|
|
4
4
|
"description": "Capture everything for non-technical people to help debug. One script tag, zero config.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"@types/libsodium-wrappers": "0.8.2",
|
|
49
49
|
"tsup": "^8.4.0",
|
|
50
50
|
"typescript": "^5.7.0",
|
|
51
|
-
"vite": "^6.
|
|
51
|
+
"vite": "^6.4.4"
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"libsodium-wrappers": "0.8.4"
|