# Decisions — `@codefast/tracking`

## Charter

**Problem.** A TanStack Start app served as cached, shared (ISR/CDN) HTML still has to track its own events type-safely
and consent-first: no event and no identifier may leave the page before a lawful basis exists for the visitor's region,
yet the shared HTML cannot know the visitor's region.

**Goals.**

- A type-safe, schema-validated `track()` backed by an app-defined event catalog.
- Fan-out to several destinations without changing call sites.
- Consent first: no tracking and no identifier minting before a lawful basis exists for the visitor's region — including
  on cached pages that cannot be personalized.
- One consent configuration shared by every surface (UI, tracker gate, tag bootstrap), so cross-surface constants cannot
  drift.

**Non-goals.**

- A server-side tracker: no beacon relay or ingest endpoint, no consent-cookie mirror. A server-owned event goes through
  the stateless GA4 Measurement Protocol sender, gated by its caller.
- An offline queue, batching or unload beacon in front of the destinations
  ([destinations own their transport](#destinations-own-their-transport)).
- Segment-style `identify`, `group`, `alias` and `page` event kinds. Page views belong to the analytics tag's own page
  tracking.
- Tag managers such as GTM; the reference consumer loads the analytics tag directly.
- Self-hosted event storage, sampling and rate limiting.
- Becoming a consent management platform ([read a CMP](#read-a-cmp-rather-than-become-one)).

## Every exported API ships with a real call site

**Status:** Accepted

**Context.** Speculative features cost maintenance and widen the public surface without evidence that the shape is
right.

**Decision.** An exported API needs at least one real consumer call site before it ships. The integrator-facing
reference bindings — the Meta, TikTok and Microsoft UET destinations, the TCF/GPP reconciler, GA4 user deletion — ship
as public API covered by tests and conformance vectors, without an `apps/web` call site.

**Consequences.** The `context` envelope key is reserved, not populated, until a consumer needs attribution; `page` and
`identify` stay anticipated additive members of the envelope's `type` discriminant, not implementations.

## Initial consent resolves through a client round trip

**Status:** Accepted

**Context.** Cached HTML is shared across visitors, so anything baked into it at build or regeneration time is the same
for everyone; baking a US opt-out default would grant analytics to every visitor, EU included.

**Decision.** Shared HTML bakes the strictest initial consent. The region-correct default comes from a per-visitor
server function the client calls after load, whose response is `private, no-store`. A missing geo header fails closed to
the strictest default.

**Consequences.** Region-dependent UI waits on `isResolved`, and each session pays one round trip. A route loader is the
wrong tool here: it would bake one visitor-independent value into the cached HTML.

## Consent is per category, mirroring Google Consent Mode v2

**Status:** Accepted

**Context.** GDPR consent must be granular per purpose, and Google Consent Mode v2, which the GA4 destination speaks,
splits measurement from advertising.

**Decision.** A decision is exactly `{ ads, analytics }`, each an explicit boolean; `analytics` drives
`analytics_storage` and `ads` drives the three advertising signals.

**Consequences.** A single granted/denied flag is rejected as malformed. GPC, a "do not sell or share" signal, can deny
`ads` without touching first-party `analytics`. Programmatic advertising that needs per-purpose, per-vendor consent
reads it from a CMP and reduces it to these two categories.

## Destinations own their transport

**Status:** Accepted

**Context.** Every real destination (gtag.js, Vercel Analytics) already queues, batches and delivers on unload in the
page. A second queue in front only delays events, and one that replays after a withdrawal sends events the visitor
refused.

**Decision.** `track()` is fire-and-forget: the tracker gates, builds the envelope and hands it to each destination's
`send`, which owns delivery.

**Consequences.** No tracker-level queue, batching, sampling or retry. A failing destination is contained and reported
through `onDeliveryError`, never retried by the tracker.

## Event schemas are any Standard Schema

**Status:** Accepted

**Context.** Apps already ship a validation library, and the client bundle should not pay for a second one.

**Decision.** The catalog's schemas are typed against Standard Schema; `@standard-schema/spec` is the package's only
runtime dependency.

**Consequences.** Any conforming library (zod, `zod/mini`, valibot, …) works. Schemas that validate asynchronously are
rejected, because tracking sits on synchronous call paths.

## The anonymous id is minted by the client and persisted by the server

**Status:** Accepted

**Context.** Minting an identifier before consent defeats consent-first tracking, and browsers cap how long a
script-written cookie lives.

**Decision.** The client mints the id lazily, on the first event allowed to send. A server endpoint only re-issues the
id the client hands it, via `Set-Cookie`, and expires it on withdrawal.

**Consequences.** The server never generates an id, and its endpoint must reject anything that is not exactly a UUID,
because it echoes input into a response header.

## The cookieless exemption is gated per jurisdiction

**Status:** Accepted

**Context.** The audience-measurement exemption waives the consent banner only; GDPR still needs a legal basis for
server-side IP processing, regulators differ on whether a cookieless sink qualifies, and no EU-wide certification
exists.

**Decision.** An exempt destination is an explicit opt-in by the integrator, and the tracker's `isExemptionAllowed`
withholds even exempt sinks wherever exemption is not defensible.

**Consequences.** Exemption is wired to the visitor's region at runtime, never assumed global or fixed at build time.

## The Google tag loads under Advanced Consent Mode

**Status:** Accepted

**Context.** Consent Mode's cookieless pings and conversion modeling only work if the tag runs while storage is denied.

**Decision.** `GtagConsentBootstrap` issues the consent `default` from the stored decision (or the baked default), then
always loads gtag.js.

**Consequences.** The tag runs for every visitor, under denied storage until consent is granted.

## Limited Data Use substitutes for ads only under an opt-out regime

**Status:** Accepted

**Context.** Limited Data Use is a US "do not sell or share" mechanism; it is not consent. It reduces an ad-platform
delivery to restricted measurement processing.

**Decision.** An ad destination transmits on an `ads` grant, or — only where the integrator enables the substitution
because the resolved mode is opt-out — on an `analytics` grant with LDU applied.

**Consequences.** Under opt-in an ad platform without `ads` consent receives nothing. A visitor who denied both
categories sends nothing to ad platforms, because the delivery would serve no purpose they allowed.

## Read a CMP rather than become one

**Status:** Accepted

**Context.** Becoming a certified CMP means IAB Europe registration and per-environment validation, Google's own
certification, a standing compliance relationship with delisting risk, and owning the consent UI, Global Vendor List
ingestion, TC String encoding and audit liability. Sites serving programmatic ads already run a certified CMP.

**Decision.** The package reads an external CMP through the standard `__tcfapi` / `__gpp` APIs and reconciles it with
the native decision. It ships detection and the reconciler; the integrator derives the CMP signal, because the TCF
purpose set and the Google vendor id are ad-ops policy.

**Consequences.** The package never mints TC or GPP strings and never hard-codes purpose or vendor ids. Programmatic ads
in the EEA, UK and Switzerland need a certified CMP on the page.

## Keep the data-subject-rights surface minimal

**Status:** Accepted

**Context.** The system stores only the id cookie and the consent record; the data subjects ask about lives at the
destinations, and each platform ships its own deletion tooling or has none.

**Decision.** The system provides the consent gate, `clear()` with server expiry, a per-destination `onErasure` hook run
by `tracker.erase`, id exposure without minting, and a GA4 deletion request builder. Everything else is delegated to the
controller and the destinations.

**Consequences.** No request portal, subject-data store, rectification or portability path. Ad platforms without a
per-visitor deletion API get cookie-clear and stop-send, never a fabricated deletion call.

## A server receipt, not the client record, is the proof of consent

**Status:** Accepted

**Context.** The controller carries the burden of proving consent, and a client record in local storage can be cleared,
forged or diverge across devices.

**Decision.** The client record gates runtime behaviour only. An append-only server receipt, carrying a coarsened IP and
an optional integrity signature, is the record of proof. The package ships the receipt model, the store contract and the
recording helper; the backend, the signing key and the retention period are the deployment's.

**Consequences.** A full IP is never persisted and never accepted from the client. Fuller evidence and retention are a
[proposal](proposals/consent-receipt-evidence.md).

## License

Released under the [MIT License](./LICENSE).
