@codefast/tracking 0.5.0-canary.4 → 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 (134) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +123 -96
  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 +143 -38
  54. package/dist/react/consent-banner.mjs +192 -92
  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 +5 -2
  58. package/dist/react/index.mjs +5 -2
  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 +27 -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/css/consent.css +119 -0
  96. package/src/destinations/google-analytics.ts +196 -133
  97. package/src/destinations/google-consent.ts +164 -0
  98. package/src/destinations/index.ts +14 -15
  99. package/src/destinations/shared.ts +45 -0
  100. package/src/destinations/vercel-analytics.ts +23 -24
  101. package/src/import-protection.ts +20 -0
  102. package/src/index.ts +46 -8
  103. package/src/react/consent-banner.tsx +308 -111
  104. package/src/react/gtag-consent-bootstrap.tsx +48 -0
  105. package/src/react/index.ts +34 -2
  106. package/src/react/use-consent.ts +53 -45
  107. package/src/react/use-google-consent-sync.ts +38 -0
  108. package/src/react/use-initial-consent.ts +22 -0
  109. package/src/server/anonymous-id-cookie.ts +76 -0
  110. package/src/server/index.ts +15 -3
  111. package/src/server/initial-consent.ts +48 -0
  112. package/src/server/region.ts +22 -5
  113. package/src/tanstack-start/index.ts +83 -0
  114. package/dist/client/lifecycle.d.mts +0 -23
  115. package/dist/client/lifecycle.mjs +0 -30
  116. package/dist/client/local-storage.d.mts +0 -13
  117. package/dist/client/local-storage.mjs +0 -31
  118. package/dist/client/queue.d.mts +0 -49
  119. package/dist/client/queue.mjs +0 -71
  120. package/dist/client/router.d.mts +0 -30
  121. package/dist/client/router.mjs +0 -17
  122. package/dist/destinations/ga4-measurement-protocol.d.mts +0 -54
  123. package/dist/destinations/ga4-measurement-protocol.mjs +0 -89
  124. package/dist/destinations/http-destination.d.mts +0 -20
  125. package/dist/destinations/http-destination.mjs +0 -25
  126. package/dist/server/create-server-tracker.d.mts +0 -42
  127. package/dist/server/create-server-tracker.mjs +0 -67
  128. package/src/client/lifecycle.ts +0 -50
  129. package/src/client/local-storage.ts +0 -44
  130. package/src/client/queue.ts +0 -117
  131. package/src/client/router.ts +0 -37
  132. package/src/destinations/ga4-measurement-protocol.ts +0 -166
  133. package/src/destinations/http-destination.ts +0 -33
  134. package/src/server/create-server-tracker.ts +0 -128
@@ -1,25 +1,23 @@
1
1
  import { ConsentDecision } from "../core/consent.mjs";
2
+ import { ConsentConfig } from "../core/consent-config.mjs";
2
3
  import { Destination } from "../core/destination.mjs";
4
+ import { GoogleConsentParams } from "./google-consent.mjs";
5
+ import { FlatPropertyValue } from "./shared.mjs";
3
6
 
4
7
  //#region src/destinations/google-analytics.d.ts
5
- type GtagPropertyValue = boolean | number | string;
6
- type GoogleConsentState = "denied" | "granted";
7
- interface GoogleConsentParams {
8
- ad_personalization: GoogleConsentState;
9
- ad_storage: GoogleConsentState;
10
- ad_user_data: GoogleConsentState;
11
- analytics_storage: GoogleConsentState;
12
- region?: ReadonlyArray<string>;
13
- wait_for_update?: number;
14
- }
8
+ type GtagPropertyValue = FlatPropertyValue;
15
9
  /**
16
10
  * All signatures share one `gtag` global, so they must live in a single overloaded type —
17
11
  * two separate `declare global` augmentations with different signatures for the same
18
12
  * property is a TS error, not a merge.
13
+ *
14
+ * @since 1.0.0-canary.6
19
15
  */
20
16
  type GtagFunction = {
17
+ (command: "config", targetId: string, params?: Record<string, GtagPropertyValue>): void;
21
18
  (command: "consent", action: "default" | "update", params: GoogleConsentParams): void;
22
19
  (command: "event", eventName: string, params?: Record<string, GtagPropertyValue>): void;
20
+ (command: "js", startDate: Date): void;
23
21
  (command: "set", params: Record<string, GtagPropertyValue>): void;
24
22
  (command: "set", key: string, value: boolean): void;
25
23
  };
@@ -30,22 +28,60 @@ declare global {
30
28
  }
31
29
  }
32
30
  /**
33
- * @since 0.5.0-canary.4
31
+ * @since 1.0.0-canary.6
34
32
  */
