@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
@@ -1,40 +1,39 @@
1
- import { track } from "@vercel/analytics/react";
1
+ import { track } from "@vercel/analytics";
2
2
 
3
3
  import type { Destination } from "#/core/destination";
4
-
5
- type VercelAnalyticsPropertyValue = boolean | number | string | null;
4
+ import { flattenEventProps } from "#/destinations/shared";
6
5
 
7
6
  /**
8
- * Vercel's `track()` rejects nested objects/arrays outright — flatten anything else
9
- * to a string instead of silently dropping it.
7
+ * @since 1.0.0-canary.6
10
8
  */
11
- function toVercelAnalyticsProps(props: Record<string, unknown>): Record<string, VercelAnalyticsPropertyValue> {
12
- const result: Record<string, VercelAnalyticsPropertyValue> = {};
13
-
14
- for (const [key, value] of Object.entries(props)) {
15
- if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
16
- result[key] = value;
17
- } else if (value !== undefined) {
18
- result[key] = JSON.stringify(value);
19
- }
20
- }
21
-
22
- return result;
9
+ export interface VercelAnalyticsDestinationOptions {
10
+ /**
11
+ * Vercel Analytics is cookieless and its events carry no identifier from this
12
+ * package, so it qualifies for `"exempt"` — it then keeps receiving events while the
13
+ * tracker's analytics gate is closed. Defaults to `"required"` so pre-consent delivery
14
+ * stays an explicit opt-in.
15
+ */
16
+ consentRequirement?: "exempt" | "required" | undefined;
17
+ name?: string | undefined;
23
18
  }
24
19
 
25
20
  /**
26
21
  * `track()` only pushes onto Vercel's own in-page queue (`window.va`/`window.vaq`), which
27
- * handles batching and unload delivery itself — hence `delivery: "immediate"`. Requires
28
- * `<Analytics />` from `@vercel/analytics/react` to be mounted once in the app.
22
+ * handles batching and unload delivery itself. Requires the Vercel Analytics script to be
23
+ * loaded once elsewhere in the app (`<Analytics />` from `@vercel/analytics/react`, or the
24
+ * framework-agnostic `inject()`) — this destination only queues events, so it imports the
25
+ * base `@vercel/analytics` package and has no React dependency of its own.
29
26
  *
30
27
  * @since 0.5.0-canary.4
31
28
  */
