@vllnt/convex-analytics 0.2.0-canary.d5fa959 → 0.2.0-canary.dee16f7

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.
Files changed (58) hide show
  1. package/CHANGELOG.md +113 -49
  2. package/README.md +461 -157
  3. package/dist/client/index.d.ts +34 -12
  4. package/dist/client/index.d.ts.map +1 -1
  5. package/dist/client/index.js +34 -12
  6. package/dist/client/index.js.map +1 -1
  7. package/dist/client/types.d.ts +9 -5
  8. package/dist/client/types.d.ts.map +1 -1
  9. package/dist/component/convex.config.d.ts +1 -0
  10. package/dist/component/convex.config.d.ts.map +1 -1
  11. package/dist/component/convex.config.js +1 -0
  12. package/dist/component/convex.config.js.map +1 -1
  13. package/dist/component/internal_mutations.d.ts +1 -1
  14. package/dist/component/internal_mutations.d.ts.map +1 -1
  15. package/dist/component/internal_mutations.js +16 -6
  16. package/dist/component/internal_mutations.js.map +1 -1
  17. package/dist/component/mutations.d.ts.map +1 -1
  18. package/dist/component/mutations.js +22 -20
  19. package/dist/component/mutations.js.map +1 -1
  20. package/dist/component/queries.d.ts.map +1 -1
  21. package/dist/component/queries.js +67 -17
  22. package/dist/component/queries.js.map +1 -1
  23. package/dist/component/validators.d.ts +15 -1
  24. package/dist/component/validators.d.ts.map +1 -1
  25. package/dist/component/validators.js +32 -0
  26. package/dist/component/validators.js.map +1 -1
  27. package/dist/react/index.d.ts +2 -3
  28. package/dist/react/index.d.ts.map +1 -1
  29. package/dist/react/index.js +2 -3
  30. package/dist/react/index.js.map +1 -1
  31. package/dist/test.d.ts +3 -1
  32. package/dist/test.d.ts.map +1 -1
  33. package/dist/test.js +3 -1
  34. package/dist/test.js.map +1 -1
  35. package/dist/web/index.d.ts +3 -2
  36. package/dist/web/index.d.ts.map +1 -1
  37. package/dist/web/index.js +2 -1
  38. package/dist/web/index.js.map +1 -1
  39. package/docs/api-reference.md +29 -10
  40. package/docs/architecture.md +33 -20
  41. package/docs/client-sdk.md +358 -140
  42. package/docs/multi-product.md +51 -40
  43. package/docs/quick-start.md +67 -70
  44. package/docs/react.md +146 -0
  45. package/docs/schema.md +13 -9
  46. package/docs/web-preset.md +96 -61
  47. package/llms.txt +43 -25
  48. package/package.json +14 -10
  49. package/src/client/index.ts +34 -12
  50. package/src/client/types.ts +9 -5
  51. package/src/component/convex.config.ts +1 -0
  52. package/src/component/internal_mutations.ts +16 -6
  53. package/src/component/mutations.ts +26 -20
  54. package/src/component/queries.ts +68 -16
  55. package/src/component/validators.ts +39 -0
  56. package/src/react/index.tsx +2 -3
  57. package/src/test.ts +3 -1
  58. package/src/web/index.ts +3 -2
