@devskin/browser-sdk 1.0.48 → 1.0.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/collectors/heatmap.d.ts.map +1 -1
- package/dist/devskin.cjs.js +2 -1
- package/dist/devskin.cjs.js.map +1 -1
- package/dist/devskin.esm.js +2 -1
- package/dist/devskin.esm.js.map +1 -1
- package/dist/devskin.umd.js +2 -1
- package/dist/devskin.umd.js.map +1 -1
- package/dist/devskin.umd.min.js +1 -1
- package/dist/devskin.umd.min.js.map +1 -1
- package/package.json +1 -1
package/dist/devskin.umd.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
!function(A,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(A="undefined"!=typeof globalThis?globalThis:A||self).DevSkin=e()}(this,function(){"use strict";function A(A,e,t,r){return new(t||(t=Promise))(function(n,s){function o(A){try{a(r.next(A))}catch(A){s(A)}}function i(A){try{a(r.throw(A))}catch(A){s(A)}}function a(A){var e;A.done?n(A.value):(e=A.value,e instanceof t?e:new t(function(A){A(e)})).then(o,i)}a((r=r.apply(A,e||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class e{constructor(A){this.config=A}collect(){return{type:this.getDeviceType(),vendor:this.getVendor(),model:this.getModel(),os:this.getOS(),screen:this.getScreenInfo(),memory:this.getMemory(),cores:this.getCores(),connection:this.getConnection()}}getDeviceType(){const A=navigator.userAgent;return/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(A)?"tablet":/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(A)?"mobile":A.includes("Windows")||A.includes("Macintosh")||A.includes("Linux")?"desktop":"unknown"}getVendor(){return navigator.vendor||void 0}getModel(){const A=navigator.userAgent.match(/\(([^)]+)\)/);if(A&&A[1])return A[1]}getOS(){const A=navigator.userAgent;let e="Unknown",t="";if(A.includes("Win"))e="Windows",A.includes("Windows NT 10.0")?t="10":A.includes("Windows NT 6.3")?t="8.1":A.includes("Windows NT 6.2")?t="8":A.includes("Windows NT 6.1")&&(t="7");else if(A.includes("Mac")){e="macOS";const r=A.match(/Mac OS X (\d+[._]\d+[._]\d+)?/);r&&r[1]&&(t=r[1].replace(/_/g,"."))}else if(A.includes("X11")||A.includes("Linux"))e="Linux";else if(A.includes("Android")){e="Android";const r=A.match(/Android (\d+\.?\d*)/);r&&r[1]&&(t=r[1])}else if(A.includes("iOS")||A.includes("iPhone")||A.includes("iPad")){e="iOS";const r=A.match(/OS (\d+_\d+(_\d+)?)/);r&&r[1]&&(t=r[1].replace(/_/g,"."))}return{name:e,version:t}}getScreenInfo(){return{width:window.screen.width,height:window.screen.height,orientation:this.getOrientation(),pixelRatio:window.devicePixelRatio||1}}getOrientation(){return window.screen.orientation?window.screen.orientation.type:window.innerWidth>window.innerHeight?"landscape":"portrait"}getMemory(){return navigator.deviceMemory}getCores(){return navigator.hardwareConcurrency}getConnection(){const A=navigator.connection||navigator.mozConnection||navigator.webkitConnection;if(A)return{effectiveType:A.effectiveType,downlink:A.downlink,rtt:A.rtt,saveData:A.saveData}}}class t{constructor(A){this.config=A,this.geoData=null,this.config.captureLocation&&this.requestGeolocation()}collect(){return Object.assign({url:window.location.href,hostname:window.location.hostname,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,protocol:window.location.protocol,port:window.location.port,referrer:document.referrer},this.geoData)}requestGeolocation(){return A(this,void 0,void 0,function*(){try{const A=Intl.DateTimeFormat().resolvedOptions().timeZone;this.geoData={timezone:A},"geolocation"in navigator&&navigator.geolocation.getCurrentPosition(A=>{this.geoData=Object.assign(Object.assign({},this.geoData),{latitude:A.coords.latitude,longitude:A.coords.longitude}),this.reverseGeocode(A.coords.latitude,A.coords.longitude)},A=>{this.config.debug&&console.log("[DevSkin] Geolocation permission denied or error:",A)},{timeout:5e3,maximumAge:6e5})}catch(A){this.config.debug&&console.error("[DevSkin] Error requesting geolocation:",A)}})}reverseGeocode(e,t){return A(this,void 0,void 0,function*(){try{const A=yield fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${e}&lon=${t}&zoom=10&addressdetails=1`,{headers:{"User-Agent":"DevSkin-SDK/1.0"}});if(A.ok){const e=yield A.json();e.address&&(this.geoData=Object.assign(Object.assign({},this.geoData),{country:e.address.country,region:e.address.state||e.address.region,city:e.address.city||e.address.town||e.address.village}))}}catch(A){this.config.debug&&console.error("[DevSkin] Error reverse geocoding:",A)}})}}class r{constructor(A){this.config=A}collect(){return{name:this.getBrowserName(),version:this.getBrowserVersion(),engine:this.getEngine(),userAgent:navigator.userAgent,language:navigator.language,languages:navigator.languages?Array.from(navigator.languages):[navigator.language],cookieEnabled:navigator.cookieEnabled,doNotTrack:this.getDoNotTrack(),viewport:{width:window.innerWidth,height:window.innerHeight},timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timezoneOffset:(new Date).getTimezoneOffset()}}getBrowserName(){const A=navigator.userAgent;return A.includes("Firefox")?"Firefox":A.includes("Edg")?"Edge":A.includes("Chrome")?"Chrome":A.includes("Safari")&&!A.includes("Chrome")?"Safari":A.includes("Opera")||A.includes("OPR")?"Opera":A.includes("Trident")||A.includes("MSIE")?"Internet Explorer":"Unknown"}getBrowserVersion(){const A=navigator.userAgent;let e=null;switch(this.getBrowserName()){case"Chrome":e=A.match(/Chrome\/(\d+\.\d+)/);break;case"Firefox":e=A.match(/Firefox\/(\d+\.\d+)/);break;case"Safari":e=A.match(/Version\/(\d+\.\d+)/);break;case"Edge":e=A.match(/Edg\/(\d+\.\d+)/);break;case"Opera":if(e=A.match(/(Opera|OPR)\/(\d+\.\d+)/),e)return e[2];break;case"Internet Explorer":if(e=A.match(/(MSIE |rv:)(\d+\.\d+)/),e)return e[2]}return e&&e[1]?e[1]:""}getEngine(){const A=navigator.userAgent;return A.includes("Gecko")&&A.includes("Firefox")?"Gecko":A.includes("AppleWebKit")?A.includes("Chrome")||A.includes("Edg")?"Blink":"WebKit":A.includes("Trident")?"Trident":"Unknown"}getDoNotTrack(){const A=navigator.doNotTrack||window.doNotTrack||navigator.msDoNotTrack;return"1"===A||"yes"===A||"0"!==A&&"no"!==A&&null}}var n,s,o,i,a=-1,c=function(A){addEventListener("pageshow",function(e){e.persisted&&(a=e.timeStamp,A(e))},!0)},B=function(){return window.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]},l=function(){var A=B();return A&&A.activationStart||0},u=function(A,e){var t=B(),r="navigate";return a>=0?r="back-forward-cache":t&&(document.prerendering||l()>0?r="prerender":document.wasDiscarded?r="restore":t.type&&(r=t.type.replace(/_/g,"-"))),{name:A,value:void 0===e?-1:e,rating:"good",delta:0,entries:[],id:"v3-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:r}},d=function(A,e,t){try{if(PerformanceObserver.supportedEntryTypes.includes(A)){var r=new PerformanceObserver(function(A){Promise.resolve().then(function(){e(A.getEntries())})});return r.observe(Object.assign({type:A,buffered:!0},t||{})),r}}catch(A){}},g=function(A,e,t,r){var n,s;return function(o){e.value>=0&&(o||r)&&((s=e.value-(n||0))||void 0===n)&&(n=e.value,e.delta=s,e.rating=function(A,e){return A>e[1]?"poor":A>e[0]?"needs-improvement":"good"}(e.value,t),A(e))}},h=function(A){requestAnimationFrame(function(){return requestAnimationFrame(function(){return A()})})},w=function(A){var e=function(e){"pagehide"!==e.type&&"hidden"!==document.visibilityState||A(e)};addEventListener("visibilitychange",e,!0),addEventListener("pagehide",e,!0)},Q=function(A){var e=!1;return function(t){e||(A(t),e=!0)}},p=-1,C=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},f=function(A){"hidden"===document.visibilityState&&p>-1&&(p="visibilitychange"===A.type?A.timeStamp:0,F())},U=function(){addEventListener("visibilitychange",f,!0),addEventListener("prerenderingchange",f,!0)},F=function(){removeEventListener("visibilitychange",f,!0),removeEventListener("prerenderingchange",f,!0)},m=function(){return p<0&&(p=C(),U(),c(function(){setTimeout(function(){p=C(),U()},0)})),{get firstHiddenTime(){return p}}},y=function(A){document.prerendering?addEventListener("prerenderingchange",function(){return A()},!0):A()},I=[1800,3e3],E=function(A,e){e=e||{},y(function(){var t,r=m(),n=u("FCP"),s=d("paint",function(A){A.forEach(function(A){"first-contentful-paint"===A.name&&(s.disconnect(),A.startTime<r.firstHiddenTime&&(n.value=Math.max(A.startTime-l(),0),n.entries.push(A),t(!0)))})});s&&(t=g(A,n,I,e.reportAllChanges),c(function(r){n=u("FCP"),t=g(A,n,I,e.reportAllChanges),h(function(){n.value=performance.now()-r.timeStamp,t(!0)})}))})},v=[.1,.25],H={passive:!0,capture:!0},b=new Date,S=function(A,e){n||(n=e,s=A,o=new Date,D(removeEventListener),L())},L=function(){if(s>=0&&s<o-b){var A={entryType:"first-input",name:n.type,target:n.target,cancelable:n.cancelable,startTime:n.timeStamp,processingStart:n.timeStamp+s};i.forEach(function(e){e(A)}),i=[]}},K=function(A){if(A.cancelable){var e=(A.timeStamp>1e12?new Date:performance.now())-A.timeStamp;"pointerdown"==A.type?function(A,e){var t=function(){S(A,e),n()},r=function(){n()},n=function(){removeEventListener("pointerup",t,H),removeEventListener("pointercancel",r,H)};addEventListener("pointerup",t,H),addEventListener("pointercancel",r,H)}(e,A):S(e,A)}},D=function(A){["mousedown","keydown","touchstart","pointerdown"].forEach(function(e){return A(e,K,H)})},M=[100,300],k=[2500,4e3],T={},O=[800,1800],x=function A(e){document.prerendering?y(function(){return A(e)}):"complete"!==document.readyState?addEventListener("load",function(){return A(e)},!0):setTimeout(e,0)},R=function(A,e){e=e||{};var t=u("TTFB"),r=g(A,t,O,e.reportAllChanges);x(function(){var n=B();if(n){var s=n.responseStart;if(s<=0||s>performance.now())return;t.value=Math.max(s-l(),0),t.entries=[n],r(!0),c(function(){t=u("TTFB",0),(r=g(A,t,O,e.reportAllChanges))(!0)})}})};class N{constructor(A,e){this.config=A,this.transport=e,this.metrics={}}start(){!function(A,e){e=e||{},E(Q(function(){var t,r=u("CLS",0),n=0,s=[],o=function(A){A.forEach(function(A){if(!A.hadRecentInput){var e=s[0],t=s[s.length-1];n&&A.startTime-t.startTime<1e3&&A.startTime-e.startTime<5e3?(n+=A.value,s.push(A)):(n=A.value,s=[A])}}),n>r.value&&(r.value=n,r.entries=s,t())},i=d("layout-shift",o);i&&(t=g(A,r,v,e.reportAllChanges),w(function(){o(i.takeRecords()),t(!0)}),c(function(){n=0,r=u("CLS",0),t=g(A,r,v,e.reportAllChanges),h(function(){return t()})}),setTimeout(t,0))}))}(A=>this.handleMetric(A)),E(A=>this.handleMetric(A)),function(A,e){e=e||{},y(function(){var t,r=m(),o=u("FID"),a=function(A){A.startTime<r.firstHiddenTime&&(o.value=A.processingStart-A.startTime,o.entries.push(A),t(!0))},B=function(A){A.forEach(a)},l=d("first-input",B);t=g(A,o,M,e.reportAllChanges),l&&w(Q(function(){B(l.takeRecords()),l.disconnect()})),l&&c(function(){var r;o=u("FID"),t=g(A,o,M,e.reportAllChanges),i=[],s=-1,n=null,D(addEventListener),r=a,i.push(r),L()})})}(A=>this.handleMetric(A)),function(A,e){e=e||{},y(function(){var t,r=m(),n=u("LCP"),s=function(A){var e=A[A.length-1];e&&e.startTime<r.firstHiddenTime&&(n.value=Math.max(e.startTime-l(),0),n.entries=[e],t())},o=d("largest-contentful-paint",s);if(o){t=g(A,n,k,e.reportAllChanges);var i=Q(function(){T[n.id]||(s(o.takeRecords()),o.disconnect(),T[n.id]=!0,t(!0))});["keydown","click"].forEach(function(A){addEventListener(A,function(){return setTimeout(i,0)},!0)}),w(i),c(function(r){n=u("LCP"),t=g(A,n,k,e.reportAllChanges),h(function(){n.value=performance.now()-r.timeStamp,T[n.id]=!0,t(!0)})})}})}(A=>this.handleMetric(A)),R(A=>this.handleMetric(A)),this.collectNavigationTimings(),this.collectResourceTimings(),this.config.longTaskThreshold&&this.observeLongTasks()}handleMetric(A){const e=A.name.toLowerCase();this.metrics[e]=A.value,this.config.debug&&console.log(`[DevSkin] Web Vital ${A.name}:`,A.value),this.transport.sendPerformanceMetric({metricName:A.name,value:A.value,rating:A.rating,url:window.location.href,timestamp:(new Date).toISOString()})}collectNavigationTimings(){window.performance&&window.performance.timing&&window.addEventListener("load",()=>{setTimeout(()=>{const A=window.performance.timing,e=window.performance.navigation,t=A.domContentLoadedEventEnd-A.navigationStart,r=A.loadEventEnd-A.navigationStart;this.metrics.domLoad=t,this.metrics.windowLoad=r,this.config.debug&&console.log("[DevSkin] Navigation Timings:",{domLoad:t,windowLoad:r,navigationType:e.type}),this.transport.sendPerformanceMetric({metricName:"Navigation",value:r,url:window.location.href,timestamp:(new Date).toISOString()})},0)})}collectResourceTimings(){window.performance&&window.performance.getEntriesByType&&window.addEventListener("load",()=>{setTimeout(()=>{const A=window.performance.getEntriesByType("resource"),e={total:A.length,byType:{},slowest:[]};A.forEach(A=>{const t=A.initiatorType||"other";e.byType[t]=(e.byType[t]||0)+1}),e.slowest=A.map(A=>({name:A.name,duration:A.duration,type:A.initiatorType})).sort((A,e)=>e.duration-A.duration).slice(0,10),this.config.debug&&console.log("[DevSkin] Resource Timings:",e),this.transport.sendPerformanceMetric({metricName:"Resources",value:A.length,url:window.location.href,timestamp:(new Date).toISOString()})},1e3)})}observeLongTasks(){if("PerformanceObserver"in window)try{new PerformanceObserver(A=>{for(const e of A.getEntries())e.duration>=(this.config.longTaskThreshold||50)&&(this.config.debug&&console.log("[DevSkin] Long Task detected:",e),this.transport.sendPerformanceMetric({metricName:"LongTask",value:e.duration,url:window.location.href,timestamp:(new Date).toISOString()}))}).observe({entryTypes:["longtask"]})}catch(A){this.config.debug&&console.error("[DevSkin] Error observing long tasks:",A)}}getMetrics(){return Object.assign({},this.metrics)}}class G{constructor(A,e){var t;this.config=A,this.transport=e,this.breadcrumbs=[],this.maxBreadcrumbs=(null===(t=A.errorOptions)||void 0===t?void 0:t.maxBreadcrumbs)||30}start(){window.addEventListener("error",A=>{this.handleError(A.error||A.message,{filename:A.filename,lineno:A.lineno,colno:A.colno})}),window.addEventListener("unhandledrejection",A=>{this.handleError(A.reason,{type:"unhandledrejection"})}),this.setupAutomaticBreadcrumbs()}captureError(A,e){this.handleError(A,e)}addBreadcrumb(A){const e={category:A.category,message:A.message,level:A.level||"info",timestamp:(new Date).toISOString(),data:A.data};this.breadcrumbs.push(e),this.breadcrumbs.length>this.maxBreadcrumbs&&this.breadcrumbs.shift(),this.config.debug&&console.log("[DevSkin] Breadcrumb added:",e)}handleError(A,e){var t;if(this.shouldIgnoreError(A))return;let r;if(A instanceof Error){if(r={message:A.message,stack:A.stack,type:A.name||"Error",timestamp:(new Date).toISOString(),sessionId:"",url:window.location.href,breadcrumbs:[...this.breadcrumbs],context:Object.assign(Object.assign({},e),{userAgent:navigator.userAgent,viewport:{width:window.innerWidth,height:window.innerHeight}})},A.stack){const e=A.stack.match(/:(\d+):(\d+)/);e&&(r.line=parseInt(e[1],10),r.column=parseInt(e[2],10))}}else r={message:String(A),type:"Error",timestamp:(new Date).toISOString(),sessionId:"",url:window.location.href,breadcrumbs:[...this.breadcrumbs],context:e};(null===(t=this.config.errorOptions)||void 0===t?void 0:t.includeLocalVariables)&&e&&(r.context=Object.assign(Object.assign({},r.context),{localVariables:e})),this.config.debug&&console.log("[DevSkin] Error captured:",r),this.addBreadcrumb({category:"error",message:r.message,level:"error",data:{type:r.type,stack:r.stack}}),this.transport.sendError(r)}shouldIgnoreError(A){var e,t;const r=(null===(e=this.config.errorOptions)||void 0===e?void 0:e.ignoreErrors)||[],n=A instanceof Error?A.message:String(A);for(const A of r)if(A instanceof RegExp){if(A.test(n))return!0}else if("string"==typeof A&&n.includes(A))return!0;const s=(null===(t=this.config.errorOptions)||void 0===t?void 0:t.denyUrls)||[],o=A instanceof Error?A.stack:"";for(const A of s)if(A.test(o||""))return!0;return!1}setupAutomaticBreadcrumbs(){this.wrapConsole(),document.addEventListener("click",A=>{var e;const t=A.target;this.addBreadcrumb({category:"ui.click",message:`Clicked on ${t.tagName}`,data:{tagName:t.tagName,id:t.id,className:t.className,innerText:null===(e=t.innerText)||void 0===e?void 0:e.substring(0,100)}})},!0);let A=window.location.href;const e=()=>{A!==window.location.href&&(this.addBreadcrumb({category:"navigation",message:`Navigated to ${window.location.pathname}`,data:{from:A,to:window.location.href}}),A=window.location.href)};window.addEventListener("popstate",e),window.addEventListener("hashchange",e);const t=history.pushState;history.pushState=function(...A){t.apply(this,A),e()};const r=history.replaceState;history.replaceState=function(...A){r.apply(this,A),e()}}wrapConsole(){["log","info","warn","error"].forEach(A=>{const e=console[A];console[A]=(...t)=>{if(e.apply(console,t),"warn"===A||"error"===A){const e=t.map(A=>String(A)).join(" ");if(e.startsWith("[DevSkin]"))return;this.addBreadcrumb({category:"console",message:e,level:"warn"===A?"warning":"error",data:{arguments:t}})}}})}getBreadcrumbs(){return[...this.breadcrumbs]}}class V{constructor(A,e){this.config=A,this.transport=e}start(){this.interceptFetch(),this.interceptXHR()}interceptFetch(){if(!window.fetch)return;const e=window.fetch;window.fetch=(...t)=>A(this,void 0,void 0,function*(){var A,r;const[n,s]=t,o="string"==typeof n?n:n instanceof Request?n.url:n.toString(),i=(null==s?void 0:s.method)||"GET",a=Date.now();try{const n=yield e(...t),s=n.clone(),c=Date.now()-a;if(this.shouldIgnoreUrl(o))return n;if((null===(A=this.config.networkRequestOptions)||void 0===A?void 0:A.captureFailedOnly)&&n.ok)return n;const B={url:o,method:i,statusCode:n.status,durationMs:c,responseSize:yield this.getResponseSize(s),timestamp:(new Date).toISOString()};return(null===(r=this.config.networkRequestOptions)||void 0===r?void 0:r.captureHeaders)&&(B.responseHeaders=this.headersToObject(n.headers)),n.ok||(B.errorMessage=`HTTP ${n.status} ${n.statusText}`),this.config.debug&&console.log("[DevSkin] Network request tracked:",B),this.transport.sendNetworkRequest(B),n}catch(A){const e=Date.now()-a;if(!this.shouldIgnoreUrl(o)){const t={url:o,method:i,durationMs:e,timestamp:(new Date).toISOString(),errorMessage:A instanceof Error?A.message:"Network request failed"};this.config.debug&&console.log("[DevSkin] Network request failed:",t),this.transport.sendNetworkRequest(t)}throw A}})}interceptXHR(){const A=XMLHttpRequest.prototype.open,e=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(e,t,r,n,s){return this.__devskin={method:e,url:t.toString(),startTime:Date.now()},void 0!==n?A.call(this,e,t,null==r||r,n,null!=s?s:void 0):void 0!==r?A.call(this,e,t,r):A.call(this,e,t,!0)},XMLHttpRequest.prototype.send=function(A){const t=this,r=t.__devskin;if(!r)return e.call(this,A);const n=window.__devskinNetworkCollector,s=()=>{const A=Date.now()-r.startTime;if(!(null==n?void 0:n.shouldIgnoreUrl(r.url))){const e={url:r.url,method:r.method,durationMs:A,timestamp:(new Date).toISOString(),errorMessage:"XHR request failed"};(null==n?void 0:n.config.debug)&&console.log("[DevSkin] XHR request failed:",e),null==n||n.transport.sendNetworkRequest(e)}};return t.addEventListener("load",()=>{var A,e;const s=Date.now()-r.startTime;if(null==n?void 0:n.shouldIgnoreUrl(r.url))return;if((null===(A=null==n?void 0:n.config.networkRequestOptions)||void 0===A?void 0:A.captureFailedOnly)&&t.status>=200&&t.status<400)return;const o={url:r.url,method:r.method,statusCode:t.status,durationMs:s,timestamp:(new Date).toISOString()};(null===(e=null==n?void 0:n.config.networkRequestOptions)||void 0===e?void 0:e.captureHeaders)&&(o.responseHeaders=n.parseResponseHeaders(t.getAllResponseHeaders())),(0===t.status||t.status>=400)&&(o.errorMessage=`HTTP ${t.status} ${t.statusText}`),(null==n?void 0:n.config.debug)&&console.log("[DevSkin] XHR request tracked:",o),null==n||n.transport.sendNetworkRequest(o)}),t.addEventListener("error",s),t.addEventListener("abort",s),e.call(this,A)},window.__devskinNetworkCollector=this}shouldIgnoreUrl(A){var e;if(A.includes(this.config.apiUrl||""))return!0;const t=(null===(e=this.config.networkRequestOptions)||void 0===e?void 0:e.ignoreUrls)||[];for(const e of t)if(e.test(A))return!0;return!1}getResponseSize(e){return A(this,void 0,void 0,function*(){try{return(yield e.blob()).size}catch(A){return}})}headersToObject(A){const e={};return A.forEach((A,t)=>{e[t]=A}),e}parseResponseHeaders(A){const e={};if(!A)return e;return A.trim().split(/[\r\n]+/).forEach(A=>{const t=A.split(": "),r=t.shift(),n=t.join(": ");r&&(e[r]=n)}),e}}class P{constructor(A,e,t,r){this.config=A,this.transport=e,this.anonymousId=t,this.sessionId=r,this.clickData=[],this.scrollData=[],this.mouseMoveData=[],this.maxScrollDepth=0,this.flushInterval=null,this.mouseMoveSampling=.1}start(){var A;(null===(A=this.config.heatmapOptions)||void 0===A?void 0:A.enabled)&&(this.config.debug&&console.log("[DevSkin] Starting heatmap collection"),!1!==this.config.heatmapOptions.trackClicks&&this.trackClicks(),!1!==this.config.heatmapOptions.trackScroll&&this.trackScrollDepth(),this.config.heatmapOptions.trackMouseMovement&&(this.mouseMoveSampling=this.config.heatmapOptions.mouseMoveSampling||.1,this.trackMouseMovement()),this.flushInterval=setInterval(()=>{this.flush()},1e4),window.addEventListener("beforeunload",()=>{this.flush()}))}stop(){this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.flush()}trackClicks(){document.addEventListener("click",A=>{const e=A.target,t=e.getBoundingClientRect(),r=A.clientX-t.left,n=A.clientY-t.top,s=A.clientX+window.scrollX,o=A.clientY+window.scrollY,i={x:A.clientX,y:A.clientY,relativeX:r,relativeY:n,pageX:s,pageY:o,element:this.getElementSelector(e),elementId:e.id||void 0,elementClass:e.className||void 0,pageUrl:window.location.href,timestamp:(new Date).toISOString(),viewportWidth:window.innerWidth,viewportHeight:window.innerHeight};this.clickData.push(i),this.config.debug&&console.log("[DevSkin] Click tracked:",i),this.clickData.length>=50&&this.flush()},!0)}trackScrollDepth(){const A=()=>{const A=window.innerHeight,e=document.documentElement.scrollHeight,t=window.scrollY||document.documentElement.scrollTop,r=Math.round((t+A)/e*100);if(r>this.maxScrollDepth){this.maxScrollDepth=r;const t={depth:r,maxDepth:this.maxScrollDepth,pageHeight:e,viewportHeight:A,pageUrl:window.location.href,timestamp:(new Date).toISOString()};this.scrollData.push(t),this.config.debug&&console.log("[DevSkin] Scroll depth:",r+"%")}};let e=null;window.addEventListener("scroll",()=>{e&&clearTimeout(e),e=setTimeout(A,100)}),A()}trackMouseMovement(){let A=null;window.addEventListener("mousemove",e=>{if(Math.random()>this.mouseMoveSampling)return;if(A)return;A=setTimeout(()=>{A=null},100);const t={x:e.clientX+window.scrollX,y:e.clientY+window.scrollY,pageUrl:window.location.href,timestamp:(new Date).toISOString()};this.mouseMoveData.push(t),this.mouseMoveData.length>=100&&this.flush()})}flush(){this.clickData.length>0&&(this.clickData.forEach(A=>{this.transport.sendHeatmapData(Object.assign({type:"click",anonymousId:this.anonymousId,sessionId:this.sessionId},A))}),this.clickData=[]),this.scrollData.length>0&&(this.scrollData.forEach(A=>{this.transport.sendHeatmapData(Object.assign({type:"scroll",anonymousId:this.anonymousId,sessionId:this.sessionId},A))}),this.scrollData=[]),this.mouseMoveData.length>0&&(this.mouseMoveData.forEach(A=>{this.transport.sendHeatmapData(Object.assign({type:"mousemove",anonymousId:this.anonymousId,sessionId:this.sessionId},A))}),this.mouseMoveData=[])}getElementSelector(A){if(A.id)return`#${A.id}`;if(A.className){const e=A.className.split(" ").filter(A=>A);if(e.length>0)return`${A.tagName.toLowerCase()}.${e.join(".")}`}return A.tagName.toLowerCase()}}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function X(A){return A&&A.__esModule&&Object.prototype.hasOwnProperty.call(A,"default")?A.default:A}var J={exports:{}};
|
|
1
|
+
!function(A,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(A="undefined"!=typeof globalThis?globalThis:A||self).DevSkin=e()}(this,function(){"use strict";function A(A,e,t,r){return new(t||(t=Promise))(function(n,s){function o(A){try{a(r.next(A))}catch(A){s(A)}}function i(A){try{a(r.throw(A))}catch(A){s(A)}}function a(A){var e;A.done?n(A.value):(e=A.value,e instanceof t?e:new t(function(A){A(e)})).then(o,i)}a((r=r.apply(A,e||[])).next())})}"function"==typeof SuppressedError&&SuppressedError;class e{constructor(A){this.config=A}collect(){return{type:this.getDeviceType(),vendor:this.getVendor(),model:this.getModel(),os:this.getOS(),screen:this.getScreenInfo(),memory:this.getMemory(),cores:this.getCores(),connection:this.getConnection()}}getDeviceType(){const A=navigator.userAgent;return/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(A)?"tablet":/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(A)?"mobile":A.includes("Windows")||A.includes("Macintosh")||A.includes("Linux")?"desktop":"unknown"}getVendor(){return navigator.vendor||void 0}getModel(){const A=navigator.userAgent.match(/\(([^)]+)\)/);if(A&&A[1])return A[1]}getOS(){const A=navigator.userAgent;let e="Unknown",t="";if(A.includes("Win"))e="Windows",A.includes("Windows NT 10.0")?t="10":A.includes("Windows NT 6.3")?t="8.1":A.includes("Windows NT 6.2")?t="8":A.includes("Windows NT 6.1")&&(t="7");else if(A.includes("Mac")){e="macOS";const r=A.match(/Mac OS X (\d+[._]\d+[._]\d+)?/);r&&r[1]&&(t=r[1].replace(/_/g,"."))}else if(A.includes("X11")||A.includes("Linux"))e="Linux";else if(A.includes("Android")){e="Android";const r=A.match(/Android (\d+\.?\d*)/);r&&r[1]&&(t=r[1])}else if(A.includes("iOS")||A.includes("iPhone")||A.includes("iPad")){e="iOS";const r=A.match(/OS (\d+_\d+(_\d+)?)/);r&&r[1]&&(t=r[1].replace(/_/g,"."))}return{name:e,version:t}}getScreenInfo(){return{width:window.screen.width,height:window.screen.height,orientation:this.getOrientation(),pixelRatio:window.devicePixelRatio||1}}getOrientation(){return window.screen.orientation?window.screen.orientation.type:window.innerWidth>window.innerHeight?"landscape":"portrait"}getMemory(){return navigator.deviceMemory}getCores(){return navigator.hardwareConcurrency}getConnection(){const A=navigator.connection||navigator.mozConnection||navigator.webkitConnection;if(A)return{effectiveType:A.effectiveType,downlink:A.downlink,rtt:A.rtt,saveData:A.saveData}}}class t{constructor(A){this.config=A,this.geoData=null,this.config.captureLocation&&this.requestGeolocation()}collect(){return Object.assign({url:window.location.href,hostname:window.location.hostname,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,protocol:window.location.protocol,port:window.location.port,referrer:document.referrer},this.geoData)}requestGeolocation(){return A(this,void 0,void 0,function*(){try{const A=Intl.DateTimeFormat().resolvedOptions().timeZone;this.geoData={timezone:A},"geolocation"in navigator&&navigator.geolocation.getCurrentPosition(A=>{this.geoData=Object.assign(Object.assign({},this.geoData),{latitude:A.coords.latitude,longitude:A.coords.longitude}),this.reverseGeocode(A.coords.latitude,A.coords.longitude)},A=>{this.config.debug&&console.log("[DevSkin] Geolocation permission denied or error:",A)},{timeout:5e3,maximumAge:6e5})}catch(A){this.config.debug&&console.error("[DevSkin] Error requesting geolocation:",A)}})}reverseGeocode(e,t){return A(this,void 0,void 0,function*(){try{const A=yield fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${e}&lon=${t}&zoom=10&addressdetails=1`,{headers:{"User-Agent":"DevSkin-SDK/1.0"}});if(A.ok){const e=yield A.json();e.address&&(this.geoData=Object.assign(Object.assign({},this.geoData),{country:e.address.country,region:e.address.state||e.address.region,city:e.address.city||e.address.town||e.address.village}))}}catch(A){this.config.debug&&console.error("[DevSkin] Error reverse geocoding:",A)}})}}class r{constructor(A){this.config=A}collect(){return{name:this.getBrowserName(),version:this.getBrowserVersion(),engine:this.getEngine(),userAgent:navigator.userAgent,language:navigator.language,languages:navigator.languages?Array.from(navigator.languages):[navigator.language],cookieEnabled:navigator.cookieEnabled,doNotTrack:this.getDoNotTrack(),viewport:{width:window.innerWidth,height:window.innerHeight},timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,timezoneOffset:(new Date).getTimezoneOffset()}}getBrowserName(){const A=navigator.userAgent;return A.includes("Firefox")?"Firefox":A.includes("Edg")?"Edge":A.includes("Chrome")?"Chrome":A.includes("Safari")&&!A.includes("Chrome")?"Safari":A.includes("Opera")||A.includes("OPR")?"Opera":A.includes("Trident")||A.includes("MSIE")?"Internet Explorer":"Unknown"}getBrowserVersion(){const A=navigator.userAgent;let e=null;switch(this.getBrowserName()){case"Chrome":e=A.match(/Chrome\/(\d+\.\d+)/);break;case"Firefox":e=A.match(/Firefox\/(\d+\.\d+)/);break;case"Safari":e=A.match(/Version\/(\d+\.\d+)/);break;case"Edge":e=A.match(/Edg\/(\d+\.\d+)/);break;case"Opera":if(e=A.match(/(Opera|OPR)\/(\d+\.\d+)/),e)return e[2];break;case"Internet Explorer":if(e=A.match(/(MSIE |rv:)(\d+\.\d+)/),e)return e[2]}return e&&e[1]?e[1]:""}getEngine(){const A=navigator.userAgent;return A.includes("Gecko")&&A.includes("Firefox")?"Gecko":A.includes("AppleWebKit")?A.includes("Chrome")||A.includes("Edg")?"Blink":"WebKit":A.includes("Trident")?"Trident":"Unknown"}getDoNotTrack(){const A=navigator.doNotTrack||window.doNotTrack||navigator.msDoNotTrack;return"1"===A||"yes"===A||"0"!==A&&"no"!==A&&null}}var n,s,o,i,a=-1,c=function(A){addEventListener("pageshow",function(e){e.persisted&&(a=e.timeStamp,A(e))},!0)},B=function(){return window.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0]},l=function(){var A=B();return A&&A.activationStart||0},u=function(A,e){var t=B(),r="navigate";return a>=0?r="back-forward-cache":t&&(document.prerendering||l()>0?r="prerender":document.wasDiscarded?r="restore":t.type&&(r=t.type.replace(/_/g,"-"))),{name:A,value:void 0===e?-1:e,rating:"good",delta:0,entries:[],id:"v3-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:r}},d=function(A,e,t){try{if(PerformanceObserver.supportedEntryTypes.includes(A)){var r=new PerformanceObserver(function(A){Promise.resolve().then(function(){e(A.getEntries())})});return r.observe(Object.assign({type:A,buffered:!0},t||{})),r}}catch(A){}},g=function(A,e,t,r){var n,s;return function(o){e.value>=0&&(o||r)&&((s=e.value-(n||0))||void 0===n)&&(n=e.value,e.delta=s,e.rating=function(A,e){return A>e[1]?"poor":A>e[0]?"needs-improvement":"good"}(e.value,t),A(e))}},h=function(A){requestAnimationFrame(function(){return requestAnimationFrame(function(){return A()})})},w=function(A){var e=function(e){"pagehide"!==e.type&&"hidden"!==document.visibilityState||A(e)};addEventListener("visibilitychange",e,!0),addEventListener("pagehide",e,!0)},Q=function(A){var e=!1;return function(t){e||(A(t),e=!0)}},p=-1,C=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},f=function(A){"hidden"===document.visibilityState&&p>-1&&(p="visibilitychange"===A.type?A.timeStamp:0,F())},U=function(){addEventListener("visibilitychange",f,!0),addEventListener("prerenderingchange",f,!0)},F=function(){removeEventListener("visibilitychange",f,!0),removeEventListener("prerenderingchange",f,!0)},m=function(){return p<0&&(p=C(),U(),c(function(){setTimeout(function(){p=C(),U()},0)})),{get firstHiddenTime(){return p}}},y=function(A){document.prerendering?addEventListener("prerenderingchange",function(){return A()},!0):A()},I=[1800,3e3],E=function(A,e){e=e||{},y(function(){var t,r=m(),n=u("FCP"),s=d("paint",function(A){A.forEach(function(A){"first-contentful-paint"===A.name&&(s.disconnect(),A.startTime<r.firstHiddenTime&&(n.value=Math.max(A.startTime-l(),0),n.entries.push(A),t(!0)))})});s&&(t=g(A,n,I,e.reportAllChanges),c(function(r){n=u("FCP"),t=g(A,n,I,e.reportAllChanges),h(function(){n.value=performance.now()-r.timeStamp,t(!0)})}))})},v=[.1,.25],H={passive:!0,capture:!0},b=new Date,S=function(A,e){n||(n=e,s=A,o=new Date,D(removeEventListener),L())},L=function(){if(s>=0&&s<o-b){var A={entryType:"first-input",name:n.type,target:n.target,cancelable:n.cancelable,startTime:n.timeStamp,processingStart:n.timeStamp+s};i.forEach(function(e){e(A)}),i=[]}},K=function(A){if(A.cancelable){var e=(A.timeStamp>1e12?new Date:performance.now())-A.timeStamp;"pointerdown"==A.type?function(A,e){var t=function(){S(A,e),n()},r=function(){n()},n=function(){removeEventListener("pointerup",t,H),removeEventListener("pointercancel",r,H)};addEventListener("pointerup",t,H),addEventListener("pointercancel",r,H)}(e,A):S(e,A)}},D=function(A){["mousedown","keydown","touchstart","pointerdown"].forEach(function(e){return A(e,K,H)})},M=[100,300],k=[2500,4e3],T={},O=[800,1800],x=function A(e){document.prerendering?y(function(){return A(e)}):"complete"!==document.readyState?addEventListener("load",function(){return A(e)},!0):setTimeout(e,0)},R=function(A,e){e=e||{};var t=u("TTFB"),r=g(A,t,O,e.reportAllChanges);x(function(){var n=B();if(n){var s=n.responseStart;if(s<=0||s>performance.now())return;t.value=Math.max(s-l(),0),t.entries=[n],r(!0),c(function(){t=u("TTFB",0),(r=g(A,t,O,e.reportAllChanges))(!0)})}})};class N{constructor(A,e){this.config=A,this.transport=e,this.metrics={}}start(){!function(A,e){e=e||{},E(Q(function(){var t,r=u("CLS",0),n=0,s=[],o=function(A){A.forEach(function(A){if(!A.hadRecentInput){var e=s[0],t=s[s.length-1];n&&A.startTime-t.startTime<1e3&&A.startTime-e.startTime<5e3?(n+=A.value,s.push(A)):(n=A.value,s=[A])}}),n>r.value&&(r.value=n,r.entries=s,t())},i=d("layout-shift",o);i&&(t=g(A,r,v,e.reportAllChanges),w(function(){o(i.takeRecords()),t(!0)}),c(function(){n=0,r=u("CLS",0),t=g(A,r,v,e.reportAllChanges),h(function(){return t()})}),setTimeout(t,0))}))}(A=>this.handleMetric(A)),E(A=>this.handleMetric(A)),function(A,e){e=e||{},y(function(){var t,r=m(),o=u("FID"),a=function(A){A.startTime<r.firstHiddenTime&&(o.value=A.processingStart-A.startTime,o.entries.push(A),t(!0))},B=function(A){A.forEach(a)},l=d("first-input",B);t=g(A,o,M,e.reportAllChanges),l&&w(Q(function(){B(l.takeRecords()),l.disconnect()})),l&&c(function(){var r;o=u("FID"),t=g(A,o,M,e.reportAllChanges),i=[],s=-1,n=null,D(addEventListener),r=a,i.push(r),L()})})}(A=>this.handleMetric(A)),function(A,e){e=e||{},y(function(){var t,r=m(),n=u("LCP"),s=function(A){var e=A[A.length-1];e&&e.startTime<r.firstHiddenTime&&(n.value=Math.max(e.startTime-l(),0),n.entries=[e],t())},o=d("largest-contentful-paint",s);if(o){t=g(A,n,k,e.reportAllChanges);var i=Q(function(){T[n.id]||(s(o.takeRecords()),o.disconnect(),T[n.id]=!0,t(!0))});["keydown","click"].forEach(function(A){addEventListener(A,function(){return setTimeout(i,0)},!0)}),w(i),c(function(r){n=u("LCP"),t=g(A,n,k,e.reportAllChanges),h(function(){n.value=performance.now()-r.timeStamp,T[n.id]=!0,t(!0)})})}})}(A=>this.handleMetric(A)),R(A=>this.handleMetric(A)),this.collectNavigationTimings(),this.collectResourceTimings(),this.config.longTaskThreshold&&this.observeLongTasks()}handleMetric(A){const e=A.name.toLowerCase();this.metrics[e]=A.value,this.config.debug&&console.log(`[DevSkin] Web Vital ${A.name}:`,A.value),this.transport.sendPerformanceMetric({metricName:A.name,value:A.value,rating:A.rating,url:window.location.href,timestamp:(new Date).toISOString()})}collectNavigationTimings(){window.performance&&window.performance.timing&&window.addEventListener("load",()=>{setTimeout(()=>{const A=window.performance.timing,e=window.performance.navigation,t=A.domContentLoadedEventEnd-A.navigationStart,r=A.loadEventEnd-A.navigationStart;this.metrics.domLoad=t,this.metrics.windowLoad=r,this.config.debug&&console.log("[DevSkin] Navigation Timings:",{domLoad:t,windowLoad:r,navigationType:e.type}),this.transport.sendPerformanceMetric({metricName:"Navigation",value:r,url:window.location.href,timestamp:(new Date).toISOString()})},0)})}collectResourceTimings(){window.performance&&window.performance.getEntriesByType&&window.addEventListener("load",()=>{setTimeout(()=>{const A=window.performance.getEntriesByType("resource"),e={total:A.length,byType:{},slowest:[]};A.forEach(A=>{const t=A.initiatorType||"other";e.byType[t]=(e.byType[t]||0)+1}),e.slowest=A.map(A=>({name:A.name,duration:A.duration,type:A.initiatorType})).sort((A,e)=>e.duration-A.duration).slice(0,10),this.config.debug&&console.log("[DevSkin] Resource Timings:",e),this.transport.sendPerformanceMetric({metricName:"Resources",value:A.length,url:window.location.href,timestamp:(new Date).toISOString()})},1e3)})}observeLongTasks(){if("PerformanceObserver"in window)try{new PerformanceObserver(A=>{for(const e of A.getEntries())e.duration>=(this.config.longTaskThreshold||50)&&(this.config.debug&&console.log("[DevSkin] Long Task detected:",e),this.transport.sendPerformanceMetric({metricName:"LongTask",value:e.duration,url:window.location.href,timestamp:(new Date).toISOString()}))}).observe({entryTypes:["longtask"]})}catch(A){this.config.debug&&console.error("[DevSkin] Error observing long tasks:",A)}}getMetrics(){return Object.assign({},this.metrics)}}class G{constructor(A,e){var t;this.config=A,this.transport=e,this.breadcrumbs=[],this.maxBreadcrumbs=(null===(t=A.errorOptions)||void 0===t?void 0:t.maxBreadcrumbs)||30}start(){window.addEventListener("error",A=>{this.handleError(A.error||A.message,{filename:A.filename,lineno:A.lineno,colno:A.colno})}),window.addEventListener("unhandledrejection",A=>{this.handleError(A.reason,{type:"unhandledrejection"})}),this.setupAutomaticBreadcrumbs()}captureError(A,e){this.handleError(A,e)}addBreadcrumb(A){const e={category:A.category,message:A.message,level:A.level||"info",timestamp:(new Date).toISOString(),data:A.data};this.breadcrumbs.push(e),this.breadcrumbs.length>this.maxBreadcrumbs&&this.breadcrumbs.shift(),this.config.debug&&console.log("[DevSkin] Breadcrumb added:",e)}handleError(A,e){var t;if(this.shouldIgnoreError(A))return;let r;if(A instanceof Error){if(r={message:A.message,stack:A.stack,type:A.name||"Error",timestamp:(new Date).toISOString(),sessionId:"",url:window.location.href,breadcrumbs:[...this.breadcrumbs],context:Object.assign(Object.assign({},e),{userAgent:navigator.userAgent,viewport:{width:window.innerWidth,height:window.innerHeight}})},A.stack){const e=A.stack.match(/:(\d+):(\d+)/);e&&(r.line=parseInt(e[1],10),r.column=parseInt(e[2],10))}}else r={message:String(A),type:"Error",timestamp:(new Date).toISOString(),sessionId:"",url:window.location.href,breadcrumbs:[...this.breadcrumbs],context:e};(null===(t=this.config.errorOptions)||void 0===t?void 0:t.includeLocalVariables)&&e&&(r.context=Object.assign(Object.assign({},r.context),{localVariables:e})),this.config.debug&&console.log("[DevSkin] Error captured:",r),this.addBreadcrumb({category:"error",message:r.message,level:"error",data:{type:r.type,stack:r.stack}}),this.transport.sendError(r)}shouldIgnoreError(A){var e,t;const r=(null===(e=this.config.errorOptions)||void 0===e?void 0:e.ignoreErrors)||[],n=A instanceof Error?A.message:String(A);for(const A of r)if(A instanceof RegExp){if(A.test(n))return!0}else if("string"==typeof A&&n.includes(A))return!0;const s=(null===(t=this.config.errorOptions)||void 0===t?void 0:t.denyUrls)||[],o=A instanceof Error?A.stack:"";for(const A of s)if(A.test(o||""))return!0;return!1}setupAutomaticBreadcrumbs(){this.wrapConsole(),document.addEventListener("click",A=>{var e;const t=A.target;this.addBreadcrumb({category:"ui.click",message:`Clicked on ${t.tagName}`,data:{tagName:t.tagName,id:t.id,className:t.className,innerText:null===(e=t.innerText)||void 0===e?void 0:e.substring(0,100)}})},!0);let A=window.location.href;const e=()=>{A!==window.location.href&&(this.addBreadcrumb({category:"navigation",message:`Navigated to ${window.location.pathname}`,data:{from:A,to:window.location.href}}),A=window.location.href)};window.addEventListener("popstate",e),window.addEventListener("hashchange",e);const t=history.pushState;history.pushState=function(...A){t.apply(this,A),e()};const r=history.replaceState;history.replaceState=function(...A){r.apply(this,A),e()}}wrapConsole(){["log","info","warn","error"].forEach(A=>{const e=console[A];console[A]=(...t)=>{if(e.apply(console,t),"warn"===A||"error"===A){const e=t.map(A=>String(A)).join(" ");if(e.startsWith("[DevSkin]"))return;this.addBreadcrumb({category:"console",message:e,level:"warn"===A?"warning":"error",data:{arguments:t}})}}})}getBreadcrumbs(){return[...this.breadcrumbs]}}class V{constructor(A,e){this.config=A,this.transport=e}start(){this.interceptFetch(),this.interceptXHR()}interceptFetch(){if(!window.fetch)return;const e=window.fetch;window.fetch=(...t)=>A(this,void 0,void 0,function*(){var A,r;const[n,s]=t,o="string"==typeof n?n:n instanceof Request?n.url:n.toString(),i=(null==s?void 0:s.method)||"GET",a=Date.now();try{const n=yield e(...t),s=n.clone(),c=Date.now()-a;if(this.shouldIgnoreUrl(o))return n;if((null===(A=this.config.networkRequestOptions)||void 0===A?void 0:A.captureFailedOnly)&&n.ok)return n;const B={url:o,method:i,statusCode:n.status,durationMs:c,responseSize:yield this.getResponseSize(s),timestamp:(new Date).toISOString()};return(null===(r=this.config.networkRequestOptions)||void 0===r?void 0:r.captureHeaders)&&(B.responseHeaders=this.headersToObject(n.headers)),n.ok||(B.errorMessage=`HTTP ${n.status} ${n.statusText}`),this.config.debug&&console.log("[DevSkin] Network request tracked:",B),this.transport.sendNetworkRequest(B),n}catch(A){const e=Date.now()-a;if(!this.shouldIgnoreUrl(o)){const t={url:o,method:i,durationMs:e,timestamp:(new Date).toISOString(),errorMessage:A instanceof Error?A.message:"Network request failed"};this.config.debug&&console.log("[DevSkin] Network request failed:",t),this.transport.sendNetworkRequest(t)}throw A}})}interceptXHR(){const A=XMLHttpRequest.prototype.open,e=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(e,t,r,n,s){return this.__devskin={method:e,url:t.toString(),startTime:Date.now()},void 0!==n?A.call(this,e,t,null==r||r,n,null!=s?s:void 0):void 0!==r?A.call(this,e,t,r):A.call(this,e,t,!0)},XMLHttpRequest.prototype.send=function(A){const t=this,r=t.__devskin;if(!r)return e.call(this,A);const n=window.__devskinNetworkCollector,s=()=>{const A=Date.now()-r.startTime;if(!(null==n?void 0:n.shouldIgnoreUrl(r.url))){const e={url:r.url,method:r.method,durationMs:A,timestamp:(new Date).toISOString(),errorMessage:"XHR request failed"};(null==n?void 0:n.config.debug)&&console.log("[DevSkin] XHR request failed:",e),null==n||n.transport.sendNetworkRequest(e)}};return t.addEventListener("load",()=>{var A,e;const s=Date.now()-r.startTime;if(null==n?void 0:n.shouldIgnoreUrl(r.url))return;if((null===(A=null==n?void 0:n.config.networkRequestOptions)||void 0===A?void 0:A.captureFailedOnly)&&t.status>=200&&t.status<400)return;const o={url:r.url,method:r.method,statusCode:t.status,durationMs:s,timestamp:(new Date).toISOString()};(null===(e=null==n?void 0:n.config.networkRequestOptions)||void 0===e?void 0:e.captureHeaders)&&(o.responseHeaders=n.parseResponseHeaders(t.getAllResponseHeaders())),(0===t.status||t.status>=400)&&(o.errorMessage=`HTTP ${t.status} ${t.statusText}`),(null==n?void 0:n.config.debug)&&console.log("[DevSkin] XHR request tracked:",o),null==n||n.transport.sendNetworkRequest(o)}),t.addEventListener("error",s),t.addEventListener("abort",s),e.call(this,A)},window.__devskinNetworkCollector=this}shouldIgnoreUrl(A){var e;if(A.includes(this.config.apiUrl||""))return!0;const t=(null===(e=this.config.networkRequestOptions)||void 0===e?void 0:e.ignoreUrls)||[];for(const e of t)if(e.test(A))return!0;return!1}getResponseSize(e){return A(this,void 0,void 0,function*(){try{return(yield e.blob()).size}catch(A){return}})}headersToObject(A){const e={};return A.forEach((A,t)=>{e[t]=A}),e}parseResponseHeaders(A){const e={};if(!A)return e;return A.trim().split(/[\r\n]+/).forEach(A=>{const t=A.split(": "),r=t.shift(),n=t.join(": ");r&&(e[r]=n)}),e}}class P{constructor(A,e,t,r){this.config=A,this.transport=e,this.anonymousId=t,this.sessionId=r,this.clickData=[],this.scrollData=[],this.mouseMoveData=[],this.maxScrollDepth=0,this.flushInterval=null,this.mouseMoveSampling=.1}start(){var A;(null===(A=this.config.heatmapOptions)||void 0===A?void 0:A.enabled)&&(this.config.debug&&console.log("[DevSkin] Starting heatmap collection"),!1!==this.config.heatmapOptions.trackClicks&&this.trackClicks(),!1!==this.config.heatmapOptions.trackScroll&&this.trackScrollDepth(),this.config.heatmapOptions.trackMouseMovement&&(this.mouseMoveSampling=this.config.heatmapOptions.mouseMoveSampling||.1,this.trackMouseMovement()),this.flushInterval=setInterval(()=>{this.flush()},1e4),window.addEventListener("beforeunload",()=>{this.flush()}))}stop(){this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.flush()}trackClicks(){document.addEventListener("click",A=>{const e=A.target,t=e.getBoundingClientRect(),r=A.clientX-t.left,n=A.clientY-t.top,s=A.clientX+window.scrollX,o=A.clientY+window.scrollY,i={x:A.clientX,y:A.clientY,relativeX:r,relativeY:n,pageX:s,pageY:o,element:this.getElementSelector(e),elementId:e.id||void 0,elementClass:e.className||void 0,pageUrl:window.location.href,timestamp:(new Date).toISOString(),viewportWidth:window.innerWidth,viewportHeight:window.innerHeight};this.clickData.push(i),this.config.debug&&console.log("[DevSkin] Click tracked:",i),this.clickData.length>=50&&this.flush()},!0)}trackScrollDepth(){const A=()=>{const A=window.innerHeight,e=document.documentElement.scrollHeight,t=window.scrollY||document.documentElement.scrollTop,r=Math.round((t+A)/e*100);if(r>this.maxScrollDepth){this.maxScrollDepth=r;const t={depth:r,maxDepth:this.maxScrollDepth,pageHeight:e,viewportHeight:A,pageUrl:window.location.href,timestamp:(new Date).toISOString()};this.scrollData.push(t),this.config.debug&&console.log("[DevSkin] Scroll depth:",r+"%")}};let e=null;window.addEventListener("scroll",()=>{e&&clearTimeout(e),e=setTimeout(A,100)}),A()}trackMouseMovement(){let A=null;window.addEventListener("mousemove",e=>{if(Math.random()>this.mouseMoveSampling)return;if(A)return;A=setTimeout(()=>{A=null},100);const t={x:e.clientX+window.scrollX,y:e.clientY+window.scrollY,pageUrl:window.location.href,timestamp:(new Date).toISOString()};this.mouseMoveData.push(t),this.mouseMoveData.length>=100&&this.flush()})}flush(){this.clickData.length>0&&(this.clickData.forEach(A=>{this.transport.sendHeatmapData(Object.assign({type:"click",anonymousId:this.anonymousId,sessionId:this.sessionId},A))}),this.clickData=[]),this.scrollData.length>0&&(this.scrollData.forEach(A=>{this.transport.sendHeatmapData(Object.assign({type:"scroll",anonymousId:this.anonymousId,sessionId:this.sessionId},A))}),this.scrollData=[]),this.mouseMoveData.length>0&&(this.mouseMoveData.forEach(A=>{this.transport.sendHeatmapData(Object.assign({type:"mousemove",anonymousId:this.anonymousId,sessionId:this.sessionId},A))}),this.mouseMoveData=[])}getElementSelector(A){if(A.id)return`#${A.id}`;if(A.className){const e=("string"==typeof A.className?A.className:A.className.baseVal||"").split(" ").filter(A=>A);if(e.length>0)return`${A.tagName.toLowerCase()}.${e.join(".")}`}return A.tagName.toLowerCase()}}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function X(A){return A&&A.__esModule&&Object.prototype.hasOwnProperty.call(A,"default")?A.default:A}var J={exports:{}};
|
|
2
2
|
/*!
|
|
3
3
|
* html2canvas 1.4.1 <https://html2canvas.hertzen.com>
|
|
4
4
|
* Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
|