@vllnt/analytics 0.1.1 → 0.2.0-canary.7824f2c

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/docs/API.md ADDED
@@ -0,0 +1,384 @@
1
+ # @vllnt/analytics API
2
+
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/`.
5
+
6
+ The library has no transport. Events are queued and gated by consent, then dropped; with
7
+ `debug: true` they are written to `console.log`. Send them to your own backend yourself.
8
+
9
+ ## Entry points
10
+
11
+ Only these subpaths are exported (`package.json` `exports`). Each has ESM, CommonJS and type
12
+ declarations in `dist/`.
13
+
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 |
19
+
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.
22
+
23
+ Peer dependency: `react` `^18.0.0 || ^19.0.0` (used by `./react` only).
24
+
25
+ All browser APIs are guarded, so importing on the server is safe. On the server `track`,
26
+ `trackPage`, `identify` and `resetAnalytics` return early, `loadConsent` returns `null`, and
27
+ `isStorageAvailable` and `isDoNotTrackEnabled` return `false`. `getConsentFromCookie` only parses
28
+ the string it is given, so it is the consent reader to use on the server. `initAnalytics`,
29
+ `enableAnalytics` and `disableAnalytics` have no server guard: `initAnalytics` on the server
30
+ starts the process-wide instance, so call it only in the browser.
31
+
32
+ ## Tracking (`@vllnt/analytics`)
33
+
34
+ ### `initAnalytics(config: AnalyticsConfig): void`
35
+
36
+ Starts the shared analytics instance and flushes queued events. Later calls do nothing while an
37
+ instance exists. It does not start, and blocks tracking, when Do Not Track is on (`"1"` or
38
+ `"yes"`) or stored consent has `analytics: false`; already queued events are kept, not flushed.
39
+ With no stored consent it starts, so call it only after the user accepts if you need opt-in
40
+ (`AnalyticsProvider` does this for you). Once tracking is blocked (by a blocked init or by
41
+ `disableAnalytics`), calling `initAnalytics` again does not unblock it; only `enableAnalytics`
42
+ does.
43
+
44
+ ```ts
45
+ import { initAnalytics } from "@vllnt/analytics";
46
+
47
+ initAnalytics({ app: "my-app", version: 1, debug: true });
48
+ ```
49
+
50
+ ### `track(name: string, properties?: Record<string, unknown>): void`
51
+
52
+ Records a custom event. Before `initAnalytics` the event is queued; while blocked it is dropped.
53
+ An empty or non-string `name` is ignored.
54
+
55
+ ```ts
56
+ track("button_click", { id: "cta-hero" });
57
+ ```
58
+
59
+ ### `trackPage(properties?: Record<string, unknown>): void`
60
+
61
+ Records a page view, queued before init like `track`.
62
+
63
+ ```ts
64
+ trackPage({ path: "/about" });
65
+ ```
66
+
67
+ ### `identify(userId: string, traits?: Record<string, unknown>): void`
68
+
69
+ Stores a user id and traits on the started instance. Ignored before init, while blocked, or
70
+ when `userId` is empty or not a string. Not queued.
71
+
72
+ ```ts
73
+ identify("user-123", { plan: "pro" });
74
+ ```
75
+
76
+ ### `resetAnalytics(): void`
77
+
78
+ Clears the stored user id and traits (for logout). The instance stays started.
79
+
80
+ ```ts
81
+ resetAnalytics();
82
+ ```
83
+
84
+ ### `enableAnalytics(config: AnalyticsConfig): void`
85
+
86
+ Unblocks, discards the current instance and runs `initAnalytics(config)` again. Does nothing
87
+ unless tracking is currently blocked, and does nothing while Do Not Track is on. Because it
88
+ re-reads stored consent, save the accepted consent first: a stored `analytics: false` blocks it
89
+ again. The new instance has no `userId` or `traits`.
90
+
91
+ ```ts
92
+ saveConsent(createAcceptAllConsent());
93
+ enableAnalytics({ app: "my-app" });
94
+ ```
95
+
96
+ ### `disableAnalytics(): void`
97
+
98
+ Blocks tracking and empties the queue after consent is revoked. It keeps the in-memory user id
99
+ and traits; call `resetAnalytics()` or reload the page to clear them.
100
+
101
+ ```ts
102
+ disableAnalytics();
103
+ resetAnalytics();
104
+ ```
105
+
106
+ ### `isAnalyticsEnabled(): boolean`
107
+
108
+ `true` when the instance has started and is not blocked.
109
+
110
+ ```ts
111
+ if (isAnalyticsEnabled()) track("export_clicked");
112
+ ```
113
+
114
+ ### `getAnalyticsState()`
115
+
116
+ Returns the current instance state for debugging, or `undefined` before init. Shape:
117
+ `{ app: string; debug?: boolean; version?: number; userId?: string; traits?: Record<string, unknown> }`.
118
+ The state type is not exported.
119
+
120
+ ```ts
121
+ console.log(getAnalyticsState()?.userId);
122
+ ```
123
+
124
+ ### Tutorial helpers
125
+
126
+ Typed wrappers around `track` that send fixed event names (`TutorialEventName`). Every helper
127
+ needs `tutorial_id`, `tutorial_title` and `locale`.
128
+
129
+ | Function | Event name | Extra required fields |
130
+ | ------------------------------------- | --------------------------- | ---------------------------------- |
131
+ | `trackTutorialStart(properties)` | `tutorial_start` | none (`section_id` not allowed) |
132
+ | `trackSectionView(properties)` | `tutorial_section_view` | none |
133
+ | `trackSectionComplete(properties)` | `tutorial_section_complete` | none |
134
+ | `trackTutorialComplete(properties)` | `tutorial_complete` | none (`section_id` not allowed) |
135
+ | `trackTutorialNavigation(properties)` | `tutorial_navigation` | `navigation_type` |
136
+ | `trackTimeSpent(properties)` | `tutorial_time_spent` | `time_spent_seconds` |
137
+
138
+ ```ts
139
+ import { trackSectionView, trackTutorialNavigation } from "@vllnt/analytics";
140
+
141
+ const base = { tutorial_id: "intro", tutorial_title: "Intro", locale: "en" };
142
+ trackSectionView({ ...base, section_id: "setup", section_index: 0, total_sections: 5 });
143
+ trackTutorialNavigation({ ...base, section_id: "setup", navigation_type: "next" });
144
+ ```
145
+
146
+ ## Consent (`@vllnt/analytics`)
147
+
148
+ Consent is stored as JSON in `localStorage` under `CONSENT_STORAGE_KEY` and mirrored to the
149
+ `CONSENT_COOKIE_NAME` cookie (`1` allowed, `0` declined; one-year expiry, `path=/`,
150
+ `SameSite=Lax`) so the server can read it.
151
+
152
+ ### Constants
153
+
154
+ | Name | Value |
155
+ | --------------------- | ---------------------------- |
156
+ | `CONSENT_VERSION` | `1` |
157
+ | `CONSENT_STORAGE_KEY` | `"vllnt:analytics-consent"` |
158
+ | `CONSENT_COOKIE_NAME` | `"vllnt-consent"` |
159
+
160
+ ### `loadConsent(): ConsentState | null`
161
+
162
+ Reads and validates stored consent. `null` when none, invalid, or storage is unavailable.
163
+
164
+ ```ts
165
+ const consent = loadConsent();
166
+ ```
167
+
168
+ ### `saveConsent(state: ConsentState): void`
169
+
170
+ Writes consent to `localStorage` and the cookie. Does nothing when storage is unavailable.
171
+
172
+ ```ts
173
+ saveConsent(createAcceptAllConsent());
174
+ ```
175
+
176
+ ### `clearConsent(): void`
177
+
178
+ Removes stored consent and expires the cookie.
179
+
180
+ ```ts
181
+ clearConsent();
182
+ ```
183
+
184
+ ### `createAcceptAllConsent(): ConsentState`
185
+
186
+ New state with `analytics: true`, `functional: true`, the current time and `CONSENT_VERSION`.
187
+
188
+ ```ts
189
+ const accepted = createAcceptAllConsent();
190
+ ```
191
+
192
+ ### `createDeclineAnalyticsConsent(): ConsentState`
193
+
194
+ New state with `analytics: false`, `functional: true`, the current time and `CONSENT_VERSION`.
195
+
196
+ ```ts
197
+ const declined = createDeclineAnalyticsConsent();
198
+ ```
199
+
200
+ ### `updateConsentCategory(current: ConsentState, category: ConsentCategory, value: boolean): ConsentState`
201
+
202
+ Returns a copy with one category changed and a new timestamp. Setting `functional` to `false`
203
+ returns `current` unchanged.
204
+
205
+ ```ts
206
+ const stored = loadConsent();
207
+ if (stored) saveConsent(updateConsentCategory(stored, "analytics", false));
208
+ ```
209
+
210
+ ### `needsRePrompt(consent: ConsentState, currentVersion: number): boolean`
211
+
212
+ `true` when `consent.version < currentVersion`.
213
+
214
+ ```ts
215
+ if (consent && needsRePrompt(consent, 2)) clearConsent();
216
+ ```
217
+
218
+ ### `getConsentFromCookie(cookieString: string): boolean | null`
219
+
220
+ Parses a `Cookie` header: `true` for `1`, `false` for any other value, `null` when the cookie is
221
+ absent. The name must start the string or follow `;`, so `evil-vllnt-consent=1` does not match.
222
+
223
+ ```ts
224
+ const allowed = getConsentFromCookie(request.headers.get("cookie") ?? "");
225
+ ```
226
+
227
+ ### `isDoNotTrackEnabled(): boolean`
228
+
229
+ Reads `navigator.doNotTrack`, then `window.doNotTrack`, then `navigator.msDoNotTrack`, and
230
+ returns `true` when the first one that is set equals `"1"` or `"yes"`. `false` on the server.
231
+
232
+ ```ts
233
+ if (isDoNotTrackEnabled()) hideBanner();
234
+ ```
235
+
236
+ ### `isStorageAvailable(): boolean`
237
+
238
+ `true` when `localStorage` can be written. `false` on the server or when storage throws.
239
+
240
+ ```ts
241
+ if (!isStorageAvailable()) console.warn("consent will not persist");
242
+ ```
243
+
244
+ ### `isValidConsentState(value: unknown): value is ConsentState`
245
+
246
+ Type guard: checks the four fields and their types.
247
+
248
+ ```ts
249
+ const parsed: unknown = JSON.parse(raw);
250
+ if (isValidConsentState(parsed)) saveConsent(parsed);
251
+ ```
252
+
253
+ ## React (`@vllnt/analytics/react`)
254
+
255
+ The ESM build (`dist/react.js`) starts with `"use client"`.
256
+
257
+ Both `AnalyticsProvider` and `useConsent` read stored consent during the first render. On the
258
+ server that read returns `null`, so `consent` is `null` and `hasResponded` is `false` there, while
259
+ the first browser render may already see stored consent. If you render a banner from
260
+ `hasResponded`, render it only after the component has mounted to avoid a hydration mismatch.
261
+
262
+ ### `AnalyticsProvider`
263
+
264
+ ```ts
265
+ function AnalyticsProvider(props: {
266
+ children: ReactNode;
267
+ config: AnalyticsConfig;
268
+ consentVersion?: number; // default CONSENT_VERSION
269
+ }): React.JSX.Element;
270
+ ```
271
+
272
+ Reads stored consent, clears it when `needsRePrompt(stored, consentVersion)`, and calls
273
+ `initAnalytics(config)` while consent has `analytics: true`. Its context actions save consent and
274
+ call `enableAnalytics` or `disableAnalytics`. Pass a stable `config` (for example a module
275
+ constant), because the init effect depends on it.
276
+
277
+ With stored `analytics: false`, the provider does not call `initAnalytics`, so tracking is not
278
+ blocked after a reload: `track()` calls are queued in memory and are flushed if the user accepts
279
+ later. Call `disableAnalytics()` yourself if events from a declined visitor must be dropped.
280
+
281
+ ```tsx
282
+ const config = { app: "my-app", version: 1 };
283
+
284
+ export function Root({ children }: { children: React.ReactNode }) {
285
+ return <AnalyticsProvider config={config}>{children}</AnalyticsProvider>;
286
+ }
287
+ ```
288
+
289
+ ### `useAnalytics()`
290
+
291
+ Returns the provider context; throws `useAnalytics must be used within an AnalyticsProvider`
292
+ outside one. Fields: `config`, `consent`, `hasResponded`, `isLoading` (always `false`),
293
+ `acceptAll()`, `declineAnalytics()`, `updateConsent(category, value)`, `resetConsent()`.
294
+ `updateConsent` does nothing while `consent` is `null` (before the user has responded).
295
+
296
+ ```tsx
297
+ function CookieBanner() {
298
+ const { hasResponded, acceptAll, declineAnalytics } = useAnalytics();
299
+ const [mounted, setMounted] = useState(false);
300
+ useEffect(() => setMounted(true), []);
301
+ if (!mounted || hasResponded) return null;
302
+ return (
303
+ <div>
304
+ <button onClick={acceptAll}>Accept</button>
305
+ <button onClick={declineAnalytics}>Decline</button>
306
+ </div>
307
+ );
308
+ }
309
+ ```
310
+
311
+ ### `useConsent(options?: UseConsentOptions): UseConsentReturn`
312
+
313
+ Standalone consent state with the same fields as `useAnalytics()` except `config`. It reads and
314
+ writes stored consent only: it does not start or stop analytics and does not share state with
315
+ `AnalyticsProvider`. Inside a provider, use `useAnalytics()` for a banner so accepting starts
316
+ tracking.
317
+
318
+ ```tsx
319
+ const { consent, updateConsent } = useConsent({ consentVersion: 1 });
320
+ ```
321
+
322
+ ### `initAnalytics`
323
+
324
+ Re-export of the core `initAnalytics`, for apps that only import from `./react`.
325
+
326
+ ### Consent version caveat
327
+
328
+ `createAcceptAllConsent()` and `createDeclineAnalyticsConsent()` always write
329
+ `CONSENT_VERSION` (`1`), and the hooks use them. With `consentVersion` above `1`, the stored
330
+ consent is older than the requested version on every mount, so it is cleared and the user is
331
+ asked again each visit.
332
+
333
+ ## Types (`@vllnt/analytics`)
334
+
335
+ ```ts
336
+ type AnalyticsConfig = { app: string; debug?: boolean; version?: number };
337
+
338
+ type AnalyticsEvent = {
339
+ name: string;
340
+ properties?: Record<string, unknown>;
341
+ timestamp?: string;
342
+ };
343
+
344
+ type ConsentCategory = "analytics" | "functional";
345
+
346
+ type ConsentState = {
347
+ analytics: boolean;
348
+ functional: boolean;
349
+ timestamp: string; // ISO time of the choice
350
+ version: number;
351
+ };
352
+
353
+ type TutorialEventName =
354
+ | "tutorial_complete"
355
+ | "tutorial_navigation"
356
+ | "tutorial_section_complete"
357
+ | "tutorial_section_view"
358
+ | "tutorial_start"
359
+ | "tutorial_time_spent";
360
+
361
+ type TutorialEventProperties = {
362
+ tutorial_id: string;
363
+ tutorial_title: string;
364
+ locale: string;
365
+ completion_percent?: number; // 0-100
366
+ navigation_type?: "keyboard" | "next" | "prev" | "toc";
367
+ section_id?: string;
368
+ section_index?: number; // 0-based
369
+ time_spent_seconds?: number;
370
+ total_sections?: number;
371
+ };
372
+
373
+ type UseConsentOptions = { consentVersion?: number };
374
+
375
+ type UseConsentReturn = {
376
+ acceptAll: () => void;
377
+ consent: ConsentState | null;
378
+ declineAnalytics: () => void;
379
+ hasResponded: boolean;
380
+ isLoading: boolean;
381
+ resetConsent: () => void;
382
+ updateConsent: (category: ConsentCategory, value: boolean) => void;
383
+ };
384
+ ```
package/llms.txt ADDED
@@ -0,0 +1,56 @@
1
+ # @vllnt/analytics
2
+
3
+ > Lightweight, privacy-first analytics with consent management and React integration.
4
+
5
+ Facts for AI tools. The library has no transport: it queues and gates events, and only
6
+ `console.log`s them when `debug: true`. Bring your own backend.
7
+
8
+ ## For coding agents
9
+
10
+ The docs are bundled in the package at `node_modules/@vllnt/analytics/docs/`, with this file,
11
+ `CHANGELOG.md` and the TypeScript sources in `src/`. They match the installed version. Read them
12
+ before writing code.
13
+
14
+ ## Package
15
+
16
+ - npm: `@vllnt/analytics` (MIT), repo: https://github.com/vllnt/analytics
17
+ - Unreleased builds from `main` use the `canary` dist-tag
18
+ - Ships ESM, CommonJS and type declarations from `dist` (built with tsup)
19
+ - Entry points: `@vllnt/analytics` (core + consent + types), `@vllnt/analytics/react` (`AnalyticsProvider`, `useAnalytics`, `useConsent`, `initAnalytics`)
20
+ - Peer dependency: React `^18.0.0 || ^19.0.0`
21
+ - Install: `pnpm add @vllnt/analytics`
22
+
23
+ ## Behaviour
24
+
25
+ - Events tracked before `initAnalytics()` are queued and flushed on the first unblocked init;
26
+ a blocked init keeps them queued.
27
+ - `initAnalytics()` blocks tracking when Do Not Track is on (`"1"` or `"yes"`) or stored consent
28
+ has `analytics: false`. With no stored consent it starts tracking. `AnalyticsProvider` calls it
29
+ only while consent has `analytics: true`; after a stored decline it does not call it, so events
30
+ stay queued in memory until the user accepts or `disableAnalytics()` is called.
31
+ - Once blocked, only `enableAnalytics(config)` unblocks; it re-reads stored consent.
32
+ - Consent is stored in `localStorage` (`vllnt:analytics-consent`) and a `vllnt-consent` cookie
33
+ (`1` or `0`) for SSR; `getConsentFromCookie(cookieString)` reads it with an anchored match.
34
+ - Consent is versioned (`CONSENT_VERSION`); a lower stored version re-prompts. The hooks always
35
+ save version `CONSENT_VERSION` (`1`), so a `consentVersion` above `1` re-prompts on every visit
36
+ (see `docs/API.md`).
37
+ - `track()` ignores empty or non-string names; `identify()` ignores empty or non-string ids.
38
+ - Browser APIs are guarded, so server-side import is safe. `initAnalytics()` has no server
39
+ guard and starts the process-wide instance there, so call it only in the browser.
40
+
41
+ ## Docs
42
+
43
+ - [API reference](./docs/API.md): every public export, signatures, examples, entry points
44
+ - [README](./README.md): usage and API summary
45
+ - [Changelog](./CHANGELOG.md): release history
46
+ - [Core exports](./src/index.ts) and [React exports](./src/react.tsx): source of the public API
47
+
48
+ ## Optional
49
+
50
+ - [Contributing](https://github.com/vllnt/analytics/blob/main/CONTRIBUTING.md): setup, checks, release flow
51
+ - [Security policy](https://github.com/vllnt/analytics/blob/main/SECURITY.md): private vulnerability reporting
52
+ - [AGENTS.md](https://github.com/vllnt/analytics/blob/main/AGENTS.md): instructions for contributing agents
53
+
54
+ ## Ecosystem
55
+
56
+ - [vllnt oss](https://oss.vllnt.com/llms.txt): index of all vllnt open-source packages
package/package.json CHANGED
@@ -1,66 +1,87 @@
1
1
  {
2
2
  "name": "@vllnt/analytics",
3
- "version": "0.1.1",
3
+ "version": "0.2.0-canary.7824f2c",
4
4
  "description": "Lightweight, privacy-first analytics with consent management and React integration",
5
5
  "type": "module",
6
+ "packageManager": "pnpm@12.22.0",
6
7
  "license": "MIT",
7
8
  "repository": {
8
9
  "type": "git",
9
10
  "url": "git+https://github.com/vllnt/analytics.git"
10
11
  },
12
+ "homepage": "https://oss.vllnt.com/packages/analytics",
11
13
  "keywords": [
12
14
  "analytics",
13
15
  "consent",
14
16
  "privacy",
15
17
  "gdpr",
16
18
  "react",
17
- "do-not-track"
19
+ "do-not-track",
20
+ "cookie-consent",
21
+ "ssr"
18
22
  ],
19
23
  "sideEffects": false,
20
24
  "files": [
25
+ "dist",
21
26
  "src",
22
27
  "!src/__tests__",
23
- "README.md",
24
- "LICENSE"
28
+ "docs/API.md",
29
+ "CHANGELOG.md",
30
+ "llms.txt"
25
31
  ],
26
- "main": "./src/index.ts",
27
- "module": "./src/index.ts",
28
- "types": "./src/index.ts",
32
+ "main": "./dist/index.cjs",
33
+ "module": "./dist/index.js",
34
+ "types": "./dist/index.d.ts",
29
35
  "exports": {
30
36
  ".": {
31
- "types": "./src/index.ts",
32
- "import": "./src/index.ts",
33
- "require": "./src/index.ts"
37
+ "import": {
38
+ "types": "./dist/index.d.ts",
39
+ "default": "./dist/index.js"
40
+ },
41
+ "require": {
42
+ "types": "./dist/index.d.cts",
43
+ "default": "./dist/index.cjs"
44
+ }
34
45
  },
35
46
  "./react": {
36
- "types": "./src/react.tsx",
37
- "import": "./src/react.tsx",
38
- "require": "./src/react.tsx"
39
- }
47
+ "import": {
48
+ "types": "./dist/react.d.ts",
49
+ "default": "./dist/react.js"
50
+ },
51
+ "require": {
52
+ "types": "./dist/react.d.cts",
53
+ "default": "./dist/react.cjs"
54
+ }
55
+ },
56
+ "./package.json": "./package.json"
57
+ },
58
+ "scripts": {
59
+ "build": "tsup",
60
+ "clean": "rm -rf node_modules dist",
61
+ "lint": "eslint --cache --cache-location node_modules/.cache/eslint/ .",
62
+ "lint:fix": "eslint --cache --cache-location node_modules/.cache/eslint/ . --fix",
63
+ "test": "vitest",
64
+ "test:once": "vitest run",
65
+ "test:coverage": "vitest run --coverage",
66
+ "typecheck": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/tsc/typecheck.tsbuildinfo",
67
+ "typecheck:ci": "tsc --noEmit --incremental --tsBuildInfoFile node_modules/.cache/tsc/typecheck-ci.tsbuildinfo"
40
68
  },
41
69
  "peerDependencies": {
42
70
  "react": "^18.0.0 || ^19.0.0"
43
71
  },
44
72
  "devDependencies": {
45
- "eslint": "^9.39.1",
46
- "@testing-library/jest-dom": "^6.9.1",
47
- "@testing-library/react": "^16.3.0",
48
- "@types/node": "^22",
49
- "@types/react": "^19.1.6",
50
- "@vitest/coverage-v8": "^4.0.16",
51
- "@vllnt/eslint-config": "^1.0.0",
52
- "@vllnt/typescript": "^1.0.0",
53
- "jsdom": "^26.1.0",
54
- "react": "^19.2.0",
55
- "typescript": "^5.9.3",
56
- "vitest": "^4.0.16"
57
- },
58
- "scripts": {
59
- "clean": "rm -rf node_modules",
60
- "lint": "eslint .",
61
- "lint:fix": "eslint . --fix",
62
- "test": "vitest",
63
- "test:once": "vitest run",
64
- "test:coverage": "vitest run --coverage"
73
+ "@testing-library/jest-dom": "^8.0.0",
74
+ "@testing-library/react": "^16.3.3",
75
+ "@types/node": "^24.19.2",
76
+ "@types/react": "^19.3.0",
77
+ "@vitest/coverage-v8": "^5.1.1",
78
+ "@vllnt/eslint-config": "^2.1.0",
79
+ "@vllnt/typescript": "^3.0.0",
80
+ "eslint": "^9.39.5",
81
+ "jsdom": "^31.0.1",
82
+ "react": "^19.3.1",
83
+ "tsup": "^9.0.0",
84
+ "typescript": "^6.0.3",
85
+ "vitest": "^5.1.1"
65
86
  }
66
- }
87
+ }
package/src/analytics.ts CHANGED
@@ -49,18 +49,11 @@ function debugLog(type: string, data: unknown): void {
49
49
  }
50
50
 
51
51
  /**
52
- * Send event to analytics endpoint or external service
53
- * This is where you'd integrate with Vercel Analytics, GA, etc.
52
+ * Central tracking point. The library has no transport: events are only
53
+ * logged in debug mode and are not sent anywhere.
54
54
  */
55
55
  function sendEvent(name: string, properties?: Record<string, unknown>): void {
56
56
  debugLog("track", { name, properties });
57
-
58
- // Integration point: Forward to Vercel Analytics or other services
59
- // Vercel Analytics integration is handled by the React provider
60
- // This function serves as the central tracking point
61
-
62
- // For custom backends, you could send to an API endpoint:
63
- // fetch('/api/analytics', { method: 'POST', body: JSON.stringify({ name, properties }) })
64
57
  }
65
58
 
66
59
  /**
@@ -118,13 +111,14 @@ function processQueue(): void {
118
111
  }
119
112
 
120
113
  /**
121
- * Track a custom event
114
+ * Track a custom event. Events with an empty or non-string name are ignored.
122
115
  */
123
116
  export function track(
124
117
  name: string,
125
118
  properties?: Record<string, unknown>,
126
119
  ): void {
127
120
  if (typeof window === "undefined") return;
121
+ if (typeof name !== "string" || name === "") return;
128
122
 
129
123
  if (isBlocked) return;
130
124
 
@@ -162,13 +156,14 @@ export function trackPage(properties?: Record<string, unknown>): void {
162
156
  }
163
157
 
164
158
  /**
165
- * Identify a user
159
+ * Identify a user. An empty or non-string user id is ignored.
166
160
  */
167
161
  export function identify(
168
162
  userId: string,
169
163
  traits?: Record<string, unknown>,
170
164
  ): void {
171
165
  if (typeof window === "undefined") return;
166
+ if (typeof userId !== "string" || userId === "") return;
172
167
  if (isBlocked) return;
173
168
 
174
169
  if (!isInitialized || !analyticsState) {
@@ -238,20 +233,14 @@ export function getAnalyticsState(): AnalyticsState | undefined {
238
233
  export function trackTutorialStart(
239
234
  properties: Omit<TutorialEventProperties, "section_id">,
240
235
  ): void {
241
- track(
242
- "tutorial_start" satisfies TutorialEventName,
243
- properties as Record<string, unknown>,
244
- );
236
+ track("tutorial_start" satisfies TutorialEventName, properties);
245
237
  }
246
238
 
247
239
  /**
248
240
  * Track section view
249
241
  */
250
242
  export function trackSectionView(properties: TutorialEventProperties): void {
251
- track(
252
- "tutorial_section_view" satisfies TutorialEventName,
253
- properties as Record<string, unknown>,
254
- );
243
+ track("tutorial_section_view" satisfies TutorialEventName, properties);
255
244
  }
256
245
 
257
246
  /**
@@ -260,10 +249,7 @@ export function trackSectionView(properties: TutorialEventProperties): void {
260
249
  export function trackSectionComplete(
261
250
  properties: TutorialEventProperties,
262
251
  ): void {
263
- track(
264
- "tutorial_section_complete" satisfies TutorialEventName,
265
- properties as Record<string, unknown>,
266
- );
252
+ track("tutorial_section_complete" satisfies TutorialEventName, properties);
267
253
  }
268
254
 
269
255
  /**
@@ -272,10 +258,7 @@ export function trackSectionComplete(
272
258
  export function trackTutorialComplete(
273
259
  properties: Omit<TutorialEventProperties, "section_id">,
274
260
  ): void {
275
- track(
276
- "tutorial_complete" satisfies TutorialEventName,
277
- properties as Record<string, unknown>,
278
- );
261
+ track("tutorial_complete" satisfies TutorialEventName, properties);
279
262
  }
280
263
 
281
264
  /**
@@ -286,10 +269,7 @@ export function trackTutorialNavigation(
286
269
  navigation_type: "keyboard" | "next" | "prev" | "toc";
287
270
  },
288
271
  ): void {
289
- track(
290
- "tutorial_navigation" satisfies TutorialEventName,
291
- properties as Record<string, unknown>,
292
- );
272
+ track("tutorial_navigation" satisfies TutorialEventName, properties);
293
273
  }
294
274
 
295
275
  /**
@@ -298,8 +278,5 @@ export function trackTutorialNavigation(
298
278
  export function trackTimeSpent(
299
279
  properties: TutorialEventProperties & { time_spent_seconds: number },
300
280
  ): void {
301
- track(
302
- "tutorial_time_spent" satisfies TutorialEventName,
303
- properties as Record<string, unknown>,
304
- );
281
+ track("tutorial_time_spent" satisfies TutorialEventName, properties);
305
282
  }