@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,166 +0,0 @@
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
- }
@@ -1,33 +0,0 @@
1
- import type { Destination } from "#/core/destination";
2
-
3
- /**
4
- * @since 0.5.0-canary.4
5
- */
6
- export interface HttpDestinationOptions {
7
- endpoint: string;
8
- headers?: Record<string, string>;
9
- name: string;
10
- }
11
-
12
- /**
13
- * Generic fetch-based `Destination` — the building block for a real provider adapter
14
- * (PostHog, GA4, ...); those ship their own payload shape and aren't implemented here.
15
- *
16
- * @since 0.5.0-canary.4
17
- */
18
- export function createHttpDestination(options: HttpDestinationOptions): Destination {
19
- return {
20
- name: options.name,
21
- async send(event) {
22
- const response = await fetch(options.endpoint, {
23
- body: JSON.stringify(event),
24
- headers: { "content-type": "application/json", ...options.headers },
25
- method: "POST",
26
- });
27
-
28
- if (!response.ok) {
29
- throw new Error(`"${options.name}" destination responded with ${String(response.status)}`);
30
- }
31
- },
32
- };
33
- }
@@ -1,128 +0,0 @@
1
- import type { z } from "zod";
2
-
3
- import type { Destination } from "#/core/destination";
4
- import type { EventCatalog, EventsOf } from "#/core/event-catalog";
5
- import { generateEventId } from "#/core/event-id";
6
- import type { TrackedEvent } from "#/core/tracked-event";
7
-
8
- /**
9
- * @since 0.5.0-canary.4
10
- */
11
- export interface ServerTrackContext {
12
- anonymousId: string;
13
- userId?: string | undefined;
14
- }
15
-
16
- /**
17
- * @since 0.5.0-canary.4
18
- */
19
- export interface ServerTrackerOptions<Catalog extends EventCatalog> {
20
- catalog: Catalog;
21
- destinations: Array<Destination>;
22
- generateEventId?: () => string;
23
- maxRetries?: number;
24
- onDestinationError?: (error: unknown, destination: Destination, event: TrackedEvent) => void;
25
- retryDelayMs?: number;
26
- }
27
-
28
- /**
29
- * @since 0.5.0-canary.4
30
- */
31
- export interface ServerTracker<Catalog extends EventCatalog> {
32
- /** Explicit anonymous → known-user merge, for when `identify` timing can't do it. */
33
- alias: (previousId: string, userId: string, context: ServerTrackContext) => Promise<void>;
34
- group: (groupId: string, traits: Record<string, unknown> | undefined, context: ServerTrackContext) => Promise<void>;
35
- track: <Name extends keyof EventsOf<Catalog, "server">>(
36
- name: Name,
37
- props: z.infer<EventsOf<Catalog, "server">[Name]["schema"]>,
38
- context: ServerTrackContext,
39
- ) => Promise<void>;
40
- }
41
-
42
- function sleep(ms: number): Promise<void> {
43
- return new Promise((resolve) => {
44
- setTimeout(resolve, ms);
45
- });
46
- }
47
-
48
- async function sendWithRetry(
49
- destination: Destination,
50
- event: TrackedEvent,
51
- maxRetries: number,
52
- retryDelayMs: number,
53
- onError: (error: unknown, destination: Destination, event: TrackedEvent) => void,
54
- ): Promise<void> {
55
- for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
56
- try {
57
- await destination.send(event);
58
-
59
- return;
60
- } catch (error) {
61
- if (attempt === maxRetries) {
62
- onError(error, destination, event);
63
-
64
- return;
65
- }
66
-
67
- await sleep(retryDelayMs * 2 ** attempt);
68
- }
69
- }
70
- }
71
-
72
- /**
73
- * No dead-letter queue yet (self-host storage is Phase 2) — a destination that keeps
74
- * failing after retries is only logged via `onDestinationError`, never re-queued.
75
- *
76
- * @since 0.5.0-canary.4
77
- */
78
- export function createServerTracker<Catalog extends EventCatalog>(
79
- options: ServerTrackerOptions<Catalog>,
80
- ): ServerTracker<Catalog> {
81
- const maxRetries = options.maxRetries ?? 2;
82
- const retryDelayMs = options.retryDelayMs ?? 200;
83
- const createId = options.generateEventId ?? generateEventId;
84
- const onError =
85
- options.onDestinationError ??
86
- ((error: unknown, destination: Destination, event: TrackedEvent): void => {
87
- console.error(`[tracking] destination "${destination.name}" failed for event "${event.name}"`, error);
88
- });
89
-
90
- async function sendEvent(name: string, props: Record<string, unknown>, context: ServerTrackContext): Promise<void> {
91
- const event: TrackedEvent = {
92
- anonymousId: context.anonymousId,
93
- eventId: createId(),
94
- name,
95
- owner: "server",
96
- props,
97
- timestamp: Date.now(),
98
- ...(context.userId === undefined ? {} : { userId: context.userId }),
99
- };
100
-
101
- await Promise.all(
102
- options.destinations.map(async (destination) =>
103
- sendWithRetry(destination, event, maxRetries, retryDelayMs, onError),
104
- ),
105
- );
106
- }
107
-
108
- return {
109
- async alias(previousId, userId, context) {
110
- await sendEvent("$alias", { previousId, userId }, context);
111
- },
112
- async group(groupId, traits, context) {
113
- await sendEvent("$group", { groupId, ...traits }, context);
114
- },
115
- async track(name, props, context) {
116
- // noUncheckedIndexedAccess types this as possibly undefined; the owner check also
117
- // guards callers who bypass the EventsOf filter with an `as` cast.
118
- const definition = options.catalog[name];
119
-
120
- if (!definition || definition.owner !== "server") {
121
- throw new Error(`Unknown server-owned event: ${String(name)}`);
122
- }
123
-
124
- definition.schema.parse(props);
125
- await sendEvent(name as string, props as Record<string, unknown>, context);
126
- },
127
- };
128
- }