@vllnt/analytics 0.1.1 → 0.2.0-canary.0cf6be9

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/package.json CHANGED
@@ -1,66 +1,102 @@
1
1
  {
2
2
  "name": "@vllnt/analytics",
3
- "version": "0.1.1",
4
- "description": "Lightweight, privacy-first analytics with consent management and React integration",
3
+ "version": "0.2.0-canary.0cf6be9",
4
+ "description": "Cookie consent state and consent-gated event tracking for React and TypeScript, with Do Not Track and an SSR consent cookie.",
5
5
  "type": "module",
6
+ "packageManager": "pnpm@12.22.0",
6
7
  "license": "MIT",
8
+ "author": {
9
+ "name": "bntvllnt",
10
+ "url": "https://bntvllnt.com"
11
+ },
12
+ "funding": {
13
+ "type": "github",
14
+ "url": "https://github.com/sponsors/bntvllnt"
15
+ },
7
16
  "repository": {
8
17
  "type": "git",
9
18
  "url": "git+https://github.com/vllnt/analytics.git"
10
19
  },
20
+ "homepage": "https://oss.vllnt.com/packages/analytics",
21
+ "bugs": {
22
+ "url": "https://github.com/vllnt/analytics/issues"
23
+ },
11
24
  "keywords": [
12
25
  "analytics",
13
- "consent",
14
- "privacy",
26
+ "event-tracking",
27
+ "cookie-consent",
28
+ "consent-management",
15
29
  "gdpr",
30
+ "do-not-track",
31
+ "privacy",
16
32
  "react",
17
- "do-not-track"
33
+ "react-hooks",
34
+ "ssr",
35
+ "typescript"
18
36
  ],
19
37
  "sideEffects": false,
20
38
  "files": [
39
+ "dist",
21
40
  "src",
22
41
  "!src/__tests__",
23
- "README.md",
24
- "LICENSE"
42
+ "docs/API.md",
43
+ "CHANGELOG.md",
44
+ "llms.txt"
25
45
  ],
26
- "main": "./src/index.ts",
27
- "module": "./src/index.ts",
28
- "types": "./src/index.ts",
46
+ "main": "./dist/index.cjs",
47
+ "module": "./dist/index.js",
48
+ "types": "./dist/index.d.ts",
29
49
  "exports": {
30
50
  ".": {
31
- "types": "./src/index.ts",
32
- "import": "./src/index.ts",
33
- "require": "./src/index.ts"
51
+ "import": {
52
+ "types": "./dist/index.d.ts",
53
+ "default": "./dist/index.js"
54
+ },
55
+ "require": {
56
+ "types": "./dist/index.d.cts",
57
+ "default": "./dist/index.cjs"
58
+ }
34
59
  },
35
60
  "./react": {
36
- "types": "./src/react.tsx",
37
- "import": "./src/react.tsx",
38
- "require": "./src/react.tsx"
39
- }
61
+ "import": {
62
+ "types": "./dist/react.d.ts",
63
+ "default": "./dist/react.js"
64
+ },
65
+ "require": {
66
+ "types": "./dist/react.d.cts",
67
+ "default": "./dist/react.cjs"
68
+ }
69
+ },
70
+ "./package.json": "./package.json"
71
+ },
72
+ "scripts": {
73
+ "build": "tsup",
74
+ "clean": "rm -rf node_modules dist",
75
+ "lint": "eslint --cache --cache-location node_modules/.cache/eslint/ .",
76
+ "lint:fix": "eslint --cache --cache-location node_modules/.cache/eslint/ . --fix",
77
+ "test": "vitest",
78
+ "test:once": "vitest run",
79
+ "test:coverage": "vitest run --coverage",
80
+ "test:package": "bash scripts/test-package.sh",
81
+ "typecheck": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/tsc/typecheck.tsbuildinfo",
82
+ "typecheck:ci": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/tsc/typecheck-ci.tsbuildinfo"
40
83
  },
41
84
  "peerDependencies": {
42
85
  "react": "^18.0.0 || ^19.0.0"
43
86
  },