32
- export function createVercelAnalyticsDestination(name = "vercel-analytics"): Destination {
29
+ export function createVercelAnalyticsDestination(options: VercelAnalyticsDestinationOptions = {}): Destination {
33
30
  return {
34
- delivery: "immediate",
35
- name,
36
- send(event) {
37
- track(event.name, toVercelAnalyticsProps(event.props));
31
+ consentRequirement: options.consentRequirement ?? "required",
32
+ name: options.name ?? "vercel-analytics",
33
+ // Synchronous today, but declared async so a throw here rejects the returned Promise
34
+ // instead of escaping as a synchronous throw — matches Destination.send's contract.
35
+ async send(event) {
36
+ track(event.name, flattenEventProps(event.properties, { allowNull: true }));
38
37
  },
39
38
  };
40
39
  }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Import specifiers (picomatch patterns) every client bundle must deny — spread into
3
+ * TanStack Start's `importProtection.client.specifiers` so the deny-list ships and
4
+ * versions with the package instead of going stale in each consumer's config. Nothing in
5
+ * this package imports it — its consumers are app build configs (see apps/ui vite.config.ts).
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * tanstackStart({
10
+ * importProtection: { client: { specifiers: [...SERVER_ONLY_IMPORT_SPECIFIERS] } },
11
+ * });
12
+ * ```
13
+ *
14
+ * @since 1.0.0-canary.6
15
+ */
16
+ export const SERVER_ONLY_IMPORT_SPECIFIERS: ReadonlyArray<string> = [
17
+ "@codefast/tracking/server",
18
+ "@codefast/tracking/server/**",
19
+ "@codefast/tracking/tanstack-start",
20
+ ];
package/src/index.ts CHANGED
@@ -1,13 +1,51 @@
1
1
  /**
2
2
  * \@codefast/tracking
3
3
  *
4
- * Fullstack, type-safe event tracking: apps define a Zod event catalog tagged with an
5
- * owner ("client" | "server"), then build trackers from it that only allow firing
6
- * events owned by that side — enforced at compile time, not by convention.
4
+ * Consent-gated, type-safe event tracking for TanStack Start apps: define an event
5
+ * catalog over any Standard Schema library, wire a `ConsentConfig` + `createConsentRuntime`,
6
+ * and fan tracked events out to gtag / Vercel Analytics destinations.
7
7
  *
8
- * - **Root** (this module): isomorphic catalog types, `Destination`, consent helpers — safe to import from both client and server code.
9
- * - **`@codefast/tracking/client`**: `createClientTracker` — batching, offline queue, retry.
10
- * - **`@codefast/tracking/server`**: `createServerTracker`, region detection for consent.
11
- * - **`@codefast/tracking/destinations`**: `createHttpDestination` and the `Destination` building block.
8
+ * - **Root** (this module): isomorphic catalog types, `Destination`, consent model + config — safe to import from both client and server code.
9
+ * - **`@codefast/tracking/client`**: `createClientTracker`, `createConsentRuntime`, anonymous-id helpers.
10
+ * - **`@codefast/tracking/server`**: region → initial-consent resolution, anonymous-id `Set-Cookie` builders. Server-only — never import from client code.
11
+ * - **`@codefast/tracking/tanstack-start`**: request/response glue over TanStack Start's server context. Server-only — deny it in the client environment via Start's `importProtection`.
12
+ * - **`@codefast/tracking/destinations`**: the gtag destination, script loader, and Consent Mode bootstrap; Vercel Analytics lives on its own subpath.
12
13
  */
13
- export * from "#/core";
14
+ export type {
15
+ ConsentCategory,
16
+ ConsentConfig,
17
+ ConsentDecision,
18
+ ConsentMode,
19
+ ConsentRecord,
20
+ ConsentRegion,
21
+ ConsentStorage,
22
+ Destination,
23
+ EventCatalog,
24
+ EventDefinition,
25
+ InitialConsent,
26
+ ResolveDefaultConsentOptions,
27
+ ResolveEffectiveConsentOptions,
28
+ TrackedEvent,
29
+ TrackedEventBase,
30
+ TrackEvent,
31
+ } from "#/core";
32
+ export {
33
+ assertValidEventProperties,
34
+ CONSENT_CATEGORIES,
35
+ CONSENT_REGIONS,
36
+ createConsentDecision,
37
+ defineConsentConfig,
38
+ defineEventCatalog,
39
+ generateEventId,
40
+ isConsentDecision,
41
+ isConsentRecord,
42
+ isConsentRegion,
43
+ isInitialConsent,
44
+ normalizeConsentDecision,
45
+ readCookieValue,
46
+ readStoredDecision,
47
+ resolveConsentMode,
48
+ resolveDefaultConsent,
49
+ resolveEffectiveConsent,
50
+ STRICTEST_INITIAL_CONSENT,
51
+ } from "#/core";
@@ -1,8 +1,9 @@
1
+ "use client";
2
+
1
3
  import type { ComponentProps, Dispatch, ReactNode, SetStateAction } from "react";
2
4
  import { createContext, useContext, useEffect, useState } from "react";
3
5
 
4
6
  import type { ConsentCategory, ConsentDecision } from "#/core/consent";
5
- import { CONSENT_CATEGORIES } from "#/core/consent";
6
7
  import type { UseConsentResult } from "#/react/use-consent";
7
8
 
8
9
  interface ConsentBannerContextValue {
@@ -29,16 +30,16 @@ function useConsentBannerContext(part: string): ConsentBannerContextValue {
29
30
  */
30
31
  export interface ConsentBannerProps extends ComponentProps<"section"> {
31
32
  consent: UseConsentResult;
32
- /** Overrides the default `needsPrompt` gating — e.g. to reopen the banner as a settings panel. */
33
+ /** Overrides the default `isPromptNeeded` gating — e.g. to reopen the banner as a settings panel. */
33
34
  open?: boolean | undefined;
34
35
  }
35
36
 
36
37
  /**
37
- * Non-blocking opt-in prompt for GDPR/NĐ 13 regions, as composable parts — the root owns
38
+ * Non-blocking opt-in prompt for GDPR/PDPL (VN) regions, as composable parts — the root owns
38
39
  * the visibility gating and the preferences-layer state; the `Accept`/`Reject`/`Customize`/
39
40
  * `Save` parts wire their own clicks to the consent hook, so any markup (including a
40
41
  * design system's button styles via `className`) slots in. Renders nothing once a decision
41
- * exists or the region defaults to opt-out (`consent.needsPrompt`), unless `open` says
42
+ * exists or the region defaults to opt-out (`consent.isPromptNeeded`), unless `open` says
42
43
  * otherwise. Rendered as a labeled region, not a `<dialog>`: an open non-modal dialog
43
44
  * neither traps focus nor blocks the page, so the dialog semantics would over-promise.
44
45
  * Unstyled by default — style via `className`/`data-slot` selectors, or import the
@@ -50,7 +51,7 @@ export interface ConsentBannerProps extends ComponentProps<"section"> {
50
51
  export function ConsentBanner({ children, consent, open, ...props }: ConsentBannerProps): ReactNode {
51
52
  const [pending, setPending] = useState<ConsentDecision | undefined>(undefined);
52
53
 
53
- const isVisible = open ?? consent.needsPrompt;
54
+ const isVisible = open ?? consent.isPromptNeeded;
54
55
 
55
56
  // Closing must reset the layer — a reopened banner starts at the prompt, not mid-preferences.
56
57
  useEffect(() => {
@@ -125,7 +126,7 @@ export function ConsentBannerActions(props: ConsentBannerActionsProps): ReactNod
125
126
  export interface ConsentBannerAcceptProps extends Omit<ComponentProps<"button">, "type"> {}
126
127
 
127
128
  /**
128
- * Grants the categories the app requested (`useConsent`'s `categories`) — never more.
129
+ * Grants the categories the app requested (`useConsent`'s `requestedCategories`) — never more.
129
130
  *
130
131
  * @since 0.5.0-canary.5
131
132
  */
@@ -288,7 +289,7 @@ export function ConsentBannerSave({ onClick, ...props }: ConsentBannerSaveProps)
288
289
  // the part owns the decision — composed so a consumer onClick still runs
289
290
  onClick={(event) => {
290
291
  onClick?.(event);
291
- consent.save(pending);
292
+ consent.saveDecision(pending);
292
293
  setPending(undefined);
293
294
  }}
294
295
  type="button"
@@ -300,15 +301,31 @@ export function ConsentBannerSave({ onClick, ...props }: ConsentBannerSaveProps)
300
301
  * @since 0.5.0-canary.4
301
302
  */
302
303
  export interface ConsentToggleProps extends Omit<ComponentProps<"button">, "children" | "onClick" | "type"> {
303
- allowLabel?: string;
304
+ /**
305
+ * Label shown while the scoped categories are denied — clicking grants them. Defaults
306
+ * to "Allow tracking".
307
+ */
308
+ allowLabel?: string | undefined;
304
309
  consent: UseConsentResult;
305
- denyLabel?: string;
310
+ /**
311
+ * Label shown while any scoped category is granted — clicking denies them. Defaults to
312
+ * CCPA/CPRA "Do Not Sell or Share My Personal Information".
313
+ */
314
+ denyLabel?: string | undefined;
315
+ /**
316
+ * Purposes this control flips. Defaults to `["ads"]` — CCPA/CPRA "Do Not Sell or Share"
317
+ * mirrors GPC (ads denied, first-party analytics left alone). Pass `["analytics"]` (or
318
+ * both) for a broader opt-out. Distinct from `useConsent`'s `requestedCategories` (what the
319
+ * prompt asks about / `grantAll` grants).
320
+ */
321
+ toggledCategories?: ReadonlyArray<ConsentCategory> | undefined;
306
322
  }
307
323
 
308
324
  /**
309
325
  * Always-visible control for opt-out regions — CCPA/CPRA requires a persistent
310
326
  * "Do Not Sell or Share My Personal Information" mechanism, not just a one-time prompt.
311
- * Flips between denying everything and re-granting the app's requested categories.
327
+ * By default it only flips `ads` (same scope as a GPC signal); pass `toggledCategories`
328
+ * to include analytics or both.
312
329
  *
313
330
  * @since 0.5.0-canary.4
314
331
  */
@@ -316,19 +333,28 @@ export function ConsentToggle({
316
333
  allowLabel = "Allow tracking",
317
334
  consent,
318
335
  denyLabel = "Do Not Sell or Share My Personal Information",
336
+ toggledCategories = ["ads"],
319
337
  ...props
320
338
  }: ConsentToggleProps): ReactNode {
321
- const anyAllowed = CONSENT_CATEGORIES.some((category) => consent.effectiveConsent[category]);
339
+ const isAnyCategoryGranted = toggledCategories.some((category) => consent.effectiveConsent[category]);
322
340
 
323
341
  return (
324
342
  <button
325
343
  data-slot="consent-toggle"
326
344
  {...props}
327
- // the toggle owns its click — flipping the stored decision is its whole purpose
328
- onClick={anyAllowed ? consent.denyAll : consent.grantAll}
345
+ // the toggle owns its click — flipping the scoped categories is its whole purpose
346
+ onClick={() => {
347
+ const next = { ...consent.effectiveConsent };
348
+
349
+ for (const category of toggledCategories) {
350
+ next[category] = !isAnyCategoryGranted;
351
+ }
352
+
353
+ consent.saveDecision(next);
354
+ }}
329
355
  type="button"
330
356
  >
331
- {anyAllowed ? denyLabel : allowLabel}
357
+ {isAnyCategoryGranted ? denyLabel : allowLabel}
332
358
  </button>
333
359
  );
334
360
  }
@@ -0,0 +1,48 @@
1
+ import type { ComponentProps, ReactNode } from "react";
2
+
3
+ import type { GtagConsentBootstrapOptions } from "#/destinations/google-analytics";
4
+ import { buildGtagConsentBootstrapScript } from "#/destinations/google-analytics";
5
+
6
+ /**
7
+ * @since 1.0.0-canary.6
8
+ */
9
+ export interface GtagConsentBootstrapProps
10
+ extends
11
+ Omit<ComponentProps<"script">, "children" | "dangerouslySetInnerHTML" | "nonce" | "src" | "type">,
12
+ GtagConsentBootstrapOptions {}
13
+
14
+ /**
15
+ * Framework-agnostic inline `<script>` that runs `buildGtagConsentBootstrapScript` before
16
+ * hydration. Pass the same `nonce` here and in `loadGtagScript` for CSP; this component
17
+ * only sets the attribute on the host script — the generated source also stamps it onto
18
+ * the injected gtag.js tag when `nonce` is provided.
19
+ *
20
+ * @since 1.0.0-canary.6
21
+ */
22
+ export function GtagConsentBootstrap({
23
+ config,
24
+ dataLayerName,
25
+ defaultConsent,
26
+ debugMode,
27
+ gaMeasurementId,
28
+ nonce,
29
+ ...props
30
+ }: GtagConsentBootstrapProps): ReactNode {
31
+ const bootstrapOptions: GtagConsentBootstrapOptions = {
32
+ config,
33
+ defaultConsent,
34
+ gaMeasurementId,
35
+ ...(dataLayerName === undefined ? {} : { dataLayerName }),
36
+ ...(debugMode === undefined ? {} : { debugMode }),
37
+ ...(nonce === undefined ? {} : { nonce }),
38
+ };
39
+
40
+ return (
41
+ <script
42
+ {...props}
43
+ dangerouslySetInnerHTML={{ __html: buildGtagConsentBootstrapScript(bootstrapOptions) }}
44
+ {...(nonce === undefined ? {} : { nonce })}
45
+ suppressHydrationWarning
46
+ />
47
+ );
48
+ }
@@ -27,3 +27,11 @@ export {
27
27
 
28
28
  export type { UseConsentOptions, UseConsentResult } from "#/react/use-consent";
29
29
  export { useConsent } from "#/react/use-consent";
30
+
31
+ export { useInitialConsent } from "#/react/use-initial-consent";
32
+
33
+ export type { UseGoogleConsentSyncOptions } from "#/react/use-google-consent-sync";
34
+ export { useGoogleConsentSync } from "#/react/use-google-consent-sync";
35
+
36
+ export type { GtagConsentBootstrapProps } from "#/react/gtag-consent-bootstrap";
37
+ export { GtagConsentBootstrap } from "#/react/gtag-consent-bootstrap";
@@ -1,22 +1,20 @@
1
- import { useRef, useSyncExternalStore } from "react";
1
+ "use client";
2
2
 
3
- import type { ConsentCategory, ConsentDecision, ConsentMode, ConsentStorage } from "#/core/consent";
4
- import { CONSENT_CATEGORIES, createConsentDecision, isConsentDecision, resolveDefaultConsent } from "#/core/consent";
3
+ import { useCallback, useMemo, useRef, useSyncExternalStore } from "react";
4
+
5
+ import type { ConsentDecision, ConsentMode, ConsentStorage } from "#/core/consent";
6
+ import { CONSENT_CATEGORIES, createConsentDecision, readStoredDecision, resolveDefaultConsent } from "#/core/consent";
7
+ import type { ConsentConfig } from "#/core/consent-config";
5
8
 
6
9
  /**
7
10
  * @since 0.5.0-canary.4
8
11
  */
9
12
  export interface UseConsentOptions {
10
- /**
11
- * Categories the app's prompt actually asks about — `grantAll` grants exactly these,
12
- * so an analytics-only banner can never grant ads consent it never asked for.
13
- * Defaults to `["analytics"]`.
14
- */
15
- categories?: ReadonlyArray<ConsentCategory>;
16
- hasGlobalPrivacyControlSignal?: boolean;
13
+ /** Must be the same object the tracker gate and the tag bootstraps receive — one config, every surface. */
14
+ config: ConsentConfig;
15
+ hasGlobalPrivacyControlSignal?: boolean | undefined;
17
16
  mode: ConsentMode;
18
- onDecision?: (decision: ConsentDecision) => void;
19
- policyVersion: string;
17
+ onDecision?: ((decision: ConsentDecision) => void) | undefined;
20
18
  /** Must be a stable reference (module-level or memoized) — a new object per render resubscribes every render. */
21
19
  storage: ConsentStorage;
22
20
  }
@@ -32,15 +30,13 @@ export interface UseConsentResult {
32
30
  effectiveConsent: ConsentDecision;
33
31
  grantAll: () => void;
34
32
  /** Effective `analytics` consent — gates this package's own tracker pipeline. */
35
- isTrackingAllowed: boolean;
33
+ isAnalyticsAllowed: boolean;
36
34
  /** True only for opt-in regions with no stored decision yet — drives whether to render the banner. */
37
- needsPrompt: boolean;
35
+ isPromptNeeded: boolean;
38
36
  /** Persist a granular per-category choice, e.g. from a preferences panel. */
39
- save: (decision: ConsentDecision) => void;
37
+ saveDecision: (decision: ConsentDecision) => void;
40
38
  }
41
39
 
42
- const DEFAULT_CATEGORIES: ReadonlyArray<ConsentCategory> = ["analytics"];
43
-
44
40
  /**
45
41
  * Bridges `resolveConsentMode`/`resolveDefaultConsent` (core, region-aware) to React via
46
42
  * `useSyncExternalStore`: the stored record is the single source of truth, hydration is
@@ -51,8 +47,9 @@ const DEFAULT_CATEGORIES: ReadonlyArray<ConsentCategory> = ["analytics"];
51
47
  * @since 0.5.0-canary.4
52
48
  */
53
49
  export function useConsent(options: UseConsentOptions): UseConsentResult {
54
- const { storage } = options;
55
- const categories = options.categories ?? DEFAULT_CATEGORIES;
50
+ const { mode, onDecision, storage } = options;
51
+ const { policyVersion, requestedCategories } = options.config;
52
+ const hasGlobalPrivacyControlSignal = options.hasGlobalPrivacyControlSignal ?? false;
56
53
 
57
54
  // useSyncExternalStore needs a referentially stable snapshot, but JSON-backed storages
58
55
  // parse a fresh record per load — so the last valid decision is cached by value.
@@ -61,51 +58,62 @@ export function useConsent(options: UseConsentOptions): UseConsentResult {
61
58
  const decision = useSyncExternalStore(
62
59
  storage.subscribe,
63
60
  (): ConsentDecision | undefined => {
64
- const record = storage.load();
65
-
66
61
  // Only a well-formed decision under the current policy version counts — the store
67
62
  // is tamperable plain JSON, and a garbage value must re-prompt, not silently deny.
68
- if (record?.policyVersion !== options.policyVersion || !isConsentDecision(record.decision)) {
63
+ const stored = readStoredDecision(storage, policyVersion);
64
+
65
+ if (stored === undefined) {
69
66
  cachedDecision.current = undefined;
70
67
 
71
68
  return undefined;
72
69
  }
73
70
 
74
- const stored = record.decision;
75
71
  const cached = cachedDecision.current;
76
72
 
77
73
  if (cached !== undefined && CONSENT_CATEGORIES.every((category) => cached[category] === stored[category])) {
78
74
  return cached;
79
75
  }
80
76
 
81
- // A normalized copy, so tampered extra keys never leak past the hook.
82
- cachedDecision.current = createConsentDecision(CONSENT_CATEGORIES.filter((category) => stored[category]));
77
+ cachedDecision.current = stored;
83
78
 
84
79
  return cachedDecision.current;
85
80
  },
86
81
  () => undefined,
87
82
  );
88
83
 
89
- function save(next: ConsentDecision): void {
90
- // No local state — the save notifies the subscription, which re-renders with the new snapshot.
91
- storage.save({ decision: next, policyVersion: options.policyVersion, timestamp: Date.now() });
92
- options.onDecision?.(next);
93
- }
84
+ // Kept stable across renders (when their own inputs don't change) so a consumer that
85
+ // passes this hook's result down as a prop/effect-dep doesn't get a fresh identity —
86
+ // and therefore an unnecessary re-render/effect-rerun — every render.
87
+ const saveDecision = useCallback(
88
+ (next: ConsentDecision): void => {
89
+ // No local state — the save notifies the subscription, which re-renders with the new snapshot.
90
+ storage.save({ decision: next, policyVersion, timestamp: Date.now() });
91
+ onDecision?.(next);
92
+ },
93
+ [onDecision, policyVersion, storage],
94
+ );
95
+
96
+ const denyAll = useCallback(() => {
97
+ saveDecision(createConsentDecision([]));
98
+ }, [saveDecision]);
94
99
 
95
- const effectiveConsent =
96
- decision ?? resolveDefaultConsent(options.mode, categories, options.hasGlobalPrivacyControlSignal ?? false);
100
+ const grantAll = useCallback(() => {
101
+ saveDecision(createConsentDecision(requestedCategories));
102
+ }, [requestedCategories, saveDecision]);
97
103
 
98
- return {
99
- decision,
100
- denyAll: () => {
101
- save(createConsentDecision([]));
102
- },
103
- effectiveConsent,
104
- grantAll: () => {
105
- save(createConsentDecision(categories));
106
- },
107
- isTrackingAllowed: effectiveConsent.analytics,
108
- needsPrompt: options.mode === "opt-in" && decision === undefined,
109
- save,
110
- };
104
+ const effectiveConsent =
105
+ decision ?? resolveDefaultConsent({ hasGlobalPrivacyControlSignal, mode, requestedCategories });
106
+
107
+ return useMemo(
108
+ () => ({
109
+ decision,
110
+ denyAll,
111
+ effectiveConsent,
112
+ grantAll,
113
+ isAnalyticsAllowed: effectiveConsent.analytics,
114
+ isPromptNeeded: mode === "opt-in" && decision === undefined,
115
+ saveDecision,
116
+ }),
117
+ [decision, denyAll, effectiveConsent, grantAll, mode, saveDecision],
118
+ );
111
119
  }
@@ -0,0 +1,38 @@
1
+ "use client";
2
+
3
+ import { useEffect } from "react";
4
+
5
+ import { updateGoogleConsent } from "#/destinations/google-analytics";
6
+ import type { UseConsentResult } from "#/react/use-consent";
7
+
8
+ /**
9
+ * @since 1.0.0-canary.6
10
+ */
11
+ export interface UseGoogleConsentSyncOptions {
12
+ /**
13
+ * Idempotent gtag.js load — advanced Consent Mode already injects the tag from a
14
+ * bootstrap; pass a loader as a safety net after a runtime grant.
15
+ */
16
+ loadGtagScript?: (() => void) | undefined;
17
+ }
18
+
19
+ /**
20
+ * Keeps Google Consent Mode v2 in sync with `useConsent`: emits `update` when a stored
21
+ * decision exists (including cross-tab / privacy-page saves), and optionally loads gtag
22
+ * when analytics is effective. Mount once on a page-wide surface (e.g. the footer gate).
23
+ *
24
+ * @since 1.0.0-canary.6
25
+ */
26
+ export function useGoogleConsentSync(consent: UseConsentResult, options: UseGoogleConsentSyncOptions = {}): void {
27
+ const { loadGtagScript } = options;
28
+
29
+ useEffect(() => {
30
+ if (consent.decision !== undefined) {
31
+ updateGoogleConsent(consent.decision);
32
+ }
33
+
34
+ if (consent.effectiveConsent.analytics) {
35
+ loadGtagScript?.();
36
+ }
37
+ }, [consent.decision, consent.effectiveConsent.analytics, loadGtagScript]);
38
+ }
@@ -0,0 +1,22 @@
1
+ "use client";
2
+
3
+ import { useEffect, useSyncExternalStore } from "react";
4
+
5
+ import type { InitialConsentSnapshot, InitialConsentStore } from "#/client/initial-consent-store";
6
+
7
+ /**
8
+ * Reactive view of a `createInitialConsentStore` — kicks off resolution on mount (a no-op
9
+ * when the app already did so at router creation) and re-renders once the server lane
10
+ * answers. SSR and the first client render read the strictest snapshot, so hydration can
11
+ * never mismatch on region.
12
+ *
13
+ * @since 1.0.0-canary.6
14
+ */
15
+ export function useInitialConsent(store: InitialConsentStore): InitialConsentSnapshot {
16
+ // Post-hydration safety net — idempotent with an earlier, pre-hydration kick.
17
+ useEffect(() => {
18
+ store.ensureResolved();
19
+ }, [store]);
20
+
21
+ return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);
22
+ }
@@ -0,0 +1,76 @@
1
+ import { ONE_YEAR_IN_SECONDS } from "#/core/cookie";
2
+
3
+ // The only shape the client ever mints (crypto.randomUUID) — anything else is rejected.
4
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
5
+
6
+ // Conservative subset of the RFC 6265 cookie-name token.
7
+ const COOKIE_NAME_PATTERN = /^[\w-]+$/;
8
+
9
+ function assertCookieName(cookieName: string): void {
10
+ if (!COOKIE_NAME_PATTERN.test(cookieName)) {
11
+ throw new Error(`Invalid anonymous-id cookie name: ${JSON.stringify(cookieName)}`);
12
+ }
13
+ }
14
+
15
+ /**
16
+ * Whether a value is safe to persist as an anonymous id. The persist endpoint is public
17
+ * and echoes its input into a response header, so only an exactly-UUID-shaped value may
18
+ * pass — anything else is a header-injection attempt or corruption, never a valid id.
19
+ *
20
+ * @since 1.0.0-canary.6
21
+ */
22
+ export function isValidAnonymousId(value: string): boolean {
23
+ return UUID_PATTERN.test(value);
24
+ }
25
+
26
+ /**
27
+ * @since 1.0.0-canary.6
28
+ */
29
+ export interface AnonymousIdSetCookieOptions {
30
+ /** Cookie name — must match what the client tracker reads. */
31
+ cookieName: string;
32
+ /** The client-minted id to persist — throws unless it is exactly UUID-shaped. */
33
+ id: string;
34
+ /** How long the id survives a return visit. Defaults to one year. */
35
+ maxAgeSeconds?: number | undefined;
36
+ }
37
+
38
+ /**
39
+ * `Set-Cookie` header value that persists (or prolongs) a client-minted anonymous id from
40
+ * the server. A server-set cookie escapes Safari ITP's 7-day cap on `document.cookie`
41
+ * writes, so the id actually lives its full max-age. The server only ever re-sets an id
42
+ * the client hands it — minting stays client-side, after consent, by design.
43
+ *
44
+ * @remarks
45
+ * Always `Secure` — on a plain-HTTP dev origin a browser may drop it, and the
46
+ * client-written cookie (`createServerPersistedAnonymousId`'s optimistic write) still
47
+ * covers that session. Not `HttpOnly`: the client tracker must read the id to stamp it
48
+ * onto events.
49
+ *
50
+ * @throws Error when `id` is not UUID-shaped or `cookieName` is not a valid token.
51
+ *
52
+ * @since 1.0.0-canary.6
53
+ */
54
+ export function buildAnonymousIdSetCookie(options: AnonymousIdSetCookieOptions): string {
55
+ const { cookieName, id, maxAgeSeconds = ONE_YEAR_IN_SECONDS } = options;
56
+
57
+ assertCookieName(cookieName);
58
+
59
+ if (!isValidAnonymousId(id)) {
60
+ throw new Error("Invalid anonymous id: expected a UUID-shaped value");
61
+ }
62
+
63
+ return `${cookieName}=${id}; Path=/; Max-Age=${String(maxAgeSeconds)}; SameSite=Lax; Secure`;
64
+ }
65
+
66
+ /**
67
+ * `Set-Cookie` header value that expires the anonymous-id cookie — the server half of a
68
+ * consent withdrawal, alongside the client's own `document.cookie` expiry.
69
+ *
70
+ * @since 1.0.0-canary.6
71
+ */
72
+ export function buildClearAnonymousIdSetCookie(cookieName: string): string {
73
+ assertCookieName(cookieName);
74
+
75
+ return `${cookieName}=; Path=/; Max-Age=0; SameSite=Lax; Secure`;
76
+ }
@@ -1,4 +1,16 @@
1
- export type { ServerTrackContext, ServerTracker, ServerTrackerOptions } from "#/server/create-server-tracker";
2
- export { createServerTracker } from "#/server/create-server-tracker";
1
+ export type { AnonymousIdSetCookieOptions } from "#/server/anonymous-id-cookie";
2
+ export {
3
+ buildAnonymousIdSetCookie,
4
+ buildClearAnonymousIdSetCookie,
5
+ isValidAnonymousId,
6
+ } from "#/server/anonymous-id-cookie";
3
7
 
4
- export { resolveRegion, resolveRegionFromCountryCode } from "#/server/region";
8
+ export type { InitialConsent, InitialConsentOptions } from "#/server/initial-consent";
9
+ export { resolveInitialConsent } from "#/server/initial-consent";
10
+
11
+ export {
12
+ EU_COUNTRY_CODES,
13
+ OPT_IN_EQUIVALENT_COUNTRY_CODES,
14
+ resolveRegion,
15
+ resolveRegionFromCountryCode,
16
+ } from "#/server/region";