35
- interface GoogleConsentDefaultOptions {
36
- /** Restrict the default to these ISO 3166-2 codes (gtag's `region` param); omit for a global default. */
37
- region?: ReadonlyArray<string>;
38
- /** Consent Mode's `wait_for_update` — how long tags hold hits so a stored decision can arrive as an update first. */
39
- waitForUpdateMs?: number;
33
+ interface EnsureGtagOptions {
34
+ /**
35
+ * Name of the queue array on `window`. Defaults to `"dataLayer"`. Must match across
36
+ * `ensureGtag` / `loadGtagScript` / `buildGtagConsentBootstrapScript` for one page.
37
+ */
38
+ dataLayerName?: string | undefined;
40
39
  }
41
40
  /**
42
- * Google Consent Mode v2's "default" signal — call before the gtag.js script tag loads
43
- * (this defines the queueing stub itself, so no snippet has to run first) with the
44
- * region-resolved default, so GA4/Ads never fire a hit ahead of it.
41
+ * Ensures the standard gtag.js queueing stub exists so consent commands can be issued
42
+ * before the tag itself loads — gtag.js replays the queue in order once it boots.
45
43
  *
46
- * @since 0.5.0-canary.4
44
+ * @since 1.0.0-canary.6
45
+ */
46
+ declare function ensureGtag(options?: EnsureGtagOptions): GtagFunction | undefined;
47
+ /**
48
+ * @since 1.0.0-canary.6
49
+ */
50
+ interface LoadGtagScriptOptions {
51
+ /**
52
+ * Name of the queue array on `window`. Defaults to `"dataLayer"` — must match the
53
+ * bootstrap / `ensureGtag` call that already applied Consent Mode.
54
+ */
55
+ dataLayerName?: string | undefined;
56
+ /** Forwarded as `gtag('config', id, { debug_mode: true })` for GA4 DebugView. */
57
+ debugMode?: boolean | undefined;
58
+ /** Google Analytics 4 Measurement ID (e.g. `"G-XXXXXXX"`). */
59
+ gaMeasurementId: string;
60
+ /**
61
+ * CSP nonce applied to the injected gtag.js `<script>` element. The app must also put
62
+ * the same nonce on any inline bootstrap `<script>` that runs `buildGtagConsentBootstrapScript`.
63
+ */
64
+ nonce?: string | undefined;
65
+ }
66
+ /**
67
+ * Loads gtag.js on demand — idempotent (a second call is a no-op) and reuses any
68
+ * existing `dataLayer`/`gtag` stub instead of clobbering it. Queues `js`/`config` before
69
+ * appending the script tag, so gtag.js replays them under the caller's already-applied
70
+ * consent state once it boots. Prefer `buildGtagConsentBootstrapScript` for page load
71
+ * (advanced Consent Mode always injects the tag after the default); use this when the
72
+ * bootstrap did not run, or as an idempotent safety net after a runtime grant.
73
+ *
74
+ * @since 1.0.0-canary.6
47
75
  */
48
- declare function setGoogleConsentDefault(decision: ConsentDecision, options?: GoogleConsentDefaultOptions): void;
76
+ declare function loadGtagScript(options: LoadGtagScriptOptions): void;
77
+ /**
78
+ * Expires Google's `_ga` / `_ga_*` cookies on `path=/` and the current host's parent
79
+ * domain. Consent Mode stops using them once denied but never removes them — call from
80
+ * a consent-withdrawal handler so a revoke does not leave identifier cookies behind.
81
+ *
82
+ * @since 1.0.0-canary.6
83
+ */
84
+ declare function clearGoogleAnalyticsCookies(): void;
49
85
  /**
50
86
  * Google Consent Mode v2's "update" signal — call whenever the visitor's effective
51
87
  * consent changes (a banner decision, or one synced from another tab), so already-loaded
@@ -53,46 +89,62 @@ declare function setGoogleConsentDefault(decision: ConsentDecision, options?: Go
53
89
  *
54
90
  * @since 0.5.0-canary.4
55
91
  */
56
- declare function updateGoogleConsent(decision: ConsentDecision): void;
92
+ declare function updateGoogleConsent(decision: ConsentDecision, options?: EnsureGtagOptions): void;
57
93
  /**
58
- * Consent Mode's `ads_data_redaction` flag — with `ad_storage` denied, gtag further
59
- * redacts ad click identifiers (gclid/dclid) from its cookieless pings. Set alongside
60
- * the consent default.
61
- *
62
- * @since 0.5.0-canary.4
94
+ * @since 1.0.0-canary.6
63
95
  */
64
- declare function setGoogleAdsDataRedaction(enabled: boolean): void;
96
+ interface GtagConsentBootstrapOptions {
97
+ /** The same object `useConsent` receives — the bootstrap reads its `storageKey` and `policyVersion`. */
98
+ config: ConsentConfig;
99
+ /**
100
+ * Name of the queue array on `window`. Defaults to `"dataLayer"`. Must match
101
+ * `loadGtagScript` / `ensureGtag` if those run later on the same page.
102
+ */
103
+ dataLayerName?: string | undefined;
104
+ /**
105
+ * Consent to apply when nothing valid is stored yet. Embedded as a literal — bake the
106
+ * strictest default on cached/shared HTML; upgrade after hydration via the private
107
+ * server-fn lane + `updateGoogleConsent`.
108
+ */
109
+ defaultConsent: ConsentDecision;
110
+ /** Forwarded as `gtag('config', id, { debug_mode: true })` after the consent default. */
111
+ debugMode?: boolean | undefined;
112
+ /** Google Analytics 4 Measurement ID (e.g. `"G-XXXXXXX"`). */
113
+ gaMeasurementId: string;
114
+ /**
115
+ * CSP nonce written onto the *injected* gtag.js `<script>` element inside the generated
116
+ * source. The host `<script dangerouslySetInnerHTML={…}>` that embeds this string must
117
+ * receive the same nonce from the app (this helper only returns JS text, not a React node).
118
+ */
119
+ nonce?: string | undefined;
120
+ }
65
121
  /**
66
- * Consent Mode's `url_passthrough` flag — carries ad click info through page URLs while
67
- * storage is denied, preserving conversion attribution without cookies.
122
+ * Builds the literal JS source for a `<script dangerouslySetInnerHTML>` mounted in
123
+ * `<head>`, before hydration: applies Consent Mode v2's default signal from the visitor's
124
+ * stored decision (falling back to literal `defaultConsent` when none is stored yet),
125
+ * then always loads gtag.js (advanced Consent Mode) so cookieless pings / modeling can
126
+ * run even when storage is denied. A runtime decision change needs `updateGoogleConsent`
127
+ * so the already-loaded tag picks up the grant/deny — this only covers the page-load
128
+ * default + script injection.
68
129
  *
69
- * @since 0.5.0-canary.4
130
+ * @since 1.0.0-canary.6
70
131
  */
71
- declare function setGoogleUrlPassthrough(enabled: boolean): void;
132
+ declare function buildGtagConsentBootstrapScript(options: GtagConsentBootstrapOptions): string;
72
133
  /**
73
134
  * @since 0.5.0-canary.4
74
135
  */
75
136
  interface GoogleAnalyticsDestinationOptions {
76
- name?: string;
77
- /**
78
- * Forward `$page_viewed` as GA4's `page_view`. Off by default: `gtag('config', ...)`
79
- * sends the initial page_view and GA4's Enhanced Measurement (on by default in admin)
80
- * tracks SPA history changes, so forwarding here would double-count. Enable only after
81
- * setting `send_page_view: false` on config and disabling Enhanced Measurement's
82
- * history-based page views.
83
- */
84
- trackPageViews?: boolean;
137
+ name?: string | undefined;
85
138
  }
86
139
  /**
87
- * Forwards events to `window.gtag`, translating this package's `$`-prefixed built-ins to
88
- * GA4's vocabulary — `$identify` sets `user_id`, `$group` becomes the recommended
89
- * `join_group` event, `$page_viewed` maps to `page_view` (opt-in, see `trackPageViews`).
90
- * Requires the gtag.js snippet plus `gtag('config', measurementId)` mounted once by the
91
- * app. Marked `delivery: "immediate"` — gtag.js has its own batching and unload delivery,
92
- * so queueing in front of it only delays events and replays stale ones next session.
140
+ * Forwards catalog events to `window.gtag` as GA4 custom events. Page views are not this
141
+ * destination's job: `gtag('config', ...)` sends the initial page_view and GA4's Enhanced
142
+ * Measurement tracks SPA history changes. Requires the gtag.js snippet plus
143
+ * `gtag('config', measurementId)` mounted once by the app (see the consent bootstrap) —
144
+ * gtag.js owns its own batching and unload delivery.
93
145
  *
94
146
  * @since 0.5.0-canary.4
95
147
  */
96
148
  declare function createGoogleAnalyticsDestination(options?: GoogleAnalyticsDestinationOptions): Destination;
97
149
  //#endregion
98
- export { GoogleAnalyticsDestinationOptions, GoogleConsentDefaultOptions, createGoogleAnalyticsDestination, setGoogleAdsDataRedaction, setGoogleConsentDefault, setGoogleUrlPassthrough, updateGoogleConsent };
150
+ export { EnsureGtagOptions, GoogleAnalyticsDestinationOptions, GtagConsentBootstrapOptions, GtagFunction, LoadGtagScriptOptions, buildGtagConsentBootstrapScript, clearGoogleAnalyticsCookies, createGoogleAnalyticsDestination, ensureGtag, loadGtagScript, updateGoogleConsent };
@@ -1,126 +1,130 @@
1
+ import { DEFAULT_DATA_LAYER_NAME, buildGoogleConsentBootstrapPreamble, ensureDataLayer, toGoogleConsentParams, warnUnlessGa4EventName } from "./google-consent.mjs";
2
+ import { flattenEventProps } from "./shared.mjs";
1
3
  //#region src/destinations/google-analytics.ts
2
- /**
3
- * The visitor's per-category decision maps onto Consent Mode v2's signals: `analytics`
4
- * drives `analytics_storage`; `ads` drives all three ads signals together — a banner
5
- * that got ads consent got it for storage, sharing, and personalization alike.
6
- */
7
- function toGoogleConsentParams(decision) {
8
- const ads = decision.ads ? "granted" : "denied";
9
- return {
10
- ad_personalization: ads,
11
- ad_storage: ads,
12
- ad_user_data: ads,
13
- analytics_storage: decision.analytics ? "granted" : "denied"
14
- };
4
+ const GTAG_SCRIPT_BASE_URL = "https://www.googletagmanager.com/gtag/js";
5
+ function gtagScriptSrc(gaMeasurementId, dataLayerName) {
6
+ const url = new URL(GTAG_SCRIPT_BASE_URL);
7
+ url.searchParams.set("id", gaMeasurementId);
8
+ if (dataLayerName !== "dataLayer") url.searchParams.set("l", dataLayerName);
9
+ return url.toString();
15
10
  }
16
11
  /**
17
12
  * Ensures the standard gtag.js queueing stub exists so consent commands can be issued
18
13
  * before the tag itself loads — gtag.js replays the queue in order once it boots.
14
+ *
15
+ * @since 1.0.0-canary.6
19
16
  */
20
- function ensureGtag() {
17
+ function ensureGtag(options = {}) {
21
18
  if (typeof window === "undefined") return;
22
- window.dataLayer ??= [];
19
+ const dataLayerName = options.dataLayerName ?? "dataLayer";
20
+ ensureDataLayer(dataLayerName);
23
21
  window.gtag ??= function gtag() {
24
- window.dataLayer?.push(arguments);
22
+ ensureDataLayer(dataLayerName)?.push(arguments);
25
23
  };
26
24
  return window.gtag;
27
25
  }
28
26
  /**
29
- * Google Consent Mode v2's "default" signal — call before the gtag.js script tag loads
30
- * (this defines the queueing stub itself, so no snippet has to run first) with the
31
- * region-resolved default, so GA4/Ads never fire a hit ahead of it.
27
+ * Loads gtag.js on demand — idempotent (a second call is a no-op) and reuses any
28
+ * existing `dataLayer`/`gtag` stub instead of clobbering it. Queues `js`/`config` before
29
+ * appending the script tag, so gtag.js replays them under the caller's already-applied
30
+ * consent state once it boots. Prefer `buildGtagConsentBootstrapScript` for page load
31
+ * (advanced Consent Mode always injects the tag after the default); use this when the
32
+ * bootstrap did not run, or as an idempotent safety net after a runtime grant.
32
33
  *
33
- * @since 0.5.0-canary.4
34
+ * @since 1.0.0-canary.6
34
35
  */
35
- function setGoogleConsentDefault(decision, options = {}) {
36
- const params = toGoogleConsentParams(decision);
37
- if (options.region !== void 0) params.region = options.region;
38
- if (options.waitForUpdateMs !== void 0) params.wait_for_update = options.waitForUpdateMs;
39
- ensureGtag()?.("consent", "default", params);
36
+ function loadGtagScript(options) {
37
+ if (typeof document === "undefined" || document.querySelector(`script[src^="${GTAG_SCRIPT_BASE_URL}"]`) !== null) return;
38
+ const dataLayerName = options.dataLayerName ?? "dataLayer";
39
+ const gtag = ensureGtag({ dataLayerName });
40
+ if (!gtag) return;
41
+ gtag("js", /* @__PURE__ */ new Date());
42
+ if (options.debugMode === true) gtag("config", options.gaMeasurementId, { debug_mode: true });
43
+ else gtag("config", options.gaMeasurementId);
44
+ const script = document.createElement("script");
45
+ script.async = true;
46
+ script.src = gtagScriptSrc(options.gaMeasurementId, dataLayerName);
47
+ if (options.nonce !== void 0) script.nonce = options.nonce;
48
+ document.head.append(script);
40
49
  }
41
50
  /**
42
- * Google Consent Mode v2's "update" signal — call whenever the visitor's effective
43
- * consent changes (a banner decision, or one synced from another tab), so already-loaded
44
- * GA4/Ads tags pick up the change without a page reload.
51
+ * Expires Google's `_ga` / `_ga_*` cookies on `path=/` and the current host's parent
52
+ * domain. Consent Mode stops using them once denied but never removes them — call from
53
+ * a consent-withdrawal handler so a revoke does not leave identifier cookies behind.
45
54
  *
46
- * @since 0.5.0-canary.4
55
+ * @since 1.0.0-canary.6
47
56
  */
48
- function updateGoogleConsent(decision) {
49
- ensureGtag()?.("consent", "update", toGoogleConsentParams(decision));
57
+ function clearGoogleAnalyticsCookies() {
58
+ if (typeof document === "undefined") return;
59
+ const { hostname } = globalThis.location;
60
+ for (const cookie of document.cookie.split("; ")) {
61
+ const name = cookie.split("=")[0];
62
+ if (name !== void 0 && (name === "_ga" || name.startsWith("_ga_"))) {
63
+ document.cookie = `${name}=; path=/; max-age=0`;
64
+ document.cookie = `${name}=; path=/; max-age=0; domain=.${hostname}`;
65
+ }
66
+ }
50
67
  }
51
68
  /**
52
- * Consent Mode's `ads_data_redaction` flag — with `ad_storage` denied, gtag further
53
- * redacts ad click identifiers (gclid/dclid) from its cookieless pings. Set alongside
54
- * the consent default.
69
+ * Google Consent Mode v2's "update" signal — call whenever the visitor's effective
70
+ * consent changes (a banner decision, or one synced from another tab), so already-loaded
71
+ * GA4/Ads tags pick up the change without a page reload.
55
72
  *
56
73
  * @since 0.5.0-canary.4
57
74
  */
58
- function setGoogleAdsDataRedaction(enabled) {
59
- ensureGtag()?.("set", "ads_data_redaction", enabled);
75
+ function updateGoogleConsent(decision, options = {}) {
76
+ ensureGtag(options)?.("consent", "update", toGoogleConsentParams(decision));
60
77
  }
61
78
  /**
62
- * Consent Mode's `url_passthrough` flag — carries ad click info through page URLs while
63
- * storage is denied, preserving conversion attribution without cookies.
79
+ * Builds the literal JS source for a `<script dangerouslySetInnerHTML>` mounted in
80
+ * `<head>`, before hydration: applies Consent Mode v2's default signal from the visitor's
81
+ * stored decision (falling back to literal `defaultConsent` when none is stored yet),
82
+ * then always loads gtag.js (advanced Consent Mode) so cookieless pings / modeling can
83
+ * run even when storage is denied. A runtime decision change needs `updateGoogleConsent`
84
+ * so the already-loaded tag picks up the grant/deny — this only covers the page-load
85
+ * default + script injection.
64
86
  *
65
- * @since 0.5.0-canary.4
66
- */
67
- function setGoogleUrlPassthrough(enabled) {
68
- ensureGtag()?.("set", "url_passthrough", enabled);
69
- }
70
- /**
71
- * gtag.js event params must be flat string/number/boolean — stringify anything else
72
- * instead of letting GA4 silently drop it.
87
+ * @since 1.0.0-canary.6
73
88
  */
74
- function toGtagParams(props) {
75
- const result = {};
76
- for (const [key, value] of Object.entries(props)) if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") result[key] = value;
77
- else if (value !== void 0 && value !== null) result[key] = JSON.stringify(value);
78
- return result;
89
+ function buildGtagConsentBootstrapScript(options) {
90
+ const { config, dataLayerName = DEFAULT_DATA_LAYER_NAME, defaultConsent, debugMode, gaMeasurementId, nonce } = options;
91
+ const gtagScriptUrl = gtagScriptSrc(gaMeasurementId, dataLayerName);
92
+ const configArgs = debugMode === true ? `${JSON.stringify(gaMeasurementId)}, { debug_mode: true }` : JSON.stringify(gaMeasurementId);
93
+ const nonceAssignment = nonce === void 0 ? "" : `gtagScript.nonce = ${JSON.stringify(nonce)};`;
94
+ return `${buildGoogleConsentBootstrapPreamble({
95
+ consentStorageKey: config.storageKey,
96
+ dataLayerName,
97
+ defaultConsent,
98
+ policyVersion: config.policyVersion
99
+ })}
100
+ gtag("js", new Date());
101
+ gtag("config", ${configArgs});
102
+ var gtagScript = document.createElement("script");
103
+ gtagScript.async = true;
104
+ gtagScript.src = ${JSON.stringify(gtagScriptUrl)};
105
+ ${nonceAssignment}
106
+ document.head.appendChild(gtagScript);
107
+ `;
79
108
  }
80
- const GA4_EVENT_NAME_PATTERN = /^[A-Za-z][\w]{0,39}$/;
81
109
  /**
82
- * Forwards events to `window.gtag`, translating this package's `$`-prefixed built-ins to
83
- * GA4's vocabulary — `$identify` sets `user_id`, `$group` becomes the recommended
84
- * `join_group` event, `$page_viewed` maps to `page_view` (opt-in, see `trackPageViews`).
85
- * Requires the gtag.js snippet plus `gtag('config', measurementId)` mounted once by the
86
- * app. Marked `delivery: "immediate"` — gtag.js has its own batching and unload delivery,
87
- * so queueing in front of it only delays events and replays stale ones next session.
110
+ * Forwards catalog events to `window.gtag` as GA4 custom events. Page views are not this
111
+ * destination's job: `gtag('config', ...)` sends the initial page_view and GA4's Enhanced
112
+ * Measurement tracks SPA history changes. Requires the gtag.js snippet plus
113
+ * `gtag('config', measurementId)` mounted once by the app (see the consent bootstrap) —
114
+ * gtag.js owns its own batching and unload delivery.
88
115
  *
89
116
  * @since 0.5.0-canary.4
90
117
  */
91
118
  function createGoogleAnalyticsDestination(options = {}) {
92
119
  const name = options.name ?? "google-analytics";
93
120
  return {
94
- delivery: "immediate",
95
121
  name,
96
- send(event) {
122
+ async send(event) {
97
123
  if (typeof window === "undefined" || typeof window.gtag !== "function") return;
98
- if (event.name === "$identify") {
99
- if (event.userId !== void 0) window.gtag("set", { user_id: event.userId });
100
- return;
101
- }
102
- if (event.name === "$page_viewed") {
103
- if (options.trackPageViews === true) {
104
- const { href: _href, name: _name, ...extras } = event.props;
105
- window.gtag("event", "page_view", toGtagParams(extras));
106
- }
107
- return;
108
- }
109
- if (event.name === "$group") {
110
- const { groupId, ...traits } = event.props;
111
- window.gtag("event", "join_group", toGtagParams({
112
- group_id: groupId,
113
- ...traits
114
- }));
115
- return;
116
- }
117
- if (!GA4_EVENT_NAME_PATTERN.test(event.name)) {
118
- console.warn(`[tracking] "${name}" dropped event "${event.name}" — GA4 event names must start with a letter and contain only letters, digits, or underscores (max 40 chars)`);
119
- return;
120
- }
121
- window.gtag("event", event.name, toGtagParams(event.props));
124
+ if (!warnUnlessGa4EventName(name, event.name)) return;
125
+ window.gtag("event", event.name, flattenEventProps(event.properties));
122
126
  }
123
127
  };
124
128
  }
125
129
  //#endregion
126
- export { createGoogleAnalyticsDestination, setGoogleAdsDataRedaction, setGoogleConsentDefault, setGoogleUrlPassthrough, updateGoogleConsent };
130
+ export { buildGtagConsentBootstrapScript, clearGoogleAnalyticsCookies, createGoogleAnalyticsDestination, ensureGtag, loadGtagScript, updateGoogleConsent };
@@ -0,0 +1,64 @@
1
+ import { ConsentDecision } from "../core/consent.mjs";
2
+
3
+ //#region src/destinations/google-consent.d.ts
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
+ declare const DEFAULT_DATA_LAYER_NAME = "dataLayer";
10
+ type GoogleConsentState = "denied" | "granted";
11
+ /**
12
+ * Consent Mode v2 params issued via `gtag('consent', …)` — shared by the gtag and GTM
13
+ * bootstraps so signal mapping cannot drift between them.
14
+ *
15
+ * @since 1.0.0-canary.6
16
+ */
17
+ interface GoogleConsentParams {
18
+ ad_personalization: GoogleConsentState;
19
+ ad_storage: GoogleConsentState;
20
+ ad_user_data: GoogleConsentState;
21
+ analytics_storage: GoogleConsentState;
22
+ region?: ReadonlyArray<string> | undefined;
23
+ wait_for_update?: number | undefined;
24
+ }
25
+ /**
26
+ * Maps a package `ConsentDecision` onto Consent Mode v2's four storage signals.
27
+ *
28
+ * @since 1.0.0-canary.6
29
+ */
30
+ declare function toGoogleConsentParams(decision: ConsentDecision): GoogleConsentParams;
31
+ /**
32
+ * @since 1.0.0-canary.6
33
+ */
34
+ interface GoogleConsentBootstrapPreambleOptions {
35
+ /** localStorage key holding the package's `ConsentRecord`. */
36
+ consentStorageKey: string;
37
+ dataLayerName: string;
38
+ /** Literal fallback when nothing valid is stored — baked into the script as JSON. */
39
+ defaultConsent: ConsentDecision;
40
+ policyVersion: string;
41
+ }
42
+ /**
43
+ * Shared head of the gtag and GTM consent bootstraps: dataLayer init, `gtag()` stub,
44
+ * stored-decision read (policy-version + shape checked), and the Consent Mode v2
45
+ * "default" signal. The builders append only their tag-specific tail, so the consent
46
+ * logic cannot drift between them.
47
+ *
48
+ * @since 1.0.0-canary.6
49
+ */
50
+ declare function buildGoogleConsentBootstrapPreamble(options: GoogleConsentBootstrapPreambleOptions): string;
51
+ /**
52
+ * Reads or creates a named `window[dataLayerName]` queue array.
53
+ *
54
+ * @since 1.0.0-canary.6
55
+ */
56
+ declare function ensureDataLayer(dataLayerName: string): Array<unknown> | undefined;
57
+ /**
58
+ * Warns and returns `false` when `eventName` would be rejected by GA4.
59
+ *
60
+ * @since 1.0.0-canary.6
61
+ */
62
+ declare function warnUnlessGa4EventName(destinationName: string, eventName: string): boolean;
63
+ //#endregion
64
+ export { DEFAULT_DATA_LAYER_NAME, GoogleConsentBootstrapPreambleOptions, GoogleConsentParams, buildGoogleConsentBootstrapPreamble, ensureDataLayer, toGoogleConsentParams, warnUnlessGa4EventName };
@@ -0,0 +1,102 @@
1
+ import { CONSENT_CATEGORIES } from "../core/consent.mjs";
2
+ //#region src/destinations/google-consent.ts
3
+ /**
4
+ * gtag.js/gtm.js's default queue-array name — shared so the gtag and GTM helpers cannot disagree.
5
+ *
6
+ * @since 1.0.0-canary.6
7
+ */
8
+ const DEFAULT_DATA_LAYER_NAME = "dataLayer";
9
+ /**
10
+ * Which per-category decision each Consent Mode v2 signal follows: `analytics` drives
11
+ * `analytics_storage`; `ads` drives all three ads signals together.
12
+ */
13
+ const GOOGLE_CONSENT_SIGNAL_CATEGORIES = {
14
+ ad_personalization: "ads",
15
+ ad_storage: "ads",
16
+ ad_user_data: "ads",
17
+ analytics_storage: "analytics"
18
+ };
19
+ /**
20
+ * Maps a package `ConsentDecision` onto Consent Mode v2's four storage signals.
21
+ *
22
+ * @since 1.0.0-canary.6
23
+ */
24
+ function toGoogleConsentParams(decision) {
25
+ return {
26
+ ad_personalization: decision[GOOGLE_CONSENT_SIGNAL_CATEGORIES.ad_personalization] ? "granted" : "denied",
27
+ ad_storage: decision[GOOGLE_CONSENT_SIGNAL_CATEGORIES.ad_storage] ? "granted" : "denied",
28
+ ad_user_data: decision[GOOGLE_CONSENT_SIGNAL_CATEGORIES.ad_user_data] ? "granted" : "denied",
29
+ analytics_storage: decision[GOOGLE_CONSENT_SIGNAL_CATEGORIES.analytics_storage] ? "granted" : "denied"
30
+ };
31
+ }
32
+ /** JS fragment that validates a stored `ConsentRecord.decision` shape inside a bootstrap. */
33
+ function consentDecisionShapeCheckExpression() {
34
+ return CONSENT_CATEGORIES.map((category) => `typeof record.decision[${JSON.stringify(category)}] === "boolean"`).join(" && ");
35
+ }
36
+ /**
37
+ * JS object-literal fragment for `gtag("consent", "default", { … })` — generated from
38
+ * {@link GOOGLE_CONSENT_SIGNAL_CATEGORIES} so runtime and bootstrap stay aligned.
39
+ */
40
+ function consentSignalAssignmentsExpression() {
41
+ return Object.keys(GOOGLE_CONSENT_SIGNAL_CATEGORIES).map((signal) => {
42
+ return `${signal}: consent.${GOOGLE_CONSENT_SIGNAL_CATEGORIES[signal]} ? "granted" : "denied"`;
43
+ }).join(",\n ");
44
+ }
45
+ /**
46
+ * Shared head of the gtag and GTM consent bootstraps: dataLayer init, `gtag()` stub,
47
+ * stored-decision read (policy-version + shape checked), and the Consent Mode v2
48
+ * "default" signal. The builders append only their tag-specific tail, so the consent
49
+ * logic cannot drift between them.
50
+ *
51
+ * @since 1.0.0-canary.6
52
+ */
53
+ function buildGoogleConsentBootstrapPreamble(options) {
54
+ const dataLayerAccess = `window[${JSON.stringify(options.dataLayerName)}]`;
55
+ return `
56
+ ${dataLayerAccess} = ${dataLayerAccess} || [];
57
+ function gtag(){${dataLayerAccess}.push(arguments);}
58
+ var storedConsent = null;
59
+ try {
60
+ var record = JSON.parse(window.localStorage.getItem(${JSON.stringify(options.consentStorageKey)}));
61
+ if (record && record.policyVersion === ${JSON.stringify(options.policyVersion)} && record.decision && ${consentDecisionShapeCheckExpression()}) {
62
+ storedConsent = record.decision;
63
+ }
64
+ } catch (e) {}
65
+ var consent = storedConsent || (${JSON.stringify(options.defaultConsent)});
66
+ gtag("consent", "default", {
67
+ ${consentSignalAssignmentsExpression()}
68
+ });`;
69
+ }
70
+ /**
71
+ * Reads or creates a named `window[dataLayerName]` queue array.
72
+ *
73
+ * @since 1.0.0-canary.6
74
+ */
75
+ function ensureDataLayer(dataLayerName) {
76
+ if (typeof window === "undefined") return;
77
+ const existing = Reflect.get(window, dataLayerName);
78
+ const layer = Array.isArray(existing) ? existing : [];
79
+ Reflect.set(window, dataLayerName, layer);
80
+ return layer;
81
+ }
82
+ /**
83
+ * GA4's event-name rules (letter start, letters/digits/underscores only, ≤40 chars).
84
+ * Catalog `track` names that fail this are accepted by gtag/MP HTTP but dropped at GA4
85
+ * processing with no client error — destinations warn and skip instead of sending nowhere.
86
+ */
87
+ const GA4_EVENT_NAME_PATTERN = /^[A-Za-z][\w]{0,39}$/;
88
+ function isGa4EventName(name) {
89
+ return GA4_EVENT_NAME_PATTERN.test(name);
90
+ }
91
+ /**
92
+ * Warns and returns `false` when `eventName` would be rejected by GA4.
93
+ *
94
+ * @since 1.0.0-canary.6
95
+ */
96
+ function warnUnlessGa4EventName(destinationName, eventName) {
97
+ if (isGa4EventName(eventName)) return true;
98
+ console.warn(`[tracking] "${destinationName}" dropped event "${eventName}" — GA4 event names must start with a letter and contain only letters, digits, or underscores (max 40 chars)`);
99
+ return false;
100
+ }
101
+ //#endregion
102
+ export { DEFAULT_DATA_LAYER_NAME, buildGoogleConsentBootstrapPreamble, ensureDataLayer, toGoogleConsentParams, warnUnlessGa4EventName };
@@ -1,5 +1,2 @@
1
- import { Ga4MeasurementProtocolDestinationOptions, createGa4MeasurementProtocolDestination, extractGa4ClientId, extractGa4SessionId } from "./ga4-measurement-protocol.mjs";
2
- import { GoogleAnalyticsDestinationOptions, GoogleConsentDefaultOptions, createGoogleAnalyticsDestination, setGoogleAdsDataRedaction, setGoogleConsentDefault, setGoogleUrlPassthrough, updateGoogleConsent } from "./google-analytics.mjs";
3
- import { HttpDestinationOptions, createHttpDestination } from "./http-destination.mjs";
4
- import { createVercelAnalyticsDestination } from "./vercel-analytics.mjs";
5
- export { type Ga4MeasurementProtocolDestinationOptions, type GoogleAnalyticsDestinationOptions, type GoogleConsentDefaultOptions, type HttpDestinationOptions, createGa4MeasurementProtocolDestination, createGoogleAnalyticsDestination, createHttpDestination, createVercelAnalyticsDestination, extractGa4ClientId, extractGa4SessionId, setGoogleAdsDataRedaction, setGoogleConsentDefault, setGoogleUrlPassthrough, updateGoogleConsent };
1
+ import { EnsureGtagOptions, GoogleAnalyticsDestinationOptions, GtagConsentBootstrapOptions, GtagFunction, LoadGtagScriptOptions, buildGtagConsentBootstrapScript, clearGoogleAnalyticsCookies, createGoogleAnalyticsDestination, ensureGtag, loadGtagScript, updateGoogleConsent } from "./google-analytics.mjs";
2
+ export { type EnsureGtagOptions, type GoogleAnalyticsDestinationOptions, type GtagConsentBootstrapOptions, type GtagFunction, type LoadGtagScriptOptions, buildGtagConsentBootstrapScript, clearGoogleAnalyticsCookies, createGoogleAnalyticsDestination, ensureGtag, loadGtagScript, updateGoogleConsent };
@@ -1,5 +1,2 @@
1
- import { createGa4MeasurementProtocolDestination, extractGa4ClientId, extractGa4SessionId } from "./ga4-measurement-protocol.mjs";
2
- import { createGoogleAnalyticsDestination, setGoogleAdsDataRedaction, setGoogleConsentDefault, setGoogleUrlPassthrough, updateGoogleConsent } from "./google-analytics.mjs";
3
- import { createHttpDestination } from "./http-destination.mjs";
4
- import { createVercelAnalyticsDestination } from "./vercel-analytics.mjs";
5
- export { createGa4MeasurementProtocolDestination, createGoogleAnalyticsDestination, createHttpDestination, createVercelAnalyticsDestination, extractGa4ClientId, extractGa4SessionId, setGoogleAdsDataRedaction, setGoogleConsentDefault, setGoogleUrlPassthrough, updateGoogleConsent };
1
+ import { buildGtagConsentBootstrapScript, clearGoogleAnalyticsCookies, createGoogleAnalyticsDestination, ensureGtag, loadGtagScript, updateGoogleConsent } from "./google-analytics.mjs";
2
+ export { buildGtagConsentBootstrapScript, clearGoogleAnalyticsCookies, createGoogleAnalyticsDestination, ensureGtag, loadGtagScript, updateGoogleConsent };
@@ -0,0 +1,20 @@
1
+ //#region src/destinations/shared.d.ts
2
+ /**
3
+ * @since 1.0.0-canary.6
4
+ */
5
+ type FlatPropertyValue = boolean | number | string;
6
+ /**
7
+ * Event params must be flat string/number/boolean (optionally `null`) — stringify
8
+ * anything else instead of letting the destination silently drop it.
9
+ *
10
+ * @since 1.0.0-canary.6
11
+ */
12
+ declare function flattenEventProps(properties: Record<string, unknown>): Record<string, FlatPropertyValue>;
13
+ /**
14
+ * @since 1.0.0-canary.6
15
+ */
16
+ declare function flattenEventProps(properties: Record<string, unknown>, options: {
17
+ allowNull: true;
18
+ }): Record<string, FlatPropertyValue | null>;
19
+ //#endregion
20
+ export { FlatPropertyValue, flattenEventProps };
@@ -0,0 +1,13 @@
1
+ //#region src/destinations/shared.ts
2
+ /**
3
+ * @since 1.0.0-canary.6
4
+ */
5
+ function flattenEventProps(properties, options = {}) {
6
+ const result = {};
7
+ for (const [key, value] of Object.entries(properties)) if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") result[key] = value;
8
+ else if (options.allowNull === true && value === null) result[key] = null;
9
+ else if (value !== void 0 && value !== null) result[key] = JSON.stringify(value);
10
+ return result;
11
+ }
12
+ //#endregion
13
+ export { flattenEventProps };