@vllnt/analytics 0.2.0-canary.13db137 → 0.2.0-canary.33c37cf
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 +74 -0
- package/README.md +252 -137
- package/dist/{analytics-DdAxcZwX.d.cts → analytics-BGm5JlCM.d.cts} +21 -3
- package/dist/{analytics-DdAxcZwX.d.ts → analytics-BGm5JlCM.d.ts} +21 -3
- package/dist/{chunk-MVOBIOKZ.cjs → chunk-BOGMJ4Z4.cjs} +23 -8
- package/dist/{chunk-6RHY2BTB.js → chunk-IBYWNCQ4.js} +22 -7
- package/dist/index.cjs +4 -2
- package/dist/index.d.cts +5 -3
- package/dist/index.d.ts +5 -3
- package/dist/index.js +3 -1
- package/dist/react.cjs +47 -36
- package/dist/react.d.cts +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/react.js +21 -10
- package/docs/API.md +524 -0
- package/llms.txt +77 -0
- package/package.json +36 -26
- package/src/analytics.ts +322 -0
- package/src/consent.ts +181 -0
- package/src/index.ts +49 -0
- package/src/react.tsx +239 -0
- package/src/types.ts +110 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project are documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project
|
|
6
|
+
adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [0.2.0] - 2026-11-28
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- The package ships version-matched docs for coding agents and other readers: `docs/API.md`
|
|
13
|
+
(every public export with its signature and an example), `llms.txt` and `CHANGELOG.md`.
|
|
14
|
+
`llms.txt` links to these files and to the TypeScript sources in `src/`, which still ship.
|
|
15
|
+
- `maxQueuedEvents` in `AnalyticsConfig` and the `DEFAULT_MAX_QUEUED_EVENTS` constant (`100`): how
|
|
16
|
+
many `track()` and `trackPage()` calls are queued before `initAnalytics()` runs. `0` queues
|
|
17
|
+
nothing; a value that is not a non-negative safe integer means the default.
|
|
18
|
+
|
|
19
|
+
### Changed
|
|
20
|
+
|
|
21
|
+
- The package entry points now resolve to compiled output in `dist` (ESM, CommonJS and type
|
|
22
|
+
declarations) instead of raw TypeScript sources, so it works without transpiling
|
|
23
|
+
`node_modules`. The `.` and `./react` export subpaths and the `react` peer range are
|
|
24
|
+
unchanged. `./package.json` is now exported too. Both builds of `./react` start with
|
|
25
|
+
`"use client"`.
|
|
26
|
+
- **Breaking:** `track()` ignores events whose name is empty or not a string, and `identify()`
|
|
27
|
+
ignores an empty or non-string user id, instead of recording them.
|
|
28
|
+
- **Breaking:** after a stored decline, `AnalyticsProvider` now blocks tracking with
|
|
29
|
+
`disableAnalytics()`, so `track()` calls are dropped. Before, they were queued in memory without
|
|
30
|
+
limit and flushed if the user accepted later.
|
|
31
|
+
- **Breaking:** when `initAnalytics()` is blocked by Do Not Track or a stored decline, it drops the
|
|
32
|
+
events queued before it, as `disableAnalytics()` does. Before, they were kept and flushed by a
|
|
33
|
+
later successful `enableAnalytics()` (after the user accepted, or Do Not Track was turned off).
|
|
34
|
+
- **Breaking:** until `initAnalytics()` runs, only the first 100 `track()` and `trackPage()`
|
|
35
|
+
calls are queued; later calls are dropped. Before, the queue had no size limit.
|
|
36
|
+
To change the limit, set `maxQueuedEvents` in the `config` you pass to `AnalyticsProvider`.
|
|
37
|
+
Without the provider, the limit stays at 100 until `initAnalytics()` runs.
|
|
38
|
+
- The npm description and keywords changed, and `package.json` now lists `homepage`, `bugs`,
|
|
39
|
+
`author` and `funding`.
|
|
40
|
+
- TypeScript users need `@types/react` 18.2.6 or later, because the compiled `./react`
|
|
41
|
+
declarations use `React.JSX.Element`. 0.1.1 shipped TypeScript sources that did not name
|
|
42
|
+
`React.JSX`, so older `@types/react` 18.x versions worked.
|
|
43
|
+
- Internal only: CI, a test that installs the packed package, a docs contract test, and tooling.
|
|
44
|
+
|
|
45
|
+
### Fixed
|
|
46
|
+
|
|
47
|
+
- `getConsentFromCookie()` no longer matches look-alike cookie names that merely end with
|
|
48
|
+
`vllnt-consent` (for example `evil-vllnt-consent=1`).
|
|
49
|
+
- In `AnalyticsProvider` and `useConsent`, `acceptAll` and `declineAnalytics` save the choice with
|
|
50
|
+
their `consentVersion`; `updateConsent` keeps the stored version. Before, they always saved
|
|
51
|
+
version `1`, so a `consentVersion` above `1` asked the user again on every visit.
|
|
52
|
+
- A stored consent choice is now read even when `localStorage` is full, so a stored decline keeps
|
|
53
|
+
tracking blocked. Before, the failed write check made it ignored, so tracking started and
|
|
54
|
+
`AnalyticsProvider` showed the banner again.
|
|
55
|
+
|
|
56
|
+
### Security
|
|
57
|
+
|
|
58
|
+
- `@latest` is now published only from a `vX.Y.Z` tag on `main` that matches `package.json` and
|
|
59
|
+
this changelog. Before, a manual workflow run bumped the version in CI. Publishing still uses
|
|
60
|
+
npm trusted publishing (OIDC) with provenance, as in 0.1.1.
|
|
61
|
+
|
|
62
|
+
## [0.1.1] - 2026-03-10
|
|
63
|
+
|
|
64
|
+
### Added
|
|
65
|
+
|
|
66
|
+
- CI and publish workflows.
|
|
67
|
+
|
|
68
|
+
## [0.1.0] - 2026-03-05
|
|
69
|
+
|
|
70
|
+
### Added
|
|
71
|
+
|
|
72
|
+
- Initial release: event tracking with a pre-initialization queue, two-category consent management
|
|
73
|
+
(localStorage and SSR cookie), versioned consent re-prompts, Do Not Track support, tutorial
|
|
74
|
+
tracking helpers, and React integration (`AnalyticsProvider`, `useAnalytics`, `useConsent`).
|
package/README.md
CHANGED
|
@@ -1,15 +1,19 @@
|
|
|
1
1
|
# @vllnt/analytics
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
## For coding agents
|
|
6
6
|
|
|
7
|
-
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
-
|
|
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
|
|
11
|
+
|
|
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,78 +21,160 @@ Lightweight, privacy-first analytics library with consent management and React i
|
|
|
17
21
|
pnpm add @vllnt/analytics
|
|
18
22
|
```
|
|
19
23
|
|
|
20
|
-
|
|
24
|
+
## Quick start
|
|
25
|
+
|
|
26
|
+
```tsx
|
|
27
|
+
import { track } from "@vllnt/analytics";
|
|
28
|
+
import { AnalyticsProvider, useAnalytics } from "@vllnt/analytics/react";
|
|
29
|
+
|
|
30
|
+
const config = { app: "my-app" };
|
|
31
|
+
|
|
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>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const App = () => (
|
|
38
|
+
<AnalyticsProvider config={config}><Banner /><button onClick={() => track("cta_click")}>Buy</button></AnalyticsProvider>
|
|
39
|
+
);
|
|
40
|
+
```
|
|
41
|
+
|
|
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
|
+
| [`DEFAULT_MAX_QUEUED_EVENTS`](docs/API.md#default_max_queued_events) | `.` | Default `maxQueuedEvents`, `100`. |
|
|
58
|
+
| [`trackTutorialStart`](docs/API.md#tutorial-helpers) | `.` | Tracks a `tutorial_start` event. |
|
|
59
|
+
| [`trackSectionView`](docs/API.md#tutorial-helpers) | `.` | Tracks a `tutorial_section_view` event. |
|
|
60
|
+
| [`trackSectionComplete`](docs/API.md#tutorial-helpers) | `.` | Tracks a `tutorial_section_complete` event. |
|
|
61
|
+
| [`trackTutorialComplete`](docs/API.md#tutorial-helpers) | `.` | Tracks a `tutorial_complete` event. |
|
|
62
|
+
| [`trackTutorialNavigation`](docs/API.md#tutorial-helpers) | `.` | Tracks a `tutorial_navigation` event. |
|
|
63
|
+
| [`trackTimeSpent`](docs/API.md#tutorial-helpers) | `.` | Tracks a `tutorial_time_spent` event. |
|
|
64
|
+
| [`CONSENT_VERSION`](docs/API.md#constants) | `.` | Default consent version, `1`. |
|
|
65
|
+
| [`CONSENT_STORAGE_KEY`](docs/API.md#constants) | `.` | `localStorage` key, `"vllnt:analytics-consent"`. |
|
|
66
|
+
| [`CONSENT_COOKIE_NAME`](docs/API.md#constants) | `.` | Cookie name, `"vllnt-consent"`. |
|
|
67
|
+
| [`loadConsent`](docs/API.md#loadconsent) | `.` | Reads and validates stored consent, or `null`. |
|
|
68
|
+
| [`saveConsent`](docs/API.md#saveconsent) | `.` | Writes consent to `localStorage` and the cookie. |
|
|
69
|
+
| [`clearConsent`](docs/API.md#clearconsent) | `.` | Removes stored consent and expires the cookie. |
|
|
70
|
+
| [`createAcceptAllConsent`](docs/API.md#createacceptallconsent) | `.` | New consent state with everything accepted. |
|
|
71
|
+
| [`createDeclineAnalyticsConsent`](docs/API.md#createdeclineanalyticsconsent) | `.` | New consent state with analytics declined. |
|
|
72
|
+
| [`updateConsentCategory`](docs/API.md#updateconsentcategory) | `.` | Copy of a consent state with one category changed. |
|
|
73
|
+
| [`needsRePrompt`](docs/API.md#needsreprompt) | `.` | `true` when stored consent is older than a version. |
|
|
74
|
+
| [`getConsentFromCookie`](docs/API.md#getconsentfromcookie) | `.` | Parses the consent cookie from a `Cookie` header. |
|
|
75
|
+
| [`isDoNotTrackEnabled`](docs/API.md#isdonottrackenabled) | `.` | `true` when the browser sends Do Not Track. |
|
|
76
|
+
| [`isStorageAvailable`](docs/API.md#isstorageavailable) | `.` | `true` when `localStorage` can be written. |
|
|
77
|
+
| [`isValidConsentState`](docs/API.md#isvalidconsentstate) | `.` | Type guard for a stored consent object. |
|
|
78
|
+
| [`AnalyticsProvider`](docs/API.md#analyticsprovider) | `./react` | Context provider that wires consent to tracking. |
|
|
79
|
+
| [`useAnalytics`](docs/API.md#useanalytics) | `./react` | Provider context: consent state and actions. |
|
|
80
|
+
| [`useConsent`](docs/API.md#useconsent) | `./react` | Standalone consent state; does not start tracking. |
|
|
81
|
+
| [`AnalyticsConfig`](docs/API.md#types) | `.` (type) | `{ app; debug?; maxQueuedEvents?; version? }`. |
|
|
82
|
+
| [`AnalyticsEvent`](docs/API.md#types) | `.` (type) | A queued event: name, properties, timestamp. |
|
|
83
|
+
| [`ConsentCategory`](docs/API.md#types) | `.` (type) | `"analytics" \| "functional"`. |
|
|
84
|
+
| [`ConsentState`](docs/API.md#types) | `.` (type) | Stored consent: categories, timestamp, version. |
|
|
85
|
+
| [`TutorialEventName`](docs/API.md#types) | `.` (type) | Event names used by the tutorial helpers. |
|
|
86
|
+
| [`TutorialEventProperties`](docs/API.md#types) | `.` (type) | Properties for the tutorial helpers. |
|
|
87
|
+
| [`UseConsentOptions`](docs/API.md#types) | `.` (type) | `{ consentVersion? }`. |
|
|
88
|
+
| [`UseConsentReturn`](docs/API.md#types) | `.` (type) | Return value of `useConsent`. |
|
|
89
|
+
|
|
90
|
+
## Common tasks
|
|
91
|
+
|
|
92
|
+
### Show the banner only after mount
|
|
93
|
+
|
|
94
|
+
Stored consent is read in the browser only, so on the server `hasResponded` is `false`. Render the
|
|
95
|
+
banner after mount to avoid a hydration mismatch.
|
|
96
|
+
|
|
97
|
+
```tsx
|
|
98
|
+
import { useEffect, useState } from "react";
|
|
99
|
+
import { useAnalytics } from "@vllnt/analytics/react";
|
|
100
|
+
|
|
101
|
+
export function CookieBanner() {
|
|
102
|
+
const { hasResponded, acceptAll, declineAnalytics } = useAnalytics();
|
|
103
|
+
const [mounted, setMounted] = useState(false);
|
|
104
|
+
useEffect(() => setMounted(true), []);
|
|
105
|
+
if (!mounted || hasResponded) return null;
|
|
106
|
+
return (
|
|
107
|
+
<div>
|
|
108
|
+
<button onClick={acceptAll}>Accept</button>
|
|
109
|
+
<button onClick={declineAnalytics}>Decline</button>
|
|
110
|
+
</div>
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Read consent on the server
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
import { getConsentFromCookie } from "@vllnt/analytics";
|
|
21
119
|
|
|
22
|
-
|
|
120
|
+
export function GET(request: Request): Response {
|
|
121
|
+
const allowed = getConsentFromCookie(request.headers.get("cookie") ?? "");
|
|
122
|
+
return Response.json({ allowed });
|
|
123
|
+
}
|
|
124
|
+
```
|
|
23
125
|
|
|
24
|
-
|
|
126
|
+
### Ask every visitor again after a policy change
|
|
25
127
|
|
|
26
|
-
|
|
128
|
+
Raise `consentVersion`. Stored choices with a lower version are cleared once; new choices are saved
|
|
129
|
+
with the new version.
|
|
27
130
|
|
|
28
131
|
```tsx
|
|
132
|
+
import type { ReactNode } from "react";
|
|
29
133
|
import { AnalyticsProvider } from "@vllnt/analytics/react";
|
|
30
134
|
|
|
31
|
-
|
|
135
|
+
const config = { app: "my-app" };
|
|
136
|
+
|
|
137
|
+
export function Root({ children }: { children: ReactNode }) {
|
|
32
138
|
return (
|
|
33
|
-
<AnalyticsProvider config={{
|
|
139
|
+
<AnalyticsProvider config={config} consentVersion={2}>
|
|
34
140
|
{children}
|
|
35
141
|
</AnalyticsProvider>
|
|
36
142
|
);
|
|
37
143
|
}
|
|
38
144
|
```
|
|
39
145
|
|
|
40
|
-
###
|
|
146
|
+
### Let the visitor change their choice later
|
|
41
147
|
|
|
42
148
|
```tsx
|
|
43
|
-
import {
|
|
44
|
-
|
|
45
|
-
function CookieBanner() {
|
|
46
|
-
const { hasResponded, isLoading, acceptAll, declineAnalytics } = useConsent();
|
|
47
|
-
|
|
48
|
-
if (isLoading || hasResponded) return null;
|
|
149
|
+
import { useAnalytics } from "@vllnt/analytics/react";
|
|
49
150
|
|
|
151
|
+
export function PrivacySettings() {
|
|
152
|
+
const { consent, updateConsent, resetConsent } = useAnalytics();
|
|
50
153
|
return (
|
|
51
154
|
<div>
|
|
52
|
-
<
|
|
53
|
-
|
|
54
|
-
|
|
155
|
+
<label>
|
|
156
|
+
<input
|
|
157
|
+
type="checkbox"
|
|
158
|
+
checked={consent?.analytics ?? false}
|
|
159
|
+
onChange={(event) => updateConsent("analytics", event.target.checked)}
|
|
160
|
+
/>
|
|
161
|
+
Analytics
|
|
162
|
+
</label>
|
|
163
|
+
<button onClick={resetConsent}>Ask me again</button>
|
|
55
164
|
</div>
|
|
56
165
|
);
|
|
57
166
|
}
|
|
58
167
|
```
|
|
59
168
|
|
|
60
|
-
### Track
|
|
169
|
+
### Track page views, users and tutorials
|
|
61
170
|
|
|
62
|
-
```
|
|
63
|
-
import {
|
|
64
|
-
|
|
65
|
-
// Generic event
|
|
66
|
-
track("button_click", { id: "cta-hero" });
|
|
171
|
+
```ts
|
|
172
|
+
import { identify, resetAnalytics, trackPage, trackSectionView } from "@vllnt/analytics";
|
|
67
173
|
|
|
68
|
-
// Page view
|
|
69
174
|
trackPage({ path: "/about" });
|
|
70
|
-
```
|
|
71
|
-
|
|
72
|
-
### Tutorial Tracking
|
|
73
|
-
|
|
74
|
-
Typed helpers for tutorial/content flows:
|
|
75
|
-
|
|
76
|
-
```tsx
|
|
77
|
-
import {
|
|
78
|
-
trackTutorialStart,
|
|
79
|
-
trackSectionView,
|
|
80
|
-
trackSectionComplete,
|
|
81
|
-
trackTutorialComplete,
|
|
82
|
-
trackTutorialNavigation,
|
|
83
|
-
trackTimeSpent,
|
|
84
|
-
} from "@vllnt/analytics";
|
|
85
175
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
tutorial_title: "Getting Started",
|
|
89
|
-
locale: "en",
|
|
90
|
-
total_sections: 5,
|
|
91
|
-
});
|
|
176
|
+
identify("user-123", { plan: "pro" });
|
|
177
|
+
resetAnalytics();
|
|
92
178
|
|
|
93
179
|
trackSectionView({
|
|
94
180
|
tutorial_id: "getting-started",
|
|
@@ -100,108 +186,137 @@ trackSectionView({
|
|
|
100
186
|
});
|
|
101
187
|
```
|
|
102
188
|
|
|
103
|
-
###
|
|
104
|
-
|
|
105
|
-
```tsx
|
|
106
|
-
import { identify, resetAnalytics } from "@vllnt/analytics";
|
|
107
|
-
|
|
108
|
-
// After login
|
|
109
|
-
identify("user-123", { plan: "pro" });
|
|
110
|
-
|
|
111
|
-
// After logout
|
|
112
|
-
resetAnalytics();
|
|
113
|
-
```
|
|
114
|
-
|
|
115
|
-
### Consent Utilities (non-React)
|
|
189
|
+
### Use it without React
|
|
116
190
|
|
|
117
191
|
```ts
|
|
118
192
|
import {
|
|
119
|
-
loadConsent,
|
|
120
|
-
saveConsent,
|
|
121
|
-
clearConsent,
|
|
122
193
|
createAcceptAllConsent,
|
|
123
194
|
createDeclineAnalyticsConsent,
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
195
|
+
disableAnalytics,
|
|
196
|
+
enableAnalytics,
|
|
197
|
+
initAnalytics,
|
|
198
|
+
loadConsent,
|
|
199
|
+
saveConsent,
|
|
127
200
|
} from "@vllnt/analytics";
|
|
128
201
|
|
|
129
|
-
|
|
130
|
-
|
|
202
|
+
const config = { app: "my-app" };
|
|
203
|
+
|
|
204
|
+
// A stored accept starts tracking; a stored decline blocks it and drops queued events.
|
|
205
|
+
if (loadConsent()) initAnalytics(config);
|
|
131
206
|
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
207
|
+
export function onAccept(): void {
|
|
208
|
+
saveConsent(createAcceptAllConsent());
|
|
209
|
+
enableAnalytics(config);
|
|
210
|
+
initAnalytics(config);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export function onDecline(): void {
|
|
214
|
+
saveConsent(createDeclineAnalyticsConsent());
|
|
215
|
+
disableAnalytics();
|
|
136
216
|
}
|
|
137
217
|
```
|
|
138
218
|
|
|
139
|
-
##
|
|
219
|
+
## Errors and fixes
|
|
220
|
+
|
|
221
|
+
The package has no error codes. These are every message it throws or logs as a warning.
|
|
222
|
+
|
|
223
|
+
| Message | Kind | Cause | Fix |
|
|
224
|
+
| --- | --- | --- | --- |
|
|
225
|
+
| `useAnalytics must be used within an AnalyticsProvider` | thrown by `useAnalytics()` | The hook ran outside `<AnalyticsProvider>`. | Render the component inside `<AnalyticsProvider>`, or use `useConsent()`. |
|
|
226
|
+
| `Failed to save consent:` | `console.warn` from `saveConsent()` | The write probe (`isStorageAvailable()`) succeeded, but writing the consent value to `localStorage` or setting the cookie threw, for example because the value did not fit in the space left. On a completely full quota the probe fails first, so `saveConsent()` returns without saving and without this warning. | 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. |
|
|
227
|
+
|
|
228
|
+
## Limits and gotchas
|
|
229
|
+
|
|
230
|
+
- No transport and no event callback: events never leave the page. With `debug: true` they are
|
|
231
|
+
logged with `console.log` as `[analytics:track]`, `[analytics:page]` and similar.
|
|
232
|
+
- Until `initAnalytics()` runs, `track()` and `trackPage()` are queued in memory. The queue keeps
|
|
233
|
+
the first `maxQueuedEvents` calls (default 100, shared by both) and drops later ones; `0` queues
|
|
234
|
+
nothing. `AnalyticsProvider` applies `config.maxQueuedEvents` on mount. Without the provider, the
|
|
235
|
+
default applies until `initAnalytics()` runs; it then keeps only the first `maxQueuedEvents`
|
|
236
|
+
queued events. The first unblocked `initAnalytics()` flushes them; a decline or a Do Not Track
|
|
237
|
+
block drops them. After `resetConsent()`, tracking is blocked and events are dropped until the
|
|
238
|
+
visitor responds again.
|
|
239
|
+
- `identify()` before init or while blocked does nothing; it is not queued.
|
|
240
|
+
- `track()` with an empty or non-string name and `identify()` with an empty or non-string id do
|
|
241
|
+
nothing.
|
|
242
|
+
- `initAnalytics()` runs once: later calls, and later `config` values, are ignored while an
|
|
243
|
+
instance exists. Pass a stable `config` (a module constant) to `AnalyticsProvider`.
|
|
244
|
+
- Once blocked, only `enableAnalytics()` unblocks. It re-reads stored consent, so save the accepted
|
|
245
|
+
consent first, and it does nothing while Do Not Track (`"1"` or `"yes"`) is on.
|
|
246
|
+
- `disableAnalytics()` keeps the user id and traits; call `resetAnalytics()` to clear them.
|
|
247
|
+
- On the server, `track`, `trackPage`, `identify` and `resetAnalytics` do nothing and `loadConsent`
|
|
248
|
+
returns `null`. `initAnalytics` has no server guard: call it only in the browser.
|
|
249
|
+
- When `localStorage` cannot be written (`isStorageAvailable()` is `false`, for example blocked or
|
|
250
|
+
completely full storage), `saveConsent` and `clearConsent` do nothing and log nothing, so a new
|
|
251
|
+
choice lasts for the current page only. `loadConsent` still reads a stored choice whenever
|
|
252
|
+
`localStorage` can be read, so a stored decline keeps tracking blocked, also after an accept that
|
|
253
|
+
could not be saved.
|
|
254
|
+
- `updateConsent("functional", false)` is ignored: functional consent is always on.
|
|
255
|
+
`updateConsent` does nothing while `consent` is `null`.
|
|
256
|
+
- `useConsent()` reads and writes stored consent only; it does not start or stop tracking and does
|
|
257
|
+
not share state with `AnalyticsProvider`.
|
|
258
|
+
- `isLoading` is always `false`.
|
|
259
|
+
- The cookie is `vllnt-consent=1` or `vllnt-consent=0`, with a one-year expiry, `path=/` and
|
|
260
|
+
`SameSite=Lax`, and without `Secure` or `HttpOnly`.
|
|
261
|
+
|
|
262
|
+
```text
|
|
263
|
+
AnalyticsProvider mounts
|
|
264
|
+
├─ Stored consent older than consentVersion ──▶ cleared, banner shown again
|
|
265
|
+
├─ Analytics accepted ──▶ initAnalytics()
|
|
266
|
+
│ ├─ Do Not Track on ──▶ blocked, queue dropped
|
|
267
|
+
│ └─ otherwise ──▶ started, queue flushed
|
|
268
|
+
├─ Analytics declined ──▶ disableAnalytics(); track() calls dropped
|
|
269
|
+
└─ No consent yet ──▶ no init; first maxQueuedEvents track() calls queued in memory
|
|
270
|
+
```
|
|
140
271
|
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
| Function | Description |
|
|
144
|
-
| --------------------------- | ---------------------------------------------- |
|
|
145
|
-
| `initAnalytics(config)` | Initialize analytics singleton |
|
|
146
|
-
| `track(name, properties?)` | Track a custom event (empty names are ignored) |
|
|
147
|
-
| `trackPage(properties?)` | Track a page view |
|
|
148
|
-
| `identify(userId, traits?)` | Identify a user (empty ids are ignored) |
|
|
149
|
-
| `resetAnalytics()` | Clear user identity (logout) |
|
|
150
|
-
| `enableAnalytics(config)` | Re-enable after consent granted |
|
|
151
|
-
| `disableAnalytics()` | Disable after consent revoked |
|
|
152
|
-
| `isAnalyticsEnabled()` | Check if tracking is active |
|
|
153
|
-
|
|
154
|
-
### Consent
|
|
155
|
-
|
|
156
|
-
| Function | Description |
|
|
157
|
-
| ----------------------------------------------- | ---------------------------------------- |
|
|
158
|
-
| `loadConsent()` | Load consent from localStorage |
|
|
159
|
-
| `saveConsent(state)` | Persist consent to localStorage + cookie |
|
|
160
|
-
| `clearConsent()` | Remove consent (triggers re-prompt) |
|
|
161
|
-
| `createAcceptAllConsent()` | Create accept-all consent state |
|
|
162
|
-
| `createDeclineAnalyticsConsent()` | Create analytics-declined state |
|
|
163
|
-
| `updateConsentCategory(state, category, value)` | Update a single category |
|
|
164
|
-
| `needsRePrompt(consent, version)` | Check if version requires re-prompt |
|
|
165
|
-
| `getConsentFromCookie(cookieString)` | Parse consent from cookie (SSR) |
|
|
166
|
-
| `isDoNotTrackEnabled()` | Check browser DNT setting |
|
|
167
|
-
|
|
168
|
-
### React (`@vllnt/analytics/react`)
|
|
169
|
-
|
|
170
|
-
| Export | Description |
|
|
171
|
-
| ---------------------- | ------------------------------------------------- |
|
|
172
|
-
| `AnalyticsProvider` | Context provider — wires consent + analytics init |
|
|
173
|
-
| `useAnalytics()` | Access full analytics context |
|
|
174
|
-
| `useConsent(options?)` | Standalone consent hook for banner UIs |
|
|
175
|
-
|
|
176
|
-
## How It Works
|
|
272
|
+
## Compatibility
|
|
177
273
|
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
│ └─ Analytics accepted ──▶ Initialize & flush queue
|
|
187
|
-
│
|
|
188
|
-
└─ No consent ──▶ Queue events until user responds
|
|
189
|
-
```
|
|
274
|
+
- React: peer range `^18.0.0 || ^19.0.0`, used by `./react` only.
|
|
275
|
+
- TypeScript users need `@types/react` 18.2.6 or later: the `./react` declarations use
|
|
276
|
+
`React.JSX.Element`.
|
|
277
|
+
- Module formats: ESM and CommonJS, with type declarations for both, from `dist/`.
|
|
278
|
+
- `./react` starts with `"use client"` in both builds; the core entry does not, so server code can
|
|
279
|
+
import it.
|
|
280
|
+
- Runtimes: browsers for tracking and consent storage. Server runtimes can import every entry point;
|
|
281
|
+
there, use `getConsentFromCookie` to read consent.
|
|
190
282
|
|
|
191
|
-
|
|
283
|
+
## Testing
|
|
192
284
|
|
|
193
|
-
|
|
285
|
+
The analytics state is a module-level singleton with no public reset. In your tests, clear
|
|
286
|
+
`localStorage` between cases and load the module fresh when a case needs a new instance.
|
|
194
287
|
|
|
195
|
-
|
|
196
|
-
pnpm
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
288
|
+
This repository's own checks: `pnpm lint`, `pnpm typecheck`, `pnpm test:coverage` (Vitest with
|
|
289
|
+
jsdom, 100% coverage gate), `pnpm build` and `pnpm test:package` (installs the packed tarball in a
|
|
290
|
+
clean project with the repo's release-age rule, and imports and type-checks every entry point).
|
|
291
|
+
|
|
292
|
+
## Security
|
|
293
|
+
|
|
294
|
+
Report vulnerabilities privately through
|
|
295
|
+
[GitHub Security Advisories](https://github.com/vllnt/analytics/security/advisories/new). Releases
|
|
296
|
+
are published from CI with npm trusted publishing and provenance.
|
|
297
|
+
|
|
298
|
+
## Related packages
|
|
299
|
+
|
|
300
|
+
None: no other @vllnt package is used together with this one in code.
|
|
301
|
+
|
|
302
|
+
## Contributing
|
|
303
|
+
|
|
304
|
+
See [CONTRIBUTING.md](https://github.com/vllnt/analytics/blob/main/CONTRIBUTING.md). Setup:
|
|
305
|
+
`pnpm install`, then `pnpm lint && pnpm typecheck && pnpm test:coverage && pnpm build && pnpm test:package`.
|
|
306
|
+
|
|
307
|
+
## Links
|
|
308
|
+
|
|
309
|
+
- Docs and changelog: [oss.vllnt.com/packages/analytics](https://oss.vllnt.com/packages/analytics) · [release feed](https://oss.vllnt.com/packages/analytics/rss.xml)
|
|
310
|
+
- All @vllnt packages: [oss.vllnt.com](https://oss.vllnt.com) · [search packages and docs on index.vllnt.com](https://index.vllnt.com)
|
|
311
|
+
- Source and issues: [GitHub](https://github.com/vllnt/analytics) · [issues](https://github.com/vllnt/analytics/issues)
|
|
312
|
+
- Questions and updates: [Discord](https://bntvllnt.com/discord) · [X @bntvllnt](https://x.com/bntvllnt)
|
|
313
|
+
- 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)
|
|
314
|
+
- Sponsor: [GitHub Sponsors](https://github.com/sponsors/bntvllnt)
|
|
204
315
|
|
|
205
316
|
## License
|
|
206
317
|
|
|
207
318
|
[MIT](LICENSE)
|
|
319
|
+
|
|
320
|
+
---
|
|
321
|
+
|
|
322
|
+
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)
|
|
@@ -58,6 +58,14 @@ type AnalyticsConfig = {
|
|
|
58
58
|
app: string;
|
|
59
59
|
/** Enable debug mode */
|
|
60
60
|
debug?: boolean;
|
|
61
|
+
/**
|
|
62
|
+
* How many `track` and `trackPage` calls are queued before `initAnalytics`
|
|
63
|
+
* runs; later calls are dropped. `0` queues nothing. Defaults to
|
|
64
|
+
* `DEFAULT_MAX_QUEUED_EVENTS` (100); any value that is not a non-negative
|
|
65
|
+
* safe integer means the default. `AnalyticsProvider` applies it on mount;
|
|
66
|
+
* without the provider, the default applies until `initAnalytics` runs.
|
|
67
|
+
*/
|
|
68
|
+
maxQueuedEvents?: number;
|
|
61
69
|
/** Application version */
|
|
62
70
|
version?: number;
|
|
63
71
|
};
|
|
@@ -96,15 +104,25 @@ type AnalyticsState = {
|
|
|
96
104
|
version?: number;
|
|
97
105
|
};
|
|
98
106
|
/**
|
|
99
|
-
*
|
|
107
|
+
* Default `maxQueuedEvents`: how many `track` and `trackPage` calls are kept
|
|
108
|
+
* in memory before `initAnalytics` runs.
|
|
109
|
+
*/
|
|
110
|
+
declare const DEFAULT_MAX_QUEUED_EVENTS = 100;
|
|
111
|
+
/**
|
|
112
|
+
* Start the shared analytics instance and flush queued events. Blocks tracking,
|
|
113
|
+
* and drops the queue, when Do Not Track is on or stored consent declines it.
|
|
114
|
+
* @see https://oss.vllnt.com/packages/analytics
|
|
100
115
|
*/
|
|
101
116
|
declare function initAnalytics(config: AnalyticsConfig): void;
|
|
102
117
|
/**
|
|
103
118
|
* Track a custom event. Events with an empty or non-string name are ignored.
|
|
119
|
+
* Before init, only the first `maxQueuedEvents` calls (shared with
|
|
120
|
+
* `trackPage`) are queued.
|
|
104
121
|
*/
|
|
105
122
|
declare function track(name: string, properties?: Record<string, unknown>): void;
|
|
106
123
|
/**
|
|
107
|
-
* Track a page view
|
|
124
|
+
* Track a page view. Before init, it shares the `maxQueuedEvents` limit with
|
|
125
|
+
* `track`.
|
|
108
126
|
*/
|
|
109
127
|
declare function trackPage(properties?: Record<string, unknown>): void;
|
|
110
128
|
/**
|
|
@@ -162,5 +180,5 @@ declare function trackTimeSpent(properties: TutorialEventProperties & {
|
|
|
162
180
|
time_spent_seconds: number;
|
|
163
181
|
}): void;
|
|
164
182
|
|
|
165
|
-
export { disableAnalytics as e, enableAnalytics as f, getAnalyticsState as g, initAnalytics as h, identify as i, isAnalyticsEnabled as j, trackPage as k, trackSectionComplete as l, trackSectionView as m, trackTimeSpent as n, trackTutorialComplete as o, trackTutorialNavigation as p, trackTutorialStart as q, resetAnalytics as r, track as t };
|
|
183
|
+
export { DEFAULT_MAX_QUEUED_EVENTS as D, disableAnalytics as e, enableAnalytics as f, getAnalyticsState as g, initAnalytics as h, identify as i, isAnalyticsEnabled as j, trackPage as k, trackSectionComplete as l, trackSectionView as m, trackTimeSpent as n, trackTutorialComplete as o, trackTutorialNavigation as p, trackTutorialStart as q, resetAnalytics as r, track as t };
|
|
166
184
|
export type { AnalyticsConfig as A, ConsentState as C, TutorialEventName as T, UseConsentOptions as U, ConsentCategory as a, AnalyticsEvent as b, TutorialEventProperties as c, UseConsentReturn as d };
|
|
@@ -58,6 +58,14 @@ type AnalyticsConfig = {
|
|
|
58
58
|
app: string;
|
|
59
59
|
/** Enable debug mode */
|
|
60
60
|
debug?: boolean;
|
|
61
|
+
/**
|
|
62
|
+
* How many `track` and `trackPage` calls are queued before `initAnalytics`
|
|
63
|
+
* runs; later calls are dropped. `0` queues nothing. Defaults to
|
|
64
|
+
* `DEFAULT_MAX_QUEUED_EVENTS` (100); any value that is not a non-negative
|
|
65
|
+
* safe integer means the default. `AnalyticsProvider` applies it on mount;
|
|
66
|
+
* without the provider, the default applies until `initAnalytics` runs.
|
|
67
|
+
*/
|
|
68
|
+
maxQueuedEvents?: number;
|
|
61
69
|
/** Application version */
|
|
62
70
|
version?: number;
|
|
63
71
|
};
|
|
@@ -96,15 +104,25 @@ type AnalyticsState = {
|
|
|
96
104
|
version?: number;
|
|
97
105
|
};
|
|
98
106
|
/**
|
|
99
|
-
*
|
|
107
|
+
* Default `maxQueuedEvents`: how many `track` and `trackPage` calls are kept
|
|
108
|
+
* in memory before `initAnalytics` runs.
|
|
109
|
+
*/
|
|
110
|
+
declare const DEFAULT_MAX_QUEUED_EVENTS = 100;
|
|
111
|
+
/**
|
|
112
|
+
* Start the shared analytics instance and flush queued events. Blocks tracking,
|
|
113
|
+
* and drops the queue, when Do Not Track is on or stored consent declines it.
|
|
114
|
+
* @see https://oss.vllnt.com/packages/analytics
|
|
100
115
|
*/
|
|
101
116
|
declare function initAnalytics(config: AnalyticsConfig): void;
|
|
102
117
|
/**
|
|
103
118
|
* Track a custom event. Events with an empty or non-string name are ignored.
|
|
119
|
+
* Before init, only the first `maxQueuedEvents` calls (shared with
|
|
120
|
+
* `trackPage`) are queued.
|
|
104
121
|
*/
|
|
105
122
|
declare function track(name: string, properties?: Record<string, unknown>): void;
|
|
106
123
|
/**
|
|
107
|
-
* Track a page view
|
|
124
|
+
* Track a page view. Before init, it shares the `maxQueuedEvents` limit with
|
|
125
|
+
* `track`.
|
|
108
126
|
*/
|
|
109
127
|
declare function trackPage(properties?: Record<string, unknown>): void;
|
|
110
128
|
/**
|
|
@@ -162,5 +180,5 @@ declare function trackTimeSpent(properties: TutorialEventProperties & {
|
|
|
162
180
|
time_spent_seconds: number;
|
|
163
181
|
}): void;
|
|
164
182
|
|
|
165
|
-
export { disableAnalytics as e, enableAnalytics as f, getAnalyticsState as g, initAnalytics as h, identify as i, isAnalyticsEnabled as j, trackPage as k, trackSectionComplete as l, trackSectionView as m, trackTimeSpent as n, trackTutorialComplete as o, trackTutorialNavigation as p, trackTutorialStart as q, resetAnalytics as r, track as t };
|
|
183
|
+
export { DEFAULT_MAX_QUEUED_EVENTS as D, disableAnalytics as e, enableAnalytics as f, getAnalyticsState as g, initAnalytics as h, identify as i, isAnalyticsEnabled as j, trackPage as k, trackSectionComplete as l, trackSectionView as m, trackTimeSpent as n, trackTutorialComplete as o, trackTutorialNavigation as p, trackTutorialStart as q, resetAnalytics as r, track as t };
|
|
166
184
|
export type { AnalyticsConfig as A, ConsentState as C, TutorialEventName as T, UseConsentOptions as U, ConsentCategory as a, AnalyticsEvent as b, TutorialEventProperties as c, UseConsentReturn as d };
|