@vllnt/convex-analytics 0.1.0 → 0.1.1-canary.879bde1

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 (46) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/README.md +99 -38
  3. package/dist/component/crons.js +1 -1
  4. package/dist/component/crons.js.map +1 -1
  5. package/dist/component/http.d.ts +5 -0
  6. package/dist/component/http.d.ts.map +1 -1
  7. package/dist/component/http.js +76 -21
  8. package/dist/component/http.js.map +1 -1
  9. package/dist/component/internal_mutations.js +4 -4
  10. package/dist/component/internal_mutations.js.map +1 -1
  11. package/dist/component/mutations.d.ts.map +1 -1
  12. package/dist/component/mutations.js +28 -13
  13. package/dist/component/mutations.js.map +1 -1
  14. package/dist/component/queries.d.ts.map +1 -1
  15. package/dist/component/queries.js +57 -58
  16. package/dist/component/queries.js.map +1 -1
  17. package/dist/component/schema.d.ts +2 -4
  18. package/dist/component/schema.js +10 -5
  19. package/dist/component/schema.js.map +1 -1
  20. package/dist/component/validators.d.ts +27 -0
  21. package/dist/component/validators.d.ts.map +1 -1
  22. package/dist/component/validators.js +54 -1
  23. package/dist/component/validators.js.map +1 -1
  24. package/dist/react/index.d.ts +1 -1
  25. package/dist/react/index.js +1 -1
  26. package/dist/test.d.ts +2 -4
  27. package/dist/web/index.d.ts +2 -2
  28. package/dist/web/index.js +2 -2
  29. package/docs/api-reference.md +132 -0
  30. package/docs/architecture.md +70 -0
  31. package/docs/client-sdk.md +249 -0
  32. package/docs/multi-product.md +69 -0
  33. package/docs/quick-start.md +115 -0
  34. package/docs/schema.md +135 -0
  35. package/docs/web-preset.md +104 -0
  36. package/llms.txt +37 -0
  37. package/package.json +39 -27
  38. package/src/component/crons.ts +1 -1
  39. package/src/component/http.ts +78 -21
  40. package/src/component/internal_mutations.ts +5 -5
  41. package/src/component/mutations.ts +37 -15
  42. package/src/component/queries.ts +83 -64
  43. package/src/component/schema.ts +10 -5
  44. package/src/component/validators.ts +80 -1
  45. package/src/react/index.tsx +1 -1
  46. package/src/web/index.ts +2 -2
@@ -1,6 +1,9 @@
1
1
  import { httpRouter } from "convex/server";
2
- import { httpAction } from "./_generated/server";
3
- import { api } from "./_generated/api";
2
+ import { ConvexError } from "convex/values";
3
+ import { httpAction } from "./_generated/server.js";
4
+ import type { ActionCtx } from "./_generated/server.js";
5
+ import { assertProps } from "./validators.js";
6
+ import { api } from "./_generated/api.js";
4
7
 
5
8
  function json(data: unknown, status = 200): Response {
6
9
  return new Response(JSON.stringify(data), {
@@ -13,6 +16,27 @@ function error(message: string, status = 400): Response {
13
16
  return json({ error: message }, status);
14
17
  }
15
18
 
19
+ /**
20
+ * Run a handler body and turn a typed input error from the component (a `ConvexError`
21
+ * with `{ code, message }`) into `400 { error, code }`. Anything else still fails the action.
22
+ */
23
+ export async function withInputErrors(run: () => Promise<Response>): Promise<Response> {
24
+ try {
25
+ return await run();
26
+ } catch (e) {
27
+ const data: unknown = e instanceof ConvexError ? e.data : undefined;
28
+ if (typeof data === "object" && data !== null && "code" in data && "message" in data) {
29
+ return json({ error: String(data.message), code: String(data.code) }, 400);
30
+ }
31
+ throw e;
32
+ }
33
+ }
34
+
35
+ /** An `httpAction` whose typed input errors are returned as 400 responses. */
36
+ function handle(fn: (ctx: ActionCtx, request: Request) => Promise<Response>) {
37
+ return httpAction((ctx, request) => withInputErrors(() => fn(ctx, request)));
38
+ }
39
+
16
40
  function timingSafeEqual(a: string, b: string): boolean {
17
41
  if (a.length !== b.length) return false;
18
42
  let result = 0;
@@ -26,6 +50,16 @@ function scopeOf(value: unknown): string {
26
50
  return typeof value === "string" && value.length > 0 ? value : "default";
27
51
  }
28
52
 
53
+ /** The stored `apiKeys` value as a string array, or `null` when it is not one. */
54
+ function parseApiKeys(raw: string): string[] | null {
55
+ try {
56
+ const keys: unknown = JSON.parse(raw);
57
+ return Array.isArray(keys) && keys.every((k) => typeof k === "string") ? keys : null;
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+
29
63
  /**
30
64
  * Gate a request by API key. Keys are a JSON string array stored at config
31
65
  * `(scope, "apiKeys")`. Returns an error Response on failure, else null.
@@ -42,7 +76,8 @@ async function requireApiKey(
42
76
  key: "apiKeys",
43
77
  } as never);
44
78
  if (!config) return error("API keys not configured", 401);
45
- const keys = JSON.parse(config as string) as string[];
79
+ const keys = parseApiKeys(config as string);
80
+ if (keys === null) return error("API keys misconfigured", 500);
46
81
  const matched = keys.some((stored) => timingSafeEqual(stored, key));
47
82
  if (!matched) return error("Invalid API key", 401);
48
83
  return null;
@@ -61,19 +96,32 @@ function getParams(request: Request): URLSearchParams {
61
96
  return new URL(request.url).searchParams;
62
97
  }
63
98
 
99
+ /** A numeric query param; blank or malformed values become NaN so the component rejects them. */
100
+ function numberParam(params: URLSearchParams, name: string): number | undefined {
101
+ const raw = params.get(name);
102
+ if (raw === null) return undefined;
103
+ return raw.trim() === "" ? NaN : Number(raw);
104
+ }
105
+
64
106
  function range(params: URLSearchParams): { from?: number; to?: number } | undefined {
65
- const from = params.get("from");
66
- const to = params.get("to");
67
- if (from === null && to === null) return undefined;
68
- return {
69
- from: from !== null ? Number(from) : undefined,
70
- to: to !== null ? Number(to) : undefined,
71
- };
107
+ const from = numberParam(params, "from");
108
+ const to = numberParam(params, "to");
109
+ if (from === undefined && to === undefined) return undefined;
110
+ return { from, to };
72
111
  }
73
112
 
74
- export const trackEndpoint = httpAction(async (ctx, request) => {
113
+ const GRANULARITIES = ["minute", "hour", "day"];
114
+
115
+ function isStringArray(value: unknown): value is string[] {
116
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
117
+ }
118
+
119
+ export const trackEndpoint = handle(async (ctx, request) => {
75
120
  const parsed = await parseJsonSafe(request);
76
121
  if (!parsed.ok) return error("Invalid JSON body");
122
+ if (typeof parsed.data !== "object" || parsed.data === null || Array.isArray(parsed.data)) {
123
+ return error("Body must be a JSON object");
124
+ }
77
125
  const body = parsed.data as Record<string, unknown>;
78
126
 
79
127
  const scope = scopeOf(body["scope"]);
@@ -83,27 +131,36 @@ export const trackEndpoint = httpAction(async (ctx, request) => {
83
131
  if (typeof body["name"] !== "string" || body["name"].length === 0) {
84
132
  return error("name is required");
85
133
  }
86
- if (!Array.isArray(body["dimensions"])) {
134
+ if (!isStringArray(body["dimensions"])) {
87
135
  return error("dimensions (string[]) is required");
88
136
  }
137
+ const props = body["props"] ?? undefined;
138
+ if (props !== undefined && (typeof props !== "object" || Array.isArray(props))) {
139
+ return error("props must be a flat object of scalar values");
140
+ }
141
+ if (props !== undefined) assertProps(props as Record<string, unknown>);
142
+ const granularities = body["granularities"] ?? ["day"];
143
+ if (!isStringArray(granularities) || !granularities.every((g) => GRANULARITIES.includes(g))) {
144
+ return error("granularities must be an array of minute, hour, or day");
145
+ }
89
146
 
90
147
  const result = await ctx.runMutation(api.mutations.track as never, {
91
148
  scope,
92
149
  name: body["name"],
93
150
  subjectRef: typeof body["subjectRef"] === "string" ? body["subjectRef"] : undefined,
94
151
  sessionRef: typeof body["sessionRef"] === "string" ? body["sessionRef"] : undefined,
95
- props: body["props"] ?? undefined,
152
+ props,
96
153
  ts: typeof body["ts"] === "number" ? body["ts"] : undefined,
97
154
  dedupeKey: typeof body["dedupeKey"] === "string" ? body["dedupeKey"] : undefined,
98
155
  dimensions: body["dimensions"],
99
- granularities: Array.isArray(body["granularities"]) ? body["granularities"] : ["day"],
156
+ granularities,
100
157
  sampleRate: typeof body["sampleRate"] === "number" ? body["sampleRate"] : undefined,
101
158
  } as never);
102
159
 
103
160
  return json({ result }, 201);
104
161
  });
105
162
 
106
- export const metricEndpoint = httpAction(async (ctx, request) => {
163
+ export const metricEndpoint = handle(async (ctx, request) => {
107
164
  const params = getParams(request);
108
165
  const scope = scopeOf(params.get("scope"));
109
166
  const authError = await requireApiKey(ctx, request, scope);
@@ -124,7 +181,7 @@ export const metricEndpoint = httpAction(async (ctx, request) => {
124
181
  return json({ name, count });
125
182
  });
126
183
 
127
- export const topEndpoint = httpAction(async (ctx, request) => {
184
+ export const topEndpoint = handle(async (ctx, request) => {
128
185
  const params = getParams(request);
129
186
  const scope = scopeOf(params.get("scope"));
130
187
  const authError = await requireApiKey(ctx, request, scope);
@@ -140,13 +197,13 @@ export const topEndpoint = httpAction(async (ctx, request) => {
140
197
  name,
141
198
  dimension,
142
199
  range: range(params),
143
- limit: params.get("limit") ? Number(params.get("limit")) : undefined,
200
+ limit: numberParam(params, "limit"),
144
201
  } as never);
145
202
 
146
203
  return json(result);
147
204
  });
148
205
 
149
- export const timeseriesEndpoint = httpAction(async (ctx, request) => {
206
+ export const timeseriesEndpoint = handle(async (ctx, request) => {
150
207
  const params = getParams(request);
151
208
  const scope = scopeOf(params.get("scope"));
152
209
  const authError = await requireApiKey(ctx, request, scope);
@@ -155,7 +212,7 @@ export const timeseriesEndpoint = httpAction(async (ctx, request) => {
155
212
  const name = params.get("name");
156
213
  if (!name) return error("name parameter required");
157
214
  const granularity = params.get("granularity") ?? "day";
158
- if (granularity !== "minute" && granularity !== "hour" && granularity !== "day") {
215
+ if (!GRANULARITIES.includes(granularity)) {
159
216
  return error("granularity must be minute, hour, or day");
160
217
  }
161
218
 
@@ -169,14 +226,14 @@ export const timeseriesEndpoint = httpAction(async (ctx, request) => {
169
226
  return json(result);
170
227
  });
171
228
 
172
- export const uniquesEndpoint = httpAction(async (ctx, request) => {
229
+ export const uniquesEndpoint = handle(async (ctx, request) => {
173
230
  const params = getParams(request);
174
231
  const scope = scopeOf(params.get("scope"));
175
232
  const authError = await requireApiKey(ctx, request, scope);
176
233
  if (authError) return authError;
177
234
 
178
235
  const granularity = params.get("granularity") ?? "day";
179
- if (granularity !== "minute" && granularity !== "hour" && granularity !== "day") {
236
+ if (!GRANULARITIES.includes(granularity)) {
180
237
  return error("granularity must be minute, hour, or day");
181
238
  }
182
239
 
@@ -1,6 +1,6 @@
1
- import { internal } from "./_generated/api";
2
- import { internalMutation } from "./_generated/server";
3
- import type { MutationCtx } from "./_generated/server";
1
+ import { internal } from "./_generated/api.js";
2
+ import { internalMutation } from "./_generated/server.js";
3
+ import type { MutationCtx } from "./_generated/server.js";
4
4
  import { v } from "convex/values";
5
5
  import { granularitiesValidator } from "./validators.js";
6
6
  import { bucketStart, valKey } from "../shared.js";
@@ -163,7 +163,7 @@ export const backfill = internalMutation({
163
163
 
164
164
  const existing = await ctx.db
165
165
  .query("rollups")
166
- .withIndex("by_scope_name_dim_val", (q) =>
166
+ .withIndex("by_scope_name_gran_dim_val_bucket", (q) =>
167
167
  q.eq("scope", args.scope).eq("name", args.name),
168
168
  )
169
169
  .collect();
@@ -185,7 +185,7 @@ export const backfill = internalMutation({
185
185
  const bucket = bucketStart(e.ts, gran);
186
186
  bump(gran, bucket, TOTAL, TOTAL);
187
187
  for (const dim of args.dimensions) {
188
- if (dim in e.props) {
188
+ if (Object.hasOwn(e.props, dim)) {
189
189
  bump(gran, bucket, dim, valKey(e.props[dim]!));
190
190
  }
191
191
  }
@@ -1,16 +1,21 @@
1
- import { mutation } from "./_generated/server";
2
- import type { MutationCtx } from "./_generated/server";
3
- import { components } from "./_generated/api";
1
+ import { mutation } from "./_generated/server.js";
2
+ import type { MutationCtx } from "./_generated/server.js";
3
+ import { components } from "./_generated/api.js";
4
4
  import { v } from "convex/values";
5
- import { DirectAggregate } from "@convex-dev/aggregate";
6
5
  import { ShardedCounter } from "@convex-dev/sharded-counter";
7
6
  import { RateLimiter, MINUTE } from "@convex-dev/rate-limiter";
8
- import { propsValidator, granularitiesValidator } from "./validators.js";
7
+ import {
8
+ propsValidator,
9
+ granularitiesValidator,
10
+ assertProps,
11
+ assertFiniteTs,
12
+ assertNonEmpty,
13
+ assertSampleRate,
14
+ invalidInput,
15
+ } from "./validators.js";
9
16
  import { bucketStart, tupleKey, valKey } from "../shared.js";
10
17
  import type { Granularity, Scalar } from "../shared.js";
11
18
 
12
- type AggregateType = { Key: number; Id: string; Namespace: string };
13
- const aggregate = new DirectAggregate<AggregateType>(components.aggregate as never);
14
19
  const counter = new ShardedCounter(components.shardedCounter as never, {
15
20
  defaultShards: 16,
16
21
  });
@@ -87,10 +92,20 @@ export const track = mutation({
87
92
  },
88
93
  returns: v.union(v.literal("tracked"), v.literal("dropped"), v.literal("duplicate")),
89
94
  handler: async (ctx, args) => {
95
+ assertNonEmpty("scope", args.scope);
96
+ assertNonEmpty("name", args.name);
97
+ assertNonEmpty("subjectRef", args.subjectRef);
98
+ assertNonEmpty("sessionRef", args.sessionRef);
99
+ assertNonEmpty("dedupeKey", args.dedupeKey);
100
+ for (const dim of args.dimensions) assertNonEmpty("dimensions[]", dim);
101
+ assertFiniteTs("ts", args.ts);
102
+ assertSampleRate(args.sampleRate);
103
+ const props: Record<string, Scalar> = args.props ?? {};
104
+ assertProps(props);
105
+
90
106
  const now = Date.now();
91
107
  const scope = args.scope;
92
108
  const ts = args.ts ?? now;
93
- const props: Record<string, Scalar> = args.props ?? {};
94
109
  const grans = args.granularities.length > 0 ? args.granularities : (["day"] as const);
95
110
 
96
111
  if (args.sessionRef !== undefined) {
@@ -132,7 +147,7 @@ export const track = mutation({
132
147
 
133
148
  await ensureScope(ctx, scope);
134
149
 
135
- const eventId = await ctx.db.insert("events", {
150
+ await ctx.db.insert("events", {
136
151
  scope,
137
152
  name: args.name,
138
153
  subjectRef: args.subjectRef,
@@ -191,7 +206,7 @@ export const track = mutation({
191
206
  const bucket = bucketStart(ts, granularity);
192
207
  await bumpRollup(ctx, scope, args.name, granularity, bucket, TOTAL, TOTAL);
193
208
  for (const dim of args.dimensions) {
194
- if (dim in props) {
209
+ if (Object.hasOwn(props, dim)) {
195
210
  await bumpRollup(
196
211
  ctx,
197
212
  scope,
@@ -205,11 +220,6 @@ export const track = mutation({
205
220
  }
206
221
  }
207
222
 
208
- await aggregate.insert(ctx, {
209
- key: ts,
210
- id: eventId as string,
211
- namespace: tupleKey(scope, args.name),
212
- });
213
223
  await counter.add(ctx, tupleKey(scope, args.name));
214
224
 
215
225
  return "tracked";
@@ -238,6 +248,8 @@ export const configSet = mutation({
238
248
  args: { scope: v.string(), key: v.string(), value: v.string() },
239
249
  returns: v.null(),
240
250
  handler: async (ctx, args) => {
251
+ assertNonEmpty("scope", args.scope);
252
+ assertNonEmpty("key", args.key);
241
253
  await ensureScope(ctx, args.scope);
242
254
  await upsertConfig(ctx, args.scope, args.key, args.value);
243
255
  return null;
@@ -253,6 +265,16 @@ export const configure = mutation({
253
265
  },
254
266
  returns: v.null(),
255
267
  handler: async (ctx, args) => {
268
+ assertNonEmpty("scope", args.scope);
269
+ assertSampleRate(args.sampleRate);
270
+ for (const [field, value] of [
271
+ ["retentionDays", args.retentionDays],
272
+ ["sessionIdleMs", args.sessionIdleMs],
273
+ ] as const) {
274
+ if (value !== undefined && !(Number.isFinite(value) && value > 0)) {
275
+ throw invalidInput("INVALID_CONFIG", `${field} must be a positive finite number`);
276
+ }
277
+ }
256
278
  await ensureScope(ctx, args.scope);
257
279
  const entries: Array<[string, string]> = [];
258
280
  if (args.retentionDays !== undefined) {
@@ -1,5 +1,7 @@
1
- import { query } from "./_generated/server";
2
- import { components } from "./_generated/api";
1
+ import { query } from "./_generated/server.js";
2
+ import type { QueryCtx } from "./_generated/server.js";
3
+ import type { Doc } from "./_generated/dataModel.js";
4
+ import { components } from "./_generated/api.js";
3
5
  import { v } from "convex/values";
4
6
  import { ShardedCounter } from "@convex-dev/sharded-counter";
5
7
  import {
@@ -13,6 +15,9 @@ import {
13
15
  retentionCohort,
14
16
  eventPage,
15
17
  distributionView,
18
+ assertCount,
19
+ assertRange,
20
+ invalidInput,
16
21
  } from "./validators.js";
17
22
  import { bucketStart, bucketSize, tupleKey, valKey } from "../shared.js";
18
23
  import type { Granularity } from "../shared.js";
@@ -23,6 +28,58 @@ const counter = new ShardedCounter(components.shardedCounter as never, {
23
28
 
24
29
  const TOTAL = "";
25
30
 
31
+ /**
32
+ * Rollup rows for `(scope, name, granularity)` with `bucket` inside the range, read through
33
+ * the index so only buckets in range are loaded. Bounds are inclusive and bucket-aligned.
34
+ */
35
+ async function rollupsInRange(
36
+ ctx: QueryCtx,
37
+ scope: string,
38
+ name: string,
39
+ granularity: Granularity,
40
+ range: { from?: number; to?: number } | undefined,
41
+ ): Promise<Doc<"rollups">[]> {
42
+ const lo = range?.from === undefined ? -Infinity : bucketStart(range.from, granularity);
43
+ const hi = range?.to === undefined ? Infinity : bucketStart(range.to, granularity);
44
+ return await ctx.db
45
+ .query("rollups")
46
+ .withIndex("by_scope_name_gran_bucket_dim", (q) =>
47
+ q
48
+ .eq("scope", scope)
49
+ .eq("name", name)
50
+ .eq("granularity", granularity)
51
+ .gte("bucket", lo)
52
+ .lte("bucket", hi),
53
+ )
54
+ .collect();
55
+ }
56
+
57
+ async function seriesInRange(
58
+ ctx: QueryCtx,
59
+ scope: string,
60
+ name: string,
61
+ granularity: Granularity,
62
+ dim: string,
63
+ val: string,
64
+ range: { from?: number; to?: number } | undefined,
65
+ ): Promise<Doc<"rollups">[]> {
66
+ const lo = range?.from === undefined ? -Infinity : bucketStart(range.from, granularity);
67
+ const hi = range?.to === undefined ? Infinity : bucketStart(range.to, granularity);
68
+ return await ctx.db
69
+ .query("rollups")
70
+ .withIndex("by_scope_name_gran_dim_val_bucket", (q) =>
71
+ q
72
+ .eq("scope", scope)
73
+ .eq("name", name)
74
+ .eq("granularity", granularity)
75
+ .eq("dim", dim)
76
+ .eq("val", val)
77
+ .gte("bucket", lo)
78
+ .lte("bucket", hi),
79
+ )
80
+ .collect();
81
+ }
82
+
26
83
  /** Total event count over a range, optionally filtered by one dimension value. */
27
84
  export const metric = query({
28
85
  args: {
@@ -33,6 +90,7 @@ export const metric = query({
33
90
  },
34
91
  returns: v.number(),
35
92
  handler: async (ctx, args) => {
93
+ assertRange(args.range);
36
94
  const dim = args.where ? args.where.dim : TOTAL;
37
95
  const val = args.where ? valKey(args.where.val) : TOTAL;
38
96
 
@@ -40,28 +98,8 @@ export const metric = query({
40
98
  return await counter.count(ctx, tupleKey(args.scope, args.name));
41
99
  }
42
100
 
43
- const rollups = await ctx.db
44
- .query("rollups")
45
- .withIndex("by_scope_name_gran_bucket_dim", (q) =>
46
- q
47
- .eq("scope", args.scope)
48
- .eq("name", args.name)
49
- .eq("granularity", "day"),
50
- )
51
- .collect();
52
-
53
- let total = 0;
54
- for (const r of rollups) {
55
- if (r.dim !== dim || r.val !== val) continue;
56
- if (args.range?.from !== undefined && r.bucket < bucketStart(args.range.from, "day")) {
57
- continue;
58
- }
59
- if (args.range?.to !== undefined && r.bucket > bucketStart(args.range.to, "day")) {
60
- continue;
61
- }
62
- total += r.count;
63
- }
64
- return total;
101
+ const rollups = await seriesInRange(ctx, args.scope, args.name, "day", dim, val, args.range);
102
+ return rollups.reduce((total, r) => total + r.count, 0);
65
103
  },
66
104
  });
67
105
 
@@ -76,26 +114,14 @@ export const top = query({
76
114
  },
77
115
  returns: v.array(topRow),
78
116
  handler: async (ctx, args) => {
117
+ assertRange(args.range);
118
+ assertCount("limit", args.limit);
79
119
  const limit = Math.min(args.limit ?? 20, 100);
80
- const rollups = await ctx.db
81
- .query("rollups")
82
- .withIndex("by_scope_name_gran_bucket_dim", (q) =>
83
- q
84
- .eq("scope", args.scope)
85
- .eq("name", args.name)
86
- .eq("granularity", "day"),
87
- )
88
- .collect();
120
+ const rollups = await rollupsInRange(ctx, args.scope, args.name, "day", args.range);
89
121
 
90
122
  const counts = new Map<string, number>();
91
123
  for (const r of rollups) {
92
124
  if (r.dim !== args.dimension) continue;
93
- if (args.range?.from !== undefined && r.bucket < bucketStart(args.range.from, "day")) {
94
- continue;
95
- }
96
- if (args.range?.to !== undefined && r.bucket > bucketStart(args.range.to, "day")) {
97
- continue;
98
- }
99
125
  counts.set(r.val, (counts.get(r.val) ?? 0) + r.count);
100
126
  }
101
127
 
@@ -117,33 +143,13 @@ export const timeseries = query({
117
143
  },
118
144
  returns: v.array(timeseriesPoint),
119
145
  handler: async (ctx, args) => {
146
+ assertRange(args.range);
120
147
  const gran: Granularity = args.granularity;
121
148
  const dim = args.where ? args.where.dim : TOTAL;
122
149
  const val = args.where ? valKey(args.where.val) : TOTAL;
123
150
 
124
- const rollups = await ctx.db
125
- .query("rollups")
126
- .withIndex("by_scope_name_gran_bucket_dim", (q) =>
127
- q.eq("scope", args.scope).eq("name", args.name).eq("granularity", gran),
128
- )
129
- .collect();
130
-
131
- const fromBucket =
132
- args.range.from !== undefined ? bucketStart(args.range.from, gran) : undefined;
133
- const toBucket =
134
- args.range.to !== undefined ? bucketStart(args.range.to, gran) : undefined;
135
-
136
- const counts = new Map<number, number>();
137
- for (const r of rollups) {
138
- if (r.dim !== dim || r.val !== val) continue;
139
- if (fromBucket !== undefined && r.bucket < fromBucket) continue;
140
- if (toBucket !== undefined && r.bucket > toBucket) continue;
141
- counts.set(r.bucket, (counts.get(r.bucket) ?? 0) + r.count);
142
- }
143
-
144
- return [...counts.entries()]
145
- .map(([bucket, count]) => ({ bucket, count }))
146
- .sort((a, b) => a.bucket - b.bucket);
151
+ const rollups = await seriesInRange(ctx, args.scope, args.name, gran, dim, val, args.range);
152
+ return rollups.map((r) => ({ bucket: r.bucket, count: r.count }));
147
153
  },
148
154
  });
149
155
 
@@ -156,13 +162,16 @@ export const uniques = query({
156
162
  },
157
163
  returns: uniquesView,
158
164
  handler: async (ctx, args) => {
165
+ assertRange(args.range);
159
166
  const now = Date.now();
160
167
  const to = args.range.to ?? now;
161
168
  const from = args.range.from ?? to - 30 * 24 * 60 * 60 * 1000;
162
169
 
163
170
  const subjects = await ctx.db
164
171
  .query("subjects")
165
- .withIndex("by_scope_firstSeen", (q) => q.eq("scope", args.scope))
172
+ .withIndex("by_scope_lastSeen", (q) =>
173
+ q.eq("scope", args.scope).gte("lastSeen", from).lte("lastSeen", to),
174
+ )
166
175
  .collect();
167
176
 
168
177
  const size = bucketSize(args.granularity);
@@ -174,7 +183,6 @@ export const uniques = query({
174
183
  const mauCutoff = to - 30 * dayMs;
175
184
 
176
185
  for (const s of subjects) {
177
- if (s.lastSeen < from || s.lastSeen > to) continue;
178
186
  mau += s.lastSeen >= mauCutoff ? 1 : 0;
179
187
  wau += s.lastSeen >= wauCutoff ? 1 : 0;
180
188
  const bucket = Math.floor(s.lastSeen / size) * size;
@@ -208,6 +216,7 @@ export const funnel = query({
208
216
  if (args.steps.length < 2) {
209
217
  throw new Error("Funnel requires at least 2 steps");
210
218
  }
219
+ assertRange(args.range);
211
220
  const now = Date.now();
212
221
  const to = args.range.to ?? now;
213
222
  const from = args.range.from ?? to - 30 * 24 * 60 * 60 * 1000;
@@ -272,6 +281,8 @@ export const retention = query({
272
281
  },
273
282
  returns: v.array(retentionCohort),
274
283
  handler: async (ctx, args) => {
284
+ assertRange(args.cohortRange);
285
+ assertCount("periods", args.periods);
275
286
  const gran: Granularity = args.granularity ?? "day";
276
287
  const size = bucketSize(gran);
277
288
  const now = Date.now();
@@ -334,6 +345,10 @@ export const distribution = query({
334
345
  },
335
346
  returns: distributionView,
336
347
  handler: async (ctx, args) => {
348
+ assertRange(args.range);
349
+ if (!args.buckets.every(Number.isFinite)) {
350
+ throw invalidInput("INVALID_BUCKETS", "buckets must be finite numbers");
351
+ }
337
352
  const bins = [...args.buckets]
338
353
  .sort((a, b) => a - b)
339
354
  .map((upper) => ({ upper, count: 0 }));
@@ -390,7 +405,11 @@ export const list = query({
390
405
  // Note: events sharing the exact boundary `ts` may be skipped across a page
391
406
  // edge — adequate for a raw-event peek; precise feeds belong in the host.
392
407
  const { numItems, cursor } = args.paginationOpts;
408
+ assertCount("numItems", numItems);
393
409
  const before = cursor ? Number(cursor) : null;
410
+ if (before !== null && !Number.isFinite(before)) {
411
+ throw invalidInput("INVALID_CURSOR", "cursor is not a value returned by list");
412
+ }
394
413
  const rows = await ctx.db
395
414
  .query("events")
396
415
  .withIndex("by_scope_name_ts", (q) => {
@@ -24,8 +24,6 @@ export default defineSchema({
24
24
  })
25
25
  .index("by_scope_name_ts", ["scope", "name", "ts"])
26
26
  .index("by_scope_ts", ["scope", "ts"])
27
- .index("by_scope_subject_ts", ["scope", "subjectRef", "ts"])
28
- .index("by_scope_session_ts", ["scope", "sessionRef", "ts"])
29
27
  .index("by_dedupe", ["scope", "dedupeKey"]),
30
28
 
31
29
  rollups: defineTable({
@@ -45,7 +43,14 @@ export default defineSchema({
45
43
  "dim",
46
44
  "val",
47
45
  ])
48
- .index("by_scope_name_dim_val", ["scope", "name", "dim", "val"]),
46
+ .index("by_scope_name_gran_dim_val_bucket", [
47
+ "scope",
48
+ "name",
49
+ "granularity",
50
+ "dim",
51
+ "val",
52
+ "bucket",
53
+ ]),
49
54
 
50
55
  subjects: defineTable({
51
56
  scope: v.string(),
@@ -55,7 +60,8 @@ export default defineSchema({
55
60
  eventCount: v.number(),
56
61
  })
57
62
  .index("by_scope_subject", ["scope", "subjectRef"])
58
- .index("by_scope_firstSeen", ["scope", "firstSeen"]),
63
+ .index("by_scope_firstSeen", ["scope", "firstSeen"])
64
+ .index("by_scope_lastSeen", ["scope", "lastSeen"]),
59
65
 
60
66
  sessions: defineTable({
61
67
  scope: v.string(),
@@ -67,7 +73,6 @@ export default defineSchema({
67
73
  eventCount: v.number(),
68
74
  })
69
75
  .index("by_scope_session", ["scope", "sessionRef"])
70
- .index("by_scope_lastTs", ["scope", "lastTs"])
71
76
  .index("by_scope_endTs_lastTs", ["scope", "endTs", "lastTs"]),
72
77
 
73
78
  scopes: defineTable({