@codefast/tracking 0.5.0-canary.5 → 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 (133) hide show
  1. package/CHANGELOG.md +165 -0
  2. package/README.md +122 -127
  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 +24 -7
  54. package/dist/react/consent-banner.mjs +16 -11
  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 +4 -1
  58. package/dist/react/index.mjs +4 -1
  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 +26 -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/destinations/google-analytics.ts +196 -133
  96. package/src/destinations/google-consent.ts +164 -0
  97. package/src/destinations/index.ts +14 -15
  98. package/src/destinations/shared.ts +45 -0
  99. package/src/destinations/vercel-analytics.ts +23 -24
  100. package/src/import-protection.ts +20 -0
  101. package/src/index.ts +46 -8
  102. package/src/react/consent-banner.tsx +40 -14
  103. package/src/react/gtag-consent-bootstrap.tsx +48 -0
  104. package/src/react/index.ts +8 -0
  105. package/src/react/use-consent.ts +53 -45
  106. package/src/react/use-google-consent-sync.ts +38 -0
  107. package/src/react/use-initial-consent.ts +22 -0
  108. package/src/server/anonymous-id-cookie.ts +76 -0
  109. package/src/server/index.ts +15 -3
  110. package/src/server/initial-consent.ts +48 -0
  111. package/src/server/region.ts +22 -5
  112. package/src/tanstack-start/index.ts +83 -0
  113. package/dist/client/lifecycle.d.mts +0 -23
  114. package/dist/client/lifecycle.mjs +0 -30
  115. package/dist/client/local-storage.d.mts +0 -13
  116. package/dist/client/local-storage.mjs +0 -31
  117. package/dist/client/queue.d.mts +0 -49
  118. package/dist/client/queue.mjs +0 -71
  119. package/dist/client/router.d.mts +0 -30
  120. package/dist/client/router.mjs +0 -17
  121. package/dist/destinations/ga4-measurement-protocol.d.mts +0 -54
  122. package/dist/destinations/ga4-measurement-protocol.mjs +0 -89
  123. package/dist/destinations/http-destination.d.mts +0 -20
  124. package/dist/destinations/http-destination.mjs +0 -25
  125. package/dist/server/create-server-tracker.d.mts +0 -42
  126. package/dist/server/create-server-tracker.mjs +0 -67
  127. package/src/client/lifecycle.ts +0 -50
  128. package/src/client/local-storage.ts +0 -44
  129. package/src/client/queue.ts +0 -117
  130. package/src/client/router.ts +0 -37
  131. package/src/destinations/ga4-measurement-protocol.ts +0 -166
  132. package/src/destinations/http-destination.ts +0 -33
  133. package/src/server/create-server-tracker.ts +0 -128
@@ -1,4 +1,5 @@
1
1
  import type { ConsentRecord, ConsentStorage } from "#/core/consent";
2
+ import { isConsentRecord } from "#/core/consent";
2
3
 
