@faststats/web 0.0.2 → 0.0.4
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/CHANGELOG.md +14 -0
- package/dist/module.d.ts +0 -3
- package/dist/module.js +3 -408
- package/package.json +3 -4
- package/src/analytics.ts +18 -45
- package/src/error.ts +0 -6
- package/src/replay.ts +0 -6
- package/src/web-vitals.ts +0 -7
- package/tsdown.config.ts +8 -47
- package/dist/error.iife.js +0 -3
- package/dist/error.js +0 -3
- package/dist/replay.iife.js +0 -29
- package/dist/replay.js +0 -29
- package/dist/script.iife.js +0 -1
- package/dist/script.js +0 -1
- package/dist/web-vitals.iife.js +0 -1
- package/dist/web-vitals.js +0 -1
- package/src/index.ts +0 -95
package/dist/script.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var FA_Script=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});function t(e){return e?``:n()}function n(){if(typeof localStorage>`u`)return``;let e=localStorage.getItem(`faststats_anon_id`);if(e)return e;let t=crypto.randomUUID();return localStorage.setItem(`faststats_anon_id`,t),t}function r(e){return e||typeof localStorage>`u`?``:(localStorage.removeItem(`faststats_anon_id`),n())}function i(){if(typeof sessionStorage>`u`)return``;let e=sessionStorage.getItem(`session_id`),t=sessionStorage.getItem(`session_timestamp`);if(e&&t){if(Date.now()-Number.parseInt(t,10)<18e5)return sessionStorage.setItem(`session_timestamp`,Date.now().toString()),e;sessionStorage.removeItem(`session_id`),sessionStorage.removeItem(`session_timestamp`),sessionStorage.removeItem(`session_start`)}let n=Date.now().toString(),r=crypto.randomUUID();return sessionStorage.setItem(`session_id`,r),sessionStorage.setItem(`session_timestamp`,n),sessionStorage.setItem(`session_start`,n),r}function a(){return typeof sessionStorage>`u`?``:(sessionStorage.removeItem(`session_id`),sessionStorage.removeItem(`session_timestamp`),sessionStorage.removeItem(`session_start`),i())}function o(){typeof sessionStorage>`u`||sessionStorage.getItem(`session_id`)&&sessionStorage.setItem(`session_timestamp`,Date.now().toString())}function s(){if(typeof sessionStorage>`u`)return Date.now();let e=sessionStorage.getItem(`session_start`);if(e)return Number.parseInt(e,10);let t=sessionStorage.getItem(`session_timestamp`);return t?Number.parseInt(t,10):Date.now()}function c(e){return typeof e!=`number`||!Number.isFinite(e)?100:Math.max(0,Math.min(100,e))}function l(){if(typeof localStorage>`u`)return!1;let e=localStorage.getItem(`disable-faststats`);return e===`true`||e===`1`}async function u(e){let{url:t,data:n,contentType:r=`application/json`,headers:i={},debug:a=!1,debugPrefix:o=`[Analytics]`}=e,s=n instanceof Blob?n:new Blob([n],{type:r});if(navigator.sendBeacon?.(t,s))return a&&console.log(`${o} ✓ Sent via beacon`),!0;try{let e=await fetch(t,{method:`POST`,body:n,headers:{"Content-Type":r,...i},keepalive:!0}),s=e.ok;return a&&(s?console.log(`${o} ✓ Sent via fetch`):console.warn(`${o} ✗ Failed: ${e.status}`)),s}catch{return a&&console.warn(`${o} ✗ Failed to send`),!1}}function d(e){for(;e&&!(e.tagName===`A`&&e.href);)e=e.parentNode;return e}function f(){let e={};if(!location.search)return e;let t=new URLSearchParams(location.search);for(let n of[`utm_source`,`utm_medium`,`utm_campaign`,`utm_term`,`utm_content`]){let r=t.get(n);r&&(e[n]=r)}return e}var p=class{endpoint;debug;baseUrl;started=!1;pageKey=``;navTimer=null;heartbeatTimer=null;scrollDepth=0;pageEntryTime=0;pagePath=``;pageUrl=``;pageHash=``;hasLeftCurrentPage=!1;scrollHandler=null;consentMode;cookielessWhilePending;constructor(e){this.options=e,this.endpoint=e.endpoint??`https://metrics.faststats.dev/v1/web`,this.debug=e.debug??!1,this.consentMode=e.consent?.mode??`granted`,this.cookielessWhilePending=e.consent?.cookielessWhilePending??!0;let t=typeof document<`u`?document.currentScript:null,n=t?.src?t.src.substring(0,t.src.lastIndexOf(`/`)):``;this.baseUrl=(e.baseUrl??n)||(typeof window<`u`?window.location.origin:``),(e.autoTrack??!0)&&this.init()}log(e){this.debug&&console.log(`[Analytics] ${e}`)}init(){if(!(typeof window>`u`)){if(l()){this.log(`disabled`);return}`requestIdleCallback`in window?window.requestIdleCallback(()=>this.start()):setTimeout(()=>this.start(),1)}}start(){if(this.started||typeof window>`u`)return;if(window.__FA_webAnalyticsInstance&&window.__FA_webAnalyticsInstance!==this){this.log(`already started by another instance`);return}if(l()){this.log(`disabled`);return}this.started=!0,window.__FA_webAnalyticsInstance=this,window.__FA_getAnonymousId=()=>t(this.isCookielessMode()),window.__FA_getSessionId=i,window.__FA_sendData=u,window.__FA_identify=(e,t,n)=>this.identify(e,t,n),window.__FA_logout=e=>this.logout(e),window.__FA_setConsentMode=e=>this.setConsentMode(e),window.__FA_optIn=()=>this.optIn(),window.__FA_optOut=()=>this.optOut(),window.__FA_trackEvent=(e,t)=>this.track(e,t??{}),window.__FA_isTrackingDisabled=l;let e=this.options,n=e.webVitals?.sampling?.percentage!==void 0,r=e.replayOptions?.samplingPercentage!==void 0||e.sessionReplays?.sampling?.percentage!==void 0;if((e.errorTracking?.enabled??e.trackErrors)&&this.load(`error`,`__FA_ErrorTracker`,{siteKey:e.siteKey,endpoint:this.endpoint,debug:this.debug,getCommonData:()=>({url:location.href,page:location.pathname,referrer:document.referrer||null})}),(e.webVitals?.enabled??e.trackWebVitals??n)&&this.load(`web-vitals`,`__FA_WebVitalsTracker`,{siteKey:e.siteKey,endpoint:this.endpoint,debug:this.debug,samplingPercentage:c(e.webVitals?.sampling?.percentage)}),e.sessionReplays?.enabled??e.trackReplay??r){let t=e.replayOptions??{};this.load(`replay`,`__FA_ReplayTracker`,{siteKey:e.siteKey,endpoint:this.endpoint,debug:this.debug,...t,samplingPercentage:c(t.samplingPercentage??e.sessionReplays?.sampling?.percentage)})}this.enterPage(),this.pageview({trigger:`load`}),this.links(),this.trackScroll(),this.startHeartbeat(),document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`?this.leavePage():this.startHeartbeat()}),window.addEventListener(`pagehide`,()=>this.leavePage()),window.addEventListener(`popstate`,()=>this.navigate()),e.trackHash&&window.addEventListener(`hashchange`,()=>this.navigate()),this.patch()}load(e,t,n){let r=document.createElement(`script`);r.src=`${this.baseUrl}/${e}.js`,r.async=!0,r.onload=()=>{let r=window[t];r&&(new r(n).start(),this.log(`${e} loaded`))},r.onerror=()=>{this.debug&&console.warn(`[Analytics] ${e} failed`)},document.head.appendChild(r)}pageview(e={}){let t=`${location.pathname}|${this.options.trackHash??!1?location.hash:``}`;t!==this.pageKey&&(this.pageKey=t,this.send(`pageview`,e))}track(e,t={}){this.send(e,t)}identify(e,n,r={}){if(l()||this.isCookielessMode())return;let i=e.trim(),a=n.trim();!i||!a||u({url:this.endpoint.replace(/\/v1\/web$/,`/v1/identify`),data:JSON.stringify({token:this.options.siteKey,identifier:t(!1),externalId:i,email:a,name:r.name?.trim()||void 0,phone:r.phone?.trim()||void 0,avatarUrl:r.avatarUrl?.trim()||void 0,traits:r.traits??{}}),contentType:`text/plain`,debug:this.debug,debugPrefix:`[Analytics] identify`})}logout(e=!0){l()||(e&&r(this.isCookielessMode()),a())}setConsentMode(e){this.consentMode=e}optIn(){this.setConsentMode(`granted`)}optOut(){this.setConsentMode(`denied`)}getConsentMode(){return this.consentMode}isCookielessMode(){return this.options.cookieless||this.consentMode===`denied`?!0:this.consentMode===`pending`?this.cookielessWhilePending:!1}send(e,n={}){let r=t(this.isCookielessMode()),a=JSON.stringify({token:this.options.siteKey,...r?{userId:r}:{},sessionId:i(),data:{event:e,page:location.pathname,referrer:document.referrer||null,title:document.title||``,url:location.href,...f(),...n}});this.log(e),u({url:this.endpoint,data:a,contentType:`text/plain`,debug:this.debug,debugPrefix:`[Analytics] ${e}`})}enterPage(){this.pageEntryTime=Date.now(),this.pagePath=location.pathname,this.pageUrl=location.href,this.pageHash=location.hash,this.scrollDepth=0,this.hasLeftCurrentPage=!1}leavePage(){if(this.hasLeftCurrentPage)return;this.hasLeftCurrentPage=!0;let e=Date.now();this.send(`page_leave`,{page:this.pagePath,url:this.pageUrl,time_on_page:e-this.pageEntryTime,scroll_depth:this.scrollDepth,session_duration:e-s()})}trackScroll(){this.scrollHandler&&window.removeEventListener(`scroll`,this.scrollHandler);let e=()=>{let e=document.documentElement,t=document.body,n=window.innerHeight,r=Math.max(e.scrollHeight,t.scrollHeight);if(r<=n){this.scrollDepth=100;return}let i=Math.min(100,Math.round(((window.scrollY||e.scrollTop)+n)/r*100));i>this.scrollDepth&&(this.scrollDepth=i)};this.scrollHandler=e,e(),window.addEventListener(`scroll`,e,{passive:!0})}startHeartbeat(){this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>{if(document.visibilityState===`hidden`){clearInterval(this.heartbeatTimer),this.heartbeatTimer=null;return}o()},300*1e3)}navigate(){this.navTimer&&clearTimeout(this.navTimer),this.navTimer=setTimeout(()=>{this.navTimer=null;let e=location.pathname!==this.pagePath,t=(this.options.trackHash??!1)&&location.hash!==this.pageHash;!e&&!t||(this.leavePage(),this.enterPage(),this.trackScroll(),this.pageview({trigger:`navigation`}))},300)}patch(){let e=()=>this.navigate();for(let t of[`pushState`,`replaceState`]){let n=history[t];history[t]=function(...t){let r=n.apply(this,t);return e(),r}}}links(){let e=e=>{let t=d(e.target);t&&t.host!==location.host&&this.track(`outbound_link`,{outbound_link:t.href})};document.addEventListener(`click`,e),document.addEventListener(`auxclick`,e)}};function m(e){if(e==null)return;let t=e.trim().toLowerCase();if(t===`true`||t===`1`)return!0;if(t===`false`||t===`0`)return!1}function h(e){if(e==null||e.trim()===``)return;let t=Number(e);if(Number.isFinite(t))return Math.max(0,Math.min(100,t))}function g(e){if(e==null)return;let t=e.trim().toLowerCase();if(t===`pending`)return`pending`;if(t===`granted`)return`granted`;if(t===`denied`)return`denied`}return typeof window<`u`&&(window.WebAnalytics=p,window.__FA_isTrackingDisabled=l,(()=>{let e=document.currentScript;if(!e)return;let t=e,n=e=>t.getAttribute(`data-${e}`),r=n(`sitekey`);if(!r)return;let i={siteKey:r},a=n(`endpoint`);a&&(i.endpoint=a);let o=n(`debug`);o&&(i.debug=o===`true`);let s=m(n(`trackErrors`));s!==void 0&&(i.trackErrors=s,i.errorTracking={enabled:s});let c=m(n(`webVitals`)),l=h(n(`web-vitals-sampling`));(c!==void 0||l!==void 0)&&(c!==void 0&&(i.trackWebVitals=c),i.webVitals={enabled:c,sampling:l===void 0?void 0:{percentage:l}});let u=m(n(`replay`)),d=h(n(`replay-sampling`));(u!==void 0||d!==void 0)&&(u!==void 0&&(i.trackReplay=u),i.sessionReplays={enabled:u,sampling:d===void 0?void 0:{percentage:d}});let f=m(n(`cookieless`));f!==void 0&&(i.cookieless=f);let _=g(n(`consent-mode`)),v=m(n(`cookieless-while-pending`));(_!==void 0||v!==void 0)&&(i.consent={mode:_,cookielessWhilePending:v}),new p(i)})()),e.WebAnalytics=p,e.isTrackingDisabled=l,e.sendData=u,e})({});
|
package/dist/web-vitals.iife.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var FA_WebVitals=(function(){var e=class{t;o=0;i=[];u(e){if(e.hadRecentInput)return;let t=this.i[0],n=this.i.at(-1);this.o&&t&&n&&e.startTime-n.startTime<1e3&&e.startTime-t.startTime<5e3?(this.o+=e.value,this.i.push(e)):(this.o=e.value,this.i=[e]),this.t?.(e)}};let t=()=>{let e=performance.getEntriesByType(`navigation`)[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},n=e=>{if(document.readyState===`loading`)return`loading`;{let n=t();if(n){if(e<n.domInteractive)return`loading`;if(n.domContentLoadedEventStart===0||e<n.domContentLoadedEventStart)return`dom-interactive`;if(n.domComplete===0||e<n.domComplete)return`dom-content-loaded`}}return`complete`},r=e=>{let t=e.nodeName;return e.nodeType===1?t.toLowerCase():t.toUpperCase().replace(/^#/,``)},i=e=>{let t=``;try{for(;e?.nodeType!==9;){let n=e,i=n.id?`#`+n.id:[r(n),...Array.from(n.classList).sort()].join(`.`);if(t.length+i.length>99)return t||i;if(t=t?i+`>`+t:i,n.id)break;e=n.parentNode}}catch{}return t},a=new WeakMap;function o(e,t){return a.get(e)||a.set(e,new t),a.get(e)}let s=-1,c=()=>s,l=e=>{addEventListener(`pageshow`,(t=>{t.persisted&&(s=t.timeStamp,e(t))}),!0)},u=(e,t,n,r)=>{let i,a;return o=>{t.value>=0&&(o||r)&&(a=t.value-(i??0),(a||i===void 0)&&(i=t.value,t.delta=a,t.rating=((e,t)=>e>t[1]?`poor`:e>t[0]?`needs-improvement`:`good`)(t.value,n),e(t)))}},d=e=>{requestAnimationFrame((()=>requestAnimationFrame((()=>e()))))},f=()=>t()?.activationStart??0,p=(e,n=-1)=>{let r=t(),i=`navigate`;return c()>=0?i=`back-forward-cache`:r&&(document.prerendering||f()>0?i=`prerender`:document.wasDiscarded?i=`restore`:r.type&&(i=r.type.replace(/_/g,`-`))),{name:e,value:n,rating:`good`,delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+0xe8d4a51000}`,navigationType:i}},m=(e,t,n={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(e)){let r=new PerformanceObserver((e=>{Promise.resolve().then((()=>{t(e.getEntries())}))}));return r.observe({type:e,buffered:!0,...n}),r}}catch{}},h=e=>{let t=!1;return()=>{t||=(e(),!0)}},g=-1,_=new Set,v=()=>document.visibilityState!==`hidden`||document.prerendering?1/0:0,y=e=>{if(document.visibilityState===`hidden`){if(e.type===`visibilitychange`)for(let e of _)e();isFinite(g)||(g=e.type===`visibilitychange`?e.timeStamp:0,removeEventListener(`prerenderingchange`,y,!0))}},b=()=>{if(g<0){let e=f();g=(document.prerendering?void 0:globalThis.performance.getEntriesByType(`visibility-state`).filter((t=>t.name===`hidden`&&t.startTime>e))[0]?.startTime)??v(),addEventListener(`visibilitychange`,y,!0),addEventListener(`prerenderingchange`,y,!0),l((()=>{setTimeout((()=>{g=v()}))}))}return{get firstHiddenTime(){return g},onHidden(e){_.add(e)}}},x=e=>{document.prerendering?addEventListener(`prerenderingchange`,(()=>e()),!0):e()},S=[1800,3e3],C=(e,t={})=>{x((()=>{let n=b(),r,i=p(`FCP`),a=m(`paint`,(e=>{for(let t of e)t.name===`first-contentful-paint`&&(a.disconnect(),t.startTime<n.firstHiddenTime&&(i.value=Math.max(t.startTime-f(),0),i.entries.push(t),r(!0)))}));a&&(r=u(e,i,S,t.reportAllChanges),l((n=>{i=p(`FCP`),r=u(e,i,S,t.reportAllChanges),d((()=>{i.value=performance.now()-n.timeStamp,r(!0)}))})))}))},w=[.1,.25],T=e=>e.find((e=>e.node?.nodeType===1))||e[0],E=(t,r={})=>{let a=o(r=Object.assign({},r),e),s=new WeakMap;a.t=e=>{if(e?.sources?.length){let t=T(e.sources),n=t?.node;if(n){let e=r.generateTarget?.(n)??i(n);s.set(t,e)}}},((t,n={})=>{let r=b();C(h((()=>{let i,a=p(`CLS`,0),s=o(n,e),c=e=>{for(let t of e)s.u(t);s.o>a.value&&(a.value=s.o,a.entries=s.i,i())},f=m(`layout-shift`,c);f&&(i=u(t,a,w,n.reportAllChanges),r.onHidden((()=>{c(f.takeRecords()),i(!0)})),l((()=>{s.o=0,a=p(`CLS`,0),i=u(t,a,w,n.reportAllChanges),d((()=>i()))})),setTimeout(i))})))})((e=>{t((e=>{let t={};if(e.entries.length){let r=e.entries.reduce(((e,t)=>e.value>t.value?e:t));if(r?.sources?.length){let e=T(r.sources);e&&(t={largestShiftTarget:s.get(e),largestShiftTime:r.startTime,largestShiftValue:r.value,largestShiftSource:e,largestShiftEntry:r,loadState:n(r.startTime)})}}return Object.assign(e,{attribution:t})})(e))}),r)},D=(e,r={})=>{C((r=>{e((e=>{let r={timeToFirstByte:0,firstByteToFCP:e.value,loadState:n(c())};if(e.entries.length){let i=t(),a=e.entries.at(-1);if(i){let t=i.activationStart||0,o=Math.max(0,i.responseStart-t);r={timeToFirstByte:o,firstByteToFCP:e.value-o,loadState:n(e.entries[0].startTime),navigationEntry:i,fcpEntry:a}}}return Object.assign(e,{attribution:r})})(r))}),r)},O=0,k=1/0,A=0,j=e=>{for(let t of e)t.interactionId&&(k=Math.min(k,t.interactionId),A=Math.max(A,t.interactionId),O=A?(A-k)/7+1:0)},M,N=()=>M?O:performance.interactionCount??0,P=()=>{`interactionCount`in performance||M||(M=m(`event`,j,{type:`event`,buffered:!0,durationThreshold:0}))},F=0;var I=class{l=[];h=new Map;m;p;v(){F=N(),this.l.length=0,this.h.clear()}M(){let e=Math.min(this.l.length-1,Math.floor((N()-F)/50));return this.l[e]}u(e){if(this.m?.(e),!e.interactionId&&e.entryType!==`first-input`)return;let t=this.l.at(-1),n=this.h.get(e.interactionId);if(n||this.l.length<10||e.duration>t.T){if(n?e.duration>n.T?(n.entries=[e],n.T=e.duration):e.duration===n.T&&e.startTime===n.entries[0].startTime&&n.entries.push(e):(n={id:e.interactionId,entries:[e],T:e.duration},this.h.set(n.id,n),this.l.push(n)),this.l.sort(((e,t)=>t.T-e.T)),this.l.length>10){let e=this.l.splice(10);for(let t of e)this.h.delete(t.id)}this.p?.(n)}}};let L=e=>{let t=globalThis.requestIdleCallback||setTimeout;document.visibilityState===`hidden`?e():(e=h(e),addEventListener(`visibilitychange`,e,{once:!0,capture:!0}),t((()=>{e(),removeEventListener(`visibilitychange`,e,{capture:!0})})))},R=[200,500],z=(e,t={})=>{let r=o(t=Object.assign({},t),I),a=[],s=[],c=0,d=new WeakMap,f=new WeakMap,h=!1,g=()=>{h||=(L(_),!0)},_=()=>{let e=r.l.map((e=>d.get(e.entries[0]))),t=s.length-50;s=s.filter(((n,r)=>r>=t||e.includes(n)));let n=new Set;for(let e of s){let t=v(e.startTime,e.processingEnd);for(let e of t)n.add(e)}let i=a.length-1-50;a=a.filter(((e,t)=>e.startTime>c&&t>i||n.has(e))),h=!1};r.m=e=>{let t=e.startTime+e.duration,n;c=Math.max(c,e.processingEnd);for(let r=s.length-1;r>=0;r--){let i=s[r];if(Math.abs(t-i.renderTime)<=8){n=i,n.startTime=Math.min(e.startTime,n.startTime),n.processingStart=Math.min(e.processingStart,n.processingStart),n.processingEnd=Math.max(e.processingEnd,n.processingEnd),n.entries.push(e);break}}n||(n={startTime:e.startTime,processingStart:e.processingStart,processingEnd:e.processingEnd,renderTime:t,entries:[e]},s.push(n)),(e.interactionId||e.entryType===`first-input`)&&d.set(e,n),g()},r.p=e=>{if(!f.get(e)){let n=e.entries[0].target;if(n){let r=t.generateTarget?.(n)??i(n);f.set(e,r)}}};let v=(e,t)=>{let n=[];for(let r of a)if(!(r.startTime+r.duration<e)){if(r.startTime>t)break;n.push(r)}return n},y=e=>{let t=e.entries[0],i=d.get(t),a=t.processingStart,o=Math.max(t.startTime+t.duration,a),s=Math.min(i.processingEnd,o),c=i.entries.sort(((e,t)=>e.processingStart-t.processingStart)),l=v(t.startTime,s),u=r.h.get(t.interactionId),p={interactionTarget:f.get(u),interactionType:t.name.startsWith(`key`)?`keyboard`:`pointer`,interactionTime:t.startTime,nextPaintTime:o,processedEventEntries:c,longAnimationFrameEntries:l,inputDelay:a-t.startTime,processingDuration:s-a,presentationDelay:o-s,loadState:n(t.startTime),longestScript:void 0,totalScriptDuration:void 0,totalStyleAndLayoutDuration:void 0,totalPaintDuration:void 0,totalUnattributedDuration:void 0};return(e=>{if(!e.longAnimationFrameEntries?.length)return;let t=e.interactionTime,n=e.inputDelay,r=e.processingDuration,i,a,o=0,s=0,c=0,l=0;for(let c of e.longAnimationFrameEntries){s=s+c.startTime+c.duration-c.styleAndLayoutStart;for(let e of c.scripts){let c=e.startTime+e.duration;if(c<t)continue;let u=c-Math.max(t,e.startTime),d=e.duration?u/e.duration*e.forcedStyleAndLayoutDuration:0;o+=u-d,s+=d,u>l&&(a=e.startTime<t+n?`input-delay`:e.startTime>=t+n+r?`presentation-delay`:`processing-duration`,i=e,l=u)}}let u=e.longAnimationFrameEntries.at(-1),d=u?u.startTime+u.duration:0;d>=t+n+r&&(c=e.nextPaintTime-d),i&&a&&(e.longestScript={entry:i,subpart:a,intersectingDuration:l}),e.totalScriptDuration=o,e.totalStyleAndLayoutDuration=s,e.totalPaintDuration=c,e.totalUnattributedDuration=e.nextPaintTime-t-o-s-c})(p),Object.assign(e,{attribution:p})};m(`long-animation-frame`,(e=>{a=a.concat(e),g()})),((e,t={})=>{if(!globalThis.PerformanceEventTiming||!(`interactionId`in PerformanceEventTiming.prototype))return;let n=b();x((()=>{P();let r,i=p(`INP`),a=o(t,I),s=e=>{L((()=>{for(let t of e)a.u(t);let t=a.M();t&&t.T!==i.value&&(i.value=t.T,i.entries=t.entries,r())}))},c=m(`event`,s,{durationThreshold:t.durationThreshold??40});r=u(e,i,R,t.reportAllChanges),c&&(c.observe({type:`first-input`,buffered:!0}),n.onHidden((()=>{s(c.takeRecords()),r(!0)})),l((()=>{a.v(),i=p(`INP`),r=u(e,i,R,t.reportAllChanges)})))}))})((t=>{e(y(t))}),t)};var B=class{m;u(e){this.m?.(e)}};let V=[2500,4e3],H=(e,n={})=>{let r=o(n=Object.assign({},n),B),a=new WeakMap;r.m=e=>{let t=e.element;if(t){let r=n.generateTarget?.(t)??i(t);a.set(e,r)}},((e,t={})=>{x((()=>{let n=b(),r,i=p(`LCP`),a=o(t,B),s=e=>{t.reportAllChanges||(e=e.slice(-1));for(let t of e)a.u(t),t.startTime<n.firstHiddenTime&&(i.value=Math.max(t.startTime-f(),0),i.entries=[t],r())},c=m(`largest-contentful-paint`,s);if(c){r=u(e,i,V,t.reportAllChanges);let n=h((()=>{s(c.takeRecords()),c.disconnect(),r(!0)})),a=e=>{e.isTrusted&&(L(n),removeEventListener(e.type,a,{capture:!0}))};for(let e of[`keydown`,`click`,`visibilitychange`])addEventListener(e,a,{capture:!0});l((n=>{i=p(`LCP`),r=u(e,i,V,t.reportAllChanges),d((()=>{i.value=performance.now()-n.timeStamp,r(!0)}))}))}}))})((n=>{e((e=>{let n={timeToFirstByte:0,resourceLoadDelay:0,resourceLoadDuration:0,elementRenderDelay:e.value};if(e.entries.length){let r=t();if(r){let t=r.activationStart||0,i=e.entries.at(-1),o=i.url&&performance.getEntriesByType(`resource`).filter((e=>e.name===i.url))[0],s=Math.max(0,r.responseStart-t),c=Math.max(s,o?(o.requestStart||o.startTime)-t:0),l=Math.min(e.value,Math.max(c,o?o.responseEnd-t:0));n={target:a.get(i),timeToFirstByte:s,resourceLoadDelay:c-s,resourceLoadDuration:l-c,elementRenderDelay:e.value-l,navigationEntry:r,lcpEntry:i},i.url&&(n.url=i.url),o&&(n.lcpResourceEntry=o)}}return Object.assign(e,{attribution:n})})(n))}),n)},U=[800,1800],W=e=>{document.prerendering?x((()=>W(e))):document.readyState===`complete`?setTimeout(e):addEventListener(`load`,(()=>W(e)),!0)},G=(e,n={})=>{((e,n={})=>{let r=p(`TTFB`),i=u(e,r,U,n.reportAllChanges);W((()=>{let a=t();a&&(r.value=Math.max(a.responseStart-f(),0),r.entries=[a],i(!0),l((()=>{r=p(`TTFB`,0),i=u(e,r,U,n.reportAllChanges),i(!0)})))}))})((t=>{e((e=>{let t={waitingDuration:0,cacheDuration:0,dnsDuration:0,connectionDuration:0,requestDuration:0};if(e.entries.length){let n=e.entries[0],r=n.activationStart||0,i=Math.max((n.workerStart||n.fetchStart)-r,0),a=Math.max(n.domainLookupStart-r,0),o=Math.max(n.connectStart-r,0),s=Math.max(n.connectEnd-r,0);t={waitingDuration:i,cacheDuration:a-i,dnsDuration:o-a,connectionDuration:s-o,requestDuration:e.value-s,navigationEntry:n}}return Object.assign(e,{attribution:t})})(t))}),n)};function K(e){return typeof e!=`number`||!Number.isFinite(e)?100:Math.max(0,Math.min(100,e))}var q=class{endpoint;siteKey;debug;samplingPercentage;started=!1;sessionSamplingSeed;metricsMap=new Map;flushed=!1;constructor(e){this.siteKey=e.siteKey,this.endpoint=this.getVitalsEndpoint(e.endpoint??`https://metrics.faststats.dev/v1/web`),this.debug=e.debug??!1,this.samplingPercentage=K(e.samplingPercentage),this.sessionSamplingSeed=Math.random()*100}getVitalsEndpoint(e){let t=new URL(e),n=t.pathname.split(`/`);return n[n.length-1]=`vitals`,t.pathname=n.join(`/`),t.toString()}start(){if(!(this.started||typeof window>`u`)){if(window.__FA_isTrackingDisabled?.()){this.debug&&console.log(`[WebVitals] Tracking disabled`);return}this.started=!0,document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&this.finalizeAndFlush()}),window.addEventListener(`pagehide`,()=>{this.finalizeAndFlush()}),this.debug&&console.log(`[WebVitals] Tracking started`),E(e=>this.captureMetric(e)),z(e=>this.captureMetric(e)),H(e=>this.captureMetric(e)),D(e=>this.captureMetric(e)),G(e=>this.captureMetric(e))}}captureMetric(e){if(this.flushed||this.samplingPercentage<100&&this.sessionSamplingSeed>=this.samplingPercentage)return;let t=e.name,n={id:e.id,rating:e.rating,delta:e.delta,navigationType:e.navigationType,...e.attribution??{}},r=t===`FCP`||t===`TTFB`;this.metricsMap.set(t,{value:e.value,attributes:n,final:r}),this.debug&&console.log(`[WebVitals] ${t} captured: ${e.value}`+(r?` (final)`:``))}finalizeAndFlush(){if(!(this.flushed||this.metricsMap.size===0)){for(let[e,t]of this.metricsMap.entries())t.final||(t.final=!0,this.debug&&console.log(`[WebVitals] ${e} finalized: ${t.value}`));this.flushWithBeacon()}}buildPayload(){if(this.metricsMap.size===0)return null;let e=Array.from(this.metricsMap.entries()).map(([e,t])=>({metric:e,value:t.value,attributes:t.attributes}));return{body:JSON.stringify({sessionId:window.__FA_getSessionId?.(),vitals:e,metadata:{url:window.location.href}}),count:e.length}}flushWithBeacon(){let e=this.buildPayload();if(e){if(this.flushed=!0,this.debug){let t=Array.from(this.metricsMap.keys()).join(`, `);console.log(`[WebVitals] Sending final metrics (${e.count}): ${t}`)}fetch(this.endpoint,{method:`POST`,body:e.body,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.siteKey}`},keepalive:!0}).catch(()=>{this.debug&&console.warn(`[WebVitals] Failed to send metrics`)})}}};return typeof window<`u`&&(window.__FA_WebVitalsTracker=q),q})();
|
package/dist/web-vitals.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var FA_WebVitals=(function(){var e=class{t;o=0;i=[];u(e){if(e.hadRecentInput)return;let t=this.i[0],n=this.i.at(-1);this.o&&t&&n&&e.startTime-n.startTime<1e3&&e.startTime-t.startTime<5e3?(this.o+=e.value,this.i.push(e)):(this.o=e.value,this.i=[e]),this.t?.(e)}};let t=()=>{let e=performance.getEntriesByType(`navigation`)[0];if(e&&e.responseStart>0&&e.responseStart<performance.now())return e},n=e=>{if(document.readyState===`loading`)return`loading`;{let n=t();if(n){if(e<n.domInteractive)return`loading`;if(n.domContentLoadedEventStart===0||e<n.domContentLoadedEventStart)return`dom-interactive`;if(n.domComplete===0||e<n.domComplete)return`dom-content-loaded`}}return`complete`},r=e=>{let t=e.nodeName;return e.nodeType===1?t.toLowerCase():t.toUpperCase().replace(/^#/,``)},i=e=>{let t=``;try{for(;e?.nodeType!==9;){let n=e,i=n.id?`#`+n.id:[r(n),...Array.from(n.classList).sort()].join(`.`);if(t.length+i.length>99)return t||i;if(t=t?i+`>`+t:i,n.id)break;e=n.parentNode}}catch{}return t},a=new WeakMap;function o(e,t){return a.get(e)||a.set(e,new t),a.get(e)}let s=-1,c=()=>s,l=e=>{addEventListener(`pageshow`,(t=>{t.persisted&&(s=t.timeStamp,e(t))}),!0)},u=(e,t,n,r)=>{let i,a;return o=>{t.value>=0&&(o||r)&&(a=t.value-(i??0),(a||i===void 0)&&(i=t.value,t.delta=a,t.rating=((e,t)=>e>t[1]?`poor`:e>t[0]?`needs-improvement`:`good`)(t.value,n),e(t)))}},d=e=>{requestAnimationFrame((()=>requestAnimationFrame((()=>e()))))},f=()=>t()?.activationStart??0,p=(e,n=-1)=>{let r=t(),i=`navigate`;return c()>=0?i=`back-forward-cache`:r&&(document.prerendering||f()>0?i=`prerender`:document.wasDiscarded?i=`restore`:r.type&&(i=r.type.replace(/_/g,`-`))),{name:e,value:n,rating:`good`,delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+0xe8d4a51000}`,navigationType:i}},m=(e,t,n={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(e)){let r=new PerformanceObserver((e=>{Promise.resolve().then((()=>{t(e.getEntries())}))}));return r.observe({type:e,buffered:!0,...n}),r}}catch{}},h=e=>{let t=!1;return()=>{t||=(e(),!0)}},g=-1,_=new Set,v=()=>document.visibilityState!==`hidden`||document.prerendering?1/0:0,y=e=>{if(document.visibilityState===`hidden`){if(e.type===`visibilitychange`)for(let e of _)e();isFinite(g)||(g=e.type===`visibilitychange`?e.timeStamp:0,removeEventListener(`prerenderingchange`,y,!0))}},b=()=>{if(g<0){let e=f();g=(document.prerendering?void 0:globalThis.performance.getEntriesByType(`visibility-state`).filter((t=>t.name===`hidden`&&t.startTime>e))[0]?.startTime)??v(),addEventListener(`visibilitychange`,y,!0),addEventListener(`prerenderingchange`,y,!0),l((()=>{setTimeout((()=>{g=v()}))}))}return{get firstHiddenTime(){return g},onHidden(e){_.add(e)}}},x=e=>{document.prerendering?addEventListener(`prerenderingchange`,(()=>e()),!0):e()},S=[1800,3e3],C=(e,t={})=>{x((()=>{let n=b(),r,i=p(`FCP`),a=m(`paint`,(e=>{for(let t of e)t.name===`first-contentful-paint`&&(a.disconnect(),t.startTime<n.firstHiddenTime&&(i.value=Math.max(t.startTime-f(),0),i.entries.push(t),r(!0)))}));a&&(r=u(e,i,S,t.reportAllChanges),l((n=>{i=p(`FCP`),r=u(e,i,S,t.reportAllChanges),d((()=>{i.value=performance.now()-n.timeStamp,r(!0)}))})))}))},w=[.1,.25],T=e=>e.find((e=>e.node?.nodeType===1))||e[0],E=(t,r={})=>{let a=o(r=Object.assign({},r),e),s=new WeakMap;a.t=e=>{if(e?.sources?.length){let t=T(e.sources),n=t?.node;if(n){let e=r.generateTarget?.(n)??i(n);s.set(t,e)}}},((t,n={})=>{let r=b();C(h((()=>{let i,a=p(`CLS`,0),s=o(n,e),c=e=>{for(let t of e)s.u(t);s.o>a.value&&(a.value=s.o,a.entries=s.i,i())},f=m(`layout-shift`,c);f&&(i=u(t,a,w,n.reportAllChanges),r.onHidden((()=>{c(f.takeRecords()),i(!0)})),l((()=>{s.o=0,a=p(`CLS`,0),i=u(t,a,w,n.reportAllChanges),d((()=>i()))})),setTimeout(i))})))})((e=>{t((e=>{let t={};if(e.entries.length){let r=e.entries.reduce(((e,t)=>e.value>t.value?e:t));if(r?.sources?.length){let e=T(r.sources);e&&(t={largestShiftTarget:s.get(e),largestShiftTime:r.startTime,largestShiftValue:r.value,largestShiftSource:e,largestShiftEntry:r,loadState:n(r.startTime)})}}return Object.assign(e,{attribution:t})})(e))}),r)},D=(e,r={})=>{C((r=>{e((e=>{let r={timeToFirstByte:0,firstByteToFCP:e.value,loadState:n(c())};if(e.entries.length){let i=t(),a=e.entries.at(-1);if(i){let t=i.activationStart||0,o=Math.max(0,i.responseStart-t);r={timeToFirstByte:o,firstByteToFCP:e.value-o,loadState:n(e.entries[0].startTime),navigationEntry:i,fcpEntry:a}}}return Object.assign(e,{attribution:r})})(r))}),r)},O=0,k=1/0,A=0,j=e=>{for(let t of e)t.interactionId&&(k=Math.min(k,t.interactionId),A=Math.max(A,t.interactionId),O=A?(A-k)/7+1:0)},M,N=()=>M?O:performance.interactionCount??0,P=()=>{`interactionCount`in performance||M||(M=m(`event`,j,{type:`event`,buffered:!0,durationThreshold:0}))},F=0;var I=class{l=[];h=new Map;m;p;v(){F=N(),this.l.length=0,this.h.clear()}M(){let e=Math.min(this.l.length-1,Math.floor((N()-F)/50));return this.l[e]}u(e){if(this.m?.(e),!e.interactionId&&e.entryType!==`first-input`)return;let t=this.l.at(-1),n=this.h.get(e.interactionId);if(n||this.l.length<10||e.duration>t.T){if(n?e.duration>n.T?(n.entries=[e],n.T=e.duration):e.duration===n.T&&e.startTime===n.entries[0].startTime&&n.entries.push(e):(n={id:e.interactionId,entries:[e],T:e.duration},this.h.set(n.id,n),this.l.push(n)),this.l.sort(((e,t)=>t.T-e.T)),this.l.length>10){let e=this.l.splice(10);for(let t of e)this.h.delete(t.id)}this.p?.(n)}}};let L=e=>{let t=globalThis.requestIdleCallback||setTimeout;document.visibilityState===`hidden`?e():(e=h(e),addEventListener(`visibilitychange`,e,{once:!0,capture:!0}),t((()=>{e(),removeEventListener(`visibilitychange`,e,{capture:!0})})))},R=[200,500],z=(e,t={})=>{let r=o(t=Object.assign({},t),I),a=[],s=[],c=0,d=new WeakMap,f=new WeakMap,h=!1,g=()=>{h||=(L(_),!0)},_=()=>{let e=r.l.map((e=>d.get(e.entries[0]))),t=s.length-50;s=s.filter(((n,r)=>r>=t||e.includes(n)));let n=new Set;for(let e of s){let t=v(e.startTime,e.processingEnd);for(let e of t)n.add(e)}let i=a.length-1-50;a=a.filter(((e,t)=>e.startTime>c&&t>i||n.has(e))),h=!1};r.m=e=>{let t=e.startTime+e.duration,n;c=Math.max(c,e.processingEnd);for(let r=s.length-1;r>=0;r--){let i=s[r];if(Math.abs(t-i.renderTime)<=8){n=i,n.startTime=Math.min(e.startTime,n.startTime),n.processingStart=Math.min(e.processingStart,n.processingStart),n.processingEnd=Math.max(e.processingEnd,n.processingEnd),n.entries.push(e);break}}n||(n={startTime:e.startTime,processingStart:e.processingStart,processingEnd:e.processingEnd,renderTime:t,entries:[e]},s.push(n)),(e.interactionId||e.entryType===`first-input`)&&d.set(e,n),g()},r.p=e=>{if(!f.get(e)){let n=e.entries[0].target;if(n){let r=t.generateTarget?.(n)??i(n);f.set(e,r)}}};let v=(e,t)=>{let n=[];for(let r of a)if(!(r.startTime+r.duration<e)){if(r.startTime>t)break;n.push(r)}return n},y=e=>{let t=e.entries[0],i=d.get(t),a=t.processingStart,o=Math.max(t.startTime+t.duration,a),s=Math.min(i.processingEnd,o),c=i.entries.sort(((e,t)=>e.processingStart-t.processingStart)),l=v(t.startTime,s),u=r.h.get(t.interactionId),p={interactionTarget:f.get(u),interactionType:t.name.startsWith(`key`)?`keyboard`:`pointer`,interactionTime:t.startTime,nextPaintTime:o,processedEventEntries:c,longAnimationFrameEntries:l,inputDelay:a-t.startTime,processingDuration:s-a,presentationDelay:o-s,loadState:n(t.startTime),longestScript:void 0,totalScriptDuration:void 0,totalStyleAndLayoutDuration:void 0,totalPaintDuration:void 0,totalUnattributedDuration:void 0};return(e=>{if(!e.longAnimationFrameEntries?.length)return;let t=e.interactionTime,n=e.inputDelay,r=e.processingDuration,i,a,o=0,s=0,c=0,l=0;for(let c of e.longAnimationFrameEntries){s=s+c.startTime+c.duration-c.styleAndLayoutStart;for(let e of c.scripts){let c=e.startTime+e.duration;if(c<t)continue;let u=c-Math.max(t,e.startTime),d=e.duration?u/e.duration*e.forcedStyleAndLayoutDuration:0;o+=u-d,s+=d,u>l&&(a=e.startTime<t+n?`input-delay`:e.startTime>=t+n+r?`presentation-delay`:`processing-duration`,i=e,l=u)}}let u=e.longAnimationFrameEntries.at(-1),d=u?u.startTime+u.duration:0;d>=t+n+r&&(c=e.nextPaintTime-d),i&&a&&(e.longestScript={entry:i,subpart:a,intersectingDuration:l}),e.totalScriptDuration=o,e.totalStyleAndLayoutDuration=s,e.totalPaintDuration=c,e.totalUnattributedDuration=e.nextPaintTime-t-o-s-c})(p),Object.assign(e,{attribution:p})};m(`long-animation-frame`,(e=>{a=a.concat(e),g()})),((e,t={})=>{if(!globalThis.PerformanceEventTiming||!(`interactionId`in PerformanceEventTiming.prototype))return;let n=b();x((()=>{P();let r,i=p(`INP`),a=o(t,I),s=e=>{L((()=>{for(let t of e)a.u(t);let t=a.M();t&&t.T!==i.value&&(i.value=t.T,i.entries=t.entries,r())}))},c=m(`event`,s,{durationThreshold:t.durationThreshold??40});r=u(e,i,R,t.reportAllChanges),c&&(c.observe({type:`first-input`,buffered:!0}),n.onHidden((()=>{s(c.takeRecords()),r(!0)})),l((()=>{a.v(),i=p(`INP`),r=u(e,i,R,t.reportAllChanges)})))}))})((t=>{e(y(t))}),t)};var B=class{m;u(e){this.m?.(e)}};let V=[2500,4e3],H=(e,n={})=>{let r=o(n=Object.assign({},n),B),a=new WeakMap;r.m=e=>{let t=e.element;if(t){let r=n.generateTarget?.(t)??i(t);a.set(e,r)}},((e,t={})=>{x((()=>{let n=b(),r,i=p(`LCP`),a=o(t,B),s=e=>{t.reportAllChanges||(e=e.slice(-1));for(let t of e)a.u(t),t.startTime<n.firstHiddenTime&&(i.value=Math.max(t.startTime-f(),0),i.entries=[t],r())},c=m(`largest-contentful-paint`,s);if(c){r=u(e,i,V,t.reportAllChanges);let n=h((()=>{s(c.takeRecords()),c.disconnect(),r(!0)})),a=e=>{e.isTrusted&&(L(n),removeEventListener(e.type,a,{capture:!0}))};for(let e of[`keydown`,`click`,`visibilitychange`])addEventListener(e,a,{capture:!0});l((n=>{i=p(`LCP`),r=u(e,i,V,t.reportAllChanges),d((()=>{i.value=performance.now()-n.timeStamp,r(!0)}))}))}}))})((n=>{e((e=>{let n={timeToFirstByte:0,resourceLoadDelay:0,resourceLoadDuration:0,elementRenderDelay:e.value};if(e.entries.length){let r=t();if(r){let t=r.activationStart||0,i=e.entries.at(-1),o=i.url&&performance.getEntriesByType(`resource`).filter((e=>e.name===i.url))[0],s=Math.max(0,r.responseStart-t),c=Math.max(s,o?(o.requestStart||o.startTime)-t:0),l=Math.min(e.value,Math.max(c,o?o.responseEnd-t:0));n={target:a.get(i),timeToFirstByte:s,resourceLoadDelay:c-s,resourceLoadDuration:l-c,elementRenderDelay:e.value-l,navigationEntry:r,lcpEntry:i},i.url&&(n.url=i.url),o&&(n.lcpResourceEntry=o)}}return Object.assign(e,{attribution:n})})(n))}),n)},U=[800,1800],W=e=>{document.prerendering?x((()=>W(e))):document.readyState===`complete`?setTimeout(e):addEventListener(`load`,(()=>W(e)),!0)},G=(e,n={})=>{((e,n={})=>{let r=p(`TTFB`),i=u(e,r,U,n.reportAllChanges);W((()=>{let a=t();a&&(r.value=Math.max(a.responseStart-f(),0),r.entries=[a],i(!0),l((()=>{r=p(`TTFB`,0),i=u(e,r,U,n.reportAllChanges),i(!0)})))}))})((t=>{e((e=>{let t={waitingDuration:0,cacheDuration:0,dnsDuration:0,connectionDuration:0,requestDuration:0};if(e.entries.length){let n=e.entries[0],r=n.activationStart||0,i=Math.max((n.workerStart||n.fetchStart)-r,0),a=Math.max(n.domainLookupStart-r,0),o=Math.max(n.connectStart-r,0),s=Math.max(n.connectEnd-r,0);t={waitingDuration:i,cacheDuration:a-i,dnsDuration:o-a,connectionDuration:s-o,requestDuration:e.value-s,navigationEntry:n}}return Object.assign(e,{attribution:t})})(t))}),n)};function K(e){return typeof e!=`number`||!Number.isFinite(e)?100:Math.max(0,Math.min(100,e))}var q=class{endpoint;siteKey;debug;samplingPercentage;started=!1;sessionSamplingSeed;metricsMap=new Map;flushed=!1;constructor(e){this.siteKey=e.siteKey,this.endpoint=this.getVitalsEndpoint(e.endpoint??`https://metrics.faststats.dev/v1/web`),this.debug=e.debug??!1,this.samplingPercentage=K(e.samplingPercentage),this.sessionSamplingSeed=Math.random()*100}getVitalsEndpoint(e){let t=new URL(e),n=t.pathname.split(`/`);return n[n.length-1]=`vitals`,t.pathname=n.join(`/`),t.toString()}start(){if(!(this.started||typeof window>`u`)){if(window.__FA_isTrackingDisabled?.()){this.debug&&console.log(`[WebVitals] Tracking disabled`);return}this.started=!0,document.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`&&this.finalizeAndFlush()}),window.addEventListener(`pagehide`,()=>{this.finalizeAndFlush()}),this.debug&&console.log(`[WebVitals] Tracking started`),E(e=>this.captureMetric(e)),z(e=>this.captureMetric(e)),H(e=>this.captureMetric(e)),D(e=>this.captureMetric(e)),G(e=>this.captureMetric(e))}}captureMetric(e){if(this.flushed||this.samplingPercentage<100&&this.sessionSamplingSeed>=this.samplingPercentage)return;let t=e.name,n={id:e.id,rating:e.rating,delta:e.delta,navigationType:e.navigationType,...e.attribution??{}},r=t===`FCP`||t===`TTFB`;this.metricsMap.set(t,{value:e.value,attributes:n,final:r}),this.debug&&console.log(`[WebVitals] ${t} captured: ${e.value}`+(r?` (final)`:``))}finalizeAndFlush(){if(!(this.flushed||this.metricsMap.size===0)){for(let[e,t]of this.metricsMap.entries())t.final||(t.final=!0,this.debug&&console.log(`[WebVitals] ${e} finalized: ${t.value}`));this.flushWithBeacon()}}buildPayload(){if(this.metricsMap.size===0)return null;let e=Array.from(this.metricsMap.entries()).map(([e,t])=>({metric:e,value:t.value,attributes:t.attributes}));return{body:JSON.stringify({sessionId:window.__FA_getSessionId?.(),vitals:e,metadata:{url:window.location.href}}),count:e.length}}flushWithBeacon(){let e=this.buildPayload();if(e){if(this.flushed=!0,this.debug){let t=Array.from(this.metricsMap.keys()).join(`, `);console.log(`[WebVitals] Sending final metrics (${e.count}): ${t}`)}fetch(this.endpoint,{method:`POST`,body:e.body,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.siteKey}`},keepalive:!0}).catch(()=>{this.debug&&console.warn(`[WebVitals] Failed to send metrics`)})}}};return typeof window<`u`&&(window.__FA_WebVitalsTracker=q),q})();
|
package/src/index.ts
DELETED
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
type ConsentMode,
|
|
3
|
-
isTrackingDisabled,
|
|
4
|
-
sendData,
|
|
5
|
-
WebAnalytics,
|
|
6
|
-
type WebAnalyticsOptions,
|
|
7
|
-
} from "./analytics";
|
|
8
|
-
|
|
9
|
-
export { isTrackingDisabled, sendData, WebAnalytics };
|
|
10
|
-
export type { ConsentMode, WebAnalyticsOptions };
|
|
11
|
-
|
|
12
|
-
function parseBooleanAttribute(
|
|
13
|
-
value: string | null | undefined,
|
|
14
|
-
): boolean | undefined {
|
|
15
|
-
if (value == null) return undefined;
|
|
16
|
-
const normalized = value.trim().toLowerCase();
|
|
17
|
-
if (normalized === "true" || normalized === "1") return true;
|
|
18
|
-
if (normalized === "false" || normalized === "0") return false;
|
|
19
|
-
return undefined;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
function parseSamplingAttribute(
|
|
23
|
-
value: string | null | undefined,
|
|
24
|
-
): number | undefined {
|
|
25
|
-
if (value == null || value.trim() === "") return undefined;
|
|
26
|
-
const parsed = Number(value);
|
|
27
|
-
if (!Number.isFinite(parsed)) return undefined;
|
|
28
|
-
return Math.max(0, Math.min(100, parsed));
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
function parseConsentModeAttribute(
|
|
32
|
-
value: string | null | undefined,
|
|
33
|
-
): ConsentMode | undefined {
|
|
34
|
-
if (value == null) return undefined;
|
|
35
|
-
const normalized = value.trim().toLowerCase();
|
|
36
|
-
if (normalized === "pending") return "pending";
|
|
37
|
-
if (normalized === "granted") return "granted";
|
|
38
|
-
if (normalized === "denied") return "denied";
|
|
39
|
-
return undefined;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
if (typeof window !== "undefined") {
|
|
43
|
-
window.WebAnalytics = WebAnalytics;
|
|
44
|
-
window.__FA_isTrackingDisabled = isTrackingDisabled;
|
|
45
|
-
|
|
46
|
-
(() => {
|
|
47
|
-
const s = document.currentScript as HTMLScriptElement | null;
|
|
48
|
-
if (!s) return;
|
|
49
|
-
const el = s;
|
|
50
|
-
const d = (k: string) => el.getAttribute(`data-${k}`);
|
|
51
|
-
const siteKey = d("sitekey");
|
|
52
|
-
if (!siteKey) return;
|
|
53
|
-
const opts: WebAnalyticsOptions = { siteKey };
|
|
54
|
-
const endpoint = d("endpoint");
|
|
55
|
-
if (endpoint) opts.endpoint = endpoint;
|
|
56
|
-
const dbg = d("debug");
|
|
57
|
-
if (dbg) opts.debug = dbg === "true";
|
|
58
|
-
const err = parseBooleanAttribute(d("trackErrors"));
|
|
59
|
-
if (err !== undefined) {
|
|
60
|
-
opts.trackErrors = err;
|
|
61
|
-
opts.errorTracking = { enabled: err };
|
|
62
|
-
}
|
|
63
|
-
const wv = parseBooleanAttribute(d("webVitals"));
|
|
64
|
-
const wvs = parseSamplingAttribute(d("web-vitals-sampling"));
|
|
65
|
-
if (wv !== undefined || wvs !== undefined) {
|
|
66
|
-
if (wv !== undefined) opts.trackWebVitals = wv;
|
|
67
|
-
opts.webVitals = {
|
|
68
|
-
enabled: wv,
|
|
69
|
-
sampling: wvs !== undefined ? { percentage: wvs } : undefined,
|
|
70
|
-
};
|
|
71
|
-
}
|
|
72
|
-
const rp = parseBooleanAttribute(d("replay"));
|
|
73
|
-
const rps = parseSamplingAttribute(d("replay-sampling"));
|
|
74
|
-
if (rp !== undefined || rps !== undefined) {
|
|
75
|
-
if (rp !== undefined) opts.trackReplay = rp;
|
|
76
|
-
opts.sessionReplays = {
|
|
77
|
-
enabled: rp,
|
|
78
|
-
sampling: rps !== undefined ? { percentage: rps } : undefined,
|
|
79
|
-
};
|
|
80
|
-
}
|
|
81
|
-
const cookieless = parseBooleanAttribute(d("cookieless"));
|
|
82
|
-
if (cookieless !== undefined) opts.cookieless = cookieless;
|
|
83
|
-
const consentMode = parseConsentModeAttribute(d("consent-mode"));
|
|
84
|
-
const cookielessWhilePending = parseBooleanAttribute(
|
|
85
|
-
d("cookieless-while-pending"),
|
|
86
|
-
);
|
|
87
|
-
if (consentMode !== undefined || cookielessWhilePending !== undefined) {
|
|
88
|
-
opts.consent = {
|
|
89
|
-
mode: consentMode,
|
|
90
|
-
cookielessWhilePending,
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
new WebAnalytics(opts);
|
|
94
|
-
})();
|
|
95
|
-
}
|