@vllnt/analytics 0.2.0-canary.9bbc838 → 0.2.0-canary.d796133

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 CHANGED
@@ -24,17 +24,18 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
24
24
  ignores an empty or non-string user id, instead of recording them.
25
25
  - **Breaking:** after a stored decline, `AnalyticsProvider` now blocks tracking with
26
26
  `disableAnalytics()`, so `track()` calls are dropped. Before, they were queued in memory without
27
- limit and sent if the user accepted later.
27
+ limit and flushed if the user accepted later.
28
28
  - **Breaking:** when `initAnalytics()` is blocked by Do Not Track or a stored decline, it drops the
29
- events queued before it, as `disableAnalytics()` does. Before, they were kept and sent by a
29
+ events queued before it, as `disableAnalytics()` does. Before, they were kept and flushed by a
30
30
  later successful `enableAnalytics()` (after the user accepted, or Do Not Track was turned off).
31
31
 
32
32
  ### Fixed
33
33
 
34
34
  - `getConsentFromCookie()` no longer matches look-alike cookie names that merely end with
35
35
  `vllnt-consent` (for example `evil-vllnt-consent=1`).
36
- - `AnalyticsProvider` and `useConsent` save each choice with their `consentVersion`. Before, they
37
- always saved version `1`, so a `consentVersion` above `1` asked the user again on every visit.
36
+ - In `AnalyticsProvider` and `useConsent`, `acceptAll` and `declineAnalytics` save the choice with
37
+ their `consentVersion`; `updateConsent` keeps the stored version. Before, they always saved
38
+ version `1`, so a `consentVersion` above `1` asked the user again on every visit.
38
39
 
39
40
  ### Security
40
41
 
package/README.md CHANGED
@@ -1,15 +1,19 @@
1
1
  # @vllnt/analytics
2
2
 
3
- Lightweight, privacy-first analytics library with consent management and React integration.
3
+ Cookie consent state and consent-gated event tracking for React and TypeScript, with Do Not Track and an SSR consent cookie.
4
4
 
5
- ## Features
5
+ ## For coding agents
6
+
7
+ Version-matched docs ship in the package: [`docs/API.md`](docs/API.md), [`llms.txt`](llms.txt),
8
+ `CHANGELOG.md` and the TypeScript sources in `src/`. Read them before writing code.
9
+
10
+ ## When to use
6
11
 