3
4
  /**
4
5
  * `localStorage`-backed consent storage. Corrupt state, a private-mode/quota error, or no
@@ -6,6 +7,11 @@ import type { ConsentRecord, ConsentStorage } from "#/core/consent";
6
7
  * for the session instead of re-prompting in a loop. `subscribe` fires for same-tab
7
8
  * writes and, via the `storage` event, for decisions made in other tabs.
8
9
  *
10
+ * `load()` parses and validates at most once per change: the result is cached and
11
+ * invalidated by `save`/`clear` and by cross-tab `storage` events, so per-event consent
12
+ * gates and per-render `useSyncExternalStore` snapshots cost a memory read, not a
13
+ * `JSON.parse`.
14
+ *
9
15
  * @remarks
10
16
  * The record persists as plain `JSON.stringify(ConsentRecord)` — a stable contract, so
11
17
  * pre-hydration inline scripts (e.g. a Consent Mode default bootstrap) can read the
@@ -16,6 +22,9 @@ import type { ConsentRecord, ConsentStorage } from "#/core/consent";
16
22
  export function createLocalStorageConsentStorage(storageKey: string): ConsentStorage {
17
23
  const listeners = new Set<() => void>();
18
24
  let memoryRecord: ConsentRecord | undefined;
25
+ // Keyed by the raw string so ANY write path (save(), another tab, dev tools) is caught
26
+ // by a cheap string compare — parse + validate re-run only when the value changed.
27
+ let cache: { raw: string | null; record: ConsentRecord | undefined } | undefined;
19
28
 
20
29
  function notify(): void {
21
30
  for (const listener of listeners) {
@@ -30,6 +39,7 @@ export function createLocalStorageConsentStorage(storageKey: string): ConsentSto
30
39
  }
31
40
 
32
41
  memoryRecord = undefined;
42
+ cache = undefined;
33
43
 
34
44
  try {
35
45
  globalThis.window.localStorage.removeItem(storageKey);
@@ -47,8 +57,26 @@ export function createLocalStorageConsentStorage(storageKey: string): ConsentSto
47
57
  try {
48
58
  const raw = globalThis.window.localStorage.getItem(storageKey);
49
59
 
50
- return raw ? (JSON.parse(raw) as ConsentRecord) : memoryRecord;
60
+ if (cache && raw === cache.raw) {
61
+ return cache.record;
62
+ }
63
+
64
+ let record: ConsentRecord | undefined;
65
+
66
+ if (raw) {
67
+ const parsed: unknown = JSON.parse(raw);
68
+
69
+ // Drop malformed records at the source — mirrors the offline-queue storage guard.
70
+ record = isConsentRecord(parsed) ? parsed : memoryRecord;
71
+ } else {
72
+ record = memoryRecord;
73
+ }
74
+
75
+ cache = { raw, record };
76
+
77
+ return record;
51
78
  } catch {
79
+ // Storage blocked — never seed the cache off an error path.
52
80
  return memoryRecord;
53
81
  }
54
82
  },
@@ -57,6 +85,8 @@ export function createLocalStorageConsentStorage(storageKey: string): ConsentSto
57
85
  return;
58
86
  }
59
87
 
88
+ cache = undefined;
89
+
60
90
  try {
61
91
  globalThis.window.localStorage.setItem(storageKey, JSON.stringify(record));
62
92
  // localStorage is authoritative now — a lingering memory copy would shadow an
@@ -0,0 +1,32 @@
1
+ import type { ConsentDecision } from "#/core/consent";
2
+
3
+ /**
4
+ * @since 1.0.0-canary.6
5
+ */
6
+ export interface ConsentWithdrawalHandlerOptions {
7
+ /** Forget the cookie-backed visitor id when analytics is denied. */
8
+ clearAnonymousId?: (() => void) | undefined;
9
+ /** Expire Google's `_ga` / `_ga_*` cookies when analytics is denied. */
10
+ clearGoogleAnalyticsCookies?: (() => void) | undefined;
11
+ }
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
+ export function createConsentWithdrawalHandler(
20
+ options: ConsentWithdrawalHandlerOptions,
21
+ ): (decision: ConsentDecision) => void {
22
+ const { clearAnonymousId, clearGoogleAnalyticsCookies } = options;
23
+
24
+ return (decision: ConsentDecision): void => {
25
+ if (decision.analytics) {
26
+ return;
27
+ }
28
+
29
+ clearAnonymousId?.();
30
+ clearGoogleAnalyticsCookies?.();
31
+ };
32
+ }
@@ -0,0 +1,93 @@
1
+ import { writeBrowserCookie } from "#/client/browser-cookie";
2
+ import { ONE_YEAR_IN_SECONDS, readCookieValue } from "#/core/cookie";
3
+
4
+ /**
5
+ * @since 1.0.0-canary.6
6
+ */
7
+ export interface CookieAnonymousIdOptions {
8
+ /** Cookie name — must not collide with another cookie on the domain. */
9
+ cookieName: string;
10
+ /** How long the id survives a return visit. Defaults to one year. */
11
+ maxAgeSeconds?: number | undefined;
12
+ }
13
+
14
+ /**
15
+ * @since 1.0.0-canary.6
16
+ */
17
+ export interface CookieAnonymousId {
18
+ /** Expires the cookie — call when the visitor withdraws tracking consent. */
19
+ clear: () => void;
20
+ /** The existing id, or a freshly minted and persisted one. */
21
+ getOrCreate: () => string;
22
+ /**
23
+ * Rolls an *existing* id's expiry forward without ever minting one — safe to call on
24
+ * page load for returning consented visitors (the ITP-refresh path), a no-op for
25
+ * visitors who never got an id.
26
+ */
27
+ refresh: () => void;
28
+ }
29
+
30
+ /**
31
+ * A `document.cookie`-backed anonymous id — not `localStorage`-only, so a server-owned
32
+ * event can read the same id from the request and correlate to this visitor. Pass
33
+ * `getOrCreate` (not the result of calling it) as `ClientTrackerOptions.anonymousId`:
34
+ * it's invoked lazily, so the cookie is minted only once an event is actually allowed to
35
+ * send, never as an import-time side effect.
36
+ *
37
+ * @since 1.0.0-canary.6
38
+ */
39
+ export function createCookieAnonymousId(options: CookieAnonymousIdOptions): CookieAnonymousId {
40
+ const { cookieName, maxAgeSeconds = ONE_YEAR_IN_SECONDS } = options;
41
+ // Cached after the first getOrCreate() so a callback invoked once per tracked event
42
+ // doesn't re-parse the whole cookie header every time — cleared alongside the cookie.
43
+ let cachedId: string | undefined;
44
+
45
+ return {
46
+ clear(): void {
47
+ cachedId = undefined;
48
+
49
+ if (typeof document === "undefined") {
50
+ return;
51
+ }
52
+
53
+ writeBrowserCookie(cookieName, "", 0);
54
+ },
55
+ getOrCreate(): string {
56
+ if (typeof document === "undefined") {
57
+ return cachedId ?? crypto.randomUUID();
58
+ }
59
+
60
+ const existing = readCookieValue(document.cookie, cookieName);
61
+
62
+ // Prefer the live cookie over `cachedId` — another tab's withdrawal expires the
63
+ // cookie without calling this instance's `clear()`, and a re-grant must not revive
64
+ // the pre-withdrawal identity from memory.
65
+ if (existing) {
66
+ cachedId = existing;
67
+
68
+ return existing;
69
+ }
70
+
71
+ cachedId = undefined;
72
+
73
+ const id = crypto.randomUUID();
74
+
75
+ writeBrowserCookie(cookieName, id, maxAgeSeconds);
76
+ cachedId = id;
77
+
78
+ return id;
79
+ },
80
+ refresh(): void {
81
+ if (typeof document === "undefined") {
82
+ return;
83
+ }
84
+
85
+ const existing = readCookieValue(document.cookie, cookieName);
86
+
87
+ if (existing) {
88
+ cachedId = existing;
89
+ writeBrowserCookie(cookieName, existing, maxAgeSeconds);
90
+ }
91
+ },
92
+ };
93
+ }
@@ -1,38 +1,52 @@
1
- import type { z } from "zod";
1
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
2
 
