import { CONSENT_COOKIE, readConsentRecord } from './storage.js' /** * The stored consent decision as an external store (React `useSyncExternalStore`). * * Why a store and not state filled in an effect: with a store React hydrates with the server's value and switches to * the browser's own before the browser paints, so the banner and the button can be part of the server HTML with no * hydration mismatch and no frame of the wrong one. One decision per document: every on a page * reads the same value. */ export type ConsentRecord = NonNullable> const listeners = new Set<() => void>() /** The value last written in this document — still the decision when the browser refuses to keep the cookie. */ let written: string | undefined let cache: { key: string; record: ConsentRecord | null } | undefined /** Raw value of the consent cookie in this browser (first cookie of that name), undefined when there is none. */ export function readConsentCookie(): string | undefined { if (typeof document === 'undefined') {return undefined} return document.cookie .split('; ') .find((c) => c.startsWith(`${CONSENT_COOKIE}=`)) ?.split('=')[1] } /** The current decision under `version`, or null. The same object until the stored value changes. */ export function getConsentSnapshot(version: number): ConsentRecord | null { const raw = readConsentCookie() const key = `${version}\n${raw ?? ''}\n${written ?? ''}` if (cache?.key !== key) { cache = { key, record: readConsentRecord(raw, version) ?? readConsentRecord(written, version) } } return cache.record } export function subscribeConsent(listener: () => void): () => void { listeners.add(listener) return () => { listeners.delete(listener) } } /** Writes the cookie (`value` already serialized, `attributes` like `;path=/;max-age=…`) and tells every reader. */ export function writeConsentCookie(value: string, attributes: string): void { document.cookie = `${CONSENT_COOKIE}=${value}${attributes}` written = value for (const listener of listeners) {listener()} } /** Tests only: forget what this document wrote. */ export function resetConsentStore(): void { written = undefined cache = undefined }