@codefast/tracking 0.0.0 → 0.5.0-canary.4

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 (71) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +46 -8
  3. package/dist/client/consent-storage.d.mts +11 -3
  4. package/dist/client/consent-storage.mjs +45 -9
  5. package/dist/client/create-client-tracker.d.mts +10 -0
  6. package/dist/client/create-client-tracker.mjs +14 -1
  7. package/dist/client/gpc.d.mts +2 -0
  8. package/dist/client/gpc.mjs +2 -0
  9. package/dist/client/lifecycle.d.mts +5 -0
  10. package/dist/client/lifecycle.mjs +2 -0
  11. package/dist/client/local-storage.d.mts +5 -2
  12. package/dist/client/local-storage.mjs +12 -5
  13. package/dist/client/queue.d.mts +7 -0
  14. package/dist/client/queue.mjs +2 -0
  15. package/dist/client/router.d.mts +4 -0
  16. package/dist/client/router.mjs +2 -0
  17. package/dist/core/consent.d.mts +61 -9
  18. package/dist/core/consent.mjs +39 -7
  19. package/dist/core/destination.d.mts +10 -0
  20. package/dist/core/event-catalog.d.mts +8 -0
  21. package/dist/core/event-catalog.mjs +2 -0
  22. package/dist/core/event-id.d.mts +2 -0
  23. package/dist/core/event-id.mjs +2 -0
  24. package/dist/core/index.d.mts +2 -2
  25. package/dist/core/index.mjs +2 -2
  26. package/dist/core/tracked-event.d.mts +2 -0
  27. package/dist/destinations/ga4-measurement-protocol.d.mts +54 -0
  28. package/dist/destinations/ga4-measurement-protocol.mjs +89 -0
  29. package/dist/destinations/google-analytics.d.mts +98 -0
  30. package/dist/destinations/google-analytics.mjs +126 -0
  31. package/dist/destinations/http-destination.d.mts +5 -0
  32. package/dist/destinations/http-destination.mjs +2 -0
  33. package/dist/destinations/index.d.mts +3 -1
  34. package/dist/destinations/index.mjs +3 -1
  35. package/dist/destinations/vercel-analytics.d.mts +4 -2
  36. package/dist/destinations/vercel-analytics.mjs +5 -2
  37. package/dist/index.d.mts +2 -2
  38. package/dist/index.mjs +2 -2
  39. package/dist/react/consent-banner.d.mts +48 -14
  40. package/dist/react/consent-banner.mjs +94 -22
  41. package/dist/react/index.d.mts +2 -2
  42. package/dist/react/use-consent.d.mts +30 -5
  43. package/dist/react/use-consent.mjs +38 -15
  44. package/dist/server/create-server-tracker.d.mts +14 -0
  45. package/dist/server/create-server-tracker.mjs +24 -5
  46. package/dist/server/region.d.mts +4 -0
  47. package/dist/server/region.mjs +4 -0
  48. package/package.json +12 -2
  49. package/src/client/consent-storage.ts +75 -10
  50. package/src/client/create-client-tracker.ts +30 -1
  51. package/src/client/gpc.ts +2 -0
  52. package/src/client/lifecycle.ts +5 -0
  53. package/src/client/local-storage.ts +21 -6
  54. package/src/client/queue.ts +7 -0
  55. package/src/client/router.ts +4 -0
  56. package/src/core/consent.ts +85 -11
  57. package/src/core/destination.ts +10 -0
  58. package/src/core/event-catalog.ts +8 -0
  59. package/src/core/event-id.ts +2 -0
  60. package/src/core/index.ts +15 -2
  61. package/src/core/tracked-event.ts +2 -0
  62. package/src/destinations/ga4-measurement-protocol.ts +166 -0
  63. package/src/destinations/google-analytics.ts +233 -0
  64. package/src/destinations/http-destination.ts +5 -0
  65. package/src/destinations/index.ts +16 -0
  66. package/src/destinations/vercel-analytics.ts +5 -2
  67. package/src/react/consent-banner.tsx +121 -22
  68. package/src/react/index.ts +1 -1
  69. package/src/react/use-consent.ts +81 -23
  70. package/src/server/create-server-tracker.ts +39 -16
  71. package/src/server/region.ts +4 -0
