apps/web/src/lib/cookie-consent/cookie-strategy.ts

1import type { StoredConsent } from './consent-state'
2
3/** Persisted in Sanity per region; drives defaults and effective script consent. */
4export type CookieStrategy = 'opt-in' | 'opt-out'
5
6export function parseCookieStrategy(
7	raw: string | undefined | null,
8): CookieStrategy {
9	return raw === 'opt-out' ? 'opt-out' : 'opt-in'
10}
11
12/** Toggles when there is no saved choice yet (managing preferences). */
13export function defaultNonEssentialToggles(strategy: CookieStrategy): {
14	functional: boolean
15	analytics: boolean
16	marketing: boolean
17} {
18	const on = strategy === 'opt-out'
19	return { functional: on, analytics: on, marketing: on }
20}
21
22/**
23 * Script activation: opt-in + no save → nothing non-essential. Opt-out + no save → all non-essential on (until user saves opt-out).
24 */
25export function getEffectiveConsentForScripts(
26	stored: StoredConsent | null,
27	strategy: CookieStrategy,
28): StoredConsent | null {
29	if (stored) {
30		return stored
31	}
32	if (strategy === 'opt-out') {
33		return {
34			v: 2,
35			functional: true,
36			analytics: true,
37			marketing: true,
38			// Not persisted — only used until the visitor saves an explicit choice.
39			decidedAt: 0,
40		}
41	}
42	return null
43}
44