@prunellejs/analytics 0.0.0-stage → 0.5.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/llms.txt +42 -0
- package/package.json +25 -4
- package/src/client.ts +59 -0
- package/src/index.ts +467 -0
- package/src/providers.ts +227 -0
- package/src/types.ts +167 -0
- package/src/visitor.ts +160 -0
- package/src/vitals.ts +84 -0
- package/README.md +0 -3
package/llms.txt
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# @prunellejs/analytics Reference
|
|
2
|
+
|
|
3
|
+
> CNIL-compliant server-side audience measurement (0 B client JS), daily-rotating SHA-256 visitor hashes with no cookies, first-party CSRF-protected custom events, and optional `<1.5 KB` Web Vitals.
|
|
4
|
+
|
|
5
|
+
## Imports
|
|
6
|
+
|
|
7
|
+
- `@prunellejs/analytics`: `analytics`, `plausible`, `umami`, `matomo`, `custom`, `computeVisitorId`, `DEFAULT_EVENT_ENDPOINT`, `DEFAULT_VITALS_ENDPOINT`; types `AnalyticsOptions`, `AnalyticsProvider`, `AnalyticsPageview`, `AnalyticsEvent`, `AnalyticsEventProps`, `WebVitalMetric`, `WebVitalName`, `WebVitalRating`, `WebVitalsOptions`, `PlausibleOptions`, `UmamiOptions`, `MatomoOptions`, `CustomAnalyticsOptions`.
|
|
8
|
+
- `@prunellejs/analytics/client`: `trackEvent`; types `AnalyticsEventProps`, `TrackEventOptions` (browser-safe, zero server imports).
|
|
9
|
+
|
|
10
|
+
## Setup (`analytics(options)`)
|
|
11
|
+
|
|
12
|
+
Register in `prunelle.config.ts` `plugins`:
|
|
13
|
+
|
|
14
|
+
- `provider`: `plausible({ domain, host? })`, `umami({ websiteId, host })`, `matomo({ url, siteId, tokenAuth? })`, or `custom({ sendPageview, sendEvent?, sendVital?, requiresConsent? })`. Self-hosted providers default to `requiresConsent: false`; third-party `plausible.io` defaults to `requiresConsent: true`.
|
|
15
|
+
- Counts both dynamic and prerendered HTML GET 2xx page views via `api.use(mw, { scope: 'all' })` with **0 B client JS** (never sets `clientEntry`). Automatically skips non-GET, non-2xx/non-HTML, `/_pru/` assets, `/auth` and `/auth/*` paths, bots, and prefetch requests. Strips query strings and fragments from `url` and `referrer` by default (pass `includeQueryParams: ['utm_source', ...]` to allowlist specific query params).
|
|
16
|
+
- `secret`: optional hash salt (defaults to `process.env.ANALYTICS_SECRET` or a random ephemeral per-process 32-byte secret). Visitor ID is `SHA-256(YYYY-MM-DD, secret, ip, userAgent, hostname)` — daily-rotating, no cookies, no persistent storage.
|
|
17
|
+
- `sendIp`: default `false`. Raw client IP is NEVER forwarded to providers unless `sendIp: true`.
|
|
18
|
+
- `requiresConsent` / `consentCategory`: consent gating automatically turns on (`'analytics'`) when `sendIp: true` or `provider.requiresConsent === true`. Applies to page views, custom events, and Web Vitals (`onVital` and `provider.sendVital`). Override with `consentCategory: 'analytics'` or `consentCategory: false`.
|
|
19
|
+
- `eventEndpoint`: first-party CSRF-protected POST endpoint (default `'/_pru/analytics/event'`, or `false` to disable). Event URLs are confined to same-origin (`site` or request origin).
|
|
20
|
+
- `webVitals`: default `false` (0 B JS). Set `true` or `{ endpoint?, onVital? }` to emit a `<1.5 KB` `<script defer src="/_pru/analytics-vitals-*.js">` collecting LCP, session-window CLS, p98 INP, FCP, and TTFB to `POST /_pru/analytics/vitals` (CSRF-protected).
|
|
21
|
+
- `ignoreBots`: default `true`. `exclude`: path prefixes, RegExps, or `(ctx) => boolean`. `rateLimit`: rate limit on event/vitals endpoints (default `60/min` per IP; `false` disables). `maxPending`: max concurrent outbound provider requests before dropping (default `64`). `onError`: optional provider error callback.
|
|
22
|
+
|
|
23
|
+
## Snippet
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
// prunelle.config.ts
|
|
27
|
+
import { analytics, plausible } from '@prunellejs/analytics'
|
|
28
|
+
import { defineConfig } from 'prunelle/config'
|
|
29
|
+
|
|
30
|
+
export default defineConfig({
|
|
31
|
+
site: 'https://example.com',
|
|
32
|
+
plugins: [
|
|
33
|
+
analytics({
|
|
34
|
+
provider: plausible({ domain: 'example.com', host: 'https://stats.example.com' }),
|
|
35
|
+
}),
|
|
36
|
+
],
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
// In an island (browser):
|
|
40
|
+
import { trackEvent } from '@prunellejs/analytics/client'
|
|
41
|
+
await trackEvent('newsletter_signup', { plan: 'free' })
|
|
42
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/analytics",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.5.2",
|
|
4
|
+
"description": "CNIL-compliant server-side first-party audience measurement, custom events, and optional Web Vitals plugin for Prunelle",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"files": [
|
|
9
|
+
"src",
|
|
10
|
+
"llms.txt"
|
|
11
|
+
],
|
|
12
|
+
"exports": {
|
|
13
|
+
".": "./src/index.ts",
|
|
14
|
+
"./client": "./src/client.ts"
|
|
15
|
+
},
|
|
16
|
+
"engines": {
|
|
17
|
+
"bun": ">=1.4.0"
|
|
18
|
+
},
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "https://github.com/Kayno0o/prunelle",
|
|
22
|
+
"directory": "packages/plugin-analytics"
|
|
23
|
+
},
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"prunelle": "^0.5.2"
|
|
26
|
+
}
|
|
27
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Browser-safe first-party custom event helper for @prunellejs/analytics/client.
|
|
2
|
+
// Zero server/Node/Bun imports.
|
|
3
|
+
|
|
4
|
+
export type AnalyticsEventProps = Record<string, string | number | boolean>
|
|
5
|
+
|
|
6
|
+
export interface TrackEventOptions {
|
|
7
|
+
/** First-party POST endpoint path (default: `'/_pru/analytics/event'`). */
|
|
8
|
+
endpoint?: string | undefined
|
|
9
|
+
/** Page URL or pathname to associate with the event (defaults to `location.href`). */
|
|
10
|
+
url?: string | undefined
|
|
11
|
+
/** Use `navigator.sendBeacon` when available (default: `false`, uses `fetch` with `keepalive: true`). */
|
|
12
|
+
beacon?: boolean | undefined
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const DEFAULT_EVENT_ENDPOINT = '/_pru/analytics/event'
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Sends a custom analytics event to Prunelle's first-party CSRF-protected endpoint.
|
|
19
|
+
* Returns `true` when accepted (HTTP 2xx or queued via `sendBeacon`), `false` otherwise.
|
|
20
|
+
*/
|
|
21
|
+
export async function trackEvent(
|
|
22
|
+
name: string,
|
|
23
|
+
props?: AnalyticsEventProps,
|
|
24
|
+
options?: TrackEventOptions,
|
|
25
|
+
): Promise<boolean> {
|
|
26
|
+
const trimmed = name.trim()
|
|
27
|
+
if (trimmed === '' || typeof window === 'undefined')
|
|
28
|
+
return false
|
|
29
|
+
|
|
30
|
+
const endpoint = options?.endpoint ?? DEFAULT_EVENT_ENDPOINT
|
|
31
|
+
const url = options?.url ?? (typeof location !== 'undefined' ? location.href : '/')
|
|
32
|
+
const body = JSON.stringify(props !== undefined ? { name: trimmed, url, props } : { name: trimmed, url })
|
|
33
|
+
|
|
34
|
+
if (options?.beacon === true && typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function') {
|
|
35
|
+
try {
|
|
36
|
+
return navigator.sendBeacon(endpoint, new Blob([body], { type: 'application/json' }))
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return false
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
if (typeof fetch !== 'function')
|
|
44
|
+
return false
|
|
45
|
+
|
|
46
|
+
try {
|
|
47
|
+
const res = await fetch(endpoint, {
|
|
48
|
+
method: 'POST',
|
|
49
|
+
headers: { 'content-type': 'application/json' },
|
|
50
|
+
body,
|
|
51
|
+
keepalive: true,
|
|
52
|
+
credentials: 'same-origin',
|
|
53
|
+
})
|
|
54
|
+
return res.ok
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return false
|
|
58
|
+
}
|
|
59
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
// @prunellejs/analytics — CNIL-compliant server-side audience measurement, first-party custom events, and optional Web Vitals.
|
|
2
|
+
// Built strictly on the public PrunellePlugin API. NEVER sets `clientEntry` (0 B of JS for page views).
|
|
3
|
+
|
|
4
|
+
import type { PrunellePlugin } from 'prunelle/config'
|
|
5
|
+
import type { Middleware, RateLimit, RequestContext } from 'prunelle/server'
|
|
6
|
+
import type {
|
|
7
|
+
AnalyticsEvent,
|
|
8
|
+
AnalyticsEventProps,
|
|
9
|
+
AnalyticsOptions,
|
|
10
|
+
AnalyticsPageview,
|
|
11
|
+
WebVitalsOptions,
|
|
12
|
+
} from './types'
|
|
13
|
+
import { definePlugin } from 'prunelle/config'
|
|
14
|
+
import { escAttr } from 'prunelle/server'
|
|
15
|
+
import {
|
|
16
|
+
computeVisitorId,
|
|
17
|
+
extractPrimaryLanguage,
|
|
18
|
+
formatUtcDate,
|
|
19
|
+
generateProcessSecret,
|
|
20
|
+
isBotUserAgent,
|
|
21
|
+
isDefaultSensitivePath,
|
|
22
|
+
isHtmlSuccessResponse,
|
|
23
|
+
isPathExcluded,
|
|
24
|
+
isPrefetchRequest,
|
|
25
|
+
resolveCanonicalLocation,
|
|
26
|
+
sanitizeReferrer,
|
|
27
|
+
} from './visitor'
|
|
28
|
+
import { buildWebVitalsScript, DEFAULT_VITALS_ENDPOINT, parseWebVitalPayload } from './vitals'
|
|
29
|
+
|
|
30
|
+
export { custom, matomo, plausible, umami } from './providers'
|
|
31
|
+
export { computeVisitorId, formatUtcDate, isBotUserAgent, isPrefetchRequest } from './visitor'
|
|
32
|
+
export { buildWebVitalsScript, DEFAULT_VITALS_ENDPOINT, rateWebVital } from './vitals'
|
|
33
|
+
export type {
|
|
34
|
+
AnalyticsEvent,
|
|
35
|
+
AnalyticsEventProps,
|
|
36
|
+
AnalyticsOptions,
|
|
37
|
+
AnalyticsPageview,
|
|
38
|
+
AnalyticsProvider,
|
|
39
|
+
CustomAnalyticsOptions,
|
|
40
|
+
FetchLike,
|
|
41
|
+
MatomoOptions,
|
|
42
|
+
PlausibleOptions,
|
|
43
|
+
UmamiOptions,
|
|
44
|
+
WebVitalMetric,
|
|
45
|
+
WebVitalName,
|
|
46
|
+
WebVitalRating,
|
|
47
|
+
WebVitalsOptions,
|
|
48
|
+
} from './types'
|
|
49
|
+
export type { VisitorIdInput } from './visitor'
|
|
50
|
+
|
|
51
|
+
export const DEFAULT_EVENT_ENDPOINT = '/_pru/analytics/event'
|
|
52
|
+
export const DEFAULT_MAX_PENDING = 64
|
|
53
|
+
export const DEFAULT_RATE_LIMIT: RateLimit<RequestContext> = { max: 60, windowMs: 60_000 }
|
|
54
|
+
|
|
55
|
+
const MAX_EVENT_NAME_LEN = 100
|
|
56
|
+
const MAX_PROP_KEYS = 32
|
|
57
|
+
const MAX_PROP_KEY_LEN = 64
|
|
58
|
+
const MAX_PROP_STR_LEN = 256
|
|
59
|
+
|
|
60
|
+
function normalizeEndpoint(raw: string): string {
|
|
61
|
+
const trimmed = raw.trim()
|
|
62
|
+
const withSlash = trimmed.startsWith('/') ? trimmed : `/${trimmed}`
|
|
63
|
+
return withSlash.length > 1 && withSlash.endsWith('/') ? withSlash.slice(0, -1) : withSlash
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function resolveConsentCategory(options: AnalyticsOptions): string | undefined {
|
|
67
|
+
if (options.consentCategory === false)
|
|
68
|
+
return undefined
|
|
69
|
+
if (typeof options.consentCategory === 'string') {
|
|
70
|
+
if (options.requiresConsent === false)
|
|
71
|
+
return undefined
|
|
72
|
+
const trimmed = options.consentCategory.trim()
|
|
73
|
+
return trimmed !== '' ? trimmed : 'analytics'
|
|
74
|
+
}
|
|
75
|
+
const needsConsent = options.requiresConsent ?? (options.sendIp === true || options.provider.requiresConsent === true)
|
|
76
|
+
return needsConsent ? 'analytics' : undefined
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function normalizeWebVitals(webVitals: AnalyticsOptions['webVitals']): { endpoint: string, onVital?: WebVitalsOptions['onVital'] } | undefined {
|
|
80
|
+
if (webVitals === undefined || webVitals === false)
|
|
81
|
+
return undefined
|
|
82
|
+
if (webVitals === true)
|
|
83
|
+
return { endpoint: DEFAULT_VITALS_ENDPOINT }
|
|
84
|
+
return {
|
|
85
|
+
endpoint: normalizeEndpoint(webVitals.endpoint ?? DEFAULT_VITALS_ENDPOINT),
|
|
86
|
+
...(webVitals.onVital !== undefined ? { onVital: webVitals.onVital } : {}),
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function sanitizeEventProps(raw: unknown): AnalyticsEventProps | undefined | null {
|
|
91
|
+
if (raw === undefined || raw === null)
|
|
92
|
+
return undefined
|
|
93
|
+
if (typeof raw !== 'object' || Array.isArray(raw))
|
|
94
|
+
return null
|
|
95
|
+
const out: AnalyticsEventProps = {}
|
|
96
|
+
let count = 0
|
|
97
|
+
for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {
|
|
98
|
+
if (count >= MAX_PROP_KEYS)
|
|
99
|
+
break
|
|
100
|
+
const key = k.trim()
|
|
101
|
+
if (key === '' || key.length > MAX_PROP_KEY_LEN)
|
|
102
|
+
return null
|
|
103
|
+
if (typeof v === 'string')
|
|
104
|
+
out[key] = v.slice(0, MAX_PROP_STR_LEN)
|
|
105
|
+
else if (typeof v === 'number' && Number.isFinite(v))
|
|
106
|
+
out[key] = v
|
|
107
|
+
else if (typeof v === 'boolean')
|
|
108
|
+
out[key] = v
|
|
109
|
+
else
|
|
110
|
+
return null
|
|
111
|
+
count++
|
|
112
|
+
}
|
|
113
|
+
return count > 0 ? out : undefined
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function parseSameOriginCandidate(
|
|
117
|
+
raw: unknown,
|
|
118
|
+
baseOrigin: string,
|
|
119
|
+
requestOrigin: string,
|
|
120
|
+
): URL | undefined {
|
|
121
|
+
if (typeof raw !== 'string')
|
|
122
|
+
return undefined
|
|
123
|
+
const trimmed = raw.trim()
|
|
124
|
+
if (trimmed === '')
|
|
125
|
+
return undefined
|
|
126
|
+
let parsed: URL
|
|
127
|
+
try {
|
|
128
|
+
parsed = new URL(trimmed, baseOrigin)
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
return undefined
|
|
132
|
+
}
|
|
133
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
|
|
134
|
+
return undefined
|
|
135
|
+
if (parsed.origin !== baseOrigin && parsed.origin !== requestOrigin)
|
|
136
|
+
return undefined
|
|
137
|
+
return parsed
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function resolveBaseOrigin(site: string | undefined, requestOrigin: string): string {
|
|
141
|
+
if (site !== undefined && site !== '' && URL.canParse(site)) {
|
|
142
|
+
const parsed = new URL(site)
|
|
143
|
+
if (parsed.protocol === 'http:' || parsed.protocol === 'https:')
|
|
144
|
+
return parsed.origin
|
|
145
|
+
}
|
|
146
|
+
return requestOrigin
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function resolveEventLocation(
|
|
150
|
+
rawUrl: unknown,
|
|
151
|
+
rawPath: unknown,
|
|
152
|
+
ctx: RequestContext,
|
|
153
|
+
site: string | undefined,
|
|
154
|
+
overrideHostname: string | undefined,
|
|
155
|
+
includeQueryParams: readonly string[] | undefined,
|
|
156
|
+
): { url: string, path: string, hostname: string } {
|
|
157
|
+
const requestOrigin = ctx.url.origin
|
|
158
|
+
const baseOrigin = resolveBaseOrigin(site, requestOrigin)
|
|
159
|
+
const targetUrl = parseSameOriginCandidate(rawUrl, baseOrigin, requestOrigin)
|
|
160
|
+
?? parseSameOriginCandidate(rawPath, baseOrigin, requestOrigin)
|
|
161
|
+
?? parseSameOriginCandidate(ctx.request.headers.get('referer'), baseOrigin, requestOrigin)
|
|
162
|
+
?? new URL('/', baseOrigin)
|
|
163
|
+
return resolveCanonicalLocation(targetUrl, site, overrideHostname, includeQueryParams)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function readJsonBody(request: Request): Promise<{ ok: true, value: unknown } | { ok: false }> {
|
|
167
|
+
let text: string
|
|
168
|
+
try {
|
|
169
|
+
text = await request.text()
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
return { ok: false }
|
|
173
|
+
}
|
|
174
|
+
if (text.trim() === '')
|
|
175
|
+
return { ok: false }
|
|
176
|
+
try {
|
|
177
|
+
return { ok: true, value: JSON.parse(text) as unknown }
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
return { ok: false }
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function parseEventPayload(
|
|
185
|
+
raw: unknown,
|
|
186
|
+
ctx: RequestContext,
|
|
187
|
+
site: string | undefined,
|
|
188
|
+
overrideHostname: string | undefined,
|
|
189
|
+
includeQueryParams: readonly string[] | undefined,
|
|
190
|
+
): { name: string, url: string, path: string, hostname: string, props?: AnalyticsEventProps | undefined } | undefined {
|
|
191
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
|
|
192
|
+
return undefined
|
|
193
|
+
const obj = raw as Record<string, unknown>
|
|
194
|
+
if (typeof obj.name !== 'string')
|
|
195
|
+
return undefined
|
|
196
|
+
const name = obj.name.trim()
|
|
197
|
+
if (name === '' || name.length > MAX_EVENT_NAME_LEN)
|
|
198
|
+
return undefined
|
|
199
|
+
const props = sanitizeEventProps(obj.props)
|
|
200
|
+
if (props === null)
|
|
201
|
+
return undefined
|
|
202
|
+
const loc = resolveEventLocation(obj.url, obj.path, ctx, site, overrideHostname, includeQueryParams)
|
|
203
|
+
return {
|
|
204
|
+
name,
|
|
205
|
+
...loc,
|
|
206
|
+
...(props !== undefined ? { props } : {}),
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function reportError(
|
|
211
|
+
onError: AnalyticsOptions['onError'],
|
|
212
|
+
error: unknown,
|
|
213
|
+
kind: 'pageview' | 'event' | 'vital',
|
|
214
|
+
dev: boolean,
|
|
215
|
+
): void {
|
|
216
|
+
if (onError !== undefined) {
|
|
217
|
+
onError(error, kind)
|
|
218
|
+
return
|
|
219
|
+
}
|
|
220
|
+
if (dev)
|
|
221
|
+
console.warn(`@prunellejs/analytics: failed to send ${kind}:`, error)
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function hashScript(script: string): string {
|
|
225
|
+
const hasher = new Bun.CryptoHasher('sha256')
|
|
226
|
+
hasher.update(script)
|
|
227
|
+
return hasher.digest('hex').slice(0, 8)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
type DispatchFn = (
|
|
231
|
+
fn: () => void | Promise<void>,
|
|
232
|
+
kind: 'pageview' | 'event' | 'vital',
|
|
233
|
+
) => Promise<void> | undefined
|
|
234
|
+
|
|
235
|
+
interface RuntimeConfig {
|
|
236
|
+
provider: AnalyticsOptions['provider']
|
|
237
|
+
sendIp: boolean
|
|
238
|
+
ignoreBots: boolean
|
|
239
|
+
exclude: AnalyticsOptions['exclude']
|
|
240
|
+
includeQueryParams: readonly string[] | undefined
|
|
241
|
+
overrideHostname: string | undefined
|
|
242
|
+
consentCategory: string | undefined
|
|
243
|
+
eventEndpoint: string | false
|
|
244
|
+
webVitals: { endpoint: string, onVital?: WebVitalsOptions['onVital'] } | undefined
|
|
245
|
+
now: () => Date
|
|
246
|
+
onError: AnalyticsOptions['onError']
|
|
247
|
+
visitorIdFor: (ctx: RequestContext, hostname: string, timestamp: Date) => string
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
function createPageviewMiddleware(
|
|
251
|
+
cfg: RuntimeConfig,
|
|
252
|
+
assetPrefix: string,
|
|
253
|
+
site: string | undefined,
|
|
254
|
+
dispatch: DispatchFn,
|
|
255
|
+
): Middleware {
|
|
256
|
+
const isInternalPath = (pathname: string): boolean =>
|
|
257
|
+
pathname === assetPrefix
|
|
258
|
+
|| pathname.startsWith(`${assetPrefix}/`)
|
|
259
|
+
|| isDefaultSensitivePath(pathname)
|
|
260
|
+
|| (cfg.eventEndpoint !== false && pathname === cfg.eventEndpoint)
|
|
261
|
+
|| (cfg.webVitals !== undefined && pathname === cfg.webVitals.endpoint)
|
|
262
|
+
|
|
263
|
+
return async (ctx, next) => {
|
|
264
|
+
const res = await next()
|
|
265
|
+
if (ctx.request.method !== 'GET' || isInternalPath(ctx.url.pathname) || !isHtmlSuccessResponse(res))
|
|
266
|
+
return res
|
|
267
|
+
if (isPrefetchRequest(ctx.request))
|
|
268
|
+
return res
|
|
269
|
+
const userAgent = ctx.request.headers.get('user-agent') ?? undefined
|
|
270
|
+
if (cfg.ignoreBots && isBotUserAgent(userAgent))
|
|
271
|
+
return res
|
|
272
|
+
if (isPathExcluded(ctx, cfg.exclude))
|
|
273
|
+
return res
|
|
274
|
+
if (cfg.consentCategory !== undefined && !ctx.consent.has(cfg.consentCategory))
|
|
275
|
+
return res
|
|
276
|
+
|
|
277
|
+
const timestamp = cfg.now()
|
|
278
|
+
const loc = resolveCanonicalLocation(ctx.url, site, cfg.overrideHostname, cfg.includeQueryParams)
|
|
279
|
+
const referrer = sanitizeReferrer(ctx.request.headers.get('referer'))
|
|
280
|
+
const language = extractPrimaryLanguage(ctx.request)
|
|
281
|
+
const pageview: AnalyticsPageview = {
|
|
282
|
+
...loc,
|
|
283
|
+
visitorId: cfg.visitorIdFor(ctx, loc.hostname, timestamp),
|
|
284
|
+
...(referrer !== undefined ? { referrer } : {}),
|
|
285
|
+
...(userAgent !== undefined && userAgent !== '' ? { userAgent } : {}),
|
|
286
|
+
...(language !== undefined ? { language } : {}),
|
|
287
|
+
...(cfg.sendIp && ctx.ip !== undefined ? { ip: ctx.ip } : {}),
|
|
288
|
+
status: res.status,
|
|
289
|
+
timestamp,
|
|
290
|
+
}
|
|
291
|
+
dispatch(() => cfg.provider.sendPageview(pageview), 'pageview')
|
|
292
|
+
return res
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function createEventHandler(
|
|
297
|
+
cfg: RuntimeConfig,
|
|
298
|
+
site: string | undefined,
|
|
299
|
+
dispatch: DispatchFn,
|
|
300
|
+
): (ctx: RequestContext) => Promise<Response> {
|
|
301
|
+
return async (ctx) => {
|
|
302
|
+
const parsedBody = await readJsonBody(ctx.request)
|
|
303
|
+
if (!parsedBody.ok)
|
|
304
|
+
return ctx.deny(400, 'Invalid JSON body')
|
|
305
|
+
const parsed = parseEventPayload(parsedBody.value, ctx, site, cfg.overrideHostname, cfg.includeQueryParams)
|
|
306
|
+
if (parsed === undefined)
|
|
307
|
+
return ctx.deny(400, 'Invalid analytics event payload')
|
|
308
|
+
if (cfg.consentCategory !== undefined && !ctx.consent.has(cfg.consentCategory))
|
|
309
|
+
return new Response(null, { status: 204 })
|
|
310
|
+
|
|
311
|
+
const timestamp = cfg.now()
|
|
312
|
+
const userAgent = ctx.request.headers.get('user-agent') ?? undefined
|
|
313
|
+
const referrer = sanitizeReferrer(ctx.request.headers.get('referer'))
|
|
314
|
+
const language = extractPrimaryLanguage(ctx.request)
|
|
315
|
+
const event: AnalyticsEvent = {
|
|
316
|
+
...parsed,
|
|
317
|
+
visitorId: cfg.visitorIdFor(ctx, parsed.hostname, timestamp),
|
|
318
|
+
...(referrer !== undefined ? { referrer } : {}),
|
|
319
|
+
...(userAgent !== undefined && userAgent !== '' ? { userAgent } : {}),
|
|
320
|
+
...(language !== undefined ? { language } : {}),
|
|
321
|
+
...(cfg.sendIp && ctx.ip !== undefined ? { ip: ctx.ip } : {}),
|
|
322
|
+
timestamp,
|
|
323
|
+
}
|
|
324
|
+
const sendEvent = cfg.provider.sendEvent
|
|
325
|
+
if (sendEvent !== undefined) {
|
|
326
|
+
const pending = dispatch(() => sendEvent(event), 'event')
|
|
327
|
+
if (pending !== undefined)
|
|
328
|
+
await pending
|
|
329
|
+
}
|
|
330
|
+
return new Response(null, { status: 202 })
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function createVitalsHandler(
|
|
335
|
+
cfg: RuntimeConfig,
|
|
336
|
+
vitals: { endpoint: string, onVital?: WebVitalsOptions['onVital'] },
|
|
337
|
+
dev: boolean,
|
|
338
|
+
dispatch: DispatchFn,
|
|
339
|
+
): (ctx: RequestContext) => Promise<Response> {
|
|
340
|
+
return async (ctx) => {
|
|
341
|
+
const parsedBody = await readJsonBody(ctx.request)
|
|
342
|
+
if (!parsedBody.ok)
|
|
343
|
+
return ctx.deny(400, 'Invalid JSON body')
|
|
344
|
+
const vital = parseWebVitalPayload(parsedBody.value, ctx.request)
|
|
345
|
+
if (vital === undefined)
|
|
346
|
+
return ctx.deny(400, 'Invalid Web Vital payload')
|
|
347
|
+
if (cfg.consentCategory !== undefined && !ctx.consent.has(cfg.consentCategory))
|
|
348
|
+
return new Response(null, { status: 204 })
|
|
349
|
+
|
|
350
|
+
if (vitals.onVital !== undefined) {
|
|
351
|
+
try {
|
|
352
|
+
await vitals.onVital(vital, ctx)
|
|
353
|
+
}
|
|
354
|
+
catch (err) {
|
|
355
|
+
reportError(cfg.onError, err, 'vital', dev)
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
const sendVital = cfg.provider.sendVital
|
|
359
|
+
if (sendVital !== undefined) {
|
|
360
|
+
const pending = dispatch(() => sendVital(vital, ctx), 'vital')
|
|
361
|
+
if (pending !== undefined)
|
|
362
|
+
await pending
|
|
363
|
+
}
|
|
364
|
+
return new Response(null, { status: 202 })
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* CNIL-compliant first-party analytics plugin for Prunelle.
|
|
370
|
+
*
|
|
371
|
+
* - Counts both dynamic and prerendered HTML page views server-side with **0 B of client JS**.
|
|
372
|
+
* - Uses a daily-rotating SHA-256 visitor hash with no cookies and no persistent storage.
|
|
373
|
+
* - Never forwards client IP addresses unless `sendIp: true` is explicitly configured.
|
|
374
|
+
* - Exposes a first-party CSRF-protected custom event endpoint respecting `ctx.consent`.
|
|
375
|
+
* - Optionally emits a `<1.5 KB` standalone Web Vitals collector when `webVitals` is enabled.
|
|
376
|
+
*/
|
|
377
|
+
export function analytics(options: AnalyticsOptions): PrunellePlugin {
|
|
378
|
+
const maxPending = options.maxPending ?? DEFAULT_MAX_PENDING
|
|
379
|
+
if (!Number.isInteger(maxPending) || maxPending < 1)
|
|
380
|
+
throw new Error(`prunelle: @prunellejs/analytics maxPending must be an integer >= 1, got ${String(maxPending)}`)
|
|
381
|
+
|
|
382
|
+
const fallbackSecret = generateProcessSecret()
|
|
383
|
+
const getSecret = (): string => options.secret ?? process.env.ANALYTICS_SECRET ?? fallbackSecret
|
|
384
|
+
const webVitals = normalizeWebVitals(options.webVitals)
|
|
385
|
+
const eventEndpoint = options.eventEndpoint === false
|
|
386
|
+
? false
|
|
387
|
+
: normalizeEndpoint(options.eventEndpoint ?? DEFAULT_EVENT_ENDPOINT)
|
|
388
|
+
const rateLimit = options.rateLimit === false ? undefined : options.rateLimit ?? DEFAULT_RATE_LIMIT
|
|
389
|
+
|
|
390
|
+
const cfg: RuntimeConfig = {
|
|
391
|
+
provider: options.provider,
|
|
392
|
+
sendIp: options.sendIp ?? false,
|
|
393
|
+
ignoreBots: options.ignoreBots ?? true,
|
|
394
|
+
exclude: options.exclude,
|
|
395
|
+
includeQueryParams: options.includeQueryParams,
|
|
396
|
+
overrideHostname: options.hostname,
|
|
397
|
+
consentCategory: resolveConsentCategory(options),
|
|
398
|
+
eventEndpoint,
|
|
399
|
+
webVitals,
|
|
400
|
+
now: options.now ?? (() => new Date()),
|
|
401
|
+
onError: options.onError,
|
|
402
|
+
visitorIdFor: (ctx, hostname, timestamp) =>
|
|
403
|
+
computeVisitorId({
|
|
404
|
+
date: formatUtcDate(timestamp),
|
|
405
|
+
secret: getSecret(),
|
|
406
|
+
ip: ctx.ip ?? '',
|
|
407
|
+
userAgent: ctx.request.headers.get('user-agent') ?? '',
|
|
408
|
+
hostname,
|
|
409
|
+
}),
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
return definePlugin({
|
|
413
|
+
name: '@prunellejs/analytics',
|
|
414
|
+
|
|
415
|
+
build(ctx) {
|
|
416
|
+
if (webVitals === undefined)
|
|
417
|
+
return
|
|
418
|
+
const script = buildWebVitalsScript(webVitals.endpoint)
|
|
419
|
+
const assetUrl = ctx.emitAsset(`analytics-vitals-${hashScript(script)}.js`, script)
|
|
420
|
+
ctx.addHead(`<script defer src="${escAttr(assetUrl)}"></script>`)
|
|
421
|
+
},
|
|
422
|
+
|
|
423
|
+
server(api) {
|
|
424
|
+
// Never count build-time prerender requests or mount live endpoints on the prerender server.
|
|
425
|
+
if (api.config?.prerender === true)
|
|
426
|
+
return
|
|
427
|
+
|
|
428
|
+
const assetPrefix = api.assetPrefix.replace(/\/+$/, '')
|
|
429
|
+
const pending = new Set<Promise<void>>()
|
|
430
|
+
const dispatch: DispatchFn = (fn, kind) => {
|
|
431
|
+
if (pending.size >= maxPending)
|
|
432
|
+
return undefined
|
|
433
|
+
let result: void | Promise<void>
|
|
434
|
+
try {
|
|
435
|
+
result = fn()
|
|
436
|
+
}
|
|
437
|
+
catch (err) {
|
|
438
|
+
reportError(cfg.onError, err, kind, api.dev)
|
|
439
|
+
return undefined
|
|
440
|
+
}
|
|
441
|
+
if (result === undefined)
|
|
442
|
+
return undefined
|
|
443
|
+
const wrapped: Promise<void> = Promise.resolve(result).catch((err) => {
|
|
444
|
+
reportError(cfg.onError, err, kind, api.dev)
|
|
445
|
+
}).finally(() => {
|
|
446
|
+
pending.delete(wrapped)
|
|
447
|
+
})
|
|
448
|
+
pending.add(wrapped)
|
|
449
|
+
return wrapped
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// `scope: 'all'` counts both dynamic and prerendered pages without shipping any client JS.
|
|
453
|
+
api.use(createPageviewMiddleware(cfg, assetPrefix, api.site, dispatch), { scope: 'all' })
|
|
454
|
+
|
|
455
|
+
const routeOpts = { csrf: true, ...(rateLimit !== undefined ? { rateLimit } : {}) }
|
|
456
|
+
if (eventEndpoint !== false)
|
|
457
|
+
api.route('POST', eventEndpoint, createEventHandler(cfg, api.site, dispatch), routeOpts)
|
|
458
|
+
if (webVitals !== undefined)
|
|
459
|
+
api.route('POST', webVitals.endpoint, createVitalsHandler(cfg, webVitals, api.dev, dispatch), routeOpts)
|
|
460
|
+
|
|
461
|
+
api.onShutdown(async () => {
|
|
462
|
+
if (pending.size > 0)
|
|
463
|
+
await Promise.allSettled([...pending])
|
|
464
|
+
})
|
|
465
|
+
},
|
|
466
|
+
})
|
|
467
|
+
}
|
package/src/providers.ts
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// Built-in analytics providers: Plausible, Umami, Matomo, and custom transport.
|
|
2
|
+
// Client IPs are NEVER sent unless `pageview.ip` / `event.ip` is explicitly populated via `sendIp: true`.
|
|
3
|
+
|
|
4
|
+
import type {
|
|
5
|
+
AnalyticsEvent,
|
|
6
|
+
AnalyticsPageview,
|
|
7
|
+
AnalyticsProvider,
|
|
8
|
+
CustomAnalyticsOptions,
|
|
9
|
+
FetchLike,
|
|
10
|
+
MatomoOptions,
|
|
11
|
+
PlausibleOptions,
|
|
12
|
+
UmamiOptions,
|
|
13
|
+
} from './types'
|
|
14
|
+
|
|
15
|
+
const DEFAULT_TIMEOUT_MS = 5_000
|
|
16
|
+
const DEFAULT_USER_AGENT = 'Prunelle-Analytics/1.0'
|
|
17
|
+
|
|
18
|
+
function stripTrailingSlash(url: string): string {
|
|
19
|
+
return url.replace(/\/+$/, '')
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function assertNonEmpty(value: string, label: string): string {
|
|
23
|
+
const trimmed = value.trim()
|
|
24
|
+
if (trimmed === '')
|
|
25
|
+
throw new Error(`prunelle: @prunellejs/analytics ${label} must be a non-empty string`)
|
|
26
|
+
return trimmed
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function postUpstream(
|
|
30
|
+
fetchImpl: FetchLike,
|
|
31
|
+
url: string,
|
|
32
|
+
headers: Record<string, string>,
|
|
33
|
+
body: string,
|
|
34
|
+
timeoutMs: number,
|
|
35
|
+
providerName: string,
|
|
36
|
+
): Promise<void> {
|
|
37
|
+
const res = await fetchImpl(url, {
|
|
38
|
+
method: 'POST',
|
|
39
|
+
headers,
|
|
40
|
+
body,
|
|
41
|
+
...(timeoutMs > 0 ? { signal: AbortSignal.timeout(timeoutMs) } : {}),
|
|
42
|
+
})
|
|
43
|
+
if (!res.ok) {
|
|
44
|
+
const text = await res.text()
|
|
45
|
+
throw new Error(`prunelle: @prunellejs/analytics (${providerName}): HTTP ${res.status}: ${text}`)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function isThirdPartyPlausibleHost(host: string): boolean {
|
|
50
|
+
if (!URL.canParse(host))
|
|
51
|
+
return false
|
|
52
|
+
const hostname = new URL(host).hostname.toLowerCase()
|
|
53
|
+
return hostname === 'plausible.io' || hostname.endsWith('.plausible.io')
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Plausible Events API provider (`POST <host>/api/event`).
|
|
58
|
+
* Self-hosted Plausible without `sendIp: true` defaults to `requiresConsent: false`.
|
|
59
|
+
* Third-party `https://plausible.io` defaults to `requiresConsent: true` unless explicitly opted out.
|
|
60
|
+
*/
|
|
61
|
+
export function plausible(options: PlausibleOptions): AnalyticsProvider {
|
|
62
|
+
const domain = assertNonEmpty(options.domain, 'plausible() domain')
|
|
63
|
+
const host = stripTrailingSlash(options.host ?? 'https://plausible.io')
|
|
64
|
+
const endpoint = `${host}/api/event`
|
|
65
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
66
|
+
const fetchImpl: FetchLike = options.fetch ?? globalThis.fetch
|
|
67
|
+
const defaultRequiresConsent = isThirdPartyPlausibleHost(host)
|
|
68
|
+
|
|
69
|
+
const send = async (
|
|
70
|
+
name: string,
|
|
71
|
+
item: AnalyticsPageview | AnalyticsEvent,
|
|
72
|
+
props?: AnalyticsEvent['props'],
|
|
73
|
+
): Promise<void> => {
|
|
74
|
+
const headers: Record<string, string> = {
|
|
75
|
+
'content-type': 'application/json',
|
|
76
|
+
'user-agent': item.userAgent ?? DEFAULT_USER_AGENT,
|
|
77
|
+
'x-visitor-id': item.visitorId,
|
|
78
|
+
}
|
|
79
|
+
if (item.ip !== undefined)
|
|
80
|
+
headers['x-forwarded-for'] = item.ip
|
|
81
|
+
const payload: Record<string, unknown> = {
|
|
82
|
+
name,
|
|
83
|
+
url: item.url,
|
|
84
|
+
domain,
|
|
85
|
+
referrer: item.referrer ?? null,
|
|
86
|
+
}
|
|
87
|
+
if (props !== undefined)
|
|
88
|
+
payload.props = props
|
|
89
|
+
await postUpstream(fetchImpl, endpoint, headers, JSON.stringify(payload), timeoutMs, 'plausible')
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return {
|
|
93
|
+
name: 'plausible',
|
|
94
|
+
requiresConsent: options.requiresConsent ?? defaultRequiresConsent,
|
|
95
|
+
sendPageview: pv => send('pageview', pv),
|
|
96
|
+
sendEvent: ev => send(ev.name, ev, ev.props),
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Umami Collect API provider (`POST <host>/api/send`).
|
|
102
|
+
* Self-hosted Umami without `sendIp: true` uses daily-rotating hashes and zero cookies.
|
|
103
|
+
*/
|
|
104
|
+
export function umami(options: UmamiOptions): AnalyticsProvider {
|
|
105
|
+
const websiteId = assertNonEmpty(options.websiteId, 'umami() websiteId')
|
|
106
|
+
const host = stripTrailingSlash(assertNonEmpty(options.host, 'umami() host'))
|
|
107
|
+
const endpoint = `${host}/api/send`
|
|
108
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
109
|
+
const fetchImpl: FetchLike = options.fetch ?? globalThis.fetch
|
|
110
|
+
|
|
111
|
+
const send = async (
|
|
112
|
+
item: AnalyticsPageview | AnalyticsEvent,
|
|
113
|
+
eventName?: string,
|
|
114
|
+
props?: AnalyticsEvent['props'],
|
|
115
|
+
): Promise<void> => {
|
|
116
|
+
const headers: Record<string, string> = {
|
|
117
|
+
'content-type': 'application/json',
|
|
118
|
+
'user-agent': item.userAgent ?? DEFAULT_USER_AGENT,
|
|
119
|
+
}
|
|
120
|
+
if (item.ip !== undefined)
|
|
121
|
+
headers['x-forwarded-for'] = item.ip
|
|
122
|
+
const payload: Record<string, unknown> = {
|
|
123
|
+
website: websiteId,
|
|
124
|
+
hostname: item.hostname,
|
|
125
|
+
url: item.path,
|
|
126
|
+
referrer: item.referrer ?? '',
|
|
127
|
+
language: item.language ?? '',
|
|
128
|
+
id: item.visitorId,
|
|
129
|
+
}
|
|
130
|
+
if (eventName !== undefined)
|
|
131
|
+
payload.name = eventName
|
|
132
|
+
if (props !== undefined)
|
|
133
|
+
payload.data = props
|
|
134
|
+
await postUpstream(fetchImpl, endpoint, headers, JSON.stringify({ type: 'event', payload }), timeoutMs, 'umami')
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return {
|
|
138
|
+
name: 'umami',
|
|
139
|
+
requiresConsent: options.requiresConsent ?? false,
|
|
140
|
+
sendPageview: pv => send(pv),
|
|
141
|
+
sendEvent: ev => send(ev, ev.name, ev.props),
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function matomoEndpoint(rawUrl: string): string {
|
|
146
|
+
const trimmed = stripTrailingSlash(assertNonEmpty(rawUrl, 'matomo() url'))
|
|
147
|
+
return trimmed.endsWith('.php') ? trimmed : `${trimmed}/matomo.php`
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function buildMatomoParams(
|
|
151
|
+
siteId: string,
|
|
152
|
+
item: AnalyticsPageview | AnalyticsEvent,
|
|
153
|
+
tokenAuth: string | undefined,
|
|
154
|
+
): URLSearchParams {
|
|
155
|
+
const params = new URLSearchParams({
|
|
156
|
+
idsite: siteId,
|
|
157
|
+
rec: '1',
|
|
158
|
+
apiv: '1',
|
|
159
|
+
send_image: '0',
|
|
160
|
+
url: item.url,
|
|
161
|
+
_id: item.visitorId.slice(0, 16),
|
|
162
|
+
})
|
|
163
|
+
if (item.referrer !== undefined)
|
|
164
|
+
params.set('urlref', item.referrer)
|
|
165
|
+
if (item.userAgent !== undefined)
|
|
166
|
+
params.set('ua', item.userAgent)
|
|
167
|
+
if (item.language !== undefined)
|
|
168
|
+
params.set('lang', item.language)
|
|
169
|
+
if (item.ip !== undefined) {
|
|
170
|
+
params.set('cip', item.ip)
|
|
171
|
+
if (tokenAuth !== undefined && tokenAuth !== '')
|
|
172
|
+
params.set('token_auth', tokenAuth)
|
|
173
|
+
}
|
|
174
|
+
return params
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Matomo Tracking HTTP API provider (`POST <url>/matomo.php`).
|
|
179
|
+
* Uses a 16-hex-char daily-rotating `_id` with zero cookies and never forwards `cip` unless `sendIp: true`.
|
|
180
|
+
*/
|
|
181
|
+
export function matomo(options: MatomoOptions): AnalyticsProvider {
|
|
182
|
+
const endpoint = matomoEndpoint(options.url)
|
|
183
|
+
const siteId = assertNonEmpty(String(options.siteId), 'matomo() siteId')
|
|
184
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS
|
|
185
|
+
const fetchImpl: FetchLike = options.fetch ?? globalThis.fetch
|
|
186
|
+
|
|
187
|
+
const post = async (item: AnalyticsPageview | AnalyticsEvent, params: URLSearchParams): Promise<void> => {
|
|
188
|
+
const headers: Record<string, string> = {
|
|
189
|
+
'content-type': 'application/x-www-form-urlencoded',
|
|
190
|
+
'user-agent': item.userAgent ?? DEFAULT_USER_AGENT,
|
|
191
|
+
}
|
|
192
|
+
if (item.ip !== undefined)
|
|
193
|
+
headers['x-forwarded-for'] = item.ip
|
|
194
|
+
await postUpstream(fetchImpl, endpoint, headers, params.toString(), timeoutMs, 'matomo')
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return {
|
|
198
|
+
name: 'matomo',
|
|
199
|
+
requiresConsent: options.requiresConsent ?? false,
|
|
200
|
+
sendPageview(pv) {
|
|
201
|
+
const params = buildMatomoParams(siteId, pv, options.tokenAuth)
|
|
202
|
+
params.set('action_name', pv.path)
|
|
203
|
+
return post(pv, params)
|
|
204
|
+
},
|
|
205
|
+
sendEvent(ev) {
|
|
206
|
+
const params = buildMatomoParams(siteId, ev, options.tokenAuth)
|
|
207
|
+
params.set('e_c', typeof ev.props?.category === 'string' ? ev.props.category : 'custom')
|
|
208
|
+
params.set('e_a', ev.name)
|
|
209
|
+
if (ev.props?.label !== undefined)
|
|
210
|
+
params.set('e_n', String(ev.props.label))
|
|
211
|
+
if (typeof ev.props?.value === 'number' && Number.isFinite(ev.props.value))
|
|
212
|
+
params.set('e_v', String(ev.props.value))
|
|
213
|
+
return post(ev, params)
|
|
214
|
+
},
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Custom analytics provider backed by user-supplied callbacks. */
|
|
219
|
+
export function custom(options: CustomAnalyticsOptions): AnalyticsProvider {
|
|
220
|
+
return {
|
|
221
|
+
name: options.name ?? 'custom',
|
|
222
|
+
requiresConsent: options.requiresConsent ?? false,
|
|
223
|
+
sendPageview: options.sendPageview,
|
|
224
|
+
...(options.sendEvent !== undefined ? { sendEvent: options.sendEvent } : {}),
|
|
225
|
+
...(options.sendVital !== undefined ? { sendVital: options.sendVital } : {}),
|
|
226
|
+
}
|
|
227
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// Public types for @prunellejs/analytics.
|
|
2
|
+
|
|
3
|
+
import type { RateLimit, RequestContext } from 'prunelle/server'
|
|
4
|
+
|
|
5
|
+
export type AnalyticsEventProps = Record<string, string | number | boolean>
|
|
6
|
+
|
|
7
|
+
export type WebVitalName = 'LCP' | 'CLS' | 'INP' | 'FCP' | 'TTFB'
|
|
8
|
+
|
|
9
|
+
export type WebVitalRating = 'good' | 'needs-improvement' | 'poor'
|
|
10
|
+
|
|
11
|
+
export interface WebVitalMetric {
|
|
12
|
+
name: WebVitalName
|
|
13
|
+
value: number
|
|
14
|
+
rating: WebVitalRating
|
|
15
|
+
path: string
|
|
16
|
+
id?: string | undefined
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface AnalyticsPageview {
|
|
20
|
+
/** Canonical full URL of the viewed page. */
|
|
21
|
+
url: string
|
|
22
|
+
/** Request pathname (e.g. `'/blog/hello'`). */
|
|
23
|
+
path: string
|
|
24
|
+
/** Resolved hostname (e.g. `'example.com'`). */
|
|
25
|
+
hostname: string
|
|
26
|
+
/** Daily-rotating SHA-256 visitor hash (never stored in cookies or browser storage). */
|
|
27
|
+
visitorId: string
|
|
28
|
+
/** Referer header, when present. */
|
|
29
|
+
referrer?: string | undefined
|
|
30
|
+
/** User-Agent header, when present. */
|
|
31
|
+
userAgent?: string | undefined
|
|
32
|
+
/** Accept-Language primary value, when present. */
|
|
33
|
+
language?: string | undefined
|
|
34
|
+
/** Client IP address — ONLY populated when `sendIp: true` is explicitly opted in. */
|
|
35
|
+
ip?: string | undefined
|
|
36
|
+
/** HTTP response status code (always 2xx for counted page views). */
|
|
37
|
+
status: number
|
|
38
|
+
/** Timestamp when the page view was recorded. */
|
|
39
|
+
timestamp: Date
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface AnalyticsEvent {
|
|
43
|
+
/** Event name (e.g. `'signup'`, `'download'`). */
|
|
44
|
+
name: string
|
|
45
|
+
/** Full page URL where the event occurred. */
|
|
46
|
+
url: string
|
|
47
|
+
/** Page pathname where the event occurred. */
|
|
48
|
+
path: string
|
|
49
|
+
/** Resolved hostname. */
|
|
50
|
+
hostname: string
|
|
51
|
+
/** Daily-rotating SHA-256 visitor hash. */
|
|
52
|
+
visitorId: string
|
|
53
|
+
/** Optional flat primitive event properties. */
|
|
54
|
+
props?: AnalyticsEventProps | undefined
|
|
55
|
+
/** Referer header, when present. */
|
|
56
|
+
referrer?: string | undefined
|
|
57
|
+
/** User-Agent header, when present. */
|
|
58
|
+
userAgent?: string | undefined
|
|
59
|
+
/** Accept-Language primary value, when present. */
|
|
60
|
+
language?: string | undefined
|
|
61
|
+
/** Client IP address — ONLY populated when `sendIp: true` is explicitly opted in. */
|
|
62
|
+
ip?: string | undefined
|
|
63
|
+
/** Timestamp when the event was recorded. */
|
|
64
|
+
timestamp: Date
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface AnalyticsProvider {
|
|
68
|
+
readonly name: string
|
|
69
|
+
/** Set `true` when the provider requires prior user consent (e.g. non-exempt third-party SaaS). */
|
|
70
|
+
readonly requiresConsent?: boolean | undefined
|
|
71
|
+
sendPageview(pageview: AnalyticsPageview): void | Promise<void>
|
|
72
|
+
sendEvent?(event: AnalyticsEvent): void | Promise<void>
|
|
73
|
+
sendVital?(vital: WebVitalMetric, ctx: RequestContext): void | Promise<void>
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>
|
|
77
|
+
|
|
78
|
+
export interface PlausibleOptions {
|
|
79
|
+
/** Site domain configured in Plausible (e.g. `'example.com'`). */
|
|
80
|
+
domain: string
|
|
81
|
+
/** Plausible server origin (default: `'https://plausible.io'`). */
|
|
82
|
+
host?: string | undefined
|
|
83
|
+
/** HTTP request timeout in milliseconds (default: `5000`). */
|
|
84
|
+
timeoutMs?: number | undefined
|
|
85
|
+
/** Whether consent is required before sending to this Plausible instance (default: `true` for third-party `plausible.io`, `false` for self-hosted `host`). */
|
|
86
|
+
requiresConsent?: boolean | undefined
|
|
87
|
+
/** Custom `fetch` implementation (useful for tests or proxying). */
|
|
88
|
+
fetch?: FetchLike | undefined
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface UmamiOptions {
|
|
92
|
+
/** Umami website UUID. */
|
|
93
|
+
websiteId: string
|
|
94
|
+
/** Umami server origin (e.g. `'https://analytics.example.com'`). */
|
|
95
|
+
host: string
|
|
96
|
+
/** HTTP request timeout in milliseconds (default: `5000`). */
|
|
97
|
+
timeoutMs?: number | undefined
|
|
98
|
+
/** Whether consent is required before sending to this Umami instance (default: `false`). */
|
|
99
|
+
requiresConsent?: boolean | undefined
|
|
100
|
+
/** Custom `fetch` implementation (useful for tests or proxying). */
|
|
101
|
+
fetch?: FetchLike | undefined
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export interface MatomoOptions {
|
|
105
|
+
/** Matomo base URL or tracking script URL (e.g. `'https://matomo.example.com'`). */
|
|
106
|
+
url: string
|
|
107
|
+
/** Matomo site ID (`idsite`). */
|
|
108
|
+
siteId: number | string
|
|
109
|
+
/** Optional Matomo `token_auth` (required by Matomo when forwarding `cip` via `sendIp: true`). */
|
|
110
|
+
tokenAuth?: string | undefined
|
|
111
|
+
/** HTTP request timeout in milliseconds (default: `5000`). */
|
|
112
|
+
timeoutMs?: number | undefined
|
|
113
|
+
/** Whether consent is required before sending to this Matomo instance (default: `false`). */
|
|
114
|
+
requiresConsent?: boolean | undefined
|
|
115
|
+
/** Custom `fetch` implementation (useful for tests or proxying). */
|
|
116
|
+
fetch?: FetchLike | undefined
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export interface CustomAnalyticsOptions {
|
|
120
|
+
/** Provider label for diagnostics (default: `'custom'`). */
|
|
121
|
+
name?: string | undefined
|
|
122
|
+
/** Whether consent is required before sending to this provider (default: `false`). */
|
|
123
|
+
requiresConsent?: boolean | undefined
|
|
124
|
+
sendPageview: (pageview: AnalyticsPageview) => void | Promise<void>
|
|
125
|
+
sendEvent?: ((event: AnalyticsEvent) => void | Promise<void>) | undefined
|
|
126
|
+
sendVital?: ((vital: WebVitalMetric, ctx: RequestContext) => void | Promise<void>) | undefined
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export interface WebVitalsOptions {
|
|
130
|
+
/** First-party POST endpoint for Web Vitals beacons (default: `'/_pru/analytics/vitals'`). */
|
|
131
|
+
endpoint?: string | undefined
|
|
132
|
+
/** Callback invoked on every validated Web Vital beacon. */
|
|
133
|
+
onVital?: ((vital: WebVitalMetric, ctx: RequestContext) => void | Promise<void>) | undefined
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export interface AnalyticsOptions {
|
|
137
|
+
/** Analytics backend (`plausible(...)`, `umami(...)`, `matomo(...)`, or `custom(...)`). */
|
|
138
|
+
provider: AnalyticsProvider
|
|
139
|
+
/** Ephemeral salt for the daily-rotating SHA-256 visitor hash (defaults to `process.env.ANALYTICS_SECRET` or a random per-process 32-byte key). */
|
|
140
|
+
secret?: string | undefined
|
|
141
|
+
/** Forward raw client IP to the provider (default: `false`). Opting in automatically enables consent gating unless `consentCategory: false`. */
|
|
142
|
+
sendIp?: boolean | undefined
|
|
143
|
+
/** Explicitly require or waive `ctx.consent` checks (defaults to `true` when `sendIp: true` or `provider.requiresConsent === true`). */
|
|
144
|
+
requiresConsent?: boolean | undefined
|
|
145
|
+
/** Consent category checked via `ctx.consent.has(...)` (default: `'analytics'` when consent is required; pass `false` to disable consent gating). */
|
|
146
|
+
consentCategory?: string | false | undefined
|
|
147
|
+
/** First-party POST endpoint for custom events (default: `'/_pru/analytics/event'`; set `false` to disable). */
|
|
148
|
+
eventEndpoint?: string | false | undefined
|
|
149
|
+
/** Enable first-party Web Vitals collection (default: `false`, emitting 0 B of JS). */
|
|
150
|
+
webVitals?: boolean | WebVitalsOptions | undefined
|
|
151
|
+
/** Skip common crawler/bot User-Agents for page views (default: `true`). */
|
|
152
|
+
ignoreBots?: boolean | undefined
|
|
153
|
+
/** Paths, regexes, or predicate excluded from server-side page view counting (in addition to `/_pru/*`, `/auth/*`, and analytics endpoints). */
|
|
154
|
+
exclude?: readonly (string | RegExp)[] | ((ctx: RequestContext) => boolean) | undefined
|
|
155
|
+
/** Allowlist of query parameter names to keep in reported `url` values (default: none — all query strings are stripped to prevent leaking tokens or PII). */
|
|
156
|
+
includeQueryParams?: readonly string[] | undefined
|
|
157
|
+
/** Override hostname used for visitor hashing and provider payloads. */
|
|
158
|
+
hostname?: string | undefined
|
|
159
|
+
/** Rate limit applied to the first-party event and Web Vitals POST endpoints (default: 60 requests/minute per IP; set `false` to disable). */
|
|
160
|
+
rateLimit?: RateLimit<RequestContext> | false | undefined
|
|
161
|
+
/** Maximum concurrent in-flight outbound provider requests before new analytics pings are dropped (default: `64`). */
|
|
162
|
+
maxPending?: number | undefined
|
|
163
|
+
/** Optional clock provider (defaults to `() => new Date()`). */
|
|
164
|
+
now?: (() => Date) | undefined
|
|
165
|
+
/** Error handler invoked when a provider transport call fails (never fails user responses). */
|
|
166
|
+
onError?: ((error: unknown, kind: 'pageview' | 'event' | 'vital') => void) | undefined
|
|
167
|
+
}
|
package/src/visitor.ts
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// Daily-rotating SHA-256 visitor hashing and server-side page view filtering.
|
|
2
|
+
|
|
3
|
+
import type { RequestContext } from 'prunelle/server'
|
|
4
|
+
|
|
5
|
+
export interface VisitorIdInput {
|
|
6
|
+
/** UTC calendar date in `YYYY-MM-DD` format. */
|
|
7
|
+
date: string
|
|
8
|
+
/** Server-side ephemeral or configured hash salt. */
|
|
9
|
+
secret: string
|
|
10
|
+
/** Client IP address (empty string if unavailable). */
|
|
11
|
+
ip: string
|
|
12
|
+
/** Raw User-Agent header (empty string if unavailable). */
|
|
13
|
+
userAgent: string
|
|
14
|
+
/** Site or request hostname. */
|
|
15
|
+
hostname: string
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const BOT_UA_RE = /\b(?:bot|crawl(?:er|ing)?|spider|slurp|bingpreview|facebookexternalhit|linkedinbot|twitterbot|whatsapp|telegrambot|discordbot|applebot|duckduckbot|yandex|baiduspider|semrush|ahrefs|mj12bot|dotbot|petalbot|bytespider|gptbot|claudebot|anthropic-ai|googleother|lighthouse|pagespeed|headlesschrome|phantomjs|uptime|pingdom|datadog|statuscake|check_http)\b|^(?:curl|wget|python-requests|go-http-client|axios|node-fetch|undici|libwww-perl|httpie)\//i
|
|
19
|
+
|
|
20
|
+
/** Formats `date` as a UTC `YYYY-MM-DD` string for daily visitor-hash rotation. */
|
|
21
|
+
export function formatUtcDate(date: Date = new Date()): string {
|
|
22
|
+
return date.toISOString().slice(0, 10)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Generates a random 32-byte hex secret scoped to the current process. */
|
|
26
|
+
export function generateProcessSecret(): string {
|
|
27
|
+
const bytes = new Uint8Array(32)
|
|
28
|
+
crypto.getRandomValues(bytes)
|
|
29
|
+
return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('')
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Computes a daily-rotating SHA-256 visitor hash keyed by UTC date, secret, client IP,
|
|
34
|
+
* User-Agent, and hostname. Uses no cookies and no persistent browser storage.
|
|
35
|
+
*/
|
|
36
|
+
export function computeVisitorId(input: VisitorIdInput): string {
|
|
37
|
+
const hasher = new Bun.CryptoHasher('sha256')
|
|
38
|
+
hasher.update(`${input.date}\0${input.secret}\0${input.ip}\0${input.userAgent}\0${input.hostname}`)
|
|
39
|
+
return hasher.digest('hex')
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Returns `true` when `userAgent` matches a known crawler, bot, monitor, or CLI HTTP client. */
|
|
43
|
+
export function isBotUserAgent(userAgent: string | null | undefined): boolean {
|
|
44
|
+
if (userAgent === null || userAgent === undefined || userAgent === '')
|
|
45
|
+
return false
|
|
46
|
+
return BOT_UA_RE.test(userAgent)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Returns `true` when request headers indicate a speculative prefetch or prerender rather than a navigation. */
|
|
50
|
+
export function isPrefetchRequest(request: Request): boolean {
|
|
51
|
+
const secPurpose = request.headers.get('sec-purpose')?.toLowerCase() ?? ''
|
|
52
|
+
if (secPurpose.includes('prefetch') || secPurpose.includes('prerender'))
|
|
53
|
+
return true
|
|
54
|
+
const purpose = request.headers.get('purpose')?.toLowerCase() ?? ''
|
|
55
|
+
if (purpose === 'prefetch' || purpose === 'preview')
|
|
56
|
+
return true
|
|
57
|
+
const xMoz = request.headers.get('x-moz')?.toLowerCase() ?? ''
|
|
58
|
+
if (xMoz === 'prefetch')
|
|
59
|
+
return true
|
|
60
|
+
const xPurpose = request.headers.get('x-purpose')?.toLowerCase() ?? ''
|
|
61
|
+
return xPurpose === 'prefetch' || xPurpose === 'preview'
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Extracts the primary language tag from an `Accept-Language` header, if present. */
|
|
65
|
+
export function extractPrimaryLanguage(request: Request): string | undefined {
|
|
66
|
+
const raw = request.headers.get('accept-language')?.trim()
|
|
67
|
+
if (raw === undefined || raw === '')
|
|
68
|
+
return undefined
|
|
69
|
+
const first = raw.split(',')[0]?.split(';')[0]?.trim()
|
|
70
|
+
return first !== undefined && first !== '' ? first : undefined
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Strips query strings and fragments from a Referer header to prevent leaking tokens or search PII. */
|
|
74
|
+
export function sanitizeReferrer(raw: string | null | undefined): string | undefined {
|
|
75
|
+
if (raw === null || raw === undefined)
|
|
76
|
+
return undefined
|
|
77
|
+
const trimmed = raw.trim()
|
|
78
|
+
if (trimmed === '' || !URL.canParse(trimmed))
|
|
79
|
+
return undefined
|
|
80
|
+
const parsed = new URL(trimmed)
|
|
81
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
|
|
82
|
+
return undefined
|
|
83
|
+
parsed.search = ''
|
|
84
|
+
parsed.hash = ''
|
|
85
|
+
return parsed.href
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function buildAllowedSearch(url: URL, includeQueryParams: readonly string[] | undefined): string {
|
|
89
|
+
if (includeQueryParams === undefined || includeQueryParams.length === 0 || url.search === '')
|
|
90
|
+
return ''
|
|
91
|
+
const allowed = new Set(includeQueryParams)
|
|
92
|
+
const kept = new URLSearchParams()
|
|
93
|
+
for (const [k, v] of url.searchParams) {
|
|
94
|
+
if (allowed.has(k))
|
|
95
|
+
kept.append(k, v)
|
|
96
|
+
}
|
|
97
|
+
const qs = kept.toString()
|
|
98
|
+
return qs !== '' ? `?${qs}` : ''
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Resolves the canonical URL and hostname for a request, preferring `site` from `prunelle.config.ts` when set.
|
|
103
|
+
* Strips query strings and fragments by default unless parameter names are explicitly listed in `includeQueryParams`.
|
|
104
|
+
*/
|
|
105
|
+
export function resolveCanonicalLocation(
|
|
106
|
+
url: URL,
|
|
107
|
+
site: string | undefined,
|
|
108
|
+
overrideHostname: string | undefined,
|
|
109
|
+
includeQueryParams?: readonly string[] | undefined,
|
|
110
|
+
): { url: string, path: string, hostname: string } {
|
|
111
|
+
const path = url.pathname
|
|
112
|
+
let origin = url.origin
|
|
113
|
+
let hostname = url.hostname
|
|
114
|
+
if (site !== undefined && site !== '' && URL.canParse(site)) {
|
|
115
|
+
const parsedSite = new URL(site)
|
|
116
|
+
if (parsedSite.protocol === 'http:' || parsedSite.protocol === 'https:') {
|
|
117
|
+
origin = parsedSite.origin
|
|
118
|
+
hostname = parsedSite.hostname
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const canonical = new URL(origin)
|
|
122
|
+
canonical.pathname = path
|
|
123
|
+
canonical.search = buildAllowedSearch(url, includeQueryParams)
|
|
124
|
+
if (overrideHostname !== undefined && overrideHostname !== '')
|
|
125
|
+
hostname = overrideHostname
|
|
126
|
+
return { url: canonical.href, path, hostname }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Returns `true` for sensitive auth paths (`/auth` and `/auth/*`) excluded from automatic pageview counting by default. */
|
|
130
|
+
export function isDefaultSensitivePath(pathname: string): boolean {
|
|
131
|
+
return pathname === '/auth' || pathname.startsWith('/auth/')
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function isPathExcluded(
|
|
135
|
+
ctx: RequestContext,
|
|
136
|
+
exclude: readonly (string | RegExp)[] | ((ctx: RequestContext) => boolean) | undefined,
|
|
137
|
+
): boolean {
|
|
138
|
+
if (exclude === undefined)
|
|
139
|
+
return false
|
|
140
|
+
if (typeof exclude === 'function')
|
|
141
|
+
return exclude(ctx)
|
|
142
|
+
const pathname = ctx.url.pathname
|
|
143
|
+
for (const rule of exclude) {
|
|
144
|
+
if (typeof rule === 'string') {
|
|
145
|
+
if (pathname === rule || pathname.startsWith(rule.endsWith('/') ? rule : `${rule}/`))
|
|
146
|
+
return true
|
|
147
|
+
}
|
|
148
|
+
else if (rule.test(pathname)) {
|
|
149
|
+
return true
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return false
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function isHtmlSuccessResponse(res: Response): boolean {
|
|
156
|
+
if (res.status < 200 || res.status >= 300)
|
|
157
|
+
return false
|
|
158
|
+
const ct = res.headers.get('content-type')?.toLowerCase() ?? ''
|
|
159
|
+
return ct.includes('text/html')
|
|
160
|
+
}
|
package/src/vitals.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
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
|
+
/**
|
|
29
|
+
* Generates a standalone, zero-dependency browser script (<1.5 KB) that observes
|
|
30
|
+
* LCP, CLS, INP, FCP, and TTFB via `PerformanceObserver` and reports them to `endpoint`
|
|
31
|
+
* using `navigator.sendBeacon` with a `fetch(..., { keepalive: true })` fallback.
|
|
32
|
+
*/
|
|
33
|
+
export function buildWebVitalsScript(endpoint: string = DEFAULT_VITALS_ENDPOINT): string {
|
|
34
|
+
const ep = JSON.stringify(endpoint)
|
|
35
|
+
return `(()=>{if(typeof PerformanceObserver>"t")return;`
|
|
36
|
+
+ `let e=${ep},j="application/json",s={},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={},`
|
|
37
|
+
+ `p=(k,v)=>{if(s[k]||!(v>=0))return;s[k]=1;`
|
|
38
|
+
+ `let r=t[k],d=JSON.stringify({name:k,value:+v.toFixed(3),rating:v<=r[0]?"good":v<=r[1]?"needs-improvement":"poor",path:location.pathname});`
|
|
39
|
+
+ `try{if(navigator.sendBeacon?.(e,new Blob([d],{type:j})))return}catch(_){}`
|
|
40
|
+
+ `fetch(e,{method:"POST",headers:{"content-type":j},body:d,keepalive:!0,credentials:"same-origin"}).catch(()=>{})},`
|
|
41
|
+
+ `o=(y,f,x)=>{try{new PerformanceObserver(g=>f(g.getEntries())).observe({type:y,buffered:!0,...x})}catch(_){}},`
|
|
42
|
+
+ `h=addEventListener;`
|
|
43
|
+
+ `try{let n=performance.getEntriesByType("navigation")[0]?.responseStart;n>=0&&p("TTFB",n)}catch(_){}`
|
|
44
|
+
+ `o("paint",g=>{for(let i of g)i.name=="first-contentful-paint"&&p("FCP",i.startTime)});`
|
|
45
|
+
+ `o("largest-contentful-paint",g=>{let i=g.at(-1);i&&(l=i.startTime)});`
|
|
46
|
+
+ `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}});`
|
|
47
|
+
+ `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});`
|
|
48
|
+
+ `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)};`
|
|
49
|
+
+ `h("visibilitychange",()=>document.visibilityState=="hidden"&&f());h("pagehide",f)})();\n`
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function fallbackPathFromReferer(request: Request): string {
|
|
53
|
+
const referer = request.headers.get('referer')
|
|
54
|
+
if (referer !== null && URL.canParse(referer))
|
|
55
|
+
return new URL(referer).pathname
|
|
56
|
+
return '/'
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Parses and validates a Web Vital JSON beacon payload. */
|
|
60
|
+
export function parseWebVitalPayload(raw: unknown, request: Request): WebVitalMetric | undefined {
|
|
61
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
|
|
62
|
+
return undefined
|
|
63
|
+
const obj = raw as Record<string, unknown>
|
|
64
|
+
if (typeof obj.name !== 'string' || !VALID_VITAL_NAMES.has(obj.name as WebVitalName))
|
|
65
|
+
return undefined
|
|
66
|
+
const name = obj.name as WebVitalName
|
|
67
|
+
if (typeof obj.value !== 'number' || !Number.isFinite(obj.value) || obj.value < 0)
|
|
68
|
+
return undefined
|
|
69
|
+
const rating: WebVitalRating = typeof obj.rating === 'string' && VALID_RATINGS.has(obj.rating as WebVitalRating)
|
|
70
|
+
? (obj.rating as WebVitalRating)
|
|
71
|
+
: rateWebVital(name, obj.value)
|
|
72
|
+
const rawPath = typeof obj.path === 'string' ? obj.path.trim() : ''
|
|
73
|
+
const path = rawPath.startsWith('/') && !rawPath.startsWith('//')
|
|
74
|
+
? (rawPath.split(/[?#]/, 1)[0] ?? '/').slice(0, 512)
|
|
75
|
+
: fallbackPathFromReferer(request)
|
|
76
|
+
const id = typeof obj.id === 'string' && obj.id.trim() !== '' ? obj.id.trim().slice(0, 64) : undefined
|
|
77
|
+
return {
|
|
78
|
+
name,
|
|
79
|
+
value: obj.value,
|
|
80
|
+
rating,
|
|
81
|
+
path,
|
|
82
|
+
...(id !== undefined ? { id } : {}),
|
|
83
|
+
}
|
|
84
|
+
}
|
package/README.md
DELETED