@prunellejs/analytics 0.0.0-stage → 0.7.2

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/src/vitals.ts ADDED
@@ -0,0 +1,99 @@
1
+ // Optional first-party Web Vitals collector (<1.5 KB standalone browser script + server payload validation).
2
+
3
+ import type { WebVitalMetric, WebVitalName, WebVitalRating } from './types'
4
+
5
+ export const DEFAULT_VITALS_ENDPOINT = '/_pru/analytics/vitals'
6
+
7
+ const VALID_VITAL_NAMES = new Set<WebVitalName>(['LCP', 'CLS', 'INP', 'FCP', 'TTFB'])
8
+ const VALID_RATINGS = new Set<WebVitalRating>(['good', 'needs-improvement', 'poor'])
9
+
10
+ const THRESHOLDS: Record<WebVitalName, readonly [number, number]> = {
11
+ LCP: [2500, 4000],
12
+ CLS: [0.1, 0.25],
13
+ INP: [200, 500],
14
+ FCP: [1800, 3000],
15
+ TTFB: [800, 1800],
16
+ }
17
+
18
+ /** Computes the Core Web Vitals rating for a metric name and numeric value. */
19
+ export function rateWebVital(name: WebVitalName, value: number): WebVitalRating {
20
+ const [good, poor] = THRESHOLDS[name]
21
+ if (value <= good)
22
+ return 'good'
23
+ if (value <= poor)
24
+ return 'needs-improvement'
25
+ return 'poor'
26
+ }
27
+
28
+ /** At most one entry per metric in a beacon. */
29
+ const MAX_VITALS_PER_BEACON = VALID_VITAL_NAMES.size
30
+
31
+ /**
32
+ * A standalone, zero-dependency browser script (<1.5 KB) that observes LCP, CLS, INP, FCP and TTFB via `PerformanceObserver`
33
+ * and sends them to `endpoint` in one beacon when the page hides, by `navigator.sendBeacon` or else `fetch(..., { keepalive: true })`.
34
+ * A `sampleRate` under 1 measures only that share of page views.
35
+ */
36
+ export function buildWebVitalsScript(endpoint: string = DEFAULT_VITALS_ENDPOINT, sampleRate = 1): string {
37
+ const ep = JSON.stringify(endpoint)
38
+ return `(()=>{if(typeof PerformanceObserver>"t"${sampleRate < 1 ? `||Math.random()>=${sampleRate}` : ''})return;`
39
+ + `let e=${ep},j="application/json",s={},q=[],t={LCP:[2500,4e3],CLS:[.1,.25],INP:[200,500],FCP:[1800,3e3],TTFB:[800,1800]},l=-1,c=0,w=0,a=0,b=0,m={},`
40
+ + `p=(k,v)=>{if(s[k]||!(v>=0))return;s[k]=1;`
41
+ + `let r=t[k];q.push({name:k,value:+v.toFixed(3),rating:v<=r[0]?"good":v<=r[1]?"needs-improvement":"poor",path:location.pathname})},`
42
+ + `o=(y,f,x)=>{try{new PerformanceObserver(g=>f(g.getEntries())).observe({type:y,buffered:!0,...x})}catch(_){}},`
43
+ + `h=addEventListener;`
44
+ + `try{let n=performance.getEntriesByType("navigation")[0]?.responseStart;n>=0&&p("TTFB",n)}catch(_){}`
45
+ + `o("paint",g=>{for(let i of g)i.name=="first-contentful-paint"&&p("FCP",i.startTime)});`
46
+ + `o("largest-contentful-paint",g=>{let i=g.at(-1);i&&(l=i.startTime)});`
47
+ + `o("layout-shift",g=>{for(let i of g){if(i.hadRecentInput)continue;let u=i.startTime;w=w&&u-b<1e3&&u-a<=5e3?w+i.value:(a=u,i.value);b=u;if(w>c)c=w}});`
48
+ + `o("event",g=>{for(let i of g){let k=i.interactionId;if(k>0&&!(m[k]>=i.duration))m[k]=i.duration}},{durationThreshold:40});`
49
+ + `let f=()=>{p("LCP",l);p("CLS",c);let v=Object.values(m).sort((x,y)=>y-x);p("INP",v.length?v[v.length/50|0]:-1);if(!q.length)return;`
50
+ + `let d=JSON.stringify(q);q=[];try{if(navigator.sendBeacon?.(e,new Blob([d],{type:j})))return}catch(_){}`
51
+ + `fetch(e,{method:"POST",headers:{"content-type":j},body:d,keepalive:!0,credentials:"same-origin"}).catch(()=>{})};`
52
+ + `h("visibilitychange",()=>document.visibilityState=="hidden"&&f());h("pagehide",f)})();\n`
53
+ }
54
+
55
+ function fallbackPathFromReferer(request: Request): string {
56
+ const referer = request.headers.get('referer')
57
+ if (referer !== null && URL.canParse(referer))
58
+ return new URL(referer).pathname
59
+ return '/'
60
+ }
61
+
62
+ /** The valid metrics of a beacon: one metric object, or an array of at most one per metric; `undefined` when none is valid or the array is longer. */
63
+ export function parseWebVitalPayloads(raw: unknown, request: Request): WebVitalMetric[] | undefined {
64
+ if (!Array.isArray(raw)) {
65
+ const one = parseWebVitalPayload(raw, request)
66
+ return one === undefined ? undefined : [one]
67
+ }
68
+ if (raw.length > MAX_VITALS_PER_BEACON)
69
+ return undefined
70
+ const vitals = raw.map(entry => parseWebVitalPayload(entry, request)).filter(v => v !== undefined)
71
+ return vitals.length === 0 ? undefined : vitals
72
+ }
73
+
74
+ /** Parses and validates a Web Vital JSON beacon payload. */
75
+ export function parseWebVitalPayload(raw: unknown, request: Request): WebVitalMetric | undefined {
76
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
77
+ return undefined
78
+ const obj = raw as Record<string, unknown>
79
+ if (typeof obj.name !== 'string' || !VALID_VITAL_NAMES.has(obj.name as WebVitalName))
80
+ return undefined
81
+ const name = obj.name as WebVitalName
82
+ if (typeof obj.value !== 'number' || !Number.isFinite(obj.value) || obj.value < 0)
83
+ return undefined
84
+ const rating: WebVitalRating = typeof obj.rating === 'string' && VALID_RATINGS.has(obj.rating as WebVitalRating)
85
+ ? (obj.rating as WebVitalRating)
86
+ : rateWebVital(name, obj.value)
87
+ const rawPath = typeof obj.path === 'string' ? obj.path.trim() : ''
88
+ const path = rawPath.startsWith('/') && !rawPath.startsWith('//')
89
+ ? (rawPath.split(/[?#]/, 1)[0] ?? '/').slice(0, 512)
90
+ : fallbackPathFromReferer(request)
91
+ const id = typeof obj.id === 'string' && obj.id.trim() !== '' ? obj.id.trim().slice(0, 64) : undefined
92
+ return {
93
+ name,
94
+ value: obj.value,
95
+ rating,
96
+ path,
97
+ ...(id !== undefined ? { id } : {}),
98
+ }
99
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.