@codefast/tracking 1.0.0-canary.6 → 1.0.0-canary.7

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 (267) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +72 -17
  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.mts → browser-cookie.d.ts} +2 -4
  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} +3 -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.mts → gpc.d.ts} +2 -4
  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.mts → consent.d.ts} +49 -51
  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.mts → cookie.d.ts} +3 -5
  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.mts → event-id.d.ts} +2 -4
  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.mts → use-initial-consent.d.ts} +3 -6
  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.mts → region.d.ts} +5 -15
  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 +238 -59
  172. package/src/adapters/tanstack-start.ts +135 -0
  173. package/src/client/ad-framework-consent.ts +86 -0
  174. package/src/client/cookie-anonymous-id.ts +19 -0
  175. package/src/client/create-client-tracker.ts +81 -10
  176. package/src/client/server-persisted-anonymous-id.ts +4 -1
  177. package/src/core/consent-receipt.ts +115 -0
  178. package/src/core/consent.ts +2 -2
  179. package/src/core/destination.ts +7 -0
  180. package/src/core/event-catalog.ts +5 -4
  181. package/src/core/tracked-event.ts +5 -20
  182. package/src/destinations/ad-consent.ts +29 -0
  183. package/src/destinations/meta.ts +96 -0
  184. package/src/destinations/microsoft-uet.ts +86 -0
  185. package/src/destinations/tiktok.ts +85 -0
  186. package/src/index.ts +138 -19
  187. package/src/server/anonymous-id-cookie.ts +49 -22
  188. package/src/server/consent-receipt-store.ts +79 -0
  189. package/src/server/consent-receipt.ts +89 -0
  190. package/src/server/initial-consent.ts +0 -2
  191. package/src/server/measurement-protocol.ts +114 -0
  192. package/src/server/region.ts +0 -10
  193. package/src/server/user-deletion.ts +93 -0
  194. package/src/tooling/import-protection.ts +22 -0
  195. package/dist/client/browser-cookie.mjs +0 -15
  196. package/dist/client/consent-runtime.d.mts +0 -56
  197. package/dist/client/consent-runtime.mjs +0 -35
  198. package/dist/client/consent-storage.mjs +0 -82
  199. package/dist/client/consent-withdrawal.d.mts +0 -21
  200. package/dist/client/consent-withdrawal.mjs +0 -17
  201. package/dist/client/cookie-anonymous-id.d.mts +0 -37
  202. package/dist/client/cookie-anonymous-id.mjs +0 -46
  203. package/dist/client/create-client-tracker.d.mts +0 -32
  204. package/dist/client/create-client-tracker.mjs +0 -40
  205. package/dist/client/gpc.mjs +0 -14
  206. package/dist/client/index.d.mts +0 -10
  207. package/dist/client/index.mjs +0 -10
  208. package/dist/client/initial-consent-store.d.mts +0 -66
  209. package/dist/client/initial-consent-store.mjs +0 -119
  210. package/dist/client/is-analytics-allowed.d.mts +0 -29
  211. package/dist/client/is-analytics-allowed.mjs +0 -23
  212. package/dist/client/server-persisted-anonymous-id.d.mts +0 -33
  213. package/dist/client/server-persisted-anonymous-id.mjs +0 -50
  214. package/dist/core/consent-config.d.mts +0 -27
  215. package/dist/core/consent-config.mjs +0 -11
  216. package/dist/core/consent.mjs +0 -152
  217. package/dist/core/cookie.mjs +0 -23
  218. package/dist/core/destination.d.mts +0 -25
  219. package/dist/core/destination.mjs +0 -1
  220. package/dist/core/event-catalog.d.mts +0 -39
  221. package/dist/core/event-catalog.mjs +0 -30
  222. package/dist/core/event-id.mjs +0 -11
  223. package/dist/core/index.d.mts +0 -8
  224. package/dist/core/index.mjs +0 -6
  225. package/dist/core/tracked-event.d.mts +0 -30
  226. package/dist/core/tracked-event.mjs +0 -1
  227. package/dist/destinations/google-analytics.d.mts +0 -150
  228. package/dist/destinations/google-analytics.mjs +0 -130
  229. package/dist/destinations/google-consent.d.mts +0 -64
  230. package/dist/destinations/google-consent.mjs +0 -102
  231. package/dist/destinations/index.d.mts +0 -2
  232. package/dist/destinations/index.mjs +0 -2
  233. package/dist/destinations/shared.d.mts +0 -20
  234. package/dist/destinations/shared.mjs +0 -13
  235. package/dist/destinations/vercel-analytics.d.mts +0 -28
  236. package/dist/destinations/vercel-analytics.mjs +0 -23
  237. package/dist/import-protection.d.mts +0 -19
  238. package/dist/import-protection.mjs +0 -23
  239. package/dist/index.d.mts +0 -8
  240. package/dist/index.mjs +0 -6
  241. package/dist/react/consent-banner.d.mts +0 -180
  242. package/dist/react/consent-banner.mjs +0 -214
  243. package/dist/react/gtag-consent-bootstrap.d.mts +0 -27
  244. package/dist/react/gtag-consent-bootstrap.mjs +0 -29
  245. package/dist/react/index.d.mts +0 -6
  246. package/dist/react/index.mjs +0 -6
  247. package/dist/react/use-consent.d.mts +0 -45
  248. package/dist/react/use-consent.mjs +0 -71
  249. package/dist/react/use-google-consent-sync.d.mts +0 -23
  250. package/dist/react/use-google-consent-sync.mjs +0 -24
  251. package/dist/react/use-initial-consent.mjs +0 -19
  252. package/dist/server/anonymous-id-cookie.d.mts +0 -46
  253. package/dist/server/anonymous-id-cookie.mjs +0 -51
  254. package/dist/server/index.d.mts +0 -5
  255. package/dist/server/index.mjs +0 -4
  256. package/dist/server/initial-consent.d.mts +0 -29
  257. package/dist/server/initial-consent.mjs +0 -31
  258. package/dist/server/region.mjs +0 -77
  259. package/dist/tanstack-start/index.d.mts +0 -58
  260. package/dist/tanstack-start/index.mjs +0 -45
  261. package/src/client/index.ts +0 -28
  262. package/src/core/index.ts +0 -40
  263. package/src/destinations/index.ts +0 -19
  264. package/src/import-protection.ts +0 -20
  265. package/src/react/index.ts +0 -37
  266. package/src/server/index.ts +0 -16
  267. package/src/tanstack-start/index.ts +0 -83