3
- import { EventQueue, type EventQueueStorage } from "#/client/queue";
4
3
  import type { Destination } from "#/core/destination";
5
- import type { EventCatalog, EventsOf } from "#/core/event-catalog";
4
+ import type { EventCatalog } from "#/core/event-catalog";
5
+ import { assertValidEventProperties } from "#/core/event-catalog";
6
6
  import { generateEventId } from "#/core/event-id";
7
7
  import type { TrackedEvent } from "#/core/tracked-event";
8
8
 
9
+ /**
10
+ * `Destination.send` is typed to always return a `Promise`, but that's unenforceable at
11
+ * runtime for a third-party/plain-JS destination — one that ignores the contract and
12
+ * throws synchronously (or returns a non-`Promise`) must still never break the tracked
13
+ * interaction. `Promise.resolve(...)` normalizes a non-`Promise` return; the outer
14
+ * try/catch is the only thing that can catch a throw that happens before `send` ever
15
+ * gets to return anything.
16
+ */
17
+ function sendToDestination(destination: Destination, event: TrackedEvent): void {
18
+ try {
19
+ void Promise.resolve(destination.send(event)).catch(() => {
20
+ /* a destination owns its transport — tracking must never break the interaction */
21
+ });
22
+ } catch {
23
+ /* a sync throw must never break the tracked interaction */
24
+ }
25
+ }
26
+
9
27
  /**
10
28
  * @since 0.5.0-canary.4
11
29
  */