44
87
  "devDependencies": {
45
- "eslint": "^9.39.1",
46
- "@testing-library/jest-dom": "^6.9.1",
47
- "@testing-library/react": "^16.3.0",
48
- "@types/node": "^22",
49
- "@types/react": "^19.1.6",
50
- "@vitest/coverage-v8": "^4.0.16",
51
- "@vllnt/eslint-config": "^1.0.0",
52
- "@vllnt/typescript": "^1.0.0",
53
- "jsdom": "^26.1.0",
54
- "react": "^19.2.0",
55
- "typescript": "^5.9.3",
56
- "vitest": "^4.0.16"
57
- },
58
- "scripts": {
59
- "clean": "rm -rf node_modules",
60
- "lint": "eslint .",
61
- "lint:fix": "eslint . --fix",
62
- "test": "vitest",
63
- "test:once": "vitest run",
64
- "test:coverage": "vitest run --coverage"
88
+ "@testing-library/jest-dom": "^8.0.0",
89
+ "@testing-library/react": "^16.3.3",
90
+ "@types/node": "^24.19.2",
91
+ "@types/react": "^19.3.0",
92
+ "@vitest/coverage-v8": "^5.1.1",
93
+ "@vllnt/eslint-config": "^2.1.0",
94
+ "@vllnt/typescript": "^3.0.0",
95
+ "eslint": "^9.39.5",
96
+ "jsdom": "^31.0.1",
97
+ "react": "^19.3.1",
98
+ "tsup": "^9.0.0",
99
+ "typescript": "^6.0.3",
100
+ "vitest": "^5.1.1"
65
101
  }
66
- }
102
+ }
package/src/analytics.ts CHANGED
@@ -1,6 +1,3 @@
1
- // Lightweight custom analytics implementation
2
- // Replaces external 'analytics' package with minimal implementation
3
-
4
1
  import { isDoNotTrackEnabled, loadConsent } from "./consent";
