@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,3 +1,4 @@
1
+ import { isConsentRecord } from "../core/consent.mjs";
1
2
  //#region src/client/consent-storage.ts
2
3
  /**
3
4
  * `localStorage`-backed consent storage. Corrupt state, a private-mode/quota error, or no
@@ -5,6 +6,11 @@
5
6
  * for the session instead of re-prompting in a loop. `subscribe` fires for same-tab
6
7
  * writes and, via the `storage` event, for decisions made in other tabs.
7
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
+ *
8
14
  * @remarks
9
15
  * The record persists as plain `JSON.stringify(ConsentRecord)` — a stable contract, so
10
16
  * pre-hydration inline scripts (e.g. a Consent Mode default bootstrap) can read the
@@ -15,6 +21,7 @@
15
21
  function createLocalStorageConsentStorage(storageKey) {
16
22
  const listeners = /* @__PURE__ */ new Set();
17
23
  let memoryRecord;
24
+ let cache;
18
25
  function notify() {
19
26
  for (const listener of listeners) listener();
20
27
  }
@@ -22,6 +29,7 @@ function createLocalStorageConsentStorage(storageKey) {
22
29
  clear() {
23
30
  if (typeof globalThis.window === "undefined") return;
24
31
  memoryRecord = void 0;
32
+ cache = void 0;
25
33
  try {
26
34
  globalThis.window.localStorage.removeItem(storageKey);
27
35
  } catch {}
@@ -31,13 +39,24 @@ function createLocalStorageConsentStorage(storageKey) {
31
39
  if (typeof globalThis.window === "undefined") return;
32
40
  try {
33
41
  const raw = globalThis.window.localStorage.getItem(storageKey);
34
- return raw ? JSON.parse(raw) : memoryRecord;
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;
35
53
  } catch {
36
54
  return memoryRecord;
37
55
  }
38
56
  },
39
57
  save(record) {
40
58
  if (typeof globalThis.window === "undefined") return;
59
+ cache = void 0;
41
60
  try {
42
61
  globalThis.window.localStorage.setItem(storageKey, JSON.stringify(record));
43
62
  memoryRecord = void 0;
@@ -0,0 +1,21 @@
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 };
@@ -0,0 +1,17 @@
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 };
@@ -0,0 +1,37 @@
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 };
@@ -0,0 +1,46 @@
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,33 +1,28 @@
1
1
  import { Destination } from "../core/destination.mjs";
2
- import { EventQueueStorage } from "./queue.mjs";
3
- import { EventCatalog, EventsOf } from "../core/event-catalog.mjs";
4
- import { z } from "zod";
2
+ import { EventCatalog } from "../core/event-catalog.mjs";
3
+ import { StandardSchemaV1 } from "@standard-schema/spec";
5
4
 
6
5
  //#region src/client/create-client-tracker.d.ts
7
6
  /**
8
7
  * @since 0.5.0-canary.4
9
8
  */
10
9
  interface ClientTrackerOptions<Catalog extends EventCatalog> {
11
- anonymousId: string;
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
12
  catalog: Catalog;
13
13
  destinations: Array<Destination>;
14
- maxQueueSize?: number;
15
- maxRetries?: number;
16
- storage: EventQueueStorage;
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;
17
20
  }
18
21
  /**
19
22
  * @since 0.5.0-canary.4
20
23
  */
21
24
  interface ClientTracker<Catalog extends EventCatalog> {
22
- /** Drops every pending event without sending it — call this when consent is revoked. */
23
- clear: () => void;
24
- flush: () => Promise<void>;
25
- /** Synchronous, best-effort flush via `navigator.sendBeacon` — for page unload only. */
26
- flushWithBeacon: (endpoint: string) => void;
27
- group: (groupId: string, traits?: Record<string, unknown>) => void;
28
- identify: (userId: string, traits?: Record<string, unknown>) => void;
29
- page: (name?: string, props?: Record<string, unknown>) => void;
30
- track: <Name extends keyof EventsOf<Catalog, "client">>(name: Name, props: z.infer<EventsOf<Catalog, "client">[Name]["schema"]>) => void;
25
+ track: <Name extends keyof Catalog & string>(name: Name, properties: StandardSchemaV1.InferOutput<Catalog[Name]["schema"]>) => void;
31
26
  }
32
27
  /**
33
28
  * @since 0.5.0-canary.4
@@ -1,66 +1,40 @@
1
+ import { assertValidEventProperties } from "../core/event-catalog.mjs";
1
2
  import { generateEventId } from "../core/event-id.mjs";
2
- import { EventQueue } from "./queue.mjs";
3
3
  //#region src/client/create-client-tracker.ts
4
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
+ /**
5
18
  * @since 0.5.0-canary.4
6
19
  */
7
20
  function createClientTracker(options) {
8
- const immediateDestinations = options.destinations.filter((destination) => destination.delivery === "immediate");
9
- const queue = new EventQueue({
10
- destinations: options.destinations.filter((destination) => destination.delivery !== "immediate"),
11
- maxQueueSize: options.maxQueueSize,
12
- maxRetries: options.maxRetries,
13
- storage: options.storage
14
- });
15
- let userId;
16
- function enqueue(name, props) {
17
- const envelope = {
18
- anonymousId: options.anonymousId,
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() : "",
19
30
  eventId: generateEventId(),
20
31
  name,
21
- owner: "client",
22
- props,
32
+ properties,
23
33
  timestamp: Date.now(),
24
- ...userId === void 0 ? {} : { userId }
34
+ type: "track"
25
35
  };
26
- for (const destination of immediateDestinations) try {
27
- Promise.resolve(destination.send(envelope)).catch(() => {});
28
- } catch {}
29
- queue.enqueue(envelope);
30
- }
31
- return {
32
- clear: () => {
33
- queue.clear();
34
- },
35
- flush: () => queue.flush(),
36
- flushWithBeacon(endpoint) {
37
- const events = queue.drain();
38
- if (events.length === 0) return;
39
- if (!navigator.sendBeacon(endpoint, JSON.stringify(events))) for (const event of events) queue.enqueue(event);
40
- },
41
- group(groupId, traits = {}) {
42
- enqueue("$group", {
43
- groupId,
44
- ...traits
45
- });
46
- },
47
- identify(id, traits = {}) {
48
- userId = id;
49
- enqueue("$identify", traits);
50
- },
51
- page(name, props = {}) {
52
- enqueue("$page_viewed", name === void 0 ? props : {
53
- name,
54
- ...props
55
- });
56
- },
57
- track(name, props) {
58
- const definition = options.catalog[name];
59
- if (!definition || definition.owner !== "client") throw new Error(`Unknown client-owned event: ${String(name)}`);
60
- definition.schema.parse(props);
61
- enqueue(name, props);
62
- }
63
- };
36
+ for (const destination of isAllowed ? options.destinations : exemptDestinations) sendToDestination(destination, event);
37
+ } };
64
38
  }