12
30
  export interface ClientTrackerOptions<Catalog extends EventCatalog> {
13
- anonymousId: string;
31
+ /** 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. */
32
+ anonymousId: () => string;
14
33
  catalog: Catalog;
15
34
  destinations: Array<Destination>;
16
- maxQueueSize?: number;
17
- maxRetries?: number;
18
- storage: EventQueueStorage;
35
+ /**
36
+ * Consulted before every event — while it returns `false`, only
37
+ * `consentRequirement: "exempt"` destinations still receive events, stripped of
38
+ * identifiers. Omit to always track.
39
+ */
40
+ isAnalyticsAllowed?: (() => boolean) | undefined;
19
41
  }
20
42
 
21
43
  /**
22
44
  * @since 0.5.0-canary.4
23
45
  */
24
46
  export interface ClientTracker<Catalog extends EventCatalog> {
25
- /** Drops every pending event without sending it — call this when consent is revoked. */
26
- clear: () => void;
27
- flush: () => Promise<void>;
28
- /** Synchronous, best-effort flush via `navigator.sendBeacon` — for page unload only. */
29
- flushWithBeacon: (endpoint: string) => void;
30
- group: (groupId: string, traits?: Record<string, unknown>) => void;
31
- identify: (userId: string, traits?: Record<string, unknown>) => void;
32
- page: (name?: string, props?: Record<string, unknown>) => void;
33
- track: <Name extends keyof EventsOf<Catalog, "client">>(
47
+ track: <Name extends keyof Catalog & string>(
34
48
  name: Name,
35
- props: z.infer<EventsOf<Catalog, "client">[Name]["schema"]>,
49
+ properties: StandardSchemaV1.InferOutput<Catalog[Name]["schema"]>,
36
50
  ) => void;
37
51
  }
38
52
 
@@ -42,85 +56,42 @@ export interface ClientTracker<Catalog extends EventCatalog> {
42
56
  export function createClientTracker<Catalog extends EventCatalog>(
43
57
  options: ClientTrackerOptions<Catalog>,
44
58
  ): ClientTracker<Catalog> {
45
- // SDK-backed destinations own their batching/unload delivery — routing them through
46
- // the queue would only delay events and replay stale ones next session.
47
- const immediateDestinations = options.destinations.filter((destination) => destination.delivery === "immediate");
48
- const queuedDestinations = options.destinations.filter((destination) => destination.delivery !== "immediate");
49
- const queue = new EventQueue({
50
- destinations: queuedDestinations,
51
- maxQueueSize: options.maxQueueSize,
52
- maxRetries: options.maxRetries,
53
- storage: options.storage,
54
- });
55
- let userId: string | undefined;
59
+ // The exempt lane only carries what a cookieless sink may see — identifier-free counts.
60
+ const exemptDestinations = options.destinations.filter((destination) => destination.consentRequirement === "exempt");
56
61
 
57
- function enqueue(name: string, props: Record<string, unknown>): void {
58
- const envelope: TrackedEvent = {
59
- anonymousId: options.anonymousId,
60
- eventId: generateEventId(),
61
- name,
62
- owner: "client",
63
- props,
64
- timestamp: Date.now(),
65
- ...(userId === undefined ? {} : { userId }),
66
- };
62
+ return {
63
+ track(name, properties) {
64
+ // noUncheckedIndexedAccess types this as possibly undefined; the check also guards
65
+ // callers who bypass the catalog key type with an `as` cast.
66
+ const definition = options.catalog[name];
67
67
 
68
- for (const destination of immediateDestinations) {
69
- try {
70
- void Promise.resolve(destination.send(envelope)).catch(() => {
71
- /* an immediate destination owns its transport — no retry path here */
72
- });
73
- } catch {
74
- /* a sync throw must never break the tracked interaction */
68
+ if (!definition) {
69
+ throw new Error(`Unknown event: ${String(name)}`);
75
70
  }
76
- }
77
71
 
78
- // Still enqueued unconditionally — the queue also feeds `flushWithBeacon`, which
79
- // ships raw envelopes to a custom endpoint independently of any destination.
80
- queue.enqueue(envelope);
81
- }
72
+ assertValidEventProperties(definition.schema, name, properties);
82
73
 
83
- return {
84
- clear: () => {
85
- queue.clear();
86
- },
87
- flush: () => queue.flush(),
88
- flushWithBeacon(endpoint) {
89
- const events = queue.drain();
74
+ // The gate runs per event (not at creation) so a consent change mid-session applies immediately.
75
+ const isAllowed = options.isAnalyticsAllowed?.() !== false;
90
76
 
91
- if (events.length === 0) {
77
+ if (!isAllowed && exemptDestinations.length === 0) {
92
78
  return;
93
79
  }
94
80
 
95
- const delivered = navigator.sendBeacon(endpoint, JSON.stringify(events));
81
+ const event: TrackedEvent = {
82
+ // Gated events ship identifier-free: no anonymousId is resolved, so none is ever
83
+ // minted as a side effect.
84
+ anonymousId: isAllowed ? options.anonymousId() : "",
85
+ eventId: generateEventId(),
86
+ name,
87
+ properties: properties as Record<string, unknown>,
88
+ timestamp: Date.now(),
89
+ type: "track",
90
+ };
96
91
 
97
- if (!delivered) {
98
- for (const event of events) {
99
- queue.enqueue(event);
100
- }
92
+ for (const destination of isAllowed ? options.destinations : exemptDestinations) {
93
+ sendToDestination(destination, event);
101
94
  }
102
95
  },
103
- group(groupId, traits = {}) {
104
- enqueue("$group", { groupId, ...traits });
105
- },
106
- identify(id, traits = {}) {
107
- userId = id;
108
- enqueue("$identify", traits);
109
- },
110
- page(name, props = {}) {
111
- enqueue("$page_viewed", name === undefined ? props : { name, ...props });
112
- },
113
- track(name, props) {
114
- // noUncheckedIndexedAccess types this as possibly undefined; the owner check also
115
- // guards callers who bypass the EventsOf filter with an `as` cast.
116
- const definition = options.catalog[name];
117
-
118
- if (!definition || definition.owner !== "client") {
119
- throw new Error(`Unknown client-owned event: ${String(name)}`);
120
- }
121
-
122
- definition.schema.parse(props);
123
- enqueue(name as string, props as Record<string, unknown>);
124
- },
125
96
  };
126
97
  }
package/src/client/gpc.ts CHANGED
@@ -1,13 +1,15 @@
1
1
  interface NavigatorWithGpc extends Navigator {
2
- globalPrivacyControl?: boolean;
2
+ globalPrivacyControl?: boolean | undefined;
3
3
  }
4
4
 
5
5
  /**
6
6
  * Global Privacy Control isn't in lib.dom yet, hence the local interface extension.
7
7
  * CCPA/CPRA requires honoring this as an opt-out signal even under the opt-out default.
8
+ * Guarded so SSR renders (where the module is reachable) read `false`, not a crash on
9
+ * runtimes without a global `navigator`.
8
10
  *
9
11
  * @since 0.5.0-canary.4
10
12
  */
11
13
  export function hasGlobalPrivacyControlSignal(): boolean {
12
- return (navigator as NavigatorWithGpc).globalPrivacyControl === true;
14
+ return typeof navigator !== "undefined" && (navigator as NavigatorWithGpc).globalPrivacyControl === true;
13
15
  }
@@ -1,17 +1,28 @@
1
1
  export type { ClientTracker, ClientTrackerOptions } from "#/client/create-client-tracker";
2
2
  export { createClientTracker } from "#/client/create-client-tracker";
3
3
 
4
+ export type { ConsentRuntime, ConsentRuntimeOptions } from "#/client/consent-runtime";
5
+ export { createConsentRuntime } from "#/client/consent-runtime";
6
+
4
7
  export { createLocalStorageConsentStorage } from "#/client/consent-storage";
5
8
 
6
- export { hasGlobalPrivacyControlSignal } from "#/client/gpc";
9
+ export type { ConsentWithdrawalHandlerOptions } from "#/client/consent-withdrawal";
10
+ export { createConsentWithdrawalHandler } from "#/client/consent-withdrawal";
7
11
 
8
- export type { ClientLifecycleOptions } from "#/client/lifecycle";
9
- export { attachClientLifecycle } from "#/client/lifecycle";
12
+ export type { CookieAnonymousId, CookieAnonymousIdOptions } from "#/client/cookie-anonymous-id";
13
+ export { createCookieAnonymousId } from "#/client/cookie-anonymous-id";
14
+
15
+ export { hasGlobalPrivacyControlSignal } from "#/client/gpc";
10
16
 
11
- export { createLocalStorageQueueStorage } from "#/client/local-storage";
17
+ export type {
18
+ InitialConsentSnapshot,
19
+ InitialConsentStore,
20
+ InitialConsentStoreOptions,
21
+ } from "#/client/initial-consent-store";
22
+ export { createInitialConsentStore } from "#/client/initial-consent-store";
12
23
 
13
- export type { EventQueueOptions, EventQueueStorage } from "#/client/queue";
14
- export { EventQueue } from "#/client/queue";
24
+ export type { IsAnalyticsAllowedOptions } from "#/client/is-analytics-allowed";
25
+ export { createIsAnalyticsAllowed } from "#/client/is-analytics-allowed";
15
26
 
16
- export type { RouterLike } from "#/client/router";
17
- export { attachRouterPageTracking } from "#/client/router";
27
+ export type { ServerPersistedAnonymousIdOptions } from "#/client/server-persisted-anonymous-id";
28
+ export { createServerPersistedAnonymousId } from "#/client/server-persisted-anonymous-id";
@@ -0,0 +1,218 @@
1
+ import type { InitialConsent } from "#/core/consent";
2
+ import { isInitialConsent, STRICTEST_INITIAL_CONSENT } from "#/core/consent";
3
+
4
+ /**
5
+ * External-store view of the visitor's region default — the strictest value until the
6
+ * server lane answers, then the resolved one.
7
+ *
8
+ * @since 1.0.0-canary.6
9
+ */
10
+ export interface InitialConsentSnapshot {
11
+ /** The region-correct default once resolved; {@link STRICTEST_INITIAL_CONSENT} until then. */
12
+ initialConsent: InitialConsent;
13
+ /**
14
+ * True once a usable default is published — either a successful server answer or a
15
+ * fail-closed fallback. A failed fetch still sets this so consent UI can render, but
16
+ * does not lock the session: resolution stays retryable.
17
+ */
18
+ isResolved: boolean;
19
+ }
20
+
21
+ /**
22
+ * @since 1.0.0-canary.6
23
+ */
24
+ export interface InitialConsentStoreOptions {
25
+ /**
26
+ * The per-visitor server lane — typically a server function wrapping
27
+ * `resolveInitialConsentFromRequest`. Prerendered/CDN-cached HTML can carry nothing
28
+ * region-specific, so this is the only place the region-correct default may come from.
29
+ */
30
+ resolve: () => Promise<InitialConsent>;
31
+ /**
32
+ * `sessionStorage` key caching the resolved value, so only the first page load of a
33
+ * session pays the round trip — omit to resolve once per page load instead. Cached
34
+ * values are re-validated with `isInitialConsent` before use.
35
+ */
36
+ sessionStorageKey?: string | undefined;
37
+ }
38
+
39
+ /**
40
+ * `useSyncExternalStore`-shaped — pass `subscribe`/`getSnapshot`/`getServerSnapshot`
41
+ * straight through, or use the `useInitialConsent` hook from `@codefast/tracking/react`.
42
+ *
43
+ * @since 1.0.0-canary.6
44
+ */
45
+ export interface InitialConsentStore {
46
+ /**
47
+ * Kicks off region resolution (at most one in-flight request; a success is sticky for
48
+ * the store's lifetime). Call it early — e.g. at router creation, window-guarded — so
49
+ * the round trip overlaps hydration instead of waiting for the first effect.
50
+ */
51
+ ensureResolved: () => void;
52
+ getServerSnapshot: () => InitialConsentSnapshot;
53
+ getSnapshot: () => InitialConsentSnapshot;
54
+ /** Test seam — clears resolved state, retry listeners, and the session cache. */
55
+ reset: () => void;
56
+ subscribe: (listener: () => void) => () => void;
57
+ }
58
+
59
+ const SERVER_SNAPSHOT: InitialConsentSnapshot = {
60
+ initialConsent: STRICTEST_INITIAL_CONSENT,
61
+ isResolved: false,
62
+ };
63
+
64
+ /**
65
+ * The client half of the server-resolved consent lane: single-flight resolution over the
66
+ * given server function, an optional per-session cache, fail-closed publishing on error
67
+ * (consent UI still renders, under the strictest default), and a retry the next time the
68
+ * tab becomes visible — so one failed request never locks the whole SPA session.
69
+ *
70
+ * @since 1.0.0-canary.6
71
+ */
72
+ export function createInitialConsentStore(options: InitialConsentStoreOptions): InitialConsentStore {
73
+ const listeners = new Set<() => void>();
74
+
75
+ let snapshot: InitialConsentSnapshot = SERVER_SNAPSHOT;
76
+ let isFetchInFlight = false;
77
+ /** Sticky only after a successful resolve (or session-cache hit) — failures stay retryable. */
78
+ let hasResolvedSuccessfully = false;
79
+
80
+ function notify(): void {
81
+ for (const listener of listeners) {
82
+ listener();
83
+ }
84
+ }
85
+
86
+ // add/removeEventListener dedupe an identical listener, so no armed-flag is needed.
87
+ function stopResolveRetry(): void {
88
+ if (typeof window === "undefined") {
89
+ return;
90
+ }
91
+
92
+ document.removeEventListener("visibilitychange", onResolveRetryResume);
93
+ window.removeEventListener("pageshow", onResolveRetryResume);
94
+ window.removeEventListener("online", onResolveRetryResume);
95
+ }
96
+
97
+ function onResolveRetryResume(): void {
98
+ if (hasResolvedSuccessfully) {
99
+ stopResolveRetry();
100
+
101
+ return;
102
+ }
103
+
104
+ if (document.visibilityState === "visible") {
105
+ ensureResolved();
106
+ }
107
+ }
108
+
109
+ /**
110
+ * After a failed fetch, retry when the tab becomes visible again or connectivity
111
+ * returns (coalesced by in-flight) — a visitor who never leaves the tab must not stay
112
+ * fail-closed for the whole session over one network blip.
113
+ */
114
+ function scheduleResolveRetry(): void {
115
+ if (typeof window === "undefined") {
116
+ return;
117
+ }
118
+
119
+ document.addEventListener("visibilitychange", onResolveRetryResume);
120
+ window.addEventListener("pageshow", onResolveRetryResume);
121
+ window.addEventListener("online", onResolveRetryResume);
122
+ }
123
+
124
+ function publishResolved(initialConsent: InitialConsent): void {
125
+ hasResolvedSuccessfully = true;
126
+ snapshot = { initialConsent, isResolved: true };
127
+ stopResolveRetry();
128
+ notify();
129
+ }
130
+
131
+ /** Fail-closed UI without permanently locking the session against a later retry. */
132
+ function publishFailClosed(): void {
133
+ snapshot = { initialConsent: STRICTEST_INITIAL_CONSENT, isResolved: true };
134
+ notify();
135
+ }
136
+
137
+ function readSessionCache(): InitialConsent | undefined {
138
+ if (options.sessionStorageKey === undefined) {
139
+ return undefined;
140
+ }
141
+
142
+ try {
143
+ const raw = window.sessionStorage.getItem(options.sessionStorageKey);
144
+ const parsed: unknown = raw === null ? undefined : JSON.parse(raw);
145
+
146
+ return isInitialConsent(parsed) ? parsed : undefined;
147
+ } catch {
148
+ return undefined;
149
+ }
150
+ }
151
+
152
+ function writeSessionCache(resolved: InitialConsent): void {
153
+ if (options.sessionStorageKey === undefined) {
154
+ return;
155
+ }
156
+
157
+ try {
158
+ window.sessionStorage.setItem(options.sessionStorageKey, JSON.stringify(resolved));
159
+ } catch {
160
+ /* private mode / quota — resolve again next page load */
161
+ }
162
+ }
163
+
164
+ function ensureResolved(): void {
165
+ if (hasResolvedSuccessfully || isFetchInFlight || typeof window === "undefined") {
166
+ return;
167
+ }
168
+
169
+ const cached = readSessionCache();
170
+
171
+ if (cached) {
172
+ publishResolved(cached);
173
+
174
+ return;
175
+ }
176
+
177
+ isFetchInFlight = true;
178
+
179
+ // Promise.resolve().then(...) folds a synchronously throwing resolver into the same
180
+ // fail-closed path — tracking must never break the caller (a React mount effect).
181
+ Promise.resolve()
182
+ .then(() => options.resolve())
183
+ .then((resolved) => {
184
+ writeSessionCache(resolved);
185
+ publishResolved(resolved);
186
+ })
187
+ .catch(() => {
188
+ publishFailClosed();
189
+ scheduleResolveRetry();
190
+ })
191
+ .finally(() => {
192
+ isFetchInFlight = false;
193
+ });
194
+ }
195
+
196
+ return {
197
+ ensureResolved,
198
+ getServerSnapshot: () => SERVER_SNAPSHOT,
199
+ getSnapshot: () => snapshot,
200
+ reset(): void {
201
+ stopResolveRetry();
202
+ snapshot = SERVER_SNAPSHOT;
203
+ isFetchInFlight = false;
204
+ hasResolvedSuccessfully = false;
205
+
206
+ if (typeof window !== "undefined" && options.sessionStorageKey !== undefined) {
207
+ window.sessionStorage.removeItem(options.sessionStorageKey);
208
+ }
209
+ },
210
+ subscribe(listener: () => void): () => void {
211
+ listeners.add(listener);
212
+
213
+ return () => {
214
+ listeners.delete(listener);
215
+ };
216
+ },
217
+ };
218
+ }