@vllnt/convex-reactions 0.1.0-canary.ef756ee

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 (64) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +128 -0
  3. package/dist/client/index.d.ts +105 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +101 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/types.d.ts +37 -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 +38 -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 +78 -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 +3 -0
  28. package/dist/component/convex.config.d.ts.map +1 -0
  29. package/dist/component/convex.config.js +7 -0
  30. package/dist/component/convex.config.js.map +1 -0
  31. package/dist/component/mutations.d.ts +35 -0
  32. package/dist/component/mutations.d.ts.map +1 -0
  33. package/dist/component/mutations.js +72 -0
  34. package/dist/component/mutations.js.map +1 -0
  35. package/dist/component/queries.d.ts +62 -0
  36. package/dist/component/queries.d.ts.map +1 -0
  37. package/dist/component/queries.js +107 -0
  38. package/dist/component/queries.js.map +1 -0
  39. package/dist/component/schema.d.ts +35 -0
  40. package/dist/component/schema.d.ts.map +1 -0
  41. package/dist/component/schema.js +30 -0
  42. package/dist/component/schema.js.map +1 -0
  43. package/dist/component/validators.d.ts +41 -0
  44. package/dist/component/validators.d.ts.map +1 -0
  45. package/dist/component/validators.js +31 -0
  46. package/dist/component/validators.js.map +1 -0
  47. package/dist/shared.d.ts +8 -0
  48. package/dist/shared.d.ts.map +1 -0
  49. package/dist/shared.js +8 -0
  50. package/dist/shared.js.map +1 -0
  51. package/package.json +98 -0
  52. package/src/client/index.ts +213 -0
  53. package/src/client/types.ts +40 -0
  54. package/src/component/_generated/api.ts +54 -0
  55. package/src/component/_generated/component.ts +94 -0
  56. package/src/component/_generated/dataModel.ts +60 -0
  57. package/src/component/_generated/server.ts +156 -0
  58. package/src/component/convex.config.ts +9 -0
  59. package/src/component/mutations.ts +79 -0
  60. package/src/component/queries.ts +124 -0
  61. package/src/component/schema.ts +30 -0
  62. package/src/component/validators.ts +33 -0
  63. package/src/shared.ts +8 -0
  64. package/src/test.ts +16 -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,9 @@
