@vllnt/convex-analytics 0.1.0-canary.2b9f918

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 (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +198 -0
  3. package/dist/client/index.d.ts +94 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +132 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/types.d.ts +109 -0
  8. package/dist/client/types.d.ts.map +1 -0
  9. package/dist/client/types.js +2 -0
  10. package/dist/client/types.js.map +1 -0
  11. package/dist/component/_generated/api.d.ts +46 -0
  12. package/dist/component/_generated/api.d.ts.map +1 -0
  13. package/dist/component/_generated/api.js +31 -0
  14. package/dist/component/_generated/api.js.map +1 -0
  15. package/dist/component/_generated/component.d.ts +181 -0
  16. package/dist/component/_generated/component.d.ts.map +1 -0
  17. package/dist/component/_generated/component.js +11 -0
  18. package/dist/component/_generated/component.js.map +1 -0
  19. package/dist/component/_generated/dataModel.d.ts +46 -0
  20. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  21. package/dist/component/_generated/dataModel.js +11 -0
  22. package/dist/component/_generated/dataModel.js.map +1 -0
  23. package/dist/component/_generated/server.d.ts +133 -0
  24. package/dist/component/_generated/server.d.ts.map +1 -0
  25. package/dist/component/_generated/server.js +80 -0
  26. package/dist/component/_generated/server.js.map +1 -0
  27. package/dist/component/convex.config.d.ts +3 -0
  28. package/dist/component/convex.config.d.ts.map +1 -0
  29. package/dist/component/convex.config.js +10 -0
  30. package/dist/component/convex.config.js.map +1 -0
  31. package/dist/component/http.d.ts +13 -0
  32. package/dist/component/http.d.ts.map +1 -0
  33. package/dist/component/http.js +180 -0
  34. package/dist/component/http.js.map +1 -0
  35. package/dist/component/internal_mutations.d.ts +26 -0
  36. package/dist/component/internal_mutations.d.ts.map +1 -0
  37. package/dist/component/internal_mutations.js +126 -0
  38. package/dist/component/internal_mutations.js.map +1 -0
  39. package/dist/component/mutations.d.ts +24 -0
  40. package/dist/component/mutations.d.ts.map +1 -0
  41. package/dist/component/mutations.js +209 -0
  42. package/dist/component/mutations.js.map +1 -0
  43. package/dist/component/queries.d.ts +148 -0
  44. package/dist/component/queries.d.ts.map +1 -0
  45. package/dist/component/queries.js +376 -0
  46. package/dist/component/queries.js.map +1 -0
  47. package/dist/component/schema.d.ts +104 -0
  48. package/dist/component/schema.d.ts.map +1 -0
  49. package/dist/component/schema.js +72 -0
  50. package/dist/component/schema.js.map +1 -0
  51. package/dist/component/validators.d.ts +195 -0
  52. package/dist/component/validators.d.ts.map +1 -0
  53. package/dist/component/validators.js +71 -0
  54. package/dist/component/validators.js.map +1 -0
  55. package/dist/react/index.d.ts +89 -0
  56. package/dist/react/index.d.ts.map +1 -0
  57. package/dist/react/index.js +63 -0
  58. package/dist/react/index.js.map +1 -0
  59. package/dist/shared.d.ts +14 -0
  60. package/dist/shared.d.ts.map +1 -0
  61. package/dist/shared.js +18 -0
  62. package/dist/shared.js.map +1 -0
  63. package/dist/test.d.ts +117 -0
  64. package/dist/test.d.ts.map +1 -0
  65. package/dist/test.js +28 -0
  66. package/dist/test.js.map +1 -0
  67. package/dist/web/index.d.ts +121 -0
  68. package/dist/web/index.d.ts.map +1 -0
  69. package/dist/web/index.js +169 -0
  70. package/dist/web/index.js.map +1 -0
  71. package/package.json +121 -0
  72. package/src/client/index.ts +259 -0
  73. package/src/client/types.ts +121 -0
  74. package/src/component/_generated/api.ts +62 -0
  75. package/src/component/_generated/component.ts +196 -0
  76. package/src/component/_generated/dataModel.ts +60 -0
  77. package/src/component/_generated/server.ts +169 -0
  78. package/src/component/convex.config.ts +12 -0
  79. package/src/component/http.ts +204 -0
  80. package/src/component/internal_mutations.ts +167 -0
  81. package/src/component/mutations.ts +255 -0
  82. package/src/component/queries.ts +436 -0
  83. package/src/component/schema.ts +76 -0
  84. package/src/component/validators.ts +94 -0
  85. package/src/react/index.tsx +127 -0
  86. package/src/shared.ts +30 -0
  87. package/src/test.ts +44 -0
  88. package/src/web/index.ts +232 -0
@@ -0,0 +1,76 @@
1
+ import { defineSchema, defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+ import { propsValidator, granularityValidator } from "./validators.js";
4
+
5
+ /**
6
+ * Generic, domain-neutral analytics schema. Zero hardcoded web fields, zero `v.any()`.
7
+ *
8
+ * - `events` — raw event log (TTL-pruned).
9
+ * - `rollups` — rollup-on-write counts per (scope, name, granularity, bucket, dim, val).
10
+ * - `subjects` — per-subject lifecycle for uniques/retention.
11
+ * - `sessions` — optional generic session aggregates for idle-close + session reads.
12
+ * - `config` — cron-relevant config (retention/sampling) keyed by scope.
13
+ */
14
+ export default defineSchema({
15
+ events: defineTable({
16
+ scope: v.string(),
17
+ name: v.string(),
18
+ subjectRef: v.optional(v.string()),
19
+ sessionRef: v.optional(v.string()),
20
+ props: propsValidator,
21
+ ts: v.number(),
22
+ seq: v.number(),
23
+ dedupeKey: v.optional(v.string()),
24
+ })
25
+ .index("by_scope_name_ts", ["scope", "name", "ts"])
26
+ .index("by_scope_subject_ts", ["scope", "subjectRef", "ts"])
27
+ .index("by_scope_session_ts", ["scope", "sessionRef", "ts"])
28
+ .index("by_dedupe", ["scope", "dedupeKey"]),
29
+
30
+ rollups: defineTable({
31
+ scope: v.string(),
32
+ name: v.string(),
33
+ granularity: granularityValidator,
34
+ bucket: v.number(),
35
+ dim: v.string(),
36
+ val: v.string(),
37
+ count: v.number(),
38
+ })
39
+ .index("by_scope_name_gran_bucket_dim", [
40
+ "scope",
41
+ "name",
42
+ "granularity",
43
+ "bucket",
44
+ "dim",
45
+ "val",
46
+ ])
47
+ .index("by_scope_name_dim_val", ["scope", "name", "dim", "val"]),
48
+
49
+ subjects: defineTable({
50
+ scope: v.string(),
51
+ subjectRef: v.string(),
52
+ firstSeen: v.number(),
53
+ lastSeen: v.number(),
54
+ eventCount: v.number(),
55
+ })
56
+ .index("by_scope_subject", ["scope", "subjectRef"])
57
+ .index("by_scope_firstSeen", ["scope", "firstSeen"]),
58
+
59
+ sessions: defineTable({
60
+ scope: v.string(),
61
+ sessionRef: v.string(),
62
+ subjectRef: v.optional(v.string()),
63
+ startTs: v.number(),
64
+ endTs: v.optional(v.number()),
65
+ lastTs: v.number(),
66
+ eventCount: v.number(),
67
+ })
68
+ .index("by_scope_session", ["scope", "sessionRef"])
69
+ .index("by_scope_lastTs", ["scope", "lastTs"]),
70
+
71
+ config: defineTable({
72
+ scope: v.string(),
73
+ key: v.string(),
74
+ value: v.string(),
75
+ }).index("by_scope_key", ["scope", "key"]),
76
+ });
@@ -0,0 +1,94 @@
1
+ import { v } from "convex/values";
2
+
3
+ /** A single property value — string, number, boolean, or null. No nested objects/arrays. */
4
+ export const scalarValidator = v.union(
5
+ v.string(),
6
+ v.number(),
7
+ v.boolean(),
8
+ v.null(),
9
+ );
10
+
11
+ /** Event properties: a flat record of scalar values. The generic, typed default — never `v.any()`. */
12
+ export const propsValidator = v.record(v.string(), scalarValidator);
13
+
14
+ /** A time range in epoch millis. */
15
+ export const rangeValidator = v.object({
16
+ from: v.optional(v.number()),
17
+ to: v.optional(v.number()),
18
+ });
19
+
20
+ /** A dimension filter: count only events whose `dim` prop equals `val`. */
21
+ export const whereValidator = v.object({
22
+ dim: v.string(),
23
+ val: scalarValidator,
24
+ });
25
+
26
+ /** Rollup bucket granularity. `minute` is opt-in for short live windows. */
27
+ export const granularityValidator = v.union(
28
+ v.literal("minute"),
29
+ v.literal("hour"),
30
+ v.literal("day"),
31
+ );
32
+
33
+ /** Array of granularities (the `granularities` config, shared by `track` + `backfill`). */
34
+ export const granularitiesValidator = v.array(granularityValidator);
35
+
36
+ /** A raw event as returned by reads. */
37
+ export const eventView = v.object({
38
+ _id: v.string(),
39
+ _creationTime: v.number(),
40
+ scope: v.string(),
41
+ name: v.string(),
42
+ subjectRef: v.optional(v.string()),
43
+ sessionRef: v.optional(v.string()),
44
+ props: propsValidator,
45
+ ts: v.number(),
46
+ seq: v.number(),
47
+ dedupeKey: v.optional(v.string()),
48
+ });
49
+
50
+ /** A `(value, count)` pair for `top` breakdowns. */
51
+ export const topRow = v.object({ value: v.string(), count: v.number() });
52
+
53
+ /** A `(bucket, count)` pair for `timeseries`. */
54
+ export const timeseriesPoint = v.object({ bucket: v.number(), count: v.number() });
55
+
56
+ /** DAU/WAU/MAU rollup of distinct subjects. */
57
+ export const uniquesView = v.object({
58
+ dau: v.number(),
59
+ wau: v.number(),
60
+ mau: v.number(),
61
+ trend: v.array(v.object({ bucket: v.number(), uniques: v.number() })),
62
+ });
63
+
64
+ /** A single funnel step result. */
65
+ export const funnelStep = v.object({
66
+ name: v.string(),
67
+ count: v.number(),
68
+ rate: v.number(),
69
+ });
70
+
71
+ /** A single retention cohort row. */
72
+ export const retentionCohort = v.object({
73
+ cohort: v.number(),
74
+ size: v.number(),
75
+ retained: v.array(v.number()),
76
+ });
77
+
78
+ /** Paginated raw-event page (Convex pagination result shape). */
79
+ export const eventPage = v.object({
80
+ page: v.array(eventView),
81
+ isDone: v.boolean(),
82
+ continueCursor: v.string(),
83
+ });
84
+
85
+ /** A single histogram bin: events whose measure falls at or below `upper`. */
86
+ export const distributionBin = v.object({ upper: v.number(), count: v.number() });
87
+
88
+ /** Histogram of a numeric measure: ascending upper-bound bins + an overflow bucket. */
89
+ export const distributionView = v.object({
90
+ bins: v.array(distributionBin),
91
+ overflow: v.number(),
92
+ count: v.number(),
93
+ sum: v.number(),
94
+ });
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Optional React hooks for `@vllnt/convex-analytics`.
3
+ *
4
+ * Thin, tree-shakeable wrappers over `convex/react`'s `useQuery` for the
5
+ * component's **aggregate** read verbs (metric, timeseries, top, uniques).
6
+ * The backend core installs and runs with zero React — these hooks are an
7
+ * opt-in `./react` entry; `react` and `convex` are optional peer deps.
8
+ *
9
+ * No-leak: aggregates ONLY (no raw events) and every call is scope-gated, so a
10
+ * hook can never surface another scope's rows or a raw event payload on the
11
+ * client.
12
+ *
13
+ * The component never owns the host's `api`. The host re-exports the analytics
14
+ * query refs from its own Convex functions and passes the matching ref into
15
+ * each hook — these wrappers forward the host's exact args and the reactive
16
+ * return, while pinning the aggregate return type for ergonomics.
17
+ *
18
+ * @packageDocumentation
19
+ */
20
+
21
+ import { useQuery } from "convex/react";
22
+ import type { OptionalRestArgsOrSkip } from "convex/react";
23
+ import type { FunctionReference, DefaultFunctionArgs } from "convex/server";
24
+ import type {
25
+ Range,
26
+ Where,
27
+ Granularity,
28
+ TopRow,
29
+ TimeseriesPoint,
30
+ UniquesView,
31
+ } from "../client/types.js";
32
+
33
+ export type { Range, Where, Granularity, TopRow, TimeseriesPoint, UniquesView };
34
+
35
+ /** A host-re-exported public analytics query ref returning `R`. */
36
+ type QueryRef<R> = FunctionReference<"query", "public", DefaultFunctionArgs, R>;
37
+
38
+ /** The args a host's re-exported `metric` query is expected to accept. */
39
+ export interface MetricArgs {
40
+ scope?: string;
41
+ name: string;
42
+ range?: Range;
43
+ where?: Where;
44
+ }
45
+
46
+ /** The args a host's re-exported `top` query is expected to accept. */
47
+ export interface TopArgs {
48
+ scope?: string;
49
+ name: string;
50
+ dimension: string;
51
+ range?: Range;
52
+ limit?: number;
53
+ }
54
+
55
+ /** The args a host's re-exported `timeseries` query is expected to accept. */
56
+ export interface TimeseriesArgs {
57
+ scope?: string;
58
+ name: string;
59
+ granularity: Granularity;
60
+ range: Range;
61
+ where?: Where;
62
+ }
63
+
64
+ /** The args a host's re-exported `uniques` query is expected to accept. */
65
+ export interface UniquesArgs {
66
+ scope?: string;
67
+ range: Range;
68
+ granularity: Granularity;
69
+ }
70
+
71
+ /**
72
+ * Reactive total count for an event over a range (optionally filtered).
73
+ *
74
+ * @param ref - The host's re-exported `metric` query reference.
75
+ * @param args - The query args (`{ name, scope?, range?, where? }`), or
76
+ * `"skip"` to defer until ready. The host ref's own validator is the
77
+ * contract; {@link MetricArgs} documents the expected shape.
78
+ * @returns The count, or `undefined` while loading.
79
+ */
80
+ export function useMetric<Ref extends QueryRef<number>>(
81
+ ref: Ref,
82
+ ...args: OptionalRestArgsOrSkip<Ref>
83
+ ): number | undefined {
84
+ return useQuery(ref, ...args);
85
+ }
86
+
87
+ /**
88
+ * Reactive breakdown — top values of a dimension for an event.
89
+ *
90
+ * @param ref - The host's re-exported `top` query reference.
91
+ * @param args - `{ name, dimension, scope?, range?, limit? }`, or `"skip"`.
92
+ * @returns The rows, or `undefined` while loading.
93
+ */
94
+ export function useTop<Ref extends QueryRef<TopRow[]>>(
95
+ ref: Ref,
96
+ ...args: OptionalRestArgsOrSkip<Ref>
97
+ ): TopRow[] | undefined {
98
+ return useQuery(ref, ...args);
99
+ }
100
+
101
+ /**
102
+ * Reactive bucketed counts for an event over a range.
103
+ *
104
+ * @param ref - The host's re-exported `timeseries` query reference.
105
+ * @param args - `{ name, granularity, range, scope?, where? }`, or `"skip"`.
106
+ * @returns The points, or `undefined` while loading.
107
+ */
108
+ export function useTimeseries<Ref extends QueryRef<TimeseriesPoint[]>>(
109
+ ref: Ref,
110
+ ...args: OptionalRestArgsOrSkip<Ref>
111
+ ): TimeseriesPoint[] | undefined {
112
+ return useQuery(ref, ...args);
113
+ }
114
+
115
+ /**
116
+ * Reactive DAU/WAU/MAU + trend from subjects.
117
+ *
118
+ * @param ref - The host's re-exported `uniques` query reference.
119
+ * @param args - `{ range, granularity, scope? }`, or `"skip"`.
120
+ * @returns The uniques view, or `undefined` while loading.
121
+ */
122
+ export function useUniques<Ref extends QueryRef<UniquesView>>(
123
+ ref: Ref,
124
+ ...args: OptionalRestArgsOrSkip<Ref>
125
+ ): UniquesView | undefined {
126
+ return useQuery(ref, ...args);
127
+ }
package/src/shared.ts ADDED
@@ -0,0 +1,30 @@
1
+ /** Shared pure helpers + types for the generic analytics component. */
2
+
3
+ /** A single property value. */
4
+ export type Scalar = string | number | boolean | null;
5
+
6
+ /** Event properties: a flat record of scalar values. */
7
+ export type Props = Record<string, Scalar>;
8
+
9
+ /** Rollup bucket granularity. `minute` is opt-in for short live windows. */
10
+ export type Granularity = "minute" | "hour" | "day";
11
+
12
+ const MINUTE_MS = 60 * 1000;
13
+ const HOUR_MS = 60 * MINUTE_MS;
14
+ const DAY_MS = 24 * HOUR_MS;
15
+
16
+ /** Bucket size in millis for a granularity. */
17
+ export function bucketSize(granularity: Granularity): number {
18
+ return granularity === "minute" ? MINUTE_MS : granularity === "hour" ? HOUR_MS : DAY_MS;
19
+ }
20
+
21
+ /** Truncate an epoch-millis timestamp to the start of its `granularity` bucket. */
22
+ export function bucketStart(ts: number, granularity: Granularity): number {
23
+ const size = bucketSize(granularity);
24
+ return Math.floor(ts / size) * size;
25
+ }
26
+
27
+ /** Coerce a scalar prop value to the string form used as a rollup `val` key. */
28
+ export function valKey(value: Scalar): string {
29
+ return value === null ? "null" : String(value);
30
+ }
package/src/test.ts ADDED
@@ -0,0 +1,44 @@
1
+ /// <reference types="vite/client" />
2
+ import type { TestConvex } from "convex-test";
3
+ import type { GenericSchema, SchemaDefinition } from "convex/server";
4
+ import aggregateTest from "@convex-dev/aggregate/test";
5
+ import shardedCounterTest from "@convex-dev/sharded-counter/test";
6
+ import rateLimiterTest from "@convex-dev/rate-limiter/test";
7
+ import schema from "./component/schema.js";
8
+
9
+ const modules = import.meta.glob("./component/**/*.ts");
10
+
11
+ /**
12
+ * Register the convex-analytics component (and its child components) with a
13
+ * convex-test instance. Child components are registered under nested paths
14
+ * (`<name>/aggregate`, `<name>/shardedCounter`, `<name>/rateLimiter`) so that
15
+ * `track`'s aggregate/counter/rate-limiter calls resolve end-to-end.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * import analyticsTest from "@vllnt/convex-analytics/test";
20
+ * import { convexTest } from "convex-test";
21
+ *
22
+ * const t = convexTest(hostSchema, hostModules);
23
+ * analyticsTest.register(t);
24
+ * ```
25
+ */
26
+ export function register(
27
+ t: TestConvex<SchemaDefinition<GenericSchema, boolean>>,
28
+ name: string = "analytics",
29
+ ): void {
30
+ t.registerComponent(name, schema, modules);
31
+ t.registerComponent(`${name}/aggregate`, aggregateTest.schema, aggregateTest.modules);
32
+ t.registerComponent(
33
+ `${name}/shardedCounter`,
34
+ shardedCounterTest.schema,
35
+ shardedCounterTest.modules,
36
+ );
37
+ t.registerComponent(
38
+ `${name}/rateLimiter`,
39
+ rateLimiterTest.schema,
40
+ rateLimiterTest.modules,
41
+ );
42
+ }
43
+
44
+ export default { register, schema, modules };
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Optional web preset for `@vllnt/convex-analytics`.
3
+ *
4
+ * Pure, host-side helpers — NOT part of the sandboxed component. A web host
5
+ * opts in by passing {@link webDimensions} to the `AnalyticsClient` `dimensions`
6
+ * config and using {@link trackPageview} to ingest page views. The generic core
7
+ * stays domain-neutral; nothing here runs inside the component sandbox.
8
+ *
9
+ * @packageDocumentation
10
+ */
11
+
12
+ import type { Scalar } from "../shared.js";
13
+
14
+ /**
15
+ * Standard web rollup dimensions. Pass to the `AnalyticsClient` `dimensions`
16
+ * config to opt into web breakdowns (path, referrer, device, browser, ...).
17
+ */
18
+ export const webDimensions = [
19
+ "path",
20
+ "referrer",
21
+ "device",
22
+ "browser",
23
+ "os",
24
+ "country",
25
+ "utmSource",
26
+ "utmMedium",
27
+ "utmCampaign",
28
+ ] as const;
29
+
30
+ /** A key of {@link webDimensions}. */
31
+ export type WebDimension = (typeof webDimensions)[number];
32
+
33
+ /** Parsed user-agent facets. */
34
+ export interface UserAgentInfo {
35
+ device: string;
36
+ browser: string;
37
+ os: string;
38
+ }
39
+
40
+ /** Geo facets resolved from edge/CDN request headers. */
41
+ export interface GeoInfo {
42
+ country: string;
43
+ region?: string;
44
+ city?: string;
45
+ }
46
+
47
+ /** UTM campaign tags. */
48
+ export interface Utm {
49
+ source?: string;
50
+ medium?: string;
51
+ campaign?: string;
52
+ }
53
+
54
+ function browserOf(ua: string): string {
55
+ if (ua.includes("Firefox/")) return "Firefox";
56
+ if (ua.includes("Edg/")) return "Edge";
57
+ if (ua.includes("Chrome/")) return "Chrome";
58
+ if (ua.includes("Safari/") && !ua.includes("Chrome/")) return "Safari";
59
+ return "Other";
60
+ }
61
+
62
+ function osOf(ua: string): string {
63
+ if (ua.includes("Windows")) return "Windows";
64
+ if (ua.includes("iPhone") || ua.includes("iPad")) return "iOS";
65
+ if (ua.includes("Android")) return "Android";
66
+ if (ua.includes("Mac OS X") || ua.includes("Macintosh")) return "macOS";
67
+ if (ua.includes("Linux")) return "Linux";
68
+ return "Other";
69
+ }
70
+
71
+ function deviceOf(ua: string): string {
72
+ if (/bot|crawler|spider/i.test(ua)) return "bot";
73
+ if (/iPhone|Android.*Mobile/i.test(ua)) return "mobile";
74
+ if (/iPad|Android(?!.*Mobile)/i.test(ua)) return "tablet";
75
+ return "desktop";
76
+ }
77
+
78
+ /**
79
+ * Parse a `User-Agent` string into device / browser / os facets.
80
+ *
81
+ * Pure and dependency-free — coarse buckets suitable for rollups, not exact
82
+ * version detection. Unknown agents fall back to `"Other"` / `"desktop"`.
83
+ *
84
+ * @param ua - The raw `User-Agent` header value.
85
+ * @returns Device, browser, and OS buckets.
86
+ * @example
87
+ * ```ts
88
+ * parseUserAgent("Mozilla/5.0 ... Chrome/120 Safari/537");
89
+ * // { device: "desktop", browser: "Chrome", os: "..." }
90
+ * ```
91
+ */
92
+ export function parseUserAgent(ua: string): UserAgentInfo {
93
+ return { device: deviceOf(ua), browser: browserOf(ua), os: osOf(ua) };
94
+ }
95
+
96
+ function headerGetter(
97
+ headers: Headers | Record<string, string>,
98
+ ): (name: string) => string | undefined {
99
+ if (typeof (headers as Headers).get === "function") {
100
+ return (name) => (headers as Headers).get(name) ?? undefined;
101
+ }
102
+ const lower: Record<string, string> = {};
103
+ for (const [k, v] of Object.entries(headers as Record<string, string>)) {
104
+ lower[k.toLowerCase()] = v;
105
+ }
106
+ return (name) => lower[name.toLowerCase()];
107
+ }
108
+
109
+ /**
110
+ * Resolve geo facets from Cloudflare / Vercel edge request headers.
111
+ *
112
+ * Reads `CF-IPCountry` and the `X-Vercel-IP-*` family. Accepts either a DOM
113
+ * `Headers` instance or a plain object (case-insensitive). Country defaults to
114
+ * `"unknown"` when no header is present.
115
+ *
116
+ * @param headers - Request headers as a `Headers` instance or a plain record.
117
+ * @returns Country (always present) plus optional region / city.
118
+ */
119
+ export function geoFromHeaders(headers: Headers | Record<string, string>): GeoInfo {
120
+ const get = headerGetter(headers);
121
+ const country =
122
+ get("CF-IPCountry") ?? get("X-Vercel-IP-Country") ?? "unknown";
123
+ const region = get("X-Vercel-IP-Country-Region");
124
+ const city = get("X-Vercel-IP-City");
125
+ const info: GeoInfo = { country };
126
+ if (region !== undefined) info.region = region;
127
+ if (city !== undefined) info.city = city;
128
+ return info;
129
+ }
130
+
131
+ /** A subset of the `AnalyticsClient` surface used by {@link trackPageview}. */
132
+ interface PageviewClient {
133
+ track(
134
+ ctx: unknown,
135
+ name: string,
136
+ opts: {
137
+ subjectRef?: string;
138
+ sessionRef?: string;
139
+ props?: Record<string, Scalar>;
140
+ ts?: number;
141
+ scope?: string;
142
+ dedupeKey?: string;
143
+ },
144
+ ): Promise<unknown>;
145
+ }
146
+
147
+ /** Options for {@link trackPageview}. */
148
+ export interface TrackPageviewOpts {
149
+ subjectRef?: string;
150
+ sessionRef?: string;
151
+ /** The page path (e.g. `/pricing`). */
152
+ path: string;
153
+ /** The document referrer, if any. */
154
+ referrer?: string;
155
+ /** Raw `User-Agent` header — parsed into device/browser/os when present. */
156
+ ua?: string;
157
+ /** Request headers — parsed for geo (country/region/city) when present. */
158
+ headers?: Headers | Record<string, string>;
159
+ /** UTM campaign tags. */
160
+ utm?: Utm;
161
+ /** Epoch-millis event time. Defaults to the component's clock when omitted. */
162
+ ts?: number;
163
+ /** Override the client's default scope for this event. */
164
+ scope?: string;
165
+ /** Skip if an event with this dedupe key already exists in the scope. */
166
+ dedupeKey?: string;
167
+ }
168
+
169
+ /**
170
+ * Build web `props` from a pageview (parsing UA + geo) and ingest a
171
+ * `"page_view"` event through the generic `AnalyticsClient`.
172
+ *
173
+ * Host-side convenience: the component never sees web concepts — this helper
174
+ * just assembles the `{@link webDimensions}`-shaped props and calls
175
+ * `client.track(ctx, "page_view", { props })`. Pair with
176
+ * `dimensions: webDimensions` on the client to get web rollups.
177
+ *
178
+ * @typeParam C - The `AnalyticsClient` (structural) type.
179
+ * @param client - An `AnalyticsClient` (or compatible) instance.
180
+ * @param ctx - The Convex mutation ctx to run `track` against.
181
+ * @param opts - Pageview fields; `path` is required.
182
+ * @returns The `track` result passed through from the client.
183
+ * @example
184
+ * ```ts
185
+ * const analytics = new AnalyticsClient(components.analytics, { dimensions: webDimensions });
186
+ * await trackPageview(analytics, ctx, {
187
+ * path: "/pricing",
188
+ * ua: request.headers.get("user-agent") ?? undefined,
189
+ * headers: request.headers,
190
+ * });
191
+ * ```
192
+ */
193
+ export async function trackPageview<C extends PageviewClient>(
194
+ client: C,
195
+ ctx: unknown,
196
+ opts: TrackPageviewOpts,
197
+ ): Promise<unknown> {
198
+ const ua = opts.ua !== undefined ? parseUserAgent(opts.ua) : undefined;
199
+ const geo = opts.headers !== undefined ? geoFromHeaders(opts.headers) : undefined;
200
+
201
+ const props: Record<string, Scalar> = { path: opts.path };
202
+ if (opts.referrer !== undefined) props["referrer"] = opts.referrer;
203
+ if (ua !== undefined) {
204
+ props["device"] = ua.device;
205
+ props["browser"] = ua.browser;
206
+ props["os"] = ua.os;
207
+ }
208
+ if (geo !== undefined) {
209
+ props["country"] = geo.country;
210
+ if (geo.region !== undefined) props["region"] = geo.region;
211
+ if (geo.city !== undefined) props["city"] = geo.city;
212
+ }
213
+ if (opts.utm?.source !== undefined) props["utmSource"] = opts.utm.source;
214
+ if (opts.utm?.medium !== undefined) props["utmMedium"] = opts.utm.medium;
215
+ if (opts.utm?.campaign !== undefined) props["utmCampaign"] = opts.utm.campaign;
216
+
217
+ const trackOpts: {
218
+ subjectRef?: string;
219
+ sessionRef?: string;
220
+ props: Record<string, Scalar>;
221
+ ts?: number;
222
+ scope?: string;
223
+ dedupeKey?: string;
224
+ } = { props };
225
+ if (opts.subjectRef !== undefined) trackOpts.subjectRef = opts.subjectRef;
226
+ if (opts.sessionRef !== undefined) trackOpts.sessionRef = opts.sessionRef;
227
+ if (opts.ts !== undefined) trackOpts.ts = opts.ts;
228
+ if (opts.scope !== undefined) trackOpts.scope = opts.scope;
229
+ if (opts.dedupeKey !== undefined) trackOpts.dedupeKey = opts.dedupeKey;
230
+
231
+ return client.track(ctx, "page_view", trackOpts);
232
+ }