'use client' import { useEffect, useRef } from 'react' // .js extension: Node's ESM resolution (this plugin's tsconfig) can't find // 'next/navigation' without it. import { usePathname } from 'next/navigation.js' import { useConsentContext } from '../consent/ConsentContext.js' import { CONSENT_COOKIE, CONSENT_MAX_AGE, parseConsent } from '../consent/storage.js' /** Visitor id cookie — set ONLY with analytics consent, deleted on withdrawal (DEFAULT_COOKIE_MAP). */ export const VISITOR_COOKIE = 'ipal_vid' function readCookie(name: string): string | undefined { return document.cookie .split('; ') .find((c) => c.startsWith(`${name}=`)) ?.split('=')[1] } function ensureVisitorId(): string { const existing = readCookie(VISITOR_COOKIE) if (existing && /^[0-9a-f]{32}$/.test(existing)) {return existing} const bytes = new Uint8Array(16) globalThis.crypto.getRandomValues(bytes) const id = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('') const secure = location.protocol === 'https:' ? ';secure' : '' document.cookie = `${VISITOR_COOKIE}=${id};path=/;max-age=${CONSENT_MAX_AGE};samesite=lax${secure}` return id } export type PageStatsProps = { /** The hit endpoint. Default '/api/ipal/hit' (ipalKit({ stats: true })). */ endpoint?: string /** Current locale code, stored with the visit. */ locale?: string } /** * Built-in statistics: sends one beacon per page view to the hit endpoint. * * - **Everyone, no consent needed** — nothing is stored in the browser; the * server joins page views into a visit with a daily-salted hash it can't * reverse, and keeps no IP. * - **With analytics consent** (the same category that turns on GA4) — sets the * `ipal_vid` cookie with a random id, so the panel can show that visitor's * history across days. Withdrawing consent deletes the cookie. * * Renders nothing. Mount once in the locale layout, INSIDE . */ export function PageStats({ endpoint = '/api/ipal/hit', locale }: PageStatsProps) { const pathname = usePathname() const { texts } = useConsentContext() const firstHit = useRef(true) useEffect(() => { if (!pathname) {return} const body: Record = { p: pathname } // the external referrer belongs to the landing page only if (firstHit.current && document.referrer) {body.r = document.referrer} firstHit.current = false if (locale) {body.l = locale} // The cookie, not context state: on a full page load this effect runs before // useConsent has read the cookie, so state would still say "no consent". if (parseConsent(readCookie(CONSENT_COOKIE), texts.version)?.analytics) {body.v = ensureVisitorId()} const json = JSON.stringify(body) if (!navigator.sendBeacon?.(endpoint, new Blob([json], { type: 'application/json' }))) { void fetch(endpoint, { body: json, headers: { 'content-type': 'application/json' }, keepalive: true, method: 'POST' }).catch(() => {}) } // texts.version is read, not a trigger: a policy change isn't a page view // eslint-disable-next-line react-hooks/exhaustive-deps }, [pathname, endpoint, locale]) return null }