@codefast/tracking 0.5.0-canary.5 → 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 (276) hide show
  1. package/CHANGELOG.md +467 -0
  2. package/README.md +176 -126
  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 +201 -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/destinations/ad-consent.ts +29 -0
  193. package/src/destinations/google-analytics.ts +196 -133
  194. package/src/destinations/google-consent.ts +164 -0
  195. package/src/destinations/meta.ts +96 -0
  196. package/src/destinations/microsoft-uet.ts +86 -0
  197. package/src/destinations/shared.ts +45 -0
  198. package/src/destinations/tiktok.ts +85 -0
  199. package/src/destinations/vercel-analytics.ts +23 -24
  200. package/src/index.ts +165 -8
  201. package/src/react/consent-banner.tsx +40 -14
  202. package/src/react/gtag-consent-bootstrap.tsx +48 -0
  203. package/src/react/use-consent.ts +53 -45
  204. package/src/react/use-google-consent-sync.ts +38 -0
  205. package/src/react/use-initial-consent.ts +22 -0
  206. package/src/server/anonymous-id-cookie.ts +103 -0
  207. package/src/server/consent-receipt-store.ts +79 -0
  208. package/src/server/consent-receipt.ts +89 -0
  209. package/src/server/initial-consent.ts +46 -0
  210. package/src/server/measurement-protocol.ts +114 -0
  211. package/src/server/region.ts +22 -15
  212. package/src/server/user-deletion.ts +93 -0
  213. package/src/tooling/import-protection.ts +22 -0
  214. package/dist/client/consent-storage.mjs +0 -63
  215. package/dist/client/create-client-tracker.d.mts +0 -37
  216. package/dist/client/create-client-tracker.mjs +0 -66
  217. package/dist/client/gpc.d.mts +0 -10
  218. package/dist/client/gpc.mjs +0 -12
  219. package/dist/client/index.d.mts +0 -8
  220. package/dist/client/index.mjs +0 -8
  221. package/dist/client/lifecycle.d.mts +0 -23
  222. package/dist/client/lifecycle.mjs +0 -30
  223. package/dist/client/local-storage.d.mts +0 -13
  224. package/dist/client/local-storage.mjs +0 -31
  225. package/dist/client/queue.d.mts +0 -49
  226. package/dist/client/queue.mjs +0 -71
  227. package/dist/client/router.d.mts +0 -30
  228. package/dist/client/router.mjs +0 -17
  229. package/dist/core/consent.d.mts +0 -89
  230. package/dist/core/consent.mjs +0 -57
  231. package/dist/core/destination.d.mts +0 -23
  232. package/dist/core/destination.mjs +0 -1
  233. package/dist/core/event-catalog.d.mts +0 -36
  234. package/dist/core/event-catalog.mjs +0 -12
  235. package/dist/core/event-id.d.mts +0 -10
  236. package/dist/core/event-id.mjs +0 -12
  237. package/dist/core/index.d.mts +0 -6
  238. package/dist/core/index.mjs +0 -4
  239. package/dist/core/tracked-event.d.mts +0 -17
  240. package/dist/core/tracked-event.mjs +0 -1
  241. package/dist/destinations/ga4-measurement-protocol.d.mts +0 -54
  242. package/dist/destinations/ga4-measurement-protocol.mjs +0 -89
  243. package/dist/destinations/google-analytics.d.mts +0 -98
  244. package/dist/destinations/google-analytics.mjs +0 -126
  245. package/dist/destinations/http-destination.d.mts +0 -20
  246. package/dist/destinations/http-destination.mjs +0 -25
  247. package/dist/destinations/index.d.mts +0 -5
  248. package/dist/destinations/index.mjs +0 -5
  249. package/dist/destinations/vercel-analytics.d.mts +0 -13
  250. package/dist/destinations/vercel-analytics.mjs +0 -30
  251. package/dist/index.d.mts +0 -6
  252. package/dist/index.mjs +0 -4
  253. package/dist/react/consent-banner.d.mts +0 -163
  254. package/dist/react/consent-banner.mjs +0 -209
  255. package/dist/react/index.d.mts +0 -3
  256. package/dist/react/index.mjs +0 -3
  257. package/dist/react/use-consent.d.mts +0 -49
  258. package/dist/react/use-consent.mjs +0 -54
  259. package/dist/server/create-server-tracker.d.mts +0 -42
  260. package/dist/server/create-server-tracker.mjs +0 -67
  261. package/dist/server/index.d.mts +0 -3
  262. package/dist/server/index.mjs +0 -3
  263. package/dist/server/region.d.mts +0 -20
  264. package/dist/server/region.mjs +0 -56
  265. package/src/client/index.ts +0 -17
  266. package/src/client/lifecycle.ts +0 -50
  267. package/src/client/local-storage.ts +0 -44
  268. package/src/client/queue.ts +0 -117
  269. package/src/client/router.ts +0 -37
  270. package/src/core/index.ts +0 -24
  271. package/src/destinations/ga4-measurement-protocol.ts +0 -166
  272. package/src/destinations/http-destination.ts +0 -33
  273. package/src/destinations/index.ts +0 -20
  274. package/src/react/index.ts +0 -29
  275. package/src/server/create-server-tracker.ts +0 -128
  276. package/src/server/index.ts +0 -4