@@ -3,6 +3,8 @@ import { z } from "zod";
3
3
  //#region src/core/event-catalog.d.ts
4
4
  /**
5
5
  * One event's Zod schema plus which side of the app is allowed to fire it.
6
+ *
7
+ * @since 0.5.0-canary.4
6
8
  */
7
9
  interface EventDefinition<Schema extends z.ZodType = z.ZodType> {
8
10
  owner: "client" | "server";
@@ -11,17 +13,23 @@ interface EventDefinition<Schema extends z.ZodType = z.ZodType> {
11
13
  /**
12
14
  * An app-defined map of event name to its definition. `@codefast/tracking` ships no
13
15
  * events of its own — every consuming app builds and passes in its own catalog.
16
+ *
17
+ * @since 0.5.0-canary.4
14
18
  */
15
19
  type EventCatalog = Record<string, EventDefinition>;
16
20
  /**
17
21
  * Filters a catalog down to the events a given owner may fire. Client and server
18
22
  * trackers are built from this, so calling a server-owned event from client code
19
23
  * (or vice versa) is a compile-time error, not a runtime surprise.
24
+ *
25
+ * @since 0.5.0-canary.4
20
26
  */
21
27
  type EventsOf<Catalog extends EventCatalog, Owner extends "client" | "server"> = { [Key in keyof Catalog as Catalog[Key]["owner"] extends Owner ? Key : never]: Catalog[Key] };
22
28
  /**
23
29
  * Identity helper for declaring a catalog with inference — nicer call-site than
24
30
  * `satisfies EventCatalog` when the catalog is assembled across multiple files.
31
+ *
32
+ * @since 0.5.0-canary.4
25
33
  */
26
34
  declare function defineEventCatalog<Catalog extends EventCatalog>(catalog: Catalog): Catalog;
27
35
  //#endregion
@@ -2,6 +2,8 @@
2
2
  /**
3
3
  * Identity helper for declaring a catalog with inference — nicer call-site than
4
4
  * `satisfies EventCatalog` when the catalog is assembled across multiple files.
5
+ *
6
+ * @since 0.5.0-canary.4
5
7
  */
6
8
  function defineEventCatalog(catalog) {
7
9
  return catalog;
@@ -2,6 +2,8 @@
2
2
  /**
3
3
  * Client-owned events use this at enqueue time; server-owned events derive an ID
4
4
  * from the request instead so retries of the same request don't double-count.
5
+ *
6
+ * @since 0.5.0-canary.4
5
7
  */
6
8
  declare function generateEventId(): string;
7
9
  //#endregion
@@ -2,6 +2,8 @@
2
2
  /**
3
3
  * Client-owned events use this at enqueue time; server-owned events derive an ID
4
4
  * from the request instead so retries of the same request don't double-count.
5
+ *
6
+ * @since 0.5.0-canary.4
5
7
  */
6
8
  function generateEventId() {
7
9
  return crypto.randomUUID();
@@ -1,6 +1,6 @@
1
- import { ConsentDecision, ConsentMode, ConsentRecord, ConsentRegion, ConsentStorage, resolveConsentMode, shouldTrackByDefault } from "./consent.mjs";
1
+ import { CONSENT_CATEGORIES, ConsentCategory, ConsentDecision, ConsentMode, ConsentRecord, ConsentRegion, ConsentStorage, createConsentDecision, isConsentDecision, resolveConsentMode, resolveDefaultConsent } from "./consent.mjs";
2
2
  import { TrackedEvent } from "./tracked-event.mjs";
3
3
  import { Destination } from "./destination.mjs";
4
4
  import { EventCatalog, EventDefinition, EventsOf, defineEventCatalog } from "./event-catalog.mjs";
5
5
  import { generateEventId } from "./event-id.mjs";
6
- export { type ConsentDecision, type ConsentMode, type ConsentRecord, type ConsentRegion, type ConsentStorage, type Destination, type EventCatalog, type EventDefinition, type EventsOf, type TrackedEvent, defineEventCatalog, generateEventId, resolveConsentMode, shouldTrackByDefault };
6
+ export { CONSENT_CATEGORIES, type ConsentCategory, type ConsentDecision, type ConsentMode, type ConsentRecord, type ConsentRegion, type ConsentStorage, type Destination, type EventCatalog, type EventDefinition, type EventsOf, type TrackedEvent, createConsentDecision, defineEventCatalog, generateEventId, isConsentDecision, resolveConsentMode, resolveDefaultConsent };
@@ -1,4 +1,4 @@
1
- import { resolveConsentMode, shouldTrackByDefault } from "./consent.mjs";
1
+ import { CONSENT_CATEGORIES, createConsentDecision, isConsentDecision, resolveConsentMode, resolveDefaultConsent } from "./consent.mjs";
2
2
  import { defineEventCatalog } from "./event-catalog.mjs";
3
3
  import { generateEventId } from "./event-id.mjs";
4
- export { defineEventCatalog, generateEventId, resolveConsentMode, shouldTrackByDefault };
4
+ export { CONSENT_CATEGORIES, createConsentDecision, defineEventCatalog, generateEventId, isConsentDecision, resolveConsentMode, resolveDefaultConsent };
@@ -1,6 +1,8 @@
1
1
  //#region src/core/tracked-event.d.ts
2
2
  /**
3
3
  * Envelope every tracker (client/server) builds before handing an event to a destination.
4
+ *
5
+ * @since 0.5.0-canary.4
4
6
  */
5
7
  interface TrackedEvent {
6
8
  anonymousId: string;
@@ -0,0 +1,54 @@
1
+ import { Destination } from "../core/destination.mjs";
2
+
3
+ //#region src/destinations/ga4-measurement-protocol.d.ts
4
+ /**
5
+ * Reads gtag.js's own client ID from a request Cookie header — `_ga=GA1.1.123.456` →
6
+ * `123.456`. This (not an app-generated anonymous ID) is the value GA4 joins hits on, so
7
+ * pass it as `clientId` to make server events land on the same user as the visitor's
8
+ * client-side hits.
9
+ *
10
+ * @since 0.5.0-canary.4
11
+ */
12
+ declare function extractGa4ClientId(cookieHeader: string | undefined): string | undefined;
13
+ /**
14
+ * Reads the current GA4 session ID from the per-stream `_ga_<suffix>` cookie
15
+ * (`G-ABC123` → `_ga_ABC123`) — handles both the dot-delimited `GS1` and the
16
+ * `$`-delimited `GS2` value formats.
17
+ *
18
+ * @since 0.5.0-canary.4
19
+ */
20
+ declare function extractGa4SessionId(cookieHeader: string | undefined, measurementId: string): string | undefined;
21
+ /**
22
+ * @since 0.5.0-canary.4
23
+ */
24
+ interface Ga4MeasurementProtocolDestinationOptions {
25
+ apiSecret: string;
26
+ /**
27
+ * gtag.js's client ID for this visitor (see `extractGa4ClientId`). Without it the
28
+ * event falls back to the tracker's anonymous ID, which GA4 treats as a *different
29
+ * user* than the visitor's client-side hits — pass it whenever the request carries a
30
+ * `_ga` cookie.
31
+ */
32
+ clientId?: string | undefined;
33
+ /** Routes to GA4's `/debug/mp/collect` validation endpoint — hits are validated but never recorded. */
34
+ debug?: boolean;
35
+ measurementId: string;
36
+ name?: string;
37
+ /**
38
+ * Current GA4 session for this visitor (see `extractGa4SessionId`). Without a
39
+ * `session_id`, GA4 accepts the event but leaves it out of session-scoped and realtime
40
+ * reporting.
41
+ */
42
+ sessionId?: string | undefined;
43
+ }
44
+ /**
45
+ * Server-side GA4 via the Measurement Protocol — for server-owned events (checkout,
46
+ * signup) that must land in GA4 without depending on client-side gtag.js. MP is designed
47
+ * to *augment* gtag.js data, so correlation hinges on echoing gtag's own identifiers:
48
+ * `clientId` from the `_ga` cookie and `sessionId` from the `_ga_<stream>` cookie.
49
+ *
50
+ * @since 0.5.0-canary.4
51
+ */
52
+ declare function createGa4MeasurementProtocolDestination(options: Ga4MeasurementProtocolDestinationOptions): Destination;
53
+ //#endregion
54
+ export { Ga4MeasurementProtocolDestinationOptions, createGa4MeasurementProtocolDestination, extractGa4ClientId, extractGa4SessionId };
@@ -0,0 +1,89 @@
1
+ //#region src/destinations/ga4-measurement-protocol.ts
2
+ /**
3
+ * Measurement Protocol event params must be flat string/number/boolean — stringify
4
+ * anything else instead of letting GA4 silently drop it.
5
+ */
6
+ function toMeasurementProtocolParams(props) {
7
+ const result = {};
8
+ for (const [key, value] of Object.entries(props)) if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") result[key] = value;
9
+ else if (value !== void 0 && value !== null) result[key] = JSON.stringify(value);
10
+ return result;
11
+ }
12
+ function readCookie(cookieHeader, cookieName) {
13
+ if (!cookieHeader) return;
14
+ for (const part of cookieHeader.split(";")) {
15
+ const separatorIndex = part.indexOf("=");
16
+ if (separatorIndex !== -1 && part.slice(0, separatorIndex).trim() === cookieName) return part.slice(separatorIndex + 1).trim();
17
+ }
18
+ }
19
+ /**
20
+ * Reads gtag.js's own client ID from a request Cookie header — `_ga=GA1.1.123.456` →
21
+ * `123.456`. This (not an app-generated anonymous ID) is the value GA4 joins hits on, so
22
+ * pass it as `clientId` to make server events land on the same user as the visitor's
23
+ * client-side hits.
24
+ *
25
+ * @since 0.5.0-canary.4
26
+ */
27
+ function extractGa4ClientId(cookieHeader) {
28
+ const value = readCookie(cookieHeader, "_ga");
29
+ if (!value) return;
30
+ const segments = value.split(".");
31
+ return segments.length >= 4 ? segments.slice(-2).join(".") : void 0;
32
+ }
33
+ /**
34
+ * Reads the current GA4 session ID from the per-stream `_ga_<suffix>` cookie
35
+ * (`G-ABC123` → `_ga_ABC123`) — handles both the dot-delimited `GS1` and the
36
+ * `$`-delimited `GS2` value formats.
37
+ *
38
+ * @since 0.5.0-canary.4
39
+ */
40
+ function extractGa4SessionId(cookieHeader, measurementId) {
41
+ const value = readCookie(cookieHeader, `_ga_${measurementId.replace(/^G-/, "")}`);
42
+ if (!value) return;
43
+ return /^GS\d+\.\d+\.s?(\d+)/.exec(value)?.[1];
44
+ }
45
+ /**
46
+ * Server-side GA4 via the Measurement Protocol — for server-owned events (checkout,
47
+ * signup) that must land in GA4 without depending on client-side gtag.js. MP is designed
48
+ * to *augment* gtag.js data, so correlation hinges on echoing gtag's own identifiers:
49
+ * `clientId` from the `_ga` cookie and `sessionId` from the `_ga_<stream>` cookie.
50
+ *
51
+ * @since 0.5.0-canary.4
52
+ */
53
+ function createGa4MeasurementProtocolDestination(options) {
54
+ const name = options.name ?? "ga4-measurement-protocol";
55
+ const endpoint = `${options.debug ? "https://www.google-analytics.com/debug/mp/collect" : "https://www.google-analytics.com/mp/collect"}?measurement_id=${encodeURIComponent(options.measurementId)}&api_secret=${encodeURIComponent(options.apiSecret)}`;
56
+ return {
57
+ name,
58
+ async send(event) {
59
+ if (event.name === "$alias") return;
60
+ const eventName = event.name === "$group" ? "join_group" : event.name;
61
+ const params = toMeasurementProtocolParams(event.name === "$group" ? renameGroupIdProp(event.props) : event.props);
62
+ if (options.sessionId !== void 0 && params.session_id === void 0) params.session_id = options.sessionId;
63
+ params.engagement_time_msec ??= 100;
64
+ const response = await fetch(endpoint, {
65
+ body: JSON.stringify({
66
+ client_id: options.clientId ?? event.anonymousId,
67
+ events: [{
68
+ name: eventName,
69
+ params
70
+ }],
71
+ timestamp_micros: event.timestamp * 1e3,
72
+ ...event.userId === void 0 ? {} : { user_id: event.userId }
73
+ }),
74
+ headers: { "content-type": "application/json" },
75
+ method: "POST"
76
+ });
77
+ if (!response.ok) throw new Error(`"${name}" destination responded with ${String(response.status)}`);
78
+ }
79
+ };
80
+ }
81
+ function renameGroupIdProp(props) {
82
+ const { groupId, ...traits } = props;
83
+ return {
84
+ group_id: groupId,
85
+ ...traits
86
+ };
87
+ }
88
+ //#endregion
89
+ export { createGa4MeasurementProtocolDestination, extractGa4ClientId, extractGa4SessionId };
@@ -0,0 +1,98 @@
1
+ import { ConsentDecision } from "../core/consent.mjs";
2
+ import { Destination } from "../core/destination.mjs";
3
+
4
+ //#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
+ }
15
+ /**
16
+ * All signatures share one `gtag` global, so they must live in a single overloaded type —
17
+ * two separate `declare global` augmentations with different signatures for the same
18
+ * property is a TS error, not a merge.
19
+ */
20
+ type GtagFunction = {
21
+ (command: "consent", action: "default" | "update", params: GoogleConsentParams): void;
22
+ (command: "event", eventName: string, params?: Record<string, GtagPropertyValue>): void;
23
+ (command: "set", params: Record<string, GtagPropertyValue>): void;
24
+ (command: "set", key: string, value: boolean): void;
25
+ };
26
+ declare global {
27
+ interface Window {
28
+ dataLayer?: Array<unknown>;
29
+ gtag?: GtagFunction;
30
+ }
31
+ }
32
+ /**
33
+ * @since 0.5.0-canary.4
34
+ */
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;
40
+ }
41
+ /**
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.
45
+ *
46
+ * @since 0.5.0-canary.4
47
+ */
48
+ declare function setGoogleConsentDefault(decision: ConsentDecision, options?: GoogleConsentDefaultOptions): void;
49
+ /**
50
+ * Google Consent Mode v2's "update" signal — call whenever the visitor's effective
51
+ * consent changes (a banner decision, or one synced from another tab), so already-loaded
52
+ * GA4/Ads tags pick up the change without a page reload.
53
+ *
54
+ * @since 0.5.0-canary.4
55
+ */
56
+ declare function updateGoogleConsent(decision: ConsentDecision): void;
57
+ /**
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
63
+ */
64
+ declare function setGoogleAdsDataRedaction(enabled: boolean): void;
65
+ /**
66
+ * Consent Mode's `url_passthrough` flag — carries ad click info through page URLs while
67
+ * storage is denied, preserving conversion attribution without cookies.
68
+ *
69
+ * @since 0.5.0-canary.4
70
+ */
71
+ declare function setGoogleUrlPassthrough(enabled: boolean): void;
72
+ /**
73
+ * @since 0.5.0-canary.4
74
+ */
75
+ 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;
85
+ }
86
+ /**
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.
93
+ *
94
+ * @since 0.5.0-canary.4
95
+ */
96
+ declare function createGoogleAnalyticsDestination(options?: GoogleAnalyticsDestinationOptions): Destination;
97
+ //#endregion
98
+ export { GoogleAnalyticsDestinationOptions, GoogleConsentDefaultOptions, createGoogleAnalyticsDestination, setGoogleAdsDataRedaction, setGoogleConsentDefault, setGoogleUrlPassthrough, updateGoogleConsent };
@@ -0,0 +1,126 @@
1
+ //#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
+ };
15
+ }
16
+ /**
17
+ * Ensures the standard gtag.js queueing stub exists so consent commands can be issued
18
+ * before the tag itself loads — gtag.js replays the queue in order once it boots.
19
+ */
20
+ function ensureGtag() {
21
+ if (typeof window === "undefined") return;
22
+ window.dataLayer ??= [];
23
+ window.gtag ??= function gtag() {
24
+ window.dataLayer?.push(arguments);
25
+ };
26
+ return window.gtag;
27
+ }
28
+ /**
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.
32
+ *
33
+ * @since 0.5.0-canary.4
34
+ */
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);
40
+ }
41
+ /**
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.
45
+ *
46
+ * @since 0.5.0-canary.4
47
+ */
48
+ function updateGoogleConsent(decision) {
49
+ ensureGtag()?.("consent", "update", toGoogleConsentParams(decision));
50
+ }
51
+ /**
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.
55
+ *
56
+ * @since 0.5.0-canary.4
57
+ */
58
+ function setGoogleAdsDataRedaction(enabled) {
59
+ ensureGtag()?.("set", "ads_data_redaction", enabled);
60
+ }
61
+ /**
62
+ * Consent Mode's `url_passthrough` flag — carries ad click info through page URLs while
63
+ * storage is denied, preserving conversion attribution without cookies.
64
+ *
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.
73
+ */
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;
79
+ }
80
+ const GA4_EVENT_NAME_PATTERN = /^[A-Za-z][\w]{0,39}$/;
81
+ /**
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.
88
+ *
89
+ * @since 0.5.0-canary.4
90
+ */
91
+ function createGoogleAnalyticsDestination(options = {}) {
92
+ const name = options.name ?? "google-analytics";
93
+ return {
94
+ delivery: "immediate",
95
+ name,
96
+ send(event) {
97
+ 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));
122
+ }
123
+ };
124
+ }
125
+ //#endregion
126
+ export { createGoogleAnalyticsDestination, setGoogleAdsDataRedaction, setGoogleConsentDefault, setGoogleUrlPassthrough, updateGoogleConsent };
@@ -1,6 +1,9 @@
1
1
  import { Destination } from "../core/destination.mjs";