5
2
  import type {
6
3
  AnalyticsConfig,
@@ -20,8 +17,15 @@ type AnalyticsState = {
20
17
 
21
18
  let analyticsState: AnalyticsState | undefined;
22
19
 
20
+ /**
21
+ * Default `maxQueuedEvents`: how many `track` and `trackPage` calls are kept
22
+ * in memory before `initAnalytics` runs.
23
+ */
24
+ export const DEFAULT_MAX_QUEUED_EVENTS = 100;
25
+
23
26
  // Queue for events before initialization
24
27
  let eventQueue: AnalyticsEvent[] = [];
28
+ let maxQueuedEvents = DEFAULT_MAX_QUEUED_EVENTS;
25
29
 
26
30
  // Track initialization state
27
31
  let isInitialized = false;
@@ -34,10 +38,40 @@ let isBlocked = false;
34
38
  export function _resetAnalyticsState(): void {
35
39
  analyticsState = undefined;
36
40
  eventQueue = [];
41
+ maxQueuedEvents = DEFAULT_MAX_QUEUED_EVENTS;
37
42
  isInitialized = false;
38
43
  isBlocked = false;
39
44
  }
40
45
 
46
+ /**
47
+ * Set the pre-init queue limit and keep only the first `limit` queued events.
48
+ * A value that is not a non-negative safe integer means the default.
49
+ * @internal
50
+ */
51
+ export function setMaxQueuedEvents(limit: number | undefined): void {
52
+ maxQueuedEvents =
53
+ typeof limit === "number" && Number.isSafeInteger(limit) && limit >= 0
54
+ ? limit
55
+ : DEFAULT_MAX_QUEUED_EVENTS;
56
+ eventQueue = eventQueue.slice(0, maxQueuedEvents);
57
+ }
58
+
59
+ /**
60
+ * Queue an event before init; calls past the limit are dropped.
61
+ */
62
+ function enqueue(event: AnalyticsEvent): void {
63
+ if (eventQueue.length < maxQueuedEvents) eventQueue.push(event);
64
+ }
65
+
66
+ /**
67
+ * Block tracking and drop queued events, so nothing recorded before the
68
+ * decision is flushed later.
69
+ */
70
+ function block(): void {
71
+ isBlocked = true;
72
+ eventQueue = [];
73
+ }
74
+
41
75
  /**
42
76
  * Log event in debug mode
43
77
  */
@@ -49,29 +83,26 @@ function debugLog(type: string, data: unknown): void {
49
83
  }
50
84
 
51
85
  /**
52
- * Send event to analytics endpoint or external service
53
- * This is where you'd integrate with Vercel Analytics, GA, etc.
86
+ * Central tracking point. The library has no transport: events are only
87
+ * logged in debug mode and are not sent anywhere.
54
88
  */
55
89
  function sendEvent(name: string, properties?: Record<string, unknown>): void {
56
90
  debugLog("track", { name, properties });
57
-
58
- // Integration point: Forward to Vercel Analytics or other services
59
- // Vercel Analytics integration is handled by the React provider
60
- // This function serves as the central tracking point
61
-
62
- // For custom backends, you could send to an API endpoint:
63
- // fetch('/api/analytics', { method: 'POST', body: JSON.stringify({ name, properties }) })
64
91
  }
65
92
 
66
93
  /**
67
- * Initialize analytics with configuration
94
+ * Start the shared analytics instance and flush queued events. Blocks tracking,
95
+ * and drops the queue, when Do Not Track is on or stored consent declines it.
96
+ * @see https://oss.vllnt.com/packages/analytics
68
97
  */
69
98
  export function initAnalytics(config: AnalyticsConfig): void {
70
99
  if (analyticsState) return;
71
100
 
101
+ setMaxQueuedEvents(config.maxQueuedEvents);
102
+
72
103
  // Check Do Not Track
73
104
  if (isDoNotTrackEnabled()) {
74
- isBlocked = true;
105
+ block();
75
106
  debugLog("init", "Do Not Track enabled, analytics blocked");
76
107
  return;
77
108
  }
@@ -79,7 +110,7 @@ export function initAnalytics(config: AnalyticsConfig): void {
79
110
  // Check consent
80
111
  const consent = loadConsent();
81
112
  if (consent && !consent.analytics) {
82
- isBlocked = true;
113
+ block();
83
114
  debugLog("init", "Analytics consent declined");
84
115
  return;
85
116
  }
@@ -118,13 +149,16 @@ function processQueue(): void {
118
149
  }
119
150
 
120
151
  /**
121
- * Track a custom event
152
+ * Track a custom event. Events with an empty or non-string name are ignored.
153
+ * Before init, only the first `maxQueuedEvents` calls (shared with
154
+ * `trackPage`) are queued.
122
155
  */
123
156
  export function track(
124
157
  name: string,
125
158
  properties?: Record<string, unknown>,
126
159
  ): void {
127
160
  if (typeof window === "undefined") return;
161
+ if (typeof name !== "string" || name === "") return;
128
162
 
129
163
  if (isBlocked) return;
130
164
 
@@ -135,7 +169,7 @@ export function track(
135
169
  };
136
170
 
137
171
  if (!isInitialized) {
138
- eventQueue.push(event);
172
+ enqueue(event);
139
173
  return;
140
174
  }
141
175
 
@@ -143,14 +177,15 @@ export function track(
143
177
  }
144
178
 
145
179
  /**
146
- * Track a page view
180
+ * Track a page view. Before init, it shares the `maxQueuedEvents` limit with
181
+ * `track`.
147
182
  */
148
183
  export function trackPage(properties?: Record<string, unknown>): void {
149
184
  if (typeof window === "undefined") return;
150
185
  if (isBlocked) return;
151
186
 
152
187
  if (!isInitialized) {
153
- eventQueue.push({
188
+ enqueue({
154
189
  name: "__page__",
155
190
  properties,
156
191
  timestamp: new Date().toISOString(),
@@ -162,13 +197,14 @@ export function trackPage(properties?: Record<string, unknown>): void {
162
197
  }
163
198
 
164
199
  /**
165
- * Identify a user
200
+ * Identify a user. An empty or non-string user id is ignored.
166
201
  */
167
202
  export function identify(
168
203
  userId: string,
169
204
  traits?: Record<string, unknown>,
170
205
  ): void {
171
206
  if (typeof window === "undefined") return;
207
+ if (typeof userId !== "string" || userId === "") return;
172
208
  if (isBlocked) return;
173
209
 
174
210
  if (!isInitialized || !analyticsState) {
@@ -212,8 +248,7 @@ export function enableAnalytics(config: AnalyticsConfig): void {
212
248
  * Callers should trigger a page reload or call resetAnalytics() to purge PII.
213
249
  */
214
250
  export function disableAnalytics(): void {
215
- isBlocked = true;
216
- eventQueue.length = 0; // Clear queue
251
+ block();
217
252
  }
218
253
 
219
254
  /**
@@ -238,20 +273,14 @@ export function getAnalyticsState(): AnalyticsState | undefined {
238
273
  export function trackTutorialStart(
239
274
  properties: Omit<TutorialEventProperties, "section_id">,
240
275
  ): void {
241
- track(
242
- "tutorial_start" satisfies TutorialEventName,
243
- properties as Record<string, unknown>,
244
- );
276
+ track("tutorial_start" satisfies TutorialEventName, properties);
245
277
  }
246
278
 
247
279
  /**
248
280
  * Track section view
249
281
  */
250
282
  export function trackSectionView(properties: TutorialEventProperties): void {
251
- track(
252
- "tutorial_section_view" satisfies TutorialEventName,
253
- properties as Record<string, unknown>,
254
- );
283
+ track("tutorial_section_view" satisfies TutorialEventName, properties);
255
284
  }
256
285
 
257
286
  /**
@@ -260,10 +289,7 @@ export function trackSectionView(properties: TutorialEventProperties): void {
260
289
  export function trackSectionComplete(
261
290
  properties: TutorialEventProperties,
262
291
  ): void {
263
- track(
264
- "tutorial_section_complete" satisfies TutorialEventName,
265
- properties as Record<string, unknown>,
266
- );
292
+ track("tutorial_section_complete" satisfies TutorialEventName, properties);
267
293
  }
268
294
 
269
295
  /**
@@ -272,10 +298,7 @@ export function trackSectionComplete(
272
298
  export function trackTutorialComplete(
273
299
  properties: Omit<TutorialEventProperties, "section_id">,
274
300
  ): void {
275
- track(
276
- "tutorial_complete" satisfies TutorialEventName,
277
- properties as Record<string, unknown>,
278
- );
301
+ track("tutorial_complete" satisfies TutorialEventName, properties);
279
302
  }
280
303
 
281
304
  /**
@@ -286,10 +309,7 @@ export function trackTutorialNavigation(
286
309
  navigation_type: "keyboard" | "next" | "prev" | "toc";
287
310
  },
288
311
  ): void {
289
- track(
290
- "tutorial_navigation" satisfies TutorialEventName,
291
- properties as Record<string, unknown>,
292
- );
312
+ track("tutorial_navigation" satisfies TutorialEventName, properties);
293
313
  }
294
314
 
295
315
  /**
@@ -298,8 +318,5 @@ export function trackTutorialNavigation(
298
318
  export function trackTimeSpent(
299
319
  properties: TutorialEventProperties & { time_spent_seconds: number },
300
320
  ): void {
301
- track(
302
- "tutorial_time_spent" satisfies TutorialEventName,
303
- properties as Record<string, unknown>,
304
- );
321
+ track("tutorial_time_spent" satisfies TutorialEventName, properties);
305
322
  }
package/src/consent.ts CHANGED
@@ -169,7 +169,11 @@ export function isDoNotTrackEnabled(): boolean {
169
169
  * Get consent from cookie (for SSR)
170
170
  */
171
171
  export function getConsentFromCookie(cookieString: string): boolean | null {
172
- const match = new RegExp(`${CONSENT_COOKIE_NAME}=([^;]+)`).exec(cookieString);
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
+ );
173
177
  if (!match) return null;
174
178
  return match[1] === "1";
175
179
  }
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  // Core analytics
2
2
  export {
3
+ DEFAULT_MAX_QUEUED_EVENTS,
3
4
  disableAnalytics,
4
5
  enableAnalytics,
5
6
  getAnalyticsState,
package/src/react.tsx CHANGED
@@ -10,7 +10,12 @@ import {
10
10
  useState,
11
11
  } from "react";
12
12
 
13
- import { disableAnalytics, enableAnalytics, initAnalytics } from "./analytics";
13
+ import {
14
+ disableAnalytics,
15
+ enableAnalytics,
16
+ initAnalytics,
17
+ setMaxQueuedEvents,
18
+ } from "./analytics";
14
19
  import {
15
20
  clearConsent,
16
21
  CONSENT_VERSION,
@@ -56,6 +61,9 @@ export function AnalyticsProvider({
56
61
  consentVersion?: number;
57
62
  }) {
58
63
  const [consent, setConsent] = useState<ConsentState | null>(() => {
64
+ // Runs once, during the first render: the limit is set before any child
65
+ // effect can queue an event and before the consent decision.
66
+ setMaxQueuedEvents(config.maxQueuedEvents);
59
67
  const stored = loadConsent();
60
68
  if (!stored) return null;
61
69
  if (needsRePrompt(stored, consentVersion)) {
@@ -67,28 +75,35 @@ export function AnalyticsProvider({
67
75
 
68
76
  const [hasResponded, setHasResponded] = useState(() => consent !== null);
69
77
 
70
- // Initialize analytics if stored consent allows
78
+ // Start analytics when consent allows it; block it (and drop queued
79
+ // events) when the stored choice is a decline.
71
80
  useEffect(() => {
72
- if (consent?.analytics) {
81
+ if (!consent) return;
82
+ if (consent.analytics) {
73
83
  initAnalytics(config);
84
+ } else {
85
+ disableAnalytics();
74
86
  }
75
87
  }, [consent, config]);
76
88
 
77
89
  const acceptAll = useCallback(() => {
78
- const newConsent = createAcceptAllConsent();
90
+ const newConsent = { ...createAcceptAllConsent(), version: consentVersion };
79
91
  saveConsent(newConsent);
80
92
  setConsent(newConsent);
81
93
  setHasResponded(true);
82
94
  enableAnalytics(config);
83
- }, [config]);
95
+ }, [config, consentVersion]);
84
96
 
85
97
  const declineAnalytics = useCallback(() => {
86
- const newConsent = createDeclineAnalyticsConsent();
98
+ const newConsent = {
99
+ ...createDeclineAnalyticsConsent(),
100
+ version: consentVersion,
101
+ };
87
102
  saveConsent(newConsent);
88
103
  setConsent(newConsent);
89
104
  setHasResponded(true);
90
105
  disableAnalytics();
91
- }, []);
106
+ }, [consentVersion]);
92
107
 
93
108
  const updateConsentHandler = useCallback(
94
109
  (category: ConsentCategory, value: boolean) => {
@@ -176,18 +191,21 @@ export function useConsent(options: UseConsentOptions = {}): UseConsentReturn {
176
191
  const [hasResponded, setHasResponded] = useState(() => consent !== null);
177
192
 
178
193
  const acceptAll = useCallback(() => {
179
- const newConsent = createAcceptAllConsent();
194
+ const newConsent = { ...createAcceptAllConsent(), version: consentVersion };
180
195
  saveConsent(newConsent);
181
196
  setConsent(newConsent);
182
197
  setHasResponded(true);
183
- }, []);
198
+ }, [consentVersion]);
184
199
 
185
200
  const declineAnalytics = useCallback(() => {
186
- const newConsent = createDeclineAnalyticsConsent();
201
+ const newConsent = {
202
+ ...createDeclineAnalyticsConsent(),
203
+ version: consentVersion,
204
+ };
187
205
  saveConsent(newConsent);
188
206
  setConsent(newConsent);
189
207
  setHasResponded(true);
190
- }, []);
208
+ }, [consentVersion]);
191
209
 
192
210
  const updateConsentHandler = useCallback(
193
211
  (category: ConsentCategory, value: boolean) => {
package/src/types.ts CHANGED
@@ -69,6 +69,14 @@ export type AnalyticsConfig = {
69
69
  app: string;
70
70
  /** Enable debug mode */
71
71
  debug?: boolean;
72
+ /**
73
+ * How many `track` and `trackPage` calls are queued before `initAnalytics`
74
+ * runs; later calls are dropped. `0` queues nothing. Defaults to
75
+ * `DEFAULT_MAX_QUEUED_EVENTS` (100); any value that is not a non-negative
76
+ * safe integer means the default. `AnalyticsProvider` applies it on mount;
77
+ * without the provider, the default applies until `initAnalytics` runs.
78
+ */
79
+ maxQueuedEvents?: number;
72
80
  /** Application version */
73
81
  version?: number;
74
82
  };