@codefast/tracking 0.0.0 → 0.5.0-canary.5
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.
- package/CHANGELOG.md +44 -0
- package/README.md +79 -9
- package/dist/client/consent-storage.d.mts +11 -3
- package/dist/client/consent-storage.mjs +45 -9
- package/dist/client/create-client-tracker.d.mts +10 -0
- package/dist/client/create-client-tracker.mjs +14 -1
- package/dist/client/gpc.d.mts +2 -0
- package/dist/client/gpc.mjs +2 -0
- package/dist/client/lifecycle.d.mts +5 -0
- package/dist/client/lifecycle.mjs +2 -0
- package/dist/client/local-storage.d.mts +5 -2
- package/dist/client/local-storage.mjs +12 -5
- package/dist/client/queue.d.mts +7 -0
- package/dist/client/queue.mjs +2 -0
- package/dist/client/router.d.mts +4 -0
- package/dist/client/router.mjs +2 -0
- package/dist/core/consent.d.mts +61 -9
- package/dist/core/consent.mjs +39 -7
- package/dist/core/destination.d.mts +10 -0
- package/dist/core/event-catalog.d.mts +8 -0
- package/dist/core/event-catalog.mjs +2 -0
- package/dist/core/event-id.d.mts +2 -0
- package/dist/core/event-id.mjs +2 -0
- package/dist/core/index.d.mts +2 -2
- package/dist/core/index.mjs +2 -2
- package/dist/core/tracked-event.d.mts +2 -0
- package/dist/destinations/ga4-measurement-protocol.d.mts +54 -0
- package/dist/destinations/ga4-measurement-protocol.mjs +89 -0
- package/dist/destinations/google-analytics.d.mts +98 -0
- package/dist/destinations/google-analytics.mjs +126 -0
- package/dist/destinations/http-destination.d.mts +5 -0
- package/dist/destinations/http-destination.mjs +2 -0
- package/dist/destinations/index.d.mts +3 -1
- package/dist/destinations/index.mjs +3 -1
- package/dist/destinations/vercel-analytics.d.mts +4 -2
- package/dist/destinations/vercel-analytics.mjs +5 -2
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +2 -2
- package/dist/react/consent-banner.d.mts +140 -18
- package/dist/react/consent-banner.mjs +195 -28
- package/dist/react/index.d.mts +2 -2
- package/dist/react/index.mjs +2 -2
- package/dist/react/use-consent.d.mts +30 -5
- package/dist/react/use-consent.mjs +38 -15
- package/dist/server/create-server-tracker.d.mts +14 -0
- package/dist/server/create-server-tracker.mjs +24 -5
- package/dist/server/region.d.mts +4 -0
- package/dist/server/region.mjs +4 -0
- package/package.json +13 -2
- package/src/client/consent-storage.ts +75 -10
- package/src/client/create-client-tracker.ts +30 -1
- package/src/client/gpc.ts +2 -0
- package/src/client/lifecycle.ts +5 -0
- package/src/client/local-storage.ts +21 -6
- package/src/client/queue.ts +7 -0
- package/src/client/router.ts +4 -0
- package/src/core/consent.ts +85 -11
- package/src/core/destination.ts +10 -0
- package/src/core/event-catalog.ts +8 -0
- package/src/core/event-id.ts +2 -0
- package/src/core/index.ts +15 -2
- package/src/core/tracked-event.ts +2 -0
- package/src/css/consent.css +119 -0
- package/src/destinations/ga4-measurement-protocol.ts +166 -0
- package/src/destinations/google-analytics.ts +233 -0
- package/src/destinations/http-destination.ts +5 -0
- package/src/destinations/index.ts +16 -0
- package/src/destinations/vercel-analytics.ts +5 -2
- package/src/react/consent-banner.tsx +301 -31
- package/src/react/index.ts +26 -2
- package/src/react/use-consent.ts +81 -23
- package/src/server/create-server-tracker.ts +39 -16
- package/src/server/region.ts +4 -0
package/dist/server/region.mjs
CHANGED
|
@@ -32,6 +32,8 @@ const EU_COUNTRY_CODES = /* @__PURE__ */ new Set([
|
|
|
32
32
|
* Missing/unrecognized codes fall back to "other", which `resolveConsentMode` treats
|
|
33
33
|
* as opt-out — the least restrictive default, safe only because opt-in regions (EU/VN)
|
|
34
34
|
* are matched explicitly above it.
|
|
35
|
+
*
|
|
36
|
+
* @since 0.5.0-canary.4
|
|
35
37
|
*/
|
|
36
38
|
function resolveRegionFromCountryCode(countryCode) {
|
|
37
39
|
if (!countryCode) return "other";
|
|
@@ -44,6 +46,8 @@ function resolveRegionFromCountryCode(countryCode) {
|
|
|
44
46
|
/**
|
|
45
47
|
* Reads the hosting platform's geo header (e.g. Vercel's `x-vercel-ip-country`) — pass
|
|
46
48
|
* the incoming request's `Headers` from server-function/middleware context.
|
|
49
|
+
*
|
|
50
|
+
* @since 0.5.0-canary.4
|
|
47
51
|
*/
|
|
48
52
|
function resolveRegion(headers, headerName = "x-vercel-ip-country") {
|
|
49
53
|
return resolveRegionFromCountryCode(headers.get(headerName) ?? void 0);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@codefast/tracking",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.5.0-canary.5",
|
|
4
4
|
"description": "Fullstack, type-safe event tracking for TanStack Start — isomorphic client/server trackers over a per-app Zod event catalog",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"analytics",
|
|
@@ -131,6 +131,16 @@
|
|
|
131
131
|
"types": "./dist/destinations/index.d.mts",
|
|
132
132
|
"import": "./dist/destinations/index.mjs"
|
|
133
133
|
},
|
|
134
|
+
"./destinations/ga4-measurement-protocol": {
|
|
135
|
+
"source": "./src/destinations/ga4-measurement-protocol.ts",
|
|
136
|
+
"types": "./dist/destinations/ga4-measurement-protocol.d.mts",
|
|
137
|
+
"import": "./dist/destinations/ga4-measurement-protocol.mjs"
|
|
138
|
+
},
|
|
139
|
+
"./destinations/google-analytics": {
|
|
140
|
+
"source": "./src/destinations/google-analytics.ts",
|
|
141
|
+
"types": "./dist/destinations/google-analytics.d.mts",
|
|
142
|
+
"import": "./dist/destinations/google-analytics.mjs"
|
|
143
|
+
},
|
|
134
144
|
"./destinations/http-destination": {
|
|
135
145
|
"source": "./src/destinations/http-destination.ts",
|
|
136
146
|
"types": "./dist/destinations/http-destination.d.mts",
|
|
@@ -171,6 +181,7 @@
|
|
|
171
181
|
"types": "./dist/server/region.d.mts",
|
|
172
182
|
"import": "./dist/server/region.mjs"
|
|
173
183
|
},
|
|
184
|
+
"./css/*": "./src/css/*",
|
|
174
185
|
"./package.json": "./package.json"
|
|
175
186
|
},
|
|
176
187
|
"publishConfig": {
|
|
@@ -198,7 +209,7 @@
|
|
|
198
209
|
"tsdown": "^0.22.3",
|
|
199
210
|
"typescript": "^6.0.3",
|
|
200
211
|
"vitest": "^4.1.9",
|
|
201
|
-
"@codefast/typescript-config": "0.5.0-canary.
|
|
212
|
+
"@codefast/typescript-config": "0.5.0-canary.5"
|
|
202
213
|
},
|
|
203
214
|
"peerDependencies": {
|
|
204
215
|
"@types/react": ">=19.0.0",
|
|
@@ -1,30 +1,95 @@
|
|
|
1
1
|
import type { ConsentRecord, ConsentStorage } from "#/core/consent";
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
* `localStorage`-backed consent storage
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* `localStorage`-backed consent storage. Corrupt state, a private-mode/quota error, or no
|
|
5
|
+
* `window` (SSR) degrades to an in-memory record — the visitor's decision still applies
|
|
6
|
+
* for the session instead of re-prompting in a loop. `subscribe` fires for same-tab
|
|
7
|
+
* writes and, via the `storage` event, for decisions made in other tabs.
|
|
8
|
+
*
|
|
9
|
+
* @remarks
|
|
10
|
+
* The record persists as plain `JSON.stringify(ConsentRecord)` — a stable contract, so
|
|
11
|
+
* pre-hydration inline scripts (e.g. a Consent Mode default bootstrap) can read the
|
|
12
|
+
* decision synchronously before any tag fires.
|
|
13
|
+
*
|
|
14
|
+
* @since 0.5.0-canary.4
|
|
7
15
|
*/
|
|
8
16
|
export function createLocalStorageConsentStorage(storageKey: string): ConsentStorage {
|
|
17
|
+
const listeners = new Set<() => void>();
|
|
18
|
+
let memoryRecord: ConsentRecord | undefined;
|
|
19
|
+
|
|
20
|
+
function notify(): void {
|
|
21
|
+
for (const listener of listeners) {
|
|
22
|
+
listener();
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
9
26
|
return {
|
|
10
27
|
clear(): void {
|
|
11
|
-
|
|
28
|
+
if (typeof globalThis.window === "undefined") {
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
memoryRecord = undefined;
|
|
33
|
+
|
|
34
|
+
try {
|
|
35
|
+
globalThis.window.localStorage.removeItem(storageKey);
|
|
36
|
+
} catch {
|
|
37
|
+
/* storage blocked (private mode / quota) */
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
notify();
|
|
12
41
|
},
|
|
13
42
|
load(): ConsentRecord | undefined {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
if (!raw) {
|
|
43
|
+
if (typeof globalThis.window === "undefined") {
|
|
17
44
|
return undefined;
|
|
18
45
|
}
|
|
19
46
|
|
|
20
47
|
try {
|
|
21
|
-
|
|
48
|
+
const raw = globalThis.window.localStorage.getItem(storageKey);
|
|
49
|
+
|
|
50
|
+
return raw ? (JSON.parse(raw) as ConsentRecord) : memoryRecord;
|
|
22
51
|
} catch {
|
|
23
|
-
return
|
|
52
|
+
return memoryRecord;
|
|
24
53
|
}
|
|
25
54
|
},
|
|
26
55
|
save(record: ConsentRecord): void {
|
|
27
|
-
|
|
56
|
+
if (typeof globalThis.window === "undefined") {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
try {
|
|
61
|
+
globalThis.window.localStorage.setItem(storageKey, JSON.stringify(record));
|
|
62
|
+
// localStorage is authoritative now — a lingering memory copy would shadow an
|
|
63
|
+
// external clear (e.g. the visitor wiping site data).
|
|
64
|
+
memoryRecord = undefined;
|
|
65
|
+
} catch {
|
|
66
|
+
// Storage blocked (private mode / quota) — keep the decision for this session.
|
|
67
|
+
memoryRecord = record;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
notify();
|
|
71
|
+
},
|
|
72
|
+
subscribe(listener: () => void): () => void {
|
|
73
|
+
listeners.add(listener);
|
|
74
|
+
|
|
75
|
+
// The `storage` event only fires in *other* tabs; same-tab writes go through notify().
|
|
76
|
+
function handleStorageEvent(event: StorageEvent): void {
|
|
77
|
+
if (event.key === null || event.key === storageKey) {
|
|
78
|
+
listener();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (typeof globalThis.window !== "undefined") {
|
|
83
|
+
globalThis.window.addEventListener("storage", handleStorageEvent);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return () => {
|
|
87
|
+
listeners.delete(listener);
|
|
88
|
+
|
|
89
|
+
if (typeof globalThis.window !== "undefined") {
|
|
90
|
+
globalThis.window.removeEventListener("storage", handleStorageEvent);
|
|
91
|
+
}
|
|
92
|
+
};
|
|
28
93
|
},
|
|
29
94
|
};
|
|
30
95
|
}
|
|
@@ -6,6 +6,9 @@ import type { EventCatalog, EventsOf } 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
|
+
* @since 0.5.0-canary.4
|
|
11
|
+
*/
|
|
9
12
|
export interface ClientTrackerOptions<Catalog extends EventCatalog> {
|
|
10
13
|
anonymousId: string;
|
|
11
14
|
catalog: Catalog;
|
|
@@ -15,12 +18,16 @@ export interface ClientTrackerOptions<Catalog extends EventCatalog> {
|
|
|
15
18
|
storage: EventQueueStorage;
|
|
16
19
|
}
|
|
17
20
|
|
|
21
|
+
/**
|
|
22
|
+
* @since 0.5.0-canary.4
|
|
23
|
+
*/
|
|
18
24
|
export interface ClientTracker<Catalog extends EventCatalog> {
|
|
19
25
|
/** Drops every pending event without sending it — call this when consent is revoked. */
|
|
20
26
|
clear: () => void;
|
|
21
27
|
flush: () => Promise<void>;
|
|
22
28
|
/** Synchronous, best-effort flush via `navigator.sendBeacon` — for page unload only. */
|
|
23
29
|
flushWithBeacon: (endpoint: string) => void;
|
|
30
|
+
group: (groupId: string, traits?: Record<string, unknown>) => void;
|
|
24
31
|
identify: (userId: string, traits?: Record<string, unknown>) => void;
|
|
25
32
|
page: (name?: string, props?: Record<string, unknown>) => void;
|
|
26
33
|
track: <Name extends keyof EventsOf<Catalog, "client">>(
|
|
@@ -29,11 +36,18 @@ export interface ClientTracker<Catalog extends EventCatalog> {
|
|
|
29
36
|
) => void;
|
|
30
37
|
}
|
|
31
38
|
|
|
39
|
+
/**
|
|
40
|
+
* @since 0.5.0-canary.4
|
|
41
|
+
*/
|
|
32
42
|
export function createClientTracker<Catalog extends EventCatalog>(
|
|
33
43
|
options: ClientTrackerOptions<Catalog>,
|
|
34
44
|
): 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");
|
|
35
49
|
const queue = new EventQueue({
|
|
36
|
-
destinations:
|
|
50
|
+
destinations: queuedDestinations,
|
|
37
51
|
maxQueueSize: options.maxQueueSize,
|
|
38
52
|
maxRetries: options.maxRetries,
|
|
39
53
|
storage: options.storage,
|
|
@@ -51,6 +65,18 @@ export function createClientTracker<Catalog extends EventCatalog>(
|
|
|
51
65
|
...(userId === undefined ? {} : { userId }),
|
|
52
66
|
};
|
|
53
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 */
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Still enqueued unconditionally — the queue also feeds `flushWithBeacon`, which
|
|
79
|
+
// ships raw envelopes to a custom endpoint independently of any destination.
|
|
54
80
|
queue.enqueue(envelope);
|
|
55
81
|
}
|
|
56
82
|
|
|
@@ -74,6 +100,9 @@ export function createClientTracker<Catalog extends EventCatalog>(
|
|
|
74
100
|
}
|
|
75
101
|
}
|
|
76
102
|
},
|
|
103
|
+
group(groupId, traits = {}) {
|
|
104
|
+
enqueue("$group", { groupId, ...traits });
|
|
105
|
+
},
|
|
77
106
|
identify(id, traits = {}) {
|
|
78
107
|
userId = id;
|
|
79
108
|
enqueue("$identify", traits);
|
package/src/client/gpc.ts
CHANGED
|
@@ -5,6 +5,8 @@ interface NavigatorWithGpc extends Navigator {
|
|
|
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
|
+
*
|
|
9
|
+
* @since 0.5.0-canary.4
|
|
8
10
|
*/
|
|
9
11
|
export function hasGlobalPrivacyControlSignal(): boolean {
|
|
10
12
|
return (navigator as NavigatorWithGpc).globalPrivacyControl === true;
|
package/src/client/lifecycle.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import type { ClientTracker } from "#/client/create-client-tracker";
|
|
2
2
|
import type { EventCatalog } from "#/core/event-catalog";
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* @since 0.5.0-canary.4
|
|
6
|
+
*/
|
|
4
7
|
export interface ClientLifecycleOptions {
|
|
5
8
|
/** `sendBeacon` target used on unload — omit to skip the unload flush entirely. */
|
|
6
9
|
beaconEndpoint?: string;
|
|
@@ -12,6 +15,8 @@ export interface ClientLifecycleOptions {
|
|
|
12
15
|
* `EventQueue`): a periodic interval flush, and a best-effort `sendBeacon` flush on
|
|
13
16
|
* unload — `fetch` isn't reliable once the page starts unloading, `sendBeacon` is.
|
|
14
17
|
* Returns a cleanup function to remove all listeners/timers.
|
|
18
|
+
*
|
|
19
|
+
* @since 0.5.0-canary.4
|
|
15
20
|
*/
|
|
16
21
|
export function attachClientLifecycle<Catalog extends EventCatalog>(
|
|
17
22
|
tracker: Pick<ClientTracker<Catalog>, "flush" | "flushWithBeacon">,
|
|
@@ -2,19 +2,26 @@ import type { EventQueueStorage } from "#/client/queue";
|
|
|
2
2
|
import type { TrackedEvent } from "#/core/tracked-event";
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* `localStorage`-backed queue storage — corrupt/missing state
|
|
6
|
-
*
|
|
5
|
+
* `localStorage`-backed queue storage — corrupt/missing state, a private-mode/quota
|
|
6
|
+
* error, or no `window` (SSR) are all treated as empty rather than thrown, since a lost
|
|
7
|
+
* offline queue is preferable to a crashing app.
|
|
8
|
+
*
|
|
9
|
+
* @since 0.5.0-canary.4
|
|
7
10
|
*/
|
|
8
11
|
export function createLocalStorageQueueStorage(storageKey: string): EventQueueStorage {
|
|
9
12
|
return {
|
|
10
13
|
load(): Array<TrackedEvent> {
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
if (!raw) {
|
|
14
|
+
if (typeof globalThis.window === "undefined") {
|
|
14
15
|
return [];
|
|
15
16
|
}
|
|
16
17
|
|
|
17
18
|
try {
|
|
19
|
+
const raw = globalThis.window.localStorage.getItem(storageKey);
|
|
20
|
+
|
|
21
|
+
if (!raw) {
|
|
22
|
+
return [];
|
|
23
|
+
}
|
|
24
|
+
|
|
18
25
|
const parsed: unknown = JSON.parse(raw);
|
|
19
26
|
|
|
20
27
|
return Array.isArray(parsed) ? (parsed as Array<TrackedEvent>) : [];
|
|
@@ -23,7 +30,15 @@ export function createLocalStorageQueueStorage(storageKey: string): EventQueueSt
|
|
|
23
30
|
}
|
|
24
31
|
},
|
|
25
32
|
save(events: Array<TrackedEvent>): void {
|
|
26
|
-
|
|
33
|
+
if (typeof globalThis.window === "undefined") {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
try {
|
|
38
|
+
globalThis.window.localStorage.setItem(storageKey, JSON.stringify(events));
|
|
39
|
+
} catch {
|
|
40
|
+
/* storage blocked (private mode / quota) */
|
|
41
|
+
}
|
|
27
42
|
},
|
|
28
43
|
};
|
|
29
44
|
}
|
package/src/client/queue.ts
CHANGED
|
@@ -4,12 +4,17 @@ import type { TrackedEvent } from "#/core/tracked-event";
|
|
|
4
4
|
/**
|
|
5
5
|
* Persistence backend for the offline queue — a thin wrapper so tests and non-browser
|
|
6
6
|
* environments can swap in an in-memory implementation instead of real `localStorage`.
|
|
7
|
+
*
|
|
8
|
+
* @since 0.5.0-canary.4
|
|
7
9
|
*/
|
|
8
10
|
export interface EventQueueStorage {
|
|
9
11
|
load: () => Array<TrackedEvent>;
|
|
10
12
|
save: (events: Array<TrackedEvent>) => void;
|
|
11
13
|
}
|
|
12
14
|
|
|
15
|
+
/**
|
|
16
|
+
* @since 0.5.0-canary.4
|
|
17
|
+
*/
|
|
13
18
|
export interface EventQueueOptions {
|
|
14
19
|
destinations: Array<Destination>;
|
|
15
20
|
flushBatchSize?: number | undefined;
|
|
@@ -26,6 +31,8 @@ interface QueuedEvent {
|
|
|
26
31
|
/**
|
|
27
32
|
* Client-side batching/offline queue: persists across reloads, caps its size
|
|
28
33
|
* (drop-oldest), and retries a failed batch up to `maxRetries` times.
|
|
34
|
+
*
|
|
35
|
+
* @since 0.5.0-canary.4
|
|
29
36
|
*/
|
|
30
37
|
export class EventQueue {
|
|
31
38
|
private readonly destinations: Array<Destination>;
|
package/src/client/router.ts
CHANGED
|
@@ -11,6 +11,8 @@ interface ResolvedNavigation {
|
|
|
11
11
|
/**
|
|
12
12
|
* Structurally matches `Router["subscribe"]` from `@tanstack/router-core` for the
|
|
13
13
|
* `"onResolved"` event — duck-typed so this package doesn't depend on TanStack Router.
|
|
14
|
+
*
|
|
15
|
+
* @since 0.5.0-canary.4
|
|
14
16
|
*/
|
|
15
17
|
export interface RouterLike {
|
|
16
18
|
subscribe: (eventType: "onResolved", fn: (event: ResolvedNavigation) => void) => () => void;
|
|
@@ -21,6 +23,8 @@ export interface RouterLike {
|
|
|
21
23
|
* `popstate` only fires for browser back/forward. Page views are low-frequency, so this
|
|
22
24
|
* flushes right away instead of waiting on the batch queue's interval/size threshold —
|
|
23
25
|
* a slow navigation shouldn't leave a pageview stranded if the tab closes right after.
|
|
26
|
+
*
|
|
27
|
+
* @since 0.5.0-canary.4
|
|
24
28
|
*/
|
|
25
29
|
export function attachRouterPageTracking<Catalog extends EventCatalog>(
|
|
26
30
|
tracker: Pick<ClientTracker<Catalog>, "flush" | "page">,
|
package/src/core/consent.ts
CHANGED
|
@@ -1,11 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @since 0.5.0-canary.4
|
|
3
|
+
*/
|
|
1
4
|
export type ConsentRegion = "eu" | "other" | "us" | "vn";
|
|
2
5
|
|
|
6
|
+
/**
|
|
7
|
+
* @since 0.5.0-canary.4
|
|
8
|
+
*/
|
|
3
9
|
export type ConsentMode = "opt-in" | "opt-out";
|
|
4
10
|
|
|
5
11
|
/**
|
|
6
12
|
* GDPR (EU) and Nghị định 13/2023 (VN) require explicit opt-in before any non-essential
|
|
7
13
|
* tracking; CCPA/CPRA (US) defaults to opt-out instead. There is no single global default
|
|
8
14
|
* that satisfies both, so the mode is resolved per region.
|
|
15
|
+
*
|
|
16
|
+
* @since 0.5.0-canary.4
|
|
9
17
|
*/
|
|
10
18
|
export function resolveConsentMode(region: ConsentRegion): ConsentMode {
|
|
11
19
|
switch (region) {
|
|
@@ -22,24 +30,83 @@ export function resolveConsentMode(region: ConsentRegion): ConsentMode {
|
|
|
22
30
|
}
|
|
23
31
|
|
|
24
32
|
/**
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
33
|
+
* Consent purposes, mirroring Google Consent Mode v2's split: `analytics` gates
|
|
34
|
+
* measurement (`analytics_storage`), `ads` gates advertising storage and data sharing
|
|
35
|
+
* (`ad_storage`/`ad_user_data`/`ad_personalization`).
|
|
36
|
+
*
|
|
37
|
+
* @since 0.5.0-canary.4
|
|
38
|
+
*/
|
|
39
|
+
export type ConsentCategory = "ads" | "analytics";
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* @since 0.5.0-canary.4
|
|
43
|
+
*/
|
|
44
|
+
export const CONSENT_CATEGORIES: ReadonlyArray<ConsentCategory> = ["ads", "analytics"];
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Per-category consent — GDPR consent must be granular per purpose, so a single
|
|
48
|
+
* granted/denied flag can't represent it. `true` means the visitor granted that purpose.
|
|
49
|
+
*
|
|
50
|
+
* @since 0.5.0-canary.4
|
|
51
|
+
*/
|
|
52
|
+
export type ConsentDecision = Record<ConsentCategory, boolean>;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* A decision granting exactly the given categories and denying every other one.
|
|
56
|
+
*
|
|
57
|
+
* @since 0.5.0-canary.4
|
|
28
58
|
*/
|
|
29
|
-
export function
|
|
59
|
+
export function createConsentDecision(grantedCategories: ReadonlyArray<ConsentCategory>): ConsentDecision {
|
|
60
|
+
return { ads: grantedCategories.includes("ads"), analytics: grantedCategories.includes("analytics") };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Guards stored JSON — the record is tamperable, so every category must be an explicit boolean.
|
|
65
|
+
*
|
|
66
|
+
* @since 0.5.0-canary.4
|
|
67
|
+
*/
|
|
68
|
+
export function isConsentDecision(value: unknown): value is ConsentDecision {
|
|
69
|
+
return (
|
|
70
|
+
typeof value === "object" &&
|
|
71
|
+
value !== null &&
|
|
72
|
+
CONSENT_CATEGORIES.every((category) => typeof (value as Record<string, unknown>)[category] === "boolean")
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The effective consent before the visitor decides: opt-in regions start all-denied,
|
|
78
|
+
* opt-out regions grant the categories the app asks for.
|
|
79
|
+
*
|
|
80
|
+
* @remarks
|
|
81
|
+
* A Global Privacy Control signal is a "do not sell or share" opt-out (CCPA/CPRA), so it
|
|
82
|
+
* forces `ads` denied — it does not withdraw first-party analytics measurement.
|
|
83
|
+
*
|
|
84
|
+
* @since 0.5.0-canary.4
|
|
85
|
+
*/
|
|
86
|
+
export function resolveDefaultConsent(
|
|
87
|
+
mode: ConsentMode,
|
|
88
|
+
requestedCategories: ReadonlyArray<ConsentCategory>,
|
|
89
|
+
hasGlobalPrivacyControlSignal: boolean,
|
|
90
|
+
): ConsentDecision {
|
|
30
91
|
if (mode === "opt-in") {
|
|
31
|
-
return
|
|
92
|
+
return createConsentDecision([]);
|
|
32
93
|
}
|
|
33
94
|
|
|
34
|
-
|
|
35
|
-
}
|
|
95
|
+
const decision = createConsentDecision(requestedCategories);
|
|
36
96
|
|
|
37
|
-
|
|
97
|
+
if (hasGlobalPrivacyControlSignal) {
|
|
98
|
+
decision.ads = false;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return decision;
|
|
102
|
+
}
|
|
38
103
|
|
|
39
104
|
/**
|
|
40
105
|
* NĐ 13/2023 and GDPR both expect a record of *when* and *under what policy* consent
|
|
41
|
-
* was given, not just
|
|
106
|
+
* was given, not just per-category flags — `policyVersion` lets a later policy change
|
|
42
107
|
* invalidate stale consent.
|
|
108
|
+
*
|
|
109
|
+
* @since 0.5.0-canary.4
|
|
43
110
|
*/
|
|
44
111
|
export interface ConsentRecord {
|
|
45
112
|
decision: ConsentDecision;
|
|
@@ -48,11 +115,18 @@ export interface ConsentRecord {
|
|
|
48
115
|
}
|
|
49
116
|
|
|
50
117
|
/**
|
|
51
|
-
* Persistence backend for the visitor's consent decision —
|
|
52
|
-
*
|
|
118
|
+
* Persistence backend for the visitor's consent decision — swap in your own
|
|
119
|
+
* implementation for non-browser environments or a different persistence layer.
|
|
120
|
+
*
|
|
121
|
+
* @since 0.5.0-canary.4
|
|
53
122
|
*/
|
|
54
123
|
export interface ConsentStorage {
|
|
55
124
|
clear: () => void;
|
|
56
125
|
load: () => ConsentRecord | undefined;
|
|
57
126
|
save: (record: ConsentRecord) => void;
|
|
127
|
+
/**
|
|
128
|
+
* Notify on any change to the stored record, including writes from other tabs — this
|
|
129
|
+
* is what drives `useConsent`'s external-store subscription. Returns an unsubscribe.
|
|
130
|
+
*/
|
|
131
|
+
subscribe: (listener: () => void) => () => void;
|
|
58
132
|
}
|
package/src/core/destination.ts
CHANGED
|
@@ -3,8 +3,18 @@ import type { TrackedEvent } from "#/core/tracked-event";
|
|
|
3
3
|
/**
|
|
4
4
|
* Fan-out target for tracked events (PostHog, GA4, a self-hosted store, ...).
|
|
5
5
|
* Trackers depend only on this interface, never on a specific provider SDK.
|
|
6
|
+
*
|
|
7
|
+
* @since 0.5.0-canary.4
|
|
6
8
|
*/
|
|
7
9
|
export interface Destination {
|
|
10
|
+
/**
|
|
11
|
+
* "immediate" for SDK-backed destinations that own their transport (gtag.js, Vercel's
|
|
12
|
+
* in-page queue) — the client tracker calls `send` at track time and never queues,
|
|
13
|
+
* persists, or retries for them.
|
|
14
|
+
*
|
|
15
|
+
* @defaultValue "queued"
|
|
16
|
+
*/
|
|
17
|
+
delivery?: "immediate" | "queued";
|
|
8
18
|
name: string;
|
|
9
19
|
send: (event: TrackedEvent) => Promise<void> | void;
|
|
10
20
|
}
|
|
@@ -2,6 +2,8 @@ import type { z } from "zod";
|
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* One event's Zod schema plus which side of the app is allowed to fire it.
|
|
5
|
+
*
|
|
6
|
+
* @since 0.5.0-canary.4
|
|
5
7
|
*/
|
|
6
8
|
export interface EventDefinition<Schema extends z.ZodType = z.ZodType> {
|
|
7
9
|
owner: "client" | "server";
|
|
@@ -11,6 +13,8 @@ export 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
|
export type EventCatalog = Record<string, EventDefinition>;
|
|
16
20
|
|
|
@@ -18,6 +22,8 @@ export type EventCatalog = Record<string, EventDefinition>;
|
|
|
18
22
|
* Filters a catalog down to the events a given owner may fire. Client and server
|
|
19
23
|
* trackers are built from this, so calling a server-owned event from client code
|
|
20
24
|
* (or vice versa) is a compile-time error, not a runtime surprise.
|
|
25
|
+
*
|
|
26
|
+
* @since 0.5.0-canary.4
|
|
21
27
|
*/
|
|
22
28
|
export type EventsOf<Catalog extends EventCatalog, Owner extends "client" | "server"> = {
|
|
23
29
|
[Key in keyof Catalog as Catalog[Key]["owner"] extends Owner ? Key : never]: Catalog[Key];
|
|
@@ -26,6 +32,8 @@ export type EventsOf<Catalog extends EventCatalog, Owner extends "client" | "ser
|
|
|
26
32
|
/**
|
|
27
33
|
* Identity helper for declaring a catalog with inference — nicer call-site than
|
|
28
34
|
* `satisfies EventCatalog` when the catalog is assembled across multiple files.
|
|
35
|
+
*
|
|
36
|
+
* @since 0.5.0-canary.4
|
|
29
37
|
*/
|
|
30
38
|
export function defineEventCatalog<Catalog extends EventCatalog>(catalog: Catalog): Catalog {
|
|
31
39
|
return catalog;
|
package/src/core/event-id.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Client-owned events use this at enqueue time; server-owned events derive an ID
|
|
3
3
|
* from the request instead so retries of the same request don't double-count.
|
|
4
|
+
*
|
|
5
|
+
* @since 0.5.0-canary.4
|
|
4
6
|
*/
|
|
5
7
|
export function generateEventId(): string {
|
|
6
8
|
return crypto.randomUUID();
|
package/src/core/index.ts
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
|
-
export type {
|
|
2
|
-
|
|
1
|
+
export type {
|
|
2
|
+
ConsentCategory,
|
|
3
|
+
ConsentDecision,
|
|
4
|
+
ConsentMode,
|
|
5
|
+
ConsentRecord,
|
|
6
|
+
ConsentRegion,
|
|
7
|
+
ConsentStorage,
|
|
8
|
+
} from "#/core/consent";
|
|
9
|
+
export {
|
|
10
|
+
CONSENT_CATEGORIES,
|
|
11
|
+
createConsentDecision,
|
|
12
|
+
isConsentDecision,
|
|
13
|
+
resolveConsentMode,
|
|
14
|
+
resolveDefaultConsent,
|
|
15
|
+
} from "#/core/consent";
|
|
3
16
|
|
|
4
17
|
export type { Destination } from "#/core/destination";
|
|
5
18
|
|