65
39
  //#endregion
66
40
  export { createClientTracker };
@@ -2,6 +2,8 @@
2
2
  /**
3
3
  * Global Privacy Control isn't in lib.dom yet, hence the local interface extension.
4
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`.
5
7
  *
6
8
  * @since 0.5.0-canary.4
7
9
  */
@@ -2,11 +2,13 @@
2
2
  /**
3
3
  * Global Privacy Control isn't in lib.dom yet, hence the local interface extension.
4
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`.
5
7
  *
6
8
  * @since 0.5.0-canary.4
7
9
  */
8
10
  function hasGlobalPrivacyControlSignal() {
9
- return navigator.globalPrivacyControl === true;
11
+ return typeof navigator !== "undefined" && navigator.globalPrivacyControl === true;
10
12
  }
11
13
  //#endregion
12
14
  export { hasGlobalPrivacyControlSignal };
@@ -1,8 +1,10 @@
1
+ import { InitialConsentSnapshot, InitialConsentStore, InitialConsentStoreOptions, createInitialConsentStore } from "./initial-consent-store.mjs";
2
+ import { ConsentRuntime, ConsentRuntimeOptions, createConsentRuntime } from "./consent-runtime.mjs";
1
3
  import { createLocalStorageConsentStorage } from "./consent-storage.mjs";
