@vllnt/analytics 0.1.1 → 0.2.0-canary.6a57f79

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/llms.txt ADDED
@@ -0,0 +1,74 @@
1
+ # @vllnt/analytics
2
+
3
+ > Cookie consent state and consent-gated event tracking for React and TypeScript, with Do Not Track and an SSR consent cookie.
4
+
5
+ Facts for AI tools. The library has no transport: it queues and gates events, and only
6
+ `console.log`s them when `debug: true`. Events never leave the page.
7
+
8
+ ## For coding agents
9
+
10
+ The docs are bundled in the package at `node_modules/@vllnt/analytics/docs/`, with this file,
11
+ `CHANGELOG.md` and the TypeScript sources in `src/`. They match the installed version. Read them
12
+ before writing code.
13
+
14
+ ## When to use
15
+
16
+ - Use it when a React app needs cookie-banner state stored in `localStorage` and a cookie.
17
+ - Use it when tracking calls must wait for consent and stop on Do Not Track or a decline.
18
+ - Use it when server code must read the visitor's choice from the `Cookie` header.
19
+ - Do not use it when events must reach a backend: it sends nothing; use your analytics vendor's SDK.
20
+ - Do not use it for a server-side consent record: use `@vllnt/convex-consent`.
21
+
22
+ ## Package
23
+
24
+ - npm: `@vllnt/analytics` (MIT), repo: https://github.com/vllnt/analytics
25
+ - Unreleased builds from `main` use the `canary` dist-tag
26
+ - Ships ESM, CommonJS and type declarations from `dist` (built with tsup); both builds of
27
+ `./react` start with `"use client"`
28
+ - Entry points: `@vllnt/analytics` (core + consent + types), `@vllnt/analytics/react` (`AnalyticsProvider`, `useAnalytics`, `useConsent`, `initAnalytics`)
29
+ - Peer dependency: React `^18.0.0 || ^19.0.0`
30
+ - Install: `pnpm add @vllnt/analytics`
31
+
32
+ ## Behaviour
33
+
34
+ - Events tracked before `initAnalytics()` are queued and flushed on the first unblocked init;
35
+ a blocked init drops them. The queue has no size limit.
36
+ - `initAnalytics()` blocks tracking when Do Not Track is on (`"1"` or `"yes"`) or stored consent
37
+ has `analytics: false`. With no stored consent it starts tracking. `AnalyticsProvider` calls it
38
+ while consent has `analytics: true` and calls `disableAnalytics()` after a stored decline, so a
39
+ declined visitor's events are dropped. Before the user responds, events are queued in memory,
40
+ except after `resetConsent()`, which blocks and drops events until the user responds again.
41
+ - Once blocked, only `enableAnalytics(config)` unblocks; it re-reads stored consent.
42
+ - Consent is stored in `localStorage` (`vllnt:analytics-consent`) and a `vllnt-consent` cookie
43
+ (`1` or `0`) for SSR; `getConsentFromCookie(cookieString)` reads it with an anchored match.
44
+ - Consent is versioned; a stored version below the hook's `consentVersion` (default
45
+ `CONSENT_VERSION`) re-prompts once, and the hooks save the new choice with that version.
46
+ - `track()` ignores empty or non-string names; `identify()` ignores empty or non-string ids.
47
+ - Browser APIs are guarded, so server-side import is safe. `initAnalytics()` has no server
48
+ guard and starts the process-wide instance there, so call it only in the browser.
49
+ - The only thrown error is `useAnalytics must be used within an AnalyticsProvider`; there are no
50
+ error codes.
51
+
52
+ ## Docs
53
+
54
+ - [API reference](./docs/API.md): every public export, signatures, examples, entry points
55
+ - [Errors and fixes](./README.md#errors-and-fixes): every message the package throws or logs
56
+ - [Limits and gotchas](./README.md#limits-and-gotchas): defaults and calls that do nothing
57
+ - [README](./README.md): usage, common tasks, compatibility
58
+ - [Changelog](./CHANGELOG.md): release history
59
+ - [Core exports](./src/index.ts) and [React exports](./src/react.tsx): source of the public API
60
+
61
+ ## Optional
62
+
63
+ - [Contributing](https://github.com/vllnt/analytics/blob/main/CONTRIBUTING.md): setup, checks, release flow
64
+ - [Security policy](https://github.com/vllnt/analytics/blob/main/SECURITY.md): private vulnerability reporting
65
+ - [AGENTS.md](https://github.com/vllnt/analytics/blob/main/AGENTS.md): instructions for contributing agents
66
+
67
+ ## Ecosystem
68
+
69
+ - [Package page](https://oss.vllnt.com/packages/analytics)
70
+ - [Release feed](https://oss.vllnt.com/packages/analytics/rss.xml)
71
+ - [All @vllnt packages](https://oss.vllnt.com/llms.txt)
72
+ - [Search vllnt packages and docs](https://index.vllnt.com)
73
+ - [vllnt](https://vllnt.com/llms.txt)
74
+ - [Author](https://bntvllnt.com)
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.6a57f79",
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,
@@ -38,6 +35,15 @@ export function _resetAnalyticsState(): void {
38
35
  isBlocked = false;
39
36
  }
40
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
+
41
47
  /**
42
48
  * Log event in debug mode
43
49
  */
@@ -49,29 +55,24 @@ function debugLog(type: string, data: unknown): void {
49
55
  }
50
56
 
51
57
  /**
52
- * Send event to analytics endpoint or external service
53
- * This is where you'd integrate with Vercel Analytics, GA, etc.
58
+ * Central tracking point. The library has no transport: events are only
59
+ * logged in debug mode and are not sent anywhere.
54
60
  */
55
61
  function sendEvent(name: string, properties?: Record<string, unknown>): void {
56
62
  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
63
  }
65
64
 
66
65
  /**
67
- * Initialize analytics with configuration
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
68
69
  */
69
70
  export function initAnalytics(config: AnalyticsConfig): void {
70
71
  if (analyticsState) return;
71
72
 
72
73
  // Check Do Not Track
73
74
  if (isDoNotTrackEnabled()) {
74
- isBlocked = true;
75
+ block();
75
76
  debugLog("init", "Do Not Track enabled, analytics blocked");
76
77
  return;
77
78
  }
@@ -79,7 +80,7 @@ export function initAnalytics(config: AnalyticsConfig): void {
79
80
  // Check consent
80
81
  const consent = loadConsent();
81
82
  if (consent && !consent.analytics) {
82
- isBlocked = true;
83
+ block();
83
84
  debugLog("init", "Analytics consent declined");
84
85
  return;
85
86
  }
@@ -118,13 +119,14 @@ function processQueue(): void {
118
119
  }
119
120
 
120
121
  /**
121
- * Track a custom event
122
+ * Track a custom event. Events with an empty or non-string name are ignored.
122
123
  */
123
124
  export function track(
124
125
  name: string,
125
126
  properties?: Record<string, unknown>,
126
127
  ): void {
127
128
  if (typeof window === "undefined") return;
129
+ if (typeof name !== "string" || name === "") return;
128
130
 
129
131
  if (isBlocked) return;
130
132
 
@@ -162,13 +164,14 @@ export function trackPage(properties?: Record<string, unknown>): void {
162
164
  }
163
165
 
164
166
  /**
165
- * Identify a user
167
+ * Identify a user. An empty or non-string user id is ignored.
166
168
  */
167
169
  export function identify(
168
170
  userId: string,
169
171
  traits?: Record<string, unknown>,
170
172
  ): void {
171
173
  if (typeof window === "undefined") return;
174
+ if (typeof userId !== "string" || userId === "") return;
172
175
  if (isBlocked) return;
173
176
 
174
177
  if (!isInitialized || !analyticsState) {
@@ -212,8 +215,7 @@ export function enableAnalytics(config: AnalyticsConfig): void {
212
215
  * Callers should trigger a page reload or call resetAnalytics() to purge PII.
213
216
  */
214
217
  export function disableAnalytics(): void {
215
- isBlocked = true;
216
- eventQueue.length = 0; // Clear queue
218
+ block();
217
219
  }
218
220
 
219
221
  /**
@@ -238,20 +240,14 @@ export function getAnalyticsState(): AnalyticsState | undefined {
238
240
  export function trackTutorialStart(
239
241
  properties: Omit<TutorialEventProperties, "section_id">,
240
242
  ): void {
241
- track(
242
- "tutorial_start" satisfies TutorialEventName,
243
- properties as Record<string, unknown>,
244
- );
243
+ track("tutorial_start" satisfies TutorialEventName, properties);
245
244
  }
246
245
 
247
246
  /**
248
247
  * Track section view
249
248
  */
250
249
  export function trackSectionView(properties: TutorialEventProperties): void {
251
- track(
252
- "tutorial_section_view" satisfies TutorialEventName,
253
- properties as Record<string, unknown>,
254
- );
250
+ track("tutorial_section_view" satisfies TutorialEventName, properties);
255
251
  }
256
252
 
257
253
  /**
@@ -260,10 +256,7 @@ export function trackSectionView(properties: TutorialEventProperties): void {
260
256
  export function trackSectionComplete(
261
257
  properties: TutorialEventProperties,
262
258
  ): void {
263
- track(
264
- "tutorial_section_complete" satisfies TutorialEventName,
265
- properties as Record<string, unknown>,
266
- );
259
+ track("tutorial_section_complete" satisfies TutorialEventName, properties);
267
260
  }
268
261
 
269
262
  /**
@@ -272,10 +265,7 @@ export function trackSectionComplete(
272
265
  export function trackTutorialComplete(
273
266
  properties: Omit<TutorialEventProperties, "section_id">,
274
267
  ): void {
275
- track(
276
- "tutorial_complete" satisfies TutorialEventName,
277
- properties as Record<string, unknown>,
278
- );
268
+ track("tutorial_complete" satisfies TutorialEventName, properties);
279
269
  }
280
270
 
281
271
  /**
@@ -286,10 +276,7 @@ export function trackTutorialNavigation(
286
276
  navigation_type: "keyboard" | "next" | "prev" | "toc";
287
277
  },
288
278
  ): void {
289
- track(
290
- "tutorial_navigation" satisfies TutorialEventName,
291
- properties as Record<string, unknown>,
292
- );
279
+ track("tutorial_navigation" satisfies TutorialEventName, properties);
293
280
  }
294
281
 
295
282
  /**
@@ -298,8 +285,5 @@ export function trackTutorialNavigation(
298
285
  export function trackTimeSpent(
299
286
  properties: TutorialEventProperties & { time_spent_seconds: number },
300
287
  ): void {
301
- track(
302
- "tutorial_time_spent" satisfies TutorialEventName,
303
- properties as Record<string, unknown>,
304
- );
288
+ track("tutorial_time_spent" satisfies TutorialEventName, properties);
305
289
  }
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/react.tsx CHANGED
@@ -67,28 +67,35 @@ export function AnalyticsProvider({
67
67
 
68
68
  const [hasResponded, setHasResponded] = useState(() => consent !== null);
69
69
 
70
- // Initialize analytics if stored consent allows
70
+ // Start analytics when consent allows it; block it (and drop queued
71
+ // events) when the stored choice is a decline.
71
72
  useEffect(() => {
72
- if (consent?.analytics) {
73
+ if (!consent) return;
74
+ if (consent.analytics) {
73
75
  initAnalytics(config);
76
+ } else {
77
+ disableAnalytics();
74
78
  }
75
79
  }, [consent, config]);
76
80
 
77
81
  const acceptAll = useCallback(() => {
78
- const newConsent = createAcceptAllConsent();
82
+ const newConsent = { ...createAcceptAllConsent(), version: consentVersion };
79
83
  saveConsent(newConsent);
80
84
  setConsent(newConsent);
81
85
  setHasResponded(true);
82
86
  enableAnalytics(config);
83
- }, [config]);
87
+ }, [config, consentVersion]);
84
88
 
85
89
  const declineAnalytics = useCallback(() => {
86
- const newConsent = createDeclineAnalyticsConsent();
90
+ const newConsent = {
91
+ ...createDeclineAnalyticsConsent(),
92
+ version: consentVersion,
93
+ };
87
94
  saveConsent(newConsent);
88
95
  setConsent(newConsent);
89
96
  setHasResponded(true);
90
97
  disableAnalytics();
91
- }, []);
98
+ }, [consentVersion]);
92
99
 
93
100
  const updateConsentHandler = useCallback(
94
101
  (category: ConsentCategory, value: boolean) => {
@@ -176,18 +183,21 @@ export function useConsent(options: UseConsentOptions = {}): UseConsentReturn {
176
183
  const [hasResponded, setHasResponded] = useState(() => consent !== null);
177
184
 
178
185
  const acceptAll = useCallback(() => {
179
- const newConsent = createAcceptAllConsent();
186
+ const newConsent = { ...createAcceptAllConsent(), version: consentVersion };
180
187
  saveConsent(newConsent);
181
188
  setConsent(newConsent);
182
189
  setHasResponded(true);
183
- }, []);
190
+ }, [consentVersion]);
184
191
 
185
192
  const declineAnalytics = useCallback(() => {
186
- const newConsent = createDeclineAnalyticsConsent();
193
+ const newConsent = {
194
+ ...createDeclineAnalyticsConsent(),
195
+ version: consentVersion,
196
+ };
187
197
  saveConsent(newConsent);
188
198
  setConsent(newConsent);
189
199
  setHasResponded(true);
190
- }, []);
200
+ }, [consentVersion]);
191
201
 
192
202
  const updateConsentHandler = useCallback(
193
203
  (category: ConsentCategory, value: boolean) => {