@codefast/tracking 0.5.0-canary.4 → 0.5.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 (277) hide show
  1. package/CHANGELOG.md +473 -0
  2. package/README.md +177 -95
  3. package/dist/adapters/tanstack-start.d.ts +80 -0
  4. package/dist/adapters/tanstack-start.d.ts.map +1 -0
  5. package/dist/adapters/tanstack-start.js +74 -0
  6. package/dist/adapters/tanstack-start.js.map +1 -0
  7. package/dist/client/ad-framework-consent.d.ts +62 -0
  8. package/dist/client/ad-framework-consent.d.ts.map +1 -0
  9. package/dist/client/ad-framework-consent.js +40 -0
  10. package/dist/client/ad-framework-consent.js.map +1 -0
  11. package/dist/client/browser-cookie.d.ts +9 -0
  12. package/dist/client/browser-cookie.d.ts.map +1 -0
  13. package/dist/client/browser-cookie.js +15 -0
  14. package/dist/client/browser-cookie.js.map +1 -0
  15. package/dist/client/consent-runtime.d.ts +53 -0
  16. package/dist/client/consent-runtime.d.ts.map +1 -0
  17. package/dist/client/consent-runtime.js +33 -0
  18. package/dist/client/consent-runtime.js.map +1 -0
  19. package/dist/client/{consent-storage.d.mts → consent-storage.d.ts} +8 -6
  20. package/dist/client/consent-storage.d.ts.map +1 -0
  21. package/dist/client/consent-storage.js +109 -0
  22. package/dist/client/consent-storage.js.map +1 -0
  23. package/dist/client/consent-withdrawal.d.ts +18 -0
  24. package/dist/client/consent-withdrawal.d.ts.map +1 -0
  25. package/dist/client/consent-withdrawal.js +17 -0
  26. package/dist/client/consent-withdrawal.js.map +1 -0
  27. package/dist/client/cookie-anonymous-id.d.ts +41 -0
  28. package/dist/client/cookie-anonymous-id.d.ts.map +1 -0
  29. package/dist/client/cookie-anonymous-id.js +65 -0
  30. package/dist/client/cookie-anonymous-id.js.map +1 -0
  31. package/dist/client/create-client-tracker.d.ts +60 -0
  32. package/dist/client/create-client-tracker.d.ts.map +1 -0
  33. package/dist/client/create-client-tracker.js +91 -0
  34. package/dist/client/create-client-tracker.js.map +1 -0
  35. package/dist/client/gpc.d.ts +10 -0
  36. package/dist/client/gpc.d.ts.map +1 -0
  37. package/dist/client/gpc.js +12 -0
  38. package/dist/client/gpc.js.map +1 -0
  39. package/dist/client/initial-consent-store.d.ts +63 -0
  40. package/dist/client/initial-consent-store.d.ts.map +1 -0
  41. package/dist/client/initial-consent-store.js +138 -0
  42. package/dist/client/initial-consent-store.js.map +1 -0
  43. package/dist/client/is-analytics-allowed.d.ts +26 -0
  44. package/dist/client/is-analytics-allowed.d.ts.map +1 -0
  45. package/dist/client/is-analytics-allowed.js +22 -0
  46. package/dist/client/is-analytics-allowed.js.map +1 -0
  47. package/dist/client/server-persisted-anonymous-id.d.ts +30 -0
  48. package/dist/client/server-persisted-anonymous-id.d.ts.map +1 -0
  49. package/dist/client/server-persisted-anonymous-id.js +72 -0
  50. package/dist/client/server-persisted-anonymous-id.js.map +1 -0
  51. package/dist/core/consent-config.d.ts +24 -0
  52. package/dist/core/consent-config.d.ts.map +1 -0
  53. package/dist/core/consent-config.js +9 -0
  54. package/dist/core/consent-config.js.map +1 -0
  55. package/dist/core/consent-receipt.d.ts +71 -0
  56. package/dist/core/consent-receipt.d.ts.map +1 -0
  57. package/dist/core/consent-receipt.js +39 -0
  58. package/dist/core/consent-receipt.js.map +1 -0
  59. package/dist/core/consent.d.ts +182 -0
  60. package/dist/core/consent.d.ts.map +1 -0
  61. package/dist/core/consent.js +159 -0
  62. package/dist/core/consent.js.map +1 -0
  63. package/dist/core/cookie.d.ts +15 -0
  64. package/dist/core/cookie.d.ts.map +1 -0
  65. package/dist/core/cookie.js +26 -0
  66. package/dist/core/cookie.js.map +1 -0
  67. package/dist/core/destination.d.ts +29 -0
  68. package/dist/core/destination.d.ts.map +1 -0
  69. package/dist/core/destination.js +2 -0
  70. package/dist/core/destination.js.map +1 -0
  71. package/dist/core/event-catalog.d.ts +35 -0
  72. package/dist/core/event-catalog.d.ts.map +1 -0
  73. package/dist/core/event-catalog.js +30 -0
  74. package/dist/core/event-catalog.js.map +1 -0
  75. package/dist/core/event-id.d.ts +7 -0
  76. package/dist/core/event-id.d.ts.map +1 -0
  77. package/dist/core/event-id.js +9 -0
  78. package/dist/core/event-id.js.map +1 -0
  79. package/dist/core/tracked-event.d.ts +15 -0
  80. package/dist/core/tracked-event.d.ts.map +1 -0
  81. package/dist/core/tracked-event.js +2 -0
  82. package/dist/core/tracked-event.js.map +1 -0
  83. package/dist/destinations/ad-consent.d.ts +23 -0
  84. package/dist/destinations/ad-consent.d.ts.map +1 -0
  85. package/dist/destinations/ad-consent.js +12 -0
  86. package/dist/destinations/ad-consent.js.map +1 -0
  87. package/dist/destinations/google-analytics.d.ts +148 -0
  88. package/dist/destinations/google-analytics.d.ts.map +1 -0
  89. package/dist/destinations/google-analytics.js +156 -0
  90. package/dist/destinations/google-analytics.js.map +1 -0
  91. package/dist/destinations/google-consent.d.ts +62 -0
  92. package/dist/destinations/google-consent.d.ts.map +1 -0
  93. package/dist/destinations/google-consent.js +109 -0
  94. package/dist/destinations/google-consent.js.map +1 -0
  95. package/dist/destinations/meta.d.ts +63 -0
  96. package/dist/destinations/meta.d.ts.map +1 -0
  97. package/dist/destinations/meta.js +44 -0
  98. package/dist/destinations/meta.js.map +1 -0
  99. package/dist/destinations/microsoft-uet.d.ts +56 -0
  100. package/dist/destinations/microsoft-uet.d.ts.map +1 -0
  101. package/dist/destinations/microsoft-uet.js +41 -0
  102. package/dist/destinations/microsoft-uet.js.map +1 -0
  103. package/dist/destinations/shared.d.ts +18 -0
  104. package/dist/destinations/shared.d.ts.map +1 -0
  105. package/dist/destinations/shared.js +19 -0
  106. package/dist/destinations/shared.js.map +1 -0
  107. package/dist/destinations/tiktok.d.ts +55 -0
  108. package/dist/destinations/tiktok.d.ts.map +1 -0
  109. package/dist/destinations/tiktok.js +40 -0
  110. package/dist/destinations/tiktok.js.map +1 -0
  111. package/dist/destinations/vercel-analytics.d.ts +25 -0
  112. package/dist/destinations/vercel-analytics.d.ts.map +1 -0
  113. package/dist/destinations/vercel-analytics.js +23 -0
  114. package/dist/destinations/vercel-analytics.js.map +1 -0
  115. package/dist/index.d.ts +64 -0
  116. package/dist/index.d.ts.map +1 -0
  117. package/dist/index.js +41 -0
  118. package/dist/index.js.map +1 -0
  119. package/dist/react/consent-banner.d.ts +155 -0
  120. package/dist/react/consent-banner.d.ts.map +1 -0
  121. package/dist/react/consent-banner.js +171 -0
  122. package/dist/react/consent-banner.js.map +1 -0
  123. package/dist/react/gtag-consent-bootstrap.d.ts +17 -0
  124. package/dist/react/gtag-consent-bootstrap.d.ts.map +1 -0
  125. package/dist/react/gtag-consent-bootstrap.js +22 -0
  126. package/dist/react/gtag-consent-bootstrap.js.map +1 -0
  127. package/dist/react/use-consent.d.ts +42 -0
  128. package/dist/react/use-consent.d.ts.map +1 -0
  129. package/dist/react/use-consent.js +60 -0
  130. package/dist/react/use-consent.js.map +1 -0
  131. package/dist/react/use-google-consent-sync.d.ts +20 -0
  132. package/dist/react/use-google-consent-sync.d.ts.map +1 -0
  133. package/dist/react/use-google-consent-sync.js +22 -0
  134. package/dist/react/use-google-consent-sync.js.map +1 -0
  135. package/dist/react/use-initial-consent.d.ts +11 -0
  136. package/dist/react/use-initial-consent.d.ts.map +1 -0
  137. package/dist/react/use-initial-consent.js +18 -0
  138. package/dist/react/use-initial-consent.js.map +1 -0
  139. package/dist/server/anonymous-id-cookie.d.ts +67 -0
  140. package/dist/server/anonymous-id-cookie.d.ts.map +1 -0
  141. package/dist/server/anonymous-id-cookie.js +71 -0
  142. package/dist/server/anonymous-id-cookie.js.map +1 -0
  143. package/dist/server/consent-receipt-store.d.ts +56 -0
  144. package/dist/server/consent-receipt-store.d.ts.map +1 -0
  145. package/dist/server/consent-receipt-store.js +44 -0
  146. package/dist/server/consent-receipt-store.js.map +1 -0
  147. package/dist/server/consent-receipt.d.ts +41 -0
  148. package/dist/server/consent-receipt.d.ts.map +1 -0
  149. package/dist/server/consent-receipt.js +60 -0
  150. package/dist/server/consent-receipt.js.map +1 -0
  151. package/dist/server/initial-consent.d.ts +26 -0
  152. package/dist/server/initial-consent.d.ts.map +1 -0
  153. package/dist/server/initial-consent.js +31 -0
  154. package/dist/server/initial-consent.js.map +1 -0
  155. package/dist/server/measurement-protocol.d.ts +69 -0
  156. package/dist/server/measurement-protocol.d.ts.map +1 -0
  157. package/dist/server/measurement-protocol.js +61 -0
  158. package/dist/server/measurement-protocol.js.map +1 -0
  159. package/dist/server/region.d.ts +27 -0
  160. package/dist/server/region.d.ts.map +1 -0
  161. package/dist/server/region.js +69 -0
  162. package/dist/server/region.js.map +1 -0
  163. package/dist/server/user-deletion.d.ts +64 -0
  164. package/dist/server/user-deletion.d.ts.map +1 -0
  165. package/dist/server/user-deletion.js +54 -0
  166. package/dist/server/user-deletion.js.map +1 -0
  167. package/dist/tooling/import-protection.d.ts +19 -0
  168. package/dist/tooling/import-protection.d.ts.map +1 -0
  169. package/dist/tooling/import-protection.js +23 -0
  170. package/dist/tooling/import-protection.js.map +1 -0
  171. package/package.json +202 -107
  172. package/src/adapters/tanstack-start.ts +135 -0
  173. package/src/client/ad-framework-consent.ts +86 -0
  174. package/src/client/browser-cookie.ts +16 -0
  175. package/src/client/consent-runtime.ts +80 -0
  176. package/src/client/consent-storage.ts +31 -1
  177. package/src/client/consent-withdrawal.ts +32 -0
  178. package/src/client/cookie-anonymous-id.ts +112 -0
  179. package/src/client/create-client-tracker.ts +128 -86
  180. package/src/client/gpc.ts +4 -2
  181. package/src/client/initial-consent-store.ts +218 -0
  182. package/src/client/is-analytics-allowed.ts +43 -0
  183. package/src/client/server-persisted-anonymous-id.ts +102 -0
  184. package/src/core/consent-config.ts +27 -0
  185. package/src/core/consent-receipt.ts +115 -0
  186. package/src/core/consent.ts +164 -10
  187. package/src/core/cookie.ts +29 -0
  188. package/src/core/destination.ts +17 -8
  189. package/src/core/event-catalog.ts +29 -15
  190. package/src/core/event-id.ts +1 -2
  191. package/src/core/tracked-event.ts +4 -4
  192. package/src/css/consent.css +119 -0
  193. package/src/destinations/ad-consent.ts +29 -0
  194. package/src/destinations/google-analytics.ts +196 -133
  195. package/src/destinations/google-consent.ts +164 -0
  196. package/src/destinations/meta.ts +96 -0
  197. package/src/destinations/microsoft-uet.ts +86 -0
  198. package/src/destinations/shared.ts +45 -0
  199. package/src/destinations/tiktok.ts +85 -0
  200. package/src/destinations/vercel-analytics.ts +23 -24
  201. package/src/index.ts +165 -8
  202. package/src/react/consent-banner.tsx +308 -111
  203. package/src/react/gtag-consent-bootstrap.tsx +48 -0
  204. package/src/react/use-consent.ts +53 -45
  205. package/src/react/use-google-consent-sync.ts +38 -0
  206. package/src/react/use-initial-consent.ts +22 -0
  207. package/src/server/anonymous-id-cookie.ts +103 -0
  208. package/src/server/consent-receipt-store.ts +79 -0
  209. package/src/server/consent-receipt.ts +89 -0
  210. package/src/server/initial-consent.ts +46 -0
  211. package/src/server/measurement-protocol.ts +114 -0
  212. package/src/server/region.ts +22 -15
  213. package/src/server/user-deletion.ts +93 -0
  214. package/src/tooling/import-protection.ts +22 -0
  215. package/dist/client/consent-storage.mjs +0 -63
  216. package/dist/client/create-client-tracker.d.mts +0 -37
  217. package/dist/client/create-client-tracker.mjs +0 -66
  218. package/dist/client/gpc.d.mts +0 -10
  219. package/dist/client/gpc.mjs +0 -12
  220. package/dist/client/index.d.mts +0 -8
  221. package/dist/client/index.mjs +0 -8
  222. package/dist/client/lifecycle.d.mts +0 -23
  223. package/dist/client/lifecycle.mjs +0 -30
  224. package/dist/client/local-storage.d.mts +0 -13
  225. package/dist/client/local-storage.mjs +0 -31
  226. package/dist/client/queue.d.mts +0 -49
  227. package/dist/client/queue.mjs +0 -71
  228. package/dist/client/router.d.mts +0 -30
  229. package/dist/client/router.mjs +0 -17
  230. package/dist/core/consent.d.mts +0 -89
  231. package/dist/core/consent.mjs +0 -57
  232. package/dist/core/destination.d.mts +0 -23
  233. package/dist/core/destination.mjs +0 -1
  234. package/dist/core/event-catalog.d.mts +0 -36
  235. package/dist/core/event-catalog.mjs +0 -12
  236. package/dist/core/event-id.d.mts +0 -10
  237. package/dist/core/event-id.mjs +0 -12
  238. package/dist/core/index.d.mts +0 -6
  239. package/dist/core/index.mjs +0 -4
  240. package/dist/core/tracked-event.d.mts +0 -17
  241. package/dist/core/tracked-event.mjs +0 -1
  242. package/dist/destinations/ga4-measurement-protocol.d.mts +0 -54
  243. package/dist/destinations/ga4-measurement-protocol.mjs +0 -89
  244. package/dist/destinations/google-analytics.d.mts +0 -98
  245. package/dist/destinations/google-analytics.mjs +0 -126
  246. package/dist/destinations/http-destination.d.mts +0 -20
  247. package/dist/destinations/http-destination.mjs +0 -25
  248. package/dist/destinations/index.d.mts +0 -5
  249. package/dist/destinations/index.mjs +0 -5
  250. package/dist/destinations/vercel-analytics.d.mts +0 -13
  251. package/dist/destinations/vercel-analytics.mjs +0 -30
  252. package/dist/index.d.mts +0 -6
  253. package/dist/index.mjs +0 -4
  254. package/dist/react/consent-banner.d.mts +0 -75
  255. package/dist/react/consent-banner.mjs +0 -114
  256. package/dist/react/index.d.mts +0 -3
  257. package/dist/react/index.mjs +0 -3
  258. package/dist/react/use-consent.d.mts +0 -49
  259. package/dist/react/use-consent.mjs +0 -54
  260. package/dist/server/create-server-tracker.d.mts +0 -42
  261. package/dist/server/create-server-tracker.mjs +0 -67
  262. package/dist/server/index.d.mts +0 -3
  263. package/dist/server/index.mjs +0 -3
  264. package/dist/server/region.d.mts +0 -20
  265. package/dist/server/region.mjs +0 -56
  266. package/src/client/index.ts +0 -17
  267. package/src/client/lifecycle.ts +0 -50
  268. package/src/client/local-storage.ts +0 -44
  269. package/src/client/queue.ts +0 -117
  270. package/src/client/router.ts +0 -37
  271. package/src/core/index.ts +0 -24
  272. package/src/destinations/ga4-measurement-protocol.ts +0 -166
  273. package/src/destinations/http-destination.ts +0 -33
  274. package/src/destinations/index.ts +0 -20
  275. package/src/react/index.ts +0 -5
  276. package/src/server/create-server-tracker.ts +0 -128
  277. package/src/server/index.ts +0 -4