1
+ import { defineComponent } from "convex/server";
2
+
3
+ const component = defineComponent("reactions");
4
+
5
+ // Nest official child components here, e.g.:
6
+ // import aggregate from "@convex-dev/aggregate/convex.config";
7
+ // component.use(aggregate);
8
+
9
+ export default component;
@@ -0,0 +1,79 @@
1
+ import { v } from "convex/values";
2
+ import { mutation } from "./_generated/server";
3
+ import { reactResult } from "./validators";
4
+
5
+ /**
6
+ * Toggle a reaction edge in one transaction. If the subject has no
7
+ * `(authorRef, resourceRef, kind)` edge it is inserted (`action: "added"`,
8
+ * `reacted: true`); if it already exists the existing edge is deleted
9
+ * (`action: "removed"`, `reacted: false`). The read and the write share the
10
+ * mutation transaction, so two concurrent toggles cannot both insert — the
11
+ * uniqueness invariant (≤1 edge per subject per kind per resource) holds.
12
+ *
13
+ * `createdAt` is stamped from the server clock (`Date.now()` inside the handler
14
+ * — never caller-supplied). `kind` vocabulary and any allowlist are the host's
15
+ * concern, enforced at the client boundary before this call.
16
+ */
17
+ export const react = mutation({
18
+ args: {
19
+ authorRef: v.string(),
20
+ resourceRef: v.string(),
21
+ kind: v.string(),
22
+ },
23
+ returns: reactResult,
24
+ handler: async (ctx, args) => {
25
+ const existing = await ctx.db
26
+ .query("reactions")
27
+ .withIndex("by_author_resource_kind", (q) =>
28
+ q
29
+ .eq("authorRef", args.authorRef)
30
+ .eq("resourceRef", args.resourceRef)
31
+ .eq("kind", args.kind),
32
+ )
33
+ .unique();
34
+
35
+ if (existing !== null) {
36
+ await ctx.db.delete(existing._id);
37
+ return { reacted: false, action: "removed" as const };
38
+ }
39
+
40
+ await ctx.db.insert("reactions", {
41
+ authorRef: args.authorRef,
42
+ resourceRef: args.resourceRef,
43
+ kind: args.kind,
44
+ createdAt: Date.now(),
45
+ });
46
+ return { reacted: true, action: "added" as const };
47
+ },
48
+ });
49
+
50
+ /**
51
+ * Remove a subject's `(authorRef, resourceRef, kind)` reaction edge. Idempotent:
52
+ * removing an edge that does not exist is a no-op that returns `false`, so a
53
+ * duplicate or replayed `unreact` is safe. Returns `true` only when an edge was
54
+ * actually deleted.
55
+ */
56
+ export const unreact = mutation({
57
+ args: {
58
+ authorRef: v.string(),
59
+ resourceRef: v.string(),
60
+ kind: v.string(),
61
+ },
62
+ returns: v.boolean(),
63
+ handler: async (ctx, args) => {
64
+ const existing = await ctx.db
65
+ .query("reactions")
66
+ .withIndex("by_author_resource_kind", (q) =>
67
+ q
68
+ .eq("authorRef", args.authorRef)
69
+ .eq("resourceRef", args.resourceRef)
70
+ .eq("kind", args.kind),
71
+ )
72
+ .unique();
73
+ if (existing === null) {
74
+ return false;
75
+ }
76
+ await ctx.db.delete(existing._id);
77
+ return true;
78
+ },
79
+ });
@@ -0,0 +1,124 @@
1
+ import { v } from "convex/values";
2
+ import { paginationOptsValidator } from "convex/server";
3
+ import { query } from "./_generated/server";
4
+ import { kindCount, reactionView } from "./validators";
5
+ import type { Doc } from "./_generated/dataModel";
6
+
7
+ /** Project a stored reaction row to its public view (drops internal fields). */
8
+ function view(row: Doc<"reactions">) {
9
+ return {
10
+ authorRef: row.authorRef,
11
+ resourceRef: row.resourceRef,
12
+ kind: row.kind,
13
+ createdAt: row.createdAt,
14
+ };
15
+ }
16
+
17
+ /**
18
+ * Tally reaction edges per `kind` on one resource. Reads every edge for
19
+ * `resourceRef` via the `by_resource_kind` index (which is prefixed by
20
+ * `resourceRef`, so a `resourceRef`-only range spans all kinds) and groups them
21
+ * into `{ kind, count }` rows, sorted by `kind` for a stable order. A resource
22
+ * with no reactions returns an empty array.
23
+ */
24
+ export const counts = query({
25
+ args: { resourceRef: v.string() },
26
+ returns: v.array(kindCount),
27
+ handler: async (ctx, args) => {
28
+ const rows = await ctx.db
29
+ .query("reactions")
30
+ .withIndex("by_resource_kind", (q) => q.eq("resourceRef", args.resourceRef))
31
+ .collect();
32
+ const tally = new Map<string, number>();
33
+ for (const row of rows) {
34
+ tally.set(row.kind, (tally.get(row.kind) ?? 0) + 1);
35
+ }
36
+ // Sort by kind for a stable, deterministic order. `localeCompare` is a
37
+ // single expression (no comparator branch), so coverage stays exact.
38
+ return [...tally.entries()]
39
+ .map(([kind, count]) => ({ kind, count }))
40
+ .sort((a, b) => a.kind.localeCompare(b.kind));
41
+ },
42
+ });
43
+
44
+ /**
45
+ * Whether a subject holds a `(authorRef, resourceRef, kind)` reaction edge. A
46
+ * unique point read over `by_author_resource_kind` — the per-subject toggle
47
+ * state the host renders next to a reaction control.
48
+ */
49
+ export const hasReacted = query({
50
+ args: {
51
+ authorRef: v.string(),
52
+ resourceRef: v.string(),
53
+ kind: v.string(),
54
+ },
55
+ returns: v.boolean(),
56
+ handler: async (ctx, args) => {
57
+ const edge = await ctx.db
58
+ .query("reactions")
59
+ .withIndex("by_author_resource_kind", (q) =>
60
+ q
61
+ .eq("authorRef", args.authorRef)
62
+ .eq("resourceRef", args.resourceRef)
63
+ .eq("kind", args.kind),
64
+ )
65
+ .unique();
66
+ return edge !== null;
67
+ },
68
+ });
69
+
70
+ /**
71
+ * Every reaction kind a subject placed on one resource (their own reaction
72
+ * state across kinds), via the `by_author_resource` index. Returns the list of
73
+ * `kind` strings; empty when the subject has not reacted to the resource.
74
+ */
75
+ export const myReactions = query({
76
+ args: { authorRef: v.string(), resourceRef: v.string() },
77
+ returns: v.array(v.string()),
78
+ handler: async (ctx, args) => {
79
+ const rows = await ctx.db
80
+ .query("reactions")
81
+ .withIndex("by_author_resource", (q) =>
82
+ q.eq("authorRef", args.authorRef).eq("resourceRef", args.resourceRef),
83
+ )
84
+ .collect();
85
+ return rows.map((row) => row.kind);
86
+ },
87
+ });
88
+
89
+ /**
90
+ * Page the subjects who reacted to `resourceRef` with one `kind`, oldest first
91
+ * via the `by_resource_kind` index. Takes the standard Convex `paginationOpts`
92
+ * and returns the standard paginated envelope (`page`, `isDone`,
93
+ * `continueCursor`) so the host can list reactors reactively.
94
+ */
95
+ export const reactors = query({
96
+ args: {
97
+ resourceRef: v.string(),
98
+ kind: v.string(),
99
+ paginationOpts: paginationOptsValidator,
100
+ },
101
+ returns: v.object({
102
+ page: v.array(reactionView),
103
+ isDone: v.boolean(),
104
+ continueCursor: v.string(),
105
+ splitCursor: v.optional(v.union(v.string(), v.null())),
106
+ pageStatus: v.optional(
107
+ v.union(
108
+ v.literal("SplitRecommended"),
109
+ v.literal("SplitRequired"),
110
+ v.null(),
111
+ ),
112
+ ),
113
+ }),
114
+ handler: async (ctx, args) => {
115
+ const result = await ctx.db
116
+ .query("reactions")
117
+ .withIndex("by_resource_kind", (q) =>
118
+ q.eq("resourceRef", args.resourceRef).eq("kind", args.kind),
119
+ )
120
+ .order("asc")
121
+ .paginate(args.paginationOpts);
122
+ return { ...result, page: result.page.map(view) };
123
+ },
124
+ });
@@ -0,0 +1,30 @@
1
+ import { defineSchema, defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+
4
+ /**
5
+ * Sandboxed table — one reaction edge per row. An edge is the opaque triple
6
+ * `(authorRef, resourceRef, kind)`: a host subject reacted to a host resource
7
+ * with one reaction kind. `createdAt` is stamped from the server clock. The
8
+ * component never de-references the opaque refs and never reads host tables.
9
+ *
10
+ * Indexes:
11
+ * - `by_author_resource_kind` — the uniqueness / toggle / dedup key. A
12
+ * `(authorRef, resourceRef, kind)` lookup is `.unique()`, so one subject can
13
+ * hold at most one edge per kind on a resource (enforced in the mutation
14
+ * transaction).
15
+ * - `by_resource_kind` — count edges of one kind on a resource and page its
16
+ * reactors oldest-first.
17
+ * - `by_author_resource` — list every kind a subject placed on a resource
18
+ * (`myReactions`).
19
+ */
20
+ export default defineSchema({
21
+ reactions: defineTable({
22
+ authorRef: v.string(),
23
+ resourceRef: v.string(),
24
+ kind: v.string(),
25
+ createdAt: v.number(),
26
+ })
27
+ .index("by_author_resource_kind", ["authorRef", "resourceRef", "kind"])
28
+ .index("by_resource_kind", ["resourceRef", "kind", "createdAt"])
29
+ .index("by_author_resource", ["authorRef", "resourceRef"]),
30
+ });
@@ -0,0 +1,33 @@
1
+ import { v } from "convex/values";
2
+
3
+ /**
4
+ * Public projection of a stored reaction edge returned by {@link reactors}.
5
+ * `authorRef` and `resourceRef` are opaque host references the component never
6
+ * de-references; `kind` is the reaction tag (an emoji, `"up"`/`"down"`, `"like"`
7
+ * — the host decides the vocabulary and may constrain it with an allowlist).
8
+ */
9
+ export const reactionView = v.object({
10
+ authorRef: v.string(),
11
+ resourceRef: v.string(),
12
+ kind: v.string(),
13
+ createdAt: v.number(),
14
+ });
15
+
16
+ /**
17
+ * A single `{ kind, count }` tally returned by {@link counts}. The component
18
+ * counts reaction edges per `kind` on a resource; `kind` is host-defined and
19
+ * opaque.
20
+ */
21
+ export const kindCount = v.object({
22
+ kind: v.string(),
23
+ count: v.number(),
24
+ });
25
+
26
+ /**
27
+ * The result of a toggle {@link react} call: whether the edge now exists
28
+ * (`reacted`) after the toggle, and the action that produced that state.
29
+ */
30
+ export const reactResult = v.object({
31
+ reacted: v.boolean(),
32
+ action: v.union(v.literal("added"), v.literal("removed")),
33
+ });
package/src/shared.ts ADDED
@@ -0,0 +1,8 @@
1
+ /** Shared constants used by both `client/` and `component/`. */
2
+
3
+ /**
4
+ * The component id (`defineComponent("reactions")`) and the default mount name a
5
+ * host gets from `app.use(component)`. Used as the default `register()` mount in
6
+ * tests so the name is declared in exactly one place.
7
+ */
8
+ export const COMPONENT_NAME = "reactions";
package/src/test.ts ADDED
@@ -0,0 +1,16 @@
1
+ import type { TestConvex } from "convex-test";
2
+ import schema from "./component/schema";
3
+ import { COMPONENT_NAME } from "./shared";
4
+
5
+ const modules = import.meta.glob("./component/**/*.ts");
6
+
7
+ /**
8
+ * Register this component with a `convex-test` instance so consuming apps can
9
+ * test integration: `import { register } from "@vllnt/convex-reactions/test"`.
10
+ */
11
+ export function register(
12
+ t: TestConvex<typeof schema>,
13
+ name: string = COMPONENT_NAME,
14
+ ): void {
15
+ t.registerComponent(name, schema, modules);
16
+ }