@@ -0,0 +1,114 @@
1
+ import type { ConsentDecision } from "#/core/consent";
2
+
3
+ /**
4
+ * A GA4 event for the Measurement Protocol. `params` are flat scalars — GA4 rejects nested values and booleans.
5
+ *
6
+ * @since 1.0.0-canary.7
7
+ */
8
+ export interface MeasurementProtocolEvent {
9
+ name: string;
10
+ params?: Record<string, number | string> | undefined;
11
+ }
12
+
13
+ /**
14
+ * The GA4 MP `consent` object — the two ad-consent signals the payload accepts.
15
+ *
16
+ * @since 1.0.0-canary.7
17
+ */
18
+ export interface MeasurementProtocolConsent {
19
+ ad_personalization: "DENIED" | "GRANTED";
20
+ ad_user_data: "DENIED" | "GRANTED";
21
+ }
22
+
23
+ /**
24
+ * Maps the package `ConsentDecision` to GA4 MP consent signals — `ads` drives both ad fields.
25
+ *
26
+ * @since 1.0.0-canary.7
27
+ */
28
+ export function toMeasurementProtocolConsent(decision: ConsentDecision): MeasurementProtocolConsent {
29
+ const state = decision.ads ? "GRANTED" : "DENIED";
30
+
31
+ return { ad_personalization: state, ad_user_data: state };
32
+ }
33
+
34
+ /**
35
+ * Extracts the GA4 `client_id` from a `_ga` cookie value, e.g.
36
+ * `GA1.1.1809596761.1693829043` → `1809596761.1693829043` (everything past the
37
+ * `GA1.<version>.` prefix). The `_ga` layout is community-established, not part of the
38
+ * Measurement Protocol reference, so anything that doesn't parse returns `undefined` rather
39
+ * than sending a malformed id.
40
+ *
41
+ * @since 1.0.0-canary.7
42
+ */
43
+ export function extractGaClientId(gaCookieValue: string | undefined): string | undefined {
44
+ if (!gaCookieValue) {
45
+ return undefined;
46
+ }
47
+
48
+ const segments = gaCookieValue.split(".");
49
+
50
+ if (segments.length < 4 || segments[0] !== "GA1") {
51
+ return undefined;
52
+ }
53
+
54
+ return segments.slice(2).join(".");
55
+ }
56
+
57
+ /**
58
+ * The one network primitive the sender needs — injected so the package ships no HTTP client.
59
+ *
60
+ * @since 1.0.0-canary.7
61
+ */
62
+ export type MeasurementProtocolTransport = (request: { body: string; url: string }) => Promise<void>;
63
+
64
+ /** Default GA4 collection origin; use `https://region1.google-analytics.com` for EU data residency. */
65
+ const DEFAULT_ENDPOINT_ORIGIN = "https://www.google-analytics.com";
66
+
67
+ async function defaultTransport(request: { body: string; url: string }): Promise<void> {
68
+ const response = await fetch(request.url, {
69
+ body: request.body,
70
+ headers: { "content-type": "application/json" },
71
+ method: "POST",
72
+ });
73
+
74
+ // MP returns 2xx with no useful body; a non-2xx is a config error worth surfacing.
75
+ if (!response.ok) {
76
+ throw new Error(`Measurement Protocol responded ${String(response.status)}`);
77
+ }
78
+ }
79
+
80
+ /**
81
+ * @since 1.0.0-canary.7
82
+ */
83
+ export interface SendMeasurementProtocolEventsOptions {
84
+ /** GA4 **API Secret** — read server-side from config, never a client-exposed var. */
85
+ apiSecret: string;
86
+ /** The visitor's GA4 client id (see {@link extractGaClientId}). */
87
+ clientId: string;
88
+ consent?: MeasurementProtocolConsent | undefined;
89
+ endpointOrigin?: string | undefined;
90
+ events: ReadonlyArray<MeasurementProtocolEvent>;
91
+ measurementId: string;
92
+ transport?: MeasurementProtocolTransport | undefined;
93
+ }
94
+
95
+ /**
96
+ * POSTs one or more events to the GA4 Measurement Protocol for a known `client_id` — the
97
+ * server-side counterpart to gtag.js. The caller owns credentials (never bake them) and the
98
+ * consent gate: send only for a server-owned event the visitor's consent permits.
99
+ *
100
+ * @see https://developers.google.com/analytics/devguides/collection/protocol/ga4/sending-events
101
+ *
102
+ * @since 1.0.0-canary.7
103
+ */
104
+ export async function sendMeasurementProtocolEvents(options: SendMeasurementProtocolEventsOptions): Promise<void> {
105
+ const origin = options.endpointOrigin ?? DEFAULT_ENDPOINT_ORIGIN;
106
+ const url = `${origin}/mp/collect?measurement_id=${encodeURIComponent(options.measurementId)}&api_secret=${encodeURIComponent(options.apiSecret)}`;
107
+ const body = JSON.stringify({
108
+ client_id: options.clientId,
109
+ events: options.events,
110
+ ...(options.consent ? { consent: options.consent } : {}),
111
+ });
112
+
113
+ await (options.transport ?? defaultTransport)({ body, url });
114
+ }
@@ -75,13 +75,3 @@ export function resolveRegionFromCountryCode(countryCode: string | undefined): C
75
75
 
