@vllnt/analytics 0.2.0-canary.8bb6613 → 0.2.0-canary.bfdedaa

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.
@@ -0,0 +1,289 @@
1
+ import { isDoNotTrackEnabled, loadConsent } from "./consent";
2
+ import type {
3
+ AnalyticsConfig,
4
+ AnalyticsEvent,
5
+ TutorialEventName,
6
+ TutorialEventProperties,
7
+ } from "./types";
8
+
9
+ // Analytics state (singleton)
10
+ type AnalyticsState = {
11
+ app: string;
12
+ debug?: boolean;
13
+ traits?: Record<string, unknown>;
14
+ userId?: string;
15
+ version?: number;
16
+ };
17
+
18
+ let analyticsState: AnalyticsState | undefined;
19
+
20
+ // Queue for events before initialization
21
+ let eventQueue: AnalyticsEvent[] = [];
22
+
23
+ // Track initialization state
24
+ let isInitialized = false;
25
+ let isBlocked = false;
26
+
27
+ /**
28
+ * Reset analytics state (for testing only)
29
+ * @internal
30
+ */
31
+ export function _resetAnalyticsState(): void {
32
+ analyticsState = undefined;
33
+ eventQueue = [];
34
+ isInitialized = false;
35
+ isBlocked = false;
36
+ }
37
+
38
+ /**
39
+ * Block tracking and drop queued events, so nothing recorded before the
40
+ * decision is flushed later.
41
+ */
42
+ function block(): void {
43
+ isBlocked = true;
44
+ eventQueue = [];
45
+ }
46
+
47
+ /**
48
+ * Log event in debug mode
49
+ */
50
+ function debugLog(type: string, data: unknown): void {
51
+ if (analyticsState?.debug) {
52
+ // eslint-disable-next-line no-console -- Debug logging is intentional
53
+ console.log(`[analytics:${type}]`, data);
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Central tracking point. The library has no transport: events are only
59
+ * logged in debug mode and are not sent anywhere.
60
+ */
61
+ function sendEvent(name: string, properties?: Record<string, unknown>): void {
62
+ debugLog("track", { name, properties });
63
+ }
64
+
65
+ /**
66
+ * Start the shared analytics instance and flush queued events. Blocks tracking,
67
+ * and drops the queue, when Do Not Track is on or stored consent declines it.
68
+ * @see https://oss.vllnt.com/packages/analytics
69
+ */
70
+ export function initAnalytics(config: AnalyticsConfig): void {
71
+ if (analyticsState) return;
72
+
73
+ // Check Do Not Track
74
+ if (isDoNotTrackEnabled()) {
75
+ block();
76
+ debugLog("init", "Do Not Track enabled, analytics blocked");
77
+ return;
78
+ }
79
+
80
+ // Check consent
81
+ const consent = loadConsent();
82
+ if (consent && !consent.analytics) {
83
+ block();
84
+ debugLog("init", "Analytics consent declined");
85
+ return;
86
+ }
87
+
88
+ analyticsState = {
89
+ app: config.app,
90
+ debug: config.debug,
91
+ version: config.version,
92
+ };
93
+
94
+ isInitialized = true;
95
+
96
+ debugLog("init", { app: config.app, version: config.version });
97
+
98
+ // Process queued events
99
+ processQueue();
100
+ }
101
+
102
+ /**
103
+ * Process queued events after initialization
104
+ */
105
+ function processQueue(): void {
106
+ if (!analyticsState || isBlocked) return;
107
+
108
+ // Process and clear the queue
109
+ const queue = [...eventQueue];
110
+ eventQueue = [];
111
+
112
+ for (const event of queue) {
113
+ if (event.name === "__page__") {
114
+ debugLog("page", event.properties);
115
+ } else {
116
+ sendEvent(event.name, event.properties);
117
+ }
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Track a custom event. Events with an empty or non-string name are ignored.
123
+ */
124
+ export function track(
125
+ name: string,
126
+ properties?: Record<string, unknown>,
127
+ ): void {
128
+ if (typeof window === "undefined") return;
129
+ if (typeof name !== "string" || name === "") return;
130
+
131
+ if (isBlocked) return;
132
+
133
+ const event: AnalyticsEvent = {
134
+ name,
135
+ properties,
136
+ timestamp: new Date().toISOString(),
137
+ };
138
+
139
+ if (!isInitialized) {
140
+ eventQueue.push(event);
141
+ return;
142
+ }
143
+
144
+ sendEvent(name, properties);
145
+ }
146
+
147
+ /**
148
+ * Track a page view
149
+ */
150
+ export function trackPage(properties?: Record<string, unknown>): void {
151
+ if (typeof window === "undefined") return;
152
+ if (isBlocked) return;
153
+
154
+ if (!isInitialized) {
155
+ eventQueue.push({
156
+ name: "__page__",
157
+ properties,
158
+ timestamp: new Date().toISOString(),
159
+ });
160
+ return;
161
+ }
162
+
163
+ debugLog("page", properties);
164
+ }
165
+
166
+ /**
167
+ * Identify a user. An empty or non-string user id is ignored.
168
+ */
169
+ export function identify(
170
+ userId: string,
171
+ traits?: Record<string, unknown>,
172
+ ): void {
173
+ if (typeof window === "undefined") return;
174
+ if (typeof userId !== "string" || userId === "") return;
175
+ if (isBlocked) return;
176
+
177
+ if (!isInitialized || !analyticsState) {
178
+ return;
179
+ }
180
+
181
+ analyticsState.userId = userId;
182
+ analyticsState.traits = traits;
183
+
184
+ debugLog("identify", { traits, userId });
185
+ }
186
+
187
+ /**
188
+ * Reset analytics state (on logout)
189
+ */
190
+ export function resetAnalytics(): void {
191
+ if (typeof window === "undefined") return;
192
+
193
+ if (analyticsState) {
194
+ analyticsState.userId = undefined;
195
+ analyticsState.traits = undefined;
196
+ }
197
+
198
+ debugLog("reset", undefined);
199
+ }
200
+
201
+ /**
202
+ * Enable analytics after consent is given
203
+ */
204
+ export function enableAnalytics(config: AnalyticsConfig): void {
205
+ if (isBlocked && !isDoNotTrackEnabled()) {
206
+ isBlocked = false;
207
+ analyticsState = undefined;
208
+ initAnalytics(config);
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Disable analytics after consent is revoked.
214
+ * NOTE: Does not clear in-memory userId/traits (GDPR Art. 17 limitation).
215
+ * Callers should trigger a page reload or call resetAnalytics() to purge PII.
216
+ */
217
+ export function disableAnalytics(): void {
218
+ block();
219
+ }
220
+
221
+ /**
222
+ * Check if analytics is currently enabled
223
+ */
224
+ export function isAnalyticsEnabled(): boolean {
225
+ return isInitialized && !isBlocked;
226
+ }
227
+
228
+ /**
229
+ * Get current analytics state (for advanced usage/debugging)
230
+ */
231
+ export function getAnalyticsState(): AnalyticsState | undefined {
232
+ return analyticsState;
233
+ }
234
+
235
+ // Tutorial-specific tracking helpers
236
+
237
+ /**
238
+ * Track tutorial start
239
+ */
240
+ export function trackTutorialStart(
241
+ properties: Omit<TutorialEventProperties, "section_id">,
242
+ ): void {
243
+ track("tutorial_start" satisfies TutorialEventName, properties);
244
+ }
245
+
246
+ /**
247
+ * Track section view
248
+ */
249
+ export function trackSectionView(properties: TutorialEventProperties): void {
250
+ track("tutorial_section_view" satisfies TutorialEventName, properties);
251
+ }
252
+
253
+ /**
254
+ * Track section completion
255
+ */
256
+ export function trackSectionComplete(
257
+ properties: TutorialEventProperties,
258
+ ): void {
259
+ track("tutorial_section_complete" satisfies TutorialEventName, properties);
260
+ }
261
+
262
+ /**
263
+ * Track tutorial completion
264
+ */
265
+ export function trackTutorialComplete(
266
+ properties: Omit<TutorialEventProperties, "section_id">,
267
+ ): void {
268
+ track("tutorial_complete" satisfies TutorialEventName, properties);
269
+ }
270
+
271
+ /**
272
+ * Track navigation between sections
273
+ */
274
+ export function trackTutorialNavigation(
275
+ properties: TutorialEventProperties & {
276
+ navigation_type: "keyboard" | "next" | "prev" | "toc";
277
+ },
278
+ ): void {
279
+ track("tutorial_navigation" satisfies TutorialEventName, properties);
280
+ }
281
+
282
+ /**
283
+ * Track time spent on a section
284
+ */
285
+ export function trackTimeSpent(
286
+ properties: TutorialEventProperties & { time_spent_seconds: number },
287
+ ): void {
288
+ track("tutorial_time_spent" satisfies TutorialEventName, properties);
289
+ }
package/src/consent.ts ADDED
@@ -0,0 +1,179 @@
1
+ import type { ConsentCategory, ConsentState } from "./types";
2
+
3
+ /** Current consent schema version - bump to re-prompt users */
4
+ export const CONSENT_VERSION = 1;
5
+
6
+ /** localStorage key for consent state */
7
+ export const CONSENT_STORAGE_KEY = "vllnt:analytics-consent";
8
+
9
+ /** Cookie name for SSR consent detection */
10
+ export const CONSENT_COOKIE_NAME = "vllnt-consent";
11
+
12
+ /**
13
+ * Type guard to validate consent state from storage
14
+ */
15
+ export function isValidConsentState(value: unknown): value is ConsentState {
16
+ if (typeof value !== "object" || value === null) return false;
17
+
18
+ const state = value as Record<string, unknown>;
19
+
20
+ return (
21
+ typeof state.analytics === "boolean" &&
22
+ typeof state.functional === "boolean" &&
23
+ typeof state.timestamp === "string" &&
24
+ typeof state.version === "number"
25
+ );
26
+ }
27
+
28
+ /**
29
+ * Check if localStorage is available
30
+ */
31
+ export function isStorageAvailable(): boolean {
32
+ if (typeof window === "undefined") return false;
33
+
34
+ try {
35
+ const testKey = "__storage_test__";
36
+ localStorage.setItem(testKey, testKey);
37
+ localStorage.removeItem(testKey);
38
+ return true;
39
+ } catch {
40
+ return false;
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Load consent state from localStorage
46
+ */
47
+ export function loadConsent(): ConsentState | null {
48
+ if (!isStorageAvailable()) return null;
49
+
50
+ try {
51
+ const raw = localStorage.getItem(CONSENT_STORAGE_KEY);
52
+ if (!raw) return null;
53
+
54
+ const parsed: unknown = JSON.parse(raw);
55
+ if (!isValidConsentState(parsed)) return null;
56
+
57
+ return parsed;
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Save consent state to localStorage and cookie
65
+ */
66
+ export function saveConsent(state: ConsentState): void {
67
+ if (!isStorageAvailable()) return;
68
+
69
+ try {
70
+ localStorage.setItem(CONSENT_STORAGE_KEY, JSON.stringify(state));
71
+
72
+ // Also set a cookie for SSR detection (1 year expiry)
73
+ const expires = new Date();
74
+ expires.setFullYear(expires.getFullYear() + 1);
75
+
76
+ // Cookie value: "1" for analytics allowed, "0" for declined
77
+ const cookieValue = state.analytics ? "1" : "0";
78
+ document.cookie = `${CONSENT_COOKIE_NAME}=${cookieValue}; expires=${expires.toUTCString()}; path=/; SameSite=Lax`;
79
+ } catch (error) {
80
+ console.warn("Failed to save consent:", error);
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Clear consent state (for re-prompting)
86
+ */
87
+ export function clearConsent(): void {
88
+ if (!isStorageAvailable()) return;
89
+
90
+ try {
91
+ localStorage.removeItem(CONSENT_STORAGE_KEY);
92
+
93
+ // Clear cookie
94
+ document.cookie = `${CONSENT_COOKIE_NAME}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Lax`;
95
+ } catch {
96
+ // Ignore errors during cleanup
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Create a new consent state with all categories accepted
102
+ */
103
+ export function createAcceptAllConsent(): ConsentState {
104
+ return {
105
+ analytics: true,
106
+ functional: true,
107
+ timestamp: new Date().toISOString(),
108
+ version: CONSENT_VERSION,
109
+ };
110
+ }
111
+
112
+ /**
113
+ * Create a consent state with analytics declined
114
+ */
115
+ export function createDeclineAnalyticsConsent(): ConsentState {
116
+ return {
117
+ analytics: false,
118
+ functional: true, // Functional always enabled
119
+ timestamp: new Date().toISOString(),
120
+ version: CONSENT_VERSION,
121
+ };
122
+ }
123
+
124
+ /**
125
+ * Update a specific consent category
126
+ */
127
+ export function updateConsentCategory(
128
+ current: ConsentState,
129
+ category: ConsentCategory,
130
+ value: boolean,
131
+ ): ConsentState {
132
+ // Functional cookies cannot be disabled
133
+ if (category === "functional" && !value) {
134
+ return current;
135
+ }
136
+
137
+ return {
138
+ ...current,
139
+ [category]: value,
140
+ timestamp: new Date().toISOString(),
141
+ };
142
+ }
143
+
144
+ /**
145
+ * Check if consent needs to be re-prompted (version mismatch)
146
+ */
147
+ export function needsRePrompt(
148
+ consent: ConsentState,
149
+ currentVersion: number,
150
+ ): boolean {
151
+ return consent.version < currentVersion;
152
+ }
153
+
154
+ /**
155
+ * Check Do Not Track browser setting
156
+ */
157
+ export function isDoNotTrackEnabled(): boolean {
158
+ if (typeof window === "undefined") return false;
159
+
160
+ const dnt =
161
+ navigator.doNotTrack ||
162
+ (window as unknown as { doNotTrack?: string }).doNotTrack ||
163
+ (navigator as unknown as { msDoNotTrack?: string }).msDoNotTrack;
164
+
165
+ return dnt === "1" || dnt === "yes";
166
+ }
167
+
168
+ /**
169
+ * Get consent from cookie (for SSR)
170
+ */
171
+ export function getConsentFromCookie(cookieString: string): boolean | null {
172
+ // Anchor to the start of the string or a cookie separator so that
173
+ // look-alike names such as "evil-vllnt-consent" are not matched.
174
+ const match = new RegExp(`(?:^|;\\s*)${CONSENT_COOKIE_NAME}=([^;]+)`).exec(
175
+ cookieString,
176
+ );
177
+ if (!match) return null;
178
+ return match[1] === "1";
179
+ }
package/src/index.ts ADDED
@@ -0,0 +1,48 @@
1
+ // Core analytics
2
+ export {
3
+ disableAnalytics,
4
+ enableAnalytics,
5
+ getAnalyticsState,
6
+ identify,
7
+ initAnalytics,
8
+ isAnalyticsEnabled,
9
+ resetAnalytics,
10
+ track,
11
+ trackPage,
12
+ trackSectionComplete,
13
+ trackSectionView,
14
+ trackTimeSpent,
15
+ trackTutorialComplete,
16
+ trackTutorialNavigation,
17
+ trackTutorialStart,
18
+ } from "./analytics";
19
+
20
+ // Consent management
21
+ export {
22
+ clearConsent,
23
+ CONSENT_COOKIE_NAME,
24
+ CONSENT_STORAGE_KEY,
25
+ CONSENT_VERSION,
26
+ createAcceptAllConsent,
27
+ createDeclineAnalyticsConsent,
28
+ getConsentFromCookie,
29
+ isDoNotTrackEnabled,
30
+ isStorageAvailable,
31
+ isValidConsentState,
32
+ loadConsent,
33
+ needsRePrompt,
34
+ saveConsent,
35
+ updateConsentCategory,
36
+ } from "./consent";
37
+
38
+ // Types
39
+ export type {
40
+ AnalyticsConfig,
41
+ AnalyticsEvent,
42
+ ConsentCategory,
43
+ ConsentState,
44
+ TutorialEventName,
45
+ TutorialEventProperties,
46
+ UseConsentOptions,
47
+ UseConsentReturn,
48
+ } from "./types";