@codefast/tracking 0.5.0-canary.5 → 1.0.0-canary.6

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.
Files changed (133) hide show
  1. package/CHANGELOG.md +165 -0
  2. package/README.md +122 -127
  3. package/dist/client/browser-cookie.d.mts +11 -0
  4. package/dist/client/browser-cookie.mjs +15 -0
  5. package/dist/client/consent-runtime.d.mts +56 -0
  6. package/dist/client/consent-runtime.mjs +35 -0
  7. package/dist/client/consent-storage.d.mts +5 -0
  8. package/dist/client/consent-storage.mjs +20 -1
  9. package/dist/client/consent-withdrawal.d.mts +21 -0
  10. package/dist/client/consent-withdrawal.mjs +17 -0
  11. package/dist/client/cookie-anonymous-id.d.mts +37 -0
  12. package/dist/client/cookie-anonymous-id.mjs +46 -0
  13. package/dist/client/create-client-tracker.d.mts +11 -16
  14. package/dist/client/create-client-tracker.mjs +27 -53
  15. package/dist/client/gpc.d.mts +2 -0
  16. package/dist/client/gpc.mjs +3 -1
  17. package/dist/client/index.d.mts +7 -5
  18. package/dist/client/index.mjs +8 -6
  19. package/dist/client/initial-consent-store.d.mts +66 -0
  20. package/dist/client/initial-consent-store.mjs +119 -0
  21. package/dist/client/is-analytics-allowed.d.mts +29 -0
  22. package/dist/client/is-analytics-allowed.mjs +23 -0
  23. package/dist/client/server-persisted-anonymous-id.d.mts +33 -0
  24. package/dist/client/server-persisted-anonymous-id.mjs +50 -0
  25. package/dist/core/consent-config.d.mts +27 -0
  26. package/dist/core/consent-config.mjs +11 -0
  27. package/dist/core/consent.d.mts +99 -4
  28. package/dist/core/consent.mjs +99 -4
  29. package/dist/core/cookie.d.mts +17 -0
  30. package/dist/core/cookie.mjs +23 -0
  31. package/dist/core/destination.d.mts +10 -8
  32. package/dist/core/event-catalog.d.mts +16 -13
  33. package/dist/core/event-catalog.mjs +19 -1
  34. package/dist/core/event-id.d.mts +1 -2
  35. package/dist/core/event-id.mjs +1 -2
  36. package/dist/core/index.d.mts +6 -4
  37. package/dist/core/index.mjs +5 -3
  38. package/dist/core/tracked-event.d.mts +21 -8
  39. package/dist/destinations/google-analytics.d.mts +100 -48
  40. package/dist/destinations/google-analytics.mjs +89 -85
  41. package/dist/destinations/google-consent.d.mts +64 -0
  42. package/dist/destinations/google-consent.mjs +102 -0
  43. package/dist/destinations/index.d.mts +2 -5
  44. package/dist/destinations/index.mjs +2 -5
  45. package/dist/destinations/shared.d.mts +20 -0
  46. package/dist/destinations/shared.mjs +13 -0
  47. package/dist/destinations/vercel-analytics.d.mts +19 -4
  48. package/dist/destinations/vercel-analytics.mjs +11 -18
  49. package/dist/import-protection.d.mts +19 -0
  50. package/dist/import-protection.mjs +23 -0
  51. package/dist/index.d.mts +6 -4
  52. package/dist/index.mjs +5 -3
  53. package/dist/react/consent-banner.d.mts +24 -7
  54. package/dist/react/consent-banner.mjs +16 -11
  55. package/dist/react/gtag-consent-bootstrap.d.mts +27 -0
  56. package/dist/react/gtag-consent-bootstrap.mjs +29 -0
  57. package/dist/react/index.d.mts +4 -1
  58. package/dist/react/index.mjs +4 -1
  59. package/dist/react/use-consent.d.mts +9 -13
  60. package/dist/react/use-consent.mjs +42 -25
  61. package/dist/react/use-google-consent-sync.d.mts +23 -0
  62. package/dist/react/use-google-consent-sync.mjs +24 -0
  63. package/dist/react/use-initial-consent.d.mts +14 -0
  64. package/dist/react/use-initial-consent.mjs +19 -0
  65. package/dist/server/anonymous-id-cookie.d.mts +46 -0
  66. package/dist/server/anonymous-id-cookie.mjs +51 -0
  67. package/dist/server/index.d.mts +5 -3
  68. package/dist/server/index.mjs +4 -3
  69. package/dist/server/initial-consent.d.mts +29 -0
  70. package/dist/server/initial-consent.mjs +31 -0
  71. package/dist/server/region.d.mts +21 -4
  72. package/dist/server/region.mjs +26 -5
  73. package/dist/tanstack-start/index.d.mts +58 -0
  74. package/dist/tanstack-start/index.mjs +45 -0
  75. package/package.json +26 -110
  76. package/src/client/browser-cookie.ts +16 -0
  77. package/src/client/consent-runtime.ts +80 -0
  78. package/src/client/consent-storage.ts +31 -1
  79. package/src/client/consent-withdrawal.ts +32 -0
  80. package/src/client/cookie-anonymous-id.ts +93 -0
  81. package/src/client/create-client-tracker.ts +56 -85
  82. package/src/client/gpc.ts +4 -2
  83. package/src/client/index.ts +19 -8
  84. package/src/client/initial-consent-store.ts +218 -0
  85. package/src/client/is-analytics-allowed.ts +43 -0
  86. package/src/client/server-persisted-anonymous-id.ts +99 -0
  87. package/src/core/consent-config.ts +27 -0
  88. package/src/core/consent.ts +164 -10
  89. package/src/core/cookie.ts +29 -0
  90. package/src/core/destination.ts +10 -8
  91. package/src/core/event-catalog.ts +28 -15
  92. package/src/core/event-id.ts +1 -2
  93. package/src/core/index.ts +19 -3
  94. package/src/core/tracked-event.ts +22 -7
  95. package/src/destinations/google-analytics.ts +196 -133
  96. package/src/destinations/google-consent.ts +164 -0
  97. package/src/destinations/index.ts +14 -15
  98. package/src/destinations/shared.ts +45 -0
  99. package/src/destinations/vercel-analytics.ts +23 -24
  100. package/src/import-protection.ts +20 -0
  101. package/src/index.ts +46 -8
  102. package/src/react/consent-banner.tsx +40 -14
  103. package/src/react/gtag-consent-bootstrap.tsx +48 -0
  104. package/src/react/index.ts +8 -0
  105. package/src/react/use-consent.ts +53 -45
  106. package/src/react/use-google-consent-sync.ts +38 -0
  107. package/src/react/use-initial-consent.ts +22 -0
  108. package/src/server/anonymous-id-cookie.ts +76 -0
  109. package/src/server/index.ts +15 -3
  110. package/src/server/initial-consent.ts +48 -0
  111. package/src/server/region.ts +22 -5
  112. package/src/tanstack-start/index.ts +83 -0
  113. package/dist/client/lifecycle.d.mts +0 -23
  114. package/dist/client/lifecycle.mjs +0 -30
  115. package/dist/client/local-storage.d.mts +0 -13
  116. package/dist/client/local-storage.mjs +0 -31
  117. package/dist/client/queue.d.mts +0 -49
  118. package/dist/client/queue.mjs +0 -71
  119. package/dist/client/router.d.mts +0 -30
  120. package/dist/client/router.mjs +0 -17
  121. package/dist/destinations/ga4-measurement-protocol.d.mts +0 -54
  122. package/dist/destinations/ga4-measurement-protocol.mjs +0 -89
  123. package/dist/destinations/http-destination.d.mts +0 -20
  124. package/dist/destinations/http-destination.mjs +0 -25
  125. package/dist/server/create-server-tracker.d.mts +0 -42
  126. package/dist/server/create-server-tracker.mjs +0 -67
  127. package/src/client/lifecycle.ts +0 -50
  128. package/src/client/local-storage.ts +0 -44
  129. package/src/client/queue.ts +0 -117
  130. package/src/client/router.ts +0 -37
  131. package/src/destinations/ga4-measurement-protocol.ts +0 -166
  132. package/src/destinations/http-destination.ts +0 -33
  133. package/src/server/create-server-tracker.ts +0 -128