2
- import { EventQueue, EventQueueOptions, EventQueueStorage } from "./queue.mjs";
4
+ import { ConsentWithdrawalHandlerOptions, createConsentWithdrawalHandler } from "./consent-withdrawal.mjs";
5
+ import { CookieAnonymousId, CookieAnonymousIdOptions, createCookieAnonymousId } from "./cookie-anonymous-id.mjs";
3
6
  import { ClientTracker, ClientTrackerOptions, createClientTracker } from "./create-client-tracker.mjs";
4
7
  import { hasGlobalPrivacyControlSignal } from "./gpc.mjs";
5
- import { ClientLifecycleOptions, attachClientLifecycle } from "./lifecycle.mjs";
6
- import { createLocalStorageQueueStorage } from "./local-storage.mjs";
7
- import { RouterLike, attachRouterPageTracking } from "./router.mjs";
8
- export { type ClientLifecycleOptions, type ClientTracker, type ClientTrackerOptions, EventQueue, type EventQueueOptions, type EventQueueStorage, type RouterLike, attachClientLifecycle, attachRouterPageTracking, createClientTracker, createLocalStorageConsentStorage, createLocalStorageQueueStorage, hasGlobalPrivacyControlSignal };
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 };
@@ -1,8 +1,10 @@
1
1
  import { createLocalStorageConsentStorage } from "./consent-storage.mjs";
2
- import { EventQueue } from "./queue.mjs";
3
- import { createClientTracker } from "./create-client-tracker.mjs";
4
2
  import { hasGlobalPrivacyControlSignal } from "./gpc.mjs";