76
76
  return "other";
77
77
  }
78
-
79
- /**
80
- * Reads the hosting platform's geo header (e.g. Vercel's `x-vercel-ip-country`) — pass
81
- * the incoming request's `Headers` from server-function/middleware context.
82
- *
83
- * @since 0.5.0-canary.4
84
- */
85
- export function resolveRegion(headers: Headers, headerName = "x-vercel-ip-country"): ConsentRegion {
86
- return resolveRegionFromCountryCode(headers.get(headerName) ?? undefined);
87
- }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * DSR delegation for GA4 (spec-data-subject-rights §3): the platform ships its own
3
+ * per-visitor deletion, so the system **delegates** rather than reimplementing a deletion
4
+ * store. Targets the current **Analytics Admin API** `properties.submitUserDeletion` — the
5
+ * legacy v3 `userDeletionRequests:upsert` was sunset with Universal Analytics, so the spec's
6
+ * DSR-V3 `{ id: { type: "CLIENT_ID", userId } }` shape is stale; the current request keys the
7
+ * subject with a flat `clientId` (a oneof with `userId`/`appInstanceId`/`userProvidedData`).
8
+ *
9
+ * @see https://developers.google.com/analytics/devguides/config/userdeletion/migration
10
+ */
11
+
12
+ const ADMIN_API_ORIGIN = "https://analyticsadmin.googleapis.com";
13
+
14
+ /**
15
+ * @since 1.0.0-canary.7
16
+ */
17
+ export interface Ga4UserDeletionRequest {
18
+ body: { clientId: string };
19
+ url: string;
20
+ }
21
+
22
+ /**
23
+ * Builds the Admin API `submitUserDeletion` request that erases one GA4 subject by
24
+ * `clientId` (the `_ga`-cookie id — see `extractGaClientId`). Pure and network-free so the
25
+ * request shape can be snapshotted/verified; pair it with {@link submitGa4UserDeletion} or
26
+ * any authenticated transport.
27
+ *
28
+ * @param options - `propertyId` is the numeric GA4 property (no `properties/` prefix).
29
+ *
30
+ * @since 1.0.0-canary.7
31
+ */
32
+ export function buildGa4UserDeletionRequest(options: { clientId: string; propertyId: string }): Ga4UserDeletionRequest {
33
+ return {
34
+ body: { clientId: options.clientId },
35
+ url: `${ADMIN_API_ORIGIN}/v1alpha/properties/${options.propertyId}:submitUserDeletion`,
36
+ };
37
+ }
38
+
39
+ /**
40
+ * The one network primitive the sender needs — injected so the package ships no HTTP client.
41
+ *
42
+ * @since 1.0.0-canary.7
43
+ */
44
+ export type Ga4UserDeletionTransport = (request: {
45
+ body: string;
46
+ headers: Record<string, string>;
47
+ url: string;
48
+ }) => Promise<void>;
49
+
50
+ async function defaultTransport(request: {
51
+ body: string;
52
+ headers: Record<string, string>;
53
+ url: string;
54
+ }): Promise<void> {
55
+ const response = await fetch(request.url, { body: request.body, headers: request.headers, method: "POST" });
56
+
57
+ if (!response.ok) {
58
+ throw new Error(`GA4 user deletion responded ${String(response.status)}`);
59
+ }
60
+ }
61
+
62
+ /**
63
+ * @since 1.0.0-canary.7
64
+ */
65
+ export interface SubmitGa4UserDeletionOptions {
66
+ /** A bearer token for the `https://www.googleapis.com/auth/analytics.edit` scope — the caller owns OAuth. */
67
+ accessToken: string;
68
+ clientId: string;
69
+ propertyId: string;
70
+ transport?: Ga4UserDeletionTransport | undefined;
71
+ }
72
+
73
+ /**
74
+ * Submits a GA4 user-deletion request for one `clientId`. Authorization is the caller's:
75
+ * pass a bearer token minted from a service account (never baked into the package). The
76
+ * deletion removes the subject from the Individual User report within ~72h and purges at the
77
+ * next run; it does **not** reach previously-aggregated reports or BigQuery exports
78
+ * (spec-data-subject-rights §3).
79
+ *
80
+ * @since 1.0.0-canary.7
81
+ */
82
+ export async function submitGa4UserDeletion(options: SubmitGa4UserDeletionOptions): Promise<void> {
83
+ const request = buildGa4UserDeletionRequest({ clientId: options.clientId, propertyId: options.propertyId });
84
+
85
+ await (options.transport ?? defaultTransport)({
86
+ body: JSON.stringify(request.body),
87
+ headers: {
88
+ authorization: `Bearer ${options.accessToken}`,
89
+ "content-type": "application/json",
90
+ },
91
+ url: request.url,
92
+ });
93
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The `@codefast/tracking` subpaths every client bundle must deny (picomatch patterns) —
3
+ * framework-neutral data each build tool maps to its own guard: TanStack Start's
4
+ * `importProtection.client.specifiers`, Next's `server-only`, Remix's `.server` convention.
5
+ * Ships and versions with the package instead of going stale in each consumer's config.
6
+ * Nothing in this package imports it — its consumers are app build configs (see apps/ui
7
+ * vite.config.ts).
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * tanstackStart({
12
+ * importProtection: { client: { specifiers: [...SERVER_ONLY_SUBPATHS] } },
13
+ * });
14
+ * ```
15
+ *
16
+ * @since 1.0.0-canary.6
17
+ */
18
+ export const SERVER_ONLY_SUBPATHS: ReadonlyArray<string> = [
19
+ "@codefast/tracking/server",
20
+ "@codefast/tracking/server/**",
21
+ "@codefast/tracking/adapters/**",
22
+ ];
@@ -1,15 +0,0 @@
1
- //#region src/client/browser-cookie.ts
2
- /**
3
- * Shared `document.cookie` writer for the client-side cookie lanes (anonymous id, consent
4
- * mirror): Secure on HTTPS so values never ride plain HTTP, SameSite=Lax, never HttpOnly —
5
- * the client must read its own cookies back. A no-op without a `document` (SSR).
6
- *
7
- * @since 1.0.0-canary.6
8
- */
9
- function writeBrowserCookie(cookieName, value, maxAgeSeconds) {
10
- if (typeof document === "undefined") return;
11
- const secure = globalThis.location.protocol === "https:" ? "; secure" : "";
12
- document.cookie = `${cookieName}=${value}; path=/; max-age=${String(maxAgeSeconds)}; samesite=lax${secure}`;
13
- }
14
- //#endregion
15
- export { writeBrowserCookie };
@@ -1,56 +0,0 @@
1
- import { ConsentStorage, InitialConsent } from "../core/consent.mjs";
2
- import { InitialConsentStore } from "./initial-consent-store.mjs";
3
- import { ConsentConfig } from "../core/consent-config.mjs";
4
-
5
- //#region src/client/consent-runtime.d.ts
6
- /**
7
- * @since 1.0.0-canary.6
8
- */
9
- interface ConsentRuntimeOptions {
10
- config: ConsentConfig;
11
- /** Re-read per event so a GPC change applies without recreating the runtime. Defaults to the real navigator signal. */
12
- hasGlobalPrivacyControlSignal?: (() => boolean) | undefined;
13
- /**
14
- * `sessionStorage` key caching the resolved region default, so only the first page
15
- * load of a session pays the round trip — omit to resolve once per page load instead.
16
- */
17
- initialConsentSessionStorageKey?: string | undefined;
18
- /**
19
- * The per-visitor server lane — typically a server function wrapping
20
- * `resolveInitialConsentFromRequest`. Shared/CDN-cached HTML can carry nothing
21
- * region-specific, so this is the only place the region-correct default may come from.
22
- */
23
- resolveInitialConsent: () => Promise<InitialConsent>;
24
- }
25
- /**
26
- * The live client-side consent instances, all derived from one `ConsentConfig` — create
27
- * it once at module scope and every surface (banner hook, tracker gate, privacy page)
28
- * shares the same storage and region resolution by construction.
29
- *
30
- * @since 1.0.0-canary.6
31
- */
32
- interface ConsentRuntime {
33
- config: ConsentConfig;
34
- /**
35
- * Kicks off region resolution — single-flight and idempotent. Call it early (e.g. at
36
- * router creation, window-guarded) so the round trip overlaps hydration instead of
37
- * waiting for the first mount effect.
38
- */
39
- ensureInitialConsentResolved: () => void;
40
- /** Feed to `useInitialConsent` for the reactive region default. */
41
- initialConsentStore: InitialConsentStore;
42
- /** Non-React gate for `createClientTracker` — the same rule `useConsent` applies. */
43
- isAnalyticsAllowed: () => boolean;
44
- /** The one `ConsentStorage` instance every surface must share. */
45
- storage: ConsentStorage;
46
- }
47
- /**
48
- * Composes the client half of the consent lane from a single `ConsentConfig`:
49
- * `localStorage`-backed decision storage, the initial-consent store over the app's
50
- * server lane, and the non-React analytics gate wired to that store's resolved mode.
51
- *
52
- * @since 1.0.0-canary.6
53
- */
54
- declare function createConsentRuntime(options: ConsentRuntimeOptions): ConsentRuntime;
55
- //#endregion
56
- export { ConsentRuntime, ConsentRuntimeOptions, createConsentRuntime };
@@ -1,35 +0,0 @@
1
- import { createLocalStorageConsentStorage } from "./consent-storage.mjs";
2
- import { hasGlobalPrivacyControlSignal } from "./gpc.mjs";
3
- import { createInitialConsentStore } from "./initial-consent-store.mjs";
4
- import { createIsAnalyticsAllowed } from "./is-analytics-allowed.mjs";
5
- //#region src/client/consent-runtime.ts
6
- /**
7
- * Composes the client half of the consent lane from a single `ConsentConfig`:
8
- * `localStorage`-backed decision storage, the initial-consent store over the app's
9
- * server lane, and the non-React analytics gate wired to that store's resolved mode.
10
- *
11
- * @since 1.0.0-canary.6
12
- */
13
- function createConsentRuntime(options) {
14
- const { config } = options;
15
- const storage = createLocalStorageConsentStorage(config.storageKey);
16
- const initialConsentStore = createInitialConsentStore({
17
- resolve: options.resolveInitialConsent,
18
- sessionStorageKey: options.initialConsentSessionStorageKey
19
- });
20
- const isAnalyticsAllowed = createIsAnalyticsAllowed({
21
- config,
22
- getMode: () => initialConsentStore.getSnapshot().initialConsent.mode,
23
- hasGlobalPrivacyControlSignal: options.hasGlobalPrivacyControlSignal ?? hasGlobalPrivacyControlSignal,
24
- storage
25
- });
26
- return {
27
- config,
28
- ensureInitialConsentResolved: initialConsentStore.ensureResolved,
29
- initialConsentStore,
30
- isAnalyticsAllowed,
31
- storage
32
- };
33
- }
34
- //#endregion
35
- export { createConsentRuntime };
@@ -1,82 +0,0 @@
1
- import { isConsentRecord } from "../core/consent.mjs";
2
- //#region src/client/consent-storage.ts
3
- /**
4
- * `localStorage`-backed consent storage. Corrupt state, a private-mode/quota error, or no
5
- * `window` (SSR) degrades to an in-memory record — the visitor's decision still applies
6
- * for the session instead of re-prompting in a loop. `subscribe` fires for same-tab
7
- * writes and, via the `storage` event, for decisions made in other tabs.
8
- *
9
- * `load()` parses and validates at most once per change: the result is cached and
10
- * invalidated by `save`/`clear` and by cross-tab `storage` events, so per-event consent
11
- * gates and per-render `useSyncExternalStore` snapshots cost a memory read, not a
12
- * `JSON.parse`.
13
- *
14
- * @remarks
15
- * The record persists as plain `JSON.stringify(ConsentRecord)` — a stable contract, so
16
- * pre-hydration inline scripts (e.g. a Consent Mode default bootstrap) can read the
17
- * decision synchronously before any tag fires.
18
- *
19
- * @since 0.5.0-canary.4
20
- */
21
- function createLocalStorageConsentStorage(storageKey) {
22
- const listeners = /* @__PURE__ */ new Set();
23
- let memoryRecord;
24
- let cache;
25
- function notify() {
26
- for (const listener of listeners) listener();
27
- }
28
- return {
29
- clear() {
30
- if (typeof globalThis.window === "undefined") return;
31
- memoryRecord = void 0;
32
- cache = void 0;
33
- try {
34
- globalThis.window.localStorage.removeItem(storageKey);
35
- } catch {}
36
- notify();
37
- },
38
- load() {
39
- if (typeof globalThis.window === "undefined") return;
40
- try {
41
- const raw = globalThis.window.localStorage.getItem(storageKey);
42
- if (cache && raw === cache.raw) return cache.record;
43
- let record;
44
- if (raw) {
45
- const parsed = JSON.parse(raw);
46
- record = isConsentRecord(parsed) ? parsed : memoryRecord;
47
- } else record = memoryRecord;
48
- cache = {
49
- raw,
50
- record
51
- };
52
- return record;
53
- } catch {
54
- return memoryRecord;
55
- }
56
- },
57
- save(record) {
58
- if (typeof globalThis.window === "undefined") return;
59
- cache = void 0;
60
- try {
61
- globalThis.window.localStorage.setItem(storageKey, JSON.stringify(record));
62
- memoryRecord = void 0;
63
- } catch {
64
- memoryRecord = record;
65
- }
66
- notify();
67
- },
68
- subscribe(listener) {
69
- listeners.add(listener);
70
- function handleStorageEvent(event) {
71
- if (event.key === null || event.key === storageKey) listener();
72
- }
73
- if (typeof globalThis.window !== "undefined") globalThis.window.addEventListener("storage", handleStorageEvent);
74
- return () => {
75
- listeners.delete(listener);
76
- if (typeof globalThis.window !== "undefined") globalThis.window.removeEventListener("storage", handleStorageEvent);
77
- };
78
- }
79
- };
80
- }
81
- //#endregion
82
- export { createLocalStorageConsentStorage };
@@ -1,21 +0,0 @@
1
- import { ConsentDecision } from "../core/consent.mjs";
2
-
3
- //#region src/client/consent-withdrawal.d.ts
4
- /**
5
- * @since 1.0.0-canary.6
6
- */
7
- interface ConsentWithdrawalHandlerOptions {
8
- /** Forget the cookie-backed visitor id when analytics is denied. */
9
- clearAnonymousId?: (() => void) | undefined;
10
- /** Expire Google's `_ga` / `_ga_*` cookies when analytics is denied. */
11
- clearGoogleAnalyticsCookies?: (() => void) | undefined;
12
- }
13
- /**
14
- * `useConsent({ onDecision })` handler that clears first-party tracking state when the
15
- * visitor denies (or withdraws) analytics. Grant paths are a no-op.
16
- *
17
- * @since 1.0.0-canary.6
18
- */
19
- declare function createConsentWithdrawalHandler(options: ConsentWithdrawalHandlerOptions): (decision: ConsentDecision) => void;
20
- //#endregion
21
- export { ConsentWithdrawalHandlerOptions, createConsentWithdrawalHandler };
@@ -1,17 +0,0 @@
1
- //#region src/client/consent-withdrawal.ts
2
- /**
3
- * `useConsent({ onDecision })` handler that clears first-party tracking state when the
4
- * visitor denies (or withdraws) analytics. Grant paths are a no-op.
5
- *
6
- * @since 1.0.0-canary.6
7
- */
8
- function createConsentWithdrawalHandler(options) {
9
- const { clearAnonymousId, clearGoogleAnalyticsCookies } = options;
10
- return (decision) => {
11
- if (decision.analytics) return;
12
- clearAnonymousId?.();
13
- clearGoogleAnalyticsCookies?.();
14
- };
15
- }
16
- //#endregion
17
- export { createConsentWithdrawalHandler };
@@ -1,37 +0,0 @@
1
- //#region src/client/cookie-anonymous-id.d.ts
2
- /**
3
- * @since 1.0.0-canary.6
4
- */
5
- interface CookieAnonymousIdOptions {
6
- /** Cookie name — must not collide with another cookie on the domain. */
7
- cookieName: string;
8
- /** How long the id survives a return visit. Defaults to one year. */
9
- maxAgeSeconds?: number | undefined;
10
- }
11
- /**
12
- * @since 1.0.0-canary.6
13
- */
14
- interface CookieAnonymousId {
15
- /** Expires the cookie — call when the visitor withdraws tracking consent. */
16
- clear: () => void;
17
- /** The existing id, or a freshly minted and persisted one. */
18
- getOrCreate: () => string;
19
- /**
20
- * Rolls an *existing* id's expiry forward without ever minting one — safe to call on
21
- * page load for returning consented visitors (the ITP-refresh path), a no-op for
22
- * visitors who never got an id.
23
- */
24
- refresh: () => void;
25
- }
26
- /**
27
- * A `document.cookie`-backed anonymous id — not `localStorage`-only, so a server-owned
28
- * event can read the same id from the request and correlate to this visitor. Pass
29
- * `getOrCreate` (not the result of calling it) as `ClientTrackerOptions.anonymousId`:
30
- * it's invoked lazily, so the cookie is minted only once an event is actually allowed to
31
- * send, never as an import-time side effect.
32
- *
33
- * @since 1.0.0-canary.6
34
- */
35
- declare function createCookieAnonymousId(options: CookieAnonymousIdOptions): CookieAnonymousId;
36
- //#endregion
37
- export { CookieAnonymousId, CookieAnonymousIdOptions, createCookieAnonymousId };
@@ -1,46 +0,0 @@
1
- import { ONE_YEAR_IN_SECONDS, readCookieValue } from "../core/cookie.mjs";
2
- import { writeBrowserCookie } from "./browser-cookie.mjs";
3
- //#region src/client/cookie-anonymous-id.ts
4
- /**
5
- * A `document.cookie`-backed anonymous id — not `localStorage`-only, so a server-owned
6
- * event can read the same id from the request and correlate to this visitor. Pass
7
- * `getOrCreate` (not the result of calling it) as `ClientTrackerOptions.anonymousId`:
8
- * it's invoked lazily, so the cookie is minted only once an event is actually allowed to
9
- * send, never as an import-time side effect.
10
- *
11
- * @since 1.0.0-canary.6
12
- */
13
- function createCookieAnonymousId(options) {
14
- const { cookieName, maxAgeSeconds = ONE_YEAR_IN_SECONDS } = options;
15
- let cachedId;
16
- return {
17
- clear() {
18
- cachedId = void 0;
19
- if (typeof document === "undefined") return;
20
- writeBrowserCookie(cookieName, "", 0);
21
- },
22
- getOrCreate() {
23
- if (typeof document === "undefined") return cachedId ?? crypto.randomUUID();
24
- const existing = readCookieValue(document.cookie, cookieName);
25
- if (existing) {
26
- cachedId = existing;
27
- return existing;
28
- }
29
- cachedId = void 0;
30
- const id = crypto.randomUUID();
31
- writeBrowserCookie(cookieName, id, maxAgeSeconds);
32
- cachedId = id;
33
- return id;
34
- },
35
- refresh() {
36
- if (typeof document === "undefined") return;
37
- const existing = readCookieValue(document.cookie, cookieName);
38
- if (existing) {
39
- cachedId = existing;
40
- writeBrowserCookie(cookieName, existing, maxAgeSeconds);
41
- }
42
- }
43
- };
44
- }
45
- //#endregion
46
- export { createCookieAnonymousId };
@@ -1,32 +0,0 @@
1
- import { Destination } from "../core/destination.mjs";
2
- import { EventCatalog } from "../core/event-catalog.mjs";
3
- import { StandardSchemaV1 } from "@standard-schema/spec";
4
-
5
- //#region src/client/create-client-tracker.d.ts
6
- /**
7
- * @since 0.5.0-canary.4
8
- */
9
- interface ClientTrackerOptions<Catalog extends EventCatalog> {
10
- /** Invoked per allowed event — defer creating the id (e.g. minting a cookie) until an event is actually allowed to send, never as an import-time side effect. */
11
- anonymousId: () => string;
12
- catalog: Catalog;
13
- destinations: Array<Destination>;
14
- /**
15
- * Consulted before every event — while it returns `false`, only
16
- * `consentRequirement: "exempt"` destinations still receive events, stripped of
17
- * identifiers. Omit to always track.
18
- */
19
- isAnalyticsAllowed?: (() => boolean) | undefined;
20
- }
21
- /**
22
- * @since 0.5.0-canary.4
23
- */
24
- interface ClientTracker<Catalog extends EventCatalog> {
25
- track: <Name extends keyof Catalog & string>(name: Name, properties: StandardSchemaV1.InferOutput<Catalog[Name]["schema"]>) => void;
26
- }
27
- /**
28
- * @since 0.5.0-canary.4
29
- */
30
- declare function createClientTracker<Catalog extends EventCatalog>(options: ClientTrackerOptions<Catalog>): ClientTracker<Catalog>;
31
- //#endregion
32
- export { ClientTracker, ClientTrackerOptions, createClientTracker };
@@ -1,40 +0,0 @@
1
- import { assertValidEventProperties } from "../core/event-catalog.mjs";
2
- import { generateEventId } from "../core/event-id.mjs";
3
- //#region src/client/create-client-tracker.ts
4
- /**
5
- * `Destination.send` is typed to always return a `Promise`, but that's unenforceable at
6
- * runtime for a third-party/plain-JS destination — one that ignores the contract and
7
- * throws synchronously (or returns a non-`Promise`) must still never break the tracked
8
- * interaction. `Promise.resolve(...)` normalizes a non-`Promise` return; the outer
9
- * try/catch is the only thing that can catch a throw that happens before `send` ever
10
- * gets to return anything.
11
- */
12
- function sendToDestination(destination, event) {
13
- try {
14
- Promise.resolve(destination.send(event)).catch(() => {});
15
- } catch {}
16
- }
17
- /**
18
- * @since 0.5.0-canary.4
19
- */
20
- function createClientTracker(options) {
21
- const exemptDestinations = options.destinations.filter((destination) => destination.consentRequirement === "exempt");
22
- return { track(name, properties) {
23
- const definition = options.catalog[name];
24
- if (!definition) throw new Error(`Unknown event: ${String(name)}`);
25
- assertValidEventProperties(definition.schema, name, properties);
26
- const isAllowed = options.isAnalyticsAllowed?.() !== false;
27
- if (!isAllowed && exemptDestinations.length === 0) return;
28
- const event = {
29
- anonymousId: isAllowed ? options.anonymousId() : "",
30
- eventId: generateEventId(),
31
- name,
32
- properties,
33
- timestamp: Date.now(),
34
- type: "track"
35
- };
36
- for (const destination of isAllowed ? options.destinations : exemptDestinations) sendToDestination(destination, event);
37
- } };
38
- }
39
- //#endregion
40
- export { createClientTracker };
@@ -1,14 +0,0 @@
1
- //#region src/client/gpc.ts
2
- /**
3
- * Global Privacy Control isn't in lib.dom yet, hence the local interface extension.
4
- * CCPA/CPRA requires honoring this as an opt-out signal even under the opt-out default.
5
- * Guarded so SSR renders (where the module is reachable) read `false`, not a crash on
6
- * runtimes without a global `navigator`.
7
- *
8
- * @since 0.5.0-canary.4
9
- */
10
- function hasGlobalPrivacyControlSignal() {
11
- return typeof navigator !== "undefined" && navigator.globalPrivacyControl === true;
12
- }
13
- //#endregion
14
- export { hasGlobalPrivacyControlSignal };
@@ -1,10 +0,0 @@
1
- import { InitialConsentSnapshot, InitialConsentStore, InitialConsentStoreOptions, createInitialConsentStore } from "./initial-consent-store.mjs";
2
- import { ConsentRuntime, ConsentRuntimeOptions, createConsentRuntime } from "./consent-runtime.mjs";
3
- import { createLocalStorageConsentStorage } from "./consent-storage.mjs";
4
- import { ConsentWithdrawalHandlerOptions, createConsentWithdrawalHandler } from "./consent-withdrawal.mjs";
5
- import { CookieAnonymousId, CookieAnonymousIdOptions, createCookieAnonymousId } from "./cookie-anonymous-id.mjs";
6
- import { ClientTracker, ClientTrackerOptions, createClientTracker } from "./create-client-tracker.mjs";
7
- import { hasGlobalPrivacyControlSignal } from "./gpc.mjs";
8
- import { IsAnalyticsAllowedOptions, createIsAnalyticsAllowed } from "./is-analytics-allowed.mjs";
9
- import { ServerPersistedAnonymousIdOptions, createServerPersistedAnonymousId } from "./server-persisted-anonymous-id.mjs";
10
- export { type ClientTracker, type ClientTrackerOptions, type ConsentRuntime, type ConsentRuntimeOptions, type ConsentWithdrawalHandlerOptions, type CookieAnonymousId, type CookieAnonymousIdOptions, type InitialConsentSnapshot, type InitialConsentStore, type InitialConsentStoreOptions, type IsAnalyticsAllowedOptions, type ServerPersistedAnonymousIdOptions, createClientTracker, createConsentRuntime, createConsentWithdrawalHandler, createCookieAnonymousId, createInitialConsentStore, createIsAnalyticsAllowed, createLocalStorageConsentStorage, createServerPersistedAnonymousId, hasGlobalPrivacyControlSignal };