7
- - **Event tracking** with pre-init queuing (no lost events during hydration)
8
- - **Consent management** — two categories (analytics + functional), localStorage + SSR cookie
9
- - **Versioned consent** — bump version to re-prompt users
10
- - **Do Not Track** — respects browser DNT setting
11
- - **SSR-safe** — all browser APIs guarded
12
- - **Zero external analytics dependencies** — bring your own backend (Vercel Analytics, GA, custom)
12
+ - Use it when a React app needs cookie-banner state stored in `localStorage` and a cookie.
13
+ - Use it when tracking calls must wait for consent and stop on Do Not Track or a decline.
14
+ - Use it when server code must read the visitor's choice from the `Cookie` header.
15
+ - Do not use it when events must reach a backend: it sends nothing; use your analytics vendor's SDK.
16
+ - Do not use it for a server-side consent record: use [`@vllnt/convex-consent`](https://oss.vllnt.com/packages/convex-consent).
13
17
 
14
18
  ## Install
15
19
 
@@ -17,55 +21,89 @@ Lightweight, privacy-first analytics library with consent management and React i
17
21
  pnpm add @vllnt/analytics
18
22
  ```
19
23
 
20
- Peer dependency: `react ^18.0.0 || ^19.0.0`
21
-
22
- Ships ESM and CommonJS builds with type declarations; no bundler transpilation of `node_modules` is needed.
23
-
24
- ## For coding agents
25
-
26
- The docs are bundled in the package at `node_modules/@vllnt/analytics/docs/` ([`docs/API.md`](docs/API.md)), together with
27
- [`llms.txt`](llms.txt), `CHANGELOG.md` and the TypeScript sources in `src/`. They match the installed
28
- version. Read them before writing code.
29
-
30
- ## Usage
31
-
32
- ### React Provider
24
+ ## Quick start
33
25
 
34
26
  ```tsx
35
- import type { ReactNode } from "react";
36
- import { AnalyticsProvider } from "@vllnt/analytics/react";
27
+ import { track } from "@vllnt/analytics";
28
+ import { AnalyticsProvider, useAnalytics } from "@vllnt/analytics/react";
37
29
 
38
- // Keep config stable: an inline object re-runs the init effect and re-renders every consumer.
39
- // Config changes are ignored while analytics is running (initAnalytics returns once started).
40
- const config = { app: "my-app", version: 1, debug: true };
30
+ const config = { app: "my-app" };
41
31
 
42
- function App({ children }: { children: ReactNode }) {
43
- return (
44
- <AnalyticsProvider config={config}>
45
- {children}
46
- </AnalyticsProvider>
47
- );
32
+ function Banner() {
33
+ const { hasResponded, acceptAll, declineAnalytics } = useAnalytics();
34
+ return hasResponded ? null : <p><button onClick={acceptAll}>Accept</button><button onClick={declineAnalytics}>Decline</button></p>;
48
35
  }
36
+
37
+ export const App = () => (
38
+ <AnalyticsProvider config={config}><Banner /><button onClick={() => track("cta_click")}>Buy</button></AnalyticsProvider>
39
+ );
49
40
  ```
50
41
 
51
- ### Consent Banner
42
+ ## API
43
+
44
+ Every public export. Full signatures and examples: [`docs/API.md`](docs/API.md).
45
+
46
+ | Export | Entry | What it does |
47
+ | --- | --- | --- |
48
+ | [`initAnalytics`](docs/API.md#initanalytics) | `.`, `./react` | Starts the shared instance and flushes queued events, unless blocked. |
49
+ | [`track`](docs/API.md#track) | `.` | Records a custom event; queued before init, dropped while blocked. |
50
+ | [`trackPage`](docs/API.md#trackpage) | `.` | Records a page view, queued before init like `track`. |
51
+ | [`identify`](docs/API.md#identify) | `.` | Stores a user id and traits on the started instance. |
52
+ | [`resetAnalytics`](docs/API.md#resetanalytics) | `.` | Clears the user id and traits (logout). |
53
+ | [`enableAnalytics`](docs/API.md#enableanalytics) | `.` | Unblocks after consent is granted and starts again. |
54
+ | [`disableAnalytics`](docs/API.md#disableanalytics) | `.` | Blocks tracking and empties the queue. |
55
+ | [`isAnalyticsEnabled`](docs/API.md#isanalyticsenabled) | `.` | `true` when started and not blocked. |
56
+ | [`getAnalyticsState`](docs/API.md#getanalyticsstate) | `.` | Current instance state, for debugging. |
57
+ | [`trackTutorialStart`](docs/API.md#tutorial-helpers) | `.` | Tracks a `tutorial_start` event. |
58
+ | [`trackSectionView`](docs/API.md#tutorial-helpers) | `.` | Tracks a `tutorial_section_view` event. |
59
+ | [`trackSectionComplete`](docs/API.md#tutorial-helpers) | `.` | Tracks a `tutorial_section_complete` event. |
60
+ | [`trackTutorialComplete`](docs/API.md#tutorial-helpers) | `.` | Tracks a `tutorial_complete` event. |
61
+ | [`trackTutorialNavigation`](docs/API.md#tutorial-helpers) | `.` | Tracks a `tutorial_navigation` event. |
62
+ | [`trackTimeSpent`](docs/API.md#tutorial-helpers) | `.` | Tracks a `tutorial_time_spent` event. |
63
+ | [`CONSENT_VERSION`](docs/API.md#constants) | `.` | Default consent version, `1`. |
64
+ | [`CONSENT_STORAGE_KEY`](docs/API.md#constants) | `.` | `localStorage` key, `"vllnt:analytics-consent"`. |
65
+ | [`CONSENT_COOKIE_NAME`](docs/API.md#constants) | `.` | Cookie name, `"vllnt-consent"`. |
66
+ | [`loadConsent`](docs/API.md#loadconsent) | `.` | Reads and validates stored consent, or `null`. |
67
+ | [`saveConsent`](docs/API.md#saveconsent) | `.` | Writes consent to `localStorage` and the cookie. |
68
+ | [`clearConsent`](docs/API.md#clearconsent) | `.` | Removes stored consent and expires the cookie. |
69
+ | [`createAcceptAllConsent`](docs/API.md#createacceptallconsent) | `.` | New consent state with everything accepted. |
70
+ | [`createDeclineAnalyticsConsent`](docs/API.md#createdeclineanalyticsconsent) | `.` | New consent state with analytics declined. |
71
+ | [`updateConsentCategory`](docs/API.md#updateconsentcategory) | `.` | Copy of a consent state with one category changed. |
72
+ | [`needsRePrompt`](docs/API.md#needsreprompt) | `.` | `true` when stored consent is older than a version. |
73
+ | [`getConsentFromCookie`](docs/API.md#getconsentfromcookie) | `.` | Parses the consent cookie from a `Cookie` header. |
74
+ | [`isDoNotTrackEnabled`](docs/API.md#isdonottrackenabled) | `.` | `true` when the browser sends Do Not Track. |
75
+ | [`isStorageAvailable`](docs/API.md#isstorageavailable) | `.` | `true` when `localStorage` can be written. |
76
+ | [`isValidConsentState`](docs/API.md#isvalidconsentstate) | `.` | Type guard for a stored consent object. |
77
+ | [`AnalyticsProvider`](docs/API.md#analyticsprovider) | `./react` | Context provider that wires consent to tracking. |
78
+ | [`useAnalytics`](docs/API.md#useanalytics) | `./react` | Provider context: consent state and actions. |
79
+ | [`useConsent`](docs/API.md#useconsent) | `./react` | Standalone consent state; does not start tracking. |
80
+ | [`AnalyticsConfig`](docs/API.md#types) | `.` (type) | `{ app; debug?; version? }`. |
81
+ | [`AnalyticsEvent`](docs/API.md#types) | `.` (type) | A queued event: name, properties, timestamp. |
82
+ | [`ConsentCategory`](docs/API.md#types) | `.` (type) | `"analytics" \| "functional"`. |
83
+ | [`ConsentState`](docs/API.md#types) | `.` (type) | Stored consent: categories, timestamp, version. |
84
+ | [`TutorialEventName`](docs/API.md#types) | `.` (type) | Event names used by the tutorial helpers. |
85
+ | [`TutorialEventProperties`](docs/API.md#types) | `.` (type) | Properties for the tutorial helpers. |
86
+ | [`UseConsentOptions`](docs/API.md#types) | `.` (type) | `{ consentVersion? }`. |
87
+ | [`UseConsentReturn`](docs/API.md#types) | `.` (type) | Return value of `useConsent`. |
88
+
89
+ ## Common tasks
90
+
91
+ ### Show the banner only after mount
92
+
93
+ Stored consent is read in the browser only, so on the server `hasResponded` is `false`. Render the
94
+ banner after mount to avoid a hydration mismatch.
52
95
 
53
96
  ```tsx
54
97
  import { useEffect, useState } from "react";
55
98
  import { useAnalytics } from "@vllnt/analytics/react";
56
99
 
57
- // Render inside <AnalyticsProvider> so accepting starts tracking.
58
- function CookieBanner() {
100
+ export function CookieBanner() {
59
101
  const { hasResponded, acceptAll, declineAnalytics } = useAnalytics();
60
- // Stored consent is read in the browser only; wait for mount to avoid a hydration mismatch.
61
102
  const [mounted, setMounted] = useState(false);
62
103
  useEffect(() => setMounted(true), []);
63
-
64
104
  if (!mounted || hasResponded) return null;
65
-
66
105
  return (
67
106
  <div>
68
- <p>We use cookies for analytics.</p>
69
107
  <button onClick={acceptAll}>Accept</button>
70
108
  <button onClick={declineAnalytics}>Decline</button>
71
109
  </div>
@@ -73,41 +111,69 @@ function CookieBanner() {
73
111
  }
74
112
  ```
75
113
 
76
- `useConsent()` exposes the same consent fields without a provider, but it only reads and writes
77
- stored consent: it does not start or stop analytics.
114
+ ### Read consent on the server
115
+
116
+ ```ts
117
+ import { getConsentFromCookie } from "@vllnt/analytics";
118
+
119
+ export function GET(request: Request): Response {
120
+ const allowed = getConsentFromCookie(request.headers.get("cookie") ?? "");
121
+ return Response.json({ allowed });
122
+ }
123
+ ```
124
+
125
+ ### Ask every visitor again after a policy change
78
126
 
79
- ### Track Events
127
+ Raise `consentVersion`. Stored choices with a lower version are cleared once; new choices are saved
128
+ with the new version.
80
129
 
81
130
  ```tsx
82
- import { track, trackPage } from "@vllnt/analytics";
131
+ import type { ReactNode } from "react";
132
+ import { AnalyticsProvider } from "@vllnt/analytics/react";
83
133
 
84
- // Generic event
85
- track("button_click", { id: "cta-hero" });
134
+ const config = { app: "my-app" };
86
135
 
87
- // Page view
88
- trackPage({ path: "/about" });
136
+ export function Root({ children }: { children: ReactNode }) {
137
+ return (
138
+ <AnalyticsProvider config={config} consentVersion={2}>
139
+ {children}
140
+ </AnalyticsProvider>
141
+ );
142
+ }
89
143
  ```
90
144
 
91
- ### Tutorial Tracking
92
-
93
- Typed helpers for tutorial/content flows:
145
+ ### Let the visitor change their choice later
94
146
 
95
147
  ```tsx
96
- import {
97
- trackTutorialStart,
98
- trackSectionView,
99
- trackSectionComplete,
100
- trackTutorialComplete,
101
- trackTutorialNavigation,
102
- trackTimeSpent,
103
- } from "@vllnt/analytics";
148
+ import { useAnalytics } from "@vllnt/analytics/react";
104
149
 
105
- trackTutorialStart({
106
- tutorial_id: "getting-started",
107
- tutorial_title: "Getting Started",
108
- locale: "en",
109
- total_sections: 5,
110
- });
150
+ export function PrivacySettings() {
151
+ const { consent, updateConsent, resetConsent } = useAnalytics();
152
+ return (
153
+ <div>
154
+ <label>
155
+ <input
156
+ type="checkbox"
157
+ checked={consent?.analytics ?? false}
158
+ onChange={(event) => updateConsent("analytics", event.target.checked)}
159
+ />
160
+ Analytics
161
+ </label>
162
+ <button onClick={resetConsent}>Ask me again</button>
163
+ </div>
164
+ );
165
+ }
166
+ ```
167
+
168
+ ### Track page views, users and tutorials
169
+
170
+ ```ts
171
+ import { identify, resetAnalytics, trackPage, trackSectionView } from "@vllnt/analytics";
172
+
173
+ trackPage({ path: "/about" });
174
+
175
+ identify("user-123", { plan: "pro" });
176
+ resetAnalytics();
111
177
 
112
178
  trackSectionView({
113
179
  tutorial_id: "getting-started",
@@ -119,120 +185,123 @@ trackSectionView({
119
185
  });
120
186
  ```
121
187
 
122
- ### Identify Users
123
-
124
- ```tsx
125
- import { identify, resetAnalytics } from "@vllnt/analytics";
126
-
127
- // After login
128
- identify("user-123", { plan: "pro" });
129
-
130
- // After logout
131
- resetAnalytics();
132
- ```
133
-
134
- ### Consent Utilities (non-React)
188
+ ### Use it without React
135
189
 
136
190
  ```ts
137
191
  import {
138
- loadConsent,
139
- saveConsent,
140
- clearConsent,
141
192
  createAcceptAllConsent,
142
193
  createDeclineAnalyticsConsent,
143
- getConsentFromCookie,
144
- isDoNotTrackEnabled,
145
- needsRePrompt,
194
+ disableAnalytics,
195
+ enableAnalytics,
196
+ initAnalytics,
197
+ loadConsent,
198
+ saveConsent,
146
199
  } from "@vllnt/analytics";
147
200
 
148
- // SSR: read consent from cookie header
149
- const analyticsAllowed = getConsentFromCookie(request.headers.get("cookie") ?? "");
201
+ const config = { app: "my-app" };
150
202
 
151
- // Check if re-prompt needed after version bump
152
- const consent = loadConsent();
153
- if (consent && needsRePrompt(consent, 2)) {
154
- clearConsent();
155
- }
156
- ```
203
+ // A stored accept starts tracking; a stored decline blocks it and drops queued events.
204
+ if (loadConsent()) initAnalytics(config);
157
205
 
158
- ## API
159
-
160
- Full reference with signatures and examples: [`docs/API.md`](docs/API.md).
161
-
162
- ### Core
163
-
164
- | Function | Description |
165
- | --------------------------- | ---------------------------------------------- |
166
- | `initAnalytics(config)` | Initialize analytics singleton |
167
- | `track(name, properties?)` | Track a custom event (empty names are ignored) |
168
- | `trackPage(properties?)` | Track a page view |
169
- | `identify(userId, traits?)` | Identify a user (empty ids are ignored) |
170
- | `resetAnalytics()` | Clear user identity (logout) |
171
- | `enableAnalytics(config)` | Re-enable after consent granted |
172
- | `disableAnalytics()` | Disable after consent revoked |
173
- | `isAnalyticsEnabled()` | Check if tracking is active |
174
-
175
- ### Consent
176
-
177
- | Function | Description |
178
- | ----------------------------------------------- | ---------------------------------------- |
179
- | `loadConsent()` | Load consent from localStorage |
180
- | `saveConsent(state)` | Persist consent to localStorage + cookie |
181
- | `clearConsent()` | Remove consent (triggers re-prompt) |
182
- | `createAcceptAllConsent()` | Create accept-all consent state |
183
- | `createDeclineAnalyticsConsent()` | Create analytics-declined state |
184
- | `updateConsentCategory(state, category, value)` | Update a single category |
185
- | `needsRePrompt(consent, version)` | Check if version requires re-prompt |
186
- | `getConsentFromCookie(cookieString)` | Parse consent from cookie (SSR) |
187
- | `isDoNotTrackEnabled()` | Check browser DNT setting |
188
-
189
- ### React (`@vllnt/analytics/react`)
190
-
191
- | Export | Description |
192
- | ---------------------- | ------------------------------------------------- |
193
- | `AnalyticsProvider` | Context provider — wires consent + analytics init |
194
- | `useAnalytics()` | Access full analytics context |
195
- | `useConsent(options?)` | Standalone consent hook for banner UIs |
196
-
197
- ## How It Works
206
+ export function onAccept(): void {
207
+ saveConsent(createAcceptAllConsent());
208
+ enableAnalytics(config);
209
+ initAnalytics(config);
210
+ }
198
211
 
212
+ export function onDecline(): void {
213
+ saveConsent(createDeclineAnalyticsConsent());
214
+ disableAnalytics();
215
+ }
199
216
  ```
217
+
218
+ ## Errors and fixes
219
+
220
+ The package has no error codes. These are every message it throws or logs as a warning.
221
+
222
+ | Message | Kind | Cause | Fix |
223
+ | --- | --- | --- | --- |
224
+ | `useAnalytics must be used within an AnalyticsProvider` | thrown by `useAnalytics()` | The hook ran outside `<AnalyticsProvider>`. | Render the component inside `<AnalyticsProvider>`, or use `useConsent()`. |
225
+ | `Failed to save consent:` | `console.warn` from `saveConsent()` | Writing `localStorage` or the cookie threw, for example a full quota. | The new choice applies on this page but is not stored, so later visits load the earlier stored choice, if any. A failed accept over a stored decline stays blocked on this page too, because `initAnalytics` re-reads the stored decline. Free storage, or call `clearConsent()` after a failed save. |
226
+
227
+ ## Limits and gotchas
228
+
229
+ - No transport and no event callback: events never leave the page. With `debug: true` they are
230
+ logged with `console.log` as `[analytics:track]`, `[analytics:page]` and similar.
231
+ - Before the visitor responds, `track()` and `trackPage()` are queued in memory with no size
232
+ limit. The first unblocked `initAnalytics()` flushes them; a decline or a Do Not Track block drops
233
+ them. After `resetConsent()`, tracking is blocked and events are dropped until the visitor
234
+ responds again.
235
+ - `identify()` before init or while blocked does nothing; it is not queued.
236
+ - `track()` with an empty or non-string name and `identify()` with an empty or non-string id do
237
+ nothing.
238
+ - `initAnalytics()` runs once: later calls, and later `config` values, are ignored while an
239
+ instance exists. Pass a stable `config` (a module constant) to `AnalyticsProvider`.
240
+ - Once blocked, only `enableAnalytics()` unblocks. It re-reads stored consent, so save the accepted
241
+ consent first, and it does nothing while Do Not Track (`"1"` or `"yes"`) is on.
242
+ - `disableAnalytics()` keeps the user id and traits; call `resetAnalytics()` to clear them.
243
+ - On the server, `track`, `trackPage`, `identify` and `resetAnalytics` do nothing and `loadConsent`
244
+ returns `null`. `initAnalytics` has no server guard: call it only in the browser.
245
+ - When `localStorage` is unavailable, `saveConsent` and `clearConsent` do nothing, so the choice
246
+ lasts for the current page only.
247
+ - `updateConsent("functional", false)` is ignored: functional consent is always on.
248
+ `updateConsent` does nothing while `consent` is `null`.
249
+ - `useConsent()` reads and writes stored consent only; it does not start or stop tracking and does
250
+ not share state with `AnalyticsProvider`.
251
+ - `isLoading` is always `false`.
252
+ - The cookie is `vllnt-consent=1` or `vllnt-consent=0`, with a one-year expiry, `path=/` and
253
+ `SameSite=Lax`, and without `Secure` or `HttpOnly`.
254
+
255
+ ```text
200
256
  AnalyticsProvider mounts
201
- │
202
- ├─ Stored consent outdated? ──▶ Clear it & re-prompt
203
- │
257
+ ├─ Stored consent older than consentVersion ──▶ cleared, banner shown again
204
258
  ├─ Analytics accepted ──▶ initAnalytics()
205
- │ ├─ DNT enabled? ──▶ Block tracking
206
- │ └─ Otherwise ──▶ Start & flush queue
207
- │
208
- ├─ Analytics declined ──▶ disableAnalytics(); track() calls are dropped
209
- │
210
- └─ No consent yet ──▶ No init; track() calls are queued in memory
259
+ │ ├─ Do Not Track on ──▶ blocked, queue dropped
260
+ │ └─ otherwise ──▶ started, queue flushed
261
+ ├─ Analytics declined ──▶ disableAnalytics(); track() calls dropped
262
+ └─ No consent yet ──▶ no init; track() calls queued in memory
211
263
  ```
212
264
 
213
- Events fired before the user responds are queued and flushed once consent is granted and
214
- analytics initializes. A decline, or an init blocked by Do Not Track, drops them.
265
+ ## Compatibility
215
266
 
216
- ## Scripts
267
+ - React: peer range `^18.0.0 || ^19.0.0`, used by `./react` only.
268
+ - Module formats: ESM and CommonJS, with type declarations for both, from `dist/`.
269
+ - `./react` starts with `"use client"` in both builds; the core entry does not, so server code can
270
+ import it.
271
+ - Runtimes: browsers for tracking and consent storage. Server runtimes can import every entry point;
272
+ there, use `getConsentFromCookie` to read consent.
217
273
 
218
- ```bash
219
- pnpm test # Run tests (watch mode)
220
- pnpm test:once # Run tests once
221
- pnpm test:coverage # Run with coverage
222
- pnpm lint # Lint
223
- pnpm lint:fix # Lint + autofix
224
- pnpm typecheck # Type-check
225
- pnpm build # Build dist (ESM, CJS, types)
226
- ```
274
+ ## Testing
275
+
276
+ The analytics state is a module-level singleton with no public reset. In your tests, clear
277
+ `localStorage` between cases and load the module fresh when a case needs a new instance.
278
+
279
+ This repository's own checks: `pnpm lint`, `pnpm typecheck`, `pnpm test:coverage` (Vitest with
280
+ jsdom, 100% coverage gate) and `pnpm build`.
281
+
282
+ ## Security
283
+
284
+ Report vulnerabilities privately through
285
+ [GitHub Security Advisories](https://github.com/vllnt/analytics/security/advisories/new). Releases
286
+ are published from CI with npm trusted publishing and provenance.
227
287
 
228
288
  ## Related packages
229
289
 
230
- - [`@vllnt/convex-analytics`](https://www.npmjs.com/package/@vllnt/convex-analytics): a Convex
231
- component that stores events and serves rollups, funnels and retention. Use it as the backend if
232
- your app runs on Convex; this package does not send events to it for you.
233
- - [`@vllnt/convex-consent`](https://www.npmjs.com/package/@vllnt/convex-consent): an append-only
234
- consent ledger stored in Convex. Use it when you need a server-side record of consent per
235
- subject and purpose; this package only keeps the visitor's choice in the browser.
290
+ None: no other @vllnt package is used together with this one in code.
291
+
292
+ ## Contributing
293
+
294
+ See [CONTRIBUTING.md](https://github.com/vllnt/analytics/blob/main/CONTRIBUTING.md). Setup:
295
+ `pnpm install`, then `pnpm lint && pnpm typecheck && pnpm test:coverage && pnpm build`.
296
+
297
+ ## Links
298
+
299
+ - Docs and changelog: [oss.vllnt.com/packages/analytics](https://oss.vllnt.com/packages/analytics) · [release feed](https://oss.vllnt.com/packages/analytics/rss.xml)
300
+ - All @vllnt packages: [oss.vllnt.com](https://oss.vllnt.com) · [search packages and docs on index.vllnt.com](https://index.vllnt.com)
301
+ - Source and issues: [GitHub](https://github.com/vllnt/analytics) · [issues](https://github.com/vllnt/analytics/issues)
302
+ - Questions and updates: [Discord](https://bntvllnt.com/discord) · [X @bntvllnt](https://x.com/bntvllnt)
303
+ - Company and author: [vllnt.com](https://vllnt.com) · [bntvllnt.com](https://bntvllnt.com) · [GitHub @bntvllnt](https://github.com/bntvllnt) · [LinkedIn](https://linkedin.com/in/bntvllnt)
304
+ - Sponsor: [GitHub Sponsors](https://github.com/sponsors/bntvllnt)
236
305
 
237
306
  ## License
238
307
 
@@ -240,4 +309,4 @@ pnpm build # Build dist (ESM, CJS, types)
240
309
 
241
310
  ---
242
311
 
243
- Part of vllnt oss: https://oss.vllnt.com
312
+ Part of [vllnt open source](https://oss.vllnt.com) · [Package page](https://oss.vllnt.com/packages/analytics) · [vllnt.com](https://vllnt.com) · Built by [bntvllnt](https://bntvllnt.com)
@@ -96,7 +96,9 @@ type AnalyticsState = {
96
96
  version?: number;
97
97
  };
98
98
  /**
99
- * Initialize analytics with configuration
99
+ * Start the shared analytics instance and flush queued events. Blocks tracking,
100
+ * and drops the queue, when Do Not Track is on or stored consent declines it.
101
+ * @see https://oss.vllnt.com/packages/analytics
100
102
  */
101
103
  declare function initAnalytics(config: AnalyticsConfig): void;
102
104
  /**
@@ -96,7 +96,9 @@ type AnalyticsState = {
96
96
  version?: number;
97
97
  };
98
98
  /**
99
- * Initialize analytics with configuration
99
+ * Start the shared analytics instance and flush queued events. Blocks tracking,
100
+ * and drops the queue, when Do Not Track is on or stored consent declines it.
101
+ * @see https://oss.vllnt.com/packages/analytics
100
102
  */
101
103
  declare function initAnalytics(config: AnalyticsConfig): void;
102
104
  /**
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as ConsentState, a as ConsentCategory } from './analytics-DdAxcZwX.cjs';
2
- export { A as AnalyticsConfig, b as AnalyticsEvent, T as TutorialEventName, c as TutorialEventProperties, U as UseConsentOptions, d as UseConsentReturn, e as disableAnalytics, f as enableAnalytics, g as getAnalyticsState, i as identify, h as initAnalytics, j as isAnalyticsEnabled, r as resetAnalytics, t as track, k as trackPage, l as trackSectionComplete, m as trackSectionView, n as trackTimeSpent, o as trackTutorialComplete, p as trackTutorialNavigation, q as trackTutorialStart } from './analytics-DdAxcZwX.cjs';
1
+ import { C as ConsentState, a as ConsentCategory } from './analytics-BxUQktfB.cjs';
2
+ export { A as AnalyticsConfig, b as AnalyticsEvent, T as TutorialEventName, c as TutorialEventProperties, U as UseConsentOptions, d as UseConsentReturn, e as disableAnalytics, f as enableAnalytics, g as getAnalyticsState, i as identify, h as initAnalytics, j as isAnalyticsEnabled, r as resetAnalytics, t as track, k as trackPage, l as trackSectionComplete, m as trackSectionView, n as trackTimeSpent, o as trackTutorialComplete, p as trackTutorialNavigation, q as trackTutorialStart } from './analytics-BxUQktfB.cjs';
3
3
 
4
4
  /** Current consent schema version - bump to re-prompt users */
5
5
  declare const CONSENT_VERSION = 1;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { C as ConsentState, a as ConsentCategory } from './analytics-DdAxcZwX.js';
2
- export { A as AnalyticsConfig, b as AnalyticsEvent, T as TutorialEventName, c as TutorialEventProperties, U as UseConsentOptions, d as UseConsentReturn, e as disableAnalytics, f as enableAnalytics, g as getAnalyticsState, i as identify, h as initAnalytics, j as isAnalyticsEnabled, r as resetAnalytics, t as track, k as trackPage, l as trackSectionComplete, m as trackSectionView, n as trackTimeSpent, o as trackTutorialComplete, p as trackTutorialNavigation, q as trackTutorialStart } from './analytics-DdAxcZwX.js';
1
+ import { C as ConsentState, a as ConsentCategory } from './analytics-BxUQktfB.js';
2
+ export { A as AnalyticsConfig, b as AnalyticsEvent, T as TutorialEventName, c as TutorialEventProperties, U as UseConsentOptions, d as UseConsentReturn, e as disableAnalytics, f as enableAnalytics, g as getAnalyticsState, i as identify, h as initAnalytics, j as isAnalyticsEnabled, r as resetAnalytics, t as track, k as trackPage, l as trackSectionComplete, m as trackSectionView, n as trackTimeSpent, o as trackTutorialComplete, p as trackTutorialNavigation, q as trackTutorialStart } from './analytics-BxUQktfB.js';
3
3
 
4
4
  /** Current consent schema version - bump to re-prompt users */
5
5
  declare const CONSENT_VERSION = 1;
package/dist/react.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
3
  import { AnalyticsConfig, ConsentState, ConsentCategory, UseConsentOptions, UseConsentReturn } from './index.cjs';
4
- export { h as initAnalytics } from './analytics-DdAxcZwX.cjs';
4
+ export { h as initAnalytics } from './analytics-BxUQktfB.cjs';
5
5
 
6
6
  type AnalyticsContextValue = {
7
7
  acceptAll: () => void;
package/dist/react.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
3
  import { AnalyticsConfig, ConsentState, ConsentCategory, UseConsentOptions, UseConsentReturn } from './index.js';
4
- export { h as initAnalytics } from './analytics-DdAxcZwX.js';
4
+ export { h as initAnalytics } from './analytics-BxUQktfB.js';
5
5
 
6
6
  type AnalyticsContextValue = {
7
7
  acceptAll: () => void;
package/docs/API.md CHANGED
@@ -1,7 +1,8 @@
1
1
  # @vllnt/analytics API
2
2
 
3
3
  Reference for every public export of this package version, written from `src/index.ts` and
4
- `src/react.tsx`. Those sources ship in this package under `src/`.
4
+ `src/react.tsx`. Those sources ship in this package under `src/`. Errors and their fixes are in the
5
+ README: [Errors and fixes](../README.md#errors-and-fixes).
5
6
 
6
7
  The library has no transport. Events are queued and gated by consent, then dropped; with
7
8
  `debug: true` they are written to `console.log`. Send them to your own backend yourself.
@@ -11,14 +12,16 @@ The library has no transport. Events are queued and gated by consent, then dropp
11
12
  Only these subpaths are exported (`package.json` `exports`). Each has ESM, CommonJS and type
12
13
  declarations in `dist/`.
13
14
 
14
- | Import | Contents |
15
- | ---------------------------- | ------------------------------------------------------------ |
16
- | `@vllnt/analytics` | Tracking functions, consent functions and constants, types |
17
- | `@vllnt/analytics/react` | `AnalyticsProvider`, `useAnalytics`, `useConsent`, `initAnalytics` |
18
- | `@vllnt/analytics/package.json` | Package metadata |
15
+ | Import | Contents |
16
+ | ------------------------------- | ------------------------------------------------------------------ |
17
+ | `@vllnt/analytics` | Tracking functions, consent functions and constants, types |
18
+ | `@vllnt/analytics/react` | `AnalyticsProvider`, `useAnalytics`, `useConsent`, `initAnalytics` |
19
+ | `@vllnt/analytics/package.json` | Package metadata |
19
20
 
20
- Types are exported from `@vllnt/analytics` only. Both entry points share one analytics state, so
21
- `initAnalytics` from `./react` and `track` from `.` act on the same instance.
21
+ Types are exported from `@vllnt/analytics` only. Within one module format, both entry points share
22
+ one analytics state, so `initAnalytics` from `./react` and `track` from `.` act on the same instance.
23
+ The ESM and CommonJS builds each have their own copy, so mixing `import` and `require` in one
24
+ process gives two instances.
22
25
 
23
26
  Peer dependency: `react` `^18.0.0 || ^19.0.0` (used by `./react` only).
24
27
 
@@ -31,16 +34,17 @@ starts the process-wide instance, so call it only in the browser.
31
34
 
32
35
  ## Tracking (`@vllnt/analytics`)
33
36
 
34
- ### `initAnalytics(config: AnalyticsConfig): void`
37
+ ### `initAnalytics`
38
+
39
+ Signature: `initAnalytics(config: AnalyticsConfig): void`
35
40
 
36
41
  Starts the shared analytics instance and flushes queued events. Later calls do nothing while an
37
42
  instance exists. It does not start, and blocks tracking, when Do Not Track is on (`"1"` or
38
43
  `"yes"`) or stored consent has `analytics: false`; already queued events are then dropped, so
39
- they are never sent later.
40
- With no stored consent it starts, so call it only after the user accepts if you need opt-in
41
- (`AnalyticsProvider` does this for you). Once tracking is blocked (by a blocked init or by
42
- `disableAnalytics`), calling `initAnalytics` again does not unblock it; only `enableAnalytics`
43
- does.
44
+ they are never flushed later. With no stored consent it starts, so call it only after the user
45
+ accepts if you need opt-in (`AnalyticsProvider` does this for you). Once tracking is blocked (by a
46
+ blocked init or by `disableAnalytics`), calling `initAnalytics` again does not unblock it; only
47
+ `enableAnalytics` does.
44
48
 
45
49
  ```ts
46
50
  import { initAnalytics } from "@vllnt/analytics";
@@ -48,41 +52,59 @@ import { initAnalytics } from "@vllnt/analytics";
48
52
  initAnalytics({ app: "my-app", version: 1, debug: true });
49
53
  ```
50
54
 
51
- ### `track(name: string, properties?: Record<string, unknown>): void`
55
+ ### `track`
56
+
57
+ Signature: `track(name: string, properties?: Record<string, unknown>): void`
52
58
 
53
59
  Records a custom event. Before `initAnalytics` the event is queued; while blocked it is dropped.
54
60
  An empty or non-string `name` is ignored.
55
61
 
56
62
  ```ts
63
+ import { track } from "@vllnt/analytics";
64
+
57
65
  track("button_click", { id: "cta-hero" });
58
66
  ```
59
67
 
60
- ### `trackPage(properties?: Record<string, unknown>): void`
68
+ ### `trackPage`
69
+
70
+ Signature: `trackPage(properties?: Record<string, unknown>): void`
61
71
 
62
72
  Records a page view, queued before init like `track`.
63
73
 
64
74
  ```ts
75
+ import { trackPage } from "@vllnt/analytics";
76
+
65
77
  trackPage({ path: "/about" });
66
78
  ```
67
79
 
68
- ### `identify(userId: string, traits?: Record<string, unknown>): void`
80
+ ### `identify`
81
+
82
+ Signature: `identify(userId: string, traits?: Record<string, unknown>): void`
69
83
 
70
84
  Stores a user id and traits on the started instance. Ignored before init, while blocked, or
71
85
  when `userId` is empty or not a string. Not queued.
72
86
 
73
87
  ```ts
88
+ import { identify } from "@vllnt/analytics";
89
+
74
90
  identify("user-123", { plan: "pro" });
75
91
  ```
76
92
 
77
- ### `resetAnalytics(): void`
93
+ ### `resetAnalytics`
94
+
95
+ Signature: `resetAnalytics(): void`
78
96
 
79
97
  Clears the stored user id and traits (for logout). The instance stays started.
80
98
 
81
99
  ```ts
100
+ import { resetAnalytics } from "@vllnt/analytics";
101
+
82
102
  resetAnalytics();
83
103
  ```
84
104
 
85
- ### `enableAnalytics(config: AnalyticsConfig): void`
105
+ ### `enableAnalytics`
106
+
107
+ Signature: `enableAnalytics(config: AnalyticsConfig): void`
86
108
 
87
109
  Unblocks, discards the current instance and runs `initAnalytics(config)` again. Does nothing
88
110
  unless tracking is currently blocked, and does nothing while Do Not Track is on. Because it
@@ -90,51 +112,64 @@ re-reads stored consent, save the accepted consent first: a stored `analytics: f
90
112
  again. The new instance has no `userId` or `traits`.
91
113
 
92
114
  ```ts
115
+ import { createAcceptAllConsent, enableAnalytics, saveConsent } from "@vllnt/analytics";
116
+
93
117
  saveConsent(createAcceptAllConsent());
94
118
  enableAnalytics({ app: "my-app" });
95
119
  ```
96
120
 
97
- ### `disableAnalytics(): void`
121
+ ### `disableAnalytics`
122
+
123
+ Signature: `disableAnalytics(): void`
98
124
 
99
125
  Blocks tracking and empties the queue after consent is revoked. It keeps the in-memory user id
100
126
  and traits; call `resetAnalytics()` or reload the page to clear them.
101
127
 
102
128
  ```ts
129
+ import { disableAnalytics, resetAnalytics } from "@vllnt/analytics";
130
+
103
131
  disableAnalytics();
104
132
  resetAnalytics();
105
133
  ```
106
134
 
107
- ### `isAnalyticsEnabled(): boolean`
135
+ ### `isAnalyticsEnabled`
136
+
137
+ Signature: `isAnalyticsEnabled(): boolean`
108
138
 
109
139
  `true` when the instance has started and is not blocked.
110
140
 
111
141
  ```ts
142
+ import { isAnalyticsEnabled, track } from "@vllnt/analytics";
143
+
112
144
  if (isAnalyticsEnabled()) track("export_clicked");
113
145
  ```
114
146
 
115
- ### `getAnalyticsState()`
147
+ ### `getAnalyticsState`
116
148
 
117
- Returns the current instance state for debugging, or `undefined` before init. Shape:
118
- `{ app: string; debug?: boolean; version?: number; userId?: string; traits?: Record<string, unknown> }`.
119
- The state type is not exported.
149
+ Signature: `getAnalyticsState(): { app: string; debug?: boolean; version?: number; userId?: string; traits?: Record<string, unknown> } | undefined`
150
+
151
+ Returns the current instance state for debugging, or `undefined` before init. The state type is
152
+ not exported.
120
153
 
121
154
  ```ts
155
+ import { getAnalyticsState } from "@vllnt/analytics";
156
+
122
157
  console.log(getAnalyticsState()?.userId);
123
158
  ```
124
159
 
125
160
  ### Tutorial helpers
126
161
 
127
- Typed wrappers around `track` that send fixed event names (`TutorialEventName`). Every helper
162
+ Typed wrappers around `track` with fixed event names (`TutorialEventName`). Every helper
128
163
  needs `tutorial_id`, `tutorial_title` and `locale`.
129
164
 
130
- | Function | Event name | Extra required fields |
131
- | ------------------------------------- | --------------------------- | ---------------------------------- |
132
- | `trackTutorialStart(properties)` | `tutorial_start` | none (`section_id` not allowed) |
133
- | `trackSectionView(properties)` | `tutorial_section_view` | none |
134
- | `trackSectionComplete(properties)` | `tutorial_section_complete` | none |
135
- | `trackTutorialComplete(properties)` | `tutorial_complete` | none (`section_id` not allowed) |
136
- | `trackTutorialNavigation(properties)` | `tutorial_navigation` | `navigation_type` |
137
- | `trackTimeSpent(properties)` | `tutorial_time_spent` | `time_spent_seconds` |
165
+ | Function | Event name | Extra required fields |
166
+ | ------------------------------------- | --------------------------- | ------------------------------- |
167
+ | `trackTutorialStart(properties)` | `tutorial_start` | none (`section_id` not allowed) |
168
+ | `trackSectionView(properties)` | `tutorial_section_view` | none |
169
+ | `trackSectionComplete(properties)` | `tutorial_section_complete` | none |
170
+ | `trackTutorialComplete(properties)` | `tutorial_complete` | none (`section_id` not allowed) |
171
+ | `trackTutorialNavigation(properties)` | `tutorial_navigation` | `navigation_type` |
172
+ | `trackTimeSpent(properties)` | `tutorial_time_spent` | `time_spent_seconds` |
138
173
 
139
174
  ```ts
140
175
  import { trackSectionView, trackTutorialNavigation } from "@vllnt/analytics";
@@ -152,103 +187,156 @@ Consent is stored as JSON in `localStorage` under `CONSENT_STORAGE_KEY` and mirr
152
187
 
153
188
  ### Constants
154
189
 
155
- | Name | Value |
156
- | --------------------- | ---------------------------- |
157
- | `CONSENT_VERSION` | `1` |
158
- | `CONSENT_STORAGE_KEY` | `"vllnt:analytics-consent"` |
159
- | `CONSENT_COOKIE_NAME` | `"vllnt-consent"` |
190
+ | Name | Value |
191
+ | --------------------- | --------------------------- |
192
+ | `CONSENT_VERSION` | `1` |
193
+ | `CONSENT_STORAGE_KEY` | `"vllnt:analytics-consent"` |
194
+ | `CONSENT_COOKIE_NAME` | `"vllnt-consent"` |
160
195
 
161
- ### `loadConsent(): ConsentState | null`
196
+ ### `loadConsent`
197
+
198
+ Signature: `loadConsent(): ConsentState | null`
162
199
 
163
200
  Reads and validates stored consent. `null` when none, invalid, or storage is unavailable.
164
201
 
165
202
  ```ts
203
+ import { loadConsent } from "@vllnt/analytics";
204
+
166
205
  const consent = loadConsent();
206
+ console.log(consent?.analytics);
167
207
  ```
168
208
 
169
- ### `saveConsent(state: ConsentState): void`
209
+ ### `saveConsent`
210
+
211
+ Signature: `saveConsent(state: ConsentState): void`
170
212
 
171
- Writes consent to `localStorage` and the cookie. Does nothing when storage is unavailable.
213
+ Writes consent to `localStorage` and the cookie. Does nothing when storage is unavailable. Logs
214
+ `Failed to save consent:` with `console.warn` when the write throws.
172
215
 
173
216
  ```ts
217
+ import { createAcceptAllConsent, saveConsent } from "@vllnt/analytics";
218
+
174
219
  saveConsent(createAcceptAllConsent());
175
220
  ```
176
221
 
177
- ### `clearConsent(): void`
222
+ ### `clearConsent`
223
+
224
+ Signature: `clearConsent(): void`
178
225
 
179
226
  Removes stored consent and expires the cookie.
180
227
 
181
228
  ```ts
229
+ import { clearConsent } from "@vllnt/analytics";
230
+
182
231
  clearConsent();
183
232
  ```
184
233
 
185
- ### `createAcceptAllConsent(): ConsentState`
234
+ ### `createAcceptAllConsent`
235
+
236
+ Signature: `createAcceptAllConsent(): ConsentState`
186
237
 
187
238
  New state with `analytics: true`, `functional: true`, the current time and `CONSENT_VERSION`. To
188
239
  record another version, override it: `{ ...createAcceptAllConsent(), version: 2 }`.
189
240
 
190
241
  ```ts
242
+ import { createAcceptAllConsent } from "@vllnt/analytics";
243
+
191
244
  const accepted = createAcceptAllConsent();
245
+ console.log(accepted.version);
192
246
  ```
193
247
 
194
- ### `createDeclineAnalyticsConsent(): ConsentState`
248
+ ### `createDeclineAnalyticsConsent`
249
+
250
+ Signature: `createDeclineAnalyticsConsent(): ConsentState`
195
251
 
196
252
  New state with `analytics: false`, `functional: true`, the current time and `CONSENT_VERSION`.
197
253
 
198
254
  ```ts
255
+ import { createDeclineAnalyticsConsent } from "@vllnt/analytics";
256
+
199
257
  const declined = createDeclineAnalyticsConsent();
258
+ console.log(declined.analytics);
200
259
  ```
201
260
 
202
- ### `updateConsentCategory(current: ConsentState, category: ConsentCategory, value: boolean): ConsentState`
261
+ ### `updateConsentCategory`
262
+
263
+ Signature: `updateConsentCategory(current: ConsentState, category: ConsentCategory, value: boolean): ConsentState`
203
264
 
204
265
  Returns a copy with one category changed and a new timestamp. Setting `functional` to `false`
205
266
  returns `current` unchanged.
206
267
 
207
268
  ```ts
269
+ import { loadConsent, saveConsent, updateConsentCategory } from "@vllnt/analytics";
270
+
208
271
  const stored = loadConsent();
209
272
  if (stored) saveConsent(updateConsentCategory(stored, "analytics", false));
210
273
  ```
211
274
 
212
- ### `needsRePrompt(consent: ConsentState, currentVersion: number): boolean`
275
+ ### `needsRePrompt`
276
+
277
+ Signature: `needsRePrompt(consent: ConsentState, currentVersion: number): boolean`
213
278
 
214
279
  `true` when `consent.version < currentVersion`.
215
280
 
216
281
  ```ts
282
+ import { clearConsent, loadConsent, needsRePrompt } from "@vllnt/analytics";
283
+
284
+ const consent = loadConsent();
217
285
  if (consent && needsRePrompt(consent, 2)) clearConsent();
218
286
  ```
219
287
 
220
- ### `getConsentFromCookie(cookieString: string): boolean | null`
288
+ ### `getConsentFromCookie`
289
+
290
+ Signature: `getConsentFromCookie(cookieString: string): boolean | null`
221
291
 
222
292
  Parses a `Cookie` header: `true` for `1`, `false` for any other value, `null` when the cookie is
223
- absent. The name must start the string or follow `;`, so `evil-vllnt-consent=1` does not match.
293
+ absent or empty (`vllnt-consent=`). The name must start the string or follow `;`, so
294
+ `evil-vllnt-consent=1` does not match.
224
295
 
225
296
  ```ts
226
- const allowed = getConsentFromCookie(request.headers.get("cookie") ?? "");
297
+ import { getConsentFromCookie } from "@vllnt/analytics";
298
+
299
+ export function isAllowed(request: Request): boolean | null {
300
+ return getConsentFromCookie(request.headers.get("cookie") ?? "");
301
+ }
227
302
  ```
228
303
 
229
- ### `isDoNotTrackEnabled(): boolean`
304
+ ### `isDoNotTrackEnabled`
305
+
306
+ Signature: `isDoNotTrackEnabled(): boolean`
230
307
 
231
308
  Reads `navigator.doNotTrack`, then `window.doNotTrack`, then `navigator.msDoNotTrack`, and
232
309
  returns `true` when the first one that is set equals `"1"` or `"yes"`. `false` on the server.
233
310
 
234
311
  ```ts
235
- if (isDoNotTrackEnabled()) hideBanner();
312
+ import { isDoNotTrackEnabled } from "@vllnt/analytics";
313
+
314
+ const showBanner = !isDoNotTrackEnabled();
315
+ console.log(showBanner);
236
316
  ```
237
317
 
238
- ### `isStorageAvailable(): boolean`
318
+ ### `isStorageAvailable`
319
+
320
+ Signature: `isStorageAvailable(): boolean`
239
321
 
240
322
  `true` when `localStorage` can be written. `false` on the server or when storage throws.
241
323
 
242
324
  ```ts
325
+ import { isStorageAvailable } from "@vllnt/analytics";
326
+
243
327
  if (!isStorageAvailable()) console.warn("consent will not persist");
244
328
  ```
245
329
 
246
- ### `isValidConsentState(value: unknown): value is ConsentState`
330
+ ### `isValidConsentState`
331
+
332
+ Signature: `isValidConsentState(value: unknown): value is ConsentState`
247
333
 
248
334
  Type guard: checks the four fields and their types.
249
335
 
250
336
  ```ts
251
- const parsed: unknown = JSON.parse(raw);
337
+ import { isValidConsentState, saveConsent } from "@vllnt/analytics";
338
+
339
+ const parsed: unknown = JSON.parse('{"analytics":true,"functional":true,"timestamp":"2026-01-01T00:00:00.000Z","version":1}');
252
340
  if (isValidConsentState(parsed)) saveConsent(parsed);
253
341
  ```
254
342
 
@@ -264,31 +352,32 @@ the first browser render may already see stored consent. If you render a banner
264
352
 
265
353
  ### `AnalyticsProvider`
266
354
 
267
- ```ts
268
- function AnalyticsProvider(props: {
269
- children: ReactNode;
270
- config: AnalyticsConfig;
271
- consentVersion?: number; // default CONSENT_VERSION
272
- }): React.JSX.Element;
273
- ```
355
+ Signature: `AnalyticsProvider(props: { children: ReactNode; config: AnalyticsConfig; consentVersion?: number }): React.JSX.Element`
274
356
 
275
- Reads stored consent, clears it when `needsRePrompt(stored, consentVersion)`, calls
276
- `initAnalytics(config)` while consent has `analytics: true`, and calls `disableAnalytics()` while
277
- it has `analytics: false`, so after a stored decline `track()` calls are dropped, not queued. Its
278
- context actions save consent with `consentVersion` and call `enableAnalytics` or
279
- `disableAnalytics`. Before the user responds (no stored consent), events are queued in memory and
280
- flushed if the user accepts. Pass a stable `config` (for example a module constant), because the
281
- init effect depends on it.
357
+ `consentVersion` defaults to `CONSENT_VERSION`. The provider reads stored consent, clears it when
358
+ `needsRePrompt(stored, consentVersion)`, calls `initAnalytics(config)` while consent has
359
+ `analytics: true`, and calls `disableAnalytics()` while it has `analytics: false`, so after a
360
+ stored decline `track()` calls are dropped, not queued. `acceptAll` and `declineAnalytics` save
361
+ consent with `consentVersion`; `updateConsent` copies the current consent, so it keeps the stored
362
+ version. The actions call `enableAnalytics` or `disableAnalytics`. Before the user responds (no
363
+ stored consent), events are queued in memory and flushed if the user accepts; after
364
+ `resetConsent()`, tracking is blocked and events are dropped until the user responds again. Pass a stable
365
+ `config` (for example a module constant), because the init effect depends on it.
282
366
 
283
367
  ```tsx
368
+ import type { ReactNode } from "react";
369
+ import { AnalyticsProvider } from "@vllnt/analytics/react";
370
+
284
371
  const config = { app: "my-app", version: 1 };
285
372
 
286
- export function Root({ children }: { children: React.ReactNode }) {
373
+ export function Root({ children }: { children: ReactNode }) {
287
374
  return <AnalyticsProvider config={config}>{children}</AnalyticsProvider>;
288
375
  }
289
376
  ```
290
377
 
291
- ### `useAnalytics()`
378
+ ### `useAnalytics`
379
+
380
+ Signature: `useAnalytics(): UseConsentReturn & { config: AnalyticsConfig }`
292
381
 
293
382
  Returns the provider context; throws `useAnalytics must be used within an AnalyticsProvider`
294
383
  outside one. Fields: `config`, `consent`, `hasResponded`, `isLoading` (always `false`),
@@ -296,7 +385,10 @@ outside one. Fields: `config`, `consent`, `hasResponded`, `isLoading` (always `f
296
385
  `updateConsent` does nothing while `consent` is `null` (before the user has responded).
297
386
 
298
387
  ```tsx
299
- function CookieBanner() {
388
+ import { useEffect, useState } from "react";
389
+ import { useAnalytics } from "@vllnt/analytics/react";
390
+
391
+ export function CookieBanner() {
300
392
  const { hasResponded, acceptAll, declineAnalytics } = useAnalytics();
301
393
  const [mounted, setMounted] = useState(false);
302
394
  useEffect(() => setMounted(true), []);
@@ -310,7 +402,9 @@ function CookieBanner() {
310
402
  }
311
403
  ```
312
404
 
313
- ### `useConsent(options?: UseConsentOptions): UseConsentReturn`
405
+ ### `useConsent`
406
+
407
+ Signature: `useConsent(options?: UseConsentOptions): UseConsentReturn`
314
408
 
315
409
  Standalone consent state with the same fields as `useAnalytics()` except `config`. It reads and
316
410
  writes stored consent only: it does not start or stop analytics and does not share state with
@@ -318,19 +412,31 @@ writes stored consent only: it does not start or stop analytics and does not sha
318
412
  tracking.
319
413
 
320
414
  ```tsx
321
- const { consent, updateConsent } = useConsent({ consentVersion: 1 });
415
+ import { useConsent } from "@vllnt/analytics/react";
416
+
417
+ export function ConsentStatus() {
418
+ const { consent, updateConsent } = useConsent({ consentVersion: 1 });
419
+ return (
420
+ <button onClick={() => updateConsent("analytics", !consent?.analytics)}>
421
+ Analytics: {consent?.analytics ? "on" : "off"}
422
+ </button>
423
+ );
424
+ }
322
425
  ```
323
426
 
324
- ### `initAnalytics`
427
+ ### `initAnalytics` (re-export)
325
428
 
326
- Re-export of the core `initAnalytics`, for apps that only import from `./react`.
429
+ Re-export of the core [`initAnalytics`](#initanalytics), for apps that only import from `./react`.
327
430
 
328
431
  ### Consent versions
329
432
 
330
- `AnalyticsProvider` and `useConsent` save each choice with their `consentVersion`. Raising
433
+ In `AnalyticsProvider` and `useConsent`, `acceptAll` and `declineAnalytics` save the choice with
434
+ `consentVersion`. `updateConsent` copies the current consent, so it keeps the stored version. Raising
331
435
  `consentVersion` asks every visitor once more; the new choice is then kept on later visits.
332
436
 
333
- ## Types (`@vllnt/analytics`)
437
+ ## Types
438
+
439
+ Exported from `@vllnt/analytics` as types only.
334
440
 
335
441
  ```ts
336
442
  type AnalyticsConfig = { app: string; debug?: boolean; version?: number };
package/llms.txt CHANGED
@@ -1,9 +1,9 @@
1
1
  # @vllnt/analytics
2
2
 
3
- > Lightweight, privacy-first analytics with consent management and React integration.
3
+ > Cookie consent state and consent-gated event tracking for React and TypeScript, with Do Not Track and an SSR consent cookie.
4
4
 
5
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`. Bring your own backend.
6
+ `console.log`s them when `debug: true`. Events never leave the page.
7
7
 
8
8
  ## For coding agents
9
9
 
@@ -11,6 +11,14 @@ The docs are bundled in the package at `node_modules/@vllnt/analytics/docs/`, wi
11
11
  `CHANGELOG.md` and the TypeScript sources in `src/`. They match the installed version. Read them
12
12
  before writing code.
13
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
+
14
22
  ## Package
15
23
 
16
24
  - npm: `@vllnt/analytics` (MIT), repo: https://github.com/vllnt/analytics
@@ -24,11 +32,12 @@ before writing code.
24
32
  ## Behaviour
25
33
 
26
34
  - Events tracked before `initAnalytics()` are queued and flushed on the first unblocked init;
27
- a blocked init drops them.
35
+ a blocked init drops them. The queue has no size limit.
28
36
  - `initAnalytics()` blocks tracking when Do Not Track is on (`"1"` or `"yes"`) or stored consent
29
37
  has `analytics: false`. With no stored consent it starts tracking. `AnalyticsProvider` calls it
30
38
  while consent has `analytics: true` and calls `disableAnalytics()` after a stored decline, so a
31
- declined visitor's events are dropped. Before the user responds, events are queued in memory.
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.
32
41
  - Once blocked, only `enableAnalytics(config)` unblocks; it re-reads stored consent.
33
42
  - Consent is stored in `localStorage` (`vllnt:analytics-consent`) and a `vllnt-consent` cookie
34
43
  (`1` or `0`) for SSR; `getConsentFromCookie(cookieString)` reads it with an anchored match.
@@ -37,11 +46,15 @@ before writing code.
37
46
  - `track()` ignores empty or non-string names; `identify()` ignores empty or non-string ids.
38
47
  - Browser APIs are guarded, so server-side import is safe. `initAnalytics()` has no server
39
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.
40
51
 
41
52
  ## Docs
42
53
 
43
54
  - [API reference](./docs/API.md): every public export, signatures, examples, entry points
44
- - [README](./README.md): usage and API summary
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
45
58
  - [Changelog](./CHANGELOG.md): release history
46
59
  - [Core exports](./src/index.ts) and [React exports](./src/react.tsx): source of the public API
47
60
 
@@ -53,4 +66,9 @@ before writing code.
53
66
 
54
67
  ## Ecosystem
55
68
 
56
- - [vllnt oss](https://oss.vllnt.com/llms.txt): index of all vllnt open-source packages
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,24 +1,38 @@
1
1
  {
2
2
  "name": "@vllnt/analytics",
3
- "version": "0.2.0-canary.9bbc838",
4
- "description": "Lightweight, privacy-first analytics with consent management and React integration",
3
+ "version": "0.2.0-canary.d796133",
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
6
  "packageManager": "pnpm@12.22.0",
7
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
+ },
8
16
  "repository": {
9
17
  "type": "git",
10
18
  "url": "git+https://github.com/vllnt/analytics.git"
11
19
  },
12
20
  "homepage": "https://oss.vllnt.com/packages/analytics",
21
+ "bugs": {
22
+ "url": "https://github.com/vllnt/analytics/issues"
23
+ },
13
24
  "keywords": [
14
25
  "analytics",
15
- "consent",
16
- "privacy",
26
+ "event-tracking",
27
+ "cookie-consent",
28
+ "consent-management",
17
29
  "gdpr",
18
- "react",
19
30
  "do-not-track",
20
- "cookie-consent",
21
- "ssr"
31
+ "privacy",
32
+ "react",
33
+ "react-hooks",
34
+ "ssr",
35
+ "typescript"
22
36
  ],
23
37
  "sideEffects": false,
24
38
  "files": [
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,
@@ -40,7 +37,7 @@ export function _resetAnalyticsState(): void {
40
37
 
41
38
  /**
42
39
  * Block tracking and drop queued events, so nothing recorded before the
43
- * decision is sent later.
40
+ * decision is flushed later.
44
41
  */
45
42
  function block(): void {
46
43
  isBlocked = true;
@@ -66,7 +63,9 @@ function sendEvent(name: string, properties?: Record<string, unknown>): void {
66
63
  }
67
64
 
68
65
  /**
69
- * 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
70
69
  */
71
70
  export function initAnalytics(config: AnalyticsConfig): void {
72
71
  if (analyticsState) return;