5
- import { attachClientLifecycle } from "./lifecycle.mjs";
6
- import { createLocalStorageQueueStorage } from "./local-storage.mjs";
7
- import { attachRouterPageTracking } from "./router.mjs";
8
- export { EventQueue, attachClientLifecycle, attachRouterPageTracking, createClientTracker, createLocalStorageConsentStorage, createLocalStorageQueueStorage, hasGlobalPrivacyControlSignal };
3
+ import { createInitialConsentStore } from "./initial-consent-store.mjs";
4
+ import { createIsAnalyticsAllowed } from "./is-analytics-allowed.mjs";
5
+ import { createConsentRuntime } from "./consent-runtime.mjs";
6
+ import { createConsentWithdrawalHandler } from "./consent-withdrawal.mjs";
7
+ import { createCookieAnonymousId } from "./cookie-anonymous-id.mjs";
8
+ import { createClientTracker } from "./create-client-tracker.mjs";
9
+ import { createServerPersistedAnonymousId } from "./server-persisted-anonymous-id.mjs";
10
+ export { createClientTracker, createConsentRuntime, createConsentWithdrawalHandler, createCookieAnonymousId, createInitialConsentStore, createIsAnalyticsAllowed, createLocalStorageConsentStorage, createServerPersistedAnonymousId, hasGlobalPrivacyControlSignal };
@@ -0,0 +1,66 @@
1
+ import { InitialConsent } from "../core/consent.mjs";
2
+
3
+ //#region src/client/initial-consent-store.d.ts
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
+ 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
+ * @since 1.0.0-canary.6
22
+ */
23
+ interface InitialConsentStoreOptions {
24
+ /**
25
+ * The per-visitor server lane — typically a server function wrapping
26
+ * `resolveInitialConsentFromRequest`. Prerendered/CDN-cached HTML can carry nothing
27
+ * region-specific, so this is the only place the region-correct default may come from.
28
+ */
29
+ resolve: () => Promise<InitialConsent>;
30
+ /**
31
+ * `sessionStorage` key caching the resolved value, so only the first page load of a
32
+ * session pays the round trip — omit to resolve once per page load instead. Cached
33
+ * values are re-validated with `isInitialConsent` before use.
34
+ */
35
+ sessionStorageKey?: string | undefined;
36
+ }
37
+ /**
38
+ * `useSyncExternalStore`-shaped — pass `subscribe`/`getSnapshot`/`getServerSnapshot`
39
+ * straight through, or use the `useInitialConsent` hook from `@codefast/tracking/react`.
40
+ *
41
+ * @since 1.0.0-canary.6
42
+ */
43
+ interface InitialConsentStore {
44
+ /**
45
+ * Kicks off region resolution (at most one in-flight request; a success is sticky for
46
+ * the store's lifetime). Call it early — e.g. at router creation, window-guarded — so
47
+ * the round trip overlaps hydration instead of waiting for the first effect.
48
+ */
49
+ ensureResolved: () => void;
50
+ getServerSnapshot: () => InitialConsentSnapshot;
51
+ getSnapshot: () => InitialConsentSnapshot;
52
+ /** Test seam — clears resolved state, retry listeners, and the session cache. */
53
+ reset: () => void;
54
+ subscribe: (listener: () => void) => () => void;
55
+ }
56
+ /**
57
+ * The client half of the server-resolved consent lane: single-flight resolution over the
58
+ * given server function, an optional per-session cache, fail-closed publishing on error
59
+ * (consent UI still renders, under the strictest default), and a retry the next time the
60
+ * tab becomes visible — so one failed request never locks the whole SPA session.
61
+ *
62
+ * @since 1.0.0-canary.6
63
+ */
64
+ declare function createInitialConsentStore(options: InitialConsentStoreOptions): InitialConsentStore;
65
+ //#endregion
66
+ export { InitialConsentSnapshot, InitialConsentStore, InitialConsentStoreOptions, createInitialConsentStore };
@@ -0,0 +1,119 @@
1
+ import { STRICTEST_INITIAL_CONSENT, isInitialConsent } from "../core/consent.mjs";
2
+ //#region src/client/initial-consent-store.ts
3
+ const SERVER_SNAPSHOT = {
4
+ initialConsent: STRICTEST_INITIAL_CONSENT,
5
+ isResolved: false
6
+ };
7
+ /**
8
+ * The client half of the server-resolved consent lane: single-flight resolution over the
9
+ * given server function, an optional per-session cache, fail-closed publishing on error
10
+ * (consent UI still renders, under the strictest default), and a retry the next time the
11
+ * tab becomes visible — so one failed request never locks the whole SPA session.
12
+ *
13
+ * @since 1.0.0-canary.6
14
+ */
15
+ function createInitialConsentStore(options) {
16
+ const listeners = /* @__PURE__ */ new Set();
17
+ let snapshot = SERVER_SNAPSHOT;
18
+ let isFetchInFlight = false;
19
+ /** Sticky only after a successful resolve (or session-cache hit) — failures stay retryable. */
20
+ let hasResolvedSuccessfully = false;
21
+ function notify() {
22
+ for (const listener of listeners) listener();
23
+ }
24
+ function stopResolveRetry() {
25
+ if (typeof window === "undefined") return;
26
+ document.removeEventListener("visibilitychange", onResolveRetryResume);
27
+ window.removeEventListener("pageshow", onResolveRetryResume);
28
+ window.removeEventListener("online", onResolveRetryResume);
29
+ }
30
+ function onResolveRetryResume() {
31
+ if (hasResolvedSuccessfully) {
32
+ stopResolveRetry();
33
+ return;
34
+ }
35
+ if (document.visibilityState === "visible") ensureResolved();
36
+ }
37
+ /**
38
+ * After a failed fetch, retry when the tab becomes visible again or connectivity
39
+ * returns (coalesced by in-flight) — a visitor who never leaves the tab must not stay
40
+ * fail-closed for the whole session over one network blip.
41
+ */
42
+ function scheduleResolveRetry() {
43
+ if (typeof window === "undefined") return;
44
+ document.addEventListener("visibilitychange", onResolveRetryResume);
45
+ window.addEventListener("pageshow", onResolveRetryResume);
46
+ window.addEventListener("online", onResolveRetryResume);
47
+ }
48
+ function publishResolved(initialConsent) {
49
+ hasResolvedSuccessfully = true;
50
+ snapshot = {
51
+ initialConsent,
52
+ isResolved: true
53
+ };
54
+ stopResolveRetry();
55
+ notify();
56
+ }
57
+ /** Fail-closed UI without permanently locking the session against a later retry. */
58
+ function publishFailClosed() {
59
+ snapshot = {
60
+ initialConsent: STRICTEST_INITIAL_CONSENT,
61
+ isResolved: true
62
+ };
63
+ notify();
64
+ }
65
+ function readSessionCache() {
66
+ if (options.sessionStorageKey === void 0) return;
67
+ try {
68
+ const raw = window.sessionStorage.getItem(options.sessionStorageKey);
69
+ const parsed = raw === null ? void 0 : JSON.parse(raw);
70
+ return isInitialConsent(parsed) ? parsed : void 0;
71
+ } catch {
72
+ return;
73
+ }
74
+ }
75
+ function writeSessionCache(resolved) {
76
+ if (options.sessionStorageKey === void 0) return;
77
+ try {
78
+ window.sessionStorage.setItem(options.sessionStorageKey, JSON.stringify(resolved));
79
+ } catch {}
80
+ }
81
+ function ensureResolved() {
82
+ if (hasResolvedSuccessfully || isFetchInFlight || typeof window === "undefined") return;
83
+ const cached = readSessionCache();
84
+ if (cached) {
85
+ publishResolved(cached);
86
+ return;
87
+ }
88
+ isFetchInFlight = true;
89
+ Promise.resolve().then(() => options.resolve()).then((resolved) => {
90
+ writeSessionCache(resolved);
91
+ publishResolved(resolved);
92
+ }).catch(() => {
93
+ publishFailClosed();
94
+ scheduleResolveRetry();
95
+ }).finally(() => {
96
+ isFetchInFlight = false;
97
+ });
98
+ }
99
+ return {
100
+ ensureResolved,
101
+ getServerSnapshot: () => SERVER_SNAPSHOT,
102
+ getSnapshot: () => snapshot,
103
+ reset() {
104
+ stopResolveRetry();
105
+ snapshot = SERVER_SNAPSHOT;
106
+ isFetchInFlight = false;
107
+ hasResolvedSuccessfully = false;
108
+ if (typeof window !== "undefined" && options.sessionStorageKey !== void 0) window.sessionStorage.removeItem(options.sessionStorageKey);
109
+ },
110
+ subscribe(listener) {
111
+ listeners.add(listener);
112
+ return () => {
113
+ listeners.delete(listener);
114
+ };
115
+ }
116
+ };
117
+ }
118
+ //#endregion
119
+ export { createInitialConsentStore };
@@ -0,0 +1,29 @@
1
+ import { ConsentMode, ConsentStorage } from "../core/consent.mjs";
2
+ import { ConsentConfig } from "../core/consent-config.mjs";
3
+
4
+ //#region src/client/is-analytics-allowed.d.ts
5
+ /**
6
+ * @since 1.0.0-canary.6
7
+ */
8
+ interface IsAnalyticsAllowedOptions {
9
+ /** Must be the same object `useConsent` receives — one config, every surface. */
10
+ config: ConsentConfig;
11
+ /**
12
+ * Re-read each call. Pass `hasGlobalPrivacyControlSignal` from `@codefast/tracking/client`
13
+ * (or a wrapper) so GPC changes apply without recreating the gate.
14
+ */
15
+ hasGlobalPrivacyControlSignal?: (() => boolean) | undefined;
16
+ /** Re-read each call so a post-hydration region resolve can win. */
17
+ getMode: () => ConsentMode;
18
+ /** Must be the same storage instance `useConsent` subscribes to. */
19
+ storage: ConsentStorage;
20
+ }
21
+ /**
22
+ * Non-React mirror of `useConsent`'s `isAnalyticsAllowed` — pass the returned function as
23
+ * `createClientTracker({ isAnalyticsAllowed })` so the pipeline and the banner share one rule.
24
+ *
25
+ * @since 1.0.0-canary.6
26
+ */
27
+ declare function createIsAnalyticsAllowed(options: IsAnalyticsAllowedOptions): () => boolean;
28
+ //#endregion
29
+ export { IsAnalyticsAllowedOptions, createIsAnalyticsAllowed };
@@ -0,0 +1,23 @@
1
+ import { resolveEffectiveConsent } from "../core/consent.mjs";
2
+ //#region src/client/is-analytics-allowed.ts
3
+ /**
4
+ * Non-React mirror of `useConsent`'s `isAnalyticsAllowed` — pass the returned function as
5
+ * `createClientTracker({ isAnalyticsAllowed })` so the pipeline and the banner share one rule.
6
+ *
7
+ * @since 1.0.0-canary.6
8
+ */
9
+ function createIsAnalyticsAllowed(options) {
10
+ const { config, getMode, storage } = options;
11
+ const readGpc = options.hasGlobalPrivacyControlSignal ?? (() => false);
12
+ return () => {
13
+ return resolveEffectiveConsent({
14
+ hasGlobalPrivacyControlSignal: readGpc(),
15
+ mode: getMode(),
16
+ policyVersion: config.policyVersion,
17
+ requestedCategories: config.requestedCategories,
18
+ storage
19
+ }).analytics;
20
+ };
21
+ }
22
+ //#endregion
23
+ export { createIsAnalyticsAllowed };
@@ -0,0 +1,33 @@
1
+ import { CookieAnonymousId } from "./cookie-anonymous-id.mjs";
2
+
3
+ //#region src/client/server-persisted-anonymous-id.d.ts
4
+ /**
5
+ * @since 1.0.0-canary.6
6
+ */
7
+ interface ServerPersistedAnonymousIdOptions {
8
+ /** Server round-trip that expires the cookie via `Set-Cookie` — the server half of `clear()`. */
9
+ clearOnServer?: (() => Promise<void>) | undefined;
10
+ /** Cookie name — must not collide with another cookie on the domain. */
11
+ cookieName: string;
12
+ /** How long the id survives a return visit. Defaults to one year. */
13
+ maxAgeSeconds?: number | undefined;
14
+ /**
15
+ * Server round-trip that re-sets the cookie via `Set-Cookie` (e.g. a server function
16
+ * calling `buildAnonymousIdSetCookie`). Fired at most once per page load, only after an
17
+ * id exists client-side — the server persists and prolongs, it never mints.
18
+ */
19
+ persist: (id: string) => Promise<void>;
20
+ }
21
+ /**
22
+ * `createCookieAnonymousId` plus server persistence: the client still mints the id
23
+ * (lazily, only once an event is allowed to send — consent stays client-owned), then
24
+ * delegates the durable write to the server. A script-written cookie is capped at 7 days
25
+ * by Safari ITP; the server's `Set-Cookie` re-issue is what makes the id actually live
26
+ * its full max-age. Same optimistic `document.cookie` write first, so the current event
27
+ * never waits on the round-trip and a failed `persist` degrades to today's behavior.
28
+ *
29
+ * @since 1.0.0-canary.6
30
+ */
31
+ declare function createServerPersistedAnonymousId(options: ServerPersistedAnonymousIdOptions): CookieAnonymousId;
32
+ //#endregion
33
+ export { ServerPersistedAnonymousIdOptions, createServerPersistedAnonymousId };