package/CHANGELOG.md CHANGED
@@ -1,5 +1,170 @@
1
1
  # @codefast/tracking
2
2
 
3
+ ## 1.0.0-canary.6
4
+
5
+ ### Major Changes
6
+
7
+ - [#565](https://github.com/codefastlabs/codefast/pull/565) [`1e80096`](https://github.com/codefastlabs/codefast/commit/1e800961f956fdc5f23c434c1bf6f9bedb6f187b) Thanks [@thevuong](https://github.com/thevuong)! - Remove `defaultConsentExpression` from gtag/GTM consent bootstraps. Pass a literal `defaultConsent` (strictest bake on shared HTML) and upgrade after hydration via the server-fn lane + `updateGoogleConsent`.
8
+
9
+ - [#567](https://github.com/codefastlabs/codefast/pull/567) [`74c52ac`](https://github.com/codefastlabs/codefast/commit/74c52acf675225cfa50c73403644ff983166c82d) Thanks [@thevuong](https://github.com/thevuong)! - Collapse the consent "must match" contracts into one `ConsentConfig`, and add `createConsentRuntime`.
10
+
11
+ Previously `storageKey`, `policyVersion`, and `requestedCategories` had to be hand-threaded — matching exactly — through `useConsent`, `createIsAnalyticsAllowed`, and the gtag consent bootstrap; one drifted string was a silent consent bug. Now:
12
+
13
+ - **`ConsentConfig` + `defineConsentConfig` (root/core)** — the one bag for `storageKey`, `policyVersion`, and `requestedCategories`. Isomorphic plain data: the same object is imported on both sides.
14
+ - **`createConsentRuntime` (client)** — derives the live client instances from the config: the shared `ConsentStorage`, the initial-consent store over your server lane, `ensureInitialConsentResolved`, and the `isAnalyticsAllowed` tracker gate wired to the store's resolved mode (GPC read from the real navigator signal by default).
15
+
16
+ **Breaking option changes (config-first):**
17
+
18
+ - `useConsent({ policyVersion, requestedCategories?, ... })` → `useConsent({ config, ... })`. The `["analytics"]` default for `requestedCategories` is gone — the config always states the requested purposes explicitly.
19
+ - `createIsAnalyticsAllowed({ policyVersion, requestedCategories, ... })` → `createIsAnalyticsAllowed({ config, ... })`.
20
+ - `GtagConsentBootstrapOptions` (and the `<GtagConsentBootstrap />` props): `consentStorageKey` + `policyVersion` → `config`.
21
+
22
+ - [#567](https://github.com/codefastlabs/codefast/pull/567) [`74c52ac`](https://github.com/codefastlabs/codefast/commit/74c52acf675225cfa50c73403644ff983166c82d) Thanks [@thevuong](https://github.com/thevuong)! - Cut every lane that shipped with zero consumer call sites — the package now covers exactly a consented gtag + Vercel Analytics setup on TanStack Start, and nothing speculative. Removed (recoverable from git history when a real need returns):
23
+
24
+ - **Server-side tracking**: `createServerTracker`, the beacon relay/ingest lane (`relayTrackedEvents`, `createTrackedEventIngestHandler`), `deriveEventId`, the consent-cookie mirror (`withConsentCookieMirror`, codec, `readConsentDecisionCookie`/`readConsentDecisionRequestCookie`), `ConsentConfig.decisionCookieName`, and the GA4 Measurement Protocol destination (its subpath included).
25
+ - **Offline queue machinery**: `EventQueue`, `createLocalStorageQueueStorage`, `attachClientLifecycle`, `flushWithBeacon`, `createHttpDestination`, `Destination.delivery`/`sendBatch` — every real destination (gtag.js, Vercel) owns its own in-page queue and unload delivery.
26
+ - **Segment-style event kinds**: `identify`/`group`/`alias`/`page` on the tracker and the envelope union, `EventDefinition.owner` + `EventsOf` (with no server side there is nothing to split), `attachRouterPageTracking` — page views belong to gtag `config` + Enhanced Measurement and Vercel's native `<Analytics />`.
27
+ - **GTM**: destination, bootstrap, loader.
28
+ - **Unused gtag helpers**: `setGoogleConsentDefault`, `setGoogleAdsDataRedaction`, `setGoogleUrlPassthrough`, `extractGa4ClientId`/`extractGa4SessionId`.
29
+
30
+ Follow-on API changes: `ClientTracker` is now `track()` only (`clear()` had nothing left to clear, so `ConsentWithdrawalHandlerOptions.clearTracker` is gone too); catalogs drop the `owner` tag (`{ schema }` only); `TrackedEvent` is the `track` envelope alone, still discriminated on `type` so a future kind is additive.
31
+
32
+ - [#567](https://github.com/codefastlabs/codefast/pull/567) [`74c52ac`](https://github.com/codefastlabs/codefast/commit/74c52acf675225cfa50c73403644ff983166c82d) Thanks [@thevuong](https://github.com/thevuong)! - Collapse the export map to group entries — per-file subpaths froze the internal file layout into public API.
33
+
34
+ **Breaking:** deep subpaths (`./client/*`, `./core/*`, `./server/*`, `./react/*`, and per-file `./destinations/*`) no longer resolve. Import from the group entry instead:
35
+
36
+ - `@codefast/tracking/core` and `@codefast/tracking/core/*` → `@codefast/tracking` (the root has always re-exported the whole isomorphic core surface).
37
+ - `@codefast/tracking/client/*` → `@codefast/tracking/client`; same pattern for `server` and `react`.
38
+ - Google helpers → `@codefast/tracking/destinations`.
39
+
40
+ One destination keeps a dedicated subpath on purpose: `@codefast/tracking/destinations/vercel-analytics` — its top-level `@vercel/analytics` import would make the optional peer mandatory for every barrel consumer.
41
+
42
+ All entries are unbundled ESM with `sideEffects: false`, so group imports tree-shake per file — the trim changes what is addressable, not what ships.
43
+
44
+ - [#565](https://github.com/codefastlabs/codefast/pull/565) [`1e80096`](https://github.com/codefastlabs/codefast/commit/1e800961f956fdc5f23c434c1bf6f9bedb6f187b) Thanks [@thevuong](https://github.com/thevuong)! - Remove the deprecated edge-middleware cookie bootstrap path:
45
+
46
+ - Drop `buildInitialConsentBootstrapScript` and the `@codefast/tracking/destinations/initial-consent-bootstrap` subpath.
47
+ - Resolve region consent via a server function (`resolveInitialConsent`) plus a client snapshot instead — see `apps/ui` `visitor-consent.ts` / `resolve-visitor-consent.ts`.
48
+
49
+ - [#565](https://github.com/codefastlabs/codefast/pull/565) [`1e80096`](https://github.com/codefastlabs/codefast/commit/1e800961f956fdc5f23c434c1bf6f9bedb6f187b) Thanks [@thevuong](https://github.com/thevuong)! - Rename public APIs to follow Swift API Design Guidelines (name by role; nouns for properties; imperative verbs for builders; assertion-form booleans).
50
+
51
+ **Breaking:**
52
+
53
+ - Envelope field: `TrackEvent.props` / `PageViewEvent.props` → `properties` (and the `track`/`page` method parameters). Segment-style name; `Props` is reserved for React components.
54
+ - Analytics gate: `isTrackingAllowed` → `isAnalyticsAllowed` on `ClientTrackerOptions` and `UseConsentResult` (the gate reads the `analytics` category only). `createIsTrackingAllowed` → `createIsAnalyticsAllowed`; subpath `./client/is-tracking-allowed` → `./client/is-analytics-allowed`.
55
+ - Options naming (drop `Create*` / `Build*` filler): `CreateIsAnalyticsAllowedOptions` → `IsAnalyticsAllowedOptions`; `CreateConsentWithdrawalHandlerOptions` → `ConsentWithdrawalHandlerOptions`; `BuildInitialConsentOptions` → `InitialConsentOptions`; `BuildAnonymousIdSetCookieOptions` → `AnonymousIdSetCookieOptions`. `ClientLifecycleOptions` stays (product-named, no verb prefix).
56
+ - Prompt scope option: `categories` → `requestedCategories` on `UseConsentOptions`, `IsAnalyticsAllowedOptions`, and `InitialConsentOptions`.
57
+ - `Destination.consent` / `VercelAnalyticsDestinationOptions.consent` → `consentRequirement` (`"exempt" | "required"`).
58
+ - `googleConsentBootstrapPreamble` → `buildGoogleConsentBootstrapPreamble`; `dataLayerOf` → `ensureDataLayer`.
59
+ - `UseConsentResult.save` → `saveDecision`.
60
+ - Demote package-private deep exports: remove `./client/queue`, `./destinations/shared`, and `./destinations/google-consent` from `package.json#exports`. `EventQueue` / `EventQueueOptions` leave the `./client` barrel; `EventQueueStorage` stays (custom offline persistence). Consent Mode helpers remain on `./destinations` / `./react`.
61
+ - Options-object for multi-arg consent resolvers (clarity at the call site): `resolveDefaultConsent(mode, requestedCategories, hasGlobalPrivacyControlSignal)` → `resolveDefaultConsent(options)` and `resolveEffectiveConsent(storage, policyVersion, requestedCategories, mode, hasGlobalPrivacyControlSignal)` → `resolveEffectiveConsent(options)`; new `ResolveDefaultConsentOptions` / `ResolveEffectiveConsentOptions` types. `readStoredDecision(storage, policyVersion)` keeps its positional args.
62
+ - GA4 Measurement Protocol debug flag: `Ga4MeasurementProtocolDestinationOptions.debug` → `debugMode` (matches `debugMode` on the gtag options).
63
+ - Server `group` signature: `ServerTracker.group(groupId, traits, context)` → `group(groupId, context, traits?)` so `traits` is truly optional instead of a forced `undefined`.
64
+ - Remove `assertNever` from the public exports (generic, non-tracking helper; internal-only now).
65
+ - `readCookieValue` is now also exported from the root entry (previously only on `./core`).
66
+
67
+ ### Minor Changes
68
+
69
+ - [#563](https://github.com/codefastlabs/codefast/pull/563) [`bad015c`](https://github.com/codefastlabs/codefast/commit/bad015c8237182b24ef24304ddcd0f939f917c1e) Thanks [@thevuong](https://github.com/thevuong)! - Switch gtag/GTM bootstraps to Google Consent Mode **advanced**:
70
+
71
+ - `buildGtagConsentBootstrapScript` / `buildGtmConsentBootstrapScript` always set Consent Mode v2 `default` (from stored decision or region fallback), then **always** load gtag.js / gtm.js — even when analytics/ads storage is denied — so cookieless pings and consent modeling can run.
72
+ - Runtime grants/denies still use `updateGoogleConsent`; `loadGtagScript` / `loadGtmScript` remain idempotent safety nets when the bootstrap did not run.
73
+ - The package's first-party consent gate is unchanged — identifiers and non-exempt destinations stay blocked without consent; only Google tag _script loading_ changes.
74
+
75
+ - [#563](https://github.com/codefastlabs/codefast/pull/563) [`bad015c`](https://github.com/codefastlabs/codefast/commit/bad015c8237182b24ef24304ddcd0f939f917c1e) Thanks [@thevuong](https://github.com/thevuong)! - Tighten the package's API contracts and framework independence, found in an architecture audit.
76
+
77
+ **Breaking:**
78
+
79
+ - `ClientTrackerOptions.anonymousId` is now `() => string` only — the plain-`string` form is removed. A resolver was already the documented best practice (defers minting an id until an event is actually allowed to send); the string form let callers accidentally mint one as an import-time side effect. Wrap a stable value in a resolver: `anonymousId: () => myId`.
80
+ - `Destination.send` now always returns `Promise<void>` — the previous `Promise<void> | void` let sync and async destinations disagree on contract. Mark a synchronous `send` `async` so a thrown error rejects the returned promise instead of throwing synchronously.
81
+
82
+ **Also:**
83
+
84
+ - `createVercelAnalyticsDestination` now imports `track` from the framework-agnostic `@vercel/analytics` instead of `@vercel/analytics/react` — the destination renders nothing, so it had no reason to depend on React.
85
+ - Adds `assertNever` (`@codefast/tracking/core`) and wires it into the `default` case of every `switch (event.type)` across the GA4/Vercel destinations — extending `TrackedEvent` with a new variant now fails to compile at every switch instead of silently falling through.
86
+ - The package root (`@codefast/tracking`) now re-exports `#/core`'s surface by explicit name instead of `export *`, matching the `client`/`server`/`destinations`/`react` subpaths, which were already explicit.
87
+ - `useConsent`'s returned object and its `save`/`denyAll`/`grantAll` callbacks are now memoized (`useMemo`/`useCallback`), so a consumer passing the hook's result down as a prop or effect dependency doesn't get a new reference every render.
88
+
89
+ - [#563](https://github.com/codefastlabs/codefast/pull/563) [`bad015c`](https://github.com/codefastlabs/codefast/commit/bad015c8237182b24ef24304ddcd0f939f917c1e) Thanks [@thevuong](https://github.com/thevuong)! - Gate the client tracker on consent and keep destinations from leaking pre-consent or duplicate data.
90
+
91
+ `createClientTracker` gains `isTrackingAllowed?: () => boolean`, consulted per event — while it returns `false` nothing is sent or queued, so a mid-session consent change applies immediately. `anonymousId` also accepts a `() => string` resolver, invoked only when an event is actually allowed to send, so apps can defer minting an identifier cookie until consent exists. `storage` is now optional; without it the queue lives in memory only instead of persisting to `localStorage`. The Vercel destination takes an options object (`{ name?, trackPageViews? }` replaces the positional name), drops `$page_viewed` unless `trackPageViews` is on — the mounted `<Analytics />` component already tracks page views natively — and drops `$identify`/`$group`, which Vercel Analytics has no identity API to translate to. The global `gtag` type gains the `config` and `js` command signatures so apps can queue them directly, e.g. when loading gtag.js on demand for basic Consent Mode.
92
+
93
+ - [#563](https://github.com/codefastlabs/codefast/pull/563) [`bad015c`](https://github.com/codefastlabs/codefast/commit/bad015c8237182b24ef24304ddcd0f939f917c1e) Thanks [@thevuong](https://github.com/thevuong)! - Consent internals cleanup. The gtag and GTM bootstraps now share one preamble builder (`googleConsentBootstrapPreamble` — generated output unchanged), `toGoogleConsentParams` derives from the signal map instead of hand-writing it, the runtime consent setters (`updateGoogleConsent`, `setGoogleConsentDefault`, `setGoogleAdsDataRedaction`, `setGoogleUrlPassthrough`) accept a `dataLayerName`, `VercelAnalyticsDestinationOptions` is exported from the destinations barrel, and the cookie-string parser is shared as `readCookieValue` (`@codefast/tracking/core/cookie`). Removed never-consumed exports: `GOOGLE_CONSENT_SIGNAL_CATEGORIES`, `GoogleConsentSignal`, `isGa4EventName`, `consentDecisionShapeCheckExpression`, `consentSignalAssignmentsExpression`.
94
+
95
+ - [#565](https://github.com/codefastlabs/codefast/pull/565) [`1e80096`](https://github.com/codefastlabs/codefast/commit/1e800961f956fdc5f23c434c1bf6f9bedb6f187b) Thanks [@thevuong](https://github.com/thevuong)! - `resolveInitialConsent` (née `buildInitialConsent`) now fails closed for a missing country code: an unknown visitor (prerender crawl, host without a geo header) resolves to the strictest opt-in default instead of `"other"`'s analytics-granted opt-out. A known non-EU country still resolves to opt-out — unknown is not known-elsewhere. Behavior change only for callers that passed `countryCode: undefined` and relied on the opt-out fallback; callers that guarded the missing case themselves can drop the guard.
96
+
97
+ - [#563](https://github.com/codefastlabs/codefast/pull/563) [`bad015c`](https://github.com/codefastlabs/codefast/commit/bad015c8237182b24ef24304ddcd0f939f917c1e) Thanks [@thevuong](https://github.com/thevuong)! - Improve gtag/GTM loader DX without changing consent-first loading:
98
+
99
+ - `ensureGtag` / `loadGtagScript` / `buildGtagConsentBootstrapScript` accept optional `dataLayerName`, `nonce` (CSP), and `debugMode`.
100
+ - Add `createGoogleTagManagerDestination`, `buildGtmConsentBootstrapScript`, and `loadGtmScript` for consent-gated GTM.
101
+ - Add `<GtagConsentBootstrap />` — a framework-agnostic inline script wrapper for the pre-hydration bootstrap.
102
+
103
+ - [#563](https://github.com/codefastlabs/codefast/pull/563) [`bad015c`](https://github.com/codefastlabs/codefast/commit/bad015c8237182b24ef24304ddcd0f939f917c1e) Thanks [@thevuong](https://github.com/thevuong)! - Rename the `http-destination` module to `http`, matching the `create<X>Destination` file-naming convention used by every other destination. Breaking for deep imports only: `@codefast/tracking/destinations/http-destination` is now `@codefast/tracking/destinations/http`; imports from the `@codefast/tracking/destinations` barrel are unaffected.
104
+
105
+ - [#563](https://github.com/codefastlabs/codefast/pull/563) [`bad015c`](https://github.com/codefastlabs/codefast/commit/bad015c8237182b24ef24304ddcd0f939f917c1e) Thanks [@thevuong](https://github.com/thevuong)! - Add three helpers that pull common consent/tracking wiring out of consumer apps and into the package:
106
+
107
+ - `resolveEffectiveConsent(storage, policyVersion, categories, mode, hasGpc)` and `readStoredDecision(storage, policyVersion)` (`@codefast/tracking/core`) — the same "stored decision, else region default" rule `useConsent` applies internally, now exposed so a non-React gate (e.g. a tracker's `isTrackingAllowed` option) doesn't have to reimplement it by hand.
108
+ - `buildGtagConsentBootstrapScript(options)` (`@codefast/tracking/destinations`) — generates the pre-hydration `<script>` source that applies Google Consent Mode v2's default signal from the stored decision (or a supplied fallback) and conditionally loads gtag.js, replacing a hand-written JS string per app.
109
+ - `createCookieAnonymousId(options)` (`@codefast/tracking/client`) — an opt-in `document.cookie`-backed anonymous id `getOrCreate`/`clear` pair for apps that don't need a custom identity strategy.
110
+
111
+ None of these change existing exports' behavior; `useConsent` is refactored internally to use `readStoredDecision` but its output is unchanged.
112
+
113
+ - [#563](https://github.com/codefastlabs/codefast/pull/563) [`bad015c`](https://github.com/codefastlabs/codefast/commit/bad015c8237182b24ef24304ddcd0f939f917c1e) Thanks [@thevuong](https://github.com/thevuong)! - Rename `UseConsentResult.needsPrompt` to `isPromptNeeded` — a boolean should read as an assertion, matching `isTrackingAllowed` on the same result (Swift API Design Guidelines pass).
114
+
115
+ **Breaking:** consumers of `useConsent`/`ConsentBanner` reading `needsPrompt` must switch to `isPromptNeeded`.
116
+
117
+ - [#563](https://github.com/codefastlabs/codefast/pull/563) [`bad015c`](https://github.com/codefastlabs/codefast/commit/bad015c8237182b24ef24304ddcd0f939f917c1e) Thanks [@thevuong](https://github.com/thevuong)! - Add `deriveEventId(requestId, discriminant)` (`@codefast/tracking/core`) and wire it into `createServerTracker`: pass `requestId` on `ServerTrackerContext` to make a server-owned event's `eventId` deterministic instead of random. Retrying the same request with the same `track`/`group`/`alias` call now reproduces the same `eventId`, so a destination that dedupes on it treats the retry as a no-op instead of double-counting — closing the gap between the package's documented idempotency intent and its previous always-random default. Omitting `requestId` keeps the existing random behavior, so this is additive and non-breaking.
118
+
119
+ - [#566](https://github.com/codefastlabs/codefast/pull/566) [`ffd777c`](https://github.com/codefastlabs/codefast/commit/ffd777c13a66a377bee287fbb9cd692056b6a6cc) Thanks [@thevuong](https://github.com/thevuong)! - Modernize the package around server-first React frameworks and shrink what the client pays for.
120
+
121
+ Breaking (pre-release):
122
+
123
+ - Event catalogs now accept any Standard Schema library (zod, `zod/mini`, valibot) — `EventDefinition` is typed on `StandardSchemaV1`, validation runs through the new `assertValidEventProperties`, and `zod` is no longer a dependency (`@standard-schema/spec` is the only one).
124
+ - `buildInitialConsent` → `resolveInitialConsent`; `ServerTrackContext` → `ServerTrackerContext`.
125
+ - `attachClientLifecycle` drops `flushIntervalMs` — the queue schedules its own flushes (one-shot idle timer armed only while events are pending, offline-aware); the lifecycle keeps hide/pagehide delivery (beacon, or a keepalive `fetch` fallback) and flush-on-reconnect.
126
+ - The `./destinations` barrel is browser-lane only: import `createVercelAnalyticsDestination` from `./destinations/vercel-analytics` (its top-level `@vercel/analytics` import made the optional peer mandatory for barrel consumers) and `createGa4MeasurementProtocolDestination` from its own subpath.
127
+ - `./server`, `./server/*`, `./tanstack-start`, and `./destinations/ga4-measurement-protocol` are server-only by contract: on TanStack Start, deny them in the client environment via `importProtection.client.specifiers` (README shows the config) so a leak fails the build with a traced violation instead of silently shipping server code or the GA4 `apiSecret`.
128
+
129
+ New:
130
+
131
+ - `@codefast/tracking/tanstack-start` (optional peer on `@tanstack/react-start`): `resolveInitialConsentFromRequest`, `setAnonymousIdResponseCookie`/`clearAnonymousIdResponseCookie`, `readAnonymousIdRequestCookie`, `readConsentDecisionRequestCookie`, `resolveServerTrackerContextFromRequest` — consumers' server functions become one-liners.
132
+ - `createInitialConsentStore` (client) + `useInitialConsent` (react): the whole post-hydration region-resolution lane — strictest-until-resolved, single-flight, per-session cache validated by the new `isInitialConsent` guard, fail-closed-but-retryable errors, retry on tab-visible.
133
+ - `createServerTracker`: `waitUntil` hands delivery (and its retry ladder) to the platform's post-response scheduler; `withContext` binds per-request identity once.
134
+ - Beacon receive half: `relayTrackedEvents` + `createTrackedEventIngestHandler` (`Request → Response`) validate client envelopes, re-stamp server-read identity, and keep client `eventId`s so re-sent beacons dedupe.
135
+ - Consent-aware server tracking: consent-cookie codec (core), `withConsentCookieMirror` (client), `readConsentRecordCookie`/`readConsentDecisionCookie` (server).
136
+ - Transport hardening: `requestTimeoutMs` (default 10s) on the fetch destinations, `keepalive` threading for unload flushes, `Destination.sendBatch` (implemented by `createHttpDestination` — one POST per queue flush).
137
+ - `CookieAnonymousId.refresh()` prolongs an existing id without ever minting; `STRICTEST_INITIAL_CONSENT`, `CONSENT_REGIONS`, `isConsentRegion` are exported from core; the localStorage consent storage caches parsed records behind a raw-string compare; client-only react modules ship `"use client"`.
138
+
139
+ - [#563](https://github.com/codefastlabs/codefast/pull/563) [`bad015c`](https://github.com/codefastlabs/codefast/commit/bad015c8237182b24ef24304ddcd0f939f917c1e) Thanks [@thevuong](https://github.com/thevuong)! - Add server-persisted anonymous id ("client mints, server persists"). `createServerPersistedAnonymousId` (client) keeps the lazy, post-consent minting of `createCookieAnonymousId` and delegates the durable cookie write to an app-supplied server round-trip, so the id outlives Safari ITP's 7-day cap on script-written cookies. The server half — `readAnonymousIdCookie`, `buildAnonymousIdSetCookie`, `buildClearAnonymousIdSetCookie`, `isValidAnonymousId` — is framework-agnostic string-in/string-out: always `Secure; SameSite=Lax`, validates the cookie name, and throws on any non-UUID id so a public persist endpoint can never echo attacker input into a response header. The server persists and prolongs an id the client hands it; it never mints one per request.
140
+
141
+ - [#563](https://github.com/codefastlabs/codefast/pull/563) [`bad015c`](https://github.com/codefastlabs/codefast/commit/bad015c8237182b24ef24304ddcd0f939f917c1e) Thanks [@thevuong](https://github.com/thevuong)! - Add a TanStack Start wiring kit so consumer apps no longer hand-roll consent/bootstrap glue:
142
+
143
+ - `resolveInitialConsent` (née `buildInitialConsent`) + exported `EU_COUNTRY_CODES` / `OPT_IN_EQUIVALENT_COUNTRY_CODES` (`@codefast/tracking/server`) — region → mode → default decision for server functions (or a fail-closed bake when country is unknown).
144
+ - `clearGoogleAnalyticsCookies` (`@codefast/tracking/destinations`) — expire `_ga` / `_ga_*` on consent withdrawal.
145
+ - `createIsTrackingAllowed` / `createConsentWithdrawalHandler` (`@codefast/tracking/client`) — tracker gate + revoke clears.
146
+ - `useGoogleConsentSync` (`@codefast/tracking/react`) — Consent Mode `update` + optional gtag load, including cross-tab / privacy-page decisions.
147
+
148
+ `InitialConsent` is exported from `@codefast/tracking` / `@codefast/tracking/core`. None of these change existing export behavior.
149
+
150
+ - [#563](https://github.com/codefastlabs/codefast/pull/563) [`bad015c`](https://github.com/codefastlabs/codefast/commit/bad015c8237182b24ef24304ddcd0f939f917c1e) Thanks [@thevuong](https://github.com/thevuong)! - Discriminate event envelopes by `type` and add a consent-exempt destination lane.
151
+
152
+ `TrackedEvent` is now a union discriminated on `type: "track" | "page" | "identify" | "group" | "alias"` (Segment-style) instead of encoding built-ins into `$`-prefixed magic names — destinations translate each kind into their own vocabulary via an exhaustive `switch` (`identify` carries `traits`, `group` carries `groupId`/`traits`, `alias` carries `previousId`), and the app-chosen `name` only exists on `track`/`page`. This changes the wire format seen by HTTP destinations and the queue storage; stale queue records without a `type` are dropped silently. `Destination` gains `consent?: "exempt" | "required"` — while the tracker's consent gate is closed, exempt immediate destinations keep receiving `track`/`page` events stripped of `anonymousId`/`userId` (identity kinds and queueing stay fully gated), so cookieless sinks like Vercel Analytics can keep counting interactions without consent-gated identifiers. The Vercel destination accepts the flag via its options and still defaults to `"required"`.
153
+
154
+ ### Patch Changes
155
+
156
+ - [#565](https://github.com/codefastlabs/codefast/pull/565) [`1e80096`](https://github.com/codefastlabs/codefast/commit/1e800961f956fdc5f23c434c1bf6f9bedb6f187b) Thanks [@thevuong](https://github.com/thevuong)! - Prefer the live anonymous-id cookie over the in-memory cache so a cross-tab consent withdrawal cannot revive the pre-withdrawal identity on re-grant.
157
+
158
+ - [#563](https://github.com/codefastlabs/codefast/pull/563) [`bad015c`](https://github.com/codefastlabs/codefast/commit/bad015c8237182b24ef24304ddcd0f939f917c1e) Thanks [@thevuong](https://github.com/thevuong)! - Fix bugs found in review of the consent-gated tracking pipeline, and dedupe the GA4/Vercel destinations.
159
+
160
+ `createClientTracker`'s `identify()` no longer commits `userId` to the tracker's closure while consent is denied — a denied `identify` could otherwise leak its `userId` onto a later, allowed `track`/`page`/`group` call. `createServerTracker`'s per-request `eventId` derivation now factors in `userId`, so two `alias()` calls with the same `previousId` but different merge targets in one request no longer collide on `eventId`. `createLocalStorageQueueStorage.load()` now drops pre-migration/malformed queue records via a new `isTrackedEvent` guard (exported from `@codefast/tracking/core`), instead of relying on each destination's `switch` to silently no-op on an unrecognized shape.
161
+
162
+ Also: the GA4 (`gtag`/Measurement Protocol) and Vercel Analytics destinations now share one prop-flattening helper and one `group`→`join_group` mapping (`@codefast/tracking/destinations`'s internal `shared.ts`) instead of three near-duplicate implementations; `buildGtagConsentBootstrapScript`'s pre-hydration Consent Mode signal mapping is generated from the same table `toGoogleConsentParams` uses instead of a hand-duplicated literal; and the package's `ensureGtag` gtag.js stub helper, plus a new `loadGtagScript(options)` (loads gtag.js on demand, idempotent), are now exported so apps don't have to reimplement on-demand script loading themselves.
163
+
164
+ - [#565](https://github.com/codefastlabs/codefast/pull/565) [`1e80096`](https://github.com/codefastlabs/codefast/commit/1e800961f956fdc5f23c434c1bf6f9bedb6f187b) Thanks [@thevuong](https://github.com/thevuong)! - Guard `createLocalStorageConsentStorage` with `isConsentRecord` so malformed localStorage JSON cannot be treated as a valid consent record.
165
+
166
+ - [#565](https://github.com/codefastlabs/codefast/pull/565) [`1e80096`](https://github.com/codefastlabs/codefast/commit/1e800961f956fdc5f23c434c1bf6f9bedb6f187b) Thanks [@thevuong](https://github.com/thevuong)! - Skip `clearOnServer` when the anonymous-id cookie is already gone, so a second withdrawal clear in the same tick does not fire a redundant server round-trip.
167
+
3
168
  ## 0.5.0-canary.5
4
169
 
5
170
  ### Minor Changes
package/README.md CHANGED
@@ -1,160 +1,155 @@
1
1
  # @codefast/tracking
2
2
 
3
- Fullstack, type-safe event tracking for TanStack Start apps. Each app defines its own Zod
4
- event catalog tagged with an owner (`"client"` or `"server"`); trackers built from that
5
- catalog only allow firing events owned by that side — enforced at compile time.
6
-
7
- See [SPEC.md](./SPEC.md) for the full design (identity correlation, offline queue/retry,
8
- multi-destination fan-out, region-based consent).
3
+ Consent-gated, type-safe event tracking for TanStack Start apps.
4
+
5
+ - **One catalog, typed end to end** — apps define their events over any
6
+ [Standard Schema](https://standardschema.dev) library (zod, `zod/mini`, valibot, ...);
7
+ `track()` validates properties at the call site and at runtime, and the client bundle
8
+ only pays for the schema library the app already ships.
9
+ - **One consent config, every surface** — `ConsentConfig` is the single bag for the
10
+ storage key, policy version, and requested purposes; the React hooks, the tracker gate,
11
+ and the pre-hydration gtag bootstrap all take the same object, so nothing drifts.
12
+ - **ISR-safe by design** — shared/CDN-cached HTML bakes the strictest consent default;
13
+ the region-correct default arrives per visitor over a private server-function lane.
9
14
 
10
15
  ## Status
11
16
 
12
- Early scaffold. `core`, `client`, `server`, and `react` (headless consent) implement the
13
- shapes described in the spec. `createVercelAnalyticsDestination`,
14
- `createGoogleAnalyticsDestination`, and `createGa4MeasurementProtocolDestination` are
15
- implemented; PostHog is not built yet — use `createHttpDestination` or implement the
16
- `Destination` interface directly.
17
+ Pre-1.0 (canary). The surface is deliberately small: it covers exactly what a consented
18
+ gtag + Vercel Analytics setup on TanStack Start needs, and nothing speculative. Lanes
19
+ that shipped here before (offline queue, beacon relay, server-side tracker, GTM,
20
+ Segment-style `identify`/`group`/`alias`/`page`) were removed because no consumer called
21
+ them — git history has them if a real need returns.
17
22
 
18
23
  ## Quick start
19
24
 
20
25
  ```ts
21
- import { defineEventCatalog } from "@codefast/tracking";
22
- import { createClientTracker, createLocalStorageQueueStorage } from "@codefast/tracking/client";
23
- import { createHttpDestination } from "@codefast/tracking/destinations";
24
- import { z } from "zod";
26
+ // consent.ts — the one consent contract every surface shares
27
+ import { defineConsentConfig } from "@codefast/tracking";
25
28
 
26
- export const catalog = defineEventCatalog({
27
- button_clicked: { owner: "client", schema: z.object({ id: z.string() }) },
28
- order_completed: { owner: "server", schema: z.object({ orderId: z.string(), amount: z.number() }) },
29
+ export const consentConfig = defineConsentConfig({
30
+ policyVersion: "2026-01", // bump to re-prompt everyone
31
+ requestedCategories: ["analytics"],
32
+ storageKey: "my-app-consent",
29
33
  });
34
+ ```
30
35
 
31
- const tracker = createClientTracker({
32
- anonymousId: crypto.randomUUID(),
33
- catalog,
34
- destinations: [createHttpDestination({ name: "internal", endpoint: "/api/events" })],
35
- storage: createLocalStorageQueueStorage("tracking-queue"),
36
- });
36
+ ```ts
37
+ // consent-runtime.ts — live client instances derived from the config
38
+ import { createConsentRuntime } from "@codefast/tracking/client";
39
+
40
+ import { consentConfig } from "./consent";
41
+ import { resolveVisitorConsent } from "./resolve-visitor-consent"; // server fn, see below
37
42
 
38
- tracker.track("button_clicked", { id: "cta" });
39
- // tracker.track("order_completed", { orderId: "o1", amount: 10 }); // compile error — server-owned
43
+ export const consentRuntime = createConsentRuntime({
44
+ config: consentConfig,
45
+ initialConsentSessionStorageKey: "my-app-initial-consent",
46
+ resolveInitialConsent: () => resolveVisitorConsent(),
47
+ });
40
48
  ```
41
49
 
42
50
  ```ts
43
- import { createServerTracker } from "@codefast/tracking/server";
51
+ // tracking.ts — catalog + tracker
52
+ import { defineEventCatalog } from "@codefast/tracking";
53
+ import { createClientTracker } from "@codefast/tracking/client";
54
+ import { createGoogleAnalyticsDestination } from "@codefast/tracking/destinations";
55
+ import { createVercelAnalyticsDestination } from "@codefast/tracking/destinations/vercel-analytics";
56
+ import * as z from "zod/mini";
57
+
58
+ import { consentRuntime } from "./consent-runtime";
44
59
 
45
- const serverTracker = createServerTracker({
60
+ export const catalog = defineEventCatalog({
61
+ copy_code: { schema: z.object({ name: z.string() }) },
62
+ });
63
+
64
+ export const tracker = createClientTracker({
65
+ anonymousId: () => "...", // see the durable anonymous id section
46
66
  catalog,
47
67
  destinations: [
48
- /* ... */
68
+ // Vercel is cookieless and receives no identifier — it may keep counting pre-consent.
69
+ createVercelAnalyticsDestination({ consentRequirement: "exempt" }),
70
+ createGoogleAnalyticsDestination(),
49
71
  ],
72
+ isAnalyticsAllowed: consentRuntime.isAnalyticsAllowed,
50
73
  });
51
74
 
52
- await serverTracker.track("order_completed", { orderId: "o1", amount: 10 }, { anonymousId, userId });
75
+ tracker.track("copy_code", { name: "button" }); // typed + runtime-validated
53
76
  ```
54
77
 
55
- ## Router page views + unload flush
56
-
57
- `attachRouterPageTracking` is duck-typed against `Router["subscribe"]`, so it takes a real
58
- `@tanstack/react-router` instance without this package depending on it. `attachClientLifecycle`
59
- wires the periodic flush and the `sendBeacon` unload flush — `EventQueue` itself already
60
- auto-flushes once a batch hits its size threshold.
61
-
62
- ```ts
63
- import { attachClientLifecycle, attachRouterPageTracking } from "@codefast/tracking/client";
64
-
65
- attachRouterPageTracking(tracker, router); // router: your app's TanStack Router instance
66
- attachClientLifecycle(tracker, { beaconEndpoint: "/api/events", flushIntervalMs: 10_000 });
67
- ```
78
+ Destinations own their transport (gtag.js and Vercel both batch in-page), so `track()`
79
+ is fire-and-forget — a failing destination can never break the interaction.
68
80
 
69
81
  ## Consent (region-based, per-category)
70
82
 
71
- Consent is granular per purpose, mirroring Google Consent Mode v2's split: a
72
- `ConsentDecision` is `{ ads: boolean, analytics: boolean }`, never a single yes/no —
73
- GDPR requires purpose-level consent, and the ads signals (`ad_storage`/`ad_user_data`/
74
- `ad_personalization`) must be able to differ from `analytics_storage`.
75
-
76
- Resolve the region/mode server-side (`resolveRegion` + `resolveConsentMode` from
77
- `@codefast/tracking/server` and `@codefast/tracking`) and pass `mode` down to the client.
78
- The banner ships as composable, headless parts — no `@codefast/ui` dependency, any
79
- markup (including a design system's button styles via `className`) slots in. For a
80
- default look without writing CSS, import the optional plain-CSS theme:
83
+ `ConsentDecision` is per-purpose (`{ ads, analytics }`), mirroring Google Consent Mode
84
+ v2. Region resolves the mode: GDPR/UK/EEA and Vietnam's PDPL get **opt-in**, CCPA/CPRA
85
+ regions get **opt-out** with GPC honored as an ads opt-out.
86
+
87
+ - `useConsent({ config, mode, storage })` — `useSyncExternalStore` bridge over the stored
88
+ decision; cross-tab saves sync through the `storage` event.
89
+ - `ConsentBanner` + parts (`Title`/`Description`/`Actions`/`Accept`/`Reject`/`Customize`/
90
+ `Preferences`/`Category`/`Save`) — headless, `data-slot`-styleable; optional plain-CSS
91
+ theme at `@codefast/tracking/css/consent.css`. `ConsentToggle` is the persistent
92
+ opt-out control CCPA requires.
93
+ - `useGoogleConsentSync(consent, { loadGtagScript? })` — pushes Consent Mode `update`
94
+ signals, including privacy-page and cross-tab decisions.
95
+ - `createConsentWithdrawalHandler({ clearAnonymousId?, clearGoogleAnalyticsCookies? })` —
96
+ wire to `onDecision` so a denial clears first-party identifiers.
97
+
98
+ ### The ISR lane
99
+
100
+ ISR/CDN-cached HTML is shared across visitors, so no render may read geo. Bake
101
+ `STRICTEST_INITIAL_CONSENT` into the shared render (and into `<GtagConsentBootstrap />`),
102
+ then resolve the region-correct default per visitor after hydration:
103
+
104
+ 1. **Server function** — `resolveInitialConsentFromRequest({ requestedCategories })`
105
+ (`@codefast/tracking/tanstack-start`) reads the geo header and `sec-gpc`, stamps
106
+ `cache-control: private, no-store`, and fails closed when geo is missing.
107
+ 2. **Client** — `createConsentRuntime` owns the rest: strictest default until the server
108
+ answers, single-flight resolve, per-session cache, fail-closed-but-retryable errors.
109
+ Kick `runtime.ensureInitialConsentResolved()` at router creation (window-guarded) so
110
+ the round trip overlaps hydration; read it reactively via
111
+ `useInitialConsent(runtime.initialConsentStore)` (`@codefast/tracking/react`).
112
+
113
+ ## Durable anonymous id ("client mints, server persists")
114
+
115
+ `createServerPersistedAnonymousId` (`@codefast/tracking/client`) mints a UUID cookie
116
+ lazily — only once an event is actually allowed to send — and asks the server to re-issue
117
+ it via `Set-Cookie`, which escapes Safari ITP's 7-day cap on script-written cookies. The
118
+ server half is one line per endpoint with `setAnonymousIdResponseCookie` /
119
+ `clearAnonymousIdResponseCookie` (`@codefast/tracking/tanstack-start`); both validate the
120
+ id is exactly UUID-shaped, so a public endpoint can never echo attacker input into a
121
+ response header.
122
+
123
+ ## Google tag (advanced Consent Mode)
124
+
125
+ `<GtagConsentBootstrap config={consentConfig} defaultConsent={...} gaMeasurementId="G-…" />`
126
+ (`@codefast/tracking/react`) renders the pre-hydration inline script: Consent Mode v2
127
+ `default` first (stored decision wins over the baked fallback), then gtag.js always loads
128
+ so cookieless pings and consent modeling can run even when storage is denied. Page views
129
+ are gtag's own job (`config` + Enhanced Measurement) — the destination only forwards
130
+ catalog events. Runtime changes go through `useGoogleConsentSync`/`updateGoogleConsent`.
131
+
132
+ ## Keeping server-only subpaths out of client bundles
133
+
134
+ `./server` and `./tanstack-start` must never enter a client bundle. On TanStack Start,
135
+ spread the package's own deny-list into the plugin's import-protection so it versions
136
+ with the package instead of going stale in your config:
81
137
 
82
- ```css
83
- @import "@codefast/tracking/css/consent.css";
84
- ```
138
+ ```ts
139
+ import { SERVER_ONLY_IMPORT_SPECIFIERS } from "@codefast/tracking/import-protection";
85
140
 
86
- Or style the parts yourself via `className`/`data-slot` attributes (`consent-banner`,
87
- `consent-title`, `consent-description`, `consent-actions`, `consent-action`,
88
- `consent-preferences`, `consent-category`, `consent-toggle`), e.g. Tailwind's
89
- `**:data-[slot=consent-action]:rounded-md`. `data-state` on the root flips between
90
- `prompt` and `preferences`.
91
-
92
- ```tsx
93
- import { createLocalStorageConsentStorage } from "@codefast/tracking/client";
94
- import { updateGoogleConsent } from "@codefast/tracking/destinations";
95
- import {
96
- ConsentBanner,
97
- ConsentBannerAccept,
98
- ConsentBannerActions,
99
- ConsentBannerCategory,
100
- ConsentBannerCustomize,
101
- ConsentBannerDescription,
102
- ConsentBannerPreferences,
103
- ConsentBannerReject,
104
- ConsentBannerSave,
105
- ConsentBannerTitle,
106
- ConsentToggle,
107
- useConsent,
108
- } from "@codefast/tracking/react";
109
-
110
- // Module scope — useConsent subscribes to the storage, so it must be a stable reference.
111
- const consentStorage = createLocalStorageConsentStorage("tracking-consent");
112
-
113
- function ConsentGate({ mode }: { mode: "opt-in" | "opt-out" }) {
114
- const consent = useConsent({
115
- categories: ["analytics"], // the purposes your prompt asks about — Accept grants exactly these
116
- mode,
117
- onDecision: (decision) => {
118
- updateGoogleConsent(decision); // per-category Consent Mode v2 update
119
- if (!decision.analytics) tracker.clear(); // stop tracking + drop the pending queue
120
- },
121
- policyVersion: "2026-01",
122
- storage: consentStorage,
123
- });
124
-
125
- return mode === "opt-in" ? (
126
- <ConsentBanner consent={consent}>
127
- <ConsentBannerTitle>Cookies &amp; analytics</ConsentBannerTitle>
128
- <ConsentBannerDescription>
129
- We use cookies to understand how you use this site. <a href="/privacy">Privacy policy</a>
130
- </ConsentBannerDescription>
131
- {/* optional second layer: per-category checkboxes ("Customize" → "Save preferences") */}
132
- <ConsentBannerPreferences>
133
- <ConsentBannerCategory category="analytics">Analytics</ConsentBannerCategory>
134
- <ConsentBannerSave>Save preferences</ConsentBannerSave>
135
- </ConsentBannerPreferences>
136
- <ConsentBannerActions>
137
- <ConsentBannerAccept>Accept</ConsentBannerAccept>
138
- <ConsentBannerReject>Reject</ConsentBannerReject>
139
- <ConsentBannerCustomize>Customize</ConsentBannerCustomize>
140
- </ConsentBannerActions>
141
- </ConsentBanner>
142
- ) : (
143
- <ConsentToggle consent={consent} />
144
- );
145
- }
141
+ tanstackStart({
142
+ importProtection: {
143
+ client: { specifiers: [...SERVER_ONLY_IMPORT_SPECIFIERS] },
144
+ },
145
+ });
146
146
  ```
147
147
 
148
- The root gates itself on `consent.needsPrompt`; pass `open` to override — e.g. reopening
149
- the banner as a "Cookie settings" panel after a decision (GDPR expects withdrawing
150
- consent to be as easy as giving it).
148
+ A violation is mocked with a console diagnostic in dev and fails the build in prod, with
149
+ a trace of the offending import chain.
151
150
 
152
- The stored decision is the single source of truth (`useSyncExternalStore` under the
153
- hood): hydration-safe on prerendered pages, and a decision made in one tab dismisses the
154
- banner in every other tab via the `storage` event.
151
+ ## Reference consumer
155
152
 
156
- For Consent Mode v2, `setGoogleConsentDefault(decision, { waitForUpdateMs, region })`
157
- issues the pre-tag default (it defines the gtag queueing stub itself), and
158
- `setGoogleAdsDataRedaction`/`setGoogleUrlPassthrough` cover the denied-ads flags. A GPC
159
- signal is honored as a do-not-sell-or-share opt-out: it forces `ads` denied without
160
- withdrawing first-party `analytics`.
153
+ `apps/ui` (`src/features/tracking/`) in this repo wires everything above on a real
154
+ ISR-deployed TanStack Start site — consent config + runtime, banner + persistent toggle,
155
+ gtag bootstrap, durable anonymous id, and the private server-function consent lane.
@@ -0,0 +1,11 @@
1
+ //#region src/client/browser-cookie.d.ts
2
+ /**
3
+ * Shared `document.cookie` writer for the client-side cookie lanes (anonymous id, consent
4
+ * mirror): Secure on HTTPS so values never ride plain HTTP, SameSite=Lax, never HttpOnly —
5
+ * the client must read its own cookies back. A no-op without a `document` (SSR).
6
+ *
7
+ * @since 1.0.0-canary.6
8
+ */
9
+ declare function writeBrowserCookie(cookieName: string, value: string, maxAgeSeconds: number): void;
10
+ //#endregion
11
+ export { writeBrowserCookie };
@@ -0,0 +1,15 @@
1
+ //#region src/client/browser-cookie.ts
2
+ /**
3
+ * Shared `document.cookie` writer for the client-side cookie lanes (anonymous id, consent
4
+ * mirror): Secure on HTTPS so values never ride plain HTTP, SameSite=Lax, never HttpOnly —
5
+ * the client must read its own cookies back. A no-op without a `document` (SSR).
6
+ *
7
+ * @since 1.0.0-canary.6
8
+ */
9
+ function writeBrowserCookie(cookieName, value, maxAgeSeconds) {
10
+ if (typeof document === "undefined") return;
11
+ const secure = globalThis.location.protocol === "https:" ? "; secure" : "";
12
+ document.cookie = `${cookieName}=${value}; path=/; max-age=${String(maxAgeSeconds)}; samesite=lax${secure}`;
13
+ }
14
+ //#endregion
15
+ export { writeBrowserCookie };
@@ -0,0 +1,56 @@
1
+ import { ConsentStorage, InitialConsent } from "../core/consent.mjs";
2
+ import { InitialConsentStore } from "./initial-consent-store.mjs";
3
+ import { ConsentConfig } from "../core/consent-config.mjs";
4
+
5
+ //#region src/client/consent-runtime.d.ts
6
+ /**
7
+ * @since 1.0.0-canary.6
8
+ */
9
+ interface ConsentRuntimeOptions {
10
+ config: ConsentConfig;
11
+ /** Re-read per event so a GPC change applies without recreating the runtime. Defaults to the real navigator signal. */
12
+ hasGlobalPrivacyControlSignal?: (() => boolean) | undefined;
13
+ /**
14
+ * `sessionStorage` key caching the resolved region default, so only the first page
15
+ * load of a session pays the round trip — omit to resolve once per page load instead.
16
+ */
17
+ initialConsentSessionStorageKey?: string | undefined;
18
+ /**
19
+ * The per-visitor server lane — typically a server function wrapping
20
+ * `resolveInitialConsentFromRequest`. Shared/CDN-cached HTML can carry nothing
21
+ * region-specific, so this is the only place the region-correct default may come from.
22
+ */
23
+ resolveInitialConsent: () => Promise<InitialConsent>;
24
+ }
25
+ /**
26
+ * The live client-side consent instances, all derived from one `ConsentConfig` — create
27
+ * it once at module scope and every surface (banner hook, tracker gate, privacy page)
28
+ * shares the same storage and region resolution by construction.
29
+ *
30
+ * @since 1.0.0-canary.6
31
+ */
32
+ interface ConsentRuntime {
33
+ config: ConsentConfig;
34
+ /**
35
+ * Kicks off region resolution — single-flight and idempotent. Call it early (e.g. at
36
+ * router creation, window-guarded) so the round trip overlaps hydration instead of
37
+ * waiting for the first mount effect.
38
+ */
39
+ ensureInitialConsentResolved: () => void;
40
+ /** Feed to `useInitialConsent` for the reactive region default. */
41
+ initialConsentStore: InitialConsentStore;
42
+ /** Non-React gate for `createClientTracker` — the same rule `useConsent` applies. */
43
+ isAnalyticsAllowed: () => boolean;
44
+ /** The one `ConsentStorage` instance every surface must share. */
45
+ storage: ConsentStorage;
46
+ }
47
+ /**
48
+ * Composes the client half of the consent lane from a single `ConsentConfig`:
49
+ * `localStorage`-backed decision storage, the initial-consent store over the app's
50
+ * server lane, and the non-React analytics gate wired to that store's resolved mode.
51
+ *
52
+ * @since 1.0.0-canary.6
53
+ */
54
+ declare function createConsentRuntime(options: ConsentRuntimeOptions): ConsentRuntime;
55
+ //#endregion
56
+ export { ConsentRuntime, ConsentRuntimeOptions, createConsentRuntime };
@@ -0,0 +1,35 @@
1
+ import { createLocalStorageConsentStorage } from "./consent-storage.mjs";
2
+ import { hasGlobalPrivacyControlSignal } from "./gpc.mjs";
3
+ import { createInitialConsentStore } from "./initial-consent-store.mjs";
4
+ import { createIsAnalyticsAllowed } from "./is-analytics-allowed.mjs";
5
+ //#region src/client/consent-runtime.ts
6
+ /**
7
+ * Composes the client half of the consent lane from a single `ConsentConfig`:
8
+ * `localStorage`-backed decision storage, the initial-consent store over the app's
9
+ * server lane, and the non-React analytics gate wired to that store's resolved mode.
10
+ *
11
+ * @since 1.0.0-canary.6
12
+ */
13
+ function createConsentRuntime(options) {
14
+ const { config } = options;
15
+ const storage = createLocalStorageConsentStorage(config.storageKey);
16
+ const initialConsentStore = createInitialConsentStore({
17
+ resolve: options.resolveInitialConsent,
18
+ sessionStorageKey: options.initialConsentSessionStorageKey
19
+ });
20
+ const isAnalyticsAllowed = createIsAnalyticsAllowed({
21
+ config,
22
+ getMode: () => initialConsentStore.getSnapshot().initialConsent.mode,
23
+ hasGlobalPrivacyControlSignal: options.hasGlobalPrivacyControlSignal ?? hasGlobalPrivacyControlSignal,
24
+ storage
25
+ });
26
+ return {
27
+ config,
28
+ ensureInitialConsentResolved: initialConsentStore.ensureResolved,
29
+ initialConsentStore,
30
+ isAnalyticsAllowed,
31
+ storage
32
+ };
33
+ }
34
+ //#endregion
35
+ export { createConsentRuntime };
@@ -7,6 +7,11 @@ import { ConsentStorage } from "../core/consent.mjs";
7
7
  * for the session instead of re-prompting in a loop. `subscribe` fires for same-tab
8
8
  * writes and, via the `storage` event, for decisions made in other tabs.
9
9
  *
10
+ * `load()` parses and validates at most once per change: the result is cached and
11
+ * invalidated by `save`/`clear` and by cross-tab `storage` events, so per-event consent
12
+ * gates and per-render `useSyncExternalStore` snapshots cost a memory read, not a
13
+ * `JSON.parse`.
14
+ *
10
15
  * @remarks
11
16
  * The record persists as plain `JSON.stringify(ConsentRecord)` — a stable contract, so
12
17
  * pre-hydration inline scripts (e.g. a Consent Mode default bootstrap) can read the