@codefast/tracking 0.0.0 → 0.5.0-canary.5
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.
- package/CHANGELOG.md +44 -0
- package/README.md +79 -9
- package/dist/client/consent-storage.d.mts +11 -3
- package/dist/client/consent-storage.mjs +45 -9
- package/dist/client/create-client-tracker.d.mts +10 -0
- package/dist/client/create-client-tracker.mjs +14 -1
- package/dist/client/gpc.d.mts +2 -0
- package/dist/client/gpc.mjs +2 -0
- package/dist/client/lifecycle.d.mts +5 -0
- package/dist/client/lifecycle.mjs +2 -0
- package/dist/client/local-storage.d.mts +5 -2
- package/dist/client/local-storage.mjs +12 -5
- package/dist/client/queue.d.mts +7 -0
- package/dist/client/queue.mjs +2 -0
- package/dist/client/router.d.mts +4 -0
- package/dist/client/router.mjs +2 -0
- package/dist/core/consent.d.mts +61 -9
- package/dist/core/consent.mjs +39 -7
- package/dist/core/destination.d.mts +10 -0
- package/dist/core/event-catalog.d.mts +8 -0
- package/dist/core/event-catalog.mjs +2 -0
- package/dist/core/event-id.d.mts +2 -0
- package/dist/core/event-id.mjs +2 -0
- package/dist/core/index.d.mts +2 -2
- package/dist/core/index.mjs +2 -2
- package/dist/core/tracked-event.d.mts +2 -0
- package/dist/destinations/ga4-measurement-protocol.d.mts +54 -0
- package/dist/destinations/ga4-measurement-protocol.mjs +89 -0
- package/dist/destinations/google-analytics.d.mts +98 -0
- package/dist/destinations/google-analytics.mjs +126 -0
- package/dist/destinations/http-destination.d.mts +5 -0
- package/dist/destinations/http-destination.mjs +2 -0
- package/dist/destinations/index.d.mts +3 -1
- package/dist/destinations/index.mjs +3 -1
- package/dist/destinations/vercel-analytics.d.mts +4 -2
- package/dist/destinations/vercel-analytics.mjs +5 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/react/consent-banner.d.mts +140 -18
- package/dist/react/consent-banner.mjs +195 -28
- package/dist/react/index.d.mts +2 -2
- package/dist/react/index.mjs +2 -2
- package/dist/react/use-consent.d.mts +30 -5
- package/dist/react/use-consent.mjs +38 -15
- package/dist/server/create-server-tracker.d.mts +14 -0
- package/dist/server/create-server-tracker.mjs +24 -5
- package/dist/server/region.d.mts +4 -0
- package/dist/server/region.mjs +4 -0
- package/package.json +13 -2
- package/src/client/consent-storage.ts +75 -10
- package/src/client/create-client-tracker.ts +30 -1
- package/src/client/gpc.ts +2 -0
- package/src/client/lifecycle.ts +5 -0
- package/src/client/local-storage.ts +21 -6
- package/src/client/queue.ts +7 -0
- package/src/client/router.ts +4 -0
- package/src/core/consent.ts +85 -11
- package/src/core/destination.ts +10 -0
- package/src/core/event-catalog.ts +8 -0
- package/src/core/event-id.ts +2 -0
- package/src/core/index.ts +15 -2
- package/src/core/tracked-event.ts +2 -0
- package/src/css/consent.css +119 -0
- package/src/destinations/ga4-measurement-protocol.ts +166 -0
- package/src/destinations/google-analytics.ts +233 -0
- package/src/destinations/http-destination.ts +5 -0
- package/src/destinations/index.ts +16 -0
- package/src/destinations/vercel-analytics.ts +5 -2
- package/src/react/consent-banner.tsx +301 -31
- package/src/react/index.ts +26 -2
- package/src/react/use-consent.ts +81 -23
- package/src/server/create-server-tracker.ts +39 -16
- package/src/server/region.ts +4 -0
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/* -------------------------------------------------------------------------
|
|
2
|
+
* Optional consent UI theme
|
|
3
|
+
*
|
|
4
|
+
* Plain CSS over the components' data-slot attributes — no Tailwind, no
|
|
5
|
+
* design-system dependency. Import it for a sensible default look:
|
|
6
|
+
*
|
|
7
|
+
* @import "@codefast/tracking/css/consent.css";
|
|
8
|
+
*
|
|
9
|
+
* Every color routes through a `--consent-*` custom property with a
|
|
10
|
+
* `light-dark()` fallback, so a host app can retheme by defining those
|
|
11
|
+
* properties (or skip this file entirely and style the slots itself).
|
|
12
|
+
* ------------------------------------------------------------------------- */
|
|
13
|
+
|
|
14
|
+
[data-slot="consent-banner"] {
|
|
15
|
+
position: fixed;
|
|
16
|
+
inset-inline: 1rem;
|
|
17
|
+
bottom: 1rem;
|
|
18
|
+
z-index: 50;
|
|
19
|
+
margin-inline: auto;
|
|
20
|
+
max-width: 24rem;
|
|
21
|
+
padding: 1.25rem;
|
|
22
|
+
border: 1px solid var(--consent-border, light-dark(rgb(0 0 0 / 12%), rgb(255 255 255 / 14%)));
|
|
23
|
+
border-radius: 1rem;
|
|
24
|
+
background: var(--consent-surface, light-dark(#fff, #1c1c1e));
|
|
25
|
+
color: var(--consent-fg, light-dark(#1c1c1e, #f2f2f7));
|
|
26
|
+
box-shadow: 0 12px 32px rgb(0 0 0 / 18%);
|
|
27
|
+
font-size: 0.875rem;
|
|
28
|
+
line-height: 1.5;
|
|
29
|
+
animation: consent-banner-in 220ms ease-out;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
@media (min-width: 640px) {
|
|
33
|
+
[data-slot="consent-banner"] {
|
|
34
|
+
inset-inline: auto 1rem;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
@keyframes consent-banner-in {
|
|
39
|
+
from {
|
|
40
|
+
opacity: 0;
|
|
41
|
+
transform: translateY(1rem);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
@media (prefers-reduced-motion: reduce) {
|
|
46
|
+
[data-slot="consent-banner"] {
|
|
47
|
+
animation: none;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
[data-slot="consent-title"] {
|
|
52
|
+
margin: 0 0 0.375rem;
|
|
53
|
+
font-size: 0.875rem;
|
|
54
|
+
font-weight: 600;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
[data-slot="consent-description"] {
|
|
58
|
+
margin: 0 0 1rem;
|
|
59
|
+
color: var(--consent-muted, light-dark(rgb(28 28 30 / 65%), rgb(242 242 247 / 65%)));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
[data-slot="consent-description"] a {
|
|
63
|
+
color: inherit;
|
|
64
|
+
text-decoration: underline;
|
|
65
|
+
text-underline-offset: 0.2em;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
[data-slot="consent-preferences"] {
|
|
69
|
+
display: flex;
|
|
70
|
+
flex-direction: column;
|
|
71
|
+
gap: 0.5rem;
|
|
72
|
+
margin-bottom: 1rem;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
[data-slot="consent-category"] {
|
|
76
|
+
display: flex;
|
|
77
|
+
gap: 0.5rem;
|
|
78
|
+
align-items: baseline;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
[data-slot="consent-actions"] {
|
|
82
|
+
display: flex;
|
|
83
|
+
gap: 0.5rem;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
[data-slot="consent-action"] {
|
|
87
|
+
flex: 1;
|
|
88
|
+
padding: 0.5rem 0.75rem;
|
|
89
|
+
border: 1px solid var(--consent-border, light-dark(rgb(0 0 0 / 12%), rgb(255 255 255 / 14%)));
|
|
90
|
+
border-radius: 0.5rem;
|
|
91
|
+
background: transparent;
|
|
92
|
+
color: inherit;
|
|
93
|
+
font: inherit;
|
|
94
|
+
font-weight: 500;
|
|
95
|
+
cursor: pointer;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/* The affirmative actions carry the accent; Reject stays equally prominent, just outlined. */
|
|
99
|
+
[data-slot="consent-action"][data-action="accept"],
|
|
100
|
+
[data-slot="consent-action"][data-action="save"] {
|
|
101
|
+
border-color: transparent;
|
|
102
|
+
background: var(--consent-accent, light-dark(#1c1c1e, #f2f2f7));
|
|
103
|
+
color: var(--consent-accent-fg, light-dark(#fff, #1c1c1e));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
[data-slot="consent-toggle"] {
|
|
107
|
+
position: fixed;
|
|
108
|
+
inset-inline-start: 1rem;
|
|
109
|
+
bottom: 1rem;
|
|
110
|
+
z-index: 50;
|
|
111
|
+
padding: 0.375rem 0.75rem;
|
|
112
|
+
border: 1px solid var(--consent-border, light-dark(rgb(0 0 0 / 12%), rgb(255 255 255 / 14%)));
|
|
113
|
+
border-radius: 9999px;
|
|
114
|
+
background: var(--consent-surface, light-dark(#fff, #1c1c1e));
|
|
115
|
+
color: var(--consent-muted, light-dark(rgb(28 28 30 / 65%), rgb(242 242 247 / 65%)));
|
|
116
|
+
font: inherit;
|
|
117
|
+
font-size: 0.75rem;
|
|
118
|
+
cursor: pointer;
|
|
119
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import type { Destination } from "#/core/destination";
|
|
2
|
+
|
|
3
|
+
type MeasurementProtocolParamValue = boolean | number | string;
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Measurement Protocol event params must be flat string/number/boolean — stringify
|
|
7
|
+
* anything else instead of letting GA4 silently drop it.
|
|
8
|
+
*/
|
|
9
|
+
function toMeasurementProtocolParams(props: Record<string, unknown>): Record<string, MeasurementProtocolParamValue> {
|
|
10
|
+
const result: Record<string, MeasurementProtocolParamValue> = {};
|
|
11
|
+
|
|
12
|
+
for (const [key, value] of Object.entries(props)) {
|
|
13
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
14
|
+
result[key] = value;
|
|
15
|
+
} else if (value !== undefined && value !== null) {
|
|
16
|
+
result[key] = JSON.stringify(value);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
return result;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function readCookie(cookieHeader: string | undefined, cookieName: string): string | undefined {
|
|
24
|
+
if (!cookieHeader) {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
for (const part of cookieHeader.split(";")) {
|
|
29
|
+
const separatorIndex = part.indexOf("=");
|
|
30
|
+
|
|
31
|
+
if (separatorIndex !== -1 && part.slice(0, separatorIndex).trim() === cookieName) {
|
|
32
|
+
return part.slice(separatorIndex + 1).trim();
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Reads gtag.js's own client ID from a request Cookie header — `_ga=GA1.1.123.456` →
|
|
41
|
+
* `123.456`. This (not an app-generated anonymous ID) is the value GA4 joins hits on, so
|
|
42
|
+
* pass it as `clientId` to make server events land on the same user as the visitor's
|
|
43
|
+
* client-side hits.
|
|
44
|
+
*
|
|
45
|
+
* @since 0.5.0-canary.4
|
|
46
|
+
*/
|
|
47
|
+
export function extractGa4ClientId(cookieHeader: string | undefined): string | undefined {
|
|
48
|
+
const value = readCookie(cookieHeader, "_ga");
|
|
49
|
+
|
|
50
|
+
if (!value) {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Format: GA1.<domain-depth>.<random>.<timestamp> — the client ID is the last two segments.
|
|
55
|
+
const segments = value.split(".");
|
|
56
|
+
|
|
57
|
+
return segments.length >= 4 ? segments.slice(-2).join(".") : undefined;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Reads the current GA4 session ID from the per-stream `_ga_<suffix>` cookie
|
|
62
|
+
* (`G-ABC123` → `_ga_ABC123`) — handles both the dot-delimited `GS1` and the
|
|
63
|
+
* `$`-delimited `GS2` value formats.
|
|
64
|
+
*
|
|
65
|
+
* @since 0.5.0-canary.4
|
|
66
|
+
*/
|
|
67
|
+
export function extractGa4SessionId(cookieHeader: string | undefined, measurementId: string): string | undefined {
|
|
68
|
+
const value = readCookie(cookieHeader, `_ga_${measurementId.replace(/^G-/, "")}`);
|
|
69
|
+
|
|
70
|
+
if (!value) {
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// GS1.1.<session_id>.<count>... vs GS2.1.s<session_id>$o<count>... — the session ID is
|
|
75
|
+
// the first number after the version prefix either way.
|
|
76
|
+
const match = /^GS\d+\.\d+\.s?(\d+)/.exec(value);
|
|
77
|
+
|
|
78
|
+
return match?.[1];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* @since 0.5.0-canary.4
|
|
83
|
+
*/
|
|
84
|
+
export interface Ga4MeasurementProtocolDestinationOptions {
|
|
85
|
+
apiSecret: string;
|
|
86
|
+
/**
|
|
87
|
+
* gtag.js's client ID for this visitor (see `extractGa4ClientId`). Without it the
|
|
88
|
+
* event falls back to the tracker's anonymous ID, which GA4 treats as a *different
|
|
89
|
+
* user* than the visitor's client-side hits — pass it whenever the request carries a
|
|
90
|
+
* `_ga` cookie.
|
|
91
|
+
*/
|
|
92
|
+
clientId?: string | undefined;
|
|
93
|
+
/** Routes to GA4's `/debug/mp/collect` validation endpoint — hits are validated but never recorded. */
|
|
94
|
+
debug?: boolean;
|
|
95
|
+
measurementId: string;
|
|
96
|
+
name?: string;
|
|
97
|
+
/**
|
|
98
|
+
* Current GA4 session for this visitor (see `extractGa4SessionId`). Without a
|
|
99
|
+
* `session_id`, GA4 accepts the event but leaves it out of session-scoped and realtime
|
|
100
|
+
* reporting.
|
|
101
|
+
*/
|
|
102
|
+
sessionId?: string | undefined;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Server-side GA4 via the Measurement Protocol — for server-owned events (checkout,
|
|
107
|
+
* signup) that must land in GA4 without depending on client-side gtag.js. MP is designed
|
|
108
|
+
* to *augment* gtag.js data, so correlation hinges on echoing gtag's own identifiers:
|
|
109
|
+
* `clientId` from the `_ga` cookie and `sessionId` from the `_ga_<stream>` cookie.
|
|
110
|
+
*
|
|
111
|
+
* @since 0.5.0-canary.4
|
|
112
|
+
*/
|
|
113
|
+
export function createGa4MeasurementProtocolDestination(
|
|
114
|
+
options: Ga4MeasurementProtocolDestinationOptions,
|
|
115
|
+
): Destination {
|
|
116
|
+
const name = options.name ?? "ga4-measurement-protocol";
|
|
117
|
+
const host = options.debug
|
|
118
|
+
? "https://www.google-analytics.com/debug/mp/collect"
|
|
119
|
+
: "https://www.google-analytics.com/mp/collect";
|
|
120
|
+
const endpoint = `${host}?measurement_id=${encodeURIComponent(options.measurementId)}&api_secret=${encodeURIComponent(options.apiSecret)}`;
|
|
121
|
+
|
|
122
|
+
return {
|
|
123
|
+
name,
|
|
124
|
+
async send(event) {
|
|
125
|
+
// GA4 has no alias concept — identity merge happens via user_id on later events.
|
|
126
|
+
if (event.name === "$alias") {
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// join_group is GA4's recommended-event equivalent of a group association.
|
|
131
|
+
const eventName = event.name === "$group" ? "join_group" : event.name;
|
|
132
|
+
const props = event.name === "$group" ? renameGroupIdProp(event.props) : event.props;
|
|
133
|
+
const params = toMeasurementProtocolParams(props);
|
|
134
|
+
|
|
135
|
+
if (options.sessionId !== undefined && params.session_id === undefined) {
|
|
136
|
+
params.session_id = options.sessionId;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Without an engagement time GA4 won't count the user as active in realtime;
|
|
140
|
+
// 100ms is the fallback Google's own MP examples use when elapsed time is unknown.
|
|
141
|
+
params.engagement_time_msec ??= 100;
|
|
142
|
+
|
|
143
|
+
const response = await fetch(endpoint, {
|
|
144
|
+
body: JSON.stringify({
|
|
145
|
+
client_id: options.clientId ?? event.anonymousId,
|
|
146
|
+
events: [{ name: eventName, params }],
|
|
147
|
+
// MP stamps receipt time otherwise — retried events would drift.
|
|
148
|
+
timestamp_micros: event.timestamp * 1000,
|
|
149
|
+
...(event.userId === undefined ? {} : { user_id: event.userId }),
|
|
150
|
+
}),
|
|
151
|
+
headers: { "content-type": "application/json" },
|
|
152
|
+
method: "POST",
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
if (!response.ok) {
|
|
156
|
+
throw new Error(`"${name}" destination responded with ${String(response.status)}`);
|
|
157
|
+
}
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function renameGroupIdProp(props: Record<string, unknown>): Record<string, unknown> {
|
|
163
|
+
const { groupId, ...traits } = props;
|
|
164
|
+
|
|
165
|
+
return { group_id: groupId, ...traits };
|
|
166
|
+
}
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import type { ConsentDecision } from "#/core/consent";
|
|
2
|
+
import type { Destination } from "#/core/destination";
|
|
3
|
+
|
|
4
|
+
type GtagPropertyValue = boolean | number | string;
|
|
5
|
+
|
|
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
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* All signatures share one `gtag` global, so they must live in a single overloaded type —
|
|
19
|
+
* two separate `declare global` augmentations with different signatures for the same
|
|
20
|
+
* property is a TS error, not a merge.
|
|
21
|
+
*/
|
|
22
|
+
type GtagFunction = {
|
|
23
|
+
(command: "consent", action: "default" | "update", params: GoogleConsentParams): void;
|
|
24
|
+
(command: "event", eventName: string, params?: Record<string, GtagPropertyValue>): void;
|
|
25
|
+
(command: "set", params: Record<string, GtagPropertyValue>): void;
|
|
26
|
+
(command: "set", key: string, value: boolean): void;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
declare global {
|
|
30
|
+
interface Window {
|
|
31
|
+
dataLayer?: Array<unknown>;
|
|
32
|
+
gtag?: GtagFunction;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
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.
|
|
40
|
+
*/
|
|
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
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Ensures the standard gtag.js queueing stub exists so consent commands can be issued
|
|
54
|
+
* before the tag itself loads — gtag.js replays the queue in order once it boots.
|
|
55
|
+
*/
|
|
56
|
+
function ensureGtag(): GtagFunction | undefined {
|
|
57
|
+
if (typeof window === "undefined") {
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
window.dataLayer ??= [];
|
|
62
|
+
|
|
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.
|
|
65
|
+
window.gtag ??= function gtag() {
|
|
66
|
+
window.dataLayer?.push(arguments);
|
|
67
|
+
} as GtagFunction;
|
|
68
|
+
|
|
69
|
+
return window.gtag;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* @since 0.5.0-canary.4
|
|
74
|
+
*/
|
|
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;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
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.
|
|
86
|
+
*
|
|
87
|
+
* @since 0.5.0-canary.4
|
|
88
|
+
*/
|
|
89
|
+
export function setGoogleConsentDefault(decision: ConsentDecision, options: GoogleConsentDefaultOptions = {}): void {
|
|
90
|
+
const params = toGoogleConsentParams(decision);
|
|
91
|
+
|
|
92
|
+
if (options.region !== undefined) {
|
|
93
|
+
params.region = options.region;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
if (options.waitForUpdateMs !== undefined) {
|
|
97
|
+
params.wait_for_update = options.waitForUpdateMs;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
ensureGtag()?.("consent", "default", params);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
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.
|
|
107
|
+
*
|
|
108
|
+
* @since 0.5.0-canary.4
|
|
109
|
+
*/
|
|
110
|
+
export function updateGoogleConsent(decision: ConsentDecision): void {
|
|
111
|
+
ensureGtag()?.("consent", "update", toGoogleConsentParams(decision));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
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.
|
|
118
|
+
*
|
|
119
|
+
* @since 0.5.0-canary.4
|
|
120
|
+
*/
|
|
121
|
+
export function setGoogleAdsDataRedaction(enabled: boolean): void {
|
|
122
|
+
ensureGtag()?.("set", "ads_data_redaction", enabled);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
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
|
|
130
|
+
*/
|
|
131
|
+
export function setGoogleUrlPassthrough(enabled: boolean): void {
|
|
132
|
+
ensureGtag()?.("set", "url_passthrough", enabled);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* gtag.js event params must be flat string/number/boolean — stringify anything else
|
|
137
|
+
* instead of letting GA4 silently drop it.
|
|
138
|
+
*/
|
|
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;
|
|
151
|
+
}
|
|
152
|
+
|
|
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
|
+
/**
|
|
158
|
+
* @since 0.5.0-canary.4
|
|
159
|
+
*/
|
|
160
|
+
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;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
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.
|
|
179
|
+
*
|
|
180
|
+
* @since 0.5.0-canary.4
|
|
181
|
+
*/
|
|
182
|
+
export function createGoogleAnalyticsDestination(options: GoogleAnalyticsDestinationOptions = {}): Destination {
|
|
183
|
+
const name = options.name ?? "google-analytics";
|
|
184
|
+
|
|
185
|
+
return {
|
|
186
|
+
delivery: "immediate",
|
|
187
|
+
name,
|
|
188
|
+
send(event) {
|
|
189
|
+
if (typeof window === "undefined" || typeof window.gtag !== "function") {
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
|
|
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
|
+
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
window.gtag("event", event.name, toGtagParams(event.props));
|
|
231
|
+
},
|
|
232
|
+
};
|
|
233
|
+
}
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import type { Destination } from "#/core/destination";
|
|
2
2
|
|
|
3
|
+
/**
|
|
4
|
+
* @since 0.5.0-canary.4
|
|
5
|
+
*/
|
|
3
6
|
export interface HttpDestinationOptions {
|
|
4
7
|
endpoint: string;
|
|
5
8
|
headers?: Record<string, string>;
|
|
@@ -9,6 +12,8 @@ export interface HttpDestinationOptions {
|
|
|
9
12
|
/**
|
|
10
13
|
* Generic fetch-based `Destination` — the building block for a real provider adapter
|
|
11
14
|
* (PostHog, GA4, ...); those ship their own payload shape and aren't implemented here.
|
|
15
|
+
*
|
|
16
|
+
* @since 0.5.0-canary.4
|
|
12
17
|
*/
|
|
13
18
|
export function createHttpDestination(options: HttpDestinationOptions): Destination {
|
|
14
19
|
return {
|
|
@@ -1,3 +1,19 @@
|
|
|
1
|
+
export type { Ga4MeasurementProtocolDestinationOptions } from "#/destinations/ga4-measurement-protocol";
|
|
2
|
+
export {
|
|
3
|
+
createGa4MeasurementProtocolDestination,
|
|
4
|
+
extractGa4ClientId,
|
|
5
|
+
extractGa4SessionId,
|
|
6
|
+
} from "#/destinations/ga4-measurement-protocol";
|
|
7
|
+
|
|
8
|
+
export type { GoogleAnalyticsDestinationOptions, GoogleConsentDefaultOptions } from "#/destinations/google-analytics";
|
|
9
|
+
export {
|
|
10
|
+
createGoogleAnalyticsDestination,
|
|
11
|
+
setGoogleAdsDataRedaction,
|
|
12
|
+
setGoogleConsentDefault,
|
|
13
|
+
setGoogleUrlPassthrough,
|
|
14
|
+
updateGoogleConsent,
|
|
15
|
+
} from "#/destinations/google-analytics";
|
|
16
|
+
|
|
1
17
|
export type { HttpDestinationOptions } from "#/destinations/http-destination";
|
|
2
18
|
export { createHttpDestination } from "#/destinations/http-destination";
|
|
3
19
|
|
|
@@ -23,12 +23,15 @@ function toVercelAnalyticsProps(props: Record<string, unknown>): Record<string,
|
|
|
23
23
|
}
|
|
24
24
|
|
|
25
25
|
/**
|
|
26
|
-
* `track()` only pushes onto Vercel's own in-page queue (`window.va`/`window.vaq`)
|
|
27
|
-
*
|
|
26
|
+
* `track()` only pushes onto Vercel's own in-page queue (`window.va`/`window.vaq`), which
|
|
27
|
+
* handles batching and unload delivery itself — hence `delivery: "immediate"`. Requires
|
|
28
28
|
* `<Analytics />` from `@vercel/analytics/react` to be mounted once in the app.
|
|
29
|
+
*
|
|
30
|
+
* @since 0.5.0-canary.4
|
|
29
31
|
*/
|
|
30
32
|
export function createVercelAnalyticsDestination(name = "vercel-analytics"): Destination {
|
|
31
33
|
return {
|
|
34
|
+
delivery: "immediate",
|
|
32
35
|
name,
|
|
33
36
|
send(event) {
|
|
34
37
|
track(event.name, toVercelAnalyticsProps(event.props));
|