2
2
 
3
3
  //#region src/destinations/http-destination.d.ts
4
+ /**
5
+ * @since 0.5.0-canary.4
6
+ */
4
7
  interface HttpDestinationOptions {
5
8
  endpoint: string;
6
9
  headers?: Record<string, string>;
@@ -9,6 +12,8 @@ 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
  declare function createHttpDestination(options: HttpDestinationOptions): Destination;
14
19
  //#endregion
@@ -2,6 +2,8 @@
2
2
  /**
3
3
  * Generic fetch-based `Destination` — the building block for a real provider adapter
4
4
  * (PostHog, GA4, ...); those ship their own payload shape and aren't implemented here.
5
+ *
6
+ * @since 0.5.0-canary.4
5
7
  */
6
8
  function createHttpDestination(options) {
7
9
  return {
@@ -1,3 +1,5 @@
1
+ import { Ga4MeasurementProtocolDestinationOptions, createGa4MeasurementProtocolDestination, extractGa4ClientId, extractGa4SessionId } from "./ga4-measurement-protocol.mjs";
2
+ import { GoogleAnalyticsDestinationOptions, GoogleConsentDefaultOptions, createGoogleAnalyticsDestination, setGoogleAdsDataRedaction, setGoogleConsentDefault, setGoogleUrlPassthrough, updateGoogleConsent } from "./google-analytics.mjs";
1
3
  import { HttpDestinationOptions, createHttpDestination } from "./http-destination.mjs";
2
4
  import { createVercelAnalyticsDestination } from "./vercel-analytics.mjs";
3
- export { type HttpDestinationOptions, createHttpDestination, createVercelAnalyticsDestination };
5
+ export { type Ga4MeasurementProtocolDestinationOptions, type GoogleAnalyticsDestinationOptions, type GoogleConsentDefaultOptions, type HttpDestinationOptions, createGa4MeasurementProtocolDestination, createGoogleAnalyticsDestination, createHttpDestination, createVercelAnalyticsDestination, extractGa4ClientId, extractGa4SessionId, setGoogleAdsDataRedaction, setGoogleConsentDefault, setGoogleUrlPassthrough, updateGoogleConsent };
@@ -1,3 +1,5 @@
1
+ import { createGa4MeasurementProtocolDestination, extractGa4ClientId, extractGa4SessionId } from "./ga4-measurement-protocol.mjs";
2
+ import { createGoogleAnalyticsDestination, setGoogleAdsDataRedaction, setGoogleConsentDefault, setGoogleUrlPassthrough, updateGoogleConsent } from "./google-analytics.mjs";
1
3
  import { createHttpDestination } from "./http-destination.mjs";
2
4
  import { createVercelAnalyticsDestination } from "./vercel-analytics.mjs";
3
- export { createHttpDestination, createVercelAnalyticsDestination };
5
+ export { createGa4MeasurementProtocolDestination, createGoogleAnalyticsDestination, createHttpDestination, createVercelAnalyticsDestination, extractGa4ClientId, extractGa4SessionId, setGoogleAdsDataRedaction, setGoogleConsentDefault, setGoogleUrlPassthrough, updateGoogleConsent };
@@ -2,9 +2,11 @@ import { Destination } from "../core/destination.mjs";
2
2
 
3
3
  //#region src/destinations/vercel-analytics.d.ts
4
4
  /**
5
- * `track()` only pushes onto Vercel's own in-page queue (`window.va`/`window.vaq`) — it
6
- * never rejects, so this destination never triggers `EventQueue`'s retry path. Requires
5
+ * `track()` only pushes onto Vercel's own in-page queue (`window.va`/`window.vaq`), which
6
+ * handles batching and unload delivery itself — hence `delivery: "immediate"`. Requires
7
7
  * `<Analytics />` from `@vercel/analytics/react` to be mounted once in the app.
8
+ *
9
+ * @since 0.5.0-canary.4
8
10
  */
9
11
  declare function createVercelAnalyticsDestination(name?: string): Destination;
10
12
  //#endregion
@@ -11,12 +11,15 @@ function toVercelAnalyticsProps(props) {
11
11
  return result;
12
12
  }
13
13
  /**
14
- * `track()` only pushes onto Vercel's own in-page queue (`window.va`/`window.vaq`) — it
15
- * never rejects, so this destination never triggers `EventQueue`'s retry path. Requires
14
+ * `track()` only pushes onto Vercel's own in-page queue (`window.va`/`window.vaq`), which
15
+ * handles batching and unload delivery itself — hence `delivery: "immediate"`. Requires
16
16
  * `<Analytics />` from `@vercel/analytics/react` to be mounted once in the app.
17
+ *
18
+ * @since 0.5.0-canary.4
17
19
  */
18
20
  function createVercelAnalyticsDestination(name = "vercel-analytics") {
19
21
  return {
22
+ delivery: "immediate",
20
23
  name,
21
24
  send(event) {
22
25
  track(event.name, toVercelAnalyticsProps(event.props));
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- import { ConsentDecision, ConsentMode, ConsentRecord, ConsentRegion, ConsentStorage, resolveConsentMode, shouldTrackByDefault } from "./core/consent.mjs";
1
+ import { CONSENT_CATEGORIES, ConsentCategory, ConsentDecision, ConsentMode, ConsentRecord, ConsentRegion, ConsentStorage, createConsentDecision, isConsentDecision, resolveConsentMode, resolveDefaultConsent } from "./core/consent.mjs";
2
2
  import { TrackedEvent } from "./core/tracked-event.mjs";
3
3
  import { Destination } from "./core/destination.mjs";
4
4
  import { EventCatalog, EventDefinition, EventsOf, defineEventCatalog } from "./core/event-catalog.mjs";
5
5
  import { generateEventId } from "./core/event-id.mjs";
6
- export { type ConsentDecision, type ConsentMode, type ConsentRecord, type ConsentRegion, type ConsentStorage, type Destination, type EventCatalog, type EventDefinition, type EventsOf, type TrackedEvent, defineEventCatalog, generateEventId, resolveConsentMode, shouldTrackByDefault };
6
+ export { CONSENT_CATEGORIES, type ConsentCategory, type ConsentDecision, type ConsentMode, type ConsentRecord, type ConsentRegion, type ConsentStorage, type Destination, type EventCatalog, type EventDefinition, type EventsOf, type TrackedEvent, createConsentDecision, defineEventCatalog, generateEventId, isConsentDecision, resolveConsentMode, resolveDefaultConsent };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { resolveConsentMode, shouldTrackByDefault } from "./core/consent.mjs";
1
+ import { CONSENT_CATEGORIES, createConsentDecision, isConsentDecision, resolveConsentMode, resolveDefaultConsent } from "./core/consent.mjs";
2
2
  import { defineEventCatalog } from "./core/event-catalog.mjs";
3
3
  import { generateEventId } from "./core/event-id.mjs";
4
- export { defineEventCatalog, generateEventId, resolveConsentMode, shouldTrackByDefault };
4
+ export { CONSENT_CATEGORIES, createConsentDecision, defineEventCatalog, generateEventId, isConsentDecision, resolveConsentMode, resolveDefaultConsent };
@@ -1,41 +1,75 @@
1
+ import { ConsentCategory } from "../core/consent.mjs";
1
2
  import { UseConsentResult } from "./use-consent.mjs";
2
- import { ReactNode } from "react";
3
+ import { ComponentProps, ReactNode } from "react";
3
4
 
4
5
  //#region src/react/consent-banner.d.ts
5
- interface ConsentBannerProps {
6
+ /**
7
+ * One row of the preferences layer — the visitor-facing wording for a consent category.
8
+ *
9
+ * @since 0.5.0-canary.4
10
+ */
11
+ interface ConsentCategoryOption {
12
+ category: ConsentCategory;
13
+ description?: string;
14
+ label: string;
15
+ }
16
+ /**
17
+ * @since 0.5.0-canary.4
18
+ */
19
+ interface ConsentBannerProps extends Omit<ComponentProps<"section">, "children"> {
6
20
  acceptLabel?: string;
7
- className?: string;
21
+ /** Enables the per-category preferences layer; omit to keep the two-button banner. */
22
+ categories?: ReadonlyArray<ConsentCategoryOption>;
8
23
  consent: UseConsentResult;
9
- message?: string;
24
+ customizeLabel?: string;
25
+ /** A node, not just a string — informed consent needs the privacy-policy link inside the message. */
26
+ message?: ReactNode;
10
27
  rejectLabel?: string;
28
+ saveLabel?: string;
11
29
  }
12
30
  /**
13
- * Blocking opt-in prompt for GDPR/NĐ 13 regions — renders nothing once a decision
14
- * exists or the region defaults to opt-out (`consent.needsPrompt` covers both). No
15
- * styling is baked in; pass `className` to match the host app's design system.
31
+ * Non-blocking opt-in prompt for GDPR/NĐ 13 regions — renders nothing once a decision
32
+ * exists or the region defaults to opt-out (`consent.needsPrompt` covers both). Accept
33
+ * grants only the categories the app requested (`useConsent`'s `categories`), and the
34
+ * optional `categories` prop adds a second layer of per-category checkboxes — GDPR
35
+ * consent must be granular per purpose, not a single yes/no. Rendered as a labeled
36
+ * region, not a `<dialog>`: an open non-modal dialog neither traps focus nor blocks the
37
+ * page, so the dialog semantics would over-promise. No styling is baked in — target the
38
+ * root via `className` and the parts via their `data-slot` attributes (`consent-message`,
39
+ * `consent-actions`, `consent-action`, `consent-preferences`, `consent-category`).
40
+ *
41
+ * @since 0.5.0-canary.4
16
42
  */
17
43
  declare function ConsentBanner({
18
44
  acceptLabel,
19
- className,
45
+ categories,
20
46
  consent,
47
+ customizeLabel,
21
48
  message,
22
- rejectLabel
49
+ rejectLabel,
50
+ saveLabel,
51
+ ...props
23
52
  }: ConsentBannerProps): ReactNode;
24
- interface ConsentToggleProps {
53
+ /**
54
+ * @since 0.5.0-canary.4
55
+ */
56
+ interface ConsentToggleProps extends Omit<ComponentProps<"button">, "children" | "onClick" | "type"> {
25
57
  allowLabel?: string;
26
- className?: string;
27
58
  consent: UseConsentResult;
28
59
  denyLabel?: string;
29
60
  }
30
61
  /**
31
62
  * Always-visible control for opt-out regions — CCPA/CPRA requires a persistent
32
63
  * "Do Not Sell or Share My Personal Information" mechanism, not just a one-time prompt.
64
+ * Flips between denying everything and re-granting the app's requested categories.
65
+ *
66
+ * @since 0.5.0-canary.4
33
67
  */
34
68
  declare function ConsentToggle({
35
69
  allowLabel,
36
- className,
37
70
  consent,
38
- denyLabel
71
+ denyLabel,
72
+ ...props
39
73
  }: ConsentToggleProps): ReactNode;
40
74
  //#endregion
41
- export { ConsentBanner, ConsentBannerProps, ConsentToggle, ConsentToggleProps };
75
+ export { ConsentBanner, ConsentBannerProps, ConsentCategoryOption, ConsentToggle, ConsentToggleProps };