@@ -0,0 +1,86 @@
1
+ import type { ConsentCategory, ConsentDecision } from "#/core/consent";
2
+
3
+ /**
4
+ * TCF/GPP interop reconciler (spec-ad-consent-frameworks): the system **reads** an external
5
+ * CMP and reconciles it with the native `{ ads, analytics }` decision — it never becomes a
6
+ * CMP, mints TC/GPP strings, or hard-codes TCF purpose ids or the Google vendor id (that
7
+ * mapping is ad-ops policy, so the caller derives `CmpConsentSignal` and passes it in).
8
+ */
9
+
10
+ /**
11
+ * Liveness of a detected CMP. `"out-of-scope"` is TCF `gdprApplies === false` / no applicable
12
+ * GPP section — the framework does not govern this user, so native consent stands.
13
+ *
14
+ * @since 1.0.0-canary.7
15
+ */
16
+ export type CmpStatus = "loading" | "out-of-scope" | "ready";
17
+
18
+ /**
19
+ * A CMP's governance over the native decision, already derived from TCData/GPP by ad-ops policy.
20
+ *
21
+ * @since 1.0.0-canary.7
22
+ */
23
+ export interface CmpConsentSignal {
24
+ /** Per-governed-category grant, read once `status` is `"ready"`. */
25
+ decision?: Partial<ConsentDecision> | undefined;
26
+ /** Categories this CMP governs in the current scope — the resolver overrides only these. */
27
+ governs: ReadonlyArray<ConsentCategory>;
28
+ status: CmpStatus;
29
+ }
30
+
31
+ /**
32
+ * @since 1.0.0-canary.7
33
+ */
34
+ export interface ReconcileAdFrameworkConsentOptions {
35
+ /** The live CMP signal, or omitted when no CMP is present (the resolver is then inert). */
36
+ cmp?: CmpConsentSignal | undefined;
37
+ /** Native GPC — can only tighten `ads`, never loosen a CMP grant. */
38
+ hasGlobalPrivacyControlSignal: boolean;
39
+ /** The stored/default decision that stands wherever no CMP governs. */
40
+ native: ConsentDecision;
41
+ }
42
+
43
+ /**
44
+ * Reconciles native consent with a CMP source of truth per spec-ad-consent-frameworks §3:
45
+ * a governing CMP overrides its categories (fail-closed to denied while loading); a missing
46
+ * or out-of-scope CMP leaves native standing; GPC always tightens `ads` last.
47
+ *
48
+ * @since 1.0.0-canary.7
49
+ */
50
+ export function reconcileAdFrameworkConsent(options: ReconcileAdFrameworkConsentOptions): ConsentDecision {
51
+ const result: ConsentDecision = { ...options.native };
52
+ const { cmp } = options;
53
+
54
+ // A governing CMP overrides only the categories it governs; no CMP / out-of-scope leaves native.
55
+ if (cmp && cmp.status !== "out-of-scope") {
56
+ for (const category of cmp.governs) {
57
+ // Fail closed until the CMP resolves; otherwise the CMP value wins for its categories.
58
+ result[category] = cmp.status === "loading" ? false : (cmp.decision?.[category] ?? false);
59
+ }
60
+ }
61
+
62
+ // GPC can only tighten `ads` — applied last so it wins over any CMP grant.
63
+ if (options.hasGlobalPrivacyControlSignal) {
64
+ result.ads = false;
65
+ }
66
+
67
+ return result;
68
+ }
69
+
70
+ /**
71
+ * Detects a TCF CMP without reading it — `typeof __tcfapi === "function"` (spec §3).
72
+ *
73
+ * @since 1.0.0-canary.7
74
+ */
75
+ export function hasTcfApi(scope: { __tcfapi?: unknown } = globalThis as { __tcfapi?: unknown }): boolean {
76
+ return typeof scope.__tcfapi === "function";
77
+ }
78
+
79
+ /**
80
+ * Detects a GPP CMP without reading it — `typeof __gpp === "function"` (spec §3).
81
+ *
82
+ * @since 1.0.0-canary.7
83
+ */
84
+ export function hasGppApi(scope: { __gpp?: unknown } = globalThis as { __gpp?: unknown }): boolean {
85
+ return typeof scope.__gpp === "function";
86
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Shared `document.cookie` writer for the client-side cookie lanes (anonymous id, consent
3
+ * mirror): Secure on HTTPS so values never ride plain HTTP, SameSite=Lax, never HttpOnly —
4
+ * the client must read its own cookies back. A no-op without a `document` (SSR).
5
+ *
6
+ * @since 1.0.0-canary.6
7
+ */
8
+ export function writeBrowserCookie(cookieName: string, value: string, maxAgeSeconds: number): void {
9
+ if (typeof document === "undefined") {
10
+ return;
11
+ }
12
+
13
+ const secure = globalThis.location.protocol === "https:" ? "; secure" : "";
14
+
15
+ document.cookie = `${cookieName}=${value}; path=/; max-age=${String(maxAgeSeconds)}; samesite=lax${secure}`;
16
+ }
@@ -0,0 +1,80 @@
1
+ import { createLocalStorageConsentStorage } from "#/client/consent-storage";
2
+ import { hasGlobalPrivacyControlSignal } from "#/client/gpc";
3
+ import type { InitialConsentStore } from "#/client/initial-consent-store";
4
+ import { createInitialConsentStore } from "#/client/initial-consent-store";
5
+ import { createIsAnalyticsAllowed } from "#/client/is-analytics-allowed";
6
+ import type { ConsentStorage, InitialConsent } from "#/core/consent";
7
+ import type { ConsentConfig } from "#/core/consent-config";
8
+
9
+ /**
10
+ * @since 1.0.0-canary.6
11
+ */
12
+ export interface ConsentRuntimeOptions {
13
+ config: ConsentConfig;
14
+ /** Re-read per event so a GPC change applies without recreating the runtime. Defaults to the real navigator signal. */
15
+ hasGlobalPrivacyControlSignal?: (() => boolean) | undefined;
16
+ /**
17
+ * `sessionStorage` key caching the resolved region default, so only the first page
18
+ * load of a session pays the round trip — omit to resolve once per page load instead.
19
+ */
20
+ initialConsentSessionStorageKey?: string | undefined;
21
+ /**
22
+ * The per-visitor server lane — typically a server function wrapping
23
+ * `resolveInitialConsentFromRequest`. Shared/CDN-cached HTML can carry nothing
24
+ * region-specific, so this is the only place the region-correct default may come from.
25
+ */
26
+ resolveInitialConsent: () => Promise<InitialConsent>;
27
+ }
28
+
29
+ /**
30
+ * The live client-side consent instances, all derived from one `ConsentConfig` — create
31
+ * it once at module scope and every surface (banner hook, tracker gate, privacy page)
32
+ * shares the same storage and region resolution by construction.
33
+ *
34
+ * @since 1.0.0-canary.6
35
+ */
36
+ export interface ConsentRuntime {
37
+ config: ConsentConfig;
38
+ /**
39
+ * Kicks off region resolution — single-flight and idempotent. Call it early (e.g. at
40
+ * router creation, window-guarded) so the round trip overlaps hydration instead of
41
+ * waiting for the first mount effect.
42
+ */
43
+ ensureInitialConsentResolved: () => void;
44
+ /** Feed to `useInitialConsent` for the reactive region default. */
45
+ initialConsentStore: InitialConsentStore;
46
+ /** Non-React gate for `createClientTracker` — the same rule `useConsent` applies. */
47
+ isAnalyticsAllowed: () => boolean;
48
+ /** The one `ConsentStorage` instance every surface must share. */
49
+ storage: ConsentStorage;
50
+ }
51
+
52
+ /**
53
+ * Composes the client half of the consent lane from a single `ConsentConfig`:
54
+ * `localStorage`-backed decision storage, the initial-consent store over the app's
55
+ * server lane, and the non-React analytics gate wired to that store's resolved mode.
56
+ *
57
+ * @since 1.0.0-canary.6
58
+ */
59
+ export function createConsentRuntime(options: ConsentRuntimeOptions): ConsentRuntime {
60
+ const { config } = options;
61
+ const storage = createLocalStorageConsentStorage(config.storageKey);
62
+ const initialConsentStore = createInitialConsentStore({
63
+ resolve: options.resolveInitialConsent,
64
+ sessionStorageKey: options.initialConsentSessionStorageKey,
65
+ });
66
+ const isAnalyticsAllowed = createIsAnalyticsAllowed({
67
+ config,
68
+ getMode: () => initialConsentStore.getSnapshot().initialConsent.mode,
69
+ hasGlobalPrivacyControlSignal: options.hasGlobalPrivacyControlSignal ?? hasGlobalPrivacyControlSignal,
70
+ storage,
71
+ });
72
+
73
+ return {
74
+ config,
75
+ ensureInitialConsentResolved: initialConsentStore.ensureResolved,
76
+ initialConsentStore,
77
+ isAnalyticsAllowed,
78
+ storage,
79
+ };
80
+ }
@@ -1,4 +1,5 @@
1
1
  import type { ConsentRecord, ConsentStorage } from "#/core/consent";
2
+ import { isConsentRecord } from "#/core/consent";
2
3
 
3
4
  /**
4
5
  * `localStorage`-backed consent storage. Corrupt state, a private-mode/quota error, or no
@@ -6,6 +7,11 @@ import type { ConsentRecord, ConsentStorage } from "#/core/consent";
6
7
  * for the session instead of re-prompting in a loop. `subscribe` fires for same-tab
7
8
  * writes and, via the `storage` event, for decisions made in other tabs.
8
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
+ *
9
15
  * @remarks
10
16
  * The record persists as plain `JSON.stringify(ConsentRecord)` — a stable contract, so
11
17
  * pre-hydration inline scripts (e.g. a Consent Mode default bootstrap) can read the
@@ -16,6 +22,9 @@ import type { ConsentRecord, ConsentStorage } from "#/core/consent";
16
22
  export function createLocalStorageConsentStorage(storageKey: string): ConsentStorage {
17
23
  const listeners = new Set<() => void>();
18
24
  let memoryRecord: ConsentRecord | undefined;
25
+ // Keyed by the raw string so ANY write path (save(), another tab, dev tools) is caught
26
+ // by a cheap string compare — parse + validate re-run only when the value changed.
27
+ let cache: { raw: string | null; record: ConsentRecord | undefined } | undefined;
19
28
 
20
29
  function notify(): void {
21
30
  for (const listener of listeners) {
@@ -30,6 +39,7 @@ export function createLocalStorageConsentStorage(storageKey: string): ConsentSto
30
39
  }
31
40
 
32
41
  memoryRecord = undefined;
42
+ cache = undefined;
33
43
 
34
44
  try {
35
45
  globalThis.window.localStorage.removeItem(storageKey);
@@ -47,8 +57,26 @@ export function createLocalStorageConsentStorage(storageKey: string): ConsentSto
47
57
  try {
48
58
  const raw = globalThis.window.localStorage.getItem(storageKey);
49
59
 
50
- return raw ? (JSON.parse(raw) as ConsentRecord) : memoryRecord;
60
+ if (cache && raw === cache.raw) {
61
+ return cache.record;
62
+ }
63
+
64
+ let record: ConsentRecord | undefined;
65
+
66
+ if (raw) {
67
+ const parsed: unknown = JSON.parse(raw);
68
+
69
+ // Drop malformed records at the source — mirrors the offline-queue storage guard.
70
+ record = isConsentRecord(parsed) ? parsed : memoryRecord;
71
+ } else {
72
+ record = memoryRecord;
73
+ }
74
+
75
+ cache = { raw, record };
76
+
77
+ return record;
51
78
  } catch {
79
+ // Storage blocked — never seed the cache off an error path.
52
80
  return memoryRecord;
53
81
  }
54
82
  },
@@ -57,6 +85,8 @@ export function createLocalStorageConsentStorage(storageKey: string): ConsentSto
57
85
  return;
58
86
  }
59
87
 
88
+ cache = undefined;
89
+
60
90
  try {
61
91
  globalThis.window.localStorage.setItem(storageKey, JSON.stringify(record));
62
92
  // localStorage is authoritative now — a lingering memory copy would shadow an
@@ -0,0 +1,32 @@
1
+ import type { ConsentDecision } from "#/core/consent";
2
+
3
+ /**
4
+ * @since 1.0.0-canary.6
5
+ */
6
+ export interface ConsentWithdrawalHandlerOptions {
7
+ /** Forget the cookie-backed visitor id when analytics is denied. */
8
+ clearAnonymousId?: (() => void) | undefined;
9
+ /** Expire Google's `_ga` / `_ga_*` cookies when analytics is denied. */
10
+ clearGoogleAnalyticsCookies?: (() => void) | undefined;
11
+ }
12
+
13
+ /**
14
+ * `useConsent({ onDecision })` handler that clears first-party tracking state when the
15
+ * visitor denies (or withdraws) analytics. Grant paths are a no-op.
16
+ *
17
+ * @since 1.0.0-canary.6
18
+ */
19
+ export function createConsentWithdrawalHandler(
20
+ options: ConsentWithdrawalHandlerOptions,
21
+ ): (decision: ConsentDecision) => void {
22
+ const { clearAnonymousId, clearGoogleAnalyticsCookies } = options;
23
+
24
+ return (decision: ConsentDecision): void => {
25
+ if (decision.analytics) {
26
+ return;
27
+ }
28
+
29
+ clearAnonymousId?.();
30
+ clearGoogleAnalyticsCookies?.();
31
+ };
32
+ }
@@ -0,0 +1,112 @@
1
+ import { writeBrowserCookie } from "#/client/browser-cookie";
2
+ import { ONE_YEAR_IN_SECONDS, readCookieValue } from "#/core/cookie";
3
+
4
+ /**
5
+ * @since 1.0.0-canary.6
6
+ */
7
+ export interface CookieAnonymousIdOptions {
8
+ /** Cookie name — must not collide with another cookie on the domain. */
9
+ cookieName: string;
10
+ /** How long the id survives a return visit. Defaults to one year. */
11
+ maxAgeSeconds?: number | undefined;
12
+ }
13
+
14
+ /**
15
+ * @since 1.0.0-canary.6
16
+ */
17
+ export interface CookieAnonymousId {
18
+ /** Expires the cookie — call when the visitor withdraws tracking consent. */
19
+ clear: () => void;
20
+ /**
21
+ * The existing id **without minting one** — `undefined` when the visitor has none yet.
22
+ * Use this to stamp a receipt/decision with the id that already identifies the visitor,
23
+ * rather than re-reading the cookie or minting a throwaway that never correlates.
24
+ */
25
+ current: () => string | undefined;
26
+ /** The existing id, or a freshly minted and persisted one. */
27
+ getOrCreate: () => string;
28
+ /**
29
+ * Rolls an *existing* id's expiry forward without ever minting one — safe to call on
30
+ * page load for returning consented visitors (the ITP-refresh path), a no-op for
31
+ * visitors who never got an id.
32
+ */
33
+ refresh: () => void;
34
+ }
35
+
36
+ /**
37
+ * A `document.cookie`-backed anonymous id — not `localStorage`-only, so a server-owned
38
+ * event can read the same id from the request and correlate to this visitor. Pass
39
+ * `getOrCreate` (not the result of calling it) as `ClientTrackerOptions.anonymousId`:
40
+ * it's invoked lazily, so the cookie is minted only once an event is actually allowed to
41
+ * send, never as an import-time side effect.
42
+ *
43
+ * @since 1.0.0-canary.6
44
+ */
45
+ export function createCookieAnonymousId(options: CookieAnonymousIdOptions): CookieAnonymousId {
46
+ const { cookieName, maxAgeSeconds = ONE_YEAR_IN_SECONDS } = options;
47
+ // Cached after the first getOrCreate() so a callback invoked once per tracked event
48
+ // doesn't re-parse the whole cookie header every time — cleared alongside the cookie.
49
+ let cachedId: string | undefined;
50
+
51
+ return {
52
+ clear(): void {
53
+ cachedId = undefined;
54
+
55
+ if (typeof document === "undefined") {
56
+ return;
57
+ }
58
+
59
+ writeBrowserCookie(cookieName, "", 0);
60
+ },
61
+ current(): string | undefined {
62
+ // Prefer the live cookie — another tab may have minted or cleared it since this
63
+ // instance last cached — falling back to the cache only when off the DOM (SSR).
64
+ if (typeof document === "undefined") {
65
+ return cachedId;
66
+ }
67
+
68
+ const existing = readCookieValue(document.cookie, cookieName);
69
+
70
+ cachedId = existing;
71
+
72
+ return existing;
73
+ },
74
+ getOrCreate(): string {
75
+ if (typeof document === "undefined") {
76
+ return cachedId ?? crypto.randomUUID();
77
+ }
78
+
79
+ const existing = readCookieValue(document.cookie, cookieName);
80
+
81
+ // Prefer the live cookie over `cachedId` — another tab's withdrawal expires the
82
+ // cookie without calling this instance's `clear()`, and a re-grant must not revive
83
+ // the pre-withdrawal identity from memory.
84
+ if (existing) {
85
+ cachedId = existing;
86
+
87
+ return existing;
88
+ }
89
+
90
+ cachedId = undefined;
91
+
92
+ const id = crypto.randomUUID();
93
+
94
+ writeBrowserCookie(cookieName, id, maxAgeSeconds);
95
+ cachedId = id;
96
+
97
+ return id;
98
+ },
99
+ refresh(): void {
100
+ if (typeof document === "undefined") {
101
+ return;
102
+ }
103
+
104
+ const existing = readCookieValue(document.cookie, cookieName);
105
+
106
+ if (existing) {
107
+ cachedId = existing;
108
+ writeBrowserCookie(cookieName, existing, maxAgeSeconds);
109
+ }
110
+ },
111
+ };
112
+ }
@@ -1,38 +1,109 @@
1
- import type { z } from "zod";
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
2
 
3
- import { EventQueue, type EventQueueStorage } from "#/client/queue";
4
3
  import type { Destination } from "#/core/destination";
5
- import type { EventCatalog, EventsOf } from "#/core/event-catalog";
4
+ import type { EventCatalog } from "#/core/event-catalog";
5
+ import { assertValidEventProperties } from "#/core/event-catalog";
6
6
  import { generateEventId } from "#/core/event-id";
7
7
  import type { TrackedEvent } from "#/core/tracked-event";
8
8
 
9
+ /**
10
+ * Context handed to {@link ClientTrackerOptions.onDeliveryError} for one failed delivery.
11
+ *
12
+ * @since 1.0.0-canary.7
13
+ */
14
+ export interface DeliveryErrorContext {
15
+ destination: Destination;
16
+ error: unknown;
17
+ event: TrackedEvent;
18
+ }
19
+
20
+ /**
21
+ * `Destination.send` is typed to always return a `Promise`, but that's unenforceable at
22
+ * runtime for a third-party/plain-JS destination — one that ignores the contract and
23
+ * throws synchronously (or returns a non-`Promise`) must still never break the tracked
24
+ * interaction. `Promise.resolve(...)` normalizes a non-`Promise` return; the outer
25
+ * try/catch is the only thing that can catch a throw that happens before `send` ever
26
+ * gets to return anything. Both failure shapes surface through `onDeliveryError` (itself
27
+ * guarded — an observer that throws must not break the interaction either).
28
+ */
29
+ function sendToDestination(
30
+ destination: Destination,
31
+ event: TrackedEvent,
32
+ onDeliveryError?: (context: DeliveryErrorContext) => void,
33
+ ): void {
34
+ const report = (error: unknown): void => {
35
+ if (!onDeliveryError) {
36
+ return;
37
+ }
38
+
39
+ try {
40
+ onDeliveryError({ destination, error, event });
41
+ } catch {
42
+ /* an observer must never break the tracked interaction */
43
+ }
44
+ };
45
+
46
+ try {
47
+ void Promise.resolve(destination.send(event)).catch(report);
48
+ } catch (error) {
49
+ report(error);
50
+ }
51
+ }
52
+
53
+ /** Invokes a destination's erasure once, swallowing both failure shapes — DSR must never break the flow. */
54
+ function eraseInDestination(destination: Destination, id: string): void {
55
+ try {
56
+ void Promise.resolve(destination.onErasure?.(id)).catch(() => {
57
+ /* an erasure failure must never break the withdrawal flow */
58
+ });
59
+ } catch {
60
+ /* a sync throw must never break the withdrawal flow */
61
+ }
62
+ }
63
+
9
64
  /**
10
65
  * @since 0.5.0-canary.4
11
66
  */
12
67
  export interface ClientTrackerOptions<Catalog extends EventCatalog> {
13
- anonymousId: string;
68
+ /** Invoked per allowed event — defer creating the id (e.g. minting a cookie) until an event is actually allowed to send, never as an import-time side effect. */
69
+ anonymousId: () => string;
14
70
  catalog: Catalog;
15
71
  destinations: Array<Destination>;
16
- maxQueueSize?: number;
17
- maxRetries?: number;
18
- storage: EventQueueStorage;
72
+ /**
73
+ * Consulted before every event — while it returns `false`, only
74
+ * `consentRequirement: "exempt"` destinations still receive events, stripped of
75
+ * identifiers. Omit to always track.
76
+ */
77
+ isAnalyticsAllowed?: (() => boolean) | undefined;
78
+ /**
79
+ * Consulted before an `exempt` destination receives an event while the gate is closed.
80
+ * ePrivacy audience-measurement exemption is jurisdiction-dependent (spec-destinations
81
+ * §2), so it MUST be gateable per region rather than assumed global — return `false`
82
+ * where exemption is not defensible and even exempt sinks are withheld. Omit to treat
83
+ * exempt destinations as exempt everywhere.
84
+ */
85
+ isExemptionAllowed?: (() => boolean) | undefined;
86
+ /**
87
+ * Notified once per failed delivery (a destination throwing or rejecting) so a consumer
88
+ * can meter the failure — the tracker still swallows it so tracking never breaks the
89
+ * interaction. Wire it to a monitor in production.
90
+ */
91
+ onDeliveryError?: ((context: DeliveryErrorContext) => void) | undefined;
19
92
  }
20
93
 
21
94
  /**
22
95
  * @since 0.5.0-canary.4
23
96
  */
24
97
  export interface ClientTracker<Catalog extends EventCatalog> {
25
- /** Drops every pending event without sending it — call this when consent is revoked. */
26
- clear: () => void;
27
- flush: () => Promise<void>;
28
- /** Synchronous, best-effort flush via `navigator.sendBeacon` — for page unload only. */
29
- flushWithBeacon: (endpoint: string) => void;
30
- group: (groupId: string, traits?: Record<string, unknown>) => void;
31
- identify: (userId: string, traits?: Record<string, unknown>) => void;
32
- page: (name?: string, props?: Record<string, unknown>) => void;
33
- track: <Name extends keyof EventsOf<Catalog, "client">>(
98
+ /**
99
+ * Runs each destination's {@link Destination.onErasure} once on withdrawal (spec-data-subject-rights
100
+ * DSR-V2), passing the subject id to erase. Failures are swallowed so a destination that
101
+ * throws never breaks the withdrawal flow.
102
+ */
103
+ erase: (id: string) => void;
104
+ track: <Name extends keyof Catalog & string>(
34
105
  name: Name,
35
- props: z.infer<EventsOf<Catalog, "client">[Name]["schema"]>,
106
+ properties: StandardSchemaV1.InferOutput<Catalog[Name]["schema"]>,
36
107
  ) => void;
37
108
  }
38
109
 
@@ -42,85 +113,56 @@ export interface ClientTracker<Catalog extends EventCatalog> {
42
113
  export function createClientTracker<Catalog extends EventCatalog>(
43
114
  options: ClientTrackerOptions<Catalog>,
44
115
  ): ClientTracker<Catalog> {
45
- // SDK-backed destinations own their batching/unload delivery — routing them through
46
- // the queue would only delay events and replay stale ones next session.
47
- const immediateDestinations = options.destinations.filter((destination) => destination.delivery === "immediate");
48
- const queuedDestinations = options.destinations.filter((destination) => destination.delivery !== "immediate");
49
- const queue = new EventQueue({
50
- destinations: queuedDestinations,
51
- maxQueueSize: options.maxQueueSize,
52
- maxRetries: options.maxRetries,
53
- storage: options.storage,
54
- });
55
- let userId: string | undefined;
56
-
57
- function enqueue(name: string, props: Record<string, unknown>): void {
58
- const envelope: TrackedEvent = {
59
- anonymousId: options.anonymousId,
60
- eventId: generateEventId(),
61
- name,
62
- owner: "client",
63
- props,
64
- timestamp: Date.now(),
65
- ...(userId === undefined ? {} : { userId }),
66
- };
67
-
68
- for (const destination of immediateDestinations) {
69
- try {
70
- void Promise.resolve(destination.send(envelope)).catch(() => {
71
- /* an immediate destination owns its transport — no retry path here */
72
- });
73
- } catch {
74
- /* a sync throw must never break the tracked interaction */
75
- }
76
- }
77
-
78
- // Still enqueued unconditionally — the queue also feeds `flushWithBeacon`, which
79
- // ships raw envelopes to a custom endpoint independently of any destination.
80
- queue.enqueue(envelope);
81
- }
116
+ // The exempt lane only carries what a cookieless sink may see — identifier-free counts.
117
+ const exemptDestinations = options.destinations.filter((destination) => destination.consentRequirement === "exempt");
82
118
 
83
119
  return {
84
- clear: () => {
85
- queue.clear();
120
+ erase(id) {
121
+ for (const destination of options.destinations) {
122
+ eraseInDestination(destination, id);
123
+ }
86
124
  },
87
- flush: () => queue.flush(),
88
- flushWithBeacon(endpoint) {
89
- const events = queue.drain();
125
+ track(name, properties) {
126
+ // noUncheckedIndexedAccess types this as possibly undefined; the check also guards
127
+ // callers who bypass the catalog key type with an `as` cast.
128
+ const definition = options.catalog[name];
90
129
 
91
- if (events.length === 0) {
92
- return;
130
+ if (!definition) {
131
+ throw new Error(`Unknown event: ${String(name)}`);
93
132
  }
94
133
 
95
- const delivered = navigator.sendBeacon(endpoint, JSON.stringify(events));
134
+ // Forward the parsed output (not the raw input) so unknown keys cannot ride along.
135
+ const validatedProperties = assertValidEventProperties(definition.schema, name, properties);
96
136
 
97
- if (!delivered) {
98
- for (const event of events) {
99
- queue.enqueue(event);
100
- }
101
- }
102
- },
103
- group(groupId, traits = {}) {
104
- enqueue("$group", { groupId, ...traits });
105
- },
106
- identify(id, traits = {}) {
107
- userId = id;
108
- enqueue("$identify", traits);
109
- },
110
- page(name, props = {}) {
111
- enqueue("$page_viewed", name === undefined ? props : { name, ...props });
112
- },
113
- track(name, props) {
114
- // noUncheckedIndexedAccess types this as possibly undefined; the owner check also
115
- // guards callers who bypass the EventsOf filter with an `as` cast.
116
- const definition = options.catalog[name];
137
+ // The gate runs per event (not at creation) so a consent change mid-session applies immediately.
138
+ const isAllowed = options.isAnalyticsAllowed?.() !== false;
117
139
 
118
- if (!definition || definition.owner !== "client") {
119
- throw new Error(`Unknown client-owned event: ${String(name)}`);
140
+ // While gated, exempt sinks still receive identifier-free events — but only where
141
+ // exemption is defensible (spec-destinations §2); a `false` here withholds them too.
142
+ const activeDestinations = isAllowed
143
+ ? options.destinations
144
+ : options.isExemptionAllowed?.() === false
145
+ ? []
146
+ : exemptDestinations;
147
+
148
+ if (activeDestinations.length === 0) {
149
+ return;
120
150
  }
121
151
 
122
- definition.schema.parse(props);
123
- enqueue(name as string, props as Record<string, unknown>);
152
+ const event: TrackedEvent = {
153
+ // Gated events ship identifier-free: no anonymousId is resolved, so none is ever
154
+ // minted as a side effect.
155
+ anonymousId: isAllowed ? options.anonymousId() : "",
156
+ eventId: generateEventId(),
157
+ name,
158
+ properties: validatedProperties as Record<string, unknown>,
159
+ timestamp: Date.now(),
160
+ type: "track",
161
+ };
162
+
163
+ for (const destination of activeDestinations) {
164
+ sendToDestination(destination, event, options.onDeliveryError);
165
+ }
124
166
  },
125
167
  };
126
168
  }
package/src/client/gpc.ts CHANGED
@@ -1,13 +1,15 @@
1
1
  interface NavigatorWithGpc extends Navigator {
2
- globalPrivacyControl?: boolean;
2
+ globalPrivacyControl?: boolean | undefined;
3
3
  }
4
4
 
5
5
  /**
6
6
  * Global Privacy Control isn't in lib.dom yet, hence the local interface extension.
7
7
  * CCPA/CPRA requires honoring this as an opt-out signal even under the opt-out default.
8
+ * Guarded so SSR renders (where the module is reachable) read `false`, not a crash on
9
+ * runtimes without a global `navigator`.
8
10
  *
9
11
  * @since 0.5.0-canary.4
10
12
  */
11
13
  export function hasGlobalPrivacyControlSignal(): boolean {
12
- return (navigator as NavigatorWithGpc).globalPrivacyControl === true;
14
+ return typeof navigator !== "undefined" && (navigator as NavigatorWithGpc).globalPrivacyControl === true;
13
15
  }