@@ -1,27 +1,33 @@
1
1
  import type { ConsentDecision } from "#/core/consent";
2
+ import type { ConsentConfig } from "#/core/consent-config";
2
3
  import type { Destination } from "#/core/destination";
4
+ import type { GoogleConsentParams } from "#/destinations/google-consent";
5
+ import {
6
+ buildGoogleConsentBootstrapPreamble,
7
+ DEFAULT_DATA_LAYER_NAME,
8
+ ensureDataLayer,
9
+ toGoogleConsentParams,
10
+ warnUnlessGa4EventName,
11
+ } from "#/destinations/google-consent";
12
+ import type { FlatPropertyValue } from "#/destinations/shared";
13
+ import { flattenEventProps } from "#/destinations/shared";
3
14
 
4
- type GtagPropertyValue = boolean | number | string;
15
+ const GTAG_SCRIPT_BASE_URL = "https://www.googletagmanager.com/gtag/js";
5
16
 
6
- type GoogleConsentState = "denied" | "granted";
7
-
8
- interface GoogleConsentParams {
9
- ad_personalization: GoogleConsentState;
10
- ad_storage: GoogleConsentState;
11
- ad_user_data: GoogleConsentState;
12
- analytics_storage: GoogleConsentState;
13
- region?: ReadonlyArray<string>;
14
- wait_for_update?: number;
15
- }
17
+ type GtagPropertyValue = FlatPropertyValue;
16
18
 
17
19
  /**
18
20
  * All signatures share one `gtag` global, so they must live in a single overloaded type —
19
21
  * two separate `declare global` augmentations with different signatures for the same
20
22
  * property is a TS error, not a merge.
23
+ *
24
+ * @since 1.0.0-canary.6
21
25
  */
22
- type GtagFunction = {
26
+ export type GtagFunction = {
27
+ (command: "config", targetId: string, params?: Record<string, GtagPropertyValue>): void;
23
28
  (command: "consent", action: "default" | "update", params: GoogleConsentParams): void;
24
29
  (command: "event", eventName: string, params?: Record<string, GtagPropertyValue>): void;
30
+ (command: "js", startDate: Date): void;
25
31
  (command: "set", params: Record<string, GtagPropertyValue>): void;
26
32
  (command: "set", key: string, value: boolean): void;
27
33
  };
@@ -33,149 +39,238 @@ declare global {
33
39
  }
34
40
  }
35
41
 
42
+ function gtagScriptSrc(gaMeasurementId: string, dataLayerName: string): string {
43
+ const url = new URL(GTAG_SCRIPT_BASE_URL);
44
+
45
+ url.searchParams.set("id", gaMeasurementId);
46
+
47
+ if (dataLayerName !== DEFAULT_DATA_LAYER_NAME) {
48
+ // gtag.js's `l` param names the queue array — must match the stub that pushes into it.
49
+ url.searchParams.set("l", dataLayerName);
50
+ }
51
+
52
+ return url.toString();
53
+ }
54
+
36
55
  /**
37
- * The visitor's per-category decision maps onto Consent Mode v2's signals: `analytics`
38
- * drives `analytics_storage`; `ads` drives all three ads signals together — a banner
39
- * that got ads consent got it for storage, sharing, and personalization alike.
56
+ * @since 1.0.0-canary.6
40
57
  */
41
- function toGoogleConsentParams(decision: ConsentDecision): GoogleConsentParams {
42
- const ads: GoogleConsentState = decision.ads ? "granted" : "denied";
43
-
44
- return {
45
- ad_personalization: ads,
46
- ad_storage: ads,
47
- ad_user_data: ads,
48
- analytics_storage: decision.analytics ? "granted" : "denied",
49
- };
58
+ export interface EnsureGtagOptions {
59
+ /**
60
+ * Name of the queue array on `window`. Defaults to `"dataLayer"`. Must match across
61
+ * `ensureGtag` / `loadGtagScript` / `buildGtagConsentBootstrapScript` for one page.
62
+ */
63
+ dataLayerName?: string | undefined;
50
64
  }
51
65
 
52
66
  /**
53
67
  * Ensures the standard gtag.js queueing stub exists so consent commands can be issued
54
68
  * before the tag itself loads — gtag.js replays the queue in order once it boots.
69
+ *
70
+ * @since 1.0.0-canary.6
55
71
  */
56
- function ensureGtag(): GtagFunction | undefined {
72
+ export function ensureGtag(options: EnsureGtagOptions = {}): GtagFunction | undefined {
57
73
  if (typeof window === "undefined") {
58
74
  return undefined;
59
75
  }
60
76
 
61
- window.dataLayer ??= [];
77
+ const dataLayerName = options.dataLayerName ?? DEFAULT_DATA_LAYER_NAME;
78
+
79
+ ensureDataLayer(dataLayerName);
62
80
 
63
- // gtag.js requires the live Arguments object on the dataLayer — pushing an array is
64
- // treated as a GTM message, not a gtag command.
81
+ // First stub wins — recreating would orphan commands already queued on another layer.
82
+ // Callers must pass the same dataLayerName for every helper on the page.
65
83
  window.gtag ??= function gtag() {
66
- window.dataLayer?.push(arguments);
84
+ ensureDataLayer(dataLayerName)?.push(arguments);
67
85
  } as GtagFunction;
68
86
 
69
87
  return window.gtag;
70
88
  }
71
89
 
72
90
  /**
73
- * @since 0.5.0-canary.4
91
+ * @since 1.0.0-canary.6
74
92
  */
75
- export interface GoogleConsentDefaultOptions {
76
- /** Restrict the default to these ISO 3166-2 codes (gtag's `region` param); omit for a global default. */
77
- region?: ReadonlyArray<string>;
78
- /** Consent Mode's `wait_for_update` — how long tags hold hits so a stored decision can arrive as an update first. */
79
- waitForUpdateMs?: number;
93
+ export interface LoadGtagScriptOptions {
94
+ /**
95
+ * Name of the queue array on `window`. Defaults to `"dataLayer"` — must match the
96
+ * bootstrap / `ensureGtag` call that already applied Consent Mode.
97
+ */
98
+ dataLayerName?: string | undefined;
99
+ /** Forwarded as `gtag('config', id, { debug_mode: true })` for GA4 DebugView. */
100
+ debugMode?: boolean | undefined;
101
+ /** Google Analytics 4 Measurement ID (e.g. `"G-XXXXXXX"`). */
102
+ gaMeasurementId: string;
103
+ /**
104
+ * CSP nonce applied to the injected gtag.js `<script>` element. The app must also put
105
+ * the same nonce on any inline bootstrap `<script>` that runs `buildGtagConsentBootstrapScript`.
106
+ */
107
+ nonce?: string | undefined;
80
108
  }
81
109
 
82
110
  /**
83
- * Google Consent Mode v2's "default" signal — call before the gtag.js script tag loads
84
- * (this defines the queueing stub itself, so no snippet has to run first) with the
85
- * region-resolved default, so GA4/Ads never fire a hit ahead of it.
111
+ * Loads gtag.js on demand — idempotent (a second call is a no-op) and reuses any
112
+ * existing `dataLayer`/`gtag` stub instead of clobbering it. Queues `js`/`config` before
113
+ * appending the script tag, so gtag.js replays them under the caller's already-applied
114
+ * consent state once it boots. Prefer `buildGtagConsentBootstrapScript` for page load
115
+ * (advanced Consent Mode always injects the tag after the default); use this when the
116
+ * bootstrap did not run, or as an idempotent safety net after a runtime grant.
86
117
  *
87
- * @since 0.5.0-canary.4
118
+ * @since 1.0.0-canary.6
88
119
  */
89
- export function setGoogleConsentDefault(decision: ConsentDecision, options: GoogleConsentDefaultOptions = {}): void {
90
- const params = toGoogleConsentParams(decision);
120
+ export function loadGtagScript(options: LoadGtagScriptOptions): void {
121
+ if (typeof document === "undefined" || document.querySelector(`script[src^="${GTAG_SCRIPT_BASE_URL}"]`) !== null) {
122
+ return;
123
+ }
124
+
125
+ const dataLayerName = options.dataLayerName ?? DEFAULT_DATA_LAYER_NAME;
126
+ const gtag = ensureGtag({ dataLayerName });
127
+
128
+ if (!gtag) {
129
+ return;
130
+ }
131
+
132
+ gtag("js", new Date());
91
133
 
92
- if (options.region !== undefined) {
93
- params.region = options.region;
134
+ if (options.debugMode === true) {
135
+ gtag("config", options.gaMeasurementId, { debug_mode: true });
136
+ } else {
137
+ gtag("config", options.gaMeasurementId);
94
138
  }
95
139
 
96
- if (options.waitForUpdateMs !== undefined) {
97
- params.wait_for_update = options.waitForUpdateMs;
140
+ const script = document.createElement("script");
141
+
142
+ script.async = true;
143
+ script.src = gtagScriptSrc(options.gaMeasurementId, dataLayerName);
144
+
145
+ if (options.nonce !== undefined) {
146
+ script.nonce = options.nonce;
98
147
  }
99
148
 
100
- ensureGtag()?.("consent", "default", params);
149
+ document.head.append(script);
101
150
  }
102
151
 
103
152
  /**
104
- * Google Consent Mode v2's "update" signal — call whenever the visitor's effective
105
- * consent changes (a banner decision, or one synced from another tab), so already-loaded
106
- * GA4/Ads tags pick up the change without a page reload.
153
+ * Expires Google's `_ga` / `_ga_*` cookies on `path=/` and the current host's parent
154
+ * domain. Consent Mode stops using them once denied but never removes them — call from
155
+ * a consent-withdrawal handler so a revoke does not leave identifier cookies behind.
107
156
  *
108
- * @since 0.5.0-canary.4
157
+ * @since 1.0.0-canary.6
109
158
  */
110
- export function updateGoogleConsent(decision: ConsentDecision): void {
111
- ensureGtag()?.("consent", "update", toGoogleConsentParams(decision));
159
+ export function clearGoogleAnalyticsCookies(): void {
160
+ if (typeof document === "undefined") {
161
+ return;
162
+ }
163
+
164
+ const { hostname } = globalThis.location;
165
+
166
+ for (const cookie of document.cookie.split("; ")) {
167
+ const name = cookie.split("=")[0];
168
+
169
+ if (name !== undefined && (name === "_ga" || name.startsWith("_ga_"))) {
170
+ // GA sets its cookies on the broadest domain it can reach — expire both variants.
171
+ document.cookie = `${name}=; path=/; max-age=0`;
172
+ document.cookie = `${name}=; path=/; max-age=0; domain=.${hostname}`;
173
+ }
174
+ }
112
175
  }
113
176
 
114
177
  /**
115
- * Consent Mode's `ads_data_redaction` flag — with `ad_storage` denied, gtag further
116
- * redacts ad click identifiers (gclid/dclid) from its cookieless pings. Set alongside
117
- * the consent default.
178
+ * Google Consent Mode v2's "update" signal — call whenever the visitor's effective
179
+ * consent changes (a banner decision, or one synced from another tab), so already-loaded
180
+ * GA4/Ads tags pick up the change without a page reload.
118
181
  *
119
182
  * @since 0.5.0-canary.4
120
183
  */
121
- export function setGoogleAdsDataRedaction(enabled: boolean): void {
122
- ensureGtag()?.("set", "ads_data_redaction", enabled);
184
+ export function updateGoogleConsent(decision: ConsentDecision, options: EnsureGtagOptions = {}): void {
185
+ ensureGtag(options)?.("consent", "update", toGoogleConsentParams(decision));
123
186
  }
124
187
 
125
188
  /**
126
- * Consent Mode's `url_passthrough` flag — carries ad click info through page URLs while
127
- * storage is denied, preserving conversion attribution without cookies.
128
- *
129
- * @since 0.5.0-canary.4
189
+ * @since 1.0.0-canary.6
130
190
  */
131
- export function setGoogleUrlPassthrough(enabled: boolean): void {
132
- ensureGtag()?.("set", "url_passthrough", enabled);
191
+ export interface GtagConsentBootstrapOptions {
192
+ /** The same object `useConsent` receives — the bootstrap reads its `storageKey` and `policyVersion`. */
193
+ config: ConsentConfig;
194
+ /**
195
+ * Name of the queue array on `window`. Defaults to `"dataLayer"`. Must match
196
+ * `loadGtagScript` / `ensureGtag` if those run later on the same page.
197
+ */
198
+ dataLayerName?: string | undefined;
199
+ /**
200
+ * Consent to apply when nothing valid is stored yet. Embedded as a literal — bake the
201
+ * strictest default on cached/shared HTML; upgrade after hydration via the private
202
+ * server-fn lane + `updateGoogleConsent`.
203
+ */
204
+ defaultConsent: ConsentDecision;
205
+ /** Forwarded as `gtag('config', id, { debug_mode: true })` after the consent default. */
206
+ debugMode?: boolean | undefined;
207
+ /** Google Analytics 4 Measurement ID (e.g. `"G-XXXXXXX"`). */
208
+ gaMeasurementId: string;
209
+ /**
210
+ * CSP nonce written onto the *injected* gtag.js `<script>` element inside the generated
211
+ * source. The host `<script dangerouslySetInnerHTML={…}>` that embeds this string must
212
+ * receive the same nonce from the app (this helper only returns JS text, not a React node).
213
+ */
214
+ nonce?: string | undefined;
133
215
  }
134
216
 
135
217
  /**
136
- * gtag.js event params must be flat string/number/boolean — stringify anything else
137
- * instead of letting GA4 silently drop it.
218
+ * Builds the literal JS source for a `<script dangerouslySetInnerHTML>` mounted in
219
+ * `<head>`, before hydration: applies Consent Mode v2's default signal from the visitor's
220
+ * stored decision (falling back to literal `defaultConsent` when none is stored yet),
221
+ * then always loads gtag.js (advanced Consent Mode) so cookieless pings / modeling can
222
+ * run even when storage is denied. A runtime decision change needs `updateGoogleConsent`
223
+ * so the already-loaded tag picks up the grant/deny — this only covers the page-load
224
+ * default + script injection.
225
+ *
226
+ * @since 1.0.0-canary.6
138
227
  */
139
- function toGtagParams(props: Record<string, unknown>): Record<string, GtagPropertyValue> {
140
- const result: Record<string, GtagPropertyValue> = {};
141
-
142
- for (const [key, value] of Object.entries(props)) {
143
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
144
- result[key] = value;
145
- } else if (value !== undefined && value !== null) {
146
- result[key] = JSON.stringify(value);
147
- }
148
- }
149
-
150
- return result;
228
+ export function buildGtagConsentBootstrapScript(options: GtagConsentBootstrapOptions): string {
229
+ const {
230
+ config,
231
+ dataLayerName = DEFAULT_DATA_LAYER_NAME,
232
+ defaultConsent,
233
+ debugMode,
234
+ gaMeasurementId,
235
+ nonce,
236
+ } = options;
237
+
238
+ const gtagScriptUrl = gtagScriptSrc(gaMeasurementId, dataLayerName);
239
+ const configArgs =
240
+ debugMode === true ? `${JSON.stringify(gaMeasurementId)}, { debug_mode: true }` : JSON.stringify(gaMeasurementId);
241
+ const nonceAssignment = nonce === undefined ? "" : `gtagScript.nonce = ${JSON.stringify(nonce)};`;
242
+ const preamble = buildGoogleConsentBootstrapPreamble({
243
+ consentStorageKey: config.storageKey,
244
+ dataLayerName,
245
+ defaultConsent,
246
+ policyVersion: config.policyVersion,
247
+ });
248
+
249
+ // Advanced Consent Mode: consent default first, then always load the tag (even when denied).
250
+ return `${preamble}
251
+ gtag("js", new Date());
252
+ gtag("config", ${configArgs});
253
+ var gtagScript = document.createElement("script");
254
+ gtagScript.async = true;
255
+ gtagScript.src = ${JSON.stringify(gtagScriptUrl)};
256
+ ${nonceAssignment}
257
+ document.head.appendChild(gtagScript);
258
+ `;
151
259
  }
152
260
 
153
- // GA4 rejects event names that don't start with a letter or exceed 40 chars — a `$`-prefixed
154
- // or otherwise invalid name would be dropped at processing without any signal to the dev.
155
- const GA4_EVENT_NAME_PATTERN = /^[A-Za-z][\w]{0,39}$/;
156
-
157
261
  /**
158
262
  * @since 0.5.0-canary.4
159
263
  */
160
264
  export interface GoogleAnalyticsDestinationOptions {
161
- name?: string;
162
- /**
163
- * Forward `$page_viewed` as GA4's `page_view`. Off by default: `gtag('config', ...)`
164
- * sends the initial page_view and GA4's Enhanced Measurement (on by default in admin)
165
- * tracks SPA history changes, so forwarding here would double-count. Enable only after
166
- * setting `send_page_view: false` on config and disabling Enhanced Measurement's
167
- * history-based page views.
168
- */
169
- trackPageViews?: boolean;
265
+ name?: string | undefined;
170
266
  }
171
267
 
172
268
  /**
173
- * Forwards events to `window.gtag`, translating this package's `$`-prefixed built-ins to
174
- * GA4's vocabulary — `$identify` sets `user_id`, `$group` becomes the recommended
175
- * `join_group` event, `$page_viewed` maps to `page_view` (opt-in, see `trackPageViews`).
176
- * Requires the gtag.js snippet plus `gtag('config', measurementId)` mounted once by the
177
- * app. Marked `delivery: "immediate"` — gtag.js has its own batching and unload delivery,
178
- * so queueing in front of it only delays events and replays stale ones next session.
269
+ * Forwards catalog events to `window.gtag` as GA4 custom events. Page views are not this
270
+ * destination's job: `gtag('config', ...)` sends the initial page_view and GA4's Enhanced
271
+ * Measurement tracks SPA history changes. Requires the gtag.js snippet plus
272
+ * `gtag('config', measurementId)` mounted once by the app (see the consent bootstrap) —
273
+ * gtag.js owns its own batching and unload delivery.
179
274
  *
180
275
  * @since 0.5.0-canary.4
181
276
  */
@@ -183,51 +278,19 @@ export function createGoogleAnalyticsDestination(options: GoogleAnalyticsDestina
183
278
  const name = options.name ?? "google-analytics";
184
279
 
185
280
  return {
186
- delivery: "immediate",
187
281
  name,
188
- send(event) {
282
+ // Synchronous today, but declared async so a throw here rejects the returned Promise
283
+ // instead of escaping as a synchronous throw — matches Destination.send's contract.
284
+ async send(event) {
189
285
  if (typeof window === "undefined" || typeof window.gtag !== "function") {
190
286
  return;
191
287
  }
192
288
 
193
- if (event.name === "$identify") {
194
- // GA4 has no identify event — user_id is set once and rides along on later hits.
195
- if (event.userId !== undefined) {
196
- window.gtag("set", { user_id: event.userId });
197
- }
198
-
199
- return;
200
- }
201
-
202
- if (event.name === "$page_viewed") {
203
- if (options.trackPageViews === true) {
204
- // gtag.js attaches page_location/page_title from the live document itself, so
205
- // only the caller's extra props are forwarded.
206
- const { href: _href, name: _name, ...extras } = event.props;
207
-
208
- window.gtag("event", "page_view", toGtagParams(extras));
209
- }
210
-
211
- return;
212
- }
213
-
214
- if (event.name === "$group") {
215
- const { groupId, ...traits } = event.props;
216
-
217
- window.gtag("event", "join_group", toGtagParams({ group_id: groupId, ...traits }));
218
-
219
- return;
220
- }
221
-
222
- if (!GA4_EVENT_NAME_PATTERN.test(event.name)) {
223
- console.warn(
224
- `[tracking] "${name}" dropped event "${event.name}" — GA4 event names must start with a letter and contain only letters, digits, or underscores (max 40 chars)`,
225
- );
226
-
289
+ if (!warnUnlessGa4EventName(name, event.name)) {
227
290
  return;
228
291
  }
229
292
 
230
- window.gtag("event", event.name, toGtagParams(event.props));
293
+ window.gtag("event", event.name, flattenEventProps(event.properties));
231
294
  },
232
295
  };
233
296
  }
@@ -0,0 +1,164 @@
1
+ import type { ConsentCategory, ConsentDecision } from "#/core/consent";
2
+ import { CONSENT_CATEGORIES } from "#/core/consent";
3
+
4
+ /**
5
+ * gtag.js/gtm.js's default queue-array name — shared so the gtag and GTM helpers cannot disagree.
6
+ *
7
+ * @since 1.0.0-canary.6
8
+ */
9
+ export const DEFAULT_DATA_LAYER_NAME = "dataLayer";
10
+
11
+ type GoogleConsentState = "denied" | "granted";
12
+
13
+ /**
14
+ * Consent Mode v2 params issued via `gtag('consent', …)` — shared by the gtag and GTM
15
+ * bootstraps so signal mapping cannot drift between them.
16
+ *
17
+ * @since 1.0.0-canary.6
18
+ */
19
+ export interface GoogleConsentParams {
20
+ ad_personalization: GoogleConsentState;
21
+ ad_storage: GoogleConsentState;
22
+ ad_user_data: GoogleConsentState;
23
+ analytics_storage: GoogleConsentState;
24
+ region?: ReadonlyArray<string> | undefined;
25
+ wait_for_update?: number | undefined;
26
+ }
27
+
28
+ /**
29
+ * Which per-category decision each Consent Mode v2 signal follows: `analytics` drives
30
+ * `analytics_storage`; `ads` drives all three ads signals together.
31
+ */
32
+ const GOOGLE_CONSENT_SIGNAL_CATEGORIES = {
33
+ ad_personalization: "ads",
34
+ ad_storage: "ads",
35
+ ad_user_data: "ads",
36
+ analytics_storage: "analytics",
37
+ } as const satisfies Record<
38
+ "ad_personalization" | "ad_storage" | "ad_user_data" | "analytics_storage",
39
+ ConsentCategory
40
+ >;
41
+
42
+ type GoogleConsentSignal = keyof typeof GOOGLE_CONSENT_SIGNAL_CATEGORIES;
43
+
44
+ /**
45
+ * Maps a package `ConsentDecision` onto Consent Mode v2's four storage signals.
46
+ *
47
+ * @since 1.0.0-canary.6
48
+ */
49
+ export function toGoogleConsentParams(decision: ConsentDecision): GoogleConsentParams {
50
+ // Derived from the signal map (not hand-written per signal) so the runtime params and
51
+ // the bootstrap fragment below can never disagree.
52
+ return {
53
+ ad_personalization: decision[GOOGLE_CONSENT_SIGNAL_CATEGORIES.ad_personalization] ? "granted" : "denied",
54
+ ad_storage: decision[GOOGLE_CONSENT_SIGNAL_CATEGORIES.ad_storage] ? "granted" : "denied",
55
+ ad_user_data: decision[GOOGLE_CONSENT_SIGNAL_CATEGORIES.ad_user_data] ? "granted" : "denied",
56
+ analytics_storage: decision[GOOGLE_CONSENT_SIGNAL_CATEGORIES.analytics_storage] ? "granted" : "denied",
57
+ };
58
+ }
59
+
60
+ /** JS fragment that validates a stored `ConsentRecord.decision` shape inside a bootstrap. */
61
+ function consentDecisionShapeCheckExpression(): string {
62
+ return CONSENT_CATEGORIES.map((category) => `typeof record.decision[${JSON.stringify(category)}] === "boolean"`).join(
63
+ " && ",
64
+ );
65
+ }
66
+
67
+ /**
68
+ * JS object-literal fragment for `gtag("consent", "default", { … })` — generated from
69
+ * {@link GOOGLE_CONSENT_SIGNAL_CATEGORIES} so runtime and bootstrap stay aligned.
70
+ */
71
+ function consentSignalAssignmentsExpression(): string {
72
+ return (Object.keys(GOOGLE_CONSENT_SIGNAL_CATEGORIES) as Array<GoogleConsentSignal>)
73
+ .map((signal) => {
74
+ const category = GOOGLE_CONSENT_SIGNAL_CATEGORIES[signal];
75
+
76
+ return `${signal}: consent.${category} ? "granted" : "denied"`;
77
+ })
78
+ .join(",\n ");
79
+ }
80
+
81
+ /**
82
+ * @since 1.0.0-canary.6
83
+ */
84
+ export interface GoogleConsentBootstrapPreambleOptions {
85
+ /** localStorage key holding the package's `ConsentRecord`. */
86
+ consentStorageKey: string;
87
+ dataLayerName: string;
88
+ /** Literal fallback when nothing valid is stored — baked into the script as JSON. */
89
+ defaultConsent: ConsentDecision;
90
+ policyVersion: string;
91
+ }
92
+
93
+ /**
94
+ * Shared head of the gtag and GTM consent bootstraps: dataLayer init, `gtag()` stub,
95
+ * stored-decision read (policy-version + shape checked), and the Consent Mode v2
96
+ * "default" signal. The builders append only their tag-specific tail, so the consent
97
+ * logic cannot drift between them.
98
+ *
99
+ * @since 1.0.0-canary.6
100
+ */
101
+ export function buildGoogleConsentBootstrapPreamble(options: GoogleConsentBootstrapPreambleOptions): string {
102
+ const dataLayerAccess = `window[${JSON.stringify(options.dataLayerName)}]`;
103
+
104
+ return `
105
+ ${dataLayerAccess} = ${dataLayerAccess} || [];
106
+ function gtag(){${dataLayerAccess}.push(arguments);}
107
+ var storedConsent = null;
108
+ try {
109
+ var record = JSON.parse(window.localStorage.getItem(${JSON.stringify(options.consentStorageKey)}));
110
+ if (record && record.policyVersion === ${JSON.stringify(options.policyVersion)} && record.decision && ${consentDecisionShapeCheckExpression()}) {
111
+ storedConsent = record.decision;
112
+ }
113
+ } catch (e) {}
114
+ var consent = storedConsent || (${JSON.stringify(options.defaultConsent)});
115
+ gtag("consent", "default", {
116
+ ${consentSignalAssignmentsExpression()}
117
+ });`;
118
+ }
119
+
120
+ /**
121
+ * Reads or creates a named `window[dataLayerName]` queue array.
122
+ *
123
+ * @since 1.0.0-canary.6
124
+ */
125
+ export function ensureDataLayer(dataLayerName: string): Array<unknown> | undefined {
126
+ if (typeof window === "undefined") {
127
+ return undefined;
128
+ }
129
+
130
+ const existing = Reflect.get(window, dataLayerName);
131
+ const layer: Array<unknown> = Array.isArray(existing) ? existing : [];
132
+
133
+ Reflect.set(window, dataLayerName, layer);
134
+
135
+ return layer;
136
+ }
137
+
138
+ /**
139
+ * GA4's event-name rules (letter start, letters/digits/underscores only, ≤40 chars).
140
+ * Catalog `track` names that fail this are accepted by gtag/MP HTTP but dropped at GA4
141
+ * processing with no client error — destinations warn and skip instead of sending nowhere.
142
+ */
143
+ const GA4_EVENT_NAME_PATTERN = /^[A-Za-z][\w]{0,39}$/;
144
+
145
+ function isGa4EventName(name: string): boolean {
146
+ return GA4_EVENT_NAME_PATTERN.test(name);
147
+ }
148
+
149
+ /**
150
+ * Warns and returns `false` when `eventName` would be rejected by GA4.
151
+ *
152
+ * @since 1.0.0-canary.6
153
+ */
154
+ export function warnUnlessGa4EventName(destinationName: string, eventName: string): boolean {
155
+ if (isGa4EventName(eventName)) {
156
+ return true;
157
+ }
158
+
159
+ console.warn(
160
+ `[tracking] "${destinationName}" dropped event "${eventName}" — GA4 event names must start with a letter and contain only letters, digits, or underscores (max 40 chars)`,
161
+ );
162
+
163
+ return false;
164
+ }