@arvoretech/bug-jar 0.4.0 → 0.7.0
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 +56 -15
- package/dist/index.d.mts +13 -4
- package/dist/index.d.ts +13 -4
- package/dist/index.global.js +72 -46
- package/dist/index.js +73 -47
- package/dist/index.mjs +72 -46
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,60 +1,86 @@
|
|
|
1
|
-
function
|
|
2
|
-
`);for(let
|
|
1
|
+
function h(){return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function H(o,e=1e4){try{let t=new WeakSet,r=JSON.stringify(o,(n,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 r&&r.length>e?r.slice(0,e)+"...[truncated]":r||""}catch{return"[Unserializable]"}}function f(o){if(!o||!(o instanceof Element))return"unknown";let e=o.tagName.toLowerCase(),t=o.id?`#${o.id}`:"",r=o.className&&typeof o.className=="string"?`.${o.className.trim().split(/\s+/).join(".")}`:"",n=o.textContent?.trim().slice(0,30)||"",s=n?` "${n}"`:"";return`${e}${t}${r}${s}`}function d(o,e){if(!o||typeof o!="object")return o;if(Array.isArray(o))return o.map(r=>d(r,e));let t={};for(let[r,n]of Object.entries(o))e.some(a=>r.toLowerCase().includes(a.toLowerCase()))?t[r]="[REDACTED]":typeof n=="object"&&n!==null?t[r]=d(n,e):t[r]=n;return t}var u=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 u(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(r=>e.includes(r))}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,r){if(e.shouldIgnore(e.resolveUrl(t)))return e.originalFetch(t,r);let n=performance.now(),s={id:h(),timestamp:Date.now(),method:(r?.method||"GET").toUpperCase(),url:typeof t=="string"?t:t instanceof URL?t.href:t.url,requestHeaders:e.extractHeaders(r?.headers),requestBody:e.safeParseBody(r?.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,r);s.status=a.status,s.statusText=a.statusText,s.responseHeaders=e.extractResponseHeaders(a.headers),s.duration=performance.now()-n;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()-n,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,r){return this.__bugjar_method=t,this.__bugjar_url=typeof r=="string"?r:r.href,this.__bugjar_headers={},e.originalXhrOpen.apply(this,arguments)},XMLHttpRequest.prototype.setRequestHeader=function(t,r){return this.__bugjar_headers&&(this.__bugjar_headers[t]=r),e.originalXhrSetRequestHeader.apply(this,arguments)},XMLHttpRequest.prototype.send=function(t){if(e.shouldIgnore(this.__bugjar_url||""))return e.originalXhrSend.apply(this,arguments);let r=performance.now(),n={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(){n.status=this.status,n.statusText=this.statusText,n.responseHeaders=e.parseXhrHeaders(this.getAllResponseHeaders()),n.duration=performance.now()-r,n.responseSize=this.responseText?.length||null,n.responseBody=e.safeParseJson(this.responseText),n.requestBody=d(n.requestBody,e.config.sensitiveFields),n.responseBody=d(n.responseBody,e.config.sensitiveFields),e.buffer.push(n)}),this.addEventListener("error",function(){n.duration=performance.now()-r,n.error="Network error",e.buffer.push(n)}),this.addEventListener("timeout",function(){n.duration=performance.now()-r,n.error="Request timeout",e.buffer.push(n)}),e.originalXhrSend.apply(this,arguments)}}interceptBeacon(){if(!navigator.sendBeacon)return;this.originalSendBeacon=navigator.sendBeacon.bind(navigator);let e=this;Navigator.prototype.sendBeacon=function(t,r){let n=typeof t=="string"?t:t.href;if(e.shouldIgnore(n))return e.originalSendBeacon(t,r);let s={id:h(),timestamp:Date.now(),method:"POST",url:n,requestHeaders:{},requestBody:e.safeParseBody(r),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,r)}}extractHeaders(e){let t={};return e&&(e instanceof Headers?e.forEach((r,n)=>{t[n]=r}):Array.isArray(e)?e.forEach(([r,n])=>{t[r]=n}):Object.assign(t,e)),t}extractResponseHeaders(e){let t={};return e.forEach((r,n)=>{t[n]=r}),t}parseXhrHeaders(e){let t={};return e&&e.trim().split(/[\r\n]+/).forEach(r=>{let n=r.split(": "),s=n.shift();s&&(t[s]=n.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((r,n)=>{t[n]=r instanceof File?`[File: ${r.name}]`:r}),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)}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 r of t)if(!r.includes("bug-jar")&&r.includes("at "))return r.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 u(e.maxConsoleEntries)}start(){for(let e of this.levels){this.originals[e]=console[e].bind(console);let t=this;console[e]=(...r)=>{t.capture(e,r),t.originals[e](...r)}}}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 r={timestamp:Date.now(),level:e,args:t.map(n=>typeof n=="string"||typeof n=="number"||typeof n=="boolean"?n:JSON.parse(H(n))),stack:e==="error"||e==="warn"?this.getStack():null};this.buffer.push(r)}getStack(){try{return new Error().stack?.split(`
|
|
3
3
|
`).slice(4).join(`
|
|
4
|
-
`)||null}catch{return null}}};var
|
|
4
|
+
`)||null}catch{return null}}};var b=class{constructor(e){this.errorHandler=null;this.rejectionHandler=null;this.resourceErrorHandler=null;this.buffer=new u(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 r=t.match(/at\s+(.+?)\s+\(/);return r?r[1]:null}catch{return null}}};var S=class{constructor(e){this.listeners=[];this.buffer=new u(e.maxUserActions)}start(){this.addListener("click",n=>{let s=n.target;this.buffer.push({timestamp:Date.now(),type:"click",target:f(s),metadata:{x:n.clientX,y:n.clientY,button:n.button}})},!0),this.addListener("input",n=>{let s=n.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",n=>{this.buffer.push({timestamp:Date.now(),type:"copy",target:f(n.target)})}),this.addListener("paste",n=>{this.buffer.push({timestamp:Date.now(),type:"paste",target:f(n.target)})});let e=history.pushState.bind(history),t=history.replaceState.bind(history),r=this;history.pushState=function(...n){return r.buffer.push({timestamp:Date.now(),type:"navigation",target:String(n[2]||window.location.href),metadata:{method:"pushState"}}),e(...n)},history.replaceState=function(...n){return r.buffer.push({timestamp:Date.now(),type:"navigation",target:String(n[2]||window.location.href),metadata:{method:"replaceState"}}),t(...n)},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:r}of this.listeners)(e==="visibilitychange"?document:window).removeEventListener(e,t,r);this.listeners=[]}getEntries(){return this.buffer.getAll()}clear(){this.buffer.clear()}addListener(e,t,r){(e==="visibilitychange"?document:window).addEventListener(e,t,r),this.listeners.push({event:e,handler:t,options:r})}throttle(e,t){let r=0;return()=>{let n=Date.now();n-r>=t&&(r=n,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"),r=performance.getEntriesByType("resource"),n=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:r.length,totalTransferSize:r.reduce((a,c)=>a+(c.transferSize||0),0),domContentLoaded:e?e.domContentLoadedEventEnd-e.startTime:null,loadComplete:e?e.loadEventEnd-e.startTime:null,firstPaint:n?n.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 r=t.getEntries();r.length>0&&(this.lcp=r[r.length-1].startTime)});e.observe({type:"largest-contentful-paint",buffered:!0}),this.observers.push(e)}catch{}}observeFID(){try{let e=new PerformanceObserver(t=>{let r=t.getEntries();r.length>0&&(this.fid=r[0].processingStart-r[0].startTime)});e.observe({type:"first-input",buffered:!0}),this.observers.push(e)}catch{}}observeCLS(){try{let e=0,t=new PerformanceObserver(r=>{for(let n of r.getEntries())n.hadRecentInput||(e+=n.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 r=0;r<e.length;r++){let n=e.key(r);if(!n)continue;if(this.config.sensitiveFields.some(a=>n.toLowerCase().includes(a.toLowerCase())))t[n]="[REDACTED]";else{let a=e.getItem(n)||"";t[n]=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 r=window.innerWidth,n=window.innerHeight,s=Math.min(window.devicePixelRatio,2);e.width=r*s,e.height=n*s,t.scale(s,s);let a=this.domToSvg(r,n);return a?new Promise(c=>{let i=new Image;i.onload=()=>{t.drawImage(i,0,0);try{let l=e.toDataURL("image/png",.8);c(l)}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 r=document.documentElement.cloneNode(!0);r.querySelectorAll("script").forEach(a=>a.remove());let s=new XMLSerializer().serializeToString(r);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(
|
|
9
|
-
<div class="bug-jar-
|
|
10
|
-
|
|
11
|
-
<span class="bug-jar-
|
|
12
|
-
<
|
|
8
|
+
</svg>`}catch{return null}}captureHtml(){try{let e=document.documentElement.cloneNode(!0);return e.querySelectorAll("script").forEach(n=>n.remove()),e.querySelectorAll('input[type="password"], input[name*="token"], input[name*="secret"]').forEach(n=>n.value="[REDACTED]"),e.outerHTML.slice(0,5e5)}catch{return null}}};var R=class{collect(){let e={},t=!1,r=window.posthog;if(r?.getFeatureFlag)try{let c=r.getAllFlags?.()||r.getFeatureFlags?.()||{};e.posthog=c,t=!0}catch{}let n=window.ldclient;if(n?.allFlags)try{e.launchdarkly=n.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)))},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 x=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
|
+
<div class="bug-jar-session-border-glow"></div>
|
|
10
|
+
<div class="bug-jar-session-pill">
|
|
11
|
+
<span class="bug-jar-session-pill-dot"></span>
|
|
12
|
+
<span>Sess\xE3o de depura\xE7\xE3o ativa</span>
|
|
13
13
|
</div>
|
|
14
|
-
`,this.injectStyles(),document.body.appendChild(this.container)
|
|
15
|
-
#bug-jar-
|
|
14
|
+
`,this.injectStyles(),document.body.appendChild(this.container))}unmount(){this.container?.remove(),this.container=null,document.getElementById("bug-jar-session-border-styles")?.remove()}injectStyles(){if(document.getElementById("bug-jar-session-border-styles"))return;let e=document.createElement("style");e.id="bug-jar-session-border-styles",e.textContent=`
|
|
15
|
+
#bug-jar-session-border {
|
|
16
16
|
position: fixed;
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
17
|
+
inset: 0;
|
|
18
|
+
z-index: 2147483646;
|
|
19
|
+
pointer-events: none;
|
|
20
|
+
}
|
|
21
|
+
.bug-jar-session-border-glow {
|
|
22
|
+
position: absolute;
|
|
23
|
+
inset: 0;
|
|
24
|
+
border-radius: 14px;
|
|
25
|
+
padding: 4px;
|
|
26
|
+
background: linear-gradient(
|
|
27
|
+
120deg,
|
|
28
|
+
#66DCCE,
|
|
29
|
+
#39AF9F,
|
|
30
|
+
#40CAB6,
|
|
31
|
+
#309385,
|
|
32
|
+
#66DCCE
|
|
33
|
+
);
|
|
34
|
+
background-size: 300% 300%;
|
|
35
|
+
animation: bug-jar-border-flow 6s ease infinite;
|
|
36
|
+
-webkit-mask:
|
|
37
|
+
linear-gradient(#fff 0 0) content-box,
|
|
38
|
+
linear-gradient(#fff 0 0);
|
|
39
|
+
-webkit-mask-composite: xor;
|
|
40
|
+
mask:
|
|
41
|
+
linear-gradient(#fff 0 0) content-box,
|
|
42
|
+
linear-gradient(#fff 0 0);
|
|
43
|
+
mask-composite: exclude;
|
|
22
44
|
}
|
|
23
|
-
.bug-jar-
|
|
45
|
+
.bug-jar-session-pill {
|
|
46
|
+
position: absolute;
|
|
47
|
+
bottom: 16px;
|
|
48
|
+
left: 50%;
|
|
49
|
+
transform: translateX(-50%);
|
|
24
50
|
display: flex;
|
|
25
51
|
align-items: center;
|
|
26
|
-
gap:
|
|
27
|
-
padding:
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
52
|
+
gap: 8px;
|
|
53
|
+
padding: 6px 14px;
|
|
54
|
+
border-radius: 999px;
|
|
55
|
+
background: rgba(15, 27, 21, 0.85);
|
|
56
|
+
color: #E6FAF7;
|
|
57
|
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
|
58
|
+
font-size: 12px;
|
|
59
|
+
font-weight: 500;
|
|
60
|
+
box-shadow: 0 4px 16px rgba(0,0,0,0.25);
|
|
61
|
+
backdrop-filter: blur(6px);
|
|
32
62
|
}
|
|
33
|
-
.bug-jar-
|
|
34
|
-
width:
|
|
35
|
-
height:
|
|
63
|
+
.bug-jar-session-pill-dot {
|
|
64
|
+
width: 8px;
|
|
65
|
+
height: 8px;
|
|
36
66
|
border-radius: 50%;
|
|
37
|
-
background: #
|
|
38
|
-
animation: bug-jar-
|
|
39
|
-
flex-shrink: 0;
|
|
67
|
+
background: #40CAB6;
|
|
68
|
+
animation: bug-jar-border-pulse 1.6s ease-in-out infinite;
|
|
40
69
|
}
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
color: #1a1a1a;
|
|
50
|
-
font-size: 13px;
|
|
51
|
-
font-weight: 600;
|
|
52
|
-
cursor: pointer;
|
|
70
|
+
@keyframes bug-jar-border-flow {
|
|
71
|
+
0% { background-position: 0% 50%; }
|
|
72
|
+
50% { background-position: 100% 50%; }
|
|
73
|
+
100% { background-position: 0% 50%; }
|
|
74
|
+
}
|
|
75
|
+
@keyframes bug-jar-border-pulse {
|
|
76
|
+
0%, 100% { opacity: 1; transform: scale(1); }
|
|
77
|
+
50% { opacity: 0.5; transform: scale(0.85); }
|
|
53
78
|
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
50% { opacity: 0.4; }
|
|
79
|
+
@media (prefers-reduced-motion: reduce) {
|
|
80
|
+
.bug-jar-session-border-glow { animation: none; }
|
|
81
|
+
.bug-jar-session-pill-dot { animation: none; }
|
|
58
82
|
}
|
|
59
|
-
`,document.head.appendChild(e)}};function L(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: ${
|
|
60
|
-
`)}function
|
|
83
|
+
`,document.head.appendChild(e)}};function $(){if(typeof window>"u")return null;try{return new URLSearchParams(window.location.search).get("debug")}catch{return null}}async function F(o,e,t=fetch){let r=`${o.replace(/\/$/,"")}/${encodeURIComponent(e)}`,n=await t(r,{method:"GET",credentials:"include"});if(!n.ok)throw new Error(`Failed to load debug session (${n.status})`);return await n.json()}function M(o,e=fetch){let t=o.replace(/\/$/,"");return async r=>{let n=`${t}/${encodeURIComponent(r.token)}/chunk-url`,s=await e(n,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({pageId:r.pageId,stream:r.stream,seq:r.seq})});if(!s.ok)throw new Error(`Failed to get chunk URL (${s.status})`);return await s.json()}}async function I(o,e,t,r,n=fetch){let a=`${o.replace(/\/$/,"")}/${encodeURIComponent(e)}/meta`;await n(a,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",keepalive:!0,body:JSON.stringify({pageId:t,meta:r})})}async function z(){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 r=0;r<e.length;r++)t[r]=e.charCodeAt(r);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 z();this.sodium=t;let r=X(e),n=t.crypto_secretstream_xchacha20poly1305_keygen(),s=t.crypto_box_seal(n,r),{state:a,header:c}=t.crypto_secretstream_xchacha20poly1305_init_push(n);this.state=a;let i=new Uint8Array(J),l=new Uint8Array([1]),p=new Uint8Array(4);new DataView(p.buffer).setUint32(0,s.length,!0);let g=W([i,l,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 r=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,r)}};function W(o){let e=o.reduce((n,s)=>n+s.length,0),t=new Uint8Array(e),r=0;for(let n of o)t.set(n,r),r+=n.length;return t}var m=class{constructor(e,t,r,n,s,a=fetch){this.token=e;this.pageId=t;this.stream=r;this.publicKey=n;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 r=this.encryptor.encryptChunk(e,t);await this.putChunk(r)})}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,r=fetch){this.baseUrl=e;this.token=t;this.rawFetch=r}async run(){let e=performance.now(),t={ranAt:Date.now(),latencyMs:null,jitterMs:null,downloadMbps:null,uploadMbps:null,durationMs:0};try{let r=await this.measureLatency();t.latencyMs=r.min,t.jitterMs=r.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),r=e.reduce((s,a)=>s+a,0)/e.length,n=e.reduce((s,a)=>s+Math.abs(a-r),0)/e.length;return{min:Math.round(t),jitter:Math.round(n)}}async measureDownload(){let e=Math.floor(2097152),t=performance.now(),r=Array.from({length:4},(c,i)=>this.rawFetch(this.url(`speedtest/download?bytes=${e}&s=${i}`),{cache:"no-store"}).then(l=>l.arrayBuffer())),n=await Promise.all(r),s=(performance.now()-t)/1e3,a=n.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 r=(performance.now()-t)/1e3;return this.toMbps(4194304,r)}toMbps(e,t){return t<=0?0:Math.round(e*8/t/1e6*100)/100}};var L="bug-jar-session";function j(){if(typeof window>"u")return;let e=window.location.hostname.split(".");return e.length<2?void 0:`.${e.slice(-2).join(".")}`}function _(){if(typeof document>"u")return null;let o=document.cookie.split("; ").find(t=>t.startsWith(`${L}=`));if(!o)return null;let e=o.slice(L.length+1);return e?decodeURIComponent(e):null}function q(o,e){if(typeof document>"u")return;let t=j(),r=new Date(e).toUTCString(),n=window.location.protocol==="https:"?"; Secure":"",s=t?`; Domain=${t}`:"";document.cookie=`${L}=${encodeURIComponent(o)}; Path=/; Expires=${r}; SameSite=Lax${s}${n}`}function O(){if(typeof document>"u")return;let o=j(),e=o?`; Domain=${o}`:"";document.cookie=`${L}=; 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: ${K(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,r=o.network.filter(i=>i.error||i.status&&i.status>=400),n=o.network.filter(i=>i.duration&&i.duration>3e3);if(e.push(`Total requests: ${t}`),r.length>0){e.push(`Failed requests (${r.length}):`);for(let i of r)e.push(` - ${i.method} ${i.url} \u2192 ${i.error||`HTTP ${i.status}`}`)}if(n.length>0){e.push(`Slow requests >3s (${n.length}):`);for(let i of n)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(l=>typeof l=="string"?l:JSON.stringify(l)).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,l]of Object.entries(c))e.push(` - ${i}: ${l}`);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} (${V(i.totalTransferSize)})`)}return e.join(`
|
|
84
|
+
`)}function K(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 V(o){return o<1024?`${o}B`:o<1024*1024?`${(o/1024).toFixed(1)}KB`:`${(o/(1024*1024)).toFixed(1)}MB`}async function D(o,e){let t=[],r=JSON.stringify(o,null,2);t.push({name:"report.json",content:new TextEncoder().encode(r)});let n=P(o);if(t.push({name:"summary.md",content:new TextEncoder().encode(n)}),o.screenshot){let s=G(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 G(o){try{let e=o.split(",")[1];if(!e)return null;let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}catch{return null}}function Y(o){let e=[],t=[],r=0;for(let i of o){let l=new TextEncoder().encode(i.name),p=te(i.content),g=Z(l,i.content.length,p);e.push(g),e.push(l),e.push(i.content);let N=Q(l,i.content.length,p,r);t.push(N),t.push(l),r+=g.length+l.length+i.content.length}let n=r,s=0;for(let i of t)s+=i.length;let a=ee(o.length,s,n),c=[...e,...t,a].map(i=>i.buffer);return new Blob(c,{type:"application/zip"})}function Z(o,e,t){let r=new Uint8Array(30),n=new DataView(r.buffer);return n.setUint32(0,67324752,!0),n.setUint16(4,20,!0),n.setUint16(6,0,!0),n.setUint16(8,0,!0),n.setUint16(10,0,!0),n.setUint16(12,0,!0),n.setUint32(14,t,!0),n.setUint32(18,e,!0),n.setUint32(22,e,!0),n.setUint16(26,o.length,!0),n.setUint16(28,0,!0),r}function Q(o,e,t,r){let n=new Uint8Array(46),s=new DataView(n.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,r,!0),n}function ee(o,e,t){let r=new Uint8Array(22),n=new DataView(r.buffer);return n.setUint32(0,101010256,!0),n.setUint16(4,0,!0),n.setUint16(6,0,!0),n.setUint16(8,o,!0),n.setUint16(10,o,!0),n.setUint32(12,e,!0),n.setUint32(16,t,!0),n.setUint16(20,0,!0),r}function te(o){let e=4294967295;for(let t=0;t<o.length;t++){e^=o[t];for(let r=0;r<8;r++)e=e>>>1^(e&1?3988292384:0)}return(e^4294967295)>>>0}var re="0.7.0",ne={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={...ne,...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 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??$()??_();e&&this.startDebugSession(e)}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:re};return this.config.onCapture&&this.config.onCapture(t),t}async captureAndExport(e=""){let t=await this.screenRecorder.stop(),r=await this.capture(e);if(this.config.endpoint)if(t){let n=new FormData;n.append("report",JSON.stringify(r)),n.append("video",t,"recording.webm"),await fetch(this.config.endpoint,{method:"POST",body:n})}else await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});else{let n=await D(r,t),s=URL.createObjectURL(n),a=document.createElement("a");a.href=s,a.download=`bug-report-${r.id}.zip`,a.click(),URL.revokeObjectURL(s)}return r}getReport(){return this.capture()}async startDebugSession(e){if(!this.config.debugSessionEndpoint)return;let t=this.config.debugSessionEndpoint,r=()=>{this.sessionBorder=new x,this.sessionBorder.mount()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",r):r();try{let n=this.network.getRawFetch();this.debugSession=await F(t,e,n),q(this.debugSession.token,this.debugSession.expiresAt);let s=M(t,n);this.dataUploader=new m(this.debugSession.token,this.pageId,"data",this.debugSession.publicKey,s,n),this.videoUploader=new m(this.debugSession.token,this.pageId,"video",this.debugSession.publicKey,s,n),this.runSpeedtest(t,this.debugSession.token,n),this.screenRecorder.setChunkHandler(a=>{this.videoUploader?.pushChunk(a)}),await this.screenRecorder.start(),this.startDataStreaming(),this.registerFlushHandlers()}catch{this.sessionBorder?.unmount()}}startDataStreaming(){let e=t=>{if(!this.dataUploader)return;let r=this.lastFlushTs,n=Date.now(),s={pageId:this.pageId,timestamp:n,url:window.location.href,network:this.network.getEntries().filter(c=>c.timestamp>r),console:this.console.getEntries().filter(c=>c.timestamp>r),errors:this.errors.getEntries().filter(c=>c.timestamp>r),userActions:this.userActions.getEntries().filter(c=>c.timestamp>r)};this.lastFlushTs=n;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(r=>r.timestamp>this.lastFlushTs),console:this.console.getEntries().filter(r=>r.timestamp>this.lastFlushTs),errors:this.errors.getEntries().filter(r=>r.timestamp>this.lastFlushTs),userActions:this.userActions.getEntries().filter(r=>r.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,r){let n=null;try{n=await new B(e,t,r).run()}catch{}await I(e,t,this.pageId,{url:window.location.href,title:document.title,startedAt:Date.now(),environment:this.environment.collect(),speedtest:n},r)}endDebugSession(){O(),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,D as exportAsZip,P as generateSummary,se as init};
|
package/package.json
CHANGED