@vllnt/convex-events 0.1.0-canary.2310a69

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 (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +140 -0
  3. package/dist/client/index.d.ts +134 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +144 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/types.d.ts +58 -0
  8. package/dist/client/types.d.ts.map +1 -0
  9. package/dist/client/types.js +3 -0
  10. package/dist/client/types.js.map +1 -0
  11. package/dist/component/_generated/api.d.ts +40 -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 +93 -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 +121 -0
  24. package/dist/component/_generated/server.d.ts.map +1 -0
  25. package/dist/component/_generated/server.js +78 -0
  26. package/dist/component/_generated/server.js.map +1 -0
  27. package/dist/component/convex.config.d.ts +8 -0
  28. package/dist/component/convex.config.d.ts.map +1 -0
  29. package/dist/component/convex.config.js +9 -0
  30. package/dist/component/convex.config.js.map +1 -0
  31. package/dist/component/crons.d.ts +8 -0
  32. package/dist/component/crons.d.ts.map +1 -0
  33. package/dist/component/crons.js +11 -0
  34. package/dist/component/crons.js.map +1 -0
  35. package/dist/component/mutations.d.ts +30 -0
  36. package/dist/component/mutations.d.ts.map +1 -0
  37. package/dist/component/mutations.js +105 -0
  38. package/dist/component/mutations.js.map +1 -0
  39. package/dist/component/queries.d.ts +54 -0
  40. package/dist/component/queries.d.ts.map +1 -0
  41. package/dist/component/queries.js +103 -0
  42. package/dist/component/queries.js.map +1 -0
  43. package/dist/component/schema.d.ts +35 -0
  44. package/dist/component/schema.d.ts.map +1 -0
  45. package/dist/component/schema.js +28 -0
  46. package/dist/component/schema.js.map +1 -0
  47. package/dist/component/validators.d.ts +82 -0
  48. package/dist/component/validators.d.ts.map +1 -0
  49. package/dist/component/validators.js +29 -0
  50. package/dist/component/validators.js.map +1 -0
  51. package/dist/react/index.d.ts +63 -0
  52. package/dist/react/index.d.ts.map +1 -0
  53. package/dist/react/index.js +40 -0
  54. package/dist/react/index.js.map +1 -0
  55. package/dist/shared.d.ts +23 -0
  56. package/dist/shared.d.ts.map +1 -0
  57. package/dist/shared.js +23 -0
  58. package/dist/shared.js.map +1 -0
  59. package/package.json +112 -0
  60. package/src/client/index.ts +297 -0
  61. package/src/client/types.ts +62 -0
  62. package/src/component/_generated/api.ts +56 -0
  63. package/src/component/_generated/component.ts +113 -0
  64. package/src/component/_generated/dataModel.ts +60 -0
  65. package/src/component/_generated/server.ts +156 -0
  66. package/src/component/convex.config.ts +10 -0
  67. package/src/component/crons.ts +18 -0
  68. package/src/component/mutations.ts +108 -0
  69. package/src/component/queries.ts +109 -0
  70. package/src/component/schema.ts +28 -0
  71. package/src/component/validators.ts +32 -0
  72. package/src/react/index.test.tsx +133 -0
  73. package/src/react/index.tsx +83 -0
  74. package/src/shared.ts +35 -0
  75. package/src/test.ts +12 -0
@@ -0,0 +1,156 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated utilities for implementing server-side Convex query and mutation functions.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ ActionBuilder,
13
+ HttpActionBuilder,
14
+ MutationBuilder,
15
+ QueryBuilder,
16
+ GenericActionCtx,
17
+ GenericMutationCtx,
18
+ GenericQueryCtx,
19
+ GenericDatabaseReader,
20
+ GenericDatabaseWriter,
21
+ } from "convex/server";
22
+ import {
23
+ actionGeneric,
24
+ httpActionGeneric,
25
+ queryGeneric,
26
+ mutationGeneric,
27
+ internalActionGeneric,
28
+ internalMutationGeneric,
29
+ internalQueryGeneric,
30
+ } from "convex/server";
31
+ import type { DataModel } from "./dataModel.js";
32
+
33
+ /**
34
+ * Define a query in this Convex app's public API.
35
+ *
36
+ * This function will be allowed to read your Convex database and will be accessible from the client.
37
+ *
38
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
39
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
40
+ */
41
+ export const query: QueryBuilder<DataModel, "public"> = queryGeneric;
42
+
43
+ /**
44
+ * Define a query that is only accessible from other Convex functions (but not from the client).
45
+ *
46
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
47
+ *
48
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
49
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
50
+ */
51
+ export const internalQuery: QueryBuilder<DataModel, "internal"> =
52
+ internalQueryGeneric;
53
+
54
+ /**
55
+ * Define a mutation in this Convex app's public API.
56
+ *
57
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
58
+ *
59
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
60
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
61
+ */
62
+ export const mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
63
+
64
+ /**
65
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
66
+ *
67
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
68
+ *
69
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
70
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
71
+ */
72
+ export const internalMutation: MutationBuilder<DataModel, "internal"> =
73
+ internalMutationGeneric;
74
+
75
+ /**
76
+ * Define an action in this Convex app's public API.
77
+ *
78
+ * An action is a function which can execute any JavaScript code, including non-deterministic
79
+ * code and code with side-effects, like calling third-party services.
80
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
81
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
82
+ *
83
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
84
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
85
+ */
86
+ export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
87
+
88
+ /**
89
+ * Define an action that is only accessible from other Convex functions (but not from the client).
90
+ *
91
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
92
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
93
+ */
94
+ export const internalAction: ActionBuilder<DataModel, "internal"> =
95
+ internalActionGeneric;
96
+
97
+ /**
98
+ * Define an HTTP action.
99
+ *
100
+ * The wrapped function will be used to respond to HTTP requests received
101
+ * by a Convex deployment if the requests matches the path and method where
102
+ * this action is routed. Be sure to route your httpAction in `convex/http.js`.
103
+ *
104
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument
105
+ * and a Fetch API `Request` object as its second.
106
+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
107
+ */
108
+ export const httpAction: HttpActionBuilder = httpActionGeneric;
109
+
110
+ /**
111
+ * A set of services for use within Convex query functions.
112
+ *
113
+ * The query context is passed as the first argument to any Convex query
114
+ * function run on the server.
115
+ *
116
+ * If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
117
+ */
118
+ export type QueryCtx = GenericQueryCtx<DataModel>;
119
+
120
+ /**
121
+ * A set of services for use within Convex mutation functions.
122
+ *
123
+ * The mutation context is passed as the first argument to any Convex mutation
124
+ * function run on the server.
125
+ *
126
+ * If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
127
+ */
128
+ export type MutationCtx = GenericMutationCtx<DataModel>;
129
+
130
+ /**
131
+ * A set of services for use within Convex action functions.
132
+ *
133
+ * The action context is passed as the first argument to any Convex action
134
+ * function run on the server.
135
+ */
136
+ export type ActionCtx = GenericActionCtx<DataModel>;
137
+
138
+ /**
139
+ * An interface to read from the database within Convex query functions.
140
+ *
141
+ * The two entry points are {@link DatabaseReader.get}, which fetches a single
142
+ * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
143
+ * building a query.
144
+ */
145
+ export type DatabaseReader = GenericDatabaseReader<DataModel>;
146
+
147
+ /**
148
+ * An interface to read from and write to the database within Convex mutation
149
+ * functions.
150
+ *
151
+ * Convex guarantees that all writes within a single mutation are
152
+ * executed atomically, so you never have to worry about partial writes leaving
153
+ * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
154
+ * for the guarantees Convex provides your functions.
155
+ */
156
+ export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
@@ -0,0 +1,10 @@
1
+ import { defineComponent } from "convex/server";
2
+
3
+ /**
4
+ * The events component. Owns the sandboxed `events` ledger + a singleton
5
+ * `config` row, and runs an internal daily retention cron (see `crons.ts`,
6
+ * `mutations.pruneExpired`) that prunes events past the host-configured window.
7
+ */
8
+ const component = defineComponent("events");
9
+
10
+ export default component;
@@ -0,0 +1,18 @@
1
+ import { cronJobs } from "convex/server";
2
+ import { api } from "./_generated/api";
3
+
4
+ /**
5
+ * Component-internal retention sweep. Runs daily and prunes events older than
6
+ * the host-configured `retentionMs` (set via `configure`). Idempotent and a
7
+ * no-op until the host configures retention — see `mutations.pruneExpired`.
8
+ */
9
+ const crons = cronJobs();
10
+
11
+ crons.daily(
12
+ "prune-expired-events",
13
+ { hourUTC: 0, minuteUTC: 0 },
14
+ api.mutations.pruneExpired,
15
+ {},
16
+ );
17
+
18
+ export default crons;
@@ -0,0 +1,108 @@
1
+ import { v } from "convex/values";
2
+ import { mutation } from "./_generated/server";
3
+ import { api } from "./_generated/api";
4
+ import { jsonValue } from "./validators";
5
+
6
+ /** Default number of rows deleted per `purge` / prune batch before rescheduling. */
7
+ const DEFAULT_PURGE_BATCH = 256;
8
+
9
+ export const record = mutation({
10
+ args: {
11
+ subjectRef: v.string(),
12
+ type: v.string(),
13
+ actorRef: v.optional(v.string()),
14
+ metadata: v.optional(jsonValue),
15
+ },
16
+ returns: v.id("events"),
17
+ handler: async (ctx, args) => {
18
+ return await ctx.db.insert("events", {
19
+ subjectRef: args.subjectRef,
20
+ type: args.type,
21
+ actorRef: args.actorRef,
22
+ metadata: args.metadata,
23
+ createdAt: Date.now(),
24
+ });
25
+ },
26
+ });
27
+
28
+ /**
29
+ * Delete a batch of a subject's events, oldest-first, rescheduling itself until
30
+ * fewer than `batch` rows remain. Idempotent and at-least-once safe: a redelivery
31
+ * simply deletes the next (or zero) batch. Returns the count deleted this batch.
32
+ */
33
+ export const purge = mutation({
34
+ args: {
35
+ subjectRef: v.string(),
36
+ before: v.optional(v.number()),
37
+ batch: v.optional(v.number()),
38
+ },
39
+ returns: v.number(),
40
+ handler: async (ctx, args) => {
41
+ const before = args.before;
42
+ const batch = args.batch ?? DEFAULT_PURGE_BATCH;
43
+ const rows = await ctx.db
44
+ .query("events")
45
+ .withIndex("by_subject", (q) => {
46
+ const scoped = q.eq("subjectRef", args.subjectRef);
47
+ return before === undefined ? scoped : scoped.lt("createdAt", before);
48
+ })
49
+ .take(batch);
50
+ for (const row of rows) {
51
+ await ctx.db.delete(row._id);
52
+ }
53
+ if (rows.length === batch) {
54
+ await ctx.scheduler.runAfter(0, api.mutations.purge, {
55
+ subjectRef: args.subjectRef,
56
+ before,
57
+ batch,
58
+ });
59
+ }
60
+ return rows.length;
61
+ },
62
+ });
63
+
64
+ /** Set (or clear) the singleton retention window the daily cron prunes against. */
65
+ export const configure = mutation({
66
+ args: { retentionMs: v.optional(v.number()) },
67
+ returns: v.null(),
68
+ handler: async (ctx, args) => {
69
+ const existing = await ctx.db.query("config").first();
70
+ if (existing === null) {
71
+ await ctx.db.insert("config", { retentionMs: args.retentionMs });
72
+ } else {
73
+ await ctx.db.patch(existing._id, { retentionMs: args.retentionMs });
74
+ }
75
+ return null;
76
+ },
77
+ });
78
+
79
+ /**
80
+ * Prune a batch of events older than the configured retention window across all
81
+ * subjects, rescheduling until short. The component's daily cron calls this; the
82
+ * host may also trigger a manual sweep. No config (or no `retentionMs`) ⇒ no-op.
83
+ * Idempotent and at-least-once safe: a redelivery prunes the next/zero batch.
84
+ */
85
+ export const pruneExpired = mutation({
86
+ args: { batch: v.optional(v.number()) },
87
+ returns: v.number(),
88
+ handler: async (ctx, args) => {
89
+ const cfg = await ctx.db.query("config").first();
90
+ const retentionMs = cfg?.retentionMs;
91
+ if (retentionMs === undefined) {
92
+ return 0;
93
+ }
94
+ const batch = args.batch ?? DEFAULT_PURGE_BATCH;
95
+ const cutoff = Date.now() - retentionMs;
96
+ const rows = await ctx.db
97
+ .query("events")
98
+ .withIndex("by_createdAt", (q) => q.lt("createdAt", cutoff))
99
+ .take(batch);
100
+ for (const row of rows) {
101
+ await ctx.db.delete(row._id);
102
+ }
103
+ if (rows.length === batch) {
104
+ await ctx.scheduler.runAfter(0, api.mutations.pruneExpired, { batch });
105
+ }
106
+ return rows.length;
107
+ },
108
+ });
@@ -0,0 +1,109 @@
1
+ import { v } from "convex/values";
2
+ import { paginationOptsValidator } from "convex/server";
3
+ import { query } from "./_generated/server";
4
+ import { eventDoc, eventPage, countResult } from "./validators";
5
+
6
+ /** Default scan bound for a capped `count` before it reports `isExact: false`. */
7
+ const DEFAULT_MAX_COUNT = 1000;
8
+
9
+ export const list = query({
10
+ args: {
11
+ subjectRef: v.string(),
12
+ type: v.optional(v.string()),
13
+ since: v.optional(v.number()),
14
+ limit: v.number(),
15
+ },
16
+ returns: v.array(eventDoc),
17
+ handler: async (ctx, args) => {
18
+ const since = args.since;
19
+ const type = args.type;
20
+ if (type === undefined) {
21
+ return await ctx.db
22
+ .query("events")
23
+ .withIndex("by_subject", (q) => {
24
+ const scoped = q.eq("subjectRef", args.subjectRef);
25
+ return since === undefined ? scoped : scoped.gte("createdAt", since);
26
+ })
27
+ .order("desc")
28
+ .take(args.limit);
29
+ }
30
+ return await ctx.db
31
+ .query("events")
32
+ .withIndex("by_subject_type", (q) => {
33
+ const scoped = q.eq("subjectRef", args.subjectRef).eq("type", type);
34
+ return since === undefined ? scoped : scoped.gte("createdAt", since);
35
+ })
36
+ .order("desc")
37
+ .take(args.limit);
38
+ },
39
+ });
40
+
41
+ /**
42
+ * Cursor-paginated feed, newest-first, honoring the same `type` / `since`
43
+ * filters as `list`. Returns Convex's `{ page, isDone, continueCursor }` so a
44
+ * host can page past any single-call `limit`.
45
+ */
46
+ export const listPaginated = query({
47
+ args: {
48
+ subjectRef: v.string(),
49
+ type: v.optional(v.string()),
50
+ since: v.optional(v.number()),
51
+ paginationOpts: paginationOptsValidator,
52
+ },
53
+ returns: eventPage,
54
+ handler: async (ctx, args) => {
55
+ const since = args.since;
56
+ const type = args.type;
57
+ if (type === undefined) {
58
+ return await ctx.db
59
+ .query("events")
60
+ .withIndex("by_subject", (q) => {
61
+ const scoped = q.eq("subjectRef", args.subjectRef);
62
+ return since === undefined ? scoped : scoped.gte("createdAt", since);
63
+ })
64
+ .order("desc")
65
+ .paginate(args.paginationOpts);
66
+ }
67
+ return await ctx.db
68
+ .query("events")
69
+ .withIndex("by_subject_type", (q) => {
70
+ const scoped = q.eq("subjectRef", args.subjectRef).eq("type", type);
71
+ return since === undefined ? scoped : scoped.gte("createdAt", since);
72
+ })
73
+ .order("desc")
74
+ .paginate(args.paginationOpts);
75
+ },
76
+ });
77
+
78
+ /**
79
+ * Bounded count for `subjectRef` (optionally one `type`). Scans at most
80
+ * `maxCount + 1` rows: if more exist, returns `{ count: maxCount, isExact: false }`
81
+ * rather than loading the whole feed.
82
+ */
83
+ export const count = query({
84
+ args: {
85
+ subjectRef: v.string(),
86
+ type: v.optional(v.string()),
87
+ maxCount: v.optional(v.number()),
88
+ },
89
+ returns: countResult,
90
+ handler: async (ctx, args) => {
91
+ const type = args.type;
92
+ const maxCount = args.maxCount ?? DEFAULT_MAX_COUNT;
93
+ const rows =
94
+ type === undefined
95
+ ? await ctx.db
96
+ .query("events")
97
+ .withIndex("by_subject", (q) => q.eq("subjectRef", args.subjectRef))
98
+ .take(maxCount + 1)
99
+ : await ctx.db
100
+ .query("events")
101
+ .withIndex("by_subject_type", (q) =>
102
+ q.eq("subjectRef", args.subjectRef).eq("type", type),
103
+ )
104
+ .take(maxCount + 1);
105
+ return rows.length > maxCount
106
+ ? { count: maxCount, isExact: false }
107
+ : { count: rows.length, isExact: true };
108
+ },
109
+ });
@@ -0,0 +1,28 @@
1
+ import { defineSchema, defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+ import { jsonValue } from "./validators";
4
+
5
+ /**
6
+ * Sandboxed tables — the activity ledger's own concern. `subjectRef` and
7
+ * `actorRef` are opaque host-owned references (never assume their shape).
8
+ * Events are append-only; ordering is by the host-stamped `createdAt`.
9
+ */
10
+ export default defineSchema({
11
+ events: defineTable({
12
+ subjectRef: v.string(),
13
+ type: v.string(),
14
+ actorRef: v.optional(v.string()),
15
+ metadata: v.optional(jsonValue),
16
+ createdAt: v.number(),
17
+ })
18
+ .index("by_subject", ["subjectRef", "createdAt"])
19
+ .index("by_subject_type", ["subjectRef", "type", "createdAt"])
20
+ .index("by_createdAt", ["createdAt"]),
21
+ /**
22
+ * Singleton retention config, written by the host via `configure`. The daily
23
+ * cron reads it to prune events older than `retentionMs`; absent ⇒ no-op.
24
+ */
25
+ config: defineTable({
26
+ retentionMs: v.optional(v.number()),
27
+ }),
28
+ });
@@ -0,0 +1,32 @@
1
+ import { v } from "convex/values";
2
+ import { paginationResultValidator } from "convex/server";
3
+
4
+ /**
5
+ * Opaque host-owned event payload. The component never inspects it.
6
+ * Prefer a host-supplied validator / typed generic on the client class;
7
+ * `jsonValue` is the documented last resort for genuinely arbitrary data.
8
+ */
9
+ export const jsonValue = v.any();
10
+
11
+ /** Shape of a stored event row, as returned by the read queries. */
12
+ export const eventDoc = v.object({
13
+ _id: v.id("events"),
14
+ _creationTime: v.number(),
15
+ subjectRef: v.string(),
16
+ type: v.string(),
17
+ actorRef: v.optional(v.string()),
18
+ metadata: v.optional(jsonValue),
19
+ createdAt: v.number(),
20
+ });
21
+
22
+ /** One page of events, as returned by the paginated read (Convex's pagination shape). */
23
+ export const eventPage = paginationResultValidator(eventDoc);
24
+
25
+ /**
26
+ * A capped count. `isExact` is `false` when the feed has more events than the
27
+ * scan bound, so `count` is the bound rather than the true total.
28
+ */
29
+ export const countResult = v.object({
30
+ count: v.number(),
31
+ isExact: v.boolean(),
32
+ });
@@ -0,0 +1,133 @@
1
+ // @vitest-environment jsdom
2
+ /**
3
+ * Unit tests for the optional React front-tooling. `convex/react` is mocked so
4
+ * the hooks are exercised in isolation — we assert each thin wrapper forwards
5
+ * exactly the right arguments to the underlying Convex hook and returns its
6
+ * result unchanged (loaded and loading branches). No backend runs here.
7
+ */
8
+ import { renderHook } from "@testing-library/react";
9
+ import { describe, expect, it, vi, beforeEach } from "vitest";
10
+ import { useQuery, usePaginatedQuery } from "convex/react";
11
+ import {
12
+ useActivityFeed,
13
+ useEventCount,
14
+ type ActivityFeedRef,
15
+ type EventCountRef,
16
+ } from "./index";
17
+
18
+ vi.mock("convex/react", () => ({
19
+ useQuery: vi.fn(),
20
+ usePaginatedQuery: vi.fn(),
21
+ }));
22
+
23
+ const mockedUseQuery = vi.mocked(useQuery);
24
+ const mockedUsePaginatedQuery = vi.mocked(usePaginatedQuery);
25
+
26
+ // Opaque function references — the hooks pass these straight through; their
27
+ // runtime shape is irrelevant because the underlying Convex hook is mocked.
28
+ const countRef = { _ref: "count" } as unknown as EventCountRef;
29
+ const paginateRef = { _ref: "paginate" } as unknown as ActivityFeedRef;
30
+
31
+ beforeEach(() => {
32
+ vi.clearAllMocks();
33
+ });
34
+
35
+ describe("useEventCount", () => {
36
+ it("forwards (ref, args) to useQuery and returns the loaded value", () => {
37
+ const args = { subjectRef: "user:1", type: "login" };
38
+ mockedUseQuery.mockReturnValue({ count: 3, isExact: true });
39
+
40
+ const { result } = renderHook(() => useEventCount(countRef, args));
41
+
42
+ expect(mockedUseQuery).toHaveBeenCalledTimes(1);
43
+ expect(mockedUseQuery).toHaveBeenCalledWith(countRef, args);
44
+ expect(result.current).toEqual({ count: 3, isExact: true });
45
+ });
46
+
47
+ it("returns undefined while loading", () => {
48
+ const args = { subjectRef: "user:2" };
49
+ mockedUseQuery.mockReturnValue(undefined);
50
+
51
+ const { result } = renderHook(() => useEventCount(countRef, args));
52
+
53
+ expect(mockedUseQuery).toHaveBeenCalledWith(countRef, args);
54
+ expect(result.current).toBeUndefined();
55
+ });
56
+ });
57
+
58
+ describe("useActivityFeed", () => {
59
+ it("forwards (ref, args, opts) to usePaginatedQuery and returns its result", () => {
60
+ const args = { subjectRef: "user:1", type: "login" } as never;
61
+ const opts = { initialNumItems: 10 };
62
+ const loadMore = vi.fn();
63
+ const paginated = {
64
+ results: [{ id: "e1" }],
65
+ status: "CanLoadMore" as const,
66
+ isLoading: false as const,
67
+ loadMore,
68
+ };
69
+ mockedUsePaginatedQuery.mockReturnValue(paginated);
70
+
71
+ const { result } = renderHook(() =>
72
+ useActivityFeed(paginateRef, args, opts),
73
+ );
74
+
75
+ expect(mockedUsePaginatedQuery).toHaveBeenCalledTimes(1);
76
+ expect(mockedUsePaginatedQuery).toHaveBeenCalledWith(paginateRef, args, opts);
77
+ expect(result.current).toBe(paginated);
78
+ expect(result.current.results).toEqual([{ id: "e1" }]);
79
+ expect(result.current.status).toBe("CanLoadMore");
80
+ expect(result.current.loadMore).toBe(loadMore);
81
+ });
82
+
83
+ it("forwards loadMore — calling it invokes the paginated hook's loadMore", () => {
84
+ const args = { subjectRef: "user:3" } as never;
85
+ const opts = { initialNumItems: 5 };
86
+ const loadMore = vi.fn();
87
+ mockedUsePaginatedQuery.mockReturnValue({
88
+ results: [],
89
+ status: "CanLoadMore" as const,
90
+ isLoading: false as const,
91
+ loadMore,
92
+ });
93
+
94
+ const { result } = renderHook(() =>
95
+ useActivityFeed(paginateRef, args, opts),
96
+ );
97
+
98
+ result.current.loadMore(20);
99
+ expect(loadMore).toHaveBeenCalledWith(20);
100
+ });
101
+
102
+ it("returns Exhausted status when the feed is fully loaded", () => {
103
+ const args = { subjectRef: "user:4" } as never;
104
+ const opts = { initialNumItems: 10 };
105
+ const loadMore = vi.fn();
106
+ const paginated = {
107
+ results: [{ id: "e1" }, { id: "e2" }],
108
+ status: "Exhausted" as const,
109
+ isLoading: false as const,
110
+ loadMore,
111
+ };
112
+ mockedUsePaginatedQuery.mockReturnValue(paginated);
113
+
114
+ const { result } = renderHook(() =>
115
+ useActivityFeed(paginateRef, args, opts),
116
+ );
117
+
118
+ expect(result.current.status).toBe("Exhausted");
119
+ expect(result.current.results).toHaveLength(2);
120
+ });
121
+ });
122
+
123
+ describe("useEventCount — with type", () => {
124
+ it("forwards type in args when present", () => {
125
+ const args = { subjectRef: "user:5", type: "purchase" };
126
+ mockedUseQuery.mockReturnValue({ count: 7, isExact: true });
127
+
128
+ const { result } = renderHook(() => useEventCount(countRef, args));
129
+
130
+ expect(mockedUseQuery).toHaveBeenCalledWith(countRef, args);
131
+ expect(result.current).toEqual({ count: 7, isExact: true });
132
+ });
133
+ });
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Optional React front-tooling for `@vllnt/convex-events`.
3
+ *
4
+ * Thin hooks over `convex/react` for the reactive activity-feed surface. They
5
+ * never import the host's `api`: the host passes its own **re-exported** public
6
+ * function reference (a `paginate` query, a `count` query) plus args. `react`
7
+ * and `convex` are optional peer deps — a backend-only consumer pulls none of
8
+ * this code (tree-shakeable, separate `./react` entry).
9
+ *
10
+ * @module
11
+ */
12
+
13
+ import {
14
+ useQuery,
15
+ usePaginatedQuery,
16
+ type PaginatedQueryArgs,
17
+ type PaginatedQueryItem,
18
+ type UsePaginatedQueryResult,
19
+ } from "convex/react";
20
+ import type { FunctionReference, PaginationOptions } from "convex/server";
21
+ import type { CountResult } from "../client/types.js";
22
+
23
+ export type { CountResult };
24
+
25
+ /**
26
+ * The host's re-exported **paginated** feed query. A public query taking
27
+ * `{ subjectRef, type?, paginationOpts }` and returning a Convex page —
28
+ * exactly the ref shape `usePaginatedQuery` consumes.
29
+ */
30
+ export type ActivityFeedRef = FunctionReference<
31
+ "query",
32
+ "public",
33
+ {
34
+ subjectRef: string;
35
+ type?: string;
36
+ paginationOpts: PaginationOptions;
37
+ },
38
+ { page: unknown[]; isDone: boolean; continueCursor: string }
39
+ >;
40
+
41
+ /** The host's re-exported `count` query: `{ subjectRef, type? }` → {@link CountResult}. */
42
+ export type EventCountRef = FunctionReference<
43
+ "query",
44
+ "public",
45
+ { subjectRef: string; type?: string },
46
+ CountResult
47
+ >;
48
+
49
+ /**
50
+ * Reactive, cursor-paginated activity feed for one `subjectRef`.
51
+ *
52
+ * Thin wrapper over `usePaginatedQuery` against the host's re-exported
53
+ * `paginate` query reference — the component never owns the host's `api`. Stays
54
+ * generic over the exact ref so the host's page item type flows through.
55
+ *
56
+ * @param paginateRef - the host's re-exported paginated feed query.
57
+ * @param args - `{ subjectRef, type? }` (the page's `paginationOpts` are managed by the hook).
58
+ * @param opts - `{ initialNumItems }` page size for the first load.
59
+ * @returns `{ results, status, loadMore }` from `usePaginatedQuery`.
60
+ */
61
+ export function useActivityFeed<Ref extends ActivityFeedRef>(
62
+ paginateRef: Ref,
63
+ args: PaginatedQueryArgs<Ref>,
64
+ opts: { initialNumItems: number },
65
+ ): UsePaginatedQueryResult<PaginatedQueryItem<Ref>> {
66
+ return usePaginatedQuery(paginateRef, args, opts);
67
+ }
68
+
69
+ /**
70
+ * Reactive bounded count for one `subjectRef` (optionally one `type`).
71
+ *
72
+ * Thin wrapper over `useQuery` against the host's re-exported `count` query.
73
+ *
74
+ * @param countRef - the host's re-exported `count` query.
75
+ * @param args - `{ subjectRef, type? }`.
76
+ * @returns the `{ count, isExact }` result, or `undefined` while loading.
77
+ */
78
+ export function useEventCount(
79
+ countRef: EventCountRef,
80
+ args: { subjectRef: string; type?: string },
81
+ ): CountResult | undefined {
82
+ return useQuery(countRef, args);
83
+ }