package/README.md CHANGED
@@ -1,66 +1,37 @@
1
- <!-- Badges -->
2
-
3
- [![convex-component](https://img.shields.io/badge/convex-component-EE342F.svg)](https://www.convex.dev/components)
4
- [![npm](https://img.shields.io/npm/v/@vllnt/convex-analytics.svg)](https://www.npmjs.com/package/@vllnt/convex-analytics)
5
- [![CI](https://github.com/vllnt/convex-analytics/actions/workflows/ci.yml/badge.svg)](https://github.com/vllnt/convex-analytics/actions/workflows/ci.yml)
6
- [![license](https://img.shields.io/npm/l/@vllnt/convex-analytics.svg)](LICENSE)
7
-
8
1
  # @vllnt/convex-analytics
9
2
 
10
- A generic, configurable, embedded analytics component for Convex — any event,
11
- any dimension, any domain — with rollup-on-write for reactive aggregate reads.
12
-
13
- ```ts
14
- import { AnalyticsClient } from "@vllnt/convex-analytics";
15
- import { components } from "./_generated/api";
16
-
17
- const analytics = new AnalyticsClient(components.analytics, {
18
- dimensions: ["plan", "country"], // prop keys to roll up on
19
- });
3
+ TypeScript Convex component for event analytics: track events, roll up counts on write, and query metrics, breakdowns, time series, funnels and retention.
20
4
 
21
- await analytics.track(ctx, "signup", {
22
- subjectRef: userId,
23
- props: { plan: "pro", country: "FR" },
24
- });
25
- const byPlan = await analytics.top(ctx, "signup", "plan"); // [{ value: "pro", count: 1 }]
26
- ```
5
+ ![Analytics — @vllnt/convex-analytics](https://raw.githubusercontent.com/vllnt/convex-analytics/main/.github/assets/thumbnail.png)
27
6
 
28
- ## Features
7
+ ## For coding agents
29
8
 
30
- - **Generic events** — free-string event name, opaque `subjectRef` / `sessionRef`, host-typed `props`.
31
- - **Host-declared dimensions** — you pass the prop keys to roll up on; nothing is hardcoded.
32
- - **Rollup-on-write** — counts are incremented as events land. Unfiltered lifetime `metric` reads a fixed-shard counter; ranged/filtered metrics, breakdowns, and time series scan matching rollup rows, not constant-time results.
33
- - **Rich verb set** — `metric`, `top`, `timeseries`, `uniques`, `funnel`, `retention`, `distribution`, plus paginated raw `list`.
34
- - **Configurable** — `scope`, `dimensions`, `granularities`, `retentionDays`, `sampleRate`; sensible defaults, zero config required.
35
- - **Per-session rate limiting + dedupe + sampling** built into `track`.
36
- - **Opt-in web preset** — `@vllnt/convex-analytics/web` adds web dimensions + UA/geo helpers when you want them.
37
- - **Optional React hooks** — `@vllnt/convex-analytics/react` for reactive aggregate reads.
38
- - **Zero hardcoded domain** — no `v.any()`, no baked-in web fields; the host owns meaning and auth.
9
+ Docs for the installed version are in `node_modules/@vllnt/convex-analytics/`: `docs/`, `llms.txt`, `CHANGELOG.md` and the TypeScript `src/`.
10
+ Every signature is in [docs/client-sdk.md](docs/client-sdk.md), [docs/web-preset.md](docs/web-preset.md) (`./web`) and [docs/react.md](docs/react.md) (`./react`); every error is in [Errors and fixes](#errors-and-fixes).
39
11
 
40
- ## Generic core vs web preset
12
+ ## When to use
41
13
 
42
- The core is domain-neutral: it knows nothing about web, mobile, or any vertical.
43
- Web analytics — pageview dimensions (`path`, `referrer`, `device`, `browser`, `os`,
44
- `country`, UTM) plus `parseUserAgent` / `geoFromHeaders` / `trackPageview` helpers —
45
- lives in the opt-in `@vllnt/convex-analytics/web` preset. You turn it on by passing
46
- `webDimensions` to the client's `dimensions` config; otherwise the core ships no web
47
- fields. See [docs/web-preset.md](docs/web-preset.md).
14
+ - Use it when a Convex app needs event counts, breakdowns and time series that its own queries read reactively.
15
+ - Use it when you know the props you slice by up front, so counts can be rolled up as each event is written.
16
+ - Use it when you also need funnels, retention cohorts, distinct-subject counts or histograms over retained raw events.
17
+ - Do not use it when you need cookie-consent state and consent-gated tracking in a React app: use [`@vllnt/analytics`](https://oss.vllnt.com/packages/analytics).
18
+ - Do not use it when you need a per-subject activity feed read back event by event: use [`@vllnt/convex-events`](https://oss.vllnt.com/packages/convex-events).
19
+ - Do not use it when you need A/B variant assignment with exposure tracking: use [`@vllnt/convex-experiments`](https://oss.vllnt.com/packages/convex-experiments).
48
20
 
49
- ## Installation
21
+ ## Install
50
22
 
51
23
  ```bash
52
24
  npm install @vllnt/convex-analytics
53
25
  ```
54
26
 
55
- Requires `convex@^1.45.0` as a peer dependency; React is optional. The command installs
56
- the latest stable release; `@canary` follows `main`.
27
+ This installs the latest stable release; `@canary` follows `main`.
57
28
 
58
- ## Usage
29
+ ## Quick start
59
30
 
60
31
  ```ts
61
32
  // convex/convex.config.ts
62
- import { defineApp } from "convex/server";
63
33
  import analytics from "@vllnt/convex-analytics/convex.config";
34
+ import { defineApp } from "convex/server";
64
35
 
65
36
  const app = defineApp();
66
37
  app.use(analytics);
@@ -68,192 +39,525 @@ export default app;
68
39
  ```
69
40
 
70
41
  ```ts
71
- // convex/analytics.ts — track + read, server-side
42
+ // convex/analytics.ts
72
43
  import { AnalyticsClient } from "@vllnt/convex-analytics";
44
+ import { v } from "convex/values";
45
+
73
46
  import { components } from "./_generated/api";
47
+ import { mutation, query } from "./_generated/server";
74
48
 
75
- type MyProps = { plan?: string; country?: string };
49
+ const analytics = new AnalyticsClient(components.analytics, {
50
+ dimensions: ["plan"], // props keys to roll up on
51
+ });
76
52
 
77
- const analytics = new AnalyticsClient<MyProps>(components.analytics, {
78
- dimensions: ["plan", "country"],
79
- granularities: ["day"],
53
+ export const signup = mutation({
54
+ args: { userId: v.string(), plan: v.string() },
55
+ returns: v.union(v.literal("tracked"), v.literal("dropped"), v.literal("duplicate")),
56
+ handler: async (ctx, { userId, plan }) =>
57
+ await analytics.track(ctx, "signup", { subjectRef: userId, props: { plan } }),
80
58
  });
81
59
 
82
- await analytics.track(ctx, "signup", {
83
- subjectRef: userId,
84
- props: { plan: "pro" },
60
+ export const signupsByPlan = query({
61
+ args: {},
62
+ returns: v.array(v.object({ value: v.string(), count: v.number() })),
63
+ handler: async (ctx) => await analytics.top(ctx, "signup", "plan"),
85
64
  });
86
- const total = await analytics.metric(ctx, "signup");
87
65
  ```
88
66
 
89
- ## Config
67
+ Run `npx convex dev` once to generate `components.analytics`. After one `signup` with
68
+ `plan: "pro"`, `signupsByPlan` returns `[{ value: "pro", count: 1 }]`. The component never
69
+ reads auth: the host decides who may call these functions and what `subjectRef` is.
90
70
 
91
- Passed to the `AnalyticsClient` constructor. All optional — the defaults work with zero config.
71
+ [![npm](https://img.shields.io/npm/v/@vllnt/convex-analytics.svg)](https://www.npmjs.com/package/@vllnt/convex-analytics)
72
+ [![CI](https://github.com/vllnt/convex-analytics/actions/workflows/ci.yml/badge.svg)](https://github.com/vllnt/convex-analytics/actions/workflows/ci.yml)
73
+ [![license](https://img.shields.io/npm/l/@vllnt/convex-analytics.svg)](LICENSE)
92
74
 
93
- | Option | Type | Default | Purpose |
94
- | --------------- | --------------------------------- | ----------- | ----------------------------------------------------------------------------------- |
95
- | `scope` | `string` | `"default"` | Multi-tenant partition; isolates one tenant's data. |
96
- | `dimensions` | `string[]` | `[]` | Prop keys to roll up on (drives rollup-on-write). Empty = count by event name only. |
97
- | `granularities` | `("minute" \| "hour" \| "day")[]` | `["day"]` | Rollup bucket sizes (`minute` for short live windows). Keep `"day"`: see below. |
98
- | `retentionDays` | `number` | `90` | Raw-event TTL in days (rollups are kept forever). Applied via `configure`. |
99
- | `sampleRate` | `number` | `1` | Fraction `0..1` of events to keep at ingest. |
100
- | `sessionIdleMs` | `number` | `1800000` | Idle timeout before a session is closed. Applied via `configure`. |
75
+ ## API
101
76
 
102
- `scope`, `dimensions`, `granularities`, and `sampleRate` apply per call from the client.
103
- `top`, and `metric` with a `range` or `where`, read only `day` rollups: if `granularities`
104
- leaves out `"day"`, they return `[]` and `0`.
105
- `retentionDays`, `sampleRate`, and `sessionIdleMs` are persisted for the prune/close-sessions
106
- crons by calling `analytics.configure(ctx, { ... })` once.
107
- `TProps` is compile-time typing only; validate untrusted props in host wrappers. There is no
108
- `propsValidator` constructor option.
77
+ Full reference: [docs/client-sdk.md](docs/client-sdk.md) (main entry, `./convex.config`,
78
+ `./test`), [docs/web-preset.md](docs/web-preset.md) (`./web`), [docs/react.md](docs/react.md)
79
+ (`./react`), [docs/api-reference.md](docs/api-reference.md) (REST routes).
80
+
81
+ | Export | Import from | What it does |
82
+ | --- | --- | --- |
83
+ | [`AnalyticsClient`](docs/client-sdk.md#analyticsclient) | `@vllnt/convex-analytics` | Host client: `new AnalyticsClient<TProps>(components.analytics, config?)` |
84
+ | [`track(ctx, name, opts?)`](docs/client-sdk.md#track) | `AnalyticsClient` method, mutation | Store one event and bump its rollups; returns `"tracked"`, `"dropped"` or `"duplicate"` |
85
+ | [`metric(ctx, name, opts?)`](docs/client-sdk.md#metric) | `AnalyticsClient` method, query | Event count, optionally in a `range` and filtered by one dimension value |
86
+ | [`top(ctx, name, dimension, opts?)`](docs/client-sdk.md#top) | `AnalyticsClient` method, query | Values of one dimension ranked by count |
87
+ | [`timeseries(ctx, name, opts)`](docs/client-sdk.md#timeseries) | `AnalyticsClient` method, query | Counts per minute, hour or day bucket |
88
+ | [`uniques(ctx, opts)`](docs/client-sdk.md#uniques) | `AnalyticsClient` method, query | Distinct subjects: `dau`, `wau`, `mau`, `trend` |
89
+ | [`funnel(ctx, steps, opts)`](docs/client-sdk.md#funnel) | `AnalyticsClient` method, query | Ordered step conversion per `subjectRef` |
90
+ | [`retention(ctx, opts)`](docs/client-sdk.md#retention) | `AnalyticsClient` method, query | Cohorts by first-seen bucket |
91
+ | [`distribution(ctx, name, measure, opts)`](docs/client-sdk.md#distribution) | `AnalyticsClient` method, query | Histogram of a numeric prop |
92
+ | [`list(ctx, name, paginationOpts, opts?)`](docs/client-sdk.md#list) | `AnalyticsClient` method, query | One page of raw events, newest first |
93
+ | [`configure(ctx, opts?)`](docs/client-sdk.md#configure) | `AnalyticsClient` method, mutation | Store `retentionDays` / `sessionIdleMs` for the crons |
94
+ | [`AnalyticsConfig`](docs/client-sdk.md#analyticsconfig) | `@vllnt/convex-analytics` (type) | Constructor options |
95
+ | [`TrackOpts`](docs/client-sdk.md#trackopts) | `@vllnt/convex-analytics` (type) | Options of `track` |
96
+ | [`TrackResult`](docs/client-sdk.md#trackresult) | `@vllnt/convex-analytics` (type) | `"tracked" \| "dropped" \| "duplicate"` |
97
+ | [`Scalar`](docs/client-sdk.md#scalar) | `@vllnt/convex-analytics` (type) | `string \| number \| boolean \| null` |
98
+ | [`Props`](docs/client-sdk.md#props) | `@vllnt/convex-analytics` (type) | `Record<string, Scalar>` |
99
+ | [`Granularity`](docs/client-sdk.md#granularity) | `@vllnt/convex-analytics`, `./react` (type) | `"minute" \| "hour" \| "day"` |
100
+ | [`Range`](docs/client-sdk.md#range) | `@vllnt/convex-analytics`, `./react` (type) | `{ from?, to? }` in epoch milliseconds |
101
+ | [`Where`](docs/client-sdk.md#where) | `@vllnt/convex-analytics`, `./react` (type) | `{ dim, val }`: one dimension equals one value |
102
+ | [`TopRow`](docs/client-sdk.md#toprow) | `@vllnt/convex-analytics`, `./react` (type) | `{ value, count }` |
103
+ | [`TimeseriesPoint`](docs/client-sdk.md#timeseriespoint) | `@vllnt/convex-analytics`, `./react` (type) | `{ bucket, count }` |
104
+ | [`UniquesView`](docs/client-sdk.md#uniquesview) | `@vllnt/convex-analytics`, `./react` (type) | `{ dau, wau, mau, trend }` |
105
+ | [`FunnelStep`](docs/client-sdk.md#funnelstep) | `@vllnt/convex-analytics` (type) | `{ name, count, rate }` |
106
+ | [`RetentionCohort`](docs/client-sdk.md#retentioncohort) | `@vllnt/convex-analytics` (type) | `{ cohort, size, retained }` |
107
+ | [`DistributionBin`](docs/client-sdk.md#distributionbin) | `@vllnt/convex-analytics` (type) | `{ upper, count }` |
108
+ | [`DistributionView`](docs/client-sdk.md#distributionview) | `@vllnt/convex-analytics` (type) | `{ bins, overflow, count, sum }` |
109
+ | [`PaginationOpts`](docs/client-sdk.md#paginationopts) | `@vllnt/convex-analytics` (type) | `{ numItems, cursor }` |
110
+ | [`EventPage`](docs/client-sdk.md#eventpage) | `@vllnt/convex-analytics` (type) | `{ page, isDone, continueCursor }` |
111
+ | [`EventView`](docs/client-sdk.md#eventview) | `@vllnt/convex-analytics` (type) | One raw event returned by `list` |
112
+ | [`configSet`](docs/client-sdk.md#configset) | `components.analytics.mutations` | Component mutation: store one config value, such as the REST `apiKeys` |
113
+ | [`configGet`](docs/client-sdk.md#configget) | `components.analytics.queries` | Component query: read one stored config value, or `null` |
114
+ | [`default` (component definition)](docs/client-sdk.md#convexconfig-default-export) | `@vllnt/convex-analytics/convex.config` | Pass to `app.use(...)` |
115
+ | [`default` (component definition, `.js` path)](docs/client-sdk.md#convexconfigjs-default-export) | `@vllnt/convex-analytics/convex.config.js` | The same definition under a `.js` specifier |
116
+ | [`ComponentApi`](docs/client-sdk.md#componentapi) | `@vllnt/convex-analytics/_generated/component.js` (type) | Type of `components.analytics` |
117
+ | [`register`](docs/client-sdk.md#register) | `@vllnt/convex-analytics/test` | Mount the component and its child components in `convex-test` |
118
+ | [`default` (test helpers)](docs/client-sdk.md#test-default-export) | `@vllnt/convex-analytics/test` | `{ register, schema, modules }` |
119
+ | [`webDimensions`](docs/web-preset.md#webdimensions) | `@vllnt/convex-analytics/web` | The nine web prop keys to pass as `dimensions` |
120
+ | [`WebDimension`](docs/web-preset.md#webdimension) | `@vllnt/convex-analytics/web` (type) | One key of `webDimensions` |
121
+ | [`parseUserAgent`](docs/web-preset.md#parseuseragent) | `@vllnt/convex-analytics/web` | `User-Agent` to `{ device, browser, os }` |
122
+ | [`UserAgentInfo`](docs/web-preset.md#useragentinfo) | `@vllnt/convex-analytics/web` (type) | Result of `parseUserAgent` |
123
+ | [`geoFromHeaders`](docs/web-preset.md#geofromheaders) | `@vllnt/convex-analytics/web` | Cloudflare / Vercel headers to `{ country, region?, city? }` |
124
+ | [`GeoInfo`](docs/web-preset.md#geoinfo) | `@vllnt/convex-analytics/web` (type) | Result of `geoFromHeaders` |
125
+ | [`trackPageview`](docs/web-preset.md#trackpageview) | `@vllnt/convex-analytics/web` | Build web props and `track` a `"page_view"` event |
126
+ | [`TrackPageviewOpts`](docs/web-preset.md#trackpageviewopts) | `@vllnt/convex-analytics/web` (type) | Options of `trackPageview` |
127
+ | [`Utm`](docs/web-preset.md#utm) | `@vllnt/convex-analytics/web` (type) | `{ source?, medium?, campaign? }` |
128
+ | [`useMetric`](docs/react.md#usemetric) | `@vllnt/convex-analytics/react` | Reactive `metric` through a host query |
129
+ | [`useTop`](docs/react.md#usetop) | `@vllnt/convex-analytics/react` | Reactive `top` through a host query |
130
+ | [`useTimeseries`](docs/react.md#usetimeseries) | `@vllnt/convex-analytics/react` | Reactive `timeseries` through a host query |
131
+ | [`useUniques`](docs/react.md#useuniques) | `@vllnt/convex-analytics/react` | Reactive `uniques` through a host query |
132
+ | [`MetricArgs`](docs/react.md#metricargs) | `@vllnt/convex-analytics/react` (type) | Expected args of the host `metric` query |
133
+ | [`TopArgs`](docs/react.md#topargs) | `@vllnt/convex-analytics/react` (type) | Expected args of the host `top` query |
134
+ | [`TimeseriesArgs`](docs/react.md#timeseriesargs) | `@vllnt/convex-analytics/react` (type) | Expected args of the host `timeseries` query |
135
+ | [`UniquesArgs`](docs/react.md#uniquesargs) | `@vllnt/convex-analytics/react` (type) | Expected args of the host `uniques` query |
136
+
137
+ ## Common tasks
138
+
139
+ Count one dimension value in a date range, as a total and per day:
109
140
 
110
- When `sessionRef` is supplied, ingest uses a token bucket per `(scope, sessionRef)`:
111
- 100 events/minute refill, capacity 10. These limits are currently fixed, not client config.
112
- Exhaustion and sampling both return `"dropped"`; without `sessionRef`, this limiter is skipped.
141
+ ```ts
142
+ // convex/reports.ts
143
+ import { AnalyticsClient } from "@vllnt/convex-analytics";
144
+ import { v } from "convex/values";
113
145
 
114
- ## API
146
+ import { components } from "./_generated/api";
147
+ import { query } from "./_generated/server";
148
+
149
+ const analytics = new AnalyticsClient(components.analytics, { dimensions: ["plan"] });
150
+
151
+ export const proSignups = query({
152
+ args: { from: v.number(), to: v.number() },
153
+ returns: v.object({
154
+ total: v.number(),
155
+ daily: v.array(v.object({ bucket: v.number(), count: v.number() })),
156
+ }),
157
+ handler: async (ctx, { from, to }) => {
158
+ const range = { from, to };
159
+ const where = { dim: "plan", val: "pro" };
160
+ const total = await analytics.metric(ctx, "signup", { range, where });
161
+ const daily = await analytics.timeseries(ctx, "signup", { granularity: "day", range, where });
162
+ return { total, daily };
163
+ },
164
+ });
165
+ ```
115
166
 
116
- | Verb | Kind | Purpose |
117
- | ---------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------- |
118
- | `track(ctx, name, opts)` | mutation | Ingest an event; rollup-on-write + raw event + counter. Returns `"tracked" \| "dropped" \| "duplicate"`. |
119
- | `metric(ctx, name, opts)` | query | Total count over a range, optionally filtered by a dimension value. |
120
- | `top(ctx, name, dimension, opts)` | query | Top values of a dimension (breakdown). |
121
- | `timeseries(ctx, name, opts)` | query | Bucketed counts over a range. |
122
- | `uniques(ctx, opts)` | query | DAU / WAU / MAU from subjects. |
123
- | `funnel(ctx, steps, opts)` | query | Ordered step conversion, keyed by `subjectRef`. |
124
- | `retention(ctx, opts)` | query | Cohort return rates by first-seen period. |
125
- | `distribution(ctx, name, measure, opts)` | query | Histogram of a numeric measure over declared buckets + overflow (with `count` / `sum`). |
126
- | `list(ctx, name, paginationOpts, opts)` | query | Paginated raw events, newest first. |
127
- | `configure(ctx, opts)` | mutation | Persist cron-relevant config (retention / sampling / idle). |
167
+ Count an outcome once, even when the mutation is retried, with your own `dedupeKey`:
128
168
 
129
- `timeseries` and `uniques` require `range` and `granularity`; `funnel` requires `range`;
130
- `retention` requires `cohortRange` and `periods`; `distribution` requires `buckets`.
131
- `list` requires pagination options. See [docs/client-sdk.md](docs/client-sdk.md) for exact types.
169
+ ```ts
170
+ // convex/games.ts
171
+ import { AnalyticsClient } from "@vllnt/convex-analytics";
172
+ import { v } from "convex/values";
132
173
 
133
- ### Optional REST access
174
+ import { components } from "./_generated/api";
175
+ import { mutation } from "./_generated/server";
176
+
177
+ const analytics = new AnalyticsClient(components.analytics, { dimensions: ["puzzleId"] });
178
+
179
+ export const solved = mutation({
180
+ args: { userId: v.string(), puzzleId: v.string(), seconds: v.number() },
181
+ returns: v.boolean(),
182
+ handler: async (ctx, { userId, puzzleId, seconds }) => {
183
+ const result = await analytics.track(ctx, "solved", {
184
+ subjectRef: userId,
185
+ props: { puzzleId, seconds },
186
+ dedupeKey: `${puzzleId}:${userId}`,
187
+ });
188
+ return result === "tracked";
189
+ },
190
+ });
191
+ ```
192
+
193
+ Compare platforms (web against mobile): add a `platform` prop to `dimensions` and read
194
+ `top(ctx, name, "platform")` or a `where: { dim: "platform", val: "ios" }` filter, or give each
195
+ platform its own `scope` ([multi-product](docs/multi-product.md)).
134
196
 
135
- Expose the routes by mounting with `app.use(analytics, { httpPrefix: "/analytics" })`.
136
- Then configure keys from a trusted host mutation (not a public unauthenticated endpoint):
197
+ Funnel, retention and a histogram of a numeric prop:
137
198
 
138
199
  ```ts
139
- await ctx.runMutation(components.analytics.mutations.configSet, {
140
- scope: "default",
141
- key: "apiKeys",
142
- value: JSON.stringify([apiKey]), // host-provided secret; never ship it to the browser
200
+ // convex/insights.ts
201
+ import { AnalyticsClient } from "@vllnt/convex-analytics";
202
+ import { v } from "convex/values";
203
+
204
+ import { components } from "./_generated/api";
205
+ import { query } from "./_generated/server";
206
+
207
+ const analytics = new AnalyticsClient(components.analytics);
208
+
209
+ export const insights = query({
210
+ args: { from: v.number(), to: v.number() },
211
+ returns: v.object({ checkoutRate: v.number(), cohorts: v.number(), underOneMinute: v.number() }),
212
+ handler: async (ctx, { from, to }) => {
213
+ const range = { from, to };
214
+ const steps = await analytics.funnel(ctx, ["view", "add_to_cart", "checkout"], { range });
215
+ const cohorts = await analytics.retention(ctx, { cohortRange: range, periods: 7 });
216
+ const times = await analytics.distribution(ctx, "solved", "seconds", {
217
+ buckets: [60, 300, 900],
218
+ range,
219
+ });
220
+ return {
221
+ checkoutRate: steps.at(-1)?.rate ?? 0,
222
+ cohorts: cohorts.length,
223
+ underOneMinute: times.bins[0]?.count ?? 0,
224
+ };
225
+ },
143
226
  });
144
227
  ```
145
228
 
146
- ```bash
147
- curl -H "x-api-key: $ANALYTICS_API_KEY" \
148
- "https://your-deployment.convex.site/analytics/metric?name=signup"
229
+ Read aggregates reactively in React: re-export a host query, then pass it to a hook:
230
+
231
+ ```ts
232
+ // convex/dashboard.ts
233
+ import { AnalyticsClient } from "@vllnt/convex-analytics";
234
+ import { v } from "convex/values";
235
+
236
+ import { components } from "./_generated/api";
237
+ import { query } from "./_generated/server";
238
+
239
+ const analytics = new AnalyticsClient(components.analytics);
240
+
241
+ export const metric = query({
242
+ args: { name: v.string() },
243
+ returns: v.number(),
244
+ handler: async (ctx, { name }) => await analytics.metric(ctx, name),
245
+ });
246
+ ```
247
+
248
+ ```tsx
249
+ // src/SignupCount.tsx
250
+ import { useMetric } from "@vllnt/convex-analytics/react";
251
+
252
+ import { api } from "../convex/_generated/api";
253
+
254
+ export function SignupCount() {
255
+ const count = useMetric(api.dashboard.metric, { name: "signup" });
256
+ return <p>{count === undefined ? "Loading" : `${String(count)} signups`}</p>;
257
+ }
149
258
  ```
150
259
 
151
- There is no client `configSet` method. Keys are stored per scope; missing/unconfigured/invalid
152
- keys return HTTP 401. See [docs/api-reference.md](docs/api-reference.md).
260
+ Track page views from an HTTP action with the web preset:
153
261
 
154
- ## What it serves
262
+ ```ts
263
+ // convex/http.ts
264
+ import { AnalyticsClient } from "@vllnt/convex-analytics";
265
+ import { trackPageview, webDimensions } from "@vllnt/convex-analytics/web";
266
+ import { httpRouter } from "convex/server";
155
267
 
156
- The Convex-native, authoritative in-app aggregate layer — predefined-dimension rollups served
157
- **reactively** from pre-aggregated rows. It complements a product-analytics warehouse; it doesn't replace one.
158
- Declare the dimensions you'll query; read cost still grows with matching buckets and values; ad-hoc or
159
- retroactive questions over **non-declared** dimensions, or beyond the raw-event retention window,
160
- are an export concern. `metric` / `top` / `timeseries` read pre-aggregated rollups (kept forever);
161
- `funnel` / `distribution` read raw events in range (index-backed, bounded, TTL-pruned) and `retention`
162
- reads per-subject first/last-seen rows.
268
+ import { components } from "./_generated/api";
269
+ import { httpAction } from "./_generated/server";
270
+
271
+ const analytics = new AnalyticsClient(components.analytics, { dimensions: [...webDimensions] });
272
+
273
+ const http = httpRouter();
274
+ http.route({
275
+ path: "/pageview",
276
+ method: "POST",
277
+ handler: httpAction(async (ctx, request) => {
278
+ const body = (await request.json()) as { path: string; referrer?: string };
279
+ await trackPageview(analytics, ctx, {
280
+ path: body.path,
281
+ referrer: body.referrer,
282
+ ua: request.headers.get("user-agent") ?? undefined,
283
+ headers: request.headers,
284
+ });
285
+ return new Response(null, { status: 204 });
286
+ }),
287
+ });
288
+ export default http;
289
+ ```
163
290
 
164
- ## Web preset
291
+ Set raw-event retention and the session idle timeout for the crons (run once, for example
292
+ with `npx convex run setup:configureAnalytics`):
165
293
 
166
294
  ```ts
295
+ // convex/setup.ts
167
296
  import { AnalyticsClient } from "@vllnt/convex-analytics";
168
- import { webDimensions, trackPageview } from "@vllnt/convex-analytics/web";
297
+ import { v } from "convex/values";
298
+
299
+ import { components } from "./_generated/api";
300
+ import { internalMutation } from "./_generated/server";
169
301
 
170
302
  const analytics = new AnalyticsClient(components.analytics, {
171
- dimensions: [...webDimensions], // readonly tuple; `dimensions` takes a string[]
303
+ retentionDays: 30,
304
+ sessionIdleMs: 15 * 60 * 1000,
172
305
  });
173
306
 
174
- await trackPageview(analytics, ctx, {
175
- path: "/pricing",
176
- ua: request.headers.get("user-agent") ?? undefined,
177
- headers: request.headers,
307
+ export const configureAnalytics = internalMutation({
308
+ args: {},
309
+ returns: v.null(),
310
+ handler: async (ctx) => {
311
+ await analytics.configure(ctx);
312
+ return null;
313
+ },
314
+ });
315
+
316
+ export const setApiKey = internalMutation({
317
+ args: { key: v.string() },
318
+ returns: v.null(),
319
+ handler: async (ctx, { key }) => {
320
+ await ctx.runMutation(components.analytics.mutations.configSet, {
321
+ scope: "default",
322
+ key: "apiKeys",
323
+ value: JSON.stringify([key]),
324
+ });
325
+ return null;
326
+ },
178
327
  });
179
328
  ```
180
329
 
181
- `webDimensions` opts the rollups into `path` / `referrer` / `device` / `browser` / `os` /
182
- `country` / UTM; `parseUserAgent` and `geoFromHeaders` build those props from a request.
183
- See [docs/web-preset.md](docs/web-preset.md).
330
+ Expose the REST routes: mount with an `httpPrefix`, store a key with `setApiKey` above, then
331
+ call a route with that key ([REST API](docs/api-reference.md)):
184
332
 
185
- ## React
333
+ ```ts
334
+ // convex/convex.config.ts
335
+ import analytics from "@vllnt/convex-analytics/convex.config";
336
+ import { defineApp } from "convex/server";
186
337
 
187
- ```tsx
188
- import { useMetric, useTop } from "@vllnt/convex-analytics/react";
189
- import { api } from "../convex/_generated/api";
338
+ const app = defineApp();
339
+ app.use(analytics, { httpPrefix: "/analytics" });
340
+ export default app;
341
+ ```
190
342
 
191
- const signups = useMetric(api.analytics.metric, { name: "signup" });
192
- const byPlan = useTop(api.analytics.top, { name: "signup", dimension: "plan" });
343
+ ```bash
344
+ curl -H "x-api-key: $ANALYTICS_API_KEY" \
345
+ "https://<deployment>.convex.site/analytics/metric?name=signup"
193
346
  ```
194
347
 
195
- Thin reactive wrappers over the host's re-exported query refs (`metric`, `top`, `timeseries`,
196
- `uniques`). `react` is an optional peer dep; backend-only consumers pull no React.
348
+ Re-derive rollups after changing `dimensions` (`backfill` is internal to the component, so
349
+ run it from the CLI; it handles one event name per call).
197
350
 
198
- ## Security
351
+ > [!WARNING]
352
+ > `backfill` deletes every rollup row of that `(scope, name)` and rebuilds them only from raw
353
+ > events still retained, so buckets older than `retentionDays` drop to 0. Run it only when the
354
+ > retained raw events cover every bucket you still need.
199
355
 
200
- - Auth-agnostic mount — the host gates access and passes opaque `subjectRef` / `sessionRef` in.
201
- - Tables are sandboxed; the host reaches them only through the exported functions.
202
- - REST endpoints require an `x-api-key` header, compared timing-safe.
203
- - Invalid input (empty strings, `NaN` / infinite timestamps, non-scalar props) is rejected with a typed `ConvexError`; see [docs/api-reference.md](docs/api-reference.md#input-errors).
204
- - The component never logs event data. Props and refs are stored as given, so keep personal data out of them (the web preset stores `path`, `referrer`, and geo as received).
356
+ ```bash
357
+ npx convex run --component analytics internal_mutations:backfill \
358
+ '{"scope":"default","name":"signup","dimensions":["plan"],"granularities":["day"]}'
359
+ ```
205
360
 
206
- See [docs/architecture.md](docs/architecture.md).
361
+ ## Errors and fixes
362
+
363
+ Input errors are a `ConvexError` whose `data` is `{ code, message }`; REST routes return
364
+ them as `400 { "error", "code" }`. Branch on `data.code`.
365
+
366
+ | Error | Cause | Fix |
367
+ | --- | --- | --- |
368
+ | `EMPTY_STRING` | `scope`, `name`, `subjectRef`, `sessionRef`, `dedupeKey`, a `dimensions` entry, a `configSet` `key`, or a read's `dimension`, `where.dim`, `funnel` step or `distribution` `measure` is `""` (writes, reads and `backfill`) | Omit the optional field instead of passing `""`; pass a non-empty value otherwise |
369
+ | `STRING_TOO_LONG` | A write (`track`, `POST /track`, `configSet`, `configure`) got a `scope`, `name`, `subjectRef`, `sessionRef`, `dedupeKey`, `dimensions` entry or config `key` over 512 characters (Unicode code points) | Shorten or hash the value |
370
+ | `INVALID_TIMESTAMP` | `ts`, `range.from` or `range.to` is `NaN` or infinite (REST: a blank or non-numeric `from` / `to`) | Pass epoch milliseconds as finite numbers |
371
+ | `INVALID_SAMPLE_RATE` | `sampleRate` is not a number from 0 to 1 | Use a value in `[0, 1]` |
372
+ | `INVALID_PROP_KEY` | A `props` key is not printable ASCII, is over 1024 characters, or starts with `$` (checked by `POST /track`; Convex rejects such keys first on function calls) | Rename the key |
373
+ | `INVALID_PROP_VALUE` | A `props` value is `NaN`, infinite, an object or an array | Send flat scalar values only |
374
+ | `INVALID_COUNT` | `limit`, `periods` or `numItems` is not a positive integer | Pass an integer of 1 or more |
375
+ | `INVALID_CURSOR` | A `list` cursor is `""`, blank, or not in the form `list` returns | Pass `null` or the previous `continueCursor` |
376
+ | `INVALID_BUCKETS` | A `distribution` bucket bound is `NaN` or infinite | Pass finite numbers |
377
+ | `INVALID_CONFIG` | `retentionDays` or `sessionIdleMs` passed to `configure` or `configSet` is not a positive finite number, or a `configSet` `sampleRate` is not a number from 0 to 1 | Pass a number above 0 (`sampleRate`: from 0 to 1) |
378
+ | `Funnel requires at least 2 steps` | `funnel` got fewer than 2 steps (a plain `Error`, not a `ConvexError`) | Pass 2 or more event names |
379
+ | `backfill requires at most 50000 retained events; existing rollups were preserved` | `backfill` found more than 50,000 raw events for the name (plain `Error`) | Wait for `prune` to remove old events or lower `retentionDays`, then retry |
380
+ | Convex argument validation error | An argument does not match the function validator, for example a nested `props` value or an unknown granularity | Match the types in [docs/client-sdk.md](docs/client-sdk.md) |
381
+ | 401 `Missing x-api-key header` | REST request without `x-api-key` | Send the header |
382
+ | 401 `API keys not configured` | No `apiKeys` config row for the request's `scope`, or the stored value is `""` | Store keys with `configSet` for that scope |
383
+ | 401 `Invalid API key` | The key is not in the scope's `apiKeys` list | Send a stored key or add it |
384
+ | 500 `API keys misconfigured` | The stored `apiKeys` value is not a JSON array of strings | Store `JSON.stringify(["key"])` |
385
+ | 500 without an `error` or `code` from this package | `POST /track` lost a burst of parallel writes after Convex's optimistic concurrency retries ran out (or another unhandled failure, such as a Convex argument-validator error); the event is not stored | Retry a conflict; it is safe to retry. Fix the input for a validator error |
386
+ | 400 `Invalid JSON body` | `POST /track` body is not JSON | Send a JSON body |
387
+ | 400 `Body must be a JSON object` | `POST /track` body is an array, `null` or a scalar | Send a JSON object |
388
+ | 400 `name is required` | `POST /track` without a non-empty string `name` | Add `name` |
389
+ | 400 `dimensions (string[]) is required` | `POST /track` without a `dimensions` string array | Add `"dimensions": []` or your keys |
390
+ | 400 `props must be a flat object of scalar values` | `POST /track` `props` is not an object | Send an object of scalars |
391
+ | 400 `granularities must be an array of minute, hour, or day` | `POST /track` `granularities` has another value | Use `minute`, `hour` or `day` |
392
+ | 400 `name parameter required` | `GET /metric` or `/top` or `/timeseries` without `name` | Add `?name=` |
393
+ | 400 `dimension parameter required` | `GET /top` without `dimension` | Add `&dimension=` |
394
+ | 400 `granularity must be minute, hour, or day` | `GET /timeseries` or `/uniques` with another `granularity` | Use `minute`, `hour` or `day` |
395
+
396
+ ## Limits and gotchas
397
+
398
+ - It serves the in-app counts your Convex functions read; it complements a data warehouse and
399
+ does not replace one. Questions on props not listed in `dimensions` (unless you `backfill`
400
+ while the raw events are retained), or on raw events older than `retentionDays`, need an
401
+ export of the raw events (for example by paging `list`) to your own store.
402
+ - Write throughput per `(scope, name)` is limited by the shared rows every `track` of that name
403
+ updates: its rollup rows and its lifetime counter, and, for calls that share one `sessionRef` or
404
+ `subjectRef`, that session's rate-limit bucket and its session or subject row. Under a burst of
405
+ parallel calls, some fail with an optimistic
406
+ concurrency error (`POST /track`: a 500) and the event is not stored: retry failed calls or
407
+ queue ingest.
408
+ - Writes accept at most 512 characters (Unicode code points) in `scope`, `name`, `subjectRef`,
409
+ `sessionRef`, `dedupeKey`, each `dimensions` entry and a config `key` (`track`, `POST /track`,
410
+ `configSet`, `configure`); longer values throw `STRING_TOO_LONG`. Reads and `backfill` accept
411
+ longer values, so rows stored earlier with them stay readable, but `track`, `configSet` and
412
+ `configure` for those values now throw. On `POST /track` a `scope` that long usually gets
413
+ `401 API keys not configured` first, because `configSet` refuses its `apiKeys` row (a row
414
+ stored before 0.2.0 passes the key check, and then `400` follows).
415
+ - `track` returns `"dropped"` (no error) when sampled out, or when a `sessionRef` exceeds its
416
+ rate limit: a token bucket per `(scope, sessionRef)` refilling 100 events per minute with
417
+ capacity 10. The limit is fixed. Events without `sessionRef` skip the limiter.
418
+ - Only keys listed in `dimensions` are rolled up; other props are stored on the raw event but
419
+ cannot be read with `metric` / `top` / `timeseries`. Changing `dimensions` does not rewrite
420
+ past rollups: run `backfill`, which can only use raw events not yet pruned. Raw events (for
421
+ `funnel`, `distribution`, `list`, `backfill`) are kept only for `retentionDays`. Rollups are
422
+ kept forever unless you run `backfill`: it deletes every rollup row of that name and rebuilds
423
+ them only from raw events still retained, so buckets older than `retentionDays` drop to 0.
424
+ - Rollup values are strings: `true`, `1` and `null` become `"true"`, `"1"` and `"null"`, so
425
+ `top` returns strings and `where: { dim, val: 1 }` also matches the string `"1"`.
426
+ - `top`, and `metric` with a `range` or `where`, read only `day` rollups: if `granularities`
427
+ leaves out `"day"` they return `[]` and `0`. `timeseries` at a granularity you do not write
428
+ returns `[]`. An empty `granularities` array means `["day"]`.
429
+ - `timeseries` returns only buckets that have events; it does not fill gaps with zeros.
430
+ - `metric` without `range` and `where` reads a lifetime counter (16 shards) that `prune` and
431
+ `backfill` never change.
432
+ - `top`: `limit` defaults to 20 and is capped at 100. It reads every `day` rollup row of the
433
+ event name in the range (all dimensions), so its cost grows with the number of dimension values.
434
+ - `metric`, `top`, `timeseries` and `uniques` collect all matching rows, and `list` reads
435
+ `numItems` events per page; very wide ranges, or a very large `numItems` over many events, can
436
+ hit Convex's per-function read and time limits: narrow the range or use a smaller `numItems`.
437
+ - `funnel` reads at most 10,000 events per step, oldest first, and skips events without
438
+ `subjectRef`. Default range: the 30 days before `range.to` (or now).
439
+ - `retention` reads at most 10,000 subjects and caps `periods` at 30. A subject counts only in
440
+ the period of its last event, not in every period it returned.
441
+ - `uniques` counts each subject once, at its last event, among subjects last seen inside
442
+ `range`: `wau` / `mau` are those last seen within 7 / 30 days before `range.to`, so a `range`
443
+ shorter than 30 days caps `mau` at the subjects in that range. `dau` is the rounded mean of the
444
+ `trend`, which has one entry per `granularity` bucket that has a subject (empty buckets are left
445
+ out of both; per hour with `"hour"`), and a subject seen again after
446
+ `range.to` is not counted. Default range: the 30 days before `range.to`.
447
+ - `distribution` reads at most 50,000 events, oldest first, then applies `where`; non-numeric
448
+ measure values are ignored. Default `range.from` is 0.
449
+ - `list` has no page-size cap (`numItems` is read as given).
450
+ - `retentionDays` (default 90) and `sessionIdleMs` (default 30 minutes) take effect only after
451
+ `configure`; until then the crons use the defaults. `configure` also stores `sampleRate`,
452
+ but nothing reads it: `track` uses the client's `sampleRate`. `configSet` accepts only values
453
+ `configure` accepts for these three keys, and the crons ignore a stored value that is not a
454
+ positive finite number.
455
+ - `dedupeKey` matches only retained raw events: after `prune` deletes the first event, the same
456
+ key tracks again.
457
+ - `prune` (cron `analytics:prune-events`) runs every 24 hours and `closeSessions` (cron
458
+ `analytics:close-sessions`) every 30 minutes; each deletes or closes at
459
+ most 500 rows per run and reschedules itself, and they page through scopes 100 at a time.
460
+ - `backfill` reads at most 50,001 events and throws if there are more than 50,000.
461
+ - The `funnel`, `retention`, `distribution` and `backfill` caps are upper bounds: Convex's own
462
+ per-function limits on documents read and execution time can end the call earlier, so narrow
463
+ the range (or, for `backfill`, the retained events) when a call fails.
464
+ - REST routes exist only when the component is mounted with `httpPrefix` (it must start with
465
+ `/`). `GET /metric` ignores `dim` without `val` (and the reverse). `POST /track` ignores a
466
+ `ts`, `subjectRef`, `sessionRef`, `dedupeKey` or `sampleRate` of the wrong type instead of
467
+ rejecting it.
468
+ - REST `scope`: a value that is not a string, or is `""`, silently becomes `"default"`, so the
469
+ request is checked against and writes to the `"default"` scope.
470
+ - `POST /track` rejects invalid JSON and a non-object body with 400 before it checks the API
471
+ key; the other body checks run after the key check.
472
+ - `@convex-dev/aggregate` is mounted as a child component but nothing writes or reads it.
473
+ - Peer warnings: `@convex-dev/aggregate` 0.3.4 pins `convex-helpers@0.1.128` (peer
474
+ `convex ^1.46.0`), so `convex` 1.45 always warns although this package's peer is `^1.45.0`.
475
+ `@convex-dev/batch-worker` accepts a range of `convex-helpers` versions, and newer ones may ask
476
+ for a higher `convex` (`convex-helpers` 0.1.137 asks for `^1.49.0`).
477
+ - Importing `@vllnt/convex-analytics/convex.config` in plain Node fails with
478
+ `ERR_MODULE_NOT_FOUND` inside `@convex-dev/batch-worker`; the Convex CLI bundler loads it fine.
479
+ - `@vllnt/convex-analytics/test` is TypeScript source that calls `import.meta.glob`: run it
480
+ under Vitest (or Vite) with `convex-test`.
481
+
482
+ ## Compatibility
483
+
484
+ - `convex`: peer `^1.45.0`, required. `convex` 1.45.0 itself requires Node 20 or later.
485
+ - `react`: peer `>=18.0.0`, optional; only `@vllnt/convex-analytics/react` imports React. A
486
+ transitive dependency (`@convex-dev/batch-worker` 0.3.3, via `@convex-dev/aggregate`) declares
487
+ `react` as a required peer, so package managers may install it in a backend-only app.
488
+ - Node: `engines` is `>=20`, because `convex` 1.45.0 (the lowest supported peer) requires it.
489
+ - ESM only; there is no CommonJS build.
490
+ - The component's functions run in Convex's default runtime. `./web` helpers are plain
491
+ host-side functions with no dependencies. `./react` hooks need a `ConvexProvider`.
492
+ - CI type-checks the README and docs examples against `convex` 1.45.0.
207
493
 
208
494
  ## Testing
209
495
 
496
+ Run the repository's tests:
497
+
210
498
  ```bash
211
499
  pnpm test
212
500
  ```
213
501
 
502
+ Test host code that uses the component with `convex-test` under Vitest:
503
+
214
504
  ```ts
505
+ // convex/analytics.test.ts
215
506
  import analyticsTest from "@vllnt/convex-analytics/test";
216
507
  import { convexTest } from "convex-test";
508
+ import { expect, test } from "vitest";
509
+
510
+ import { api } from "./_generated/api";
511
+ import schema from "./schema";
217
512
 
218
- const t = convexTest(hostSchema, hostModules);
219
- analyticsTest.register(t);
513
+ const modules = import.meta.glob("./**/*.ts");
514
+
515
+ test("signups are counted by plan", async () => {
516
+ const t = convexTest(schema, modules);
517
+ analyticsTest.register(t);
518
+ await t.mutation(api.analytics.signup, { userId: "u1", plan: "pro" });
519
+ expect(await t.query(api.analytics.signupsByPlan, {})).toEqual([{ value: "pro", count: 1 }]);
520
+ });
220
521
  ```
221
522
 
222
- ## Documentation
523
+ `register(t, name?)` registers the component under `name` (default `"analytics"`) and its
524
+ child components under `<name>/aggregate`, `<name>/shardedCounter` and `<name>/rateLimiter`.
223
525
 
224
- [Schema](docs/schema.md) · [Client SDK](docs/client-sdk.md) · [REST API](docs/api-reference.md) ·
225
- [Web Preset](docs/web-preset.md) · [Multi-Product](docs/multi-product.md) ·
226
- [Architecture](docs/architecture.md) ·
227
- [`llms.txt`](llms.txt) (documentation index).
526
+ ## Security
228
527
 
229
- ## For coding agents
528
+ - The component reads no auth. The host gates every call and passes opaque `subjectRef` /
529
+ `sessionRef` strings in.
530
+ - Component tables are sandboxed: the host reaches them only through the exported functions.
531
+ - REST routes require an `x-api-key` header, compared against the scope's `apiKeys` config
532
+ with a loop that does not stop at the first differing character (it returns early only when
533
+ the lengths differ). Store keys from a trusted internal mutation; never ship them to a browser.
534
+ - Invalid input is rejected with a typed `ConvexError` (see [Errors and fixes](#errors-and-fixes)).
535
+ - The component never logs event data. Props and refs are stored as given, so keep personal
536
+ data out of them; the web preset stores `path`, `referrer` and geo headers as received.
230
537
 
231
- The npm package bundles these docs at `node_modules/@vllnt/convex-analytics/docs/`, along
232
- with `llms.txt`, `CHANGELOG.md` and the TypeScript `src/`. They match the installed version.
233
- Read them before writing code against this package.
538
+ See [docs/architecture.md](docs/architecture.md) and [SECURITY.md](https://github.com/vllnt/convex-analytics/blob/main/SECURITY.md).
234
539
 
235
540
  ## Related packages
236
541
 
237
- | Package | Use it when |
238
- | ------- | ----------- |
239
- | [`@vllnt/analytics`](https://oss.vllnt.com/packages/analytics) | You need browser-side tracking with consent management and React integration. Use this component for counts stored in your Convex backend. |
240
- | [`@vllnt/convex-events`](https://oss.vllnt.com/packages/convex-events) | You need an append-only activity feed and event ledger per subject. Use this component for aggregate counts, breakdowns and trends. |
241
- | [`@vllnt/convex-experiments`](https://oss.vllnt.com/packages/convex-experiments) | You need A/B variant assignment and deduped exposure tracking. Use this component for general event metrics. |
542
+ No public @vllnt package depends on, is tested with, or has an example using this package today.
242
543
 
243
544
  ## Contributing
244
545
 
245
546
  See [CONTRIBUTING.md](https://github.com/vllnt/convex-analytics/blob/main/CONTRIBUTING.md).
246
547
 
247
- ## Author
248
-
249
- Built by [bntvllnt](https://github.com/bntvllnt) · [bntvllnt.com](https://bntvllnt.com) · [X @bntvllnt](https://x.com/bntvllnt)
548
+ ## Links
250
549
 
251
- If this is useful, [sponsor the work](https://github.com/sponsors/bntvllnt).
550
+ - Docs and changelog: [oss.vllnt.com/packages/convex-analytics](https://oss.vllnt.com/packages/convex-analytics) · [release feed](https://oss.vllnt.com/packages/convex-analytics/rss.xml)
551
+ - All @vllnt packages: [oss.vllnt.com](https://oss.vllnt.com) · [search packages and docs on index.vllnt.com](https://index.vllnt.com)
552
+ - Source and issues: [GitHub](https://github.com/vllnt/convex-analytics) · [issues](https://github.com/vllnt/convex-analytics/issues) · [npm](https://www.npmjs.com/package/@vllnt/convex-analytics)
553
+ - Questions and updates: [Discord](https://bntvllnt.com/discord) · [X @bntvllnt](https://x.com/bntvllnt)
554
+ - 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)
555
+ - Sponsor: [GitHub Sponsors](https://github.com/sponsors/bntvllnt)
252
556
 
253
557
  ## License
254
558
 
255
- MIT — see [LICENSE](LICENSE).
559
+ MIT. See [LICENSE](LICENSE).
256
560
 
257
561
  ---
258
562
 
259
- Part of vllnt oss: https://oss.vllnt.com
563
+ Part of [vllnt open source](https://oss.vllnt.com) · [Package page](https://oss.vllnt.com/packages/convex-analytics) · [vllnt.com](https://vllnt.com) · Built by [bntvllnt](https